Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.48.5.0 fix: community fix wave — 57 PR adoptions + 42 verified issue fixes + composite review rounds (#4954)

Sina Matian43597b19e50a
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5656592dfb..6c54739df9 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.48.4.0",
+ "version": "0.48.5.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 5af856fcdd..0ea19905f6 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.48.4.0",
+ "version": "0.48.5.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/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index ac5f286a2e..80220d0e78 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.48.4.0 -->
+<!-- gbrain-runbook-stamp: 0.48.5.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 ea08c89a80..69c5ddb8b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,445 @@
All notable changes to GBrain will be documented in this file.
+## [0.48.5.0] - 2026-09-07
+
+**The community fix wave: 57 contributor pull requests adopted or reworked
+with credit, 42 verified open issues fixed directly, and a hostile review
+pass over the whole set.** Your nightly extraction stops re-spending money on
+transcripts that never yield anything, code repositories registered as code
+sources are indexed the way you registered them instead of silently skipped,
+Chinese, Japanese and Korean pages get real overlap between search chunks,
+tool calls from the Claude CLI lane stop being dropped, and the doctor stops
+crying wolf about transcript-minted atoms. Every adopted fix carries a
+regression test proven red before the fix.
+
+### Behavior changes (read before you upgrade)
+
+- **Code sources sync as code everywhere.** A source registered with
+ `--strategy code` is now indexed as code from autopilot, the dream cycle,
+ the MCP sync tool and a plain `gbrain sync`, not only from `sync --all`.
+ Markdown pages that were imported into such a source under the old
+ 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,
+ 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
+ tombstones every transcript that yields zero atoms (editing the file makes
+ it eligible again), so the nightly work pool shrinks and stays shrunk.
+ (#4916, contributed by @mariokarras)
+- **`gbrain serve` refuses an unknown `GBRAIN_SOURCE`.** A stdio serve whose
+ environment names a source that is missing or archived now exits with the
+ value and the fix instead of silently serving an empty scope. Unset,
+ `__all__`, and malformed values behave as before. (#4851, contributed by
+ @NothoiMatt; fixes #4850)
+- **`gbrain think` and `gbrain graph-query` resolve their source like
+ search does.** A bare `think` gathers from your resolved default source
+ plus federated sources, honoring `GBRAIN_SOURCE`, `.gbrain-source` and
+ `sources.default`; a bare `graph-query` walks only the resolved source and
+ `--include-foreign` genuinely widens it. `--source __all__` spans the brain
+ on both. Single-source brains see identical output. (#4652, #4765)
+- **`recall` honors `since` together with an entity.** `gbrain recall
+ <entity> --since` (and `--watch` / `--since-last-run`) now returns only
+ facts from that window, ordered by event time, instead of the full entity
+ card every tick; an unparseable `since` is rejected instead of silently
+ widening the window. (#4882, contributed by @bhattman-dev)
+- **`delta` cursors carry microseconds.** `since` and `next_cursor.since`
+ now keep the stored timestamp's six fractional digits, so pages saved in
+ the same millisecond are never re-delivered. Callers that pattern-match a
+ three-digit fraction see the longer form. (#4681, contributed by
+ @jeanpierre121)
+- **`gbrain sync --json` keeps stdout pure.** Human progress lines go to
+ stderr, so `sync --json | jq` works as documented. Runs without `--json`
+ are unchanged. (#4888)
+- **Autopilot skips checkouts that are not on this machine.** Sources
+ registered elsewhere or with an unmounted path are reported as
+ `skipped_unavailable_path` once per tick instead of enqueuing jobs that
+ fail every tick; managed remote clones still dispatch. (#4865,
+ contributed by @javieraldape; fixes #4729)
+- **CJK chunk overlap applies to pages chunked from now on.** Existing
+ Chinese, Japanese and Korean pages keep their current chunks until the
+ chunker version is bumped (a whole-brain re-embed, tracked in TODOS.md);
+ English and Latin pages are byte-identical. (#4871, contributed by
+ @G0-0000)
+- **Entity slugs for names with Latin stroke letters changed grammar.**
+ Names containing d-stroke, l-stroke, o-slash, eth, thorn, sharp s, ae or
+ oe now fold to their ASCII form when an entity slug is minted (`duc-example`
+ where the old code produced `uc-example`). Entity pages minted under the old
+ spelling keep their slug; new facts about the same person resolve to the
+ folded slug, so a brain with such names can grow a second page until the
+ old one is renamed (tracked in TODOS.md). (#4855, contributed by @LongPV)
+- **`gbrain import --source <id>` now requires a registered source.** A typo
+ fails with the same one-line error `sync --source` gives instead of one
+ foreign-key failure per file; a bare `--source` with no value is refused.
+- **`gbrain bootstrap harness --source <id>` is validated**, and an implicit
+ source resolves through the same ladder `gbrain serve` uses (environment,
+ dotfile, working directory, brain default), so hooks stop binding to a
+ source the serve never resolved. Under a live PGLite serve the harness
+ cannot read that ladder: without a token it refuses with the two escape
+ hatches (pre-mint a token, or stop the serve), and the `--token` lane, when
+ no `--source` is given, wires the hooks unpinned with a warning, since an
+ unpinned hook resolves through the live serve's own binding (the receipt
+ records `source_pinned: false`).
+- **Smaller contract changes.** `gbrain import --json` gains additive
+ `failures`, `unchanged` and `malformed_skipped` keys (#4803, contributed by
+ @afshaker); `code_blast` and `code_flow` gain additive `status` and
+ `ready` fields (#4773, contributed by @armandovargash);
+ `extract-conversation-facts` exits 1 when a page changed mid-extraction
+ (#4869); subagent tool calls are validated like MCP calls, so a
+ wrong-typed argument is rejected with a named error (#4925, contributed by
+ @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
+ 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
+ thin page (#4948, contributed by @gagecane).
+
+### AI providers
+
+- Claude Fable 5.1 is accepted by the Anthropic and claude-cli recipes and
+ priced with its published 0.025x cache-read rate, so pinning a tier to it
+ no longer silently degrades. (#4794, contributed by @morven-ai)
+- The DeepSeek API key can be stored in gbrain config and is picked up in
+ launchd, cron and MCP contexts with no shell environment. (#4843,
+ contributed by @javieraldape; fixes #4808)
+- Thinking-by-default models such as DeepSeek v4 get the same output
+ headroom as Claude 5 in subagent jobs, skillopt rollouts and any chat call
+ without its own cap, so they stop returning empty answers after spending
+ the budget on reasoning. (#4847, contributed by @awilhite)
+- Query expansion works when your utility or expansion model runs through
+ the Claude CLI subscription lane. (#4861, contributed by @LongPV)
+- Gemini embedding models reached through OpenRouter or another
+ OpenAI-compatible router honor your configured embedding dimensions.
+ (#4868, contributed by @morven-ai)
+- Claude CLI tool calls are no longer dropped when the model mentions the
+ tool tag in prose before the real block (#4898, contributed by
+ @mariokarras), and calls that put their arguments beside the name instead
+ of inside a wrapper now reach the tool with those arguments (#4924,
+ contributed by @Walliiee; fixes #4922).
+- Voyage's preview `rerank-3` and `rerank-3-lite` rerankers can be selected;
+ the default stays `rerank-2.5`. (#4940, contributed by @malachany; fixes
+ #4938)
+- Short model aliases such as `claude-cli:haiku` price like the model they
+ resolve to under a cost cap, so `gbrain enrich` no longer stops at the
+ first call. (#4942, contributed by @johnerik)
+- Documents sent to the reranker are capped by size and token count, so a
+ self-hosted reranker with a small batch no longer fails and silently
+ serves unranked order. (#4947, contributed by @gagecane)
+- MiniMax M2 and M3 are recognized as tool-capable, so capability checks
+ and the doctor give the accurate reason when the subagent loop is refused.
+ (#4782)
+
+### Dream / cycle
+
+- Nightly dream stops rebuilding link manifests and re-repairing,
+ re-stamping and re-embedding pages for transcripts whose synthesis
+ already completed. (#4805, contributed by @jeanpierre121)
+- On durability-hardened brains, cycle lint and `gbrain lint --fix` commit
+ each repaired page so the post-commit hook pushes it. (#4815, contributed
+ by @mike-tech-ship-it)
+- Oneshot synthesis children get a prompt that matches their tool-less
+ JSON-only contract, and a reply that hit the output cap is reported as a
+ length fallback instead of unparseable, so fewer transcripts double-bill
+ through the agentic fallback. (#4886, contributed by @mvanhorn; fixes
+ #4785)
+- Concept synthesis gives reasoning-by-default models enough output headroom
+ to actually answer, so concept pages stop coming back as stubs. (#4889,
+ contributed by @awilhite)
+- `gbrain dream --json` stdout stays parseable through the extract phase,
+ and `totals.pages_extracted` counts pages, not links. (#4890, contributed
+ by @tomatkins)
+- Dream reports `exclude_patterns` hits in one stderr line instead of
+ silently saying there was nothing to process. (#4926, contributed by
+ @Walliiee; fixes #4923)
+- Installs whose only chat provider is not Anthropic or OpenAI now run
+ `extract_atoms` and the other default-model phases on the provider they
+ configured instead of stopping with a provider failure. (#3813)
+- Concept pages written by `synthesize_concepts` carry graph edges to and
+ from every atom they were synthesized from, so they appear in backlinks,
+ relational recall and graph coverage instead of landing as orphans;
+ re-running the phase backfills existing brains. (#4589)
+- `gbrain dream` with `GBRAIN_SOURCE` set scopes the cycle to that source
+ exactly like `--source`. (#4778)
+
+### Atoms / extraction / facts
+
+- The mention scan honours the `link_resolution.cross_source` opt-in the
+ same way wikilink resolution does, and a same-name entity in the page's
+ own source always wins over a cross-source twin. (#4793, contributed by
+ @paul-0320)
+- Fact reconciliation runs under the same per-page lock the fence writers
+ use and refuses to delete rows when the Markdown on disk is newer than the
+ page cache, so a fact you just remembered is no longer wiped by a sweep
+ that runs before sync. (#4835, contributed by @bhattman-dev)
+- Atoms distilled from an imported transcript link back to the conversation
+ page the session was rendered into. (#4853, contributed by @Natetgmaxwell)
+- Names containing Latin stroke letters (d-stroke, eth, o-slash, l-stroke,
+ dotless i, sharp s, ae, oe, thorn) get the ASCII entity slug and wikilink
+ key you would expect. (#4855, contributed by @LongPV)
+- Atom extraction no longer produces zero atoms when a free local chat model
+ is paired with an unpriced embedding route; the cost cap checks both models
+ and honors `pricing.overrides`. (#4878, contributed by @NothoiMatt; fixes
+ #4877)
+- Durable facts-absorb jobs honor the 10-minute handler default instead of a
+ hard-coded 3-minute timeout. (#4887, contributed by @javieraldape; fixes
+ #4864)
+- Models that emit a `<thinking>` block before their JSON answer are
+ recovered the same way as `<think>` (#4912), and the atoms array is found
+ even when the reply opens with bracketed prose (#4913; both contributed by
+ @mariokarras).
+- `extract_atoms` stops re-spending budget on transcripts that keep returning
+ malformed or empty output; they get the same bounded retry and tombstone
+ as pages. (#4916, contributed by @mariokarras)
+- Meeting pages your agent wrote directly are found by `gbrain extract
+ timeline --from-meetings` and dated from their frontmatter. (#4943,
+ contributed by @johnerik)
+- Atom extraction no longer burns retries on metadata-only pages; the model
+ is told to return an empty list when there is nothing to extract. (#4948,
+ contributed by @gagecane)
+- Failed facts extraction jobs record a bounded error-type label (auth,
+ rate limit, and so on) in the job error text. (#4950, contributed by
+ @Masashi-Ono0611)
+- The maintenance sweep honors the cross-source link opt-in and your
+ configured default source, so cross-source links extract created are kept
+ instead of dropped (#3757, #4611), and relative `./page.md` links count as
+ live references so their edges are no longer pruned (#4873).
+- Forgetting a fact sticks: the next reconcile no longer brings it back
+ (#4696). Facts whose entity came back as the literal text `null` are
+ filed as unparented (#4755). A page's first Facts fence lands above a bare
+ `---` + `## Timeline` separator, so template-shaped pages stop freezing
+ with `FACTS_FENCE_BELOW_SENTINEL` (#4756). Facts extracted on a thin-client
+ brain record the page they came from (#4819). Queued fact extraction
+ honors a medium-and-up notability filter (#4870). `gbrain remember` keeps
+ the database page body in sync with the fence it wrote to disk, so a
+ get-and-put round trip no longer drops the fact (#4872).
+ `migrate-embeddings --status` stops counting checkpoint rows as pending
+ fact embeddings (#4875).
+
+### Doctor / brain health
+
+- `atom_provenance_drift` no longer reports transcript-minted atoms as
+ drifted or as missing their source page; they are counted in their own
+ slug-unbound bucket outside the warning ratio, and the check finishes in
+ seconds on large brains instead of stalling health monitors. (#4799,
+ contributed by @Masashi-Ono0611; #4806, #4937)
+- A failed binary self-update no longer leaves a permanent doctor warning.
+ (#4814, contributed by @mike-tech-ship-it)
+- Skill triggers written in non-Latin scripts match intents in
+ `check-resolvable` and the doctor skill checks instead of being stripped
+ to nothing. (#4820, contributed by @hyunje-ethan-jang)
+- The resolver health check reports a skills folder that belongs to another
+ tool as a warning instead of a failure (#4822, contributed by
+ @Masashi-Ono0611), and raises one orphan warning per unregistered skill
+ pointing at `manifest.json` instead of one per trigger blaming
+ `RESOLVER.md` (#4831).
+- Pages whose recorded source path is only a basename while the slug lives
+ in a directory are no longer flagged as DB-only, and write-through
+ resolves them to the real file. (#4933, contributed by @javieraldape;
+ fixes #4744)
+- `eval_drift` inspects gbrain's own source checkout instead of whatever
+ repository you ran the doctor from, and says so on an installed CLI.
+ (#4606)
+
+### Google / open loops
+
+- Google connect via paste or `--code` accepts a real loopback redirect URL
+ again, which Google now stamps with `iss=accounts.google.com`. (#4891,
+ contributed by @johnerik; fixes #4917)
+- Gmail backfill waits out rate limits with a patient retry budget, never
+ marks a rate-limited thread as poisoned, and defers the rest of a
+ throttled batch to the next run. (#4894, contributed by @johnerik)
+
+### Search / eval
+
+- Search-mode settings load from your brain in one query instead of one per
+ setting, so every search on a hosted Postgres brain starts sooner. (#4781,
+ contributed by @hpamike)
+- Chinese, Japanese and Korean pages get a real, bounded overlap between
+ search chunks, and emoji are no longer split in half at chunk boundaries.
+ (#4871, contributed by @G0-0000)
+
+### MCP / schema / auth
+
+- Listing pages sorted by slug pages deterministically across federated
+ sources that share a slug, and `list_pages` rejects a malformed
+ `source_id` loudly instead of silently widening to every source. (#4857,
+ contributed by @proxynico)
+- Remote MCP OAuth discovery advertises `/mcp` as the protected resource and
+ serves RFC 9728 path-based metadata, with the root path kept as an alias.
+ (#4866, contributed by @amirelion)
+- Ontology reads hide values whose provenance page is private from untrusted
+ callers and resolve the newest value they are allowed to see. (#4881,
+ contributed by @bhattman-dev)
+- A stdio serve started with `--stdio-idle-timeout` no longer risks a hung
+ handshake when the client's first frame arrives before boot finishes.
+ (#4935, contributed by @Masashi-Ono0611)
+- The thin-client doctor report confines its page count and brain score to
+ the caller's granted sources (#4592); reading with an explicit `source_id`
+ that names a removed source fails with a clear `unknown_source` error
+ (#4620); the `sources_list` and `sources_status` tool descriptions state
+ that results are scope-filtered (#4811); and the OpenClaw bundle plugin
+ starts its MCP server through the shipped launcher, so a global install
+ works without building a binary (#4841).
+
+### Sync / import
+
+- `gbrain import --json` lists each rejected file with its error, so a
+ scripted import can tell a failed file from an unchanged one. (#4803,
+ contributed by @afshaker)
+- Empty code files such as a package `__init__.py` are reindexed by
+ `gbrain reindex-code` instead of being reported as failures. (#4904,
+ contributed by @Jey2311; fixes #4902)
+- Incremental sync removes the stale duplicate a renamed frontmatter-slug
+ file leaves behind (#4597); `gbrain features` stops telling a multi-source
+ brain to configure sync (#4767); Markdown files saved with a UTF-8 byte
+ order mark get their title from the first heading (#4798); and
+ `gbrain import` accepts `--source <id>` like every other command (#4862).
+
+### Transcripts / code intel
+
+- `code_blast` and `code_flow` report whether the code graph is ready, so an
+ empty blast radius on an unbuilt graph is no longer mistaken for zero
+ callers. (#4773, contributed by @armandovargash)
+- The Codex session-end hook recovers rollouts Codex has moved into its
+ archived store. (#4929, contributed by @mariokarras)
+- Repos with YAML files stop logging a false "semantic parsing unavailable"
+ warning on every sync (#4669); `transcripts ingest` honors `--limit` under
+ `--dry-run` (#4762); Claude Code subagent logs are no longer treated as
+ sessions, ending a permanent not-yet-imported backlog and a false drift
+ warning (#4796); and transcript pages no longer inherit a facts fence from
+ a page the session quoted (#4821).
+
+### CLI
+
+- `gbrain get <slug> --json` returns the page as JSON, and an ambiguous slug
+ returns a machine-readable error envelope. (#4813, contributed by
+ @mike-tech-ship-it)
+
+### Minions / autopilot
+
+- Live minion workers no longer vanish from `gbrain jobs` and the doctor on
+ hosts whose timezone differs from the runtime's. (#4856, contributed by
+ @proxynico; fixes #4885)
+- Contextual re-embed jobs on Postgres release their rate lease as soon as
+ each call finishes, so backfills run at the configured concurrency.
+ (#4880, contributed by @spiky02plateau)
+- Subagent tool calls that omit a required parameter get back a message
+ naming it, so the model can retry instead of hitting an opaque crash.
+ (#4925, contributed by @Walliiee)
+- The autopilot lock check recognizes a live process on Windows (#4563), and
+ the autopilot wrapper falls back to the gbrain on PATH when the binary it
+ was installed against has moved, instead of failing silently on every boot
+ (#4728).
+
+### Bootstrap / hooks
+
+- On Windows, `gbrain serve` binds its resolve-IPC socket again after an
+ unclean exit or reboot (#4333); a short-lived serve for the same brain no
+ longer takes down the long-lived serve's socket (#4896); and `gbrain
+ bootstrap harness` without `--source` binds its hooks to the source the
+ serve actually resolves (#4897).
+
+### Other
+
+- Pages whose chunks straddle a stale-embedding batch boundary get their
+ embedding signature stamped by whichever batch finishes them, so they are
+ no longer skipped by later model-swap checks. (#4825, contributed by
+ @morven-ai)
+
+### For contributors
+
+- Cancelling a running test suite stops every shard instead of leaving them
+ holding memory until the shard timeout. (#4774, contributed by
+ @armandovargash)
+- `bun run ci:local` on a stock macOS shell no longer aborts with an
+ unbound-variable error in a plain clone. (#4930, contributed by
+ @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).
+
+### Review hardening
+
+A hostile review over the composed set (eight lenses, two independent
+refuters per finding) confirmed thirteen defects that were only visible in
+composition, all fixed before ship: `gbrain sync --source <id> --json` kept
+stdout pure on the full-sync path too, not only for incremental runs;
+`gbrain graph-query --source <id>` on a thin-client install now errors
+instead of silently walking the wrong scope; a pasted Google consent-page
+URL with no scheme is rejected by host again instead of being taken as an
+authorization code; `gbrain remember` and `forget` keep the page's content
+hash so the next sync re-chunks the new or struck fact text instead of
+skipping the page; an implicit `default` source in `gbrain bootstrap
+harness` is treated as the federated floor, matching dream and doctor; and
+three reference doc entries brought back to current state. The slug-extension
+change proposed in #4807 was tried, found to need a data migration with
+collision rules the maintainer should decide, and returned to the queue.
+
+A second pass with independent reviewers (including an outside model) then
+closed the interactions between fixes: an honest empty atoms array is accepted
+at any offset of the model's reply while a non-atom-shaped array is a failure
+rather than a permanent tombstone; an explicitly configured extraction budget
+stays enforced even when the embedding route is unpriced; `extract timeline
+--from-meetings` never dates a meeting from its import timestamp, skips
+private meetings, and honors the cross-source gate on attendee edges as well as
+mentions; a remote `run_doctor` on a source-scoped token no longer reveals
+other sources' ids or backlog; concept synthesis on a thinking model uses the
+same output headroom as every other call; `forget` strikes the page body under
+the page lock and stamps a hash that makes the next sync re-chunk; every
+Facts-fence writer places the first fence above the timeline sentinel;
+`gbrain import --source` validates the source like `sync` does and refuses a
+missing value; `sync trigger --json` prints JSON; `GBRAIN_SOURCE=__all__` makes
+`dream` span the brain; `graph-query` refuses `--source` with
+`--include-foreign` instead of silently dropping the scope; and the bootstrap
+harness binds hooks to the source the serve actually resolves.
+
+With thanks to every contributor whose pull request this wave adopts:
+@afshaker, @amirelion, @arisgysel-design, @armandovargash, @awilhite,
+@bhattman-dev, @G0-0000, @gagecane, @hpamike, @hyunje-ethan-jang,
+@javieraldape, @jeanpierre121, @Jey2311, @johnerik, @LongPV, @malachany,
+@mariokarras, @Masashi-Ono0611, @mike-tech-ship-it, @morven-ai, @mvanhorn,
+@Natetgmaxwell, @noelboss, @NothoiMatt, @paul-0320, @proxynico,
+@spiky02plateau, @tomatkins, @Walliiee, and to the reporters whose verified
+issues drove the direct fixes.
+
+## To take advantage of 0.48.5.0
+
+`gbrain upgrade` runs migration v146 for you. If it did not, or if
+`gbrain doctor` warns about a partial migration:
+
+1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
+2. **Verify the upgrade:**
+ ```bash
+ gbrain --version
+ gbrain doctor
+ ```
+3. **Code sources:** the stored strategy now applies to every sync entry
+ point. If a source registered as `code` also holds Markdown you want kept,
+ an explicit flag always wins for that run:
+ ```bash
+ gbrain sync --source <id> --strategy auto
+ ```
+ Autopilot and cycle syncs use the stored strategy, so modified Markdown
+ pages under a `code` source are soft-deleted on their next sync and stay
+ recoverable for 72 hours (`gbrain sources archived`, `gbrain sources
+ restore`).
+4. **CJK brains:** new pages chunk with overlap automatically. To re-chunk
+ existing Chinese, Japanese or Korean pages, wait for the chunker version
+ bump in a later release or re-import the pages you care about.
+
+**Say to your agent:** *"check my brain's health"* (your agent runs
+`gbrain doctor`) — *"sync my code repo into the brain"* (your agent runs
+`gbrain sync --source <id>`; code sources now index as code from every
+entry point) — *"show me only what changed for this person since Monday"*
+(your agent runs `gbrain recall <entity> --since <date>`).
+
## [0.48.4.0] - 2026-09-06
**The ranker wave: search stops burying graph answers and concept pages, `gbrain eval longmemeval` becomes the like-for-like receipt producer, and every ranking default that moved carries a pre-registered receipt.**
diff --git a/README.md b/README.md
index c533ea7848..1edbd17968 100644
--- a/README.md
+++ b/README.md
@@ -418,7 +418,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).
- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential vault + gateway**: `gbrain creds` manages OAuth and API credentials in a local vault ([`recipes/credential-gateway.md`](recipes/credential-gateway.md)); agent-side vault-aware secret distribution: [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
- **Memorable (procedural memory)**: optional, off by default. Your brain remembers *what* happened; Memorable makes your agent remember *how* — finished sessions become replayable procedures stored on your machine (in a standalone local store, or inside your brain database if you opt in), recalled when a similar task comes back. See the section below, and [`docs/memorable-agents.md`](docs/memorable-agents.md) for the agent-facing detail.
diff --git a/TODOS.md b/TODOS.md
index 0956fbdea2..6eca06622d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,23 @@
# TODOS
+## 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.**
+ **What:** #4871 (wave adoption) made `extractTrailingContext` count chars for CJK-dominant chunks (the unit `countCJKAwareWords` uses) instead of whitespace tokens, so CJK pages get a real, bounded overlap instead of none / a near-total duplicate; the L4 char-slice fallback also stopped halving astral pairs. Both change chunk boundaries for CJK-dominant text only and apply to pages chunked from now on — pages already in the index keep their old boundaries until the chunker version moves. **How:** `export const MARKDOWN_CHUNKER_VERSION = 5;` in `src/core/chunkers/recursive.ts`, DECOUPLED from `SAFE_FENCE_CHUNKER_VERSION` (stays 4 as the safe-chunks provenance floor; `safeChunksFilter` is `>= 4`, so 5 passes); update the `MARKDOWN_CHUNKER_VERSION is 4` pin in `test/chunkers/recursive.test.ts`. **Cost (why this is a maintainer decision, not a fix-wave change):** the post-upgrade sweep re-chunks AND re-embeds every markdown page in every brain (markdown import has no embedding reuse) — the same full-brain re-embed shape as the v4 bump in 0.48.3.0, for a boundary change that only affects CJK-dominant pages. Coalescing it with the next planned chunker bump spares a standalone sweep. English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). **Effort:** S.
+## Community fix wave follow-ups (filed 2026-09-07, sync-import train)
+- [ ] **P3 — `gbrain import` human summary labels returned per-file failures as "unchanged".**
+ **What:** the non-`--json` summary line in `src/commands/import.ts` prints `${skipped - errors} unchanged`, but `skipped` also counts the failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) while `errors` counts only the thrown ones, so a returned failure reads as an unchanged no-op. The `--json` payload was fixed in #4803 (`unchanged` / `malformed_skipped` / `failures`); the human line was deliberately left alone in that wave. **How:** reuse the same `skipped - failures.length - malformedFileSkips` arithmetic and print the returned-failure count as its own term. **Effort:** S. **Priority:** P3.
+## Community fix wave follow-ups (filed 2026-09-07, minions-autopilot train)
+- [ ] **P3 — pglite-lock `readProcessArgs` has the same win32 gap as #4563, failing the other way.** **What:** `src/core/pglite-lock.ts` `readProcessArgs` probes `ps` then `/proc` with no Windows branch; on win32 it returns null, which that caller treats as "unknowable => alive", so a recycled-pid PGLite lock is never reaped and `acquire` waits out its timeout instead of stealing. Distinct symptom from the autopilot classifier (which now has the CIM branch in `src/core/autopilot-lock.ts` `readProcessCommand`). **How:** route `readProcessArgs` through the shared `readProcessCommand(pid)` (already handles /proc, ps, and win32 CIM) and delete the duplicate probe. **Effort:** S. **Priority:** P3.
+
+## Community fix wave follow-ups (filed 2026-09-07, atoms/extraction/facts train)
+
+- [ ] **P3 — stamp `effective_date` at the `put_page` write seam.**
+ **What:** `put_page` -> `writePageThrough` -> `engine.putPage` stores `effective_date ?? null` and never runs `computeEffectiveDate`, so every agent/MCP-written page carries a NULL column until `gbrain backfill effective_date` runs. `extract timeline --from-meetings` now derives the date itself (#4943); the sibling gate at `src/core/onboard/checks.ts` (`effective_date IS NOT NULL` on meetings, the `onboard.extract_timeline_from_meetings` remediation) still under-counts those pages, and recency/salience ranking COALESCEs to `updated_at` for them. **How:** compute in `writePageThrough` (or `putPage`) when the caller supplies none, using the backfill-registry recipe; it changes recency ranking for internally-written pages, so it goes behind the eval gate, and both consumers above drop their local workarounds once it lands. **Effort:** S. **Priority:** P3.
+
+- [ ] **P3 — extract_atoms parser: bracketed prose AFTER the array, and the sibling first-`[` anchors.**
+ **What:** `parseAtomsOutcomeInner` (`src/core/cycle/extract-atoms.ts`) now scans successive `[` offsets so bracketed preamble (`[Source: …]`, `[[wikilink]]`, `[user]`) no longer hijacks the anchor (#4913). The symmetric case still fails: bracketed prose AFTER the array (e.g. `[atoms]\nSee [Source: X].`) because the trim-back runs to the LAST `]`. The sibling first-`[` anchors in `propose-takes.ts`, `extract-events.ts`, and `calibration-profile.ts` are independent copies and remain unfixed. **How:** a shared "find the first parseable array that yields >= 1 shaped element" helper (scan forward on `[`, trim back over candidate `]`s) that all four callers route through. **Effort:** S. **Priority:** P3.
+
## Ranker wave follow-ups (filed 2026-09-06, v0.48.4.0 wave; plan: ~/.claude/plans/do-a-gbrain-evals-fix-snug-starlight.md)
- [ ] **P2 — session-aware autocut (the next pre-registered mechanism for `search.autocut`).**
@@ -156,18 +174,77 @@
## Community fix wave follow-ups (filed 2026-09-01, v0.48.1.0 wave)
-- [ ] **P1 — Fix-wave 2: the 27 deferred M-effort verified issues.**
- **What:** the v0.48.1.0 community fix wave triaged every open issue; 22
- were fixed in-wave and 27 verified M-effort issues were deferred to a
- second wave. Full triage records (verdict, rationale, fix sketch, key
- files per issue) live in `.context/fix-wave-triage.json` (gitignored —
- wave working state, not repo content). Deferred issue numbers: #4744
- #4741 #4738 #4732 #4729 #4728 #4696 #4684 #4679 #4653 #4652 #4649 #4620
- #4616 #4609 #4606 #4605 #4603 #4601 #4597 #4589 #4588 #4586 #4578 #4563
- #4558 #4359. (#4636 and #4564 were also triaged M but got fixed in-wave —
- #4636 by the #4279 adoption, #4564 by the #4583 default-write guard.)
- **How:** same discipline as wave 1 — red-proven regression test per fix,
- themed trains, per-train targeted sweeps.
+- [ ] **P3 — Share the #4728 baked-CLI-path guard with the brain-repo durability cron wrapper.**
+ **What:** `src/core/brain-repo-durability.ts` `renderCronWrapper` bakes a
+ CLI path at install time the same way the autopilot wrapper did before
+ #4728 (private resolver at `resolveGbrainCliPath` in that file; it degrades
+ to bare `gbrain`, so PATH resolution partially happens today, but a vanished
+ absolute path still fails as a bare bash exec error with no remediation).
+ A follow-up can lift the `[ ! -x <baked> ] -> type -P gbrain -> re-run
+ --install` bash snippet out of `writeWrapperScript` into one shared helper
+ and render it from both wrappers. **Why:** same ephemeral-container wipe
+ class; one guard, two callers. **Context:** #4728 deliberately did not widen
+ into `core/`. **Effort:** S. **Priority:** P3.
+- [ ] **P1 — Fix-wave 3: the 27 verified issues deferred by the 0.48.5.0 wave.**
+ **What:** the 0.48.5.0 community fix wave re-verified every open issue
+ against master (first-pass verifier + adversarial refuter per issue) and
+ fixed 42 directly; 26 verified M-effort bugs and one S-effort bug on the
+ 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).
+ 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
+ needs-info, #4679 and #4609 feature requests, #4601 docs-only), and the
+ rest carry forward above.
+ **How:** same discipline — red-proven regression test per fix, themed
+ trains in isolated worktrees, composed-collector `verify` + full suite,
+ composite hostile review before ship.
+- [ ] **P2 — Wave-review follow-ups (0.48.5.0): eleven INVESTIGATE items the
+ composite and ship reviews confirmed but deliberately left for a design call.**
+ (1) `src/core/context/resolve-ipc.ts` — a serve that defers to a live
+ provider never re-probes; when the provider exits cleanly nothing takes over
+ the socket until a restart (re-probe on EOF or retry the bind on an interval).
+ (2) `src/core/ai/recipes/minimax.ts` — M2/M3 are tool-capable now; confirm with
+ a live probe whether they reason by default and, if so, declare
+ `thinking_by_default` so #4847's headroom applies. (3) `gbrain graph-query`
+ default scope walks only the resolved source while `search`/`think` walk the
+ resolved source plus its federated set; decide one contract. (4)
+ `src/core/cycle/synthesize.ts` — the synth-v2 completion skip treats a
+ transcript as done when its children are `completed`, which happens before
+ the parent verifies quotes and writes markdown; an interrupted parent leaves
+ the transcript permanently skipped. (5) `src/core/entities/resolve.ts` — the
+ #4855 fold changes the minted slug for names with stroke letters; brains that
+ already hold `uc-example`-style pages need an alias/remap pass before facts
+ stop forking. (6) `src/core/creds/redirect.ts` — a scheme-less loopback paste
+ (`127.0.0.1:41999/?code=…`) is rejected because `URLSearchParams` never sees
+ `code=`. (7) `src/core/legacy-token-scope.ts` — legacy scalar-string grants
+ carry no `allowedSources`, so `assertExplicitSourceLive` cannot enforce them
+ (mirror the OAuth synthesis). (8) `src/commands/sync.ts` — the
+ `carriedByOtherRename` guard compares raw manifest paths while the
+ #4597 index is mode-normalized; under source-root mode the spare never fires.
+ (9) `sync --source-id` is accepted by the flag registry and ignored. (10) the
+ `(updated_at, slug)` keyset cursor cannot distinguish same-slug rows across
+ 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.
+- [ ] **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
+ `transcripts/discover.ts` in extract-atoms.ts instead of the runtime
+ `import()` + nullable pointer; fold `src/mcp/source-preflight.ts` into
+ `assertSourceExists`; trim the doc-heavy `extract-atoms-cost-gate.ts`; one
+ chunk-set tally for `findSynthV2Completion`/`findLegacyCompletion`; share the
+ sentence-alignment tail between the Latin and CJK trailing-context branches;
+ `new URL().hostname` for the consent-host check; drop the identity `pathKey`
+ default and the `compileExcludePatterns` wrapper; `basenameSlugForms` shared
+ by the FS and DB resolvers; `PAGE_LOCK_TIMEOUT_MS` shared by the four writers;
+ `parseEmbeddingSignature` beside `currentEmbeddingSignature`; the
+ `drift-watch.ts` walk-up should reuse `repo-root.ts`.
- [ ] **P2 — Enforce pack vocabulary at the put_page choke point, not
per-surface.** **What:** #4655's write-time vocabulary enforcement
(`src/core/schema-pack/write-vocabulary.ts`) is wired at three surfaces
@@ -499,7 +576,13 @@ deferred M-effort issues above are NOT repeated here.
`stripReasoningBlocks`, but ~13 hand-rolled brace-scan sites remain
(judges, grade-takes, drift, voice-gate, calibration-profile, chronicle,
facts/classify, loops-extract, skillopt x3, eval json-repair, think/index);
- propose-takes.ts carries its own duplicate regex to converge.
+ propose-takes.ts carries its own duplicate regex to converge. Caveat for
+ the propose-takes.ts pair: they are PRE-FILTERS (strip before any parse, no
+ `i` flag, no unclosed-tag arm), so routing them through
+ `stripReasoningBlocks` (which since #4912 also strips `<thinking>`) is a
+ semantic change — it would eat an unclosed `<think` tail before the raw parse
+ and add case-insensitivity. Needs its own ladder-shaped rework with a
+ red-first test, not a mechanical swap.
- [ ] **P2 — verify gpt-5.6-terra / gpt-5.6-sol canonical prices.** **What:**
while live-verifying luna (#4560), OpenAI's official pricing page listed
terra at $2.00/$12.00 and sol at $4.00/$20.00 vs CANONICAL_PRICING's
@@ -753,7 +836,11 @@ deferred M-effort issues above are NOT repeated here.
defaults to Anthropic (unservable) and degrades to the honest keyless path
instead of using the key it has; and every static entry rots the way the
openai gpt-5.2 pin did. **Context:** the mechanism is done — one table
- entry per provider; the work is choosing tier grammar per provider and
+ entry per provider; `resolveTierDefault` already falls back to a SERVABLE
+ file-plane pin (`expansion_model` / `chat_model`) below the key walk, so a
+ single-provider install that pinned its model at init is covered (#3813);
+ the table work remains for installs with a key but NO pin. The rest of the
+ work is choosing tier grammar per provider and
asserting recipe capability fit (tool support for subagent). Start:
`PROVIDER_TIER_DEFAULTS` + `test/model-config.serial.test.ts` matrix +
the openai-latest ranking pattern. **Effort:** S-M per provider.
@@ -2569,8 +2656,12 @@ and the scope record at `~/.gstack/projects/garrytan-gbrain/ceo-plans/2026-06-12
`src/core/verbs/entity-card.ts` open-threads assembly + a new schema table
(additive — the card field already exists, so this is a quality upgrade, not
a contract change).
-- [ ] **P2 — `recall` filter composition vs the spec (found by the v0.43.0.0
- cross-model doc review).** The handler dispatch is first-match
+- [x] **P2 — `recall` filter composition vs the spec (found by the v0.43.0.0
+ cross-model doc review).** **Completed: v0.48.5.0 (2026-09-07)** — #4882: the
+ `recall` handler composes `since` with `entity`/`session_id` before the SQL
+ LIMIT and rejects unparseable values (`src/core/ops/facts.ts`), the composition
+ is spelled out in `docs/protocol/MEMORY_VERBS_v1.md`, and the server-side `limit`
+ cap landed earlier (`clampRecallLimit`, v0.46.13.0). Original text: The handler dispatch is first-match
(`supersessions` > `entity` > `session_id` > `since`), so `since` is
silently ignored when `entity`/`session_id` is supplied, and `limit` has no
server-side cap. Either compose the filters (additive — the spec's "filters
@@ -4990,10 +5081,12 @@ into one committed wave with a target version.
Switch to `\p{Script=Han}` / `\p{Script=Hiragana}` / `\p{Script=Katakana}`
/ `\p{Script=Hangul}`. Astral-plane support also requires
`Array.from(str)` codepoint iteration in chunker's char-slice fallback.
-- [ ] **v0.42 — CJK-aware overlap context in chunker.** `extractTrailingContext`
+- [x] **v0.42 — CJK-aware overlap context in chunker.** `extractTrailingContext`
is whitespace-token-based today; CJK chunks under maxChars cap have no
useful overlap with previous chunk. Switch to char-count when
- `countCJKAwareWords` would have triggered the CJK branch.
+ `countCJKAwareWords` would have triggered the CJK branch. Landed via
+ #4871 (wave adoption) for newly chunked pages; already-indexed pages
+ re-chunk on the MARKDOWN_CHUNKER_VERSION bump filed at the top of this file.
- [ ] **v0.42 — Thai / Arabic / Cyrillic / Devanagari script support.**
Same five-layer fix pattern as CJK: slugify ranges, chunker density
threshold, PGLite keyword fallback with script-aware tokenization.
@@ -5686,14 +5779,16 @@ contributor traps.
Affects `src/commands/sync.ts:buildDetachedWorkingTreeManifest` +
`buildSyncManifest`. Defer until someone files a tab-in-filename issue.
-- [ ] **v0.33+: CJK-aware overlap context in chunker.** v0.32.7
+- [x] **v0.33+: CJK-aware overlap context in chunker.** v0.32.7
`extractTrailingContext` is still whitespace-token-based, so CJK chunks
under the maxChars cap have no useful overlap with the previous chunk.
Search continuity across chunk boundaries degrades for pure CJK content.
The maxChars sliding-window in v0.32.7 IS overlap-protected for the
hard-cap path, so this only affects normal-size chunks. Plan: switch
`extractTrailingContext` to char-count when `countCJKAwareWords` would
- have triggered the CJK branch.
+ have triggered the CJK branch. Landed via #4871 (wave adoption) for newly
+ chunked pages; the version bump that re-chunks existing pages is filed at
+ the top of this file.
- [ ] **v0.33+: other non-Latin scripts (Thai, Arabic, Cyrillic,
Devanagari).** Same five-layer fix pattern as CJK applies: slugify
@@ -9109,3 +9204,20 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.
**Context:** filed from the ranker wave R1 fix (v0.48.4.0); the per-brain
opt-out is `gbrain config set search.relational_rerank_pin off`. **Effort:** M.
+
+- [ ] **P2 — ontology reads ignore fact-level `visibility` for remote
+ callers.** **What:** `getOntology` / `findOntologyConflicts` (both engines)
+ now hide observations whose PROVENANCE PAGE is `visibility: private`
+ (#4881 wave adoption), but they still return facts regardless of the
+ fact row's own `visibility` column, while every other facts read pushes
+ `visibility = 'world'` for untrusted callers (`pglite-engine/facts.ts`
+ listFacts, meta-hook, entity-card). `mergeOntologyFact` defaults
+ `visibility` to `'private'`, so nearly every ontology fact is
+ fact-private today. **Why:** the page-level gate closes the
+ "private page leaks through its extracted values + slug" hole; the
+ fact-level column is the larger remaining gap and deserves its own
+ fail-closed fix (thread `excludePrivate` into a `visibility = 'world'`
+ predicate on the same two queries, mirror in `loadChronicleContext`,
+ pin in `test/chronicle-ontology-private-visibility.test.ts` and the
+ e2e content-privacy suite). **Context:** filed from the #4881 adoption
+ (refuter amendment). **Effort:** S.
diff --git a/VERSION b/VERSION
index 00daba0fac..b8afe4c169 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.48.4.0
\ No newline at end of file
+0.48.5.0
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index d2684f172e..708697055f 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -301,7 +301,9 @@ Reports (JSON `schema_version: 1`): the effective engine vs the config-file
engine (they can differ under a transient env URL), `db_url_source`, an
env-shadow note when a cwd-.env `DATABASE_URL` is being excluded by the
cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loaded
-from the working directory's `.env`; with the precedence note when both `GBRAIN_DATABASE_URL` and
+from the working directory's `.env` family: `.env`, `.env.local`, and the
+`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,
+`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and
`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a
zero-round-trip pooler block (Supabase pooler detection, prepared-statement
resolution, pool sizes, direct/session-pooler derivability). `--brain <id>`
diff --git a/docs/TESTING.md b/docs/TESTING.md
index fd01018d0e..6113f3f36e 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -153,7 +153,7 @@ there even though they pass on Linux and macOS.
- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 10 matrix shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; files with no mined weight fall back to the p75 file weight so a new unweighted file can't silently unbalance a shard) and INCLUDES `*.slow.test.ts` (the three outlier slow files — longmemeval, entity-resolve-perf, brainbench-e2e — run as dedicated jobs alongside the matrix) plus `evals/**/*.test.ts` (keyless-allowlist-gated — `test/scripts/evals-collection.test.ts`). Each shard's bun process is bounded by `--max-concurrency` (`GBRAIN_TEST_MAX_CONCURRENCY`, default 4). Every bun-test job — matrix shards, serial-tests, verify, the slow/eval jobs — activates the PGLite schema snapshot (built in-runner via `scripts/lib/test-env.sh`; the brainbench gate brings its own in-memory PGLite and skips it; the ~42MB tar is also cached across jobs via actions/cache, with the runner's own hash check staying authoritative). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in the pooled `serial-tests` job via `bun run test:serial` — one bun process per file preserves the `mock.module` quarantine; the pool runs those processes concurrently. `bun run verify` gets its own job too, as does the BrainBench memory-conformance gate (`brainbench` job → `scripts/ci-brainbench-gate.sh`, hermetic in-memory PGLite, ~15s), which compares HEAD's fresh run against master's committed baseline (`evals/brainbench/baselines/main.json`) — the `test-status` aggregate checks its result explicitly. E2E (`.github/workflows/e2e.yml`) always runs its applicable execution lanes, with the jsonb-parity job in front of tier2 as the token-spend gate, and aggregates through `e2e-status`. Scheduled runs also require the full-corpus lanes, including each slow suite excluded from the coverage shards (longmemeval, entity-resolve-perf, and brainbench-e2e). Both aggregates reject failures, cancellations, and unexpected skips. Dependency caches and validated PGLite snapshots remain; successful test results are never reused. CI is the ground truth for "did everything pass."
- **Local fast loop** (`scripts/run-unit-shard.sh` via the parallel wrapper) uses round-robin-by-index sharding and EXCLUDES `*.slow.test.ts` AND `*.serial.test.ts`. Local trades coverage for inner-loop speed; CI catches what local skips.
-This divergence is intentional. Don't try to make them equal — the two scripts deliberately solve different problems. The regression test at `test/scripts/run-unit-shard.test.ts` pins what the local fast loop should and shouldn't include; `test/scripts/run-unit-parallel.test.ts` pins the wrapper's memory-adaptive concurrency and the OOM/external-kill serial rescue pass.
+This divergence is intentional. Don't try to make them equal — the two scripts deliberately solve different problems. The regression test at `test/scripts/run-unit-shard.test.ts` pins what the local fast loop should and shouldn't include, and that no unit-lane file spawning the CLI through `test/helpers/cli-spawn.ts` hand-pins a per-test timeout below the bunfig default (an explicit `test(name, fn, N)` ceiling overrides bun's `--timeout`, so `GBRAIN_TEST_TIMEOUT_MULTIPLIER` never reaches it — inherit the default instead; cli-spawn's own kill timer still reaps a hung child); `test/scripts/run-unit-parallel.test.ts` pins the wrapper's memory-adaptive concurrency, and the OOM/external-kill serial rescue pass, and operator-interrupt teardown (a Ctrl-C / SIGTERM to the wrapper while shards are live TERMs then KILLs every shard descendant, so a cancelled run cannot leave gtimeout/bun alive until the shard cap).
### Coverage lanes and gates
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index ce6e9017d4..cc35dac803 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -13,7 +13,11 @@ resolves to the `native-anthropic` implementation (SDK + `ANTHROPIC_API_KEY`),
`claude-cli:claude-sonnet-5` resolves to `ClaudeCliLanguageModel` (subprocess,
CLI-managed auth).
-**Chat-only — no embedding.** `gateway.embed()` throws immediately for
+**Chat + query expansion — no embedding.** Query expansion runs through the
+same `claude --print` subprocess as chat, on the schemaless text path (the CLI
+cannot carry a JSON schema, so the fenced JSON it answers with is parsed back),
+so a brain whose utility tier points at `claude-cli:` keeps the multi-query
+recall arm. `gateway.embed()` throws immediately for
`claude-cli` models (`claude-cli has no embedding model. Use openai or google
for embeddings.`). Claude has no first-party embedding model regardless of
transport; pair this recipe with `openai`, `google`, or `voyage` for
@@ -115,7 +119,7 @@ above.
| 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. |
| 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. |
+| 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). |
## Doctor probe timeout: per-recipe, 30s for claude-cli
diff --git a/docs/ai-providers/llama-server-reranker.md b/docs/ai-providers/llama-server-reranker.md
index d145bd07f7..a502464556 100644
--- a/docs/ai-providers/llama-server-reranker.md
+++ b/docs/ai-providers/llama-server-reranker.md
@@ -150,6 +150,20 @@ gbrain config set search.reranker.timeout_ms 60000
Per-call overrides in `SearchOpts.reranker_timeout_ms` still win for
any single call.
+## Document size
+
+Every document handed to the reranker is capped before the call: about 1,400
+estimated tokens (a 6,000-character cut first, then a shrink by measured
+token ratio), always on a UTF-8-safe boundary so a lone surrogate never turns
+a 500 into a 400. Prose chunks (~300 words) pass through untouched; code or
+CJK chunks at the chunker ceiling lose part of their tail before scoring, the
+same trade the embed side already makes. The cap exists because a
+chunker-ceiling chunk plus the query plus the server-side reranker template
+does not fit llama-server's default 2048 ubatch, and a pooled self-hosted
+reranker answered that overflow with a 500 that `applyReranker` fails open
+on, silently serving raw RRF order. It applies to every provider, hosted
+included, and has no config knob.
+
## Budget caps + local rerank
The recipe declares `cost_per_1m_tokens_usd: 0` and registers under
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index e21861e086..add7e7bae4 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -11,7 +11,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `docs/operations/conversation-parser-llm-fallback.md` — operator and maintainer contract for the default-off LLM parse fallback: exact config key, deterministic-first dispatch boundary, sampled data surface, untrusted-content prompt handling, page-date/cache-key coupling, timestamp validation, cache/checkpoint behavior, observability, limitations, and focused test commands.
-- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (the column is also submit_agent's binding, so one stored value must mean one span of slugs on both paths), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents/<id>/` namespace", so `??`, which only substitutes null/undefined, would leave a vacuous-subset bypass). `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` but NO `auth`, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`): a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (the column is also submit_agent's binding, so one stored value must mean one span of slugs on both paths), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents/<id>/` namespace", so `??`, which only substitutes null/undefined, would leave a vacuous-subset bypass). `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` but NO `auth`, so an auth-only check would let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `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`.
@@ -53,7 +53,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/docker-postgres.ts` — gbrain's OWN docker Postgres container, the shared seam between the init ladder's docker rung and db-repair's `conn_refused` auto arm. `GBRAIN_PG_CONTAINER = 'gbrain-postgres'` / `GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16'` / `GBRAIN_PG_HOST_PORT = 5434` live HERE and only here (DRY — the init rung and the repair arm must never carry two string literals that can drift). Ownership contract: gbrain starts and reuses this container, NEVER stops or removes it, and never touches a container whose credentials it cannot recover via `inspectCredentials` (docker inspect → `POSTGRES_PASSWORD` env + the container's ORIGINAL port mapping — a freshly generated password can never match a surviving container; unrecoverable → refuse with a recreate-with-consent recipe). Hardening: the port binds loopback-only (`127.0.0.1:5434` — a single-machine brain store, not a network service); data lives on the named `gbrain-pgdata` volume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare `-e POSTGRES_PASSWORD` — argv is world-readable in `ps`); `docker run` gets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls). `isGbrainDockerUrl` is the one predicate for "does this URL point at our container" (loopback + dedicated port — never error text).
- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.
- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure checks: `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check, a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.
-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts`, `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.
+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.
- `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.
@@ -62,8 +62,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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)`, `countCJKAwareWords(s)` (30% density threshold — 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`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
-- `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 markdown chunker version records the current index format.
+- `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/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.
- `src/core/chunkers/llm.ts` — LLM-guided chunking: pre-splits into 128-word candidates via the recursive chunker, then asks a Haiku-class model "where does the FIRST topic shift occur?" per window.
- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.
@@ -74,7 +75,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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). 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/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/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.
@@ -82,7 +83,7 @@ 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`.
+- `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/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.
@@ -106,7 +107,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` fails the build if the compiled binary ever silently falls through to recursive chunks. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.
- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve `--source <id>` (space or inline `=` spelling) and the ambient source scope through the shared `code-scope.ts` resolver, matching `code-callers`/`code-callees`; `--all-sources` restores the brain-wide read. The `AND p.source_id = $N` fragment comes from `code-scope.ts`'s `pushSourcePredicate(params, opts)` (numbered off `params.length` so it composes with `--lang` and any other optional predicate; `''` when spanning every source) — code-def's lookup, its filtered-types probe, and code-refs all use it.
- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.
-- `src/core/code-graph-readiness.ts` — typed readiness signal shared by the four code-* surfaces (`code-def`/`code-refs`/`code-callers`/`code-callees`). `resolveCodeReadiness(engine, {kind:'symbol'|'edge', count, sourceId?, allSources?, remote?})` returns `{status:'not_built'|'no_symbols'|'indexing'|'ready'|'out_of_scope'|'unknown', ready, has_code, pending_edges, scoped_source_id?}` (6-state `CodeGraphStatus`; `scoped_source_id` is set only for `out_of_scope`, naming the excluded scope). `count>0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes against `content_chunks` JOIN `pages` (`page_kind='code'`) — no `page_kind` index needed, and the pending probe rides the partial `idx_content_chunks_edges_backfill`. `kind:'symbol'` (code-def/refs) is 3-state + brain-wide, because symbol metadata is set at chunk time and edge resolution is irrelevant to it: no code chunks → `not_built`; code chunks but none carry `symbol_name` yet → `no_symbols` (chunks indexed before symbol extraction; hints at `reindex-code`); symbol-bearing chunks → `ready` (it never reports `indexing`). `kind:'edge'` (code-callers/callees) is 3-state + source-scoped (`not_built`/`indexing`/`ready`), with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS` from `src/core/chunkers/symbol-resolver.ts`) so a resolver-version bump never falsely reports `ready`. Both grains additionally share `out_of_scope`: when the scoped probe finds no code but an unscoped rerun finds code exists brain-wide (a chunk-existence check only — it doesn't verify symbol metadata or edge completeness), it's the caller's resolved scope that excludes it, not an unbuilt graph. That unscoped rerun runs ONLY for trusted local callers (`remote === false`); a scoped remote caller sees `not_built` instead, never a brain-wide code-existence disclosure. Probe scope matches each command's result-query `deleted_at` posture (def/refs don't filter `deleted_at`, so neither do the probes). Any DB error returns `status:'unknown'` (fail-open; never breaks the command). `readinessHint(r)` renders the human one-liner. Wired into `code-def.ts`/`code-refs.ts` (brain-wide), `code-callers.ts`/`code-callees.ts` (resolved `sourceId`/`allSources`), and all four `code_*` MCP op handlers in `src/core/ops/code-intel.ts` (`operations.ts` imports `codeIntelOperations` and spreads it into the canonical `operations` array, not a re-export). Pinned by `test/code-graph-readiness.test.ts` + readiness-envelope cases in `test/e2e/code-intel-mcp-ops-pglite.test.ts`.
+- `src/core/code-graph-readiness.ts` — typed readiness signal shared by the code-* surfaces (`code-def`/`code-refs`/`code-callers`/`code-callees`, plus the `code_blast`/`code_flow` walk ops). `resolveCodeReadiness(engine, {kind:'symbol'|'edge', count, sourceId?, allSources?, remote?})` returns `{status:'not_built'|'no_symbols'|'indexing'|'ready'|'out_of_scope'|'unknown', ready, has_code, pending_edges, scoped_source_id?}` (6-state `CodeGraphStatus`; `scoped_source_id` is set only for `out_of_scope`, naming the excluded scope). `count>0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes against `content_chunks` JOIN `pages` (`page_kind='code'`) — no `page_kind` index needed, and the pending probe rides the partial `idx_content_chunks_edges_backfill`. `kind:'symbol'` (code-def/refs) is 3-state + brain-wide, because symbol metadata is set at chunk time and edge resolution is irrelevant to it: no code chunks → `not_built`; code chunks but none carry `symbol_name` yet → `no_symbols` (chunks indexed before symbol extraction; hints at `reindex-code`); symbol-bearing chunks → `ready` (it never reports `indexing`). `kind:'edge'` (code-callers/callees) is 3-state + source-scoped (`not_built`/`indexing`/`ready`), with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS` from `src/core/chunkers/symbol-resolver.ts`) so a resolver-version bump never falsely reports `ready`. Both grains additionally share `out_of_scope`: when the scoped probe finds no code but an unscoped rerun finds code exists brain-wide (a chunk-existence check only — it doesn't verify symbol metadata or edge completeness), it's the caller's resolved scope that excludes it, not an unbuilt graph. That unscoped rerun runs ONLY for trusted local callers (`remote === false`); a scoped remote caller sees `not_built` instead, never a brain-wide code-existence disclosure. Probe scope matches each command's result-query `deleted_at` posture (def/refs don't filter `deleted_at`, so neither do the probes). Any DB error returns `status:'unknown'` (fail-open; never breaks the command). `readinessHint(r)` renders the human one-liner. Wired into `code-def.ts`/`code-refs.ts` (brain-wide), `code-callers.ts`/`code-callees.ts` (resolved `sourceId`/`allSources`), and all six `code_*` MCP op handlers in `src/core/ops/code-intel.ts` (`operations.ts` imports `codeIntelOperations` and spreads it into the canonical `operations` array, not a re-export). `code_blast`/`code_flow` stamp `status`/`ready` (+ `scoped_source_id`) onto the walk result through the module-private `attachWalkReadiness` helper: computed AFTER the traversal cache (readiness is never cached), `not_found` probes at symbol grain, `ok`/`ambiguous` at edge grain with count = nodes/candidates, and `unsupported_language` is passed through untouched. Pinned by `test/code-graph-readiness.test.ts` + readiness-envelope cases in `test/e2e/code-intel-mcp-ops-pglite.test.ts`.
- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.
- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.
- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.
@@ -185,7 +186,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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-*`) and drives `defaultMaxOutputTokens`'s 32k thinking headroom; think/index.ts shares it. `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. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.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']`.
@@ -195,33 +196,33 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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, 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.
+- `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): `rerank-2.5` flagship ($0.05/M) + `rerank-2.5-lite` ($0.02/M; prices verified 2026-08-15), `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. 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. Pinned by `test/claude-cli-recipe.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`.
- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.
- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts`, `minions/batch-projection.ts`, and `cycle/budget-meter.ts`.
- `src/core/takes-quality-eval/pricing.ts` — fail-closed budget pricing for `eval takes-quality run --budget-usd N`. `MODEL_PRICING` is a curated `provider:model` allowlist (default panel + likely overrides) whose VALUES are derived from `model-pricing.ts` via `canonicalLookup`; an allowlisted id missing from canonical throws at module load. Schema is `{input_per_1m, output_per_1m}`. A model NOT on the allowlist aborts the run with an actionable error rather than guessing (distinct from `cross-modal-eval/runner.ts`, which silently estimates zero on unknown models — both now source numbers from canonical).
-- `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); `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/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/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); no key at all → `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/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`.
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/zeroentropy/dashscope/google — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker completes the job as a calm skip. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called from `reconfigureGatewayWithEngine`, TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.
-- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/google + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
+- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/zeroentropy/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, re-exported by `src/cli.ts`. Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries (a symlink dirent is followed via `statSync` — `readdirSync` dirents report the link's OWN type without following, so skill dirs symlinked in from a shared store, e.g. `~/.agents/skills/<name>`, still load), `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.
- `src/core/skill-catalog.ts` — host-repo skill catalog backing the MCP `list_skills` / `get_skill` ops. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills over `gbrain serve` — a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) **publish gate** — `assertPublishEnabled(ctx, publishSkills)`; remote callers require `mcp.publish_skills === true`, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (`ctx.remote === false`) always pass. (2) **path confinement** — `assertSkillNameShape` rejects separators/`..`/null/space before any FS access; the client `name` is a manifest LOOKUP KEY (via `loadOrDeriveManifest`), never a raw path segment; `confineManifestPath` does realpath + relative-containment + `SKILL.md`-regular-file check on EVERY entry (defeats poisoned manifest.json `path`, symlink/`..` escape). (3) **frontmatter allowlist** — `GetSkillResult.frontmatter` projects a safe subset; private `writes_to` + `sources` dropped. (4) **prose-only + 256KB cap** (`MAX_SKILL_MD_BYTES`, env `GBRAIN_MAX_SKILL_MD_BYTES`), size-checked twice (statSync + UTF-8 byte length). (5) **no install_path serve for remote** — remote callers use `autoDetectSkillsDir` (no install-path tier) so a hosted gbrain with no agent repo returns `storage_error`; local callers use `autoDetectSkillsDirReadOnly`. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: `readMcpPublishSkills` / `readMcpSkillsDir` prefer the DB plane (`engine.getConfig`) over the file plane (`ctx.config.mcp`). Tool-honesty: `crossReferenceTools(declared, ctx)` splits a skill's declared `tools:` into `usable_tools` vs `unavailable_tools`; `buildSkillCatalog`'s `instructions` envelope (`SKILL_CATALOG_INSTRUCTIONS`) carries the "these are prose, follow-then-call-tools" protocol. Skills are host-filesystem repo-global — `sourceScopeOpts(ctx)` / `ctx.brainId` deliberately do NOT apply. `buildSkillCatalog` is resilient (one malformed/escaping skill is skipped, never throws). Config keys in `src/core/config.ts`: `GBrainConfig.mcp?: { publish_skills?, skills_dir? }` + `KNOWN_CONFIG_KEYS` entries `mcp.publish_skills`/`mcp.publish_skills_prompted`/`mcp.skills_dir` + `mcp.` prefix in `KNOWN_CONFIG_KEY_PREFIXES`. `src/commands/init.ts` writes `config.mcp = { publish_skills: true, ... }` for new installs (existing config wins on re-init). `src/commands/upgrade.ts:runPostUpgrade` adds a one-time consent prompt (gated by `mcp.publish_skills_prompted`; existing installs stay OFF until owner opts in). Three ops register in `src/core/ops/skills-catalog.ts` (spread into the `operations.ts` façade): `list_skills` with optional `section` filter + `cliHints:{name:'skills'}`; `get_skill` taking `name` (+ `source_id` for brain-resident packs) + `cliHints:{name:'skill', positional:['name']}`; `list_brain_skillpack`. They dynamically import this module to avoid the import cycle (skill-catalog statically imports the `operations` array). Descriptions in `src/core/operations-descriptions.ts` (`LIST_SKILLS_DESCRIPTION`, `GET_SKILL_DESCRIPTION`, `SKILL_CATALOG_INSTRUCTIONS`, `SKILL_CLIENT_GUIDANCE`), pinned by `test/operations-descriptions.test.ts`. CLI: `gbrain skills` / `gbrain skill <name>`. Pinned by `test/skill-catalog.test.ts`, `test/skill-catalog-security.test.ts` (path-confinement / poisoned-manifest / symlink-escape), `test/skill-catalog-transports.test.ts` (publish-gate + remote-vs-local) over `test/fixtures/skill-catalog/`.
-- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K).
+- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
- `src/core/repo-root.ts` — Shared `findRepoRoot(startDir?)`: walks up from `startDir` (default `process.cwd()`) looking for `skills/RESOLVER.md`. Zero-dependency, imported by `doctor.ts` and `check-resolvable.ts`; parameterized `startDir` makes tests hermetic. Read-path / write-path split: `autoDetectSkillsDir` (shared, read+write-safe) has tier-0 `$GBRAIN_SKILLS_DIR` operator override ahead of the 4-tier chain. `autoDetectSkillsDirReadOnly` wraps it with a tier-5 install-path fallback that walks up from `fileURLToPath(import.meta.url)` and gates on `isGbrainRepoRoot` so unrelated repos can't false-positive. Read-path callers (`doctor`, `check-resolvable`, `routing-eval`) use the read-only variant; write-path callers (`skillpack install`, `skillify scaffold`, `post-install-advisory`) stay on the shared function so install-from-`~` can't retarget the bundled gbrain `skills/` instead of the user's workspace. `SkillsDirSource` variants `'env_explicit'`, `'install_path'`; `AUTO_DETECT_HINT_READ_ONLY` documents the extra tier. The `--fix` safety gate in `doctor.ts` + `check-resolvable.ts` refuses auto-repair when `detected.source === 'install_path'`.
- `src/core/skills-integrity.ts` — Tamper-evidence manifest for the bundled `skills/` tree; NOT a signature system. Pure functions over `node:crypto` sha256: `computeSkillsManifest(dir)` (recursive, sorted '/'-relative paths, excludes the manifest itself, skips symlinks), `renderSkillsManifest(dir)` (2-space JSON + trailing newline, deterministic), `verifySkillsManifest(dir, manifest)` → `{modified, missing, extra}`. Committed manifest lives at `skills/skills.lock.json` (`SKILLS_MANIFEST_FILENAME`); regenerate via `bun run scripts/generate-skills-manifest.ts`. Consumers: the warn-only `skills_manifest_integrity` doctor check in `src/commands/doctor.ts` (ok/skip when no manifest is present — user workspaces and compiled-binary installs are not drift) and the CI freshness guard `scripts/check-skills-manifest-fresh.sh` (`bun run check:skills-manifest`, in `bun run verify`). Pinned by `test/skills-integrity.test.ts`.
- `src/commands/check-resolvable.ts` — Standalone CLI wrapper over `checkResolvable()`. Exports `parseFlags`, `resolveSkillsDir`, `DEFERRED`, `runCheckResolvable`. Exit rule: **1 on any issue (warnings OR errors)**, stricter than doctor's `ok` flag. Stable JSON envelope `{ok, skillsDir, report, autoFix, deferred, error, message}` — same shape on success and error. `--fix` runs `autoFixDryViolations` BEFORE `checkResolvable` (same ordering as doctor). `scripts/skillify-check.ts` subprocess-calls `gbrain check-resolvable --json` (cached per process) and fails loud on binary-missing. AGENTS.md workspaces resolve natively (see `src/core/resolver-filenames.ts`). `DEFERRED[]` is empty. Resolver lookup is the multi-file merge in `src/core/check-resolvable.ts` — entries collected from every `RESOLVER.md`/`AGENTS.md` across the skills dir AND its parent, deduped by `skillPath` (first occurrence wins). Uses `autoDetectSkillsDirReadOnly` so `cd ~ && gbrain check-resolvable` finds bundled skills via the install-path fallback; `--fix` carries the same install-path safety gate (refuses to write when `detected.source === 'install_path'`).
@@ -236,7 +237,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `test/helpers/tty-harness.ts` + `scripts/dx-explore.ts` — the repo's single real-PTY layer, on pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json; no node-pty). `launchTty` spawns any CLI under a true pseudo-terminal with the hermetic env contract from `test/helpers/agent-harness.ts` (`hermeticChildEnv`; `dropEnv` strips pass-through auth keys), records timestamped output frames, and exposes `waitFor`/`waitForAny`/`mark`/`sendKey`/`waitForQuiet`/`waitForExit`/`close`. Lifecycle rule: only `close()` clears the wall-clock kill timer — always call it in a `finally`. Pure helpers (`stripAnsi`, `computeStalls`, `renderStallsReport`, `parseDriveCommand`, `buildClaudeTuiSeed`) are unit-tested in `test/tty-harness.test.ts`; that file's live-PTY smokes are `describe.skipIf(!ptySupported())`-gated. Transcript writes are structurally redacted: `redactSecrets` (secrets ≥ `MIN_REDACT_SECRET_LEN` → `[REDACTED:<name>]`) runs at every write site, `coalesceSecretStraddles` merges frames so a secret split across a frame boundary can't bypass redaction, and `saveTranscript` takes an explicit `redact` map (seam — dx-explore builds it, tty-harness stays import-free of it). `scripts/dx-explore.ts` is the DX-exploration driver built on it — a developer instrument, not a test: nothing asserts, transcripts land gitignored under `.context/dx-runs/` (doc: `docs/guides/bootstrap.md`). The interactive `gbrain init` pickers are asserted for real in `test/init-picker-pty.serial.test.ts` (serial lane, so it runs in required CI).
- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.
- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
-- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.
+- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.
- `src/core/skill-manifest.ts` — parser for `skill-manifest.json` records. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting.
- `src/commands/routing-eval.ts` + `src/core/routing-eval.ts` — `gbrain routing-eval` catches user phrasings that route to the wrong skill. Reads `skills/<name>/routing-eval.jsonl` fixtures (`{intent, expected_skill, ambiguous_with?}`). Structural layer runs in `check-resolvable` by default (zero API cost). `--llm` is a placeholder for a future LLM tie-break layer; today it emits a stderr notice and runs structural only. Uses `autoDetectSkillsDirReadOnly` and the same multi-file resolver merge as `check-resolvable`, so on OpenClaw layouts (`skills/RESOLVER.md` + `../AGENTS.md`) all three commands see the same trigger index. RESOLVER.md rows carry the full frontmatter `triggers:` arrays so the structural matcher sees realistic phrasings; ambiguous-fixture annotations cover deliberate skill chains like `enrich → article-enrichment`.
- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` — Check 6 of `check-resolvable`. Parses `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON (error severity). Internal `parseFrontmatter` is a thin wrapper over the shared `src/core/skill-frontmatter.ts` parser so both filing-audit and skill-brain-first read the same shape (`tools?`, `triggers?`, `brain_first?: 'exempt'`, typed `brain_first_typo`) from one source of truth.
@@ -257,7 +258,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/lock-renewal-tick.ts` — Pure function behind `MinionWorker.launchJob`'s setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. Exports `runLockRenewalTick(deps, state) → Promise<TickResult>` + `resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs` + `RenewalCallTimeoutError` + `LockRenewalTelemetryCtx`. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (`lease - safetyMargin`, cadence-aware: `sinceLastSuccess + intervalMs >= deadline`), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (audit `success_after_failure` with `via: 'verify'`); fenced-false → CERTAIN loss → `lock_lost` (the only certain signal); verify unreachable → defer + reconnect-once (audit `failure` with `deadline_deferred: true`), aborting only past `hardEvictMs` — a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps): `GBRAIN_LOCK_RENEWAL_MAX_FAILURES` (default 3, audit-labeling only), `GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS` (default `min(lease/3, 15s)`), `GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS` (default `min(lease/6, 30s)`), `GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS` (default `2×lease`, floored to the soft deadline; setting it TO the deadline approximates abort-at-deadline). Telemetry: tick lateness (`now - lastTickFiredAt - intervalMs`, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation), `overlapSkips` (tickInFlight re-entrancy skips only), failure-cause classification via the named `RenewalCallTimeoutError` (`call-timeout` | `refused` | `fenced-lost`), optional `deps.loadSnapshot` (try/caught — telemetry must never throw into control flow) and `deps.onRenewalSuccess` (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected `deps.now`, which production binds to `performance.now()` (monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded to `renewLock` (best-effort — the fence is the correctness authority). The tick checks `state.cancelled()` at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: `should_abort` carries `{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}` and `lock_lost` carries `{cause: 'fenced-lost', via: 'renewal'|'verify'}`; the worker stashes the result as per-launch `abortMeta` so the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned by `test/worker-lock-renewal.test.ts` (hermetic state-machine suite incl. a fake-time starvation replay, the cadence-quantization pin, hard-backstop timelines, relational-clamp cases) + `test/e2e/worker-lock-renewal-starvation.test.ts` (real-PG foundations). `LockRenewalDeps.renewLock` carries an optional per-call `{signal}`; the timeout race aborts it so the losing UPDATE releases its slot.
- `src/core/minions/worker-exit-codes.ts` — single source of truth for reserved worker process exit codes, shared by the worker (sets them) and supervisor/CLI (classify them). Exports `WORKER_EXIT_RSS_WATCHDOG = 12`. The RSS watchdog drain must be self-identifying: a code-0 exit is indistinguishable from a healthy queue-drain, so a `code===0 → clean_exit` classifier would never count it and a respawn loop would stay invisible. A distinct code makes the drain `likely_cause=rss_watchdog`. Code 12 is deliberately outside {0 clean, 1 runtime_error} and the 128+N signal range. Also reserves the `jobs run-child` codes: 13 usage/PGLite, 14 not-claimed/token-mismatch, 15 result-write-failed (result-file presence, not the exit code, classifies the normal path).
- `src/core/minions/rss-default.ts` — cgroup-aware auto-sized default for the worker RSS watchdog cap. `resolveDefaultMaxRssMb(opts?)` / `describeDefaultMaxRss(opts?)` (provenance for the startup log) / `readCgroupMemLimitBytes(readFile?)`. Used at every spawn site (`jobs work`, `jobs supervisor`, autopilot, `MinionSupervisor`). Formula `clamp(round(0.5 × basisMB), 4096, 16384)` where `basis = min(cgroupLimit, totalmem)`. LOAD-BEARING NUANCE: plain `os.totalmem()` reports HOST RAM, so in a 4GB cgroup on a 126GB host it would pick 16GB, the watchdog would never fire, and the kernel OOM-killer would SIGKILL at 4GB. The cap MUST sit below the real ceiling so the graceful drain (distinct exit code, loud log) beats the kernel's silent kill; the 4096 floor applies only when it stays below the basis. Reads cgroup v2 `/sys/fs/cgroup/memory.max` (literal `max` = unlimited) then v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Explicit `--max-rss` (including `0` to disable) always wins. Pinned by `test/rss-default.test.ts`.
-- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output.
+- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.
- `scripts/check-worker-lock-renewal-shape.sh` — CI guard wired into `bun run verify`. Two invariants on `src/core/minions/worker.ts`: (1) the bug pattern `lockTimer = setInterval(async ...)` must NOT appear (narrowed via `lockTimer =` prefix so unrelated `setInterval(async)` calls — like the stall detector — don't false-fire), (2) `runLockRenewalTick` must remain referenced so the pure-function test seam survives refactors. Bug-pattern-specific by design — a future refactor to `setTimeout`-recursion or `AbortController`-based scheduling passes as long as the bug pattern stays absent. POSIX ERE + `[[:space:]]` for BSD-grep portability. Honors `GBRAIN_LOCK_RENEWAL_SHAPE_TARGET` env override for fixture-based meta-tests. Pinned by `test/scripts/check-worker-lock-renewal-shape.test.ts` (5 cases).
- `src/core/doctor-cause-rank.ts` — pure cause-ranking for `gbrain doctor`. `rankIssues(checks)` returns non-ok checks ordered fail-before-warn then root-before-symptom then name (deterministic). `ROOT_CAUSE_CHECKS` / `SYMPTOM_CHECKS` are ORDERING ONLY — tier membership asserts no causality. `downstream_of` is set ONLY from a small map of KNOWN grounded edges (`queue_health` / `supervisor` → `worker_oom_loop`, since they read the same `aborted: watchdog` / `rss_watchdog` source) AND only when the named root is itself failing — never a root×symptom cartesian (co-occurrence never implies causality). `fix` prefers `details.fix_hint` else the message. `CAUSE_GRAPH_NAMES` + `allKnownCheckNames()` back a drift guard asserting every graphed name is a real check. Consumed by `computeDoctorReport` (`top_issues` field, additive, schema_version stays 2) + the "Top issues (ranked by cause)" header in `outputResults`. Pinned by `test/doctor-cause-rank.test.ts`.
- `src/core/audit/pool-recovery-audit.ts` — reap/reconnect audit on the shared `audit-writer` primitive. Events: `reap_detected` (CONNECTION_ENDED), `reconnect_other` (network/auth/health-check), `reconnect_succeeded`, `reconnect_failed`. `readRecentPoolRecoveries(hours=1)` returns `{reaps, recoveries, failures, others, events}`. Error summaries route through `redactConnectionInfo` before truncation (DSN/host/IP safe). Emitted ONLY from `PostgresEngine.reconnect(ctx?)` (the rare reap-retry path, near-zero hot-path cost); `reconnect()` classifies the threaded error via `isConnectionEndedError` (in retry-matcher.ts) so only true pooler reaps are labeled `reap_detected`. The retry callback in retry.ts threads the triggering error as `(ctx?: {error?}) => Promise<void>`. Pinned by `test/audit/pool-recovery-audit.test.ts`.
@@ -270,7 +271,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` (strict per-source; multi-source iteration is the caller's job) drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → `getPage` → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, auto-link + write-through) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).
- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping.
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same window `embedPage`'s single-page chunkless branch has. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page — but ONLY when EVERY chunk was stale this pass (a partially-stale page keeps preserved chunks of unknown provenance, so it stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it re-fetches the LIVE page via `getPage` (chunks CURRENT content, not the batch-list snapshot) and re-checks `getChunks`, narrowing (NOT fully closing — accepted residual risk, see the function's docstring) the check-then-write window: a concurrent writer landing chunks in the gap between that re-check and the `upsertChunks` call can still have them overwritten with this sweep's stale-content chunks, the same window `embedPage`'s single-page chunkless branch has. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, embeds, re-upserts via `upsertChunks`. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). This list is load-bearing: `upsertChunks` overwrites from EXCLUDED (not COALESCE), so any re-embed path that omits a field resets it — omitting `modality` flips every image chunk to `modality='text'` and silently zeroes the image search arm (its filter is `cc.modality = 'image'`). Never hand-roll a per-path field list. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Every embed-write path stamps `pages.embedding_signature` via `engine.setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` matches the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`.
- `src/core/retrieval-upgrade-planner.ts` — legacy ze-switch planner, slated for deletion with the ZeroEntropy removal; CLI-unreachable (the ze-switch shim refuses every operation) and kept ONLY as a test vehicle: `applyRetrievalUpgrade`/`resumeRetrievalUpgrade` carry the multimodal-column preservation pins and env-override gate cases in `test/retrieval-upgrade-planner.test.ts` + `test/ze-switch-env-override.test.ts`. The shared primitives (`runSchemaTransition`, `transitionDimPinnedColumn`, `TEXT_EMBEDDING_DIM_PINNED_TABLES`, `detectEnvOverride`, `EnvOverrideWarning`, `formatEnvOverrideWarning`) LIVE in `embedding-migration.ts`; this file re-exports them until the deletion. Its resume/undo paths probe `readContentChunksEmbeddingDim` first and skip the schema transition when the column is already at the target width — a same-width DROP+ADD still deletes every stored vector. Note the plane caveat: apply/undo write DB-plane config (`engine.setConfig`) that the file-plane-canonical embed pipeline does not read.
- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history + `force_sunset_target`) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
- `src/core/embedding-invalidation.ts` — signature-truth guards shared by the migration + embed paths, engine-pure via `executeRaw` (identical SQL on both engines). `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})`: same semantics as the engines' `invalidateStaleSignatureEmbeddings` PLUS the `NOT (frontmatter ? 'embed_skip')` predicate every stale selector applies — never NULL what nothing will re-embed (without it a migration would destroy vectors retained on embed_skip pages permanently and silently). ALL invalidation call sites (`applyEmbeddingMigration`, `runEmbedCore`, `embedStaleChunks`) route through it. `countFalseStampedChunks` / `clearFalseStampedSignatures`: the chunk-model truth cross-check — pages stamped WITH the target signature whose embedded chunks' `model` names another provider (bare provider-less model tails exempt, no surprise paid re-embed); count feeds plan/verify/`--status` honesty, clear runs in apply so the NULL-signature-inclusive invalidation re-embeds them. Pinned by `test/embedding-migration.test.ts` (`#4305 false target stamps + #4306 embed_skip-safe invalidation`).
@@ -283,12 +284,12 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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. 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. `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.
- 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/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>]`: 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`. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). 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).
+- `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}]` — the per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under `skipped`, not `errors`, and the failure ledger is written only for git-repo dirs, so this list is a non-git 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] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). Foreign-edge footer always present (`X foreign edges (use --include-foreign to traverse)`) so cross-source edges never disappear silently; `--include-foreign` widens the SQL filter to walk them. 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. Pinned by `test/graph-query.test.ts`.
+- `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/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).
@@ -321,7 +322,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.
- `src/core/minions/db-probe.ts` — hermetic DB-liveness probe with pool-starvation disambiguation: `runDbProbe(deps)` probes the read pool (signal-cancelled at `timeoutMs`), on failure probes the DIRECT lane (`DIRECT_PROBE_TIMEOUT_MS`, only when dual-pool is genuinely active) and returns a verdict — `pool_starved` ("server IS reachable; fault is in the transaction-pooler path — client pool exhaustion or a pooler-layer fault", deliberately an honest disjunction), `server_unreachable`, or `unknown`. Gauge counts render as a labeled tracked SUBSET; no waiter/available arithmetic. Pinned by `test/db-probe.test.ts`.
- `src/core/minions/niceness.ts` — OS scheduling-priority (niceness) primitives for the `--nice` flag. `parseNiceValue(raw)` whole-string parses + range-validates to POSIX `[-20, 19]` (rejects `"3.5"`/`"10abc"` that `parseInt` would silently truncate). `applyNiceness(nice, setPriority?, getPriority?)` calls `os.setPriority(0, n)` and ALWAYS re-reads `os.getPriority(0)` afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an `RLIMIT_NICE` clamp records the real effective value (e.g. `0`), not null; returns `{applied, requested, effective, error?}`. `getEffectiveNiceness(pid, getPriority?)` reads an arbitrary pid's niceness (null on dead/unreadable). `formatNice(n)` → `+10`/`0`/`-5`. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned by `test/niceness.test.ts`.
-- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (`ps -o lstart`, rejects a pid whose process started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.test.ts`.
+- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
- `src/core/minions/handler-timeouts.ts` — per-handler-type defaults for BOTH per-job time knobs, co-located so they can't drift apart unseen (they are different quantities: the budget bounds total runtime, the lease bounds dead-worker reclaim — never derive one from the other). `HANDLER_DEFAULT_TIMEOUT_MS`: 30 min for `subagent`, `subagent_aggregator`, `embed-backfill`, `autopilot-cycle`, `autopilot-global-maintenance`; 10 min for `chronicle_extract` + `facts-absorb`; 60 min for `contextual_reindex_per_chunk`. `HANDLER_DEFAULT_LOCK_DURATION_MS`: 300 s for the long LLM/loop handlers, 120 s for the single-LLM-call handlers, `shell` deliberately absent (fast dead-worker reclaim; verify-before-evict protects it anyway). `defaultTimeoutMsFor` / `defaultLockDurationMsFor` return the mapped default or `null` (short handlers keep the tight null-default wall-clock / the 30 s worker lease). `clampLockDurationMs` + `LOCK_DURATION_MS_MIN/MAX` ([5s, 1h]) is the ONE clamp shared by `queue.add`, the CLI `--lock-duration-ms` flag (`--dry-run` echoes the clamped value), and the MCP `submit_job` param; the same bound is mirrored in SQL at claim time and by the `minion_jobs.lock_duration_ms` range CHECK, so every layer agrees. Layers (explicit value always wins): `MinionQueue.add()` stamps at submit; `MinionQueue.claim()` COALESCEs NULL columns from the maps (durable invariant); migration v128 one-shot backfilled `timeout_ms` with authoring-time snapshot values — do NOT sync v128 when editing the maps (`lock_duration_ms` has no backfill: NULL = worker default). Pinned by `test/minions.test.ts` + `test/migrations-v128.test.ts` + `test/migrations-v130.test.ts`.
- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.
@@ -335,8 +336,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.
- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
- `src/core/minions/backpressure-audit.ts` — sibling of shell-audit.ts for `maxWaiting` AND `maxPending` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. One line per coalesce with `(queue, name, waiting_count/max_waiting OR pending_count/max_pending, returned_job_id, ts)`. `readRecentCoalesceCounts` feeds the `jobs stats` Backpressure line (reads current + previous ISO-week files so a 24h window survives week boundaries, filtered per queue). Makes the backpressure guards' coalesces visible instead of silent drops. Pinned by `test/backpressure-audit-read.test.ts`.
-- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) throw UnrecoverableError → dead when attempted>0 with zero successes. `resolveMaxOutputTokens` takes the model: thinking-by-default Claude 5 defaults to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
-- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(5 min, timeout/4) → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`.
+- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) throw UnrecoverableError → dead when attempted>0 with zero successes. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)
+- `src/core/minions/handlers/subagent-oneshot.ts` — oneshot synthesis runner. ONE rate-leased tool-less `gateway.chat` call (static `ONESHOT_SYSTEM` JSON contract rides the prompt-cache prefix; sub-budget min(5 min, timeout/4) → `fallback_reason: 'oneshot_timeout'`), then all-or-nothing validation BEFORE any write: JSON contract (`parseOneshotResponse`, ≤12 pages), slug grammar + `allowed_slug_prefixes` + reflections/originals task shape + the exact `oneshot_slug_suffix` (the idempotency boundary, enforced structurally), exact-match wikilink rule against existing ∪ in-batch slugs (`extractWikilinkTargets`; cold-brain relaxation: <5 pages AND no manifest accepts syntactic presence). Writes go through the SAME `brain_put_page` ToolDef the loop uses (fences/side-effects/provenance identical) with `deferEmbeds`, bracketed by standard ledger rows under invocation-scoped ids `oneshot-<inv8>-p<i>`; a post-batch `autoLinkWrittenPage` pass materializes in-batch forward wikilink edges. Ledger-first crash recovery: any prior oneshot rows → finalize from the ledger, never re-call the nondeterministic model. Transcript rows persist ONLY after success (a failed attempt is never replayable as a completed result). Every failure shape returns `{kind:'fallback', reason}` and the same job falls through to the agentic loop. Pinned by `test/minions/subagent-oneshot.test.ts` + the oneshot describes in `test/subagent-handler.test.ts` and `test/e2e/dream-synthesize-pglite.test.ts`. `ONESHOT_SYSTEM` spells out JSON string escaping (quotes, backslashes, line breaks). A parse failure whose reported output usage reaches the requested cap falls back as `length` even when the provider normalized the stop to `end`/`other`; below-cap malformed output stays `unparseable`, and valid JSON at the cap proceeds normally.
- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs whose every attempted write failed; `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`, plus the oneshot markers `oneshot_fallback | oneshot_timeout`; oneshot-path events carry `mode: 'oneshot'` and fallback events a `reason` — both rendered by `gbrain agent logs`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.
@@ -346,14 +347,15 @@ 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` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). 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` — trust comes from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitters set it. `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).
+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). 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` — trust comes from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitters set it. `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/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.
- `src/core/verbs/usage-log.ts` — observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.
- `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/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. 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/core/facts/forget.ts` — `forgetFactInFence(engine, id, {reason?, sourceId?, worldOnly?})`: forget as a fence rewrite (strike the claim, `valid_until` = today, `forgotten: <reason>` appended to context; atomic tmp + parse-validate + rename at the file `resolvePageWriteTarget` names), falling back to a DB-only `expireFact` when the row lacks v51 columns, the source has no `local_path`, or the file / fence row is missing. BOTH tiers also strike the row in `pages.compiled_truth` via `refreshPageBody`: the extract_facts reconcile reads the DB body, not the file, and would otherwise heal fence-live/row-expired "drift" by re-inserting the claim active at the same row_num. The mirror is body-only (`content_chunks` untouched), so the next `gbrain sync` must see the file as changed and re-chunk: the fence tier writes the parsed + sanitized FILE bytes and KEEPS the row's existing `content_hash` (the file changed, so it no longer matches — stamping the importer's hash made sync skip the page and the struck claim kept surfacing in chunk search); the legacy tier did NOT rewrite the file, so it stamps a row-shaped `contentHash` over the struck body instead (keeping the importer's hash there made sync skip the unchanged file). Neither tier ever persists an empty hash — a row that had none gets a row-shaped hash of its pre-mirror content (same rule in `fence-write.ts`). Both tiers run the strike under the per-page lock (`withPageLock`, 5s, same as the fence writers; the fence tier's fallbacks reuse the lock it already holds). The fence stays canonical, so a later absorb of a still-live file legitimately revives the row. The DB-body mirror is best-effort — a failure leaves file + facts row correct. Scope checks (`sourceId`, `worldOnly`) return `not_found` before any state inspection. Pinned by `test/forget-reconcile-durability.test.ts` + `test/fence-write.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).
- `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).
@@ -362,9 +364,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `starter` surface — override with `--surface` at registration or widen per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.
- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. Help is real and guarded: `JOBS_HELP` (full block incl. watch/stats/smoke flags + a footer naming exactly the five subcommands with dedicated help) and `JOBS_SUBCOMMAND_HELP` (work/supervisor/submit/watch/prune) print from a guard at the TOP of `runJobs`, BEFORE the thin-client refusal and the subcommand switch — `jobs work --help` can never start a daemon; only `--help`/`-h` are help tokens (bare `help` can be a job name); cli.ts routes it engine-free via `SELF_HELP_WITHOUT_ENGINE` + `CLI_ONLY_SELF_HELP`. `formatJobDetail` prints the effective wall-clock budget (`Timeout:`/`Deadline:` — 1x deadline kill when claimed, 2x wall-clock backstop, or which default applies) with a Date|string-defensive renderer; `timeout_at` is in `JOB_DATE_FIELDS` for thin-client rehydration. `jobs stats` prints a `Backpressure (24h)` line (per-name coalesce counts from the backpressure audit, current+previous ISO-week files, queue-filtered, best-effort) plus a suppressed-by hint naming the in-flight live-lock job when waiting=0 past the shared `GBRAIN_WEDGED_QUEUE_WARN_MINUTES` threshold — the read-only visibility for maxPending single-flight suppression. Pinned by `test/jobs-subcommand-help.serial.test.ts`, `test/jobs-format-detail.test.ts`, `test/jobs-stats-backpressure.serial.test.ts`. `case 'work'` wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging (the worker must not disconnect an engine it doesn't own; pool slots free immediately on shutdown rather than waiting for TCP keepalive). `jobs submit` surfaces the `MinionJobInput` retry/backoff/timeout/idempotency surface as flags: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`, `--max-waiting` (`maxPending` is deliberately internal-only — no flag; see TODOS). `jobs smoke --sigkill-rescue` is the SIGKILL-rescue guard. `registerBuiltinHandlers` always registers `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at startup with a loud per-plugin line; `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface). The `autopilot-cycle` handler forwards `job.data.phases` to `runCycle`, validated against `ALL_PHASES` from `src/core/cycle.ts` (invalid names filtered; empty/missing falls back to the default cycle); when `source_id` is set it binds `brainDir` to that source's `local_path` (null for a pure-DB source, never the global repo) and checks `isSourceInCooldown` before `runCycle`, returning a no-op `skipped` (not a failure) for a source still in its failure cooldown. The sibling `autopilot-global-maintenance` handler runs `MAINTENANCE_PHASES` (mixed ∪ global) once (no `sourceId`, `pull:false`) and stamps `autopilot.last_global_at` on success. `resolveJobPull` gives both cycle and standalone sync jobs one positive-polarity `pull` contract while preserving queued payloads that still carry the inverse legacy `noPull` key; explicit `pull` wins. The `sync` handler resolves `sourceId` at entry from `sources.local_path` (mirrors `cycle.ts:480`) so multi-source brains read the per-source `last_commit` anchor; concurrency routes through `autoConcurrency()` in `src/core/sync-concurrency.ts` (PGLite stays serial); `noEmbed` default is `true`. `gbrain jobs supervisor status` consumes `summarizeCrashes()` from `src/core/minions/handlers/supervisor-audit.ts` for parity with `gbrain doctor`: JSON adds `crashes_by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}` + `clean_exits_24h`; human output includes per-cause + clean-exits lines. Pinned by `test/job-pull-policy.test.ts` and 4 source-grep wiring assertions in `test/doctor.test.ts` requiring `crashes_by_cause` + `clean_exits_24h=` in both `doctor.ts` and `jobs.ts`. `gbrain jobs watch` decouples its two output axes: `--json` picks FORMAT (human default, never gated on isTTY), `--follow` picks LOOP (default `isTTY && !json`). Non-TTY with no flags prints ONE human snapshot then exits (clean for subagent/pipe/cron); `--follow` opts into a continuous stream (human plain per tick, or JSONL with `--json`); a TTY with no flags keeps the live ANSI dashboard. Resolution is the pure `resolveWatchMode(opts, isTTY): {json, follow, useAnsiDashboard}` in `src/commands/jobs-watch.ts`; the dispatch wires `--follow`. Pinned by `test/jobs-watch-mode.test.ts` (format×loop matrix incl. the TTY+`--json`-one-shot case) + `test/e2e/non-tty-output.serial.test.ts` (the `cmd </dev/null` non-empty-stdout contract). registers 11 Minion handlers: `reindex`, `repair-jsonb`, `orphans`, `integrity`, `purge`, `synthesize` (PROTECTED), `patterns` (PROTECTED), `consolidate` (PROTECTED), `extract_facts`, `resolve_symbol_edges`, `recompute_emotional_weight`. Phase wrappers delegate to `runCycle({phases:[name]})` so `src/core/cycle.ts` stays the single source of truth for phase semantics. The standalone `sync` handler passes `noExtract: true` to match `runPhaseSync`'s contract (doctor's remediation plan emitting `[sync, extract]` would otherwise double-extract). The `extract` handler routes `{stale: true}` jobs (submitted by performSync's size-gate defer branch) through `extractStaleFromDB` scoped to `data.sourceId`, chaining a continuation job (no maxWaiting — same NULL-sourceId coalesce hazard; timeout derived from `STALE_TIME_BUDGET_MS`) when the sweep's budget leaves `staleRemaining > 0` with forward progress. `parseJobIsolationFlag(args, env?)` (`--job-isolation`, space/= forms, `GBRAIN_JOB_ISOLATION` fallback, default inline); `case 'work'` resolves + fail-fast validates the child CLI invocation and warns when `--max-rss` is combined with isolation (watchdog covers the worker only); `case 'run-child'` is the INTERNAL child entrypoint (quiet registerBuiltinHandlers incl. plugin discovery, CLI owns disconnect+exit); startup warning when a Supabase-shaped engine runs single-pool (kill-switch collapse made loud); the `db_dead` fatal text is verdict-aware (pool starved vs server unreachable). Generic `jobs submit` normalizes the job name once before trust, queueing, handler lookup, and audit; after the admission check and dry-run return, its explicit `ensureSchema()` preflight still runs before shell/handler validation so stale brains retain the canonical init/migration error precedence. On PGLite, `jobs submit embed-backfill` refuses with `no_worker_surface` and a paste-ready inline embed command before any queue access; `--dry-run` evaluates the same read-only feasibility gate and never says “Would submit” for an impossible job. `--follow` is the sole CLI exception because it starts and awaits the inline worker; padded names follow the same normalized path and cannot strand a row. The MCP `submit_job` operation applies the same gate (including dry-run), translates the expected refusal to branchable `OperationError('no_worker_surface')`, and never emits `internal_error` for this capability miss. The `sync` handler forwards `job.data.github_item` ({repo, number, kind}) into `performSync` for github-kind single-item webhook refreshes.
- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.
-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and `maxCrashes: 5`. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).
+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and `maxCrashes: 5`. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (a stale lock from a crashed process does not block). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution).
- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract. It is compile-time source text (no runtime filesystem dependency; static imports of pure core leaves are fine — the rule bans filesystem/dynamic loading) and is imported by the stdio SDK server, OAuth HTTP SDK server, and legacy raw HTTP initialize path so all transports return the same instructions without drift. The contract covers skill routing, untrusted-content posture, source scope, and the `put_page` whole-page replacement/read-before-write rule. Two append-only extensions compose on top of it, in a fixed order: `buildMcpInstructions({writeback?})` adds the opt-in ambient-writeback section (from `src/core/facts/writeback-instructions.ts`) when `memory.auto_writeback` is enabled — absent/off is BYTE-IDENTICAL to `GBRAIN_MCP_INSTRUCTIONS`, and three exact-equality transport pins depend on that; `resolveMcpInstructions(config, env?, { writeback? })` takes that composed base and appends the operator-set deployment identity LAST under a `Deployment identity:` banner (no transport can weaken the contract): `GBRAIN_MCP_INSTRUCTIONS` env wins when non-blank, else `mcp.instructions` from the FILE plane (`~/.gbrain/config.json`; `gbrain config set|unset mcp.instructions` route there via `FILE_PLANE_DOTTED_KEYS` in `src/commands/config.ts`); an empty or whitespace-only env value is UNSET, not an override, and blank identity + writeback off returns the byte-identical canonical contract. Every transport calls `resolveMcpInstructions` with its own writeback opts: stdio once at boot via the fail-closed resolver (restart-to-flip, the strict-params posture; read failure = OFF bundle, never a wrong visibility posture; a running `gbrain serve` also needs a restart to pick up a new identity); OAuth per request (write-scope-gated, and the section renders only when THIS token's actual visible set — surface filter + bound-client fence — can call `remember`; `extract_facts` advertised under the same predicates); legacy bearer per initialize (surface-clamped: a surface without `remember` gets no section). All three route availability through `ambientOptsFrom(wb, {remember, extractFacts})`. Pinned over a real SDK `StdioClientTransport` by `test/e2e/serve-stdio-roundtrip.test.ts`, over raw HTTP by `test/http-transport.test.ts`, the identity plane (incl. the three-way composition order) by `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`, and the enabled-state builder/parity matrix by `test/mcp-instructions-writeback.test.ts`.
- `src/mcp/server.ts` — MCP stdio server (generated from operations). Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/e2e/serve-stdio-roundtrip.test.ts`.
+- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. Exemptions mirror `resolveMcpStdioSourceScope`: unset env, `__all__`, and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` (helper cases + a real `startMcpServer` integration case with a tmp `GBRAIN_HOME`).
- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run` via `resolveSocketPathForConfig`; the bound-source posture rejects requests naming any other source) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.
- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`.
- `src/mcp/validate-params.ts` — param normalization + validation for dispatch (direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per process — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts.
@@ -374,9 +377,9 @@ 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. 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).
+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. 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`). Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).
+- `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/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. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `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`.
@@ -396,28 +399,29 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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).
+- `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), `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), 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` — `<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/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/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), and `slog(...)` / `serr(...)` (prefix-aware `console.log`/`console.error`). 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/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/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/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).
- `src/core/sync-concurrency.ts` — single source of truth for the parallel-sync policy. Exports `autoConcurrency(engine, fileCount, override?)` (PGLite always serial; explicit override clamped to >=1; auto path returns `DEFAULT_PARALLEL_WORKERS=4` when `fileCount > AUTO_CONCURRENCY_FILE_THRESHOLD=100`), `shouldRunParallel(workers, fileCount, explicit)` (explicit `--workers` bypasses the >50-file floor), and `parseWorkers(s)` (rejects `'0'`, `'-3'`, `'foo'`, `'1.5'`, trailing chars). Used by `performSync`, `performFullSync`, `runImport`, and the Minion `sync` handler so the sites can't drift. `DEFAULT_PARALLEL_SOURCES = 4` is a SEPARATE constant for the per-source fan-out under `gbrain sync --all` — kept distinct from `DEFAULT_PARALLEL_WORKERS` because total live Postgres connections per wave ≈ `DEFAULT_PARALLEL_SOURCES × DEFAULT_PARALLEL_WORKERS × 2 (per-file pool)` = 32 at both defaults (each per-file worker opens its own `PostgresEngine` with `poolSize = min(2, resolvePoolSize(2))`); `sync.ts` warns when `parallel × workers × 2 > 16`. `resolveWorkersWithClamp(engine, override, commandName, fileCount)` wraps `autoConcurrency` with a per-command stderr clamp warning on PGLite (per-(command, requested) dedup via module-scoped warned-once set with `_resetWorkersClampWarningsForTest()` seam) and is the canonical surface for every bulk-command `--workers N` flag (extract-conversation-facts, extract, edges-backfill, reindex-multimodal, reindex, reindex-code); embed.ts deliberately bypasses it and keeps `GBRAIN_EMBED_CONCURRENCY || 20`. `resolveMaxConnections()` (reads `GBRAIN_MAX_CONNECTIONS`, undefined when unset) + `clampWorkersForConnectionBudget(workers, perWorkerPool, maxConnections, parentPool)` back the opt-in single-sync connection-footprint clamp so a big sync stays under a low pooler cap (`parent_pool + workers×perWorkerPool ≤ budget`); `gbrain doctor`'s `pool_budget` check (`computePoolBudgetCheck` / `checkPoolBudget` in `src/commands/doctor.ts`) warns when the budget leaves no room for a worker, pointing at `GBRAIN_POOL_SIZE=2`. Pinned by `test/pglite-workers-clamp.test.ts`.
-- `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` — the budget cap is a structural ceiling under concurrency. `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/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. `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 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/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 — completed legacy rows are read via `loadSuccessfulLegacySynthesisKeys` so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model. `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)
+- `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.
-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility is `COALESCE(frontmatter->>'atoms_scan_hash','') <> substring(content_hash from 1 for 16)`; the completion marker (`ATOMS_SCAN_HASH_KEY` in utils.ts) is EXCLUDED from `contentHash()`'s input so stamping it can't re-arm the very page it marks (and import-file.ts strips it from untrusted `remote===true` frontmatter so a remote writer can't suppress mining). Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable).
+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility is `COALESCE(frontmatter->>'atoms_scan_hash','') <> substring(content_hash from 1 for 16)`; the completion marker (`ATOMS_SCAN_HASH_KEY` in utils.ts) is EXCLUDED from `contentHash()`'s input so stamping it can't re-arm the very page it marks (and import-file.ts strips it from untrusted `remote===true` frontmatter so a remote writer can't suppress mining). Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the page `atoms_scan_hash` semantics), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`.
+- `src/core/cycle/extract-atoms-cost-gate.ts` — pure cost-gate decision for the extract_atoms `BudgetTracker`. `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` returns `{enforceCap, unpricedModel?, unpricedKind?, zeroPricedEmbedModel?, pricingOverrides?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable, so the import runs `noEmbed` and nothing embeds). Only a DEFAULT cap may be dropped that way: when the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced EMBED route keeps the cap and is priced at $0 via the returned `pricingOverrides` (the caller's map plus the $0 row); an unpriced CHAT model drops the cap either way. The phase passes the decision into `maxCostUsd` and hands the gate's overrides (or its own) to the tracker; it warns once either way (unpriced: kind + model + the `pricing.overrides` remedy, running uncapped rather than latching `budget_exhausted` on the first item; zero-priced: the embed model + the rate remedy). Pinned by `test/extract-atoms-embed-cost-gate.test.ts` (pure cases + a PGLite round-trip with a $0 chat model and an unpriced embed route).
- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched.
- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).
- `src/core/cycle/link-manifest.ts` — pre-retrieval LINK CANDIDATES manifest. `buildManifestContext(engine, sourceId?)` snapshots the source's slugs + basename index once per phase; `buildLinkManifest(engine, ctx, verdict, basename, {outputRoot, sourceId})` resolves wikilink candidates ZERO-EMBED from the triage verdict's cached entities/segment notes (basename-index exact/slugified matches first, bounded `searchKeyword` FTS second), excludes dream-output prefixes (self-consumption guard), renders `- [[slug]] — <deterministic first-two-sentence one-liner>` under hard caps (20 pages / 2400 chars) with buildTriageMapBlock's injection posture (whitespace-collapse + length caps + a 'data, not instructions' header). Best-effort everywhere — any failure degrades to the manifest-less prompt. Pinned by `test/cycle-link-manifest.test.ts`.
@@ -426,7 +430,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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. `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/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).
- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1; zero residue = phantom). Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match) → `findPrefixCandidates` ambiguity check → `fenceDbDrift` bi-directional check → dry-run early exit → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to canonical's disk fence with `(claim, valid_from)` dedup-guard + row_num continuation → `engine.refreshPageBody` with SHA-256 content_hash recomputed via the import-file shape → `engine.migrateFactsToCanonical` (lossless) → `engine.rewriteLinks` (DB FK rewrite; wiki-link text rewrite is a documented follow-up) → `engine.softDeletePage` + `engine.deleteFactsForPage(phantom)` + `fs.unlinkSync(phantomPath)`. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append.
@@ -436,15 +440,17 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `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/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). `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`.
+- `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`.
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).
+- `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). `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`.
+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).
- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`.
- `src/commands/friction.ts` + `src/core/friction.ts` — `gbrain friction {log,render,list,summary,diff}` reporter. Append-only JSONL under `$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl`. Schema is a flat extension of `StructuredAgentError`; every claw-test run opens with a `phase-marker`/`start` meta record carrying `agent` + `scenario` + `harness_schema` (agent-name resolution depends on it). Render groups by severity → phase, defaults to `--redact` for md output (strips `$HOME`/`$CWD` to placeholders so reports paste safely in PRs). `diff --base <run-or-agent> --compare <run-or-agent>` is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is `(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)` over `kind ∈ {friction, delight}` as MULTISETS (per-severity counts + totals are the compared attributes: `count_changed` = volume, `severity_changed` = distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to <run>" — an instrument, never a blame-attributor. Run-id resolves from `--run-id` > `$GBRAIN_FRICTION_RUN_ID` > `standalone.jsonl`. Skills the claw-test exercises carry a `_friction-protocol.md` callout so agents know when to log friction.
- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Four runners ship (`src/core/claw-test/runners/{openclaw,hermes,grok,opencode}.ts`; shared `detectBinary`/`filterAllowlistEnv` live in `agent-runner.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`); grok (xAI Grok Build, observed shapes in `docs/mcp/GROK-CLI-PIN.md`) invokes `grok -p <brief> --output-format plain` (`$GROK_BIN` > `which grok`; delta `GROK_HOME` + `XAI_API_KEY`; writes a version preamble into the transcript and warns loudly when the operator's `~/.claude.json` registers gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes in `docs/mcp/OPENCODE-CLI-PIN.md`) invokes `opencode run <brief> --format default` (`$OPENCODE_BIN` > `which opencode`; delta = the EXPLICIT multi-provider keys XAI/Google/Gemini/OpenRouter — BASE carries only Anthropic+OpenAI — plus XDG dirs, OPENCODE_CONFIG(_DIR), and OPENCODE_DISABLE_AUTOUPDATE; OPENCODE_CONFIG_CONTENT deliberately absent, it is a config-shadow channel; no `--auto` — MCP tools fire without it; bare-semver version preamble is the SST-vs-claimant discriminator; warns loudly when the user-global opencode config carries mcp.gbrain). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are `test/e2e/install-real-hermes.serial.test.ts`, `test/e2e/install-real-grok.serial.test.ts`, and `test/e2e/install-real-opencode.serial.test.ts` (split-gated a step past grok: opencode's anonymous free tier drives MCP tool calls keyless, so even the nonce SMOKE — with a STRUCTURAL `gbrain_*` tool_use assert via `parseOpencodeJsonl` — runs in the keyless tier; the paid anthropic leg self-validates its pinned model id against the authed `opencode models` list before any spend) (grok door is split-gated: keyless compat tier needs only the binary — `mcp doctor` is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs `XAI_API_KEY` and asserts a per-run nonce fact, never the committed one). Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (so a 256KB burst cannot stall the child). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).
- `skills/_friction-protocol.md` — shared cross-cutting convention skill (like `_brain-filing-rules.md`). Tells agents when to call `gbrain friction log` and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `docs/progress-events.md` — Canonical JSON event schema reference. Additive only.
-- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and leaves write containment to the caller.
+- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller.
- `scripts/check-jsonb-pattern.sh` — CI grep guard. Fails the build if any source contains (a) the `${JSON.stringify(x)}::jsonb` interpolation pattern (postgres.js v3 double-encodes it), or (b) `max_stalled INTEGER NOT NULL DEFAULT 1` in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokes `scripts/check-jsonb-params.mjs` and propagates its exit code. Wired into `bun test`.
- `scripts/check-getpage-scoped-write.mjs` — CI scanner for the unscoped-check/scoped-write source-isolation bug class: flags any non-test src file containing BOTH a `getPage(` call with no second argument (or the `X ? {sourceId} : undefined` any-source-when-unset ternary) AND a write-path call (`putPage(`/`importFromContent(`/`importFromFile(`). Fix pattern: `getPage(slug, { sourceId: x ?? 'default' })` (mirror the write's schema default); opt-out marker `gbrain-allow-unscoped-getpage: <reason>` for documented read-only first-match sites (span, preceding lines, or trailing same-line comment). Grandfathered allowlist is EMPTY. Comment/string-aware balanced-paren span walker (same skeleton as check-jsonb-params.mjs); argv-overridable roots; wired as `check:getpage-scope` in verify CHECKS + guards-manifest + `test/fixtures/guards/check-getpage-scoped-write.mjs/{bad,good}/` + `test/check-getpage-scoped-write.test.ts`.
- `scripts/check-jsonb-params.mjs` — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an `executeRaw`/`executeRawDirect`/`.unsafe()` call whose balanced arg span binds `JSON.stringify(x)` into a bare `$N::jsonb` cast. Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (`executeRaw<T>(`), and allows the sanctioned forms (`$N::text::jsonb`, `$N::text[]`, `executeRawJsonb`, `sql.json`, an inline `jsonb-guard-ok` comment). PGLite's native `db.query` is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a `JSON.stringify` assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Scan roots overridable via argv for its self-test (`test/check-jsonb-params.test.ts`).
@@ -504,7 +510,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `skills/migrations/` — Version migration files with feature_pitch YAML frontmatter
- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)
- `src/commands/backlinks.ts` — Back-link checker and fixer (enforces Iron Law). Repair-inserted references land as UNDATED rows (`- Referenced in [Title](path)`) in a dedicated `## Referenced by` section placed ABOVE the timeline region — retroactively stamping the repair date onto a timeline would forge events that never happened on that date; only live capture writes dated timeline entries. `insertBacklinkEntry(content, bodyStart, entry)` never touches bytes before `bodyStart`, locates the timeline boundary via `findTimelineSplitIndex` (existing timeline sentinels take precedence over bare `## Timeline`/`## History` headings), appends to an existing `## Referenced by` section or creates one above the timeline, and is CRLF-tolerant; `insertTimelineEntry` is an alias for existing import sites. `buildBacklinkEntry(sourceTitle, sourcePath)` takes no date; dir-shaped sources get an extension-less brain-slug link so the next check pass credits the fresh row instead of re-flagging (idempotency).
-- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.
+- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.
- `src/commands/report.ts` — Structured report saver (audit trail for maintenance/enrichment)
- `src/core/destructive-guard.ts` — three-layer protection against accidental data loss. `assessDestructiveImpact(engine, sourceId)` counts pages/chunks/embeddings/files/facts for a source (a fact-only source — a revoked agent's workspace, since facts are the primary agent write lane — is data at stake, not empty; pre-facts brains degrade to 0), plus `oauthClientCount` — OAuth clients whose `source_id` references it. `checkDestructiveConfirmation(impact, opts)` is the fail-closed gate (`--confirm-destructive` required when data is present; `--yes` alone is rejected). FK-RESTRICT lifecycle: `clientsReferencingSource(engine, sourceId)` lists ALL physical OAuth-client rows referencing a source via `oauth_clients.source_id` — the FK is PHYSICAL (ON DELETE RESTRICT ignores `deleted_at`), so soft-deleted (revoked-but-retained) rows BLOCK a hard delete too and come back tagged `deleted`; pre-migration brains without `deleted_at` fall back to untagged referents (42703-retry idiom) and brains without the table have none by construction. `formatClientReferentsBlock` renders the shared refusal `sources remove`/`sources purge` print (naming each client — `[revoked, retained]` for soft-deleted rows — + the revoke command) so the raw Postgres FK violation never reaches the operator. `softDeleteSource` / `restoreSource` / `listArchivedSources` / `purgeExpiredSources` drive the source-level archive lifecycle via `sources.archived BOOLEAN`, `archived_at TIMESTAMPTZ`, `archive_expires_at TIMESTAMPTZ`; `purgeExpiredSources` SKIPS client-referenced sources via a physical `NOT EXISTS` (soft-deleted clients count) so recurring maintenance keeps sweeping the rest instead of aborting. Page-level analog: `BrainEngine.softDeletePage` / `restorePage` / `purgeDeletedPages` plus `pages.deleted_at TIMESTAMPTZ` and a partial purge index. The MCP `delete_page` op rewires to `softDeletePage`; ops `restore_page` (`scope: write`) and `purge_deleted_pages` (`scope: admin`, `localOnly: true`) round out the surface. `get_page`/`delete_page`/`restore_page` (`src/core/ops/pages.ts`) accept an explicit per-call `source_id` that is honored or rejected loudly, never silently dropped: `get_page` resolves it through the caller's read grant (`'__all__'` spans every source for trusted local callers, the granted sources for remote callers), while `delete_page`/`restore_page` reject `'__all__'`, target exactly one source, and — for every caller other than trusted local CLI (`ctx.remote === false`) — accept only the caller's write authority (`ctx.auth.sourceId`, falling back to `ctx.sourceId` for legacy tokens and unauthenticated transports; the federated read grant `allowedSources` confers no delete/restore access), echoing the targeted `source_id` in the response. Pinned by `test/pages-source-scoping-4329.test.ts`. Search visibility (`buildVisibilityClause` in `src/core/search/sql-ranking.ts`) hides soft-deleted pages and archived sources from `searchKeyword` / `searchKeywordChunks` / `searchVector` in both engines. The autopilot cycle's `purge` phase calls `purgeExpiredSources` + `engine.purgeDeletedPages(72)` so the 72h TTL is real.
- `src/commands/pages.ts` — `gbrain purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.
@@ -514,7 +520,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `openclaw.plugin.json` — ClawHub bundle plugin manifest
- `.codex-plugin/plugin.json` + `.codex-plugin/mcp.json` + `.agents/plugins/marketplace.json` — the Codex plugin lane: manifest (skills → the committed `plugin/` tree; mcpServers → the NON-root mcp.json), the MCP declaration (`serve --surface starter --source-guard`, code-derived `env_vars` passthrough), and the codex-native marketplace. Version lockstep with package.json + the claude/openclaw manifests pinned by `test/codex-plugin-manifest.test.ts`.
- `.claude-plugin/plugin.json` + `.claude-plugin/marketplace.json` — the Claude Code plugin lane: inline MCP declaration (command/args/cwd via `${CLAUDE_PLUGIN_ROOT}`; no `env` block — Claude passes the parent env through); the Claude marketplace carries the full plugin PLUS the persona variant entries (`gbrain-coding`/`gbrain-daily` → `plugin-variants/`), while the codex marketplace intentionally stays single-entry until codex's multi-entry handling gets its observation run — variant names are pinned to `skills/plugin-lanes.json#personas` by `test/codex-plugin-manifest.test.ts`.
-- `.agents/gbrain-launcher` — shared plugin MCP launcher (sh, Unix-only): GBRAIN_BIN → PATH → ~/.bun/bin resolution, one stderr resolution line, GBRAIN_SURFACE substitute-or-append override for `serve` argv, actionable exit-127 recovery copy, no auto-install by design. Behavioral branches all pinned in the manifest test.
+- `.agents/gbrain-launcher` — shared plugin MCP launcher (sh, Unix-only) for the Codex, Claude Code, and OpenClaw (`openclaw.plugin.json` `mcpServers.gbrain`) lanes: GBRAIN_BIN → ~/.bun/bin/gbrain → PATH resolution, one stderr resolution line, GBRAIN_SURFACE substitute-or-append override for `serve` argv, actionable exit-127 recovery copy, no auto-install by design. Behavioral branches all pinned in the manifest test.
- `skills/plugin-lanes.json` — curation record for the plugin lanes: lane set = (openclaw bundle ∖ base_exclusions) ∪ additions, a reason per entry; `starter_gaps` is the generated snapshot of per-skill beyond-starter MCP ops (refresh via `--write-gaps`). The openclaw lane's own curation is untouched — plugin users ARE the brain host (the downstream-vs-host inversion).
- `scripts/generate-plugin-tree.ts` + `scripts/check-plugin-tree.sh` + `plugin/` — generator, byte-diff drift gate (in the skills commit gate), and the committed curated skill tree both plugin lanes ship (67 skills + shared conventions/_*.md deps + a generated README carrying the CLI-primary starter note).
- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).
@@ -640,14 +646,16 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/serve-health.ts` — serve `/health` probe + scopes version-skew floor, re-exported by `harness.ts`. `probeServeHealth(mcpUrl, fetchFn, timeoutMs=3000)` GETs `<base>/health` and returns `{ok, version?, engine?, detail?}`, never throws; `fetchFn` is an explicit argument (no ambient fetch, no engine, no config). `isServeOlderThanScopes(v)` compares against the PINNED `SCOPES_MIN_SERVE_VERSION` constant — a comparison against the moving CLI VERSION would false-flag every scope-aware serve on the next release. An older serve verifies scoped tokens as FULL ACCESS, so callers print the floor line unconditionally.
- `src/core/bootstrap/opencode-json.ts` — the ONE direct opencode-config writer (workspace stdio lane, harness remote lane, connect `--install`). ALL edits ride jsonc-parser `modify`/`applyEdits` (comments/formatting/EOLs survive byte-for-byte outside the edited range — opencode's own `mcp add` preserves comments, and JSONC is its effective grammar for BOTH `.json` and `.jsonc` filenames, which MERGE when both exist). Ownership is a 4-state STRUCTURAL FINGERPRINT (`opencodeEntryKind` → ours-same-source | ours-other-source | foreign | absent; GBRAIN_SOURCE EQUALITY for local entries, receipt-url match or the `{env:GBRAIN_REMOTE_TOKEN}` interpolation for remote), never a marker key (a future strict-schema flip must not brick the host). Distinct read-failure classes (ENOENT create / empty-as-{} / unreadable refuse); foreign refusal on write AND remove; post-render validation (our entry round-trips + every other key survives) keeps the original on failure; 0600 for inline-bearer targets; backups are UNIQUE per operation (`<config>.bak-<hex>`, returned in the result with `writtenText`, the exact rendered bytes) so overlapping runs can never clobber each other's snapshot, and a backup is chmod'd 0600 whenever the COPIED content carries an inline bearer (write AND remove paths); the ours-other-source refusal is caller-appropriate (url + `--force` wording on the remote/expect-url path, GBRAIN_SOURCE wording on the local path); `removeOpencodeMcpEntry` takes a caller expectation + optional `skipOtherSource` — the uninstall lane passes THIS workspace's source id so an ours-other-source match becomes a calm skip-with-note (another workspace's registration is never deleted; foreign still refuses); `reconcileOpencodeSiblingGlobal` clears a same-name gbrain entry from the OTHER global filename before a global write (foreign → refuse naming both files) — opencode merges both, so a leftover sibling entry is a shadow registration; the bun-run ownership lane is ANCHORED (an exact `gbrain`/`gbrain-*` path segment in some arg — a gbrainy-fork cli path is NOT ours, fail-closed); `parseOpencodeEntryBearer` recovers the harness `--status` token url-matched only; `opencodeRemoteEntryExists` is the stdio-lane ownership arbiter (codexBlockOwnsName analog). Callers hold `acquireBootstrapLock` (config-dir → opencode-dir ordering). Pinned by `test/opencode-json.test.ts` (incl. the fingerprint truth-table suite).
- `src/core/bootstrap/atomic-write.ts` — the ONE atomic config-file writer for bootstrap host surfaces: symlink-target-resolving, mode-inheriting (`freshMode` for new files, `forceMode` for secret-bearing targets), random-suffix tmp + rename, tmp unlinked best-effort when write/chmod/rename throws (ENOSPC/EACCES never strand `.tmp-` litter), and the existsSync→realpathSync race falls back to fresh-path resolution instead of throwing raw ENOENT. hooks.ts (JSON), codex-toml.ts (TOML+EOL), and opencode-json.ts (JSONC) all swap through it; serialization and EOL policy stay caller-side.
-- `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); 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/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()`, parses rollouts via `parseCodexHookTranscript`, and falls back to bounded id-matched discovery when the SessionEnd payload carries `transcript_path: null` — 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/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/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 `codexSessionsDir()` — CODEX_HOME-resolved since the spawner IS codex; 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, id-in-filename match, symlink-reject, 4096 dirent cap — the fallback for `transcript_path: null` 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` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.
+- `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`.
- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.
+- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy: `startResolveIpcServer` connect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.
+- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic.
- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.
- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob. NOTE the deliberate asymmetry with the ambient-writeback TEMPLATE resolver (writeback-config.ts below): this READ/extract default fail-closes UNSET to private; write GUIDANCE treats unset as world (the `remember` verb's own default) because telling agents to write private-by-default on a default install makes their facts invisible to their own later remote sessions.
- **Ambient memory writeback cluster** (opt-in, `memory.auto_writeback = off|salient|all`, default off; guide `docs/guides/ambient-writeback.md`):
@@ -662,7 +670,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- 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).
-- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP).
+- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; sidecar-marked exactly-once). Bounded, fail-soft, never throws; armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `GBRAIN_SWEEP=0` kills it. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created.
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
- `src/core/secret-scan.ts` — pattern scanner for USER workspaces (own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml`, which is a public-repo CI fixture policy); redacted previews only; `redactFindings` is the corpus-write mode.
@@ -673,7 +681,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.
- `src/core/bootstrap/template-repo.ts` + `scripts/generate-template-repo.ts` — deterministic public-template generation (render `--minimal` + placeholder manifest + stamped README); published only by the release workflow after diffing against the vendored tree.
- `scripts/check-bootstrap-tag.sh` / `scripts/check-bootstrap-templates.sh` — CI guards: sanctioned distribution ref only (`latest-stable`; the release job advances it after assets publish) + runbook stamp == VERSION; template↔question-bank token bijection + placeholder-only assertion + offline generator↔vendored byte-diff + runbook-phase↔status.ts consistency. Both skip gracefully when their subjects are absent.
-- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes.
+- `src/core/cycle/synthesize-concepts.ts` concept-quality addendum — eligible groups are processed deterministically by tier, descending atom count, then concept slug so the fixed LLM budget reaches the strongest evidence first regardless of database row order. Every page and phase receipt distinguishes `llm`, intended `deterministic_tier`, `budget_fallback`, and `error_fallback` synthesis modes. The narrative call's output cap is sized from the resolved `models.dream.synthesize` model via `resolveSynthMaxOutputTokens`: 500 for non-thinking models, the gateway's `THINKING_MODEL_MAX_OUTPUT_TOKENS` (no phase-private number — DeepSeek v4 truncates at 8192-class caps) when the gateway's shared `isThinkingModel` matches (name-matched Claude 5 or recipe-declared `thinking_by_default`; unknown providers count as non-thinking), so a tier-`reasoning` thinking model no longer spends the whole budget on reasoning and persists a template stub or truncated chain-of-thought as the concept narrative. Pinned by `test/cycle/synthesize-concepts-token-cap.test.ts`. Right after each concept page write the phase banks concept<->member-atom provenance edges through `engine.addLinksBatch` (`link_source: 'concept-provenance'`; `synthesized_from` concept->atom, `synthesizes` atom->concept; audit site `cycle.synthesize_concepts.provenance`), both endpoints scoped to the cycle's source, so the concept pages are graph-reachable (backlinks, relational recall, doctor `graph_signals_coverage`/`orphans`) even though the prompt forbids enumerating atoms in the body. The dedicated `link_source` keeps reconcile passes from pruning them; `ON CONFLICT DO NOTHING` makes re-runs the backfill; a failed or zero-row edge write lands in `link_warnings[]` (phase `warn`) — NOT in `failures[]`, which means "LLM-failed → template fallback" downstream and drives the rollup's `halt_delta`/`round_completed_delta` — and never aborts the page write. Atom discovery (the `type = 'atom'` scan) is scoped to the cycle source (`opts.sourceId ?? 'default'`) so same-slug atoms from other sources are never grouped into this source's concepts. Pinned by the `#4589` describe in `test/cycle/extract-atoms-synthesize-concepts.test.ts` and `test/cycle/synthesize-concepts-source-scope.test.ts`.
## Google connector + open-loop engine (key files cluster)
diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.md
index df298d8c9a..8a5f495ca4 100644
--- a/docs/architecture/brains-and-sources.md
+++ b/docs/architecture/brains-and-sources.md
@@ -209,6 +209,15 @@ ARRAY of readable sources that takes precedence over the scalar
operations layer). Local CLI callers never set it; the scalar chain above
is the whole story for them.
+One guard on tier 2 for the MCP stdio lane: a harness-launched `gbrain serve`
+checks a well-formed `GBRAIN_SOURCE` against the `sources` table at startup
+and exits with the offending value and the fix when it names no active
+(non-archived) source, instead of serving a scope that holds zero pages while
+every health check stays green. Unset, `__all__`, and malformed values keep
+their normal handling, and a transient database error never blocks startup.
+The CLI env tier fails the same way (`assertSourceExists` in
+`src/core/source-resolver.ts`).
+
---
## For agents reading this
@@ -266,6 +275,31 @@ write ops are local-only. Retrieval-side union — `get_links` /
by the `entity_identity.union` config key (default off) and never widens a
federated caller's source grant.
+## Cross-source link edges
+
+Wikilink and markdown-link edges stay inside one source by default. When a
+page in source A links a target that exists only in source B (typically via
+`link_resolution.global_basename`), the edge is NOT written; instead the drop
+is counted so graph sparsity is observable — `gbrain extract links --source db`
+and `gbrain extract --stale` print `Skipped N cross-source candidate(s)` (JSON:
+`skipped_cross_source`), and the serve sweep records it as `cross_source_link`
+in its skip ledger.
+
+To write those edges, opt in:
+
+```
+gbrain config set link_resolution.cross_source true # or env GBRAIN_LINK_RESOLUTION_CROSS_SOURCE=1
+gbrain extract links --source db # re-extract once; --stale will not revisit stamped pages
+```
+
+Without the flag, an isolated (`federated=false`) source only writes edges
+whose both endpoints live in that source; a federated source may also link
+into the configured default source (`sources.default`). With the flag on, a
+target that exists only in other sources resolves to the lexicographically
+smallest source id, so repeated extracts converge on the same row. The read
+side is unchanged: a federated caller's source grant still scopes every link
+read.
+
## What confines remote callers (and what does not)
When a brain is served to remote agents (HTTP MCP, stdio MCP treated as
diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.md
index 30464d7af4..8e4c617134 100644
--- a/docs/guides/cron-schedule.md
+++ b/docs/guides/cron-schedule.md
@@ -198,7 +198,9 @@ Above the triage cascade sit the execution dials:
backfilled at phase end by a bounded pass over just the pages the phase
wrote — never a source-wide sweep). A response that fails any check automatically
falls back to the classic agentic loop **in the same job** — no lost work,
- no resubmission. Typical effect: 10+ provider round-trips per transcript
+ no resubmission. The oneshot attempt and its fallback calls are both paid
+ provider work and both are included in synthesis token/spend telemetry.
+ Typical effect: 10+ provider round-trips per transcript
(up to the 16-turn default cap, more on raised `max_turns`) → 1. Revert
dial: `gbrain config set dream.synthesize.mode agentic`.
- `dream.synthesize.link_manifest` (default on) — the zero-embed
@@ -214,7 +216,9 @@ Above the triage cascade sit the execution dials:
Reading the phase report (`details.synthesis`): `mode`, `oneshot_jobs` /
`fallback_jobs` / `agentic_jobs` + a `fallback_reasons` histogram (a rising
fallback rate means the model is failing the output contract — check the
-top reason before considering the agentic revert), `queue_wait_ms_p50/p95`
+top reason before considering the agentic revert; `length` includes malformed
+responses whose output usage reached the requested output cap even when the
+provider stop reason was ambiguous), `queue_wait_ms_p50/p95`
and `child_runtime_ms_p50/p95` (a slow-but-healthy drain is visible instead
of indistinguishable from a stuck one), and `dead_jobs`/`degraded`. A run
with any non-completed child does NOT stamp the cooldown, so the next
diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.md
index 47b9f987c8..2fb4895a24 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -155,6 +155,25 @@ consecutive failures instead of wedging the sync forever;
`gbrain sync --source <id> --full` retries skipped threads with a fresh
ledger.
+### Rate limits during backfill
+
+A large mailbox backfilling a wide `--history-days` window can trip Gmail's
+per-user rate limit in bursts — Google answers with HTTP 403
+(`rateLimitExceeded` / `userRateLimitExceeded`) or 429, and it clears on its
+own within seconds to low minutes. The client retries a rate-limited request
+patiently — 6 attempts by default, exponential backoff with jitter capped at
+60s, honoring `Retry-After` when Google sends one — before finally giving up
+and reporting `rate_limited`. That budget is deliberately much larger than
+the 2-attempt budget used for other retryable failures (like a 401 needing a
+token refresh): giving up too early used to mean a thread that would have
+succeeded a few seconds later was instead skipped for the rest of the sync.
+
+Even when a thread's retry budget IS exhausted, a rate-limit failure is never
+counted toward the poison-skip threshold — unlike a genuine per-thread
+failure (a malformed message, a permissions edge case), a rate limit says
+nothing about that specific thread, so the sweep keeps retrying it on every
+future run instead of silently giving up on it.
+
## Other ways to reach Google (no gbrain OAuth)
If your stack already holds Google access another way — a Google CLI with its
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 8a64c06bf7..b33cbfb9f3 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -69,7 +69,7 @@ The doctor distinguishes two repair paths:
- **Cost-sensitive, English-only**: Ollama (free, local) or Voyage (paid, best quality per dollar).
- **Quality-first**: Voyage `voyage-4-large` (1024-2048 dims, ~3-4× more dense tokens than OpenAI tiktoken).
- **Code-heavy brain (gstack per-worktree, source repos)**: Voyage `voyage-code-3` (1024 default; supports 256/512/1024/2048), or `voyage-code-4` (hosted, flexible dims, $0.12/M). Tuned on programming languages. Voyage publishes head-to-head numbers showing it outperforms their general flagships on code retrieval ([voyageai.com/blog](https://voyageai.com/blog)). For gstack's per-worktree pglite-backed code brain, this is the right default — see Topology 3 in `docs/architecture/topologies.md`.
-- **Reranking pair**: Voyage `rerank-2.5` ($0.05/M; `rerank-2.5-lite` at $0.02/M for cost-sensitive setups) is the mode-bundle default and rides the same `VOYAGE_API_KEY` as embeddings; without the key search fails open in fusion order and `gbrain search modes` says so. ZeroEntropy `zerank-2` is deprecated (hosted API ends 2026-09-04); an explicitly configured `zeroentropyai:zerank-*` short-circuits past that date (see [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)).
+- **Reranking pair**: Voyage `rerank-2.5` ($0.05/M; `rerank-2.5-lite` at $0.02/M for cost-sensitive setups) is the mode-bundle default and rides the same `VOYAGE_API_KEY` as embeddings. Voyage's preview `rerank-3` / `rerank-3-lite` pair is also allowlisted — opt in with `gbrain config set search.reranker.model voyage:rerank-3` (the default stays on `rerank-2.5` so upgrades never move you); without the key search fails open in fusion order and `gbrain search modes` says so. ZeroEntropy `zerank-2` is deprecated (hosted API ends 2026-09-04); an explicitly configured `zeroentropyai:zerank-*` short-circuits past that date (see [`docs/ai-providers/zeroentropy.md`](../ai-providers/zeroentropy.md)).
- **Local reranking (no API spend)**: `llama-server-reranker` recipe — point gbrain at your own `llama-server --reranking` instance running Qwen3-Reranker or self-hosted ZeroEntropy weights. Same `gateway.rerank()` seam, $0 per call. Walkthrough in [`docs/ai-providers/llama-server-reranker.md`](../ai-providers/llama-server-reranker.md).
- **One key for many hosted models**: OpenRouter. Set `OPENROUTER_API_KEY` and use `openrouter:<provider>/<model>` for chat against GPT-5.2, Claude 4.x, Gemini 3, DeepSeek, and dozens more without juggling per-provider keys. Embedding catalog includes OpenAI, Google, Qwen, BGE-M3.
- **Enterprise compliance**: Azure OpenAI (data residency + private endpoints) or self-hosted via llama-server / Ollama.
@@ -91,7 +91,16 @@ Optional `OPENAI_BASE_URL` — point the native OpenAI provider at an OpenAI-com
Voyage 4 family shares an embedding space across all variants, so you can index with `voyage-4` and later point the query model at `voyage-4-large` or `voyage-4-lite` without reindexing. Dims: 256, 512, 1024, 2048. **2048 exceeds pgvector's HNSW cap of 2000** — those brains fall back to exact vector scans (still correct, just slower).
-Voyage also serves the hosted rerankers `rerank-2.5` ($0.05/M) and `rerank-2.5-lite` ($0.02/M) at `POST /v1/rerank` (prices verified 2026-08-15) — the mode-bundle reranker default, so no config row is needed (an explicit `search.reranker.model` equal to it is exactly what `gbrain doctor`'s `search_mode` check calls redundant).
+Voyage also serves four hosted rerankers at `POST /v1/rerank` — `rerank-2.5` ($0.05/M) and `rerank-2.5-lite` ($0.02/M), plus the preview `rerank-3` ($0.05/M) and `rerank-3-lite` ($0.02/M) (2.5 pair verified 2026-08-15, rerank-3 pair 2026-09-06). All four share one request/response wire, so switching is a config change and nothing else.
+
+`rerank-2.5` is the mode-bundle reranker default, so no config row is needed for it (an explicit `search.reranker.model` equal to it is exactly what `gbrain doctor`'s `search_mode` check calls redundant). Moving to the preview generation is one command:
+
+```bash
+gbrain config set search.reranker.model voyage:rerank-3
+gbrain models doctor # green `reranker_config voyage:rerank-3` is the whole test
+```
+
+**Say to your agent:** *"switch my reranker to voyage rerank-3"* — *"check my model config"* (your agent runs `gbrain config set search.reranker.model voyage:rerank-3` then `gbrain models doctor`).
**For brains that index source code** (gstack's per-worktree pglite-backed code brain — see Topology 3 in `docs/architecture/topologies.md`), prefer `voyage-code-3` over `voyage-4-large`. Voyage tunes it on programming languages and publishes head-to-head numbers vs their general flagships on code retrieval. Configure at install time:
diff --git a/docs/mcp/CHATGPT.md b/docs/mcp/CHATGPT.md
index d4ad0ccabd..d983aaadd7 100644
--- a/docs/mcp/CHATGPT.md
+++ b/docs/mcp/CHATGPT.md
@@ -18,7 +18,8 @@ Follow [DEPLOY.md — OAuth 2.1 Setup](DEPLOY.md#oauth-21-setup) to start
`gbrain serve --http`, save the admin bootstrap token, and expose the server
at a public HTTPS URL (e.g. `https://your-brain.ngrok.app`). ChatGPT's
connector auto-discovers the spec-compliant endpoint at
-`/.well-known/oauth-authorization-server`.
+`/.well-known/oauth-authorization-server` and the `/mcp` protected-resource
+metadata at `/.well-known/oauth-protected-resource/mcp`.
### 2. Register a ChatGPT client
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index fd2be893c4..53395f078a 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -62,7 +62,9 @@ Codex; route the brain axis with `GBRAIN_BRAIN_ID` (env only — there is no
config default for the brain axis). `--source-guard` makes this fail-closed:
when a brain has more than one source to choose from and no binding, write
and admin operations error with an actionable message until a source is bound
-(the user-global stdio serve binds the source from `GBRAIN_SOURCE`, not a flag); a sole
+(the user-global stdio serve binds the source from `GBRAIN_SOURCE`, not a flag,
+and exits at startup when that value names a source that is missing or
+archived); a sole
real source is unambiguous and unaffected, and reads always pass. (Edge case:
a `.gbrain-source` dotfile placed at `$HOME` is an ancestor of the plugin
snapshot dir and would bind every plugin-lane write to it — put source pins
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 6b9a97b3a2..5435c9199a 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -211,7 +211,14 @@ ngrok http 3131 --url your-brain.ngrok.app
Your OAuth issuer URL becomes `https://your-brain.ngrok.app`. The MCP SDK's
router exposes the spec-compliant discovery endpoint at
-`/.well-known/oauth-authorization-server`.
+`/.well-known/oauth-authorization-server`. The protected resource is the
+`/mcp` endpoint itself: its RFC 9728 metadata is served at
+`/.well-known/oauth-protected-resource/mcp` (the bare
+`/.well-known/oauth-protected-resource` root stays as an alias for older
+clients), and every 401 carries `WWW-Authenticate: Bearer
+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.
### 4. Scopes and localOnly
diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.md
index 8bf6161eb3..025ce2d781 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -11,8 +11,12 @@ Two supported shapes, both stdio.
GBrain ships [`openclaw.plugin.json`](../../openclaw.plugin.json) at the repo
root. Installing the bundle plugin registers the MCP server for you — the
-manifest carries an `mcpServers.gbrain` entry (`./bin/gbrain serve`) plus the
-bundled skills — and declares the `gbrain-context` context engine. To route
+manifest carries an `mcpServers.gbrain` entry that runs the bundled
+`.agents/gbrain-launcher serve` (the same launcher the Codex and Claude Code
+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:
```
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index bcf3ba7e64..66f4ed8cf4 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -114,7 +114,10 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.
pages; both present ⇒ both arms run.
- `since`: ISO 8601 date/datetime — filters the FACTS arm only in v1. (The
reference implementation also accepts relative phrases like `"8 hours ago"`
- as a convenience; only ISO 8601 is part of the frozen contract.)
+ as a convenience; only ISO 8601 is part of the frozen contract.) The window
+ is measured on event time (`valid_from`, falling back to `created_at`) and
+ composes with `entity` and `session_id` in the same query, before the
+ per-arm limit. An unparseable value is rejected with `invalid_params`.
- `limit` is a PER-ARM cap (facts and search results each).
- `budget_tokens`: SERVER-side packing — facts pack first (limit-capped
one-liners, so search-arm starvation is bounded), search results take the
diff --git a/llms-full.txt b/llms-full.txt
index c14e6d88e3..bb5f6da8ac 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2256,7 +2256,7 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h
- **Gmail + Calendar + Contacts (native)**: the google source kind syncs threads, events, and contacts through your own OAuth client and runs the open-loop engine on top (`gbrain waiting`). Setup: [`docs/guides/google-connect.md`](docs/guides/google-connect.md); recipes: [`recipes/email-to-brain.md`](recipes/email-to-brain.md), [`recipes/calendar-to-brain.md`](recipes/calendar-to-brain.md).
- **Email + calendar (webhooks)**: webhook handlers that route to brain signals. [`docs/integrations/meeting-webhooks.md`](docs/integrations/meeting-webhooks.md).
- **Embedding providers**: a dozen providers covered — Voyage (default: `voyage-4` @ 1024d), OpenAI, OpenRouter, Google Gemini, Azure OpenAI, MiniMax, Alibaba DashScope, Zhipu, Ollama (local), llama.cpp llama-server (local), LiteLLM proxy, plus ZeroEntropy (deprecated — hosted API ends 2026-09-04). Pricing matrix + decision tree in [`docs/integrations/embedding-providers.md`](docs/integrations/embedding-providers.md).
-- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
+- **Rerankers**: Voyage `rerank-2.5` hosted (the default; reranking is on in `balanced` and `tokenmax` modes, same `VOYAGE_API_KEY` as embeddings; the preview `rerank-3` / `rerank-3-lite` are selectable with `gbrain config set search.reranker.model voyage:rerank-3`), ZeroEntropy `zerank-2` (deprecated — hosted API ends 2026-09-04; an explicit config short-circuits past that date), plus the `llama-server-reranker` recipe for fully-local cross-encoder rerank via llama.cpp — runs Qwen3-Reranker or self-hosted zerank weights against the same `gateway.rerank()` seam. Setup walkthrough in [`docs/ai-providers/llama-server-reranker.md`](docs/ai-providers/llama-server-reranker.md).
- **Credential vault + gateway**: `gbrain creds` manages OAuth and API credentials in a local vault ([`recipes/credential-gateway.md`](recipes/credential-gateway.md)); agent-side vault-aware secret distribution: [`docs/integrations/credential-gateway.md`](docs/integrations/credential-gateway.md).
- **MCP clients**: every major MCP client is supported. [`docs/mcp/`](docs/mcp/) per-client setup.
- **Memorable (procedural memory)**: optional, off by default. Your brain remembers *what* happened; Memorable makes your agent remember *how* — finished sessions become replayable procedures stored on your machine (in a standalone local store, or inside your brain database if you opt in), recalled when a similar task comes back. See the section below, and [`docs/memorable-agents.md`](docs/memorable-agents.md) for the agent-facing detail.
@@ -2814,7 +2814,9 @@ Reports (JSON `schema_version: 1`): the effective engine vs the config-file
engine (they can differ under a transient env URL), `db_url_source`, an
env-shadow note when a cwd-.env `DATABASE_URL` is being excluded by the
cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loaded
-from the working directory's `.env`; with the precedence note when both `GBRAIN_DATABASE_URL` and
+from the working directory's `.env` family: `.env`, `.env.local`, and the
+`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,
+`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and
`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a
zero-round-trip pooler block (Supabase pooler detection, prepared-statement
resolution, pool sizes, direct/session-pooler derivability). `--brain <id>`
@@ -3876,7 +3878,9 @@ Above the triage cascade sit the execution dials:
backfilled at phase end by a bounded pass over just the pages the phase
wrote — never a source-wide sweep). A response that fails any check automatically
falls back to the classic agentic loop **in the same job** — no lost work,
- no resubmission. Typical effect: 10+ provider round-trips per transcript
+ no resubmission. The oneshot attempt and its fallback calls are both paid
+ provider work and both are included in synthesis token/spend telemetry.
+ Typical effect: 10+ provider round-trips per transcript
(up to the 16-turn default cap, more on raised `max_turns`) → 1. Revert
dial: `gbrain config set dream.synthesize.mode agentic`.
- `dream.synthesize.link_manifest` (default on) — the zero-embed
@@ -3892,7 +3896,9 @@ Above the triage cascade sit the execution dials:
Reading the phase report (`details.synthesis`): `mode`, `oneshot_jobs` /
`fallback_jobs` / `agentic_jobs` + a `fallback_reasons` histogram (a rising
fallback rate means the model is failing the output contract — check the
-top reason before considering the agentic revert), `queue_wait_ms_p50/p95`
+top reason before considering the agentic revert; `length` includes malformed
+responses whose output usage reached the requested output cap even when the
+provider stop reason was ambiguous), `queue_wait_ms_p50/p95`
and `child_runtime_ms_p50/p95` (a slow-but-healthy drain is visible instead
of indistinguishable from a stuck one), and `dead_jobs`/`degraded`. A run
with any non-completed child does NOT stamp the cooldown, so the next
@@ -5110,7 +5116,14 @@ ngrok http 3131 --url your-brain.ngrok.app
Your OAuth issuer URL becomes `https://your-brain.ngrok.app`. The MCP SDK's
router exposes the spec-compliant discovery endpoint at
-`/.well-known/oauth-authorization-server`.
+`/.well-known/oauth-authorization-server`. The protected resource is the
+`/mcp` endpoint itself: its RFC 9728 metadata is served at
+`/.well-known/oauth-protected-resource/mcp` (the bare
+`/.well-known/oauth-protected-resource` root stays as an alias for older
+clients), and every 401 carries `WWW-Authenticate: Bearer
+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.
### 4. Scopes and localOnly
@@ -5431,7 +5444,10 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.
pages; both present ⇒ both arms run.
- `since`: ISO 8601 date/datetime — filters the FACTS arm only in v1. (The
reference implementation also accepts relative phrases like `"8 hours ago"`
- as a convenience; only ISO 8601 is part of the frozen contract.)
+ as a convenience; only ISO 8601 is part of the frozen contract.) The window
+ is measured on event time (`valid_from`, falling back to `created_at`) and
+ composes with `entity` and `session_id` in the same query, before the
+ per-arm limit. An unparseable value is rejected with `invalid_params`.
- `limit` is a PER-ARM cap (facts and search results each).
- `budget_tokens`: SERVER-side packing — facts pack first (limit-capped
one-liners, so search-arm starvation is bounded), search results take the
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index ec4e02e1c6..bceaf8fa17 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.48.4.0",
+ "version": "0.48.5.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
@@ -24,7 +24,7 @@
},
"mcpServers": {
"gbrain": {
- "command": "./bin/gbrain",
+ "command": "./.agents/gbrain-launcher",
"args": [
"serve"
]
diff --git a/package.json b/package.json
index 107f8664b5..55369db108 100644
--- a/package.json
+++ b/package.json
@@ -174,7 +174,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.48.4.0",
+ "version": "0.48.5.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "3.1.6",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 186436b0ad..490edf94f3 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.48.4.0",
+ "version": "0.48.5.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 a2f1892bf3..710ed90064 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.48.4.0",
+ "version": "0.48.5.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 f6e3d495a6..84cdbac229 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.48.4.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.48.5.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/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
index 19e1e3526e..afcc57ddc8 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md
@@ -84,7 +84,8 @@ wins over the auto-route. Archived sources are excluded from the count.
CLI commands honoring this chain: `gbrain sync`, `gbrain import`,
`gbrain search`, `gbrain extract` (via `--source-id <id>` since
`--source` is the fs|db data-source axis), `gbrain graph-query`
-(via `--include-foreign` for cross-source traversal).
+(`--source` scopes the walk; `--include-foreign` widens it to every
+source).
**Trust boundary (v0.34.1.0):** the resolver is CLI-layer only.
Operations.ts handlers do NOT read `.gbrain-source` or
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 7538fbed4a..3efc4cd08c 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.48.4.0",
+ "version": "0.48.5.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 c6bcb3974e..8e9f3baab7 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.48.4.0",
+ "version": "0.48.5.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 934e95b226..9f259e448e 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.48.4.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.48.5.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/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
index 19e1e3526e..afcc57ddc8 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md
@@ -84,7 +84,8 @@ wins over the auto-route. Archived sources are excluded from the count.
CLI commands honoring this chain: `gbrain sync`, `gbrain import`,
`gbrain search`, `gbrain extract` (via `--source-id <id>` since
`--source` is the fs|db data-source axis), `gbrain graph-query`
-(via `--include-foreign` for cross-source traversal).
+(`--source` scopes the walk; `--include-foreign` widens it to every
+source).
**Trust boundary (v0.34.1.0):** the resolver is CLI-layer only.
Operations.ts handlers do NOT read `.gbrain-source` or
diff --git a/plugin/README.md b/plugin/README.md
index a49d96bb30..480c88af11 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.48.4.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.48.5.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/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.md
index 19e1e3526e..afcc57ddc8 100644
--- a/plugin/skills/conventions/brain-routing.md
+++ b/plugin/skills/conventions/brain-routing.md
@@ -84,7 +84,8 @@ wins over the auto-route. Archived sources are excluded from the count.
CLI commands honoring this chain: `gbrain sync`, `gbrain import`,
`gbrain search`, `gbrain extract` (via `--source-id <id>` since
`--source` is the fs|db data-source axis), `gbrain graph-query`
-(via `--include-foreign` for cross-source traversal).
+(`--source` scopes the walk; `--include-foreign` widens it to every
+source).
**Trust boundary (v0.34.1.0):** the resolver is CLI-layer only.
Operations.ts handlers do NOT read `.gbrain-source` or
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index 0b57d652ad..91e53468d3 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -391,7 +391,8 @@ if [ -f .git ]; then
fi
echo "[ci-local] Running checks inside runner container..."
-docker compose -f "$COMPOSE_FILE" run --rm "${EXTRA_MOUNTS[@]}" runner bash -c "$INNER_CMD"
+# Bash 3.2 treats an empty array as unset under nounset; preserve zero argv.
+docker compose -f "$COMPOSE_FILE" run --rm ${EXTRA_MOUNTS[@]+"${EXTRA_MOUNTS[@]}"} runner bash -c "$INNER_CMD"
echo ""
echo "[ci-local] All checks passed."
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 61f39f4873..5e774c08ee 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -4,39 +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 4050 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
-src/commands/autopilot.ts 2648 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
+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/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 2100 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)
-src/commands/extract.ts 2494 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)
+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 3151 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)
-src/commands/serve-http.ts 3379 ratchet 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
-src/core/ai/gateway.ts 4779 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)
-src/commands/sync.ts 5801 ratchet 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)
-src/core/cycle.ts 3203 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
-src/core/cycle/synthesize.ts 3151 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
-src/core/engine.ts 2638 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
-src/core/import-file.ts 2250 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)
+src/commands/serve-http.ts 3399 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
+src/core/ai/gateway.ts 4823 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)
+src/commands/sync.ts 5870 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
+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 2247 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)
src/core/migrate.ts 687 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)
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 6089 ratchet 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
-src/core/postgres-engine.ts 5568 ratchet 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
+src/core/pglite-engine.ts 6097 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)
+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 2095 ratchet 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)
+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/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease
src/commands/init.ts 2048 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
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 1892 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
-src/commands/bootstrap.ts 2112 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
+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 1560 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave
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 1728 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
+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/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 1575 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
-src/core/config.ts 1772 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)
-src/core/bootstrap/harness.ts 2300 ratchet +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
+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/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard)
-src/core/ops/pages.ts 1472 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)
-src/core/search/mode.ts 1746 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)
+src/core/ops/pages.ts 1480 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
+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)
diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.sh
index ba4376eb9b..504da8cc62 100755
--- a/scripts/run-unit-parallel.sh
+++ b/scripts/run-unit-parallel.sh
@@ -227,6 +227,66 @@ fi
# so $? is recoverable per-shard (we never trust `wait`'s aggregate value).
# ──────────────────────────────────────────────────────────────────────────
SHARD_PIDS=()
+HB_PID=""
+CLEANUP_STARTED=0
+
+# An operator interrupt must stop the work, not only this wrapper. The shard
+# subshells are async children of a non-interactive bash, so they (and their
+# gtimeout/bun descendants) inherit SIGINT ignored: without a trap, bash exits
+# while gtimeout/bun stay alive under launchd and can retain gigabytes until
+# the shard cap fires. Only armed while the shards are live (disarmed on the
+# normal path once they are reaped). TERM gives cooperative children a moment
+# to exit, then KILL guarantees a TERM-resistant test cannot outlive the
+# cancelled suite.
+cleanup_children() {
+ local exit_code="${1:-0}"
+ [ "$CLEANUP_STARTED" = "1" ] && return
+ CLEANUP_STARTED=1
+
+ if [ -n "$HB_PID" ]; then
+ pkill -P "$HB_PID" 2>/dev/null || true
+ kill "$HB_PID" 2>/dev/null || true
+ fi
+
+ local pid descendants=""
+ collect_descendants() {
+ local parent="$1" child
+ for child in $(pgrep -P "$parent" 2>/dev/null); do
+ collect_descendants "$child"
+ printf '%s\n' "$child"
+ done
+ }
+
+ # Snapshot descendants BEFORE the subshell is TERMed: once it dies its
+ # gtimeout/bun children reparent to launchd and pgrep -P can't find them.
+ # The subshells are not process-group leaders here, so signal by PID.
+ for pid in ${SHARD_PIDS[@]+"${SHARD_PIDS[@]}"}; do
+ descendants="$descendants $(collect_descendants "$pid")"
+ kill -TERM "$pid" 2>/dev/null || true
+ done
+ for pid in $descendants; do kill -TERM "$pid" 2>/dev/null || true; done
+ [ "${#SHARD_PIDS[@]}" -gt 0 ] && sleep 1
+ for pid in $descendants; do kill -KILL "$pid" 2>/dev/null || true; done
+ for pid in ${SHARD_PIDS[@]+"${SHARD_PIDS[@]}"}; do
+ kill -KILL "$pid" 2>/dev/null || true
+ wait "$pid" 2>/dev/null || true
+ done
+ [ -n "$HB_PID" ] && wait "$HB_PID" 2>/dev/null || true
+
+ return "$exit_code"
+}
+
+handle_interrupt() {
+ local exit_code="$1"
+ trap - INT TERM EXIT
+ cleanup_children "$exit_code" || true
+ exit "$exit_code"
+}
+
+trap 'handle_interrupt 130' INT
+trap 'handle_interrupt 143' TERM
+trap 'cleanup_children $?' EXIT
+
for i in $(seq 1 "$N"); do
(
SHARD_LOG="$LOG_DIR/shard-$i.log"
@@ -436,15 +496,16 @@ HB_PID=$!
# process cleanup" at end-of-job reports them as (unnamed) test failures.
# Seen on the garrytan/port-pr-1406 PR, 2 CI runs in a row, 6 orphans
# matching the 6 invocations in test/scripts/run-unit-parallel.test.ts.
-trap 'pkill -P "$HB_PID" 2>/dev/null; kill "$HB_PID" 2>/dev/null; wait "$HB_PID" 2>/dev/null' EXIT
-
# Wait for every shard. Don't care about wait's exit code.
for pid in "${SHARD_PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
pkill -P "$HB_PID" 2>/dev/null
kill "$HB_PID" 2>/dev/null
wait "$HB_PID" 2>/dev/null
-trap - EXIT
+# Every shard is reaped: disarm the interrupt handlers too, so a later
+# Ctrl-C during the foreground serial/rescue phases can't run
+# cleanup_children against SHARD_PIDS that may have been reused.
+trap - INT TERM EXIT
# ──────────────────────────────────────────────────────────────────────────
# Aggregate failures (single writer; serial; never concurrent).
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index be0964810e..a0236788c8 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -14,7 +14,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 13 readFileSync
+test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 15 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
@@ -53,10 +53,11 @@ test/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSync
test/check-update.test.ts check-update CLI 3 bun-file
test/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSync
test/chronicle-extract.test.ts runChronicleExtract 9 readFileSync
+test/ci-local-empty-mounts.test.ts (file-level) 2 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — abort + error envelopes 13 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — context isolation 2 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip 4 readFileSync
-test/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 11 readFileSync
+test/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 17 readFileSync
test/claude-cli-recipe.test.ts claude-cli recipe registration 2 readFileSync
test/cli-force-exit-teardown-arming.test.ts cli.ts — disconnect hard-deadline armed at teardown entry, not before the op body 1 readFileSync
test/cli.test.ts BigInt-safe output normalization (#2450) 5 readFileSync
@@ -94,6 +95,7 @@ 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/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
test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helper
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 23d6fc7fc5..125f469709 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -1,1201 +1,1706 @@
{
- "test/abort-check.test.ts": 2,
- "test/active-pack-wiring.test.ts": 4,
- "test/admin-agents-spend.test.ts": 3155,
- "test/admin-sse-eventsource.test.ts": 3,
- "test/admin-sse-handshake.test.ts": 104,
- "test/advisor-apply.test.ts": 4,
- "test/advisor-core.test.ts": 18,
- "test/advisor-mcp-client-fit.test.ts": 488,
- "test/advisor-op-gate.test.ts": 49,
- "test/advisor-ranking-eval.test.ts": 0,
- "test/agent-cli.test.ts": 487,
- "test/agent-runner.test.ts": 20,
- "test/ai-probes-models.test.ts": 12,
- "test/ai/adaptive-embed-batch.test.ts": 21,
- "test/ai/anthropic-key.test.ts": 6,
- "test/ai/build-gateway-config.test.ts": 834,
- "test/ai/capabilities.test.ts": 4,
- "test/ai/config-no-env-mutation.test.ts": 4,
- "test/ai/deepseek-reasoning-content.test.ts": 4,
- "test/ai/diagnose-embedding-dims.test.ts": 2,
- "test/ai/dims-openai.test.ts": 10,
- "test/ai/dims-qwen3-native.test.ts": 4,
- "test/ai/dims-zeroentropy.test.ts": 4,
- "test/ai/embedQuery.test.ts": 9,
- "test/ai/gateway-chat.test.ts": 5,
- "test/ai/gateway-openai-prompt-cache-key.test.ts": 10,
- "test/ai/gateway-probe-chat-model.test.ts": 4,
- "test/ai/gateway-reset-baseline.test.ts": 4,
- "test/ai/gateway-tool-loop.test.ts": 7,
- "test/ai/gateway-toolcall-pairing.test.ts": 21,
- "test/ai/gateway-tools-schema.test.ts": 22,
- "test/ai/gateway.test.ts": 824,
- "test/ai/model-resolver-slash.test.ts": 2,
- "test/ai/recipe-azure-openai.test.ts": 10,
- "test/ai/recipe-dashscope-rerank.test.ts": 5,
- "test/ai/recipe-dashscope.test.ts": 14,
- "test/ai/recipe-llama-server-reranker.test.ts": 3,
- "test/ai/recipe-llama-server.test.ts": 5,
- "test/ai/recipe-minimax.test.ts": 1,
- "test/ai/recipe-mistral.test.ts": 2,
- "test/ai/recipe-moonshot.test.ts": 3,
- "test/ai/recipe-nvidia.test.ts": 3,
- "test/ai/recipe-ollama-dims.test.ts": 5,
- "test/ai/recipe-openrouter.test.ts": 4,
- "test/ai/recipe-perplexity.test.ts": 19,
- "test/ai/recipe-zhipu.test.ts": 3,
- "test/ai/recipes-existing-regression.test.ts": 5,
- "test/ai/rerank.test.ts": 21,
- "test/ai/resolve-native-base-url.test.ts": 1,
- "test/ai/schema-templating.test.ts": 6,
- "test/ai/silent-drop-regression.test.ts": 3,
- "test/ai/voyage-code-3-recipe.test.ts": 3,
- "test/ai/zeroentropy-compat-fetch.test.ts": 8,
- "test/all-sources-sentinel.test.ts": 24,
- "test/ambient-recall-cli.test.ts": 7497,
- "test/ambient-recall-templates.test.ts": 4,
- "test/ambient-recall.test.ts": 5116,
- "test/anomalies.test.ts": 11,
- "test/anthropic-model-ids.test.ts": 1,
- "test/anthropic-pricing.test.ts": 1,
- "test/apply-migrations.test.ts": 13,
- "test/archive-crawler-config.test.ts": 9,
- "test/artifact-abstraction.test.ts": 109,
- "test/asymmetric-encoding-contract.test.ts": 3,
- "test/audit/audit-dir-preload.test.ts": 0,
- "test/audit/audit-writer.test.ts": 10,
- "test/audit/batch-retry-audit.test.ts": 11,
- "test/audit/batch-retry-redaction.test.ts": 6,
- "test/audit/content-sanity-audit.test.ts": 9,
- "test/audit/lock-renewal-audit.test.ts": 8,
- "test/audit/pool-recovery-audit.test.ts": 17,
- "test/audit/redact-connection-info.test.ts": 7,
- "test/auth-create-args.test.ts": 10,
- "test/auth-register-client-args.test.ts": 9,
- "test/auto-think-phase.test.ts": 542,
- "test/autopilot-auto-drain-wiring.test.ts": 4,
- "test/autopilot-cycle-failure-classification.test.ts": 10,
- "test/autopilot-cycle-handler.test.ts": 478,
- "test/autopilot-cycle-source-checkout.test.ts": 680,
- "test/autopilot-drain-deadlock-2050.test.ts": 2945,
- "test/autopilot-failure-cooldown.test.ts": 968,
- "test/autopilot-fanout-wiring.test.ts": 8,
- "test/autopilot-fanout.test.ts": 32,
- "test/autopilot-global-maintenance.test.ts": 1805,
- "test/autopilot-install.test.ts": 12,
- "test/autopilot-lock-path.test.ts": 2,
- "test/autopilot-lock.test.ts": 10,
- "test/autopilot-nightly-probe-wiring.test.ts": 2,
- "test/autopilot-parser-probe-wiring.test.ts": 27,
- "test/autopilot-pause-marker.test.ts": 24,
- "test/autopilot-reconnect-classifier.test.ts": 22,
- "test/autopilot-resolve-cli.test.ts": 33,
- "test/autopilot-self-disable-and-status.test.ts": 28,
- "test/autopilot-self-upgrade.test.ts": 16,
- "test/autopilot-shutdown-engine-close.test.ts": 5,
- "test/autopilot-supervisor-wiring.test.ts": 16,
- "test/backfill-base.test.ts": 8,
- "test/backlink-count-mention-filter.test.ts": 2016,
- "test/backlinks-job-default.test.ts": 4,
- "test/backlinks.test.ts": 23,
- "test/backoff.test.ts": 1,
- "test/backpressure-audit-read.test.ts": 8,
- "test/balanced-reranker-default.test.ts": 5,
- "test/batch-projection.test.ts": 6,
- "test/bench-publish.test.ts": 18,
- "test/bench/baseline-file.test.ts": 4,
- "test/bench/correctness-gate.test.ts": 4,
- "test/bench/qrels-file.test.ts": 3,
- "test/binary-self-update.test.ts": 6,
- "test/book-mirror.test.ts": 652,
- "test/bootstrap-codex-door.test.ts": 24,
- "test/bootstrap-doctor-checks.test.ts": 3055,
- "test/bootstrap-harness-writers.test.ts": 27,
- "test/bootstrap-hooks-writers.test.ts": 23,
- "test/bootstrap-lock.test.ts": 11,
- "test/bootstrap-render.test.ts": 84,
- "test/bootstrap-repo.test.ts": 49,
- "test/bootstrap.test.ts": 19209,
- "test/brain-resolver.test.ts": 17,
- "test/brain-score-breakdown.test.ts": 2033,
- "test/brain-score-recommendations.test.ts": 8,
- "test/brain-writer-partial-scan.test.ts": 2031,
- "test/brain-writer-walk-prune.test.ts": 37,
- "test/brain-writer.test.ts": 966,
- "test/brainbench-adapters.test.ts": 965,
- "test/brainbench-continuity.test.ts": 1558,
- "test/brainbench-fixtures.test.ts": 29,
- "test/brainbench-generator.test.ts": 20,
- "test/brainbench-metrics.test.ts": 7,
- "test/brainbench-scoreboard.test.ts": 10,
- "test/brainbench-writeback.test.ts": 2032,
- "test/brainstorm-timeout.test.ts": 4,
- "test/brainstorm/cost-guardrails.test.ts": 39,
- "test/brainstorm/distance.test.ts": 1,
- "test/brainstorm/eval-brainstorm.test.ts": 4,
- "test/brainstorm/judges-maxtokens.test.ts": 5,
- "test/brainstorm/lsd-mode-skip.test.ts": 24,
- "test/brainstorm/model-config.test.ts": 6,
- "test/brainstorm/save.test.ts": 3236,
- "test/budget-meter.test.ts": 11,
- "test/budget-tracker.test.ts": 433,
- "test/budget/free-local-chat-pricing.test.ts": 1,
- "test/build-llms.test.ts": 15,
- "test/by-mention.test.ts": 487,
- "test/cache-scope-key.test.ts": 1,
- "test/calibration-cli.test.ts": 12,
- "test/calibration-profile.test.ts": 9,
- "test/candidate-audit.test.ts": 20,
- "test/capability.test.ts": 3,
- "test/capture-build-content.test.ts": 21,
- "test/capture-runcapture.test.ts": 4,
- "test/cathedral-ii-brainbench.test.ts": 650,
- "test/check-bootstrap-guards.test.ts": 1307,
- "test/check-jsonb-params.test.ts": 60,
- "test/check-resolvable-cli.test.ts": 4394,
- "test/check-resolvable-openclaw-compact.test.ts": 15,
- "test/check-resolvable.test.ts": 172,
- "test/check-system-of-record.test.ts": 57,
- "test/check-update.test.ts": 1248,
- "test/child-worker-supervisor.test.ts": 1953,
- "test/chronicle-advisor.test.ts": 384,
- "test/chronicle-backfill.test.ts": 328,
- "test/chronicle-capture.test.ts": 162,
- "test/chronicle-context.test.ts": 345,
- "test/chronicle-delight.test.ts": 376,
- "test/chronicle-doctor.test.ts": 361,
- "test/chronicle-extract.test.ts": 497,
- "test/chronicle-ontology-ops.test.ts": 2110,
- "test/chronicle-ontology.test.ts": 426,
- "test/chronicle-search-boost.test.ts": 5,
- "test/chronicle-timeline-reads.test.ts": 393,
- "test/chunk-grain-fts.test.ts": 736,
- "test/chunker-timeout.test.ts": 23,
- "test/chunker-version-gate.test.ts": 2,
- "test/chunker-version-insert-default.test.ts": 362,
- "test/chunkers/cap-oversized-cjk.test.ts": 210,
- "test/chunkers/code.test.ts": 90,
- "test/chunkers/embed-estimate-home.test.ts": 680,
- "test/chunkers/recursive.test.ts": 396,
- "test/cjk.test.ts": 4,
- "test/claude-cli-recipe.test.ts": 107,
- "test/claude-code-jsonl.test.ts": 10,
- "test/claw-test-cli.test.ts": 49,
- "test/cli-args.test.ts": 19,
- "test/cli-bigint-normalize.test.ts": 16,
- "test/cli-concept-nudge.test.ts": 1,
- "test/cli-dispatch-thin-client.test.ts": 9327,
- "test/cli-dream-engine-warn.test.ts": 4153,
- "test/cli-empty-retrieval-render.test.ts": 3,
- "test/cli-exit-verdict-pin.test.ts": 30,
- "test/cli-finish-teardown.test.ts": 2554,
- "test/cli-flag-validation.test.ts": 1931,
- "test/cli-force-exit-teardown-arming.test.ts": 2,
- "test/cli-format-search-json.test.ts": 9,
- "test/cli-format-volunteer.test.ts": 13,
- "test/cli-help-discoverability.test.ts": 4492,
- "test/cli-multimodal-integration.test.ts": 441,
- "test/cli-options.test.ts": 2858,
- "test/cli-pipe-truncation.test.ts": 1118,
- "test/cli-query-image.test.ts": 42,
- "test/cli-search-dispatch.test.ts": 11165,
- "test/cli-should-force-exit.test.ts": 15,
- "test/cli-stdin-hang.test.ts": 3369,
- "test/cli.test.ts": 4757,
- "test/client-slug-fence.test.ts": 29,
- "test/code-callers-cli.test.ts": 3,
- "test/code-def-refs.test.ts": 488,
- "test/code-edges.test.ts": 568,
- "test/code-graph-readiness.test.ts": 573,
- "test/code-intel/edge-densification.test.ts": 58,
- "test/code-intel/eval-capture-graph.test.ts": 4,
- "test/code-intel/recursive-walk.test.ts": 1801,
- "test/code-intel/scope-walker-resolution.test.ts": 38,
- "test/code-intel/traversal-cache.test.ts": 3463,
- "test/code-retrieval-harness.test.ts": 22,
- "test/code-scoped-source-resolve.test.ts": 1826,
- "test/codex-toml.test.ts": 8,
- "test/commands-search.test.ts": 401,
- "test/commands/capture.test.ts": 3175,
- "test/commands/schema-packpath.test.ts": 14,
- "test/config-ensure-gitignore.test.ts": 4,
- "test/config-env-hijack.test.ts": 9,
- "test/config-env.test.ts": 1,
- "test/config-file-plane-keys.test.ts": 10,
- "test/config-get-plane.test.ts": 7,
- "test/config-set.test.ts": 18,
- "test/config-show-object-values.test.ts": 8,
- "test/config-unset.test.ts": 373,
- "test/config.test.ts": 10,
- "test/connect.test.ts": 58,
- "test/connection-resilience.test.ts": 8,
- "test/console-prefix.test.ts": 5,
- "test/consolidate-valid-until.test.ts": 468,
- "test/content-sanity-literals.test.ts": 3,
- "test/content-sanity.test.ts": 18,
- "test/context-engine.test.ts": 43,
- "test/context/entity-salience.test.ts": 4,
- "test/context/resolve-ipc.test.ts": 10,
- "test/contextual-retrieval-resolver.test.ts": 6,
- "test/contextual-retrieval-service-pure.test.ts": 232,
- "test/conversation-parser-cli.test.ts": 26,
- "test/conversation-parser-normalize-block.test.ts": 19,
- "test/conversation-parser/llm-base.test.ts": 8,
- "test/conversation-parser/llm-fallback.test.ts": 31,
- "test/conversation-parser/llm-polish.test.ts": 8,
- "test/conversation-parser/nightly-probe.test.ts": 6,
- "test/conversation-parser/parse.test.ts": 39,
- "test/core/background-work.test.ts": 23,
- "test/core/base-phase.test.ts": 5,
- "test/core/budget/budget-tracker.test.ts": 15,
- "test/core/diarize/payload-fitter-summarize.test.ts": 7,
- "test/core/git-head.test.ts": 14,
- "test/core/retry-reconnect.test.ts": 91,
- "test/core/retry-stress.slow.test.ts": 207,
- "test/core/retry.test.ts": 653,
- "test/cosine-rescore-column.test.ts": 400,
- "test/cross-brain-calibration.test.ts": 173,
- "test/cross-modal-default-slots.test.ts": 23,
- "test/cross-modal-eval-aggregate.test.ts": 8,
- "test/cross-modal-eval-cli.test.ts": 17,
- "test/cross-modal-eval-json-repair.test.ts": 7,
- "test/cross-modal-phase1.test.ts": 6,
- "test/cross-modal-phase2.test.ts": 58,
- "test/cycle-abort.test.ts": 114,
- "test/cycle-any-abort-signal.test.ts": 217,
- "test/cycle-auto-think-config-zero.test.ts": 7,
- "test/cycle-consolidate.test.ts": 432,
- "test/cycle-dream-output-root.test.ts": 409,
- "test/cycle-enabled-phase-completeness.test.ts": 934,
- "test/cycle-extract-source.test.ts": 616,
- "test/cycle-last-full-cycle-at.test.ts": 1075,
- "test/cycle-legacy-phases.test.ts": 1799,
- "test/cycle-lock-per-source.test.ts": 120,
- "test/cycle-pack-gating.test.ts": 4,
- "test/cycle-patterns-child-outcome.test.ts": 1289,
- "test/cycle-patterns-deadline-budget.test.ts": 431,
- "test/cycle-patterns-source-scope.test.ts": 284,
- "test/cycle-patterns.test.ts": 21,
- "test/cycle-stamp-write-failure.test.ts": 1237,
- "test/cycle-synthesize-braindir-resolve.test.ts": 579,
- "test/cycle-synthesize-chunker.test.ts": 2,
- "test/cycle-synthesize-config-zero.test.ts": 24,
- "test/cycle-synthesize-md-discovery.test.ts": 18,
- "test/cycle-synthesize-slug-collection.test.ts": 415,
- "test/cycle-synthesize-subagent-timeout.test.ts": 656,
- "test/cycle-synthesize.test.ts": 18,
- "test/cycle/cycle-lock-ttl.test.ts": 3,
- "test/cycle/extract-atoms-batch.test.ts": 920,
- "test/cycle/extract-atoms-progress.test.ts": 2595,
- "test/cycle/extract-atoms-synthesize-concepts.test.ts": 4546,
- "test/cycle/extract-atoms-work-interleave.test.ts": 1095,
- "test/cycle/nightly-probe-adapters.test.ts": 1,
- "test/cycle/regression-pr-wave-r1-r2-r4.test.ts": 4,
- "test/cycle/synthesize-concepts-progress.test.ts": 1956,
- "test/cycle/synthesize-gateway-adapter.test.ts": 15,
- "test/cycle/yield-during-phase-refresh.test.ts": 1,
- "test/cycle/yield-during-phase-throttle.test.ts": 840,
- "test/data-research.test.ts": 8,
- "test/database-url-guard-preload.test.ts": 458,
- "test/db-disconnect-audit.test.ts": 25,
- "test/db-guard-coverage.test.ts": 296,
- "test/db-lock-auto-takeover.test.ts": 1961,
- "test/db-lock-election.test.ts": 1926,
- "test/db-lock-fencing.test.ts": 861,
- "test/db-lock-heartbeat-takeover.test.ts": 436,
- "test/db-lock-inspect.test.ts": 1424,
- "test/db-lock-per-source.test.ts": 1109,
- "test/db-lock-reap.test.ts": 377,
- "test/db-lock-refresh.test.ts": 7,
- "test/db-pacer.test.ts": 9,
- "test/dedup.test.ts": 9,
- "test/default-model-panels.test.ts": 15,
- "test/denied-after-list.test.ts": 357,
- "test/destructive-guard.test.ts": 4308,
- "test/disk-walk.test.ts": 9,
- "test/dispatch-localonly.test.ts": 4,
- "test/distribution-import-boundary.test.ts": 5,
- "test/docs-cli-commands.test.ts": 71,
- "test/doctor-asset-paths.test.ts": 2,
- "test/doctor-batch-retry.test.ts": 16,
- "test/doctor-behavioral.test.ts": 4869,
- "test/doctor-brain-checks-score.test.ts": 19,
- "test/doctor-calibration-checks.test.ts": 37,
- "test/doctor-categories.test.ts": 12,
- "test/doctor-cause-rank.test.ts": 27,
- "test/doctor-child-orphans.test.ts": 30,
- "test/doctor-conversation-facts-backlog.test.ts": 2420,
- "test/doctor-cycle-freshness.test.ts": 3474,
- "test/doctor-cycle-phase-scope.test.ts": 6,
- "test/doctor-drift-advice.test.ts": 61,
- "test/doctor-embedding-env-override.test.ts": 2446,
- "test/doctor-extract-atoms-backlog.test.ts": 983,
- "test/doctor-extract-health.test.ts": 317,
- "test/doctor-federation-health.test.ts": 1026,
- "test/doctor-fix.test.ts": 2824,
- "test/doctor-frontmatter-partial.test.ts": 6,
- "test/doctor-hidden-by-search-policy.test.ts": 1335,
- "test/doctor-home-dir-in-worktree.test.ts": 425,
- "test/doctor-image-assets-wsl.test.ts": 1800,
- "test/doctor-links-extraction-lag.test.ts": 1717,
- "test/doctor-minions-check.test.ts": 2062,
- "test/doctor-orphan-ratio.test.ts": 4731,
- "test/doctor-parser-probe-check.test.ts": 6,
- "test/doctor-pglite-datadir.test.ts": 13,
- "test/doctor-pglite-scratch-probe.test.ts": 6472,
- "test/doctor-pool-reap-health.test.ts": 15,
- "test/doctor-raw-provenance.test.ts": 402,
- "test/doctor-remediation-plan-render.test.ts": 75,
- "test/doctor-retrieval-reflex.test.ts": 14,
- "test/doctor-scope-filter.test.ts": 47,
- "test/doctor-search-mode.test.ts": 975,
- "test/doctor-self-upgrade.test.ts": 31,
- "test/doctor-silent-death-checks.test.ts": 2184,
- "test/doctor-source-config-shape.test.ts": 10,
- "test/doctor-subagent-health.test.ts": 2043,
- "test/doctor-supervisor-singleton-pidfile.test.ts": 2017,
- "test/doctor-sync-consolidation.test.ts": 968,
- "test/doctor-timeline-metric-labels-2298.test.ts": 3717,
- "test/doctor-v0_37_7_checks.test.ts": 434,
- "test/doctor-v0_41_13_checks.test.ts": 2965,
- "test/doctor-volunteer-channels.test.ts": 18,
- "test/doctor-wedged-queue.test.ts": 1955,
- "test/doctor-worker-oom-loop.test.ts": 6,
- "test/doctor-ze-checks.test.ts": 1378,
- "test/doctor.test.ts": 4964,
- "test/domain-aggregators.test.ts": 1710,
- "test/dream-cli-flags.test.ts": 40,
- "test/dream-dir-source-stamp.test.ts": 1152,
- "test/dream.test.ts": 4561,
- "test/drift-watch.test.ts": 16,
- "test/dry-fix.test.ts": 220,
- "test/durability-cron.test.ts": 15,
- "test/edge-extractor.test.ts": 125,
- "test/effective-date.test.ts": 2,
- "test/embed-backfill-submit.test.ts": 445,
- "test/embed-helper-migration.test.ts": 2,
- "test/embed-keyless-guard.test.ts": 15,
- "test/embed-modality-preserved.test.ts": 371,
- "test/embed-multimodal-batching.test.ts": 19,
- "test/embed-preflight.test.ts": 9,
- "test/embed-skip.test.ts": 4,
- "test/embedding-context.test.ts": 7,
- "test/embedding-dim-check-facts.test.ts": 16,
- "test/embedding-dim-check.test.ts": 1839,
- "test/embedding-migration.test.ts": 3372,
- "test/embedding-model-dims.test.ts": 27,
- "test/embedding-pricing.test.ts": 8,
- "test/embedding-signature-stale.test.ts": 1091,
- "test/emotional-weight.test.ts": 20,
- "test/engine-factory.test.ts": 0,
- "test/engine-find-trajectory.test.ts": 381,
- "test/engine-parity-event-type.test.ts": 388,
- "test/engine-resolve-slug-with-alias.test.ts": 1292,
- "test/engine-upsertFile.test.ts": 1110,
- "test/engine-weight-rounding-integration.test.ts": 364,
- "test/enrich-cycle-phase.test.ts": 799,
- "test/enrich/idempotency.test.ts": 3,
- "test/enrich/thin.test.ts": 3,
- "test/enrichable-pack.test.ts": 8,
- "test/enrichment-service.test.ts": 2,
- "test/enrichment.test.ts": 2772,
- "test/entity-card-perf.slow.test.ts": 38698,
- "test/entity-resolve-perf.slow.test.ts": 4665,
- "test/entity-resolve-slug-fallback.test.ts": 417,
- "test/entity-resolve.test.ts": 412,
- "test/env-number.test.ts": 3,
- "test/envelope-to-gbrain.test.ts": 3234,
- "test/error-classify.test.ts": 25,
- "test/errors.test.ts": 4,
- "test/eval-canary.test.ts": 6393,
- "test/eval-candidates.test.ts": 379,
- "test/eval-capture-drain.test.ts": 153,
- "test/eval-capture-scrub.test.ts": 31,
- "test/eval-capture.test.ts": 5,
- "test/eval-chronicle.test.ts": 334,
- "test/eval-compare.test.ts": 48,
- "test/eval-contradictions-auto-supersession.test.ts": 7,
- "test/eval-contradictions-cache.test.ts": 3386,
- "test/eval-contradictions-calibration-join.test.ts": 7,
- "test/eval-contradictions-calibration.test.ts": 1,
- "test/eval-contradictions-cost-prompt.test.ts": 1351,
- "test/eval-contradictions-cost.test.ts": 7,
- "test/eval-contradictions-cross-source.test.ts": 4,
- "test/eval-contradictions-date-filter.test.ts": 6,
- "test/eval-contradictions-engine.test.ts": 3671,
- "test/eval-contradictions-fixture-redact.test.ts": 1,
- "test/eval-contradictions-integrations.test.ts": 3245,
- "test/eval-contradictions-judge-errors.test.ts": 32,
- "test/eval-contradictions-judge.test.ts": 14,
- "test/eval-contradictions-runner.test.ts": 3601,
- "test/eval-contradictions-severity.test.ts": 6,
- "test/eval-contradictions-trends.test.ts": 2833,
- "test/eval-contradictions/cost-tracker-slash.test.ts": 7,
- "test/eval-contradictions/no-valid-until-write.test.ts": 32,
- "test/eval-conversation-parser-cli.test.ts": 12,
- "test/eval-cross-modal-batch.test.ts": 136,
- "test/eval-export.test.ts": 382,
- "test/eval-gate.test.ts": 1463,
- "test/eval-longmemeval.slow.test.ts": 4231,
- "test/eval-prune.test.ts": 1899,
- "test/eval-replay-gate.test.ts": 1541,
- "test/eval-replay-metadata-skip.test.ts": 588,
- "test/eval-replay.test.ts": 29,
- "test/eval-retrieval-quality.test.ts": 615,
- "test/eval-run-all.test.ts": 15,
- "test/eval-schema-authoring.test.ts": 1,
- "test/eval-shared-json-repair-shim.test.ts": 4,
- "test/eval-suspected-contradictions-budget-default.test.ts": 5,
- "test/eval-takes-quality-aggregate.test.ts": 5,
- "test/eval-takes-quality-boundaries.test.ts": 435,
- "test/eval-takes-quality-cli.test.ts": 14,
- "test/eval-takes-quality-pricing.test.ts": 4,
- "test/eval-takes-quality-receipt-name.test.ts": 4,
- "test/eval-takes-quality-receipt-write.test.ts": 375,
- "test/eval-takes-quality-regress.test.ts": 5,
- "test/eval-takes-quality-replay.test.ts": 366,
- "test/eval-takes-quality-rubric.test.ts": 17,
- "test/eval-takes-quality-trend.test.ts": 343,
- "test/eval-trajectory.test.ts": 917,
- "test/eval-v041_2-scaffolds.test.ts": 26,
- "test/eval-whoknows.test.ts": 5,
- "test/eval.test.ts": 9,
- "test/eval/cycle-default.test.ts": 3,
- "test/execution-env.test.ts": 1,
- "test/exit-classification.test.ts": 12,
- "test/expert-types-pack.test.ts": 61,
- "test/extract-abort.test.ts": 1928,
- "test/extract-atoms-chunk-embed.test.ts": 456,
- "test/extract-atoms-drain-handler.test.ts": 384,
- "test/extract-atoms-drain.test.ts": 5,
- "test/extract-atoms-extractable-types.test.ts": 6,
- "test/extract-atoms-page-discovery.test.ts": 5398,
- "test/extract-atoms-unpriced-model.test.ts": 19,
- "test/extract-by-mention-resume.test.ts": 474,
- "test/extract-by-mention.test.ts": 559,
- "test/extract-conversation-facts-workers.test.ts": 4,
- "test/extract-conversation-facts.test.ts": 3114,
- "test/extract-db.test.ts": 511,
- "test/extract-facts-phase.test.ts": 718,
- "test/extract-from-fence.test.ts": 4,
- "test/extract-fs-source-id.test.ts": 913,
- "test/extract-fs.test.ts": 556,
- "test/extract-incremental.test.ts": 1627,
- "test/extract-source-aware.test.ts": 468,
- "test/extract-stale.test.ts": 662,
- "test/extract-takes-from-pages-progression.test.ts": 340,
- "test/extract-takes-holder-producer-seam.test.ts": 452,
- "test/extract-takes-model-resolution.test.ts": 413,
- "test/extract-takes.test.ts": 788,
- "test/extract-workers.test.ts": 3,
- "test/extract.test.ts": 27,
- "test/extract/benchmark.test.ts": 8,
- "test/extract/receipt-writer.test.ts": 1064,
- "test/extract/status.test.ts": 16,
- "test/extractable-pack.test.ts": 73,
- "test/extractable-spec-widening.test.ts": 22,
- "test/extraction-review.test.ts": 3323,
- "test/facts-absorb-log.test.ts": 326,
- "test/facts-anti-loop.test.ts": 552,
- "test/facts-backstop-gating.test.ts": 2130,
- "test/facts-backstop-integration.test.ts": 405,
- "test/facts-backstop.test.ts": 413,
- "test/facts-canonicality.test.ts": 374,
- "test/facts-classify.test.ts": 4,
- "test/facts-decay.test.ts": 12,
- "test/facts-doctor-shape.test.ts": 405,
- "test/facts-eligibility.test.ts": 108,
- "test/facts-engine.test.ts": 426,
- "test/facts-extract-salvage.test.ts": 10,
- "test/facts-extract-silent-no-op.test.ts": 3,
- "test/facts-extract-smoke.test.ts": 6,
- "test/facts-extract-truncation.test.ts": 19,
- "test/facts-extract.test.ts": 17,
- "test/facts-fence-typed.test.ts": 10,
- "test/facts-fence.test.ts": 21,
- "test/facts-meta-cache.test.ts": 382,
- "test/facts-migration-dim.test.ts": 2470,
- "test/facts-multi-tenant.test.ts": 1948,
- "test/facts-queue-drain-pending.test.ts": 1624,
- "test/facts-queue.test.ts": 629,
- "test/facts-recall-render.test.ts": 339,
- "test/facts-reconcile-protect-cli.test.ts": 355,
- "test/facts-separation-pglite.test.ts": 1930,
- "test/facts-unknown-speaker-gate.test.ts": 10,
- "test/facts-visibility.test.ts": 362,
- "test/fail-improve.test.ts": 103,
- "test/feature-flags.test.ts": 2571,
- "test/features.test.ts": 14,
- "test/fence-extraction.test.ts": 2788,
- "test/fence-write.test.ts": 363,
- "test/file-migration.test.ts": 11,
- "test/file-resolver.test.ts": 10,
- "test/file-upload-engine-context.test.ts": 306,
- "test/file-upload-security.test.ts": 1,
- "test/files.test.ts": 11,
- "test/filing-audit.test.ts": 18,
- "test/find-experts-op.test.ts": 515,
- "test/fix-wave-structural.test.ts": 12,
- "test/flush-then-exit-harness.test.ts": 2117,
- "test/founder-scorecard.test.ts": 6,
- "test/friction-cli.test.ts": 16,
- "test/friction.test.ts": 24,
- "test/frontmatter-cli.test.ts": 1388,
- "test/frontmatter-inference.test.ts": 7,
- "test/frontmatter-install-hook.test.ts": 46,
- "test/frontmatter-non-string-fields.test.ts": 5,
- "test/frontmatter-validate-slug-565.test.ts": 1689,
- "test/fuzz/filesystem-validators.test.ts": 26,
- "test/fuzz/mixed-validators.test.ts": 103,
- "test/fuzz/pure-validators.test.ts": 84,
- "test/gateway-embed-model-override.test.ts": 7,
- "test/gateway-model-messages.test.ts": 6,
- "test/gbrain-home-isolation.test.ts": 4,
- "test/get-agent-job.test.ts": 1802,
- "test/get-brain-identity.test.ts": 1492,
- "test/get-page-federated-scope.test.ts": 4423,
- "test/get-status-snapshot-op.test.ts": 316,
- "test/get-timeline-op.test.ts": 41,
- "test/git-remote.test.ts": 276,
- "test/grade-takes-ensemble.test.ts": 48,
- "test/grade-takes.test.ts": 46,
- "test/graph-query.test.ts": 514,
- "test/gstack-learnings-coupling.test.ts": 25,
- "test/guardrails.test.ts": 31,
- "test/handlers-embed-backfill.test.ts": 483,
- "test/handlers.test.ts": 774,
- "test/health-soft-delete.test.ts": 455,
- "test/helpers/agent-harness.unit.test.ts": 24,
- "test/helpers/schema-diff-indexes.test.ts": 1,
- "test/helpers/schema-diff.test.ts": 5,
- "test/helpers/with-env.test.ts": 1,
- "test/http-transport.test.ts": 131,
- "test/hybrid-recency-config.test.ts": 4,
- "test/import-abort-error.test.ts": 10,
- "test/import-checkpoint.test.ts": 495,
- "test/import-clear-failures-on-success.test.ts": 2019,
- "test/import-code-edges-source-id.test.ts": 349,
- "test/import-dedup-frontmatter-id.test.ts": 2623,
- "test/import-error-summary.test.ts": 0,
- "test/import-file-content-sanity.test.ts": 4133,
- "test/import-file.test.ts": 145,
- "test/import-git-fastpath-prune.test.ts": 53,
- "test/import-image-file.test.ts": 2935,
- "test/import-metafile-skip.test.ts": 17,
- "test/import-repo-path-guard.test.ts": 815,
- "test/import-resume.test.ts": 1631,
- "test/import-source-id.test.ts": 460,
- "test/import-walker.test.ts": 14,
- "test/import-yaml-frontmatter.test.ts": 8,
- "test/incremental-chunking.test.ts": 2063,
- "test/infer-type-pack.test.ts": 10,
- "test/ingestion/daemon.test.ts": 68,
- "test/ingestion/dedup.test.ts": 5,
- "test/ingestion/gstack-learnings.test.ts": 2,
- "test/ingestion/ingest-capture.test.ts": 2458,
- "test/ingestion/markdown-greenfield.test.ts": 12,
- "test/ingestion/migration-mode.test.ts": 21,
- "test/ingestion/put-page-write-through.test.ts": 1662,
- "test/ingestion/skillpack-load.test.ts": 19,
- "test/ingestion/sources/file-watcher.test.ts": 480,
- "test/ingestion/sources/inbox-folder.test.ts": 554,
- "test/ingestion/test-harness.test.ts": 70,
- "test/ingestion/types.test.ts": 6,
- "test/init-embed-check.test.ts": 8,
- "test/init-env-detection.test.ts": 19,
- "test/init-mcp-only.test.ts": 5864,
- "test/init-migrate-only.test.ts": 6014,
- "test/init-mode-picker.test.ts": 2058,
- "test/init-nudge.test.ts": 5,
- "test/init-provider-picker.test.ts": 13,
- "test/insert-facts-batch.test.ts": 380,
- "test/integrations-heartbeat-max-age.test.ts": 12,
- "test/integrations-install.test.ts": 161,
- "test/integrations.test.ts": 26,
- "test/integrity.test.ts": 2260,
- "test/intent-weights.test.ts": 8,
- "test/job-pull-policy.test.ts": 75,
- "test/jobs-format-detail.test.ts": 1,
- "test/jobs-nice-flag.test.ts": 8,
- "test/jobs-thin-client-date-rehydration.test.ts": 69,
- "test/jobs-unify-types-default-dryrun.test.ts": 1331,
- "test/jobs-watch-mode.test.ts": 11,
- "test/jobs-watch-snapshot.test.ts": 4,
- "test/language-manifest.test.ts": 104,
- "test/last-retrieved.test.ts": 292,
- "test/lease-cap-controller.test.ts": 421,
- "test/legacy-token-federated-scope.test.ts": 19,
- "test/lens-pack-manifests.test.ts": 19,
- "test/levenshtein.test.ts": 5,
- "test/link-extraction-code-refs.test.ts": 2,
- "test/link-extraction-dir-whitelist-2576.test.ts": 7,
- "test/link-extraction.test.ts": 30,
- "test/link-inference-pack.test.ts": 18,
- "test/link-source-namespaced-regex.test.ts": 650,
- "test/links-timeline-jsonb-poison.test.ts": 2157,
- "test/lint-content-sanity.test.ts": 30,
- "test/lint-fix-single-pass.test.ts": 3,
- "test/lint-frontmatter.test.ts": 19,
- "test/lint-shared-engine.test.ts": 17,
- "test/lint.test.ts": 23,
- "test/list-all-sources.test.ts": 1511,
- "test/list-clamp-local-trust.test.ts": 488,
- "test/list-pages-truncation.test.ts": 2302,
- "test/llm-intent-escalation.test.ts": 4,
- "test/loadConfig-merge.test.ts": 20,
- "test/local-federated-search-scope.test.ts": 405,
- "test/longmemeval-extract.test.ts": 349,
- "test/longmemeval-intent.test.ts": 16,
- "test/longmemeval-sanitize.test.ts": 15,
- "test/longmemeval-trajectory-routing.test.ts": 2610,
- "test/maintain.test.ts": 17,
- "test/markdown-serializer.test.ts": 7,
- "test/markdown-validation.test.ts": 11,
- "test/markdown.test.ts": 10,
- "test/mcp-client-hardening.test.ts": 290,
- "test/mcp-client.test.ts": 56,
- "test/mcp-dispatch-optional-params.test.ts": 1901,
- "test/mcp-dispatch-summarize.test.ts": 3,
- "test/mcp-eval-capture.test.ts": 1136,
- "test/mcp-stdio-source-resolution.test.ts": 22,
- "test/mcp-surface.test.ts": 405,
- "test/mcp-tool-defs.test.ts": 24,
- "test/mcp-usage.test.ts": 292,
- "test/memory-verbs-conformance.test.ts": 6235,
- "test/metric-glossary.test.ts": 15,
- "test/migrate-engine-resume.test.ts": 0,
- "test/migrate-extensions.test.ts": 2,
- "test/migrate-retry.test.ts": 124,
- "test/migrate-stdout-clean.test.ts": 405,
- "test/migrate.test.ts": 6385,
- "test/migration-orchestrator-v0_21_0.test.ts": 5,
- "test/migration-orchestrator-v0_31_0.test.ts": 1117,
- "test/migration-resume.test.ts": 18,
- "test/migration-v120.test.ts": 338,
- "test/migrations-cjk-wave.test.ts": 350,
- "test/migrations-registry.test.ts": 9,
- "test/migrations-v0_11_0.test.ts": 15,
- "test/migrations-v0_12_0.test.ts": 23,
- "test/migrations-v0_12_2.test.ts": 13,
- "test/migrations-v0_13_0.test.ts": 21,
- "test/migrations-v0_13_1-grandfather.test.ts": 3176,
- "test/migrations-v0_13_1.test.ts": 17,
- "test/migrations-v0_14_0.test.ts": 15,
- "test/migrations-v0_16_0.test.ts": 6,
- "test/migrations-v0_19_0.test.ts": 2637,
- "test/migrations-v0_21_0.test.ts": 7,
- "test/migrations-v0_22_4.test.ts": 4,
- "test/migrations-v0_27_1.test.ts": 2126,
- "test/migrations-v0_32_2.test.ts": 483,
- "test/migrations-v126.test.ts": 1885,
- "test/migrations-v128.test.ts": 465,
- "test/migrations-v48-takes-weight-backfill.test.ts": 403,
- "test/migrations-v94.test.ts": 1581,
- "test/migrations-v99.test.ts": 1760,
- "test/minions-lease-full-retry.test.ts": 445,
- "test/minions-quiet-hours.test.ts": 2009,
- "test/minions-shell-inherit.test.ts": 5,
- "test/minions-shell-redact.test.ts": 2,
- "test/minions-shell-validate.test.ts": 34,
- "test/minions-shell.test.ts": 477,
- "test/minions.test.ts": 8214,
- "test/minions/agent-audit.test.ts": 9,
- "test/mode-switch-ux.test.ts": 800,
- "test/model-id.test.ts": 5,
- "test/model-pricing.test.ts": 7,
- "test/models-doctor-embed.test.ts": 7,
- "test/models-doctor-reranker.test.ts": 25,
- "test/models-doctor-v1-hint.test.ts": 18,
- "test/mounts-cache.test.ts": 25,
- "test/mounts-cli.test.ts": 61,
- "test/multi-source-drift.test.ts": 404,
- "test/multi-source-integration.test.ts": 2064,
- "test/niceness.test.ts": 3,
- "test/nightly-probe-config-plane.test.ts": 14,
- "test/nightly-quality-probe.test.ts": 19,
- "test/no-tracked-symlinks-guard.test.ts": 54,
- "test/notability-eval.test.ts": 21,
- "test/npm-squat-check.test.ts": 2,
- "test/nudge.test.ts": 43,
- "test/oauth-authorize-scope-default.test.ts": 355,
- "test/oauth-confidential-client.test.ts": 380,
- "test/oauth-dcr-ttl.test.ts": 2272,
- "test/oauth-scope-probe.test.ts": 8,
- "test/oauth-surface-ladder.test.ts": 2820,
- "test/oauth.test.ts": 3183,
- "test/onboard-pack-upgrade-checks.test.ts": 3181,
- "test/op-checkpoint-mentions-fingerprint.test.ts": 4,
- "test/op-checkpoint.test.ts": 5748,
- "test/openai-compat-multimodal.test.ts": 9,
- "test/openclaw-plugin-manifest.test.ts": 7,
- "test/openrouter-reranker-recipe.test.ts": 2,
- "test/operation-context-sourceid-required.test.ts": 4,
- "test/operations-allow-list.test.ts": 24,
- "test/operations-descriptions.test.ts": 6,
- "test/operations-embedding-column.test.ts": 2,
- "test/operations-find-trajectory.test.ts": 421,
- "test/operations-fuzzy-source-scope.test.ts": 2687,
- "test/operations-schema-pack.test.ts": 3424,
- "test/operations-trust-boundary.test.ts": 3504,
- "test/orphans-pure-fn.test.ts": 529,
- "test/orphans-source-scope.test.ts": 520,
- "test/orphans.test.ts": 2409,
- "test/owner-holder.test.ts": 18,
- "test/pace-mode.test.ts": 17,
- "test/page-generation-counter.test.ts": 3921,
- "test/page-lock.test.ts": 262,
- "test/page-search-vector-overflow.test.ts": 3152,
- "test/page-type-exhaustive.test.ts": 9,
- "test/pages-soft-delete.test.ts": 1209,
- "test/parallel.test.ts": 122,
- "test/parent-scope.test.ts": 443,
- "test/parity.test.ts": 9,
- "test/path-confine.test.ts": 13,
- "test/performfullsync-source-id.test.ts": 638,
- "test/pglite-engine.test.ts": 1610,
- "test/pglite-init-classifier.test.ts": 17,
- "test/pglite-leftovers-check.test.ts": 9,
- "test/pglite-lock.test.ts": 7031,
- "test/pglite-repair.test.ts": 120,
- "test/pglite-resetwal.test.ts": 39,
- "test/pglite-workers-clamp.test.ts": 6,
- "test/phantom-redirect-engine-parity.test.ts": 1254,
- "test/phantom-redirect-per-source-lock.test.ts": 2,
- "test/phantom-redirect.test.ts": 4511,
- "test/phase-scope-coverage.test.ts": 1,
- "test/plugin-loader.test.ts": 11,
- "test/post-install-advisory.test.ts": 40,
- "test/post-write-lint.test.ts": 3590,
- "test/postgres-disconnect-bounded.test.ts": 2504,
- "test/postgres-engine-config-reconnect.test.ts": 21,
- "test/postgres-engine-getter-selfheal.test.ts": 15,
- "test/postgres-engine-rls-scope.test.ts": 8,
- "test/postgres-engine-singleton-ownership.test.ts": 4,
- "test/postgres-engine.test.ts": 13,
- "test/postgres-execute-raw-direct.test.ts": 33,
- "test/preferences.test.ts": 14,
- "test/privacy-script-wired.test.ts": 9,
- "test/privacy-strip-and-forget.test.ts": 440,
- "test/process-cleanup.test.ts": 3035,
- "test/process-watchdog.test.ts": 5,
- "test/progress-tail.test.ts": 3,
- "test/progress.test.ts": 330,
- "test/progressive-batch/orchestrator.test.ts": 77,
- "test/progressive-batch/retrofit-wrap.test.ts": 9,
- "test/propose-takes-per-claim.test.ts": 1903,
- "test/propose-takes.test.ts": 49,
- "test/providers-test-model-base-url.test.ts": 1,
- "test/providers.test.ts": 2,
- "test/public-exports.test.ts": 52,
- "test/publish-gates.test.ts": 9,
- "test/publish.test.ts": 120,
- "test/put-page-dedup-fence.test.ts": 1499,
- "test/put-page-empty-guard.test.ts": 1614,
- "test/put-page-namespace.test.ts": 8,
- "test/put-page-provenance.test.ts": 2382,
- "test/put-page-writer-lint.test.ts": 2084,
- "test/qualified-names.test.ts": 2,
- "test/quarantine-cli.test.ts": 1672,
- "test/quarantine.test.ts": 10,
- "test/query-cache-gate.test.ts": 917,
- "test/query-cache.test.ts": 2149,
- "test/query-intent-concept.test.ts": 5,
- "test/query-intent-legacy.test.ts": 6,
- "test/query-intent.test.ts": 10,
- "test/query-sanitization.test.ts": 4,
- "test/queue-child-done.test.ts": 490,
- "test/queue-getstats-wedge.test.ts": 398,
- "test/queue-lock-retry.test.ts": 14,
- "test/queue-stall-parent-unblock.test.ts": 415,
- "test/queue-started-at-retry.test.ts": 991,
- "test/rate-leases-uncapped.test.ts": 782,
- "test/rate-leases.test.ts": 431,
- "test/readme-hero-anchors.test.ts": 5,
- "test/recall-extensions.test.ts": 2447,
- "test/recall-footer.test.ts": 17,
- "test/recall-rollup.test.ts": 78,
- "test/recency-decay.test.ts": 6,
- "test/recompute-emotional-weight.test.ts": 7,
- "test/reconcile-links-cli-reachability.test.ts": 547,
- "test/redos-hardening.test.ts": 16,
- "test/register-client-source-normalize.test.ts": 3,
- "test/regression-strict-source-id.test.ts": 7,
- "test/regression-v0_16_4.test.ts": 13,
- "test/regressions/gbrain-base-equivalence.test.ts": 14,
- "test/regressions/v0.36.1.0-iron-rule.test.ts": 9,
- "test/regressions/v0_36_frontier_cap.test.ts": 2207,
- "test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 2006,
- "test/reindex-code.test.ts": 738,
- "test/reindex-cost-refusal.test.ts": 13,
- "test/reindex-frontmatter-connect.test.ts": 1889,
- "test/reindex-preserve-tags.test.ts": 2493,
- "test/reindex.test.ts": 519,
- "test/relational-ab.test.ts": 2763,
- "test/relational-fanout.test.ts": 447,
- "test/relational-intent.test.ts": 1,
- "test/relational-recall.test.ts": 412,
- "test/release-workflow.test.ts": 21,
- "test/remediation-step.test.ts": 8,
- "test/remote-ping-status-field.test.ts": 0,
- "test/repair-jsonb.test.ts": 12,
- "test/repo-root.test.ts": 9,
- "test/repo-visibility.test.ts": 134,
- "test/report.test.ts": 7,
- "test/repos-alias.test.ts": 1994,
- "test/request-tools.test.ts": 408,
- "test/rerank-audit.test.ts": 7,
- "test/resolve-ipc-v2.test.ts": 1187,
- "test/resolve-prepare.test.ts": 3,
- "test/resolver-merge.test.ts": 1,
- "test/resolver.test.ts": 141,
- "test/resolvers.test.ts": 4159,
- "test/restart-sweep.test.ts": 44,
- "test/retrieval-quality-harness.test.ts": 16,
- "test/retrieval-reflex.test.ts": 475,
- "test/retrieval-upgrade-planner.test.ts": 6111,
- "test/retry-matcher.test.ts": 18,
- "test/routing-eval-cli.test.ts": 1309,
- "test/routing-eval.test.ts": 9,
- "test/rrf-source-key.test.ts": 7,
- "test/rss-default.test.ts": 25,
- "test/salience.test.ts": 0,
- "test/scenarios.test.ts": 14,
- "test/schema-bootstrap-coverage.test.ts": 4794,
- "test/schema-cli-contract.test.ts": 4,
- "test/schema-cli.test.ts": 5370,
- "test/schema-migrate-link-source-mentions.test.ts": 443,
- "test/schema-pack-best-effort.test.ts": 8,
- "test/schema-pack-expand-type-filter.test.ts": 3,
- "test/schema-pack-infer-type-and-subtype.test.ts": 5,
- "test/schema-pack-lint-rules.test.ts": 13,
- "test/schema-pack-loader.test.ts": 21,
- "test/schema-pack-manifest-v041_2.test.ts": 7,
- "test/schema-pack-merge.test.ts": 10,
- "test/schema-pack-mutate-audit.test.ts": 18,
- "test/schema-pack-mutate.test.ts": 83,
- "test/schema-pack-pack-lock.test.ts": 66,
- "test/schema-pack-page-to-alias.test.ts": 894,
- "test/schema-pack-page-to-link.test.ts": 1168,
- "test/schema-pack-query-cache-invalidator.test.ts": 710,
- "test/schema-pack-registry-reload.test.ts": 42,
- "test/schema-pack-registry.test.ts": 1,
- "test/schema-pack-retype.test.ts": 3796,
- "test/schema-pack-rewrite-links-batch.test.ts": 743,
- "test/schema-pack-stats.test.ts": 2897,
- "test/schema-pack-sync.test.ts": 2743,
- "test/schema-pack-trust-boundary.test.ts": 6,
- "test/schema-pack-unify-types-handler.test.ts": 1611,
- "test/schema-pack/scaffold-extractable.test.ts": 9,
- "test/schema-verify.test.ts": 18,
- "test/scope-agent-isolation.test.ts": 5,
- "test/scope-normalize.test.ts": 13,
- "test/scope.test.ts": 5,
- "test/scripts/check-engine-dynamic-import.test.ts": 5332,
- "test/scripts/check-key-files-current-state.test.ts": 126,
- "test/scripts/check-proposal-pii.test.ts": 506,
- "test/scripts/check-skill-refs.test.ts": 1077,
- "test/scripts/check-test-isolation.test.ts": 279,
- "test/scripts/check-worker-lock-renewal-shape.test.ts": 30,
- "test/scripts/check-worker-pool-atomicity.test.ts": 117,
- "test/scripts/evals-collection.test.ts": 996,
- "test/scripts/mine-shard-weights.test.ts": 10,
- "test/scripts/run-serial-pool.test.ts": 3082,
- "test/scripts/run-unit-parallel.test.ts": 1328,
- "test/scripts/run-unit-shard.test.ts": 195,
- "test/scripts/run-verify-parallel.test.ts": 2917,
- "test/scripts/serial-files.test.ts": 95,
- "test/scripts/sharding.test.ts": 8,
- "test/scripts/test-shard.slow.test.ts": 576,
- "test/search-alias-resolved-boost.test.ts": 783,
- "test/search-by-image-op.test.ts": 1044,
- "test/search-compiled-truth-boost-scope.test.ts": 4,
- "test/search-image-column.test.ts": 724,
- "test/search-lang-symbol-kind.test.ts": 346,
- "test/search-limit.test.ts": 348,
- "test/search-mode.test.ts": 9,
- "test/search-telemetry.test.ts": 400,
- "test/search-types-filter.test.ts": 424,
- "test/search.test.ts": 15,
- "test/search/alias-hop.test.ts": 1346,
- "test/search/alias-normalize.test.ts": 18,
- "test/search/attribution-stamping.test.ts": 5,
- "test/search/autocut-eval.test.ts": 4,
- "test/search/autocut.test.ts": 8,
- "test/search/evidence.test.ts": 5,
- "test/search/explain-formatter.test.ts": 23,
- "test/search/graph-signals-wire-integration.test.ts": 559,
- "test/search/graph-signals.test.ts": 30,
- "test/search/knobs-hash-reranker.test.ts": 12,
- "test/search/page-aliases-engine.test.ts": 2235,
- "test/search/per-call-mode.test.ts": 3,
- "test/search/pre-migration-failopen.test.ts": 2402,
- "test/search/query-embed-deadline.test.ts": 4044,
- "test/search/query-op-adaptive-return.test.ts": 4,
- "test/search/query-op-autocut.test.ts": 16,
- "test/search/reindex-aliases.test.ts": 840,
- "test/search/rerank.test.ts": 14,
- "test/search/return-policy.test.ts": 7,
- "test/search/search-diagnose.test.ts": 455,
- "test/search/search-stats-graph-signals.test.ts": 381,
- "test/search/searchvector-maxpool.test.ts": 2023,
- "test/search/telemetry-rank1.test.ts": 1669,
- "test/search/title-boost-stage.test.ts": 9,
- "test/search/title-match.test.ts": 11,
- "test/search/title-retrieval-arm.test.ts": 2566,
- "test/secret-scan.test.ts": 12,
- "test/select-e2e.test.ts": 25,
- "test/self-fix.test.ts": 1984,
- "test/self-upgrade-pending.test.ts": 25,
- "test/self-upgrade.test.ts": 28,
- "test/serve-http-bootstrap-token.test.ts": 115,
- "test/serve-http-cors.test.ts": 114,
- "test/serve-http-embedding-width.test.ts": 361,
- "test/serve-http-health.test.ts": 378,
- "test/serve-http-lifecycle.test.ts": 128,
- "test/serve-http-oauth-token-rate-limit.test.ts": 98,
- "test/serve-http-trust-proxy.test.ts": 95,
- "test/serve-skills-publish-nudge.test.ts": 192,
- "test/serve-stdio-lifecycle.test.ts": 1388,
- "test/session-state-gc.test.ts": 424,
- "test/setup-branching.test.ts": 7,
- "test/skill-brain-first.test.ts": 27,
- "test/skill-catalog-block-scalar.test.ts": 1,
- "test/skill-catalog-security.test.ts": 9,
- "test/skill-catalog-transports.test.ts": 1029,
- "test/skill-catalog.test.ts": 21,
- "test/skill-currency.test.ts": 10,
- "test/skill-manifest.test.ts": 12,
- "test/skill-preconditions.test.ts": 19,
- "test/skill-trigger-index.test.ts": 8,
- "test/skillify-check.test.ts": 1259,
- "test/skillify-scaffold.test.ts": 12,
- "test/skillopt/adversarial/resume-after-crash.test.ts": 13,
- "test/skillopt/apply-edits.test.ts": 2,
- "test/skillopt/audit.test.ts": 28,
- "test/skillopt/batch.test.ts": 3,
- "test/skillopt/benchmark.test.ts": 10,
- "test/skillopt/bootstrap-from-skill.test.ts": 27,
- "test/skillopt/held-out.test.ts": 21,
- "test/skillopt/lock.test.ts": 2790,
- "test/skillopt/lr-schedule.test.ts": 3,
- "test/skillopt/reflect.test.ts": 21,
- "test/skillopt/rejected-buffer.test.ts": 12,
- "test/skillopt/rollout-schema.test.ts": 16,
- "test/skillopt/rollout.test.ts": 1,
- "test/skillopt/score.test.ts": 8,
- "test/skillopt/validate-gate-abort.test.ts": 5,
- "test/skillopt/version-store.test.ts": 23,
- "test/skillopt/write-capture.test.ts": 1400,
- "test/skillpack-apply-hunks.test.ts": 24,
- "test/skillpack-bootstrap-display.test.ts": 4,
- "test/skillpack-brain-resident-locate.test.ts": 27,
- "test/skillpack-changed-since-version.test.ts": 228,
- "test/skillpack-check.test.ts": 4258,
- "test/skillpack-copy.test.ts": 12,
- "test/skillpack-endorse.test.ts": 95,
- "test/skillpack-frontmatter-sources.test.ts": 8,
- "test/skillpack-harvest-lint.test.ts": 7,
- "test/skillpack-harvest.test.ts": 17,
- "test/skillpack-init-brain-pack.test.ts": 4,
- "test/skillpack-init-pack.test.ts": 59,
- "test/skillpack-install.test.ts": 69,
- "test/skillpack-manifest-v1.test.ts": 8,
- "test/skillpack-migrate-fence.test.ts": 16,
- "test/skillpack-nag-state.test.ts": 30,
- "test/skillpack-reference-apply.test.ts": 26,
- "test/skillpack-reference-pack-is-ten.test.ts": 8,
- "test/skillpack-reference.test.ts": 17,
- "test/skillpack-registry-client.test.ts": 18,
- "test/skillpack-registry-schema.test.ts": 2,
- "test/skillpack-remote-source.test.ts": 73,
- "test/skillpack-rubric-doctor.test.ts": 38,
- "test/skillpack-scaffold-third-party.test.ts": 42,
- "test/skillpack-scaffold.test.ts": 34,
- "test/skillpack-scrub-legacy.test.ts": 7,
- "test/skillpack-state.test.ts": 5,
- "test/skillpack-status.test.ts": 10,
- "test/skillpack-tarball.test.ts": 129,
- "test/skillpack-trust-prompt.test.ts": 32,
- "test/skills-conformance.test.ts": 42,
- "test/skills-integrity.test.ts": 32,
- "test/slug-unicode-scripts.test.ts": 15,
- "test/slug-validation.test.ts": 9,
- "test/snapshot-shape-guard.test.ts": 14,
- "test/sort-newest-first.test.ts": 2,
- "test/source-config-redact.test.ts": 1,
- "test/source-health.test.ts": 643,
- "test/source-id-routing.test.ts": 949,
- "test/source-id-tx-regression.test.ts": 2082,
- "test/source-id.test.ts": 15,
- "test/source-resolver-silent-fallback.test.ts": 1784,
- "test/source-resolver-sole-non-default.test.ts": 8,
- "test/source-resolver-with-tier.test.ts": 27,
- "test/source-resolver.test.ts": 8,
- "test/source-scope-resolver.test.ts": 3,
- "test/sources-archive-idempotent.test.ts": 1872,
- "test/sources-load.test.ts": 2785,
- "test/sources-mcp.test.ts": 3022,
- "test/sources-ops.test.ts": 7879,
- "test/sources-resync-recovery.test.ts": 3664,
- "test/sources-set-cr-mode.test.ts": 1632,
- "test/sources-webhook.test.ts": 19,
- "test/sources.test.ts": 17,
- "test/spawn-helpers.test.ts": 4,
- "test/spend-off-switch.test.ts": 0,
- "test/sql-query.test.ts": 1445,
- "test/sql-ranking.test.ts": 6,
- "test/ssrf-validate.test.ts": 12,
- "test/status-autopilot-lock.test.ts": 9,
- "test/status-sections.test.ts": 38,
- "test/status-thin-client-skew.test.ts": 32,
- "test/storage-backfill.test.ts": 26,
- "test/storage-config.test.ts": 7,
- "test/storage-export.test.ts": 462,
- "test/storage-pglite.test.ts": 455,
- "test/storage-status.test.ts": 2,
- "test/storage-sync.test.ts": 34,
- "test/storage.test.ts": 130,
- "test/stub-guard-audit.test.ts": 8,
- "test/subagent-aggregator.test.ts": 12,
- "test/subagent-audit.test.ts": 13,
- "test/subagent-handler.test.ts": 637,
- "test/subagent-prompt-too-long.test.ts": 9,
- "test/subagent-transcript.test.ts": 979,
- "test/subagent-v1-v2-shim.test.ts": 2039,
- "test/submit-agent.test.ts": 2361,
- "test/submit-queue-state.test.ts": 3090,
- "test/sum-stale-chunk-chars.test.ts": 1044,
- "test/supabase-admin.test.ts": 20,
- "test/supervisor-audit.test.ts": 11,
- "test/supervisor-build-worker-args.test.ts": 6,
- "test/supervisor-db-lock.test.ts": 332,
- "test/supervisor-pid.test.ts": 3,
- "test/supervisor-tini.test.ts": 9,
- "test/supervisor-wedge.test.ts": 1960,
- "test/supervisor.test.ts": 2128,
- "test/surface-audit.test.ts": 8,
- "test/svg-renderer.test.ts": 3,
- "test/sweep.test.ts": 745,
- "test/sync-all-missing-path.test.ts": 7,
- "test/sync-all-parallel.test.ts": 8,
- "test/sync-baseline-guard.test.ts": 1,
- "test/sync-brain-op-source-id.test.ts": 2005,
- "test/sync-break-lock-all.test.ts": 3058,
- "test/sync-classifier-widening.test.ts": 2,
- "test/sync-concurrency.test.ts": 2,
- "test/sync-cost-estimate.test.ts": 220,
- "test/sync-cost-preview.test.ts": 25,
- "test/sync-delete-batch.slow.test.ts": 3258,
- "test/sync-delete-batch.test.ts": 1893,
- "test/sync-deleted-slug-embed.test.ts": 2254,
- "test/sync-delta.test.ts": 262,
- "test/sync-discover-git-root-stderr.test.ts": 374,
- "test/sync-failures.test.ts": 62,
- "test/sync-git-autoinit.test.ts": 2652,
- "test/sync-hard-deadline.test.ts": 3,
- "test/sync-isSyncable-shape.test.ts": 13,
- "test/sync-monorepo.test.ts": 2985,
- "test/sync-no-embed-sentinel.test.ts": 49,
- "test/sync-nudge-status-gate.test.ts": 11,
- "test/sync-parallel.test.ts": 4736,
- "test/sync-path-containment.test.ts": 13,
- "test/sync-reconcile-mass-delete.test.ts": 12,
- "test/sync-rename-batch.test.ts": 1061,
- "test/sync-sole-non-default-routing.test.ts": 1127,
- "test/sync-strategy.test.ts": 3,
- "test/sync-timeout-cli-dispatch.test.ts": 620,
- "test/sync-timeout.test.ts": 2,
- "test/sync-trigger-cli.test.ts": 317,
- "test/sync-walker-submodule.test.ts": 6,
- "test/sync-walker-symlink.test.ts": 52,
- "test/sync.test.ts": 6850,
- "test/synth-enabled-default.test.ts": 14,
- "test/synthesize-chunk-budget.test.ts": 35,
- "test/system-prompt.test.ts": 3,
- "test/take-forecast.test.ts": 4,
- "test/takes-command-source-scope.test.ts": 35,
- "test/takes-engine.test.ts": 434,
- "test/takes-extract-json.test.ts": 7,
- "test/takes-fence.test.ts": 18,
- "test/takes-holder-semantics.test.ts": 20,
- "test/takes-holder-validation.test.ts": 21,
- "test/takes-list-subcommand.test.ts": 338,
- "test/takes-resolution.test.ts": 2,
- "test/takes-source-scope.test.ts": 409,
- "test/takes-weight-rounding.test.ts": 12,
- "test/template-repo-generator.test.ts": 13,
- "test/text-safe.test.ts": 12,
- "test/thin-client-routing-audit.test.ts": 6,
- "test/thin-client-source-scope.test.ts": 8,
- "test/thin-client-upgrade-prompt.test.ts": 38,
- "test/think-ab.test.ts": 23,
- "test/think-cost.test.ts": 22,
- "test/think-entity-extract.test.ts": 6,
- "test/think-gaps.test.ts": 6,
- "test/think-gateway-adapter.test.ts": 192,
- "test/think-intent.test.ts": 2,
- "test/think-max-output-tokens.test.ts": 5,
- "test/think-pages-block.test.ts": 17,
- "test/think-sanitize-trajectory.test.ts": 27,
- "test/think-trajectory-injection.test.ts": 2248,
- "test/think-with-calibration.test.ts": 7,
- "test/timeline-date-batch.test.ts": 567,
- "test/timeline-dedup-repair.test.ts": 308,
- "test/timeline-entry-subagent-fence.test.ts": 4,
- "test/timeout.test.ts": 70,
- "test/timing-safe.test.ts": 32,
- "test/token-budget.test.ts": 4,
- "test/token-mint.test.ts": 341,
- "test/tool-catalog.test.ts": 15,
- "test/trajectory-format.test.ts": 32,
- "test/trajectory.test.ts": 15,
- "test/transcript-capture.test.ts": 245,
- "test/transcription-injection.test.ts": 4,
- "test/transcription.test.ts": 0,
- "test/transcripts.test.ts": 28,
- "test/traverse-graph-dedup.test.ts": 459,
- "test/trust-boundary-contract.test.ts": 2,
- "test/truthful-catalog.e2e-lite.test.ts": 2420,
- "test/tty-harness.test.ts": 1323,
- "test/turn-context.test.ts": 1858,
- "test/two-pass.test.ts": 412,
- "test/undo-wave.test.ts": 8,
- "test/unfederate-read-scope-2928.test.ts": 1243,
- "test/upgrade-reembed-prompt.test.ts": 369,
- "test/upgrade-reference-sweep.test.ts": 155,
- "test/url-redact.test.ts": 4,
- "test/utils.test.ts": 4,
- "test/v0_29-tool-surfaces.test.ts": 6,
- "test/v81-v82-smoke.test.ts": 446,
- "test/validate-params.test.ts": 24,
- "test/vector-ef-search.test.ts": 2512,
- "test/vector-index-lifecycle.test.ts": 6,
- "test/voice-gate.test.ts": 17,
- "test/volunteer-context.test.ts": 560,
- "test/volunteer-events-delivery.test.ts": 5,
- "test/voyage-multimodal.test.ts": 23,
- "test/voyage-response-cap.test.ts": 2,
- "test/wait-for-completion.test.ts": 1002,
- "test/watch-command.test.ts": 920,
- "test/whoami.test.ts": 5,
- "test/whoknows-doctor.test.ts": 18,
- "test/whoknows.test.ts": 4,
- "test/worker-conn-resilience-1720.test.ts": 133,
- "test/worker-lock-renewal-shape.test.ts": 5,
- "test/worker-lock-renewal.test.ts": 30,
- "test/worker-pool.test.ts": 60,
- "test/worker-promote-reconnect.test.ts": 12,
- "test/worker-rss.test.ts": 29,
- "test/worker-shutdown-disconnect.test.ts": 518,
- "test/worker-supervised-db-probe.test.ts": 539,
- "test/worker-watchdog-trigger.test.ts": 2037,
- "test/write-through.test.ts": 2119,
- "test/write-verify-guard.test.ts": 1036,
- "test/writer.test.ts": 6150,
- "test/yaml-lite.test.ts": 3,
- "test/ze-switch-cli.test.ts": 2793,
- "test/ze-switch-env-override.test.ts": 2567,
- "test/zombie-reap.test.ts": 6,
- "test/eval-brainbench-e2e.slow.test.ts": 57548
+ "test/abort-check.test.ts": 12,
+ "test/active-pack-wiring.test.ts": 1,
+ "test/admin-agents-spend.test.ts": 2939,
+ "test/admin-sse-eventsource.test.ts": 3,
+ "test/admin-sse-handshake.test.ts": 2,
+ "test/advisor-apply.test.ts": 17,
+ "test/advisor-cli.test.ts": 19,
+ "test/advisor-collectors-findings.test.ts": 5,
+ "test/advisor-core.test.ts": 36,
+ "test/advisor-mcp-client-fit.test.ts": 534,
+ "test/advisor-op-gate.test.ts": 42,
+ "test/advisor-ranking-eval.test.ts": 16,
+ "test/agent-cli.test.ts": 563,
+ "test/agent-register.test.ts": 467,
+ "test/agent-runner.test.ts": 14,
+ "test/ai-probes-models.test.ts": 12,
+ "test/ai/adaptive-embed-batch.test.ts": 35,
+ "test/ai/anthropic-key.test.ts": 9,
+ "test/ai/build-gateway-config.test.ts": 957,
+ "test/ai/capabilities.test.ts": 3,
+ "test/ai/classify-global-llm-error.test.ts": 7,
+ "test/ai/claude-cli-expansion.test.ts": 5,
+ "test/ai/config-no-env-mutation.test.ts": 1,
+ "test/ai/deepseek-reasoning-content.test.ts": 5,
+ "test/ai/diagnose-embedding-dims.test.ts": 13,
+ "test/ai/dims-openai.test.ts": 2,
+ "test/ai/dims-qwen3-native.test.ts": 6,
+ "test/ai/dims-zeroentropy.test.ts": 4,
+ "test/ai/embed-env-batch-cap.test.ts": 5,
+ "test/ai/embed-keyless-base-url.test.ts": 0,
+ "test/ai/embedQuery.test.ts": 7,
+ "test/ai/gateway-cache-breakpoint.test.ts": 14,
+ "test/ai/gateway-chat-temperature.test.ts": 13,
+ "test/ai/gateway-chat.test.ts": 14,
+ "test/ai/gateway-ocr-budget.test.ts": 7,
+ "test/ai/gateway-openai-prompt-cache-key.test.ts": 13,
+ "test/ai/gateway-probe-chat-model.test.ts": 1,
+ "test/ai/gateway-reset-baseline.test.ts": 3,
+ "test/ai/gateway-thinking-headroom.test.ts": 9,
+ "test/ai/gateway-thinking-model-re.test.ts": 1,
+ "test/ai/gateway-tool-loop.test.ts": 32,
+ "test/ai/gateway-toolcall-pairing.test.ts": 10,
+ "test/ai/gateway-tools-schema.test.ts": 20,
+ "test/ai/gateway.test.ts": 819,
+ "test/ai/model-resolver-slash.test.ts": 3,
+ "test/ai/no-batch-cap-item-split.test.ts": 0,
+ "test/ai/normalize-ai-error.test.ts": 5,
+ "test/ai/ocr-model-routing.test.ts": 26,
+ "test/ai/ollama-library-tag-dims.test.ts": 5,
+ "test/ai/recipe-azure-openai.test.ts": 2,
+ "test/ai/recipe-dashscope-rerank.test.ts": 5,
+ "test/ai/recipe-dashscope.test.ts": 22,
+ "test/ai/recipe-google-embedding-2.test.ts": 1,
+ "test/ai/recipe-google-prompt-cache.test.ts": 9,
+ "test/ai/recipe-llama-server-reranker.test.ts": 4,
+ "test/ai/recipe-llama-server.test.ts": 3,
+ "test/ai/recipe-lmstudio.test.ts": 28,
+ "test/ai/recipe-minimax.test.ts": 7,
+ "test/ai/recipe-mistral.test.ts": 2,
+ "test/ai/recipe-moonshot.test.ts": 4,
+ "test/ai/recipe-nan.test.ts": 6,
+ "test/ai/recipe-nvidia.test.ts": 6,
+ "test/ai/recipe-ollama-dims.test.ts": 6,
+ "test/ai/recipe-ollama-thinking.test.ts": 4,
+ "test/ai/recipe-ollama.test.ts": 20,
+ "test/ai/recipe-openrouter.test.ts": 7,
+ "test/ai/recipe-perplexity.test.ts": 3,
+ "test/ai/recipe-zhipu.test.ts": 3,
+ "test/ai/recipes-existing-regression.test.ts": 9,
+ "test/ai/rerank.test.ts": 32,
+ "test/ai/reranker-readiness.test.ts": 7,
+ "test/ai/resolve-native-base-url.test.ts": 3,
+ "test/ai/schema-templating.test.ts": 1,
+ "test/ai/silent-drop-regression.test.ts": 2,
+ "test/ai/sunset-warn.test.ts": 25,
+ "test/ai/voyage-code-3-recipe.test.ts": 8,
+ "test/ai/voyage-reranker-recipe.test.ts": 3,
+ "test/ai/zeroentropy-compat-fetch.test.ts": 14,
+ "test/ai/zeroentropy-recipe.test.ts": 2,
+ "test/all-sources-sentinel.test.ts": 23,
+ "test/ambient-recall-cli.test.ts": 7690,
+ "test/ambient-recall-templates.test.ts": 11,
+ "test/ambient-recall.test.ts": 4647,
+ "test/ambient-writeback-wiring-pins.test.ts": 408,
+ "test/anomalies.test.ts": 5,
+ "test/anthropic-model-ids.test.ts": 1,
+ "test/anthropic-pricing.test.ts": 4,
+ "test/apply-migrations-list-db-state.test.ts": 1,
+ "test/apply-migrations.test.ts": 20,
+ "test/archive-crawler-config.test.ts": 8,
+ "test/archived-source-scoping.test.ts": 8,
+ "test/artifact-abstraction.test.ts": 3,
+ "test/asymmetric-encoding-contract.test.ts": 18,
+ "test/atomic-write.test.ts": 11,
+ "test/atoms-scan-hash-rearm.test.ts": 413,
+ "test/audit/audit-dir-preload.test.ts": 14,
+ "test/audit/audit-writer.test.ts": 2,
+ "test/audit/batch-retry-audit.test.ts": 16,
+ "test/audit/batch-retry-redaction.test.ts": 20,
+ "test/audit/content-sanity-audit.test.ts": 8,
+ "test/audit/lock-renewal-audit.test.ts": 22,
+ "test/audit/pool-recovery-audit.test.ts": 0,
+ "test/audit/redact-connection-info.test.ts": 3,
+ "test/auth-create-args.test.ts": 373,
+ "test/auth-register-client-args.test.ts": 23,
+ "test/auth-register-client-output-pin.test.ts": 7,
+ "test/auto-link-targeted-probe-2544.test.ts": 3308,
+ "test/auto-think-phase.test.ts": 549,
+ "test/autopilot-auto-drain-wiring.test.ts": 1,
+ "test/autopilot-cycle-failure-classification.test.ts": 9,
+ "test/autopilot-cycle-handler.test.ts": 563,
+ "test/autopilot-cycle-source-checkout.test.ts": 936,
+ "test/autopilot-drain-deadlock-2050.test.ts": 3140,
+ "test/autopilot-failure-cooldown.test.ts": 1156,
+ "test/autopilot-fanout-wiring.test.ts": 7,
+ "test/autopilot-fanout.test.ts": 10,
+ "test/autopilot-global-maintenance.test.ts": 2099,
+ "test/autopilot-install.test.ts": 31,
+ "test/autopilot-lock-path.test.ts": 4,
+ "test/autopilot-lock.test.ts": 28,
+ "test/autopilot-nightly-probe-wiring.test.ts": 6,
+ "test/autopilot-parser-probe-wiring.test.ts": 3,
+ "test/autopilot-pause-marker.test.ts": 12,
+ "test/autopilot-positional-args.test.ts": 1724,
+ "test/autopilot-reconnect-classifier.test.ts": 2,
+ "test/autopilot-resolve-cli.test.ts": 16,
+ "test/autopilot-self-disable-and-status.test.ts": 16,
+ "test/autopilot-self-upgrade.test.ts": 21,
+ "test/autopilot-shutdown-engine-close.test.ts": 5,
+ "test/autopilot-supervisor-wiring.test.ts": 14,
+ "test/backfill-base.test.ts": 19,
+ "test/backlink-count-mention-filter.test.ts": 629,
+ "test/backlinks-job-default.test.ts": 2,
+ "test/backlinks.test.ts": 10100,
+ "test/backoff.test.ts": 4,
+ "test/backpressure-audit-read.test.ts": 7,
+ "test/balanced-reranker-default.test.ts": 6,
+ "test/batch-projection.test.ts": 9,
+ "test/bench-publish.test.ts": 20,
+ "test/bench/baseline-file.test.ts": 4,
+ "test/bench/correctness-gate.test.ts": 2,
+ "test/bench/qrels-file.test.ts": 15,
+ "test/binary-self-update.test.ts": 28,
+ "test/book-mirror.test.ts": 777,
+ "test/bootstrap-atomic-write.test.ts": 8,
+ "test/bootstrap-codex-door.test.ts": 18,
+ "test/bootstrap-contract.test.ts": 21,
+ "test/bootstrap-doctor-checks.test.ts": 3313,
+ "test/bootstrap-harness-writers.test.ts": 22,
+ "test/bootstrap-hooks-writers.test.ts": 10,
+ "test/bootstrap-instructions-block.test.ts": 2,
+ "test/bootstrap-lock.test.ts": 23,
+ "test/bootstrap-render.test.ts": 74,
+ "test/bootstrap-repo.test.ts": 48,
+ "test/bootstrap-verify-embedding-plane.test.ts": 493,
+ "test/bootstrap-verify-hook-carrier-overlap.test.ts": 29,
+ "test/bootstrap.test.ts": 19421,
+ "test/brain-resolver.test.ts": 9,
+ "test/brain-score-breakdown.test.ts": 2081,
+ "test/brain-score-recommendations.test.ts": 21,
+ "test/brain-writer-partial-scan.test.ts": 2360,
+ "test/brain-writer-walk-prune.test.ts": 54,
+ "test/brain-writer.test.ts": 1191,
+ "test/brainbench-adapters.test.ts": 712,
+ "test/brainbench-continuity.test.ts": 1663,
+ "test/brainbench-fixtures.test.ts": 34,
+ "test/brainbench-floors.test.ts": 6,
+ "test/brainbench-generator.test.ts": 24,
+ "test/brainbench-metrics.test.ts": 3,
+ "test/brainbench-scoreboard.test.ts": 25,
+ "test/brainbench-writeback.test.ts": 1474,
+ "test/brainstorm-timeout.test.ts": 20,
+ "test/brainstorm/cost-guardrails.test.ts": 16,
+ "test/brainstorm/distance.test.ts": 5,
+ "test/brainstorm/eval-brainstorm.test.ts": 7,
+ "test/brainstorm/judges-maxtokens.test.ts": 7,
+ "test/brainstorm/lsd-mode-skip.test.ts": 2,
+ "test/brainstorm/model-config.test.ts": 12,
+ "test/brainstorm/save.test.ts": 2074,
+ "test/budget-meter.test.ts": 15,
+ "test/budget-tracker.test.ts": 512,
+ "test/budget/free-local-chat-pricing.test.ts": 3,
+ "test/budget/pricing-overrides.test.ts": 20,
+ "test/build-llms.test.ts": 15,
+ "test/by-mention.test.ts": 525,
+ "test/cache-cli.test.ts": 4168,
+ "test/cache-scope-key.test.ts": 3,
+ "test/calibration-cli.test.ts": 12,
+ "test/calibration-profile.test.ts": 23,
+ "test/call-federated-scope.test.ts": 18,
+ "test/candidate-audit.test.ts": 12,
+ "test/canonical-migration-command.test.ts": 106,
+ "test/capability.test.ts": 4,
+ "test/capture-build-content.test.ts": 91,
+ "test/capture-explicit-type.test.ts": 25,
+ "test/capture-op.test.ts": 558,
+ "test/capture-runcapture.test.ts": 3,
+ "test/cathedral-ii-brainbench.test.ts": 899,
+ "test/chat-key-plane.test.ts": 3,
+ "test/chat-usage.test.ts": 438,
+ "test/check-bootstrap-guards.test.ts": 1760,
+ "test/check-getpage-scoped-write.test.ts": 156,
+ "test/check-jsonb-params.test.ts": 47,
+ "test/check-resolvable-cli.test.ts": 5213,
+ "test/check-resolvable-openclaw-compact.test.ts": 1,
+ "test/check-resolvable.test.ts": 164,
+ "test/check-system-of-record.test.ts": 85,
+ "test/check-update.test.ts": 1321,
+ "test/checkpoint-manifest.test.ts": 421,
+ "test/child-job-runner.test.ts": 2018,
+ "test/child-worker-supervisor.test.ts": 1949,
+ "test/chronicle-advisor.test.ts": 420,
+ "test/chronicle-backfill.test.ts": 2138,
+ "test/chronicle-capture.test.ts": 8,
+ "test/chronicle-context.test.ts": 411,
+ "test/chronicle-delight.test.ts": 436,
+ "test/chronicle-doctor.test.ts": 441,
+ "test/chronicle-extract.test.ts": 418,
+ "test/chronicle-ontology-ops.test.ts": 2110,
+ "test/chronicle-ontology-private-visibility.test.ts": 753,
+ "test/chronicle-ontology.test.ts": 426,
+ "test/chronicle-ops-scope.test.ts": 2971,
+ "test/chronicle-search-boost.test.ts": 5,
+ "test/chronicle-timeline-reads.test.ts": 434,
+ "test/chunk-grain-fts.test.ts": 965,
+ "test/chunker-timeout.test.ts": 78,
+ "test/chunker-version-gate.test.ts": 2,
+ "test/chunker-version-insert-default.test.ts": 494,
+ "test/chunkers/cap-oversized-cjk.test.ts": 192,
+ "test/chunkers/code-component-markup.test.ts": 2160,
+ "test/chunkers/code-merge-defs.test.ts": 33,
+ "test/chunkers/code.test.ts": 136,
+ "test/chunkers/embed-estimate-home.test.ts": 648,
+ "test/chunkers/recursive-cjk-overlap.test.ts": 58,
+ "test/chunkers/recursive.test.ts": 391,
+ "test/ci-local-empty-mounts.test.ts": 8,
+ "test/cite-render-closure.test.ts": 1974,
+ "test/cjk-keyword-sql.test.ts": 12,
+ "test/cjk.test.ts": 5,
+ "test/claude-cli-recipe.test.ts": 163,
+ "test/claude-code-jsonl.test.ts": 30,
+ "test/claw-test-cli.test.ts": 56,
+ "test/cli-ambient-source-fail-closed.test.ts": 1029,
+ "test/cli-args.test.ts": 7,
+ "test/cli-bigint-normalize.test.ts": 5,
+ "test/cli-concept-nudge.test.ts": 1,
+ "test/cli-dispatch-thin-client.test.ts": 12635,
+ "test/cli-dream-engine-warn.test.ts": 4467,
+ "test/cli-empty-retrieval-render.test.ts": 1,
+ "test/cli-exit-verdict-pin.test.ts": 36,
+ "test/cli-explain-degraded-render.test.ts": 24,
+ "test/cli-finish-teardown.test.ts": 2569,
+ "test/cli-flag-validation.test.ts": 2377,
+ "test/cli-force-exit-teardown-arming.test.ts": 1,
+ "test/cli-format-get-page-json.test.ts": 3,
+ "test/cli-format-history-json.test.ts": 1,
+ "test/cli-format-search-json.test.ts": 20,
+ "test/cli-format-volunteer.test.ts": 15,
+ "test/cli-help-discoverability.test.ts": 12066,
+ "test/cli-help-eval-storage-reindex.test.ts": 2637,
+ "test/cli-import-no-signal-handlers.test.ts": 430,
+ "test/cli-input-plumbing-2822.test.ts": 1464,
+ "test/cli-multimodal-integration.test.ts": 2172,
+ "test/cli-op-error-status-exit.test.ts": 7181,
+ "test/cli-options.test.ts": 3646,
+ "test/cli-pipe-truncation.test.ts": 1166,
+ "test/cli-query-image.test.ts": 57,
+ "test/cli-search-dispatch.test.ts": 11511,
+ "test/cli-should-force-exit.test.ts": 18,
+ "test/cli-stdin-hang.test.ts": 4048,
+ "test/cli-stdout-delivery.test.ts": 17124,
+ "test/cli.test.ts": 6154,
+ "test/client-slug-fence.test.ts": 44,
+ "test/code-callers-cli.test.ts": 3,
+ "test/code-def-refs-source-scope.test.ts": 525,
+ "test/code-def-refs.test.ts": 620,
+ "test/code-edges.test.ts": 2424,
+ "test/code-graph-readiness.test.ts": 762,
+ "test/code-intel-source-scope.test.ts": 2283,
+ "test/code-intel/edge-densification.test.ts": 26,
+ "test/code-intel/eval-capture-graph.test.ts": 10,
+ "test/code-intel/recursive-walk.test.ts": 3861,
+ "test/code-intel/scope-walker-resolution.test.ts": 24,
+ "test/code-intel/traversal-cache.test.ts": 2371,
+ "test/code-retrieval-harness.test.ts": 34,
+ "test/code-scoped-source-resolve.test.ts": 1131,
+ "test/codex-hook-lane-archived.test.ts": 6,
+ "test/codex-hook-lane.test.ts": 37,
+ "test/codex-hooks-writer.test.ts": 15,
+ "test/codex-plugin-manifest.test.ts": 2308,
+ "test/codex-toml.test.ts": 18,
+ "test/commands-search.test.ts": 486,
+ "test/commands/capture.test.ts": 4106,
+ "test/commands/schema-packpath.test.ts": 4,
+ "test/compile-view.test.ts": 45,
+ "test/config-adaptive-return-keys.test.ts": 25,
+ "test/config-db-merge.test.ts": 441,
+ "test/config-db-plane-round-trips.test.ts": 21,
+ "test/config-ensure-gitignore.test.ts": 10,
+ "test/config-env-hijack.test.ts": 11,
+ "test/config-env.test.ts": 0,
+ "test/config-file-plane-keys.test.ts": 31,
+ "test/config-gbrain-env-file.test.ts": 12,
+ "test/config-get-plane.test.ts": 30,
+ "test/config-set-mcp-instructions.test.ts": 8,
+ "test/config-set.test.ts": 39,
+ "test/config-show-object-values.test.ts": 8,
+ "test/config-unset.test.ts": 431,
+ "test/config.test.ts": 23,
+ "test/confirm-prompt.test.ts": 25,
+ "test/connect.test.ts": 61,
+ "test/connection-resilience.test.ts": 2,
+ "test/connectors-classify.test.ts": 5,
+ "test/connectors-config-keys.test.ts": 11,
+ "test/connectors-embed-kickoff.test.ts": 1,
+ "test/connectors-pkce.test.ts": 534,
+ "test/connectors-providers.test.ts": 5,
+ "test/console-prefix.test.ts": 4,
+ "test/consolidate-valid-until.test.ts": 789,
+ "test/content-hash-parity-3694.test.ts": 412,
+ "test/content-sanity-literals.test.ts": 4,
+ "test/content-sanity.test.ts": 20,
+ "test/context-engine.test.ts": 65,
+ "test/context/entity-salience.test.ts": 2,
+ "test/context/resolve-ipc-sweep-kinds.test.ts": 31,
+ "test/context/resolve-ipc-sync-kinds.test.ts": 49,
+ "test/context/resolve-ipc.test.ts": 40,
+ "test/context/sync-ipc-validation.test.ts": 2,
+ "test/contextual-reindex-lease-release.test.ts": 21,
+ "test/contextual-retrieval-resolver.test.ts": 5,
+ "test/contextual-retrieval-service-pure.test.ts": 224,
+ "test/conversation-facts-pricing-wiring.test.ts": 999,
+ "test/conversation-facts-type-allowlist-drift.test.ts": 807,
+ "test/conversation-parser-body.test.ts": 3,
+ "test/conversation-parser-cli.test.ts": 9,
+ "test/conversation-parser-normalize-block.test.ts": 6,
+ "test/conversation-parser-transcript-signals.test.ts": 3,
+ "test/conversation-parser/body-path-containment.test.ts": 6,
+ "test/conversation-parser/llm-base.test.ts": 9,
+ "test/conversation-parser/llm-fallback.test.ts": 13,
+ "test/conversation-parser/llm-polish.test.ts": 30,
+ "test/conversation-parser/nightly-probe.test.ts": 6,
+ "test/conversation-parser/parse.test.ts": 34,
+ "test/core/background-work.test.ts": 12,
+ "test/core/base-phase.test.ts": 5,
+ "test/core/budget/gateway-budget-composition.test.ts": 9,
+ "test/core/diarize/payload-fitter-summarize.test.ts": 10,
+ "test/core/diarize/payload-fitter.test.ts": 7,
+ "test/core/git-head.test.ts": 10,
+ "test/core/retry-reconnect.test.ts": 89,
+ "test/core/retry-stress.slow.test.ts": 153,
+ "test/core/retry.test.ts": 646,
+ "test/corpus-segments.test.ts": 27,
+ "test/corrective-containment.test.ts": 6,
+ "test/cosine-rescore-chunkless-headstart.test.ts": 5,
+ "test/cosine-rescore-column.test.ts": 420,
+ "test/creds-export.test.ts": 632,
+ "test/creds-relay-client.test.ts": 23,
+ "test/cross-brain-calibration.test.ts": 2,
+ "test/cross-modal-default-slots.test.ts": 6,
+ "test/cross-modal-eval-aggregate.test.ts": 4,
+ "test/cross-modal-eval-cli.test.ts": 27,
+ "test/cross-modal-eval-json-repair.test.ts": 8,
+ "test/cross-modal-eval-prompt.test.ts": 7,
+ "test/cross-modal-phase1.test.ts": 11,
+ "test/cross-modal-phase2.test.ts": 60,
+ "test/cycle-abort.test.ts": 122,
+ "test/cycle-any-abort-signal.test.ts": 212,
+ "test/cycle-auto-think-config-zero.test.ts": 2,
+ "test/cycle-consolidate.test.ts": 506,
+ "test/cycle-conversation-facts-backfill.test.ts": 2530,
+ "test/cycle-date.test.ts": 31,
+ "test/cycle-drain-renewal.test.ts": 66,
+ "test/cycle-dream-output-root.test.ts": 938,
+ "test/cycle-enabled-phase-completeness.test.ts": 1016,
+ "test/cycle-extract-source.test.ts": 567,
+ "test/cycle-last-full-cycle-at.test.ts": 1246,
+ "test/cycle-legacy-phases.test.ts": 2088,
+ "test/cycle-link-manifest.test.ts": 2519,
+ "test/cycle-lint-durability.test.ts": 101,
+ "test/cycle-lock-per-source.test.ts": 7,
+ "test/cycle-pack-gating.test.ts": 5,
+ "test/cycle-patterns-child-outcome.test.ts": 2267,
+ "test/cycle-patterns-deadline-budget.test.ts": 468,
+ "test/cycle-patterns-source-scope.test.ts": 421,
+ "test/cycle-patterns.test.ts": 3,
+ "test/cycle-phase-deadline-drift.test.ts": 4,
+ "test/cycle-phase-deadline.test.ts": 52,
+ "test/cycle-stale-drain.test.ts": 2589,
+ "test/cycle-stamp-write-failure.test.ts": 1518,
+ "test/cycle-start-recovery.test.ts": 447,
+ "test/cycle-summary-file-write.test.ts": 1176,
+ "test/cycle-synthesize-braindir-resolve.test.ts": 456,
+ "test/cycle-synthesize-chunker.test.ts": 23,
+ "test/cycle-synthesize-config-zero.test.ts": 18,
+ "test/cycle-synthesize-daily-cap.test.ts": 3072,
+ "test/cycle-synthesize-inline-concurrency.test.ts": 8002,
+ "test/cycle-synthesize-md-discovery.test.ts": 9,
+ "test/cycle-synthesize-slug-collection.test.ts": 445,
+ "test/cycle-synthesize-subagent-timeout.test.ts": 975,
+ "test/cycle-synthesize-summary-page.test.ts": 40,
+ "test/cycle-synthesize-triage-calibration.test.ts": 7,
+ "test/cycle-synthesize-triage.test.ts": 49,
+ "test/cycle-synthesize-verify.test.ts": 452,
+ "test/cycle-synthesize.test.ts": 25,
+ "test/cycle-triage-rescue.test.ts": 6,
+ "test/cycle-write-path-mini-eval.test.ts": 739,
+ "test/cycle/cycle-lock-ttl.test.ts": 9,
+ "test/cycle/extract-atoms-batch.test.ts": 1125,
+ "test/cycle/extract-atoms-config-caps.test.ts": 987,
+ "test/cycle/extract-atoms-model-config-fail-soft.test.ts": 561,
+ "test/cycle/extract-atoms-progress.test.ts": 1591,
+ "test/cycle/extract-atoms-quote-provenance.test.ts": 2644,
+ "test/cycle/extract-atoms-synthesize-concepts.test.ts": 8287,
+ "test/cycle/extract-atoms-work-interleave.test.ts": 2972,
+ "test/cycle/nightly-probe-adapters.test.ts": 19,
+ "test/cycle/regression-pr-wave-r1-r2-r4.test.ts": 4,
+ "test/cycle/synthesize-concepts-progress.test.ts": 804,
+ "test/cycle/synthesize-concepts-source-scope.test.ts": 1005,
+ "test/cycle/synthesize-concepts-task-model.test.ts": 2690,
+ "test/cycle/synthesize-concepts-token-cap.test.ts": 678,
+ "test/cycle/synthesize-gateway-adapter.test.ts": 19,
+ "test/cycle/yield-during-phase-refresh.test.ts": 22,
+ "test/cycle/yield-during-phase-throttle.test.ts": 944,
+ "test/dart-call-edges.test.ts": 47,
+ "test/data-research.test.ts": 6,
+ "test/database-url-guard-preload.test.ts": 492,
+ "test/db-disconnect-audit.test.ts": 6,
+ "test/db-guard-coverage.test.ts": 456,
+ "test/db-lock-auto-takeover.test.ts": 2074,
+ "test/db-lock-cross-host-wait.test.ts": 2602,
+ "test/db-lock-election.test.ts": 311,
+ "test/db-lock-fencing.test.ts": 1123,
+ "test/db-lock-heartbeat-takeover.test.ts": 504,
+ "test/db-lock-inspect.test.ts": 2480,
+ "test/db-lock-per-source.test.ts": 1372,
+ "test/db-lock-reap.test.ts": 308,
+ "test/db-lock-refresh.test.ts": 10,
+ "test/db-pacer.test.ts": 15,
+ "test/db-pool-max-lifetime.test.ts": 18,
+ "test/db-probe.test.ts": 110,
+ "test/dedup.test.ts": 5,
+ "test/deep-research-fetch.test.ts": 1317,
+ "test/default-alias-liveness.test.ts": 1,
+ "test/default-model-panels.test.ts": 7,
+ "test/default-source-path-check.test.ts": 1021,
+ "test/degraded-engine.test.ts": 79,
+ "test/degraded-stages-recall.test.ts": 5,
+ "test/delta-cursor-microseconds.test.ts": 911,
+ "test/denied-after-list.test.ts": 2163,
+ "test/destructive-guard.test.ts": 6605,
+ "test/detached-stderr.test.ts": 1,
+ "test/disk-walk.test.ts": 30,
+ "test/dispatch-localonly.test.ts": 302,
+ "test/distribution-import-boundary.test.ts": 4,
+ "test/docker-postgres.test.ts": 4,
+ "test/docs-cli-commands.test.ts": 82,
+ "test/doctor-abandoned-threads-month-precision.test.ts": 453,
+ "test/doctor-asset-paths.test.ts": 5,
+ "test/doctor-atom-provenance-drift.test.ts": 3640,
+ "test/doctor-batch-retry.test.ts": 9,
+ "test/doctor-behavioral.test.ts": 5168,
+ "test/doctor-brain-checks-score.test.ts": 23,
+ "test/doctor-brainstorm-health.test.ts": 1756,
+ "test/doctor-calibration-checks.test.ts": 22,
+ "test/doctor-categories.test.ts": 11,
+ "test/doctor-cause-rank.test.ts": 8,
+ "test/doctor-chat-fallback-chain.test.ts": 24,
+ "test/doctor-child-orphans.test.ts": 19,
+ "test/doctor-conversation-facts-backlog.test.ts": 999,
+ "test/doctor-conversation-format-coverage.test.ts": 1015,
+ "test/doctor-cycle-freshness.test.ts": 1795,
+ "test/doctor-cycle-phase-scope.test.ts": 1,
+ "test/doctor-drift-advice.test.ts": 16,
+ "test/doctor-effective-date-health.test.ts": 6928,
+ "test/doctor-embedding-env-override.test.ts": 2732,
+ "test/doctor-extract-atoms-backlog.test.ts": 4863,
+ "test/doctor-extract-health.test.ts": 422,
+ "test/doctor-fast-supervisor.test.ts": 459,
+ "test/doctor-federation-health.test.ts": 1383,
+ "test/doctor-fix.test.ts": 3261,
+ "test/doctor-frontmatter-partial.test.ts": 18,
+ "test/doctor-graph-coverage-inbound.test.ts": 2423,
+ "test/doctor-graph-coverage-soft-deleted.test.ts": 1663,
+ "test/doctor-hidden-by-search-policy.test.ts": 1617,
+ "test/doctor-home-dir-in-worktree.test.ts": 592,
+ "test/doctor-image-assets-wsl.test.ts": 3481,
+ "test/doctor-image-assets.test.ts": 24,
+ "test/doctor-links-extraction-lag.test.ts": 1982,
+ "test/doctor-memorable.test.ts": 24,
+ "test/doctor-memory-verbs-check.test.ts": 19,
+ "test/doctor-minions-check.test.ts": 2408,
+ "test/doctor-oauth-client-scope-health.test.ts": 438,
+ "test/doctor-orphan-ratio.test.ts": 8872,
+ "test/doctor-parser-probe-check.test.ts": 7,
+ "test/doctor-pglite-datadir.test.ts": 65,
+ "test/doctor-pglite-scratch-probe.test.ts": 6676,
+ "test/doctor-pool-reap-health.test.ts": 14,
+ "test/doctor-queue-divergence.test.ts": 1868,
+ "test/doctor-raw-provenance.test.ts": 367,
+ "test/doctor-remediation-plan-render.test.ts": 12,
+ "test/doctor-reranker-health.test.ts": 14,
+ "test/doctor-retrieval-reflex.test.ts": 43,
+ "test/doctor-schema-column-diff.test.ts": 510,
+ "test/doctor-schema-pack-checks.test.ts": 4262,
+ "test/doctor-schema-pack-db-config.test.ts": 23,
+ "test/doctor-schema-version-forward-skew.test.ts": 1715,
+ "test/doctor-scope-filter.test.ts": 207,
+ "test/doctor-search-mode.test.ts": 1562,
+ "test/doctor-self-upgrade.test.ts": 96,
+ "test/doctor-silent-death-checks.test.ts": 7648,
+ "test/doctor-skill-checks.test.ts": 365,
+ "test/doctor-skills-dir.test.ts": 232,
+ "test/doctor-source-config-shape.test.ts": 4,
+ "test/doctor-stale-lock-hints.test.ts": 978,
+ "test/doctor-stale-mentions.test.ts": 1797,
+ "test/doctor-subagent-capability.test.ts": 3,
+ "test/doctor-subagent-health.test.ts": 501,
+ "test/doctor-supervisor-singleton-pidfile.test.ts": 1990,
+ "test/doctor-sync-consolidation.test.ts": 1244,
+ "test/doctor-timeline-metric-labels-2298.test.ts": 2796,
+ "test/doctor-upgrade-errors-stale.test.ts": 16,
+ "test/doctor-upgrade-errors.test.ts": 25,
+ "test/doctor-v0_37_7_checks.test.ts": 427,
+ "test/doctor-v0_41_13_checks.test.ts": 3585,
+ "test/doctor-volunteer-channels.test.ts": 12,
+ "test/doctor-wedged-queue.test.ts": 757,
+ "test/doctor-worker-oom-loop.test.ts": 40,
+ "test/doctor-ze-checks.test.ts": 1170,
+ "test/doctor.test.ts": 5005,
+ "test/domain-aggregators.test.ts": 2635,
+ "test/dream-clean-status-skip-visibility.test.ts": 19,
+ "test/dream-cli-flags.test.ts": 13,
+ "test/dream-dir-source-stamp.test.ts": 1218,
+ "test/dream-env-source-scope.test.ts": 1446,
+ "test/dream-keyless-exit.test.ts": 9854,
+ "test/dream-retriage.test.ts": 4122,
+ "test/dream-verdict-cache-ttl.test.ts": 499,
+ "test/dream.test.ts": 7806,
+ "test/drift-watch.test.ts": 168,
+ "test/dry-fix.test.ts": 201,
+ "test/durability-cron.test.ts": 15,
+ "test/edge-extractor.test.ts": 194,
+ "test/effective-date.test.ts": 17,
+ "test/embed-backfill-submit.test.ts": 518,
+ "test/embed-helper-migration.test.ts": 1,
+ "test/embed-keyless-guard.test.ts": 3,
+ "test/embed-modality-preserved.test.ts": 470,
+ "test/embed-multimodal-batching.test.ts": 21,
+ "test/embed-oversize-heal.test.ts": 93,
+ "test/embed-preflight.test.ts": 5,
+ "test/embed-reuse.test.ts": 7,
+ "test/embed-skip.test.ts": 5,
+ "test/embed-stall.test.ts": 399,
+ "test/embedding-context.test.ts": 2,
+ "test/embedding-dim-check-facts.test.ts": 28,
+ "test/embedding-dim-check.test.ts": 4028,
+ "test/embedding-input-limit.test.ts": 41,
+ "test/embedding-migration.test.ts": 6250,
+ "test/embedding-model-dims.test.ts": 4,
+ "test/embedding-pricing.test.ts": 13,
+ "test/embedding-signature-stale.test.ts": 1073,
+ "test/emotional-weight.test.ts": 16,
+ "test/engine-factory.test.ts": 4,
+ "test/engine-find-trajectory.test.ts": 479,
+ "test/engine-keyset-microseconds.test.ts": 509,
+ "test/engine-parity-event-type.test.ts": 355,
+ "test/engine-resolve-slug-with-alias.test.ts": 3672,
+ "test/engine-status.test.ts": 4865,
+ "test/engine-surface-coverage.test.ts": 1143,
+ "test/engine-upsertFile.test.ts": 1338,
+ "test/engine-weight-rounding-integration.test.ts": 456,
+ "test/enrich-cycle-phase.test.ts": 1473,
+ "test/enrich/budget-message.test.ts": 0,
+ "test/enrich/evidence-order.test.ts": 1218,
+ "test/enrich/idempotency.test.ts": 3,
+ "test/enrich/thin.test.ts": 8,
+ "test/enrichable-pack.test.ts": 14,
+ "test/enrichment-service.test.ts": 6,
+ "test/enrichment.test.ts": 2392,
+ "test/entity-card-loops.test.ts": 2474,
+ "test/entity-card-perf.slow.test.ts": 41911,
+ "test/entity-hints-cap.test.ts": 388,
+ "test/entity-identity.test.ts": 656,
+ "test/entity-resolve-perf.slow.test.ts": 5297,
+ "test/entity-resolve-prefix-dirs.test.ts": 413,
+ "test/entity-resolve-slug-fallback.test.ts": 366,
+ "test/entity-resolve.test.ts": 479,
+ "test/env-number.test.ts": 4,
+ "test/envelope-to-gbrain.test.ts": 3075,
+ "test/error-classify.test.ts": 24,
+ "test/errors.test.ts": 6,
+ "test/eval-canary.test.ts": 6766,
+ "test/eval-candidates.test.ts": 424,
+ "test/eval-capture-drain.test.ts": 157,
+ "test/eval-capture-scrub.test.ts": 5,
+ "test/eval-capture.test.ts": 25,
+ "test/eval-chronicle.test.ts": 427,
+ "test/eval-compare.test.ts": 19,
+ "test/eval-contradictions-auto-supersession.test.ts": 48,
+ "test/eval-contradictions-cache.test.ts": 2466,
+ "test/eval-contradictions-calibration-join.test.ts": 2,
+ "test/eval-contradictions-calibration.test.ts": 4,
+ "test/eval-contradictions-cost-prompt.test.ts": 3637,
+ "test/eval-contradictions-cost.test.ts": 3,
+ "test/eval-contradictions-cross-source.test.ts": 6,
+ "test/eval-contradictions-date-filter.test.ts": 6,
+ "test/eval-contradictions-engine.test.ts": 3087,
+ "test/eval-contradictions-fixture-redact.test.ts": 5,
+ "test/eval-contradictions-integrations.test.ts": 1777,
+ "test/eval-contradictions-judge-errors.test.ts": 4,
+ "test/eval-contradictions-judge.test.ts": 20,
+ "test/eval-contradictions-run-health.test.ts": 7,
+ "test/eval-contradictions-runner.test.ts": 4729,
+ "test/eval-contradictions-severity.test.ts": 6,
+ "test/eval-contradictions-trends.test.ts": 1718,
+ "test/eval-contradictions/cost-tracker-slash.test.ts": 9,
+ "test/eval-contradictions/no-valid-until-write.test.ts": 46,
+ "test/eval-conversation-parser-cli.test.ts": 16,
+ "test/eval-cross-modal-batch.test.ts": 108,
+ "test/eval-export.test.ts": 322,
+ "test/eval-gate.test.ts": 4215,
+ "test/eval-longmemeval-cli-smoke.test.ts": 5064,
+ "test/eval-longmemeval-gateway-routing.test.ts": 9363,
+ "test/eval-longmemeval-judge.slow.test.ts": 4196,
+ "test/eval-longmemeval-mixedcase.slow.test.ts": 8978,
+ "test/eval-longmemeval-parse-args.test.ts": 18,
+ "test/eval-longmemeval-search-config.test.ts": 1413,
+ "test/eval-longmemeval.slow.test.ts": 2809,
+ "test/eval-prune.test.ts": 420,
+ "test/eval-replay-gate.test.ts": 1807,
+ "test/eval-replay-metadata-skip.test.ts": 681,
+ "test/eval-replay.test.ts": 22,
+ "test/eval-retrieval-quality.test.ts": 648,
+ "test/eval-run-all.test.ts": 18,
+ "test/eval-schema-authoring.test.ts": 15,
+ "test/eval-shared-json-repair-shim.test.ts": 1,
+ "test/eval-spend-guard.test.ts": 4541,
+ "test/eval-suspected-contradictions-budget-default.test.ts": 9,
+ "test/eval-synthesize-concepts-routing.test.ts": 617,
+ "test/eval-takes-bootstrap.test.ts": 193,
+ "test/eval-takes-quality-aggregate.test.ts": 9,
+ "test/eval-takes-quality-boundaries.test.ts": 421,
+ "test/eval-takes-quality-cli.test.ts": 17,
+ "test/eval-takes-quality-pricing.test.ts": 14,
+ "test/eval-takes-quality-receipt-name.test.ts": 6,
+ "test/eval-takes-quality-receipt-write.test.ts": 364,
+ "test/eval-takes-quality-regress.test.ts": 6,
+ "test/eval-takes-quality-replay.test.ts": 357,
+ "test/eval-takes-quality-rubric.test.ts": 3,
+ "test/eval-takes-quality-trend.test.ts": 379,
+ "test/eval-trajectory.test.ts": 411,
+ "test/eval-v041_2-scaffolds.test.ts": 1,
+ "test/eval-whoknows.test.ts": 23,
+ "test/eval.test.ts": 9,
+ "test/eval/cycle-default.test.ts": 21,
+ "test/execution-env.test.ts": 17,
+ "test/exit-classification.test.ts": 22,
+ "test/expert-types-pack.test.ts": 18,
+ "test/explicit-skills-dir-readonly.test.ts": 859,
+ "test/export-import-slug-roundtrip.test.ts": 826,
+ "test/extract-abort.test.ts": 2027,
+ "test/extract-atoms-array-anchor-scan.test.ts": 23,
+ "test/extract-atoms-chunk-embed.test.ts": 2118,
+ "test/extract-atoms-drain-errors.test.ts": 14,
+ "test/extract-atoms-drain-handler.test.ts": 501,
+ "test/extract-atoms-drain.test.ts": 10,
+ "test/extract-atoms-embed-cost-gate.test.ts": 2113,
+ "test/extract-atoms-empty-array-rule.test.ts": 548,
+ "test/extract-atoms-extractable-types.test.ts": 10,
+ "test/extract-atoms-failure-classes.test.ts": 4811,
+ "test/extract-atoms-page-discovery.test.ts": 4779,
+ "test/extract-atoms-provenance-links.test.ts": 933,
+ "test/extract-atoms-transcript-failure-classes.test.ts": 2084,
+ "test/extract-atoms-transcript-state-errors.test.ts": 426,
+ "test/extract-atoms-unpriced-model.test.ts": 135,
+ "test/extract-by-mention-rebuild.test.ts": 622,
+ "test/extract-by-mention-resume.test.ts": 477,
+ "test/extract-by-mention.test.ts": 637,
+ "test/extract-conversation-facts-entity-resolution.test.ts": 1593,
+ "test/extract-conversation-facts-workers.test.ts": 10,
+ "test/extract-conversation-facts.test.ts": 2647,
+ "test/extract-cross-source-links.test.ts": 7,
+ "test/extract-cross-source-resolution-observability.test.ts": 22,
+ "test/extract-db.test.ts": 584,
+ "test/extract-explain.test.ts": 37,
+ "test/extract-facts-guard-rollup.test.ts": 15,
+ "test/extract-facts-phase.test.ts": 6700,
+ "test/extract-from-fence.test.ts": 22,
+ "test/extract-fs-source-id.test.ts": 1003,
+ "test/extract-fs.test.ts": 608,
+ "test/extract-incremental.test.ts": 4504,
+ "test/extract-rollup-expected-limit.test.ts": 435,
+ "test/extract-source-aware.test.ts": 519,
+ "test/extract-stale.test.ts": 772,
+ "test/extract-stamp-source-3957.test.ts": 2623,
+ "test/extract-takes-from-pages-progression.test.ts": 472,
+ "test/extract-takes-holder-producer-seam.test.ts": 472,
+ "test/extract-takes-md-first.test.ts": 412,
+ "test/extract-takes-model-resolution.test.ts": 3990,
+ "test/extract-takes.test.ts": 432,
+ "test/extract-timeline-from-meetings.test.ts": 2071,
+ "test/extract-workers.test.ts": 18,
+ "test/extract.test.ts": 11,
+ "test/extract/benchmark.test.ts": 2,
+ "test/extract/receipt-writer.test.ts": 1011,
+ "test/extract/status.test.ts": 3,
+ "test/extractable-pack.test.ts": 23,
+ "test/extractable-spec-widening.test.ts": 19,
+ "test/extraction-review.test.ts": 4407,
+ "test/facts-absorb-log.test.ts": 2291,
+ "test/facts-anti-loop.test.ts": 385,
+ "test/facts-backstop-gating.test.ts": 592,
+ "test/facts-backstop-integration.test.ts": 472,
+ "test/facts-backstop-remedy-verb.test.ts": 6,
+ "test/facts-backstop.test.ts": 608,
+ "test/facts-canonicality.test.ts": 393,
+ "test/facts-classify.test.ts": 1,
+ "test/facts-decay.test.ts": 19,
+ "test/facts-doctor-shape.test.ts": 418,
+ "test/facts-eligibility.test.ts": 7,
+ "test/facts-engine.test.ts": 2238,
+ "test/facts-extract-idea-kind.test.ts": 27,
+ "test/facts-extract-junk-filter.test.ts": 20,
+ "test/facts-extract-salvage.test.ts": 124,
+ "test/facts-extract-silent-no-op.test.ts": 30,
+ "test/facts-extract-smoke.test.ts": 12,
+ "test/facts-extract-truncation.test.ts": 1,
+ "test/facts-extract.test.ts": 4,
+ "test/facts-fallback-stub-guard.test.ts": 470,
+ "test/facts-fence-typed.test.ts": 9,
+ "test/facts-fence.test.ts": 15,
+ "test/facts-meta-cache.test.ts": 552,
+ "test/facts-migration-dim.test.ts": 2684,
+ "test/facts-multi-tenant.test.ts": 382,
+ "test/facts-pipeline-budget-accounting.test.ts": 958,
+ "test/facts-queue-drain-pending.test.ts": 1601,
+ "test/facts-queue.test.ts": 610,
+ "test/facts-recall-audit-rows.test.ts": 1474,
+ "test/facts-recall-event-time-op.test.ts": 2072,
+ "test/facts-recall-grep-sql.test.ts": 430,
+ "test/facts-recall-render.test.ts": 470,
+ "test/facts-recall-since-composition.test.ts": 447,
+ "test/facts-reconcile-protect-cli.test.ts": 430,
+ "test/facts-separation-pglite.test.ts": 410,
+ "test/facts-thin-client-provenance.test.ts": 451,
+ "test/facts-unknown-speaker-gate.test.ts": 9,
+ "test/facts-visibility.test.ts": 2135,
+ "test/facts/ttl-validity.test.ts": 386,
+ "test/facts/writeback-gate.test.ts": 19,
+ "test/fail-improve.test.ts": 136,
+ "test/feature-flags.test.ts": 1122,
+ "test/features-no-sync.test.ts": 6,
+ "test/features-recipe-secrets.test.ts": 18,
+ "test/features.test.ts": 11,
+ "test/fence-extraction.test.ts": 1711,
+ "test/fence-write.test.ts": 1324,
+ "test/file-migration.test.ts": 7,
+ "test/file-resolver.test.ts": 30,
+ "test/file-upload-engine-context.test.ts": 435,
+ "test/file-upload-fail-closed.test.ts": 403,
+ "test/file-upload-remote-default.test.ts": 282,
+ "test/file-upload-security.test.ts": 11,
+ "test/files.test.ts": 707,
+ "test/filing-audit.test.ts": 23,
+ "test/find-experts-op.test.ts": 492,
+ "test/fix-wave-structural.test.ts": 22,
+ "test/flush-then-exit-harness.test.ts": 2160,
+ "test/forget-reconcile-durability.test.ts": 5623,
+ "test/founder-scorecard.test.ts": 69,
+ "test/friction-cli.test.ts": 11,
+ "test/friction.test.ts": 25,
+ "test/frontmatter-cli.test.ts": 1326,
+ "test/frontmatter-inference.test.ts": 21,
+ "test/frontmatter-install-hook.test.ts": 58,
+ "test/frontmatter-non-string-fields.test.ts": 20,
+ "test/frontmatter-validate-slug-565.test.ts": 1756,
+ "test/fuzz/filesystem-validators.test.ts": 22,
+ "test/fuzz/mixed-validators.test.ts": 117,
+ "test/fuzz/pure-validators.test.ts": 73,
+ "test/gateway-embed-model-override.test.ts": 21,
+ "test/gateway-model-messages.test.ts": 10,
+ "test/gbrain-home-isolation.test.ts": 6,
+ "test/gbrain-to-envelope.test.ts": 1908,
+ "test/generate-flag-registry.test.ts": 393,
+ "test/get-agent-job.test.ts": 2173,
+ "test/get-brain-identity.test.ts": 1747,
+ "test/get-job-stats-op.test.ts": 451,
+ "test/get-page-alias-hop-errors.test.ts": 4481,
+ "test/get-page-content-roundtrip-2225.test.ts": 523,
+ "test/get-page-federated-scope.test.ts": 10389,
+ "test/get-page-unknown-source-4620.test.ts": 374,
+ "test/get-status-snapshot-op.test.ts": 0,
+ "test/get-timeline-op.test.ts": 60,
+ "test/git-remote.test.ts": 362,
+ "test/git-visible-files.test.ts": 314,
+ "test/github-source-demo.test.ts": 9,
+ "test/github-source-materialize.test.ts": 6335,
+ "test/github-source-page.test.ts": 2337,
+ "test/google-access.test.ts": 24,
+ "test/google-auth.test.ts": 17,
+ "test/google-clients.test.ts": 1541,
+ "test/google-loop-detect.test.ts": 22,
+ "test/google-oauth-doctor.test.ts": 16,
+ "test/google-redirect.test.ts": 118,
+ "test/google-render.test.ts": 12,
+ "test/google-source-config.test.ts": 10,
+ "test/google-source-materialize.test.ts": 4223,
+ "test/google-source-reconcile.test.ts": 5153,
+ "test/grade-takes-ensemble.test.ts": 32,
+ "test/grade-takes-evidence.test.ts": 494,
+ "test/grade-takes.test.ts": 26,
+ "test/graph-query.test.ts": 646,
+ "test/gstack-learnings-coupling.test.ts": 15,
+ "test/guardrails-env-load.test.ts": 7,
+ "test/guardrails.test.ts": 31,
+ "test/handlers-embed-backfill.test.ts": 1480,
+ "test/handlers.test.ts": 2595,
+ "test/health-islanded-liveness.test.ts": 552,
+ "test/health-soft-delete.test.ts": 559,
+ "test/helpers/agent-harness.unit.test.ts": 36,
+ "test/helpers/cli-spawn.test.ts": 819,
+ "test/helpers/git-fixture.test.ts": 143,
+ "test/helpers/reset-pglite-narrow.test.ts": 1569,
+ "test/helpers/schema-diff-indexes.test.ts": 9,
+ "test/helpers/schema-diff.test.ts": 6,
+ "test/helpers/wait-for.test.ts": 137,
+ "test/helpers/with-env.test.ts": 2,
+ "test/helpers/with-snapshot.test.ts": 4,
+ "test/http-degraded-health.test.ts": 24,
+ "test/http-transport.test.ts": 202,
+ "test/hybrid-arm-rethrow.test.ts": 1,
+ "test/hybrid-recency-config.test.ts": 6,
+ "test/import-abort-error.test.ts": 7,
+ "test/import-checkpoint.test.ts": 9,
+ "test/import-clear-failures-on-success.test.ts": 494,
+ "test/import-code-edges-source-id.test.ts": 562,
+ "test/import-dedup-frontmatter-id.test.ts": 2686,
+ "test/import-default-write-guard-once.test.ts": 1947,
+ "test/import-default-write-warn-destination.test.ts": 499,
+ "test/import-error-summary.test.ts": 6,
+ "test/import-file-content-sanity.test.ts": 6492,
+ "test/import-file.test.ts": 152,
+ "test/import-git-fastpath-prune.test.ts": 37,
+ "test/import-image-file.test.ts": 1952,
+ "test/import-metafile-skip.test.ts": 16,
+ "test/import-repo-path-guard.test.ts": 1153,
+ "test/import-resume.test.ts": 1689,
+ "test/import-source-id-bookkeeping.test.ts": 468,
+ "test/import-source-id-last-sync-at.test.ts": 4176,
+ "test/import-source-id.test.ts": 688,
+ "test/import-walker.test.ts": 30,
+ "test/import-yaml-frontmatter.test.ts": 18,
+ "test/incremental-chunking.test.ts": 633,
+ "test/infer-type-pack.test.ts": 14,
+ "test/ingest-log-noop-gate.test.ts": 467,
+ "test/ingestion/daemon.test.ts": 74,
+ "test/ingestion/dedup.test.ts": 3,
+ "test/ingestion/gstack-learnings.test.ts": 7,
+ "test/ingestion/ingest-capture.test.ts": 7693,
+ "test/ingestion/markdown-greenfield.test.ts": 11,
+ "test/ingestion/migration-mode.test.ts": 20,
+ "test/ingestion/put-page-write-through.test.ts": 2146,
+ "test/ingestion/skillpack-load.test.ts": 11,
+ "test/ingestion/sources/file-watcher.test.ts": 482,
+ "test/ingestion/sources/inbox-folder.test.ts": 509,
+ "test/ingestion/test-harness.test.ts": 59,
+ "test/ingestion/types.test.ts": 9,
+ "test/init-embed-check.test.ts": 8,
+ "test/init-env-detection.test.ts": 14,
+ "test/init-force-engine-preservation.test.ts": 6383,
+ "test/init-mcp-only.test.ts": 7100,
+ "test/init-migrate-only.test.ts": 6464,
+ "test/init-mode-picker.test.ts": 487,
+ "test/init-nudge.test.ts": 7,
+ "test/init-prefer-postgres.test.ts": 3761,
+ "test/init-provider-picker.test.ts": 13,
+ "test/init-reranker-default.test.ts": 14,
+ "test/init-schema-lock.test.ts": 4,
+ "test/inline-drain-keepalive.test.ts": 6417,
+ "test/insert-facts-batch.test.ts": 415,
+ "test/integrations-getstatus-anyof.test.ts": 8,
+ "test/integrations-heartbeat-max-age.test.ts": 26,
+ "test/integrations-install.test.ts": 183,
+ "test/integrations.test.ts": 41,
+ "test/integrity.test.ts": 3378,
+ "test/intent-weights.test.ts": 5,
+ "test/job-isolation-protocol.test.ts": 63,
+ "test/job-pull-policy.test.ts": 26,
+ "test/jobs-agent-scope.test.ts": 541,
+ "test/jobs-format-detail.test.ts": 10,
+ "test/jobs-gateway-refresh-set.test.ts": 5,
+ "test/jobs-isolation-flag.test.ts": 14,
+ "test/jobs-lifecycle-ops.test.ts": 4064,
+ "test/jobs-nice-flag.test.ts": 18,
+ "test/jobs-ops-token-redaction.test.ts": 1246,
+ "test/jobs-sidechannel-fence.test.ts": 2177,
+ "test/jobs-submit-identity-stamp.test.ts": 414,
+ "test/jobs-thin-client-date-rehydration.test.ts": 1,
+ "test/jobs-unify-types-default-dryrun.test.ts": 505,
+ "test/jobs-watch-mode.test.ts": 2,
+ "test/jobs-watch-snapshot.test.ts": 25,
+ "test/jobs-worker-startup-recovery.test.ts": 446,
+ "test/junk-entity-guards.test.ts": 576,
+ "test/language-manifest.test.ts": 92,
+ "test/last-retrieved.test.ts": 292,
+ "test/latin-fold.test.ts": 2,
+ "test/lease-cap-controller.test.ts": 284,
+ "test/legacy-token-federated-scope.test.ts": 5,
+ "test/lens-pack-manifests.test.ts": 26,
+ "test/levenshtein.test.ts": 3,
+ "test/link-extraction-code-refs.test.ts": 19,
+ "test/link-extraction-dir-whitelist-2576.test.ts": 21,
+ "test/link-extraction-pack-3190.test.ts": 445,
+ "test/link-extraction-relative-path.test.ts": 8,
+ "test/link-extraction.test.ts": 54,
+ "test/link-inference-pack.test.ts": 15,
+ "test/link-source-namespaced-regex.test.ts": 586,
+ "test/links-timeline-jsonb-poison.test.ts": 3935,
+ "test/lint-3958.test.ts": 11,
+ "test/lint-content-sanity.test.ts": 39,
+ "test/lint-fix-single-pass.test.ts": 32,
+ "test/lint-frontmatter.test.ts": 4,
+ "test/lint-shared-engine.test.ts": 8,
+ "test/lint.test.ts": 29,
+ "test/list-all-sources.test.ts": 2207,
+ "test/list-clamp-local-trust.test.ts": 547,
+ "test/list-pages-slug-total-order.test.ts": 420,
+ "test/list-pages-source-scope.test.ts": 3,
+ "test/list-pages-truncation.test.ts": 1847,
+ "test/list-pages-updated-asc-total-order.test.ts": 2106,
+ "test/llm-halt-cooldown.test.ts": 9,
+ "test/llm-intent-escalation.test.ts": 8,
+ "test/llm-json-reasoning-ladder.test.ts": 30,
+ "test/loadConfig-merge.test.ts": 17,
+ "test/local-federated-search-scope.test.ts": 2129,
+ "test/lock-keys.test.ts": 9,
+ "test/longmemeval-capture.test.ts": 4,
+ "test/longmemeval-diagnostics.test.ts": 1403,
+ "test/longmemeval-embed-cache.test.ts": 87,
+ "test/longmemeval-emit.test.ts": 28,
+ "test/longmemeval-extract.test.ts": 511,
+ "test/longmemeval-intent.test.ts": 7,
+ "test/longmemeval-judge.test.ts": 40,
+ "test/longmemeval-metrics.test.ts": 23,
+ "test/longmemeval-reader.test.ts": 8,
+ "test/longmemeval-resume.test.ts": 26,
+ "test/longmemeval-run-config.test.ts": 11,
+ "test/longmemeval-sanitize.test.ts": 17,
+ "test/longmemeval-splits-fixture.test.ts": 6,
+ "test/longmemeval-trajectory-routing.test.ts": 2909,
+ "test/loop-apply.test.ts": 1982,
+ "test/loops-cli.test.ts": 4386,
+ "test/loops-extract-eligibility.test.ts": 7,
+ "test/loops-extract-parse.test.ts": 7,
+ "test/loops-extract-wiring.test.ts": 7,
+ "test/loops-store.test.ts": 2972,
+ "test/maintain.test.ts": 1,
+ "test/markdown-leading-blank-frontmatter.test.ts": 16,
+ "test/markdown-serializer.test.ts": 508,
+ "test/markdown-validation.test.ts": 3,
+ "test/markdown.test.ts": 17,
+ "test/mcp-client-hardening.test.ts": 285,
+ "test/mcp-client.test.ts": 2219,
+ "test/mcp-default-write-advisory.test.ts": 4,
+ "test/mcp-dispatch-db-error.test.ts": 4,
+ "test/mcp-dispatch-optional-params.test.ts": 398,
+ "test/mcp-dispatch-summarize.test.ts": 1,
+ "test/mcp-eval-capture.test.ts": 853,
+ "test/mcp-instructions-writeback.test.ts": 30,
+ "test/mcp-registration-blocks.test.ts": 6,
+ "test/mcp-server-identity.test.ts": 4,
+ "test/mcp-stdio-gate-list.test.ts": 20,
+ "test/mcp-stdio-source-preflight.test.ts": 4,
+ "test/mcp-stdio-source-resolution.test.ts": 22,
+ "test/mcp-surface.test.ts": 397,
+ "test/mcp-tool-defs.test.ts": 30,
+ "test/mcp-usage.test.ts": 394,
+ "test/memory-verbs-conformance.test.ts": 6363,
+ "test/metric-glossary.test.ts": 10,
+ "test/migrate-engine-resume.test.ts": 11,
+ "test/migrate-extensions.test.ts": 2,
+ "test/migrate-retry.test.ts": 112,
+ "test/migrate-stdout-clean.test.ts": 502,
+ "test/migrate-timeline-full-copy.test.ts": 1052,
+ "test/migrate-timestamps-removelink-count.test.ts": 690,
+ "test/migrate.test.ts": 8470,
+ "test/migration-ledger.test.ts": 432,
+ "test/migration-orchestrator-v0_21_0.test.ts": 13,
+ "test/migration-orchestrator-v0_31_0.test.ts": 672,
+ "test/migration-resume.test.ts": 15,
+ "test/migration-v120.test.ts": 322,
+ "test/migrations-cjk-wave.test.ts": 382,
+ "test/migrations-registry.test.ts": 12,
+ "test/migrations-v0_11_0.test.ts": 20,
+ "test/migrations-v0_12_0.test.ts": 7,
+ "test/migrations-v0_12_2.test.ts": 0,
+ "test/migrations-v0_13_0.test.ts": 6,
+ "test/migrations-v0_13_1-grandfather.test.ts": 3195,
+ "test/migrations-v0_13_1.test.ts": 3,
+ "test/migrations-v0_14_0.test.ts": 33,
+ "test/migrations-v0_16_0.test.ts": 1,
+ "test/migrations-v0_19_0.test.ts": 2571,
+ "test/migrations-v0_21_0.test.ts": 8,
+ "test/migrations-v0_22_4.test.ts": 1,
+ "test/migrations-v0_27_1.test.ts": 407,
+ "test/migrations-v0_32_2.test.ts": 557,
+ "test/migrations-v126.test.ts": 1126,
+ "test/migrations-v128.test.ts": 505,
+ "test/migrations-v130.test.ts": 477,
+ "test/migrations-v131.test.ts": 432,
+ "test/migrations-v136.test.ts": 476,
+ "test/migrations-v145.test.ts": 389,
+ "test/migrations-v48-takes-weight-backfill.test.ts": 396,
+ "test/migrations-v94.test.ts": 2369,
+ "test/migrations-v99.test.ts": 1442,
+ "test/minion-queue-renewlock-signal.test.ts": 5,
+ "test/minions-admission.test.ts": 2451,
+ "test/minions-lease-full-retry.test.ts": 466,
+ "test/minions-quiet-hours.test.ts": 2554,
+ "test/minions-shell-inherit.test.ts": 7,
+ "test/minions-shell-redact.test.ts": 21,
+ "test/minions-shell-validate.test.ts": 6,
+ "test/minions-shell.test.ts": 2266,
+ "test/minions.test.ts": 9555,
+ "test/minions/agent-audit.test.ts": 10,
+ "test/minions/budget-meter.test.ts": 3890,
+ "test/minions/dream-quota-degradation.test.ts": 1713,
+ "test/minions/generic-handler-spend-attribution.test.ts": 350,
+ "test/minions/subagent-oneshot.test.ts": 8537,
+ "test/mode-switch-ux.test.ts": 889,
+ "test/model-id.test.ts": 6,
+ "test/model-pricing.test.ts": 8,
+ "test/models-doctor-chat-probe-timeout.slow.test.ts": 10506,
+ "test/models-doctor-chat-probe-timeout.test.ts": 5,
+ "test/models-doctor-embed.test.ts": 26,
+ "test/models-doctor-reranker.test.ts": 9,
+ "test/models-doctor-v1-hint.test.ts": 14,
+ "test/modes-report-reranker.test.ts": 1,
+ "test/mounts-cache.test.ts": 34,
+ "test/mounts-cli.test.ts": 302,
+ "test/multi-source-drift.test.ts": 1094,
+ "test/multi-source-integration.test.ts": 474,
+ "test/niceness.test.ts": 34,
+ "test/nightly-probe-config-plane.test.ts": 14,
+ "test/nightly-quality-probe.test.ts": 16,
+ "test/no-grant-federated-scope.test.ts": 355,
+ "test/no-tracked-symlinks-guard.test.ts": 35,
+ "test/notability-eval.test.ts": 29,
+ "test/npm-squat-check.test.ts": 4,
+ "test/nudge.test.ts": 2,
+ "test/oauth-authorize-scope-default.test.ts": 448,
+ "test/oauth-confidential-client.test.ts": 458,
+ "test/oauth-dcr-ttl.test.ts": 2825,
+ "test/oauth-refresh-invalid-grant.test.ts": 2754,
+ "test/oauth-scope-probe.test.ts": 7,
+ "test/oauth-surface-ladder.test.ts": 2956,
+ "test/oauth.test.ts": 3366,
+ "test/ocr-run-budget.test.ts": 3255,
+ "test/ollama-recipe.test.ts": 3,
+ "test/onboard-coverage-invariants.test.ts": 1003,
+ "test/onboard-pack-upgrade-checks.test.ts": 2516,
+ "test/onboard-phantom-rec-gates.test.ts": 1946,
+ "test/op-checkpoint-mentions-fingerprint.test.ts": 20,
+ "test/op-checkpoint.test.ts": 4932,
+ "test/openai-compat-multimodal.test.ts": 25,
+ "test/openclaw-plugin-manifest.test.ts": 26,
+ "test/opencode-json.test.ts": 45,
+ "test/openrouter-reranker-recipe.test.ts": 3,
+ "test/operation-context-sourceid-required.test.ts": 1,
+ "test/operations-allow-list.test.ts": 11,
+ "test/operations-coverage-ledger.test.ts": 6,
+ "test/operations-descriptions.test.ts": 10,
+ "test/operations-embedding-column.test.ts": 2,
+ "test/operations-find-trajectory.test.ts": 575,
+ "test/operations-fuzzy-source-scope.test.ts": 1372,
+ "test/operations-schema-pack.test.ts": 5560,
+ "test/operations-source-isolation-matrix.test.ts": 1336,
+ "test/operations-trust-boundary.test.ts": 3759,
+ "test/operator-env-preload.test.ts": 688,
+ "test/ops-loops.test.ts": 5677,
+ "test/ops-search-types.test.ts": 580,
+ "test/orphans-mode-islanded.test.ts": 2413,
+ "test/orphans-private-aggregate.test.ts": 1648,
+ "test/orphans-pure-fn.test.ts": 523,
+ "test/orphans-source-scope.test.ts": 622,
+ "test/orphans.test.ts": 2159,
+ "test/owner-holder.test.ts": 6,
+ "test/pace-mode.test.ts": 14,
+ "test/page-generation-counter.test.ts": 2816,
+ "test/page-lock.test.ts": 267,
+ "test/page-search-vector-overflow.test.ts": 3552,
+ "test/page-type-exhaustive.test.ts": 18,
+ "test/pages-body-nul-sanitize.test.ts": 389,
+ "test/pages-soft-delete.test.ts": 1396,
+ "test/pages-source-scoping-4329.test.ts": 3364,
+ "test/pages-upsert-arbiter.test.ts": 2814,
+ "test/parallel.test.ts": 98,
+ "test/parent-scope.test.ts": 575,
+ "test/parity.test.ts": 7,
+ "test/path-confine.test.ts": 24,
+ "test/performfullsync-source-id.test.ts": 855,
+ "test/pg-access-classify.test.ts": 13,
+ "test/pglite-disconnect-checkpoint.test.ts": 420,
+ "test/pglite-embedded-assets.test.ts": 21,
+ "test/pglite-engine.test.ts": 1596,
+ "test/pglite-init-classifier.test.ts": 10,
+ "test/pglite-leftovers-check.test.ts": 19,
+ "test/pglite-lock.test.ts": 16164,
+ "test/pglite-repair.test.ts": 119,
+ "test/pglite-resetwal.test.ts": 36,
+ "test/pglite-workers-clamp.test.ts": 6,
+ "test/phantom-redirect-content-hash.test.ts": 137,
+ "test/phantom-redirect-engine-parity.test.ts": 1271,
+ "test/phantom-redirect-per-source-lock.test.ts": 2,
+ "test/phantom-redirect.test.ts": 5537,
+ "test/phase-scope-coverage.test.ts": 1,
+ "test/pid1-reaper.test.ts": 146,
+ "test/plugin-loader.test.ts": 15,
+ "test/pool-gauge.test.ts": 8,
+ "test/post-install-advisory.test.ts": 32,
+ "test/post-write-lint.test.ts": 3831,
+ "test/postgres-disconnect-bounded.test.ts": 2513,
+ "test/postgres-engine-config-reconnect.test.ts": 40,
+ "test/postgres-engine-getter-selfheal.test.ts": 21,
+ "test/postgres-engine-reserved-routing.test.ts": 27,
+ "test/postgres-engine-rls-scope.test.ts": 22,
+ "test/postgres-engine-singleton-ownership.test.ts": 162,
+ "test/postgres-engine.test.ts": 24,
+ "test/postgres-execute-raw-direct.test.ts": 4,
+ "test/preferences.test.ts": 20,
+ "test/privacy-script-wired.test.ts": 7,
+ "test/privacy-strip-and-forget.test.ts": 1345,
+ "test/private-queue-schema-parity.test.ts": 10,
+ "test/private-visibility.test.ts": 473,
+ "test/process-cleanup.test.ts": 3027,
+ "test/process-watchdog.test.ts": 12,
+ "test/progress-tail.test.ts": 6,
+ "test/progress.test.ts": 327,
+ "test/progressive-batch/orchestrator.test.ts": 75,
+ "test/progressive-batch/retrofit-wrap.test.ts": 9,
+ "test/propose-takes-config-max-tokens.test.ts": 6,
+ "test/propose-takes-per-claim.test.ts": 865,
+ "test/propose-takes-served-model.test.ts": 11,
+ "test/propose-takes-truncation.test.ts": 14,
+ "test/propose-takes.test.ts": 114,
+ "test/protocol-document.test.ts": 62,
+ "test/provider-env.test.ts": 1,
+ "test/provider-fixture-env.test.ts": 110,
+ "test/providers-test-model-base-url.test.ts": 14,
+ "test/providers.test.ts": 11,
+ "test/public-exports.test.ts": 18,
+ "test/publish-gates.test.ts": 10,
+ "test/publish.test.ts": 123,
+ "test/put-page-dedup-fence.test.ts": 1870,
+ "test/put-page-embedding-plane-split.test.ts": 2080,
+ "test/put-page-empty-guard.test.ts": 2135,
+ "test/put-page-empty-overwrite-guard.test.ts": 916,
+ "test/put-page-error-passthrough.test.ts": 893,
+ "test/put-page-namespace.test.ts": 23,
+ "test/put-page-provenance.test.ts": 691,
+ "test/put-page-remote-autolink-hint.test.ts": 672,
+ "test/put-page-write-through-failure.test.ts": 970,
+ "test/put-page-writer-lint.test.ts": 2588,
+ "test/qualified-names.test.ts": 158,
+ "test/quarantine-cache-ops.test.ts": 2023,
+ "test/quarantine-cli.test.ts": 2347,
+ "test/quarantine.test.ts": 14,
+ "test/query-cache-gate.test.ts": 2881,
+ "test/query-cache.test.ts": 609,
+ "test/query-intent-concept.test.ts": 11,
+ "test/query-intent-config.test.ts": 17,
+ "test/query-intent-legacy.test.ts": 8,
+ "test/query-intent.test.ts": 7,
+ "test/query-sanitization.test.ts": 21,
+ "test/queue-child-done.test.ts": 2532,
+ "test/queue-getstats-wedge.test.ts": 2155,
+ "test/queue-lock-retry.test.ts": 11,
+ "test/queue-probe-cancellation.test.ts": 55,
+ "test/queue-stall-parent-unblock.test.ts": 456,
+ "test/queue-started-at-retry.test.ts": 488,
+ "test/r1-namedthing-rerank-ab.test.ts": 7238,
+ "test/ranking-inversion-895.test.ts": 510,
+ "test/rate-leases-uncapped.test.ts": 731,
+ "test/rate-leases.test.ts": 499,
+ "test/readme-hero-anchors.test.ts": 15,
+ "test/recall-extensions.test.ts": 3071,
+ "test/recall-federated-search-scope.test.ts": 3077,
+ "test/recall-federated.test.ts": 444,
+ "test/recall-footer.test.ts": 7,
+ "test/recall-keyword-fallback.test.ts": 1403,
+ "test/recall-rollup.test.ts": 5,
+ "test/receipt-cr-state.test.ts": 627,
+ "test/recency-decay.test.ts": 20,
+ "test/recompute-emotional-weight.test.ts": 15,
+ "test/reconcile-links-cli-reachability.test.ts": 671,
+ "test/redos-hardening.test.ts": 8,
+ "test/reflex-volunteer.test.ts": 1514,
+ "test/register-client-source-normalize.test.ts": 7,
+ "test/regression-strict-source-id.test.ts": 34,
+ "test/regression-v0_16_4.test.ts": 18,
+ "test/regressions/gbrain-base-equivalence.test.ts": 32,
+ "test/regressions/v0.36.1.0-iron-rule.test.ts": 3,
+ "test/regressions/v0_36_frontier_cap.test.ts": 676,
+ "test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 2075,
+ "test/reindex-code-empty-file.test.ts": 768,
+ "test/reindex-code-recovery.test.ts": 447,
+ "test/reindex-code.test.ts": 914,
+ "test/reindex-cost-refusal.test.ts": 3,
+ "test/reindex-frontmatter-connect.test.ts": 397,
+ "test/reindex-preserve-tags.test.ts": 1154,
+ "test/reindex.test.ts": 2528,
+ "test/relational-ab.test.ts": 3499,
+ "test/relational-fanout.test.ts": 456,
+ "test/relational-intent.test.ts": 8,
+ "test/relational-recall.test.ts": 638,
+ "test/release-workflow.test.ts": 19,
+ "test/remediation-command-resolution.test.ts": 210,
+ "test/remediation-step.test.ts": 19,
+ "test/remote-body.test.ts": 10,
+ "test/remote-cli.test.ts": 7115,
+ "test/remote-ping-status-field.test.ts": 23,
+ "test/remote-privacy-sweep.test.ts": 3869,
+ "test/repair-jsonb.test.ts": 28,
+ "test/replay-autocut-floor.test.ts": 377,
+ "test/repo-root.test.ts": 21,
+ "test/repo-visibility.test.ts": 104,
+ "test/report.test.ts": 2,
+ "test/repos-alias.test.ts": 2013,
+ "test/request-tools.test.ts": 515,
+ "test/rerank-audit.test.ts": 14,
+ "test/rerank-doc-cap.test.ts": 105,
+ "test/reranker-default-seam.test.ts": 72,
+ "test/resolve-ipc-binding.test.ts": 20,
+ "test/resolve-ipc-engine-uniform.test.ts": 15,
+ "test/resolve-ipc-v2.test.ts": 1118,
+ "test/resolve-prepare.test.ts": 0,
+ "test/resolver-merge.test.ts": 18,
+ "test/resolver.test.ts": 171,
+ "test/resolvers.test.ts": 4277,
+ "test/restart-sweep.test.ts": 45,
+ "test/retrieval-quality-harness.test.ts": 13,
+ "test/retrieval-reflex-pre-v110.test.ts": 379,
+ "test/retrieval-reflex-recipe-routing.test.ts": 1,
+ "test/retrieval-reflex.test.ts": 620,
+ "test/retrieval-upgrade-planner.test.ts": 7692,
+ "test/retry-matcher.test.ts": 4,
+ "test/routing-eval-cli.test.ts": 1280,
+ "test/routing-eval.test.ts": 22,
+ "test/rrf-source-key.test.ts": 4,
+ "test/rss-default.test.ts": 12,
+ "test/run-child-entry.test.ts": 557,
+ "test/salience-source-scope.test.ts": 3412,
+ "test/salience.test.ts": 6,
+ "test/scenarios.test.ts": 10,
+ "test/schema-bootstrap-coverage.test.ts": 5679,
+ "test/schema-cli-contract.test.ts": 5,
+ "test/schema-cli-lint-extends.test.ts": 2330,
+ "test/schema-cli.test.ts": 6459,
+ "test/schema-lint-extends-resolution.test.ts": 37,
+ "test/schema-lint-extends.test.ts": 1141,
+ "test/schema-lint-pack-confine.test.ts": 17,
+ "test/schema-migrate-link-source-mentions.test.ts": 394,
+ "test/schema-pack-best-effort.test.ts": 16,
+ "test/schema-pack-expand-type-filter.test.ts": 9,
+ "test/schema-pack-infer-type-and-subtype.test.ts": 3,
+ "test/schema-pack-lint-rules.test.ts": 11,
+ "test/schema-pack-loader.test.ts": 9,
+ "test/schema-pack-manifest-v041_2.test.ts": 20,
+ "test/schema-pack-merge.test.ts": 11,
+ "test/schema-pack-mutate-audit.test.ts": 8,
+ "test/schema-pack-mutate-path-confine.test.ts": 2182,
+ "test/schema-pack-mutate.test.ts": 69,
+ "test/schema-pack-pack-lock.test.ts": 70,
+ "test/schema-pack-page-to-alias.test.ts": 968,
+ "test/schema-pack-page-to-link.test.ts": 1463,
+ "test/schema-pack-query-cache-invalidator.test.ts": 1261,
+ "test/schema-pack-registry-reload.test.ts": 51,
+ "test/schema-pack-registry.test.ts": 12,
+ "test/schema-pack-retype.test.ts": 4762,
+ "test/schema-pack-rewrite-links-batch.test.ts": 2620,
+ "test/schema-pack-stats.test.ts": 5149,
+ "test/schema-pack-sync.test.ts": 2782,
+ "test/schema-pack-trust-boundary.test.ts": 11,
+ "test/schema-pack-unify-types-handler.test.ts": 2836,
+ "test/schema-pack/scaffold-extractable.test.ts": 9,
+ "test/schema-pack/suggest.test.ts": 20,
+ "test/schema-type-usage.test.ts": 806,
+ "test/schema-verify.test.ts": 17,
+ "test/schema-version-health.test.ts": 23,
+ "test/scope-agent-isolation.test.ts": 3,
+ "test/scope-normalize.test.ts": 9,
+ "test/scope.test.ts": 6,
+ "test/scripts/check-engine-dynamic-import.test.ts": 5448,
+ "test/scripts/check-key-files-current-state.test.ts": 114,
+ "test/scripts/check-module-size.test.ts": 52,
+ "test/scripts/check-proposal-pii.test.ts": 428,
+ "test/scripts/check-skill-refs.test.ts": 1088,
+ "test/scripts/check-test-isolation.test.ts": 250,
+ "test/scripts/check-wasm-embedded-pipefail.test.ts": 10,
+ "test/scripts/check-worker-lock-renewal-shape.test.ts": 34,
+ "test/scripts/check-worker-pool-atomicity.test.ts": 103,
+ "test/scripts/ci-gates.test.ts": 119,
+ "test/scripts/ci-local-rendering.test.ts": 505,
+ "test/scripts/classify-tests.test.ts": 6,
+ "test/scripts/coverage-baseline-gate.test.ts": 343,
+ "test/scripts/coverage-diff-gate.test.ts": 419,
+ "test/scripts/e2e-wiring.test.ts": 53,
+ "test/scripts/evals-collection.test.ts": 1100,
+ "test/scripts/merge-lcov.test.ts": 515,
+ "test/scripts/mine-shard-weights.test.ts": 41,
+ "test/scripts/render-coverage-summary.test.ts": 143,
+ "test/scripts/run-serial-pool.test.ts": 3403,
+ "test/scripts/run-unit-parallel.test.ts": 8630,
+ "test/scripts/run-unit-shard.test.ts": 226,
+ "test/scripts/run-verify-parallel.test.ts": 3391,
+ "test/scripts/serial-files.test.ts": 111,
+ "test/scripts/sharding.test.ts": 22,
+ "test/scripts/test-shard.slow.test.ts": 882,
+ "test/search-alias-resolved-boost.test.ts": 1024,
+ "test/search-by-image-op.test.ts": 3413,
+ "test/search-compiled-truth-boost-scope.test.ts": 4,
+ "test/search-image-column.test.ts": 2968,
+ "test/search-introspection-ops.test.ts": 406,
+ "test/search-lang-symbol-kind.test.ts": 434,
+ "test/search-limit.test.ts": 421,
+ "test/search-mode-config-snapshot.test.ts": 6,
+ "test/search-mode.test.ts": 31,
+ "test/search-op-source-id.test.ts": 2099,
+ "test/search-snippet-cap.test.ts": 497,
+ "test/search-telemetry.test.ts": 549,
+ "test/search-types-filter.test.ts": 478,
+ "test/search.test.ts": 5,
+ "test/search/alias-hop.test.ts": 2141,
+ "test/search/alias-normalize.test.ts": 11,
+ "test/search/arm-confidence-hybrid.test.ts": 700,
+ "test/search/arm-confidence.test.ts": 17,
+ "test/search/attribution-stamping.test.ts": 5,
+ "test/search/autocut-eval.test.ts": 5,
+ "test/search/autocut.test.ts": 32,
+ "test/search/compiled-truth-boost.test.ts": 2,
+ "test/search/concept-weights.test.ts": 2177,
+ "test/search/crag-query-op.test.ts": 1616,
+ "test/search/crag.test.ts": 2,
+ "test/search/evidence.test.ts": 13,
+ "test/search/exact-lookup.test.ts": 3039,
+ "test/search/expansion-variant-budget.test.ts": 1735,
+ "test/search/explain-formatter.test.ts": 8,
+ "test/search/fusion-lists.test.ts": 14,
+ "test/search/graph-signals-wire-integration.test.ts": 2273,
+ "test/search/graph-signals.test.ts": 30,
+ "test/search/knobs-hash-reranker.test.ts": 20,
+ "test/search/metadata-boost-gate-hybrid.test.ts": 611,
+ "test/search/metadata-boost-gate.test.ts": 5,
+ "test/search/modes-report-coverage.test.ts": 22,
+ "test/search/page-aliases-engine.test.ts": 3401,
+ "test/search/per-call-mode.test.ts": 19,
+ "test/search/pre-migration-failopen.test.ts": 2627,
+ "test/search/query-embed-deadline.test.ts": 4026,
+ "test/search/query-op-adaptive-return.test.ts": 0,
+ "test/search/query-op-autocut.test.ts": 16,
+ "test/search/query-shape.test.ts": 1,
+ "test/search/reindex-aliases.test.ts": 799,
+ "test/search/relational-intent-memo.test.ts": 3,
+ "test/search/relational-rerank-pin.test.ts": 4,
+ "test/search/rerank.test.ts": 14,
+ "test/search/return-policy.test.ts": 17,
+ "test/search/search-diagnose.test.ts": 411,
+ "test/search/search-stats-graph-signals.test.ts": 415,
+ "test/search/searchvector-escalation.test.ts": 10903,
+ "test/search/searchvector-maxpool.test.ts": 405,
+ "test/search/supersede-downrank.test.ts": 1106,
+ "test/search/telemetry-rank1.test.ts": 377,
+ "test/search/title-boost-stage.test.ts": 5,
+ "test/search/title-match.test.ts": 4,
+ "test/search/title-retrieval-arm.test.ts": 6220,
+ "test/search/walk-dedup-cap.test.ts": 12,
+ "test/secret-scan.test.ts": 13,
+ "test/select-e2e.test.ts": 11,
+ "test/self-fix.test.ts": 374,
+ "test/self-upgrade-pending.test.ts": 10,
+ "test/self-upgrade.test.ts": 12,
+ "test/sensitivity-scan.test.ts": 33,
+ "test/serve-http-admin-route-guard.test.ts": 18,
+ "test/serve-http-bootstrap-token.test.ts": 1,
+ "test/serve-http-cors.test.ts": 167,
+ "test/serve-http-embedding-width.test.ts": 375,
+ "test/serve-http-github-webhook.test.ts": 115,
+ "test/serve-http-health.test.ts": 221,
+ "test/serve-http-lifecycle.test.ts": 168,
+ "test/serve-http-mcp-transport-cleanup.test.ts": 5,
+ "test/serve-http-metrics.test.ts": 113,
+ "test/serve-http-oauth-token-rate-limit.test.ts": 15,
+ "test/serve-http-stall-watchdog.test.ts": 28,
+ "test/serve-http-trust-proxy.test.ts": 91,
+ "test/serve-skills-publish-nudge.test.ts": 92,
+ "test/serve-stdin-eof-drain.test.ts": 356,
+ "test/serve-stdio-lifecycle.test.ts": 1408,
+ "test/serve-sweep-runner-677.test.ts": 503,
+ "test/server-degraded-scope.test.ts": 23,
+ "test/session-receipts.test.ts": 744,
+ "test/session-state-gc.test.ts": 411,
+ "test/setup-branching.test.ts": 2,
+ "test/skill-brain-first.test.ts": 13,
+ "test/skill-catalog-block-scalar.test.ts": 3,
+ "test/skill-catalog-security.test.ts": 9,
+ "test/skill-catalog-transports.test.ts": 2034,
+ "test/skill-catalog.test.ts": 21,
+ "test/skill-currency.test.ts": 22,
+ "test/skill-manifest.test.ts": 19,
+ "test/skill-preconditions.test.ts": 5,
+ "test/skill-trigger-index.test.ts": 12,
+ "test/skillify-check.test.ts": 1494,
+ "test/skillify-scaffold.test.ts": 16,
+ "test/skillopt/apply-edits.test.ts": 3,
+ "test/skillopt/audit.test.ts": 9,
+ "test/skillopt/batch.test.ts": 11,
+ "test/skillopt/benchmark.test.ts": 10,
+ "test/skillopt/bootstrap-from-skill.test.ts": 37,
+ "test/skillopt/deadline-and-hermetic.test.ts": 5,
+ "test/skillopt/held-out.test.ts": 7,
+ "test/skillopt/lock.test.ts": 1200,
+ "test/skillopt/lr-schedule.test.ts": 29,
+ "test/skillopt/reflect.test.ts": 6,
+ "test/skillopt/rejected-buffer.test.ts": 1,
+ "test/skillopt/rollout-schema.test.ts": 20,
+ "test/skillopt/rollout.test.ts": 8,
+ "test/skillopt/score.test.ts": 6,
+ "test/skillopt/silent-abort-3516.test.ts": 19,
+ "test/skillopt/validate-gate-abort.test.ts": 6,
+ "test/skillopt/version-store.test.ts": 21,
+ "test/skillopt/write-capture.test.ts": 1161,
+ "test/skillpack-apply-hunks.test.ts": 2,
+ "test/skillpack-bootstrap-display.test.ts": 17,
+ "test/skillpack-brain-resident-locate.test.ts": 42,
+ "test/skillpack-bridge-state.test.ts": 16,
+ "test/skillpack-changed-since-version.test.ts": 167,
+ "test/skillpack-check.test.ts": 5011,
+ "test/skillpack-copy.test.ts": 13,
+ "test/skillpack-endorse.test.ts": 91,
+ "test/skillpack-frontmatter-sources.test.ts": 15,
+ "test/skillpack-harness-bridge.test.ts": 51,
+ "test/skillpack-harvest-lint.test.ts": 6,
+ "test/skillpack-harvest.test.ts": 23,
+ "test/skillpack-init-brain-pack.test.ts": 16,
+ "test/skillpack-init-pack.test.ts": 51,
+ "test/skillpack-install.test.ts": 55,
+ "test/skillpack-manifest-v1.test.ts": 13,
+ "test/skillpack-migrate-fence.test.ts": 12,
+ "test/skillpack-nag-state.test.ts": 1,
+ "test/skillpack-personas.test.ts": 12,
+ "test/skillpack-reference-apply.test.ts": 18,
+ "test/skillpack-reference-harness.test.ts": 43,
+ "test/skillpack-reference-pack-is-ten.test.ts": 9,
+ "test/skillpack-reference.test.ts": 10,
+ "test/skillpack-registry-client.test.ts": 18,
+ "test/skillpack-registry-schema.test.ts": 6,
+ "test/skillpack-remote-source.test.ts": 59,
+ "test/skillpack-rubric-doctor.test.ts": 54,
+ "test/skillpack-scaffold-harness.test.ts": 19960,
+ "test/skillpack-scaffold-third-party.test.ts": 24,
+ "test/skillpack-scaffold.test.ts": 24,
+ "test/skillpack-scrub-legacy.test.ts": 11,
+ "test/skillpack-state.test.ts": 6,
+ "test/skillpack-status.test.ts": 10,
+ "test/skillpack-tarball.test.ts": 132,
+ "test/skillpack-trust-prompt.test.ts": 9,
+ "test/skills-conformance.test.ts": 48,
+ "test/skills-integrity.test.ts": 0,
+ "test/slug-unicode-scripts.test.ts": 3,
+ "test/slug-validation.test.ts": 4,
+ "test/smoke-test-worker.test.ts": 142,
+ "test/snapshot-shape-guard.test.ts": 15,
+ "test/soft-delete-link-visibility.test.ts": 588,
+ "test/sort-newest-first.test.ts": 3,
+ "test/source-boundary-mutation-errors.test.ts": 385,
+ "test/source-config-redact.test.ts": 2,
+ "test/source-health.test.ts": 705,
+ "test/source-id-routing.test.ts": 1568,
+ "test/source-id-tx-regression.test.ts": 547,
+ "test/source-id.test.ts": 4,
+ "test/source-resolver-default-write-guard.test.ts": 7,
+ "test/source-resolver-implicit-default.test.ts": 5,
+ "test/source-resolver-silent-fallback.test.ts": 1888,
+ "test/source-resolver-sole-non-default.test.ts": 10,
+ "test/source-resolver-tier4-parallel-realpath.test.ts": 1,
+ "test/source-resolver-with-tier.test.ts": 2,
+ "test/source-resolver.test.ts": 27,
+ "test/source-scope-resolver.test.ts": 19,
+ "test/sources-abs-path-3696.test.ts": 442,
+ "test/sources-archive-idempotent.test.ts": 3271,
+ "test/sources-google-access-flags.test.ts": 2237,
+ "test/sources-list-scalar-confinement.test.ts": 395,
+ "test/sources-list-scope.test.ts": 2037,
+ "test/sources-load.test.ts": 3769,
+ "test/sources-mcp.test.ts": 3191,
+ "test/sources-ops.test.ts": 8746,
+ "test/sources-resync-recovery.test.ts": 2312,
+ "test/sources-set-cr-mode.test.ts": 1867,
+ "test/sources-set-path.test.ts": 2666,
+ "test/sources-webhook.test.ts": 3,
+ "test/sources.test.ts": 17,
+ "test/spawn-helpers.test.ts": 9,
+ "test/spend-off-switch.test.ts": 7,
+ "test/sql-query.test.ts": 343,
+ "test/sql-ranking.test.ts": 8,
+ "test/ssrf-validate.test.ts": 33,
+ "test/stale-takes-bigint.test.ts": 15,
+ "test/stats-health-source-scope.test.ts": 424,
+ "test/status-autopilot-lock.test.ts": 17,
+ "test/status-sections.test.ts": 113,
+ "test/status-thin-client-skew.test.ts": 18,
+ "test/storage-backfill.test.ts": 25,
+ "test/storage-config.test.ts": 21,
+ "test/storage-export.test.ts": 397,
+ "test/storage-pglite.test.ts": 525,
+ "test/storage-s3.test.ts": 147,
+ "test/storage-status.test.ts": 5,
+ "test/storage-supabase.test.ts": 4035,
+ "test/storage-sync.test.ts": 28,
+ "test/storage.test.ts": 148,
+ "test/stub-guard-audit.test.ts": 7,
+ "test/subagent-aggregator.test.ts": 6,
+ "test/subagent-audit.test.ts": 6,
+ "test/subagent-handler.test.ts": 1088,
+ "test/subagent-prompt-too-long.test.ts": 3,
+ "test/subagent-tool-ledger.test.ts": 446,
+ "test/subagent-transcript.test.ts": 472,
+ "test/subagent-v1-v2-shim.test.ts": 3441,
+ "test/submit-agent.test.ts": 3529,
+ "test/submit-queue-state.test.ts": 1808,
+ "test/sum-stale-chunk-chars.test.ts": 1197,
+ "test/supabase-admin.test.ts": 6,
+ "test/supervisor-audit.test.ts": 5,
+ "test/supervisor-build-worker-args.test.ts": 7,
+ "test/supervisor-db-lock.test.ts": 2016,
+ "test/supervisor-pid.test.ts": 5,
+ "test/supervisor-tini.test.ts": 7,
+ "test/supervisor-wedge.test.ts": 2173,
+ "test/supervisor.test.ts": 2979,
+ "test/surface-audit.test.ts": 1,
+ "test/svg-renderer.test.ts": 10,
+ "test/sweep-writeback-corpus.test.ts": 482,
+ "test/sweep.test.ts": 873,
+ "test/sync-all-missing-path.test.ts": 2,
+ "test/sync-all-parallel.test.ts": 24,
+ "test/sync-baseline-guard.test.ts": 3,
+ "test/sync-brain-op-source-id.test.ts": 502,
+ "test/sync-break-lock-all.test.ts": 4681,
+ "test/sync-break-lock-source-resolution.test.ts": 493,
+ "test/sync-break-lock-source.test.ts": 655,
+ "test/sync-classifier-widening.test.ts": 11,
+ "test/sync-concurrency.test.ts": 6,
+ "test/sync-cost-estimate.test.ts": 220,
+ "test/sync-cost-preview.test.ts": 7,
+ "test/sync-default-write-guard-dry-run.test.ts": 2250,
+ "test/sync-delegate-ladder.test.ts": 16,
+ "test/sync-delete-batch.slow.test.ts": 5044,
+ "test/sync-delete-batch.test.ts": 2864,
+ "test/sync-deleted-slug-embed.test.ts": 699,
+ "test/sync-delta.test.ts": 170,
+ "test/sync-discover-git-root-stderr.test.ts": 386,
+ "test/sync-embedding-infra-gate.test.ts": 4,
+ "test/sync-exclude-config.test.ts": 1549,
+ "test/sync-failures.test.ts": 52,
+ "test/sync-git-autoinit.test.ts": 3531,
+ "test/sync-hard-deadline.test.ts": 4,
+ "test/sync-include-hidden.test.ts": 47,
+ "test/sync-incremental-image-2683.test.ts": 1801,
+ "test/sync-isSyncable-shape.test.ts": 10,
+ "test/sync-json-stdout-clean.test.ts": 883,
+ "test/sync-lock-busy-classification.test.ts": 1531,
+ "test/sync-monorepo.test.ts": 3303,
+ "test/sync-no-embed-sentinel.test.ts": 2,
+ "test/sync-nudge-status-gate.test.ts": 30,
+ "test/sync-parallel.test.ts": 4167,
+ "test/sync-path-containment.test.ts": 16,
+ "test/sync-reconcile-mass-delete.test.ts": 28,
+ "test/sync-rename-batch.test.ts": 1174,
+ "test/sync-repo-source-routing.test.ts": 651,
+ "test/sync-slug-root-mode-4342.test.ts": 2246,
+ "test/sync-sole-non-default-routing.test.ts": 1034,
+ "test/sync-strategy.test.ts": 6,
+ "test/sync-timeout-cli-dispatch.test.ts": 852,
+ "test/sync-timeout.test.ts": 4,
+ "test/sync-trigger-cli.test.ts": 359,
+ "test/sync-walker-submodule.test.ts": 0,
+ "test/sync-walker-symlink.test.ts": 32,
+ "test/sync-working-tree-cli.test.ts": 2644,
+ "test/sync-working-tree.test.ts": 1051,
+ "test/sync.test.ts": 7121,
+ "test/synth-enabled-default.test.ts": 7,
+ "test/synthesize-chunk-budget.test.ts": 4,
+ "test/system-prompt.test.ts": 2,
+ "test/take-forecast.test.ts": 25,
+ "test/take-proposals.test.ts": 466,
+ "test/takes-command-source-scope.test.ts": 220,
+ "test/takes-engine.test.ts": 408,
+ "test/takes-extract-json.test.ts": 6,
+ "test/takes-fence.test.ts": 32,
+ "test/takes-holder-semantics.test.ts": 2,
+ "test/takes-holder-validation.test.ts": 9,
+ "test/takes-list-subcommand.test.ts": 430,
+ "test/takes-propose-drain.test.ts": 372,
+ "test/takes-resolution.test.ts": 4,
+ "test/takes-source-scope.test.ts": 452,
+ "test/takes-weight-rounding.test.ts": 17,
+ "test/takes-write-ops.test.ts": 2447,
+ "test/template-repo-generator.test.ts": 8,
+ "test/test-reads-source-smell.test.ts": 228,
+ "test/text-safe.test.ts": 21,
+ "test/thin-client-routing-audit.test.ts": 16,
+ "test/thin-client-routing.test.ts": 19,
+ "test/thin-client-source-scope.test.ts": 48,
+ "test/thin-client-upgrade-prompt.test.ts": 37,
+ "test/think-ab.test.ts": 7,
+ "test/think-cost.test.ts": 65,
+ "test/think-entity-extract.test.ts": 1,
+ "test/think-envelope-salvage.test.ts": 628,
+ "test/think-gaps.test.ts": 10,
+ "test/think-gateway-adapter.test.ts": 246,
+ "test/think-intent.test.ts": 4,
+ "test/think-max-output-tokens.test.ts": 467,
+ "test/think-pages-block.test.ts": 19,
+ "test/think-persist-take.test.ts": 394,
+ "test/think-sanitize-trajectory.test.ts": 13,
+ "test/think-trajectory-injection.test.ts": 699,
+ "test/think-with-calibration.test.ts": 14,
+ "test/timeline-date-batch.test.ts": 402,
+ "test/timeline-dedup-repair.test.ts": 468,
+ "test/timeline-dup-skipped-3827.test.ts": 511,
+ "test/timeline-entry-subagent-fence.test.ts": 4,
+ "test/timeline-write-through.test.ts": 4730,
+ "test/timeout.test.ts": 86,
+ "test/timing-safe.test.ts": 5,
+ "test/title-fuzzy-index.test.ts": 431,
+ "test/token-budget.test.ts": 4,
+ "test/token-mint.test.ts": 391,
+ "test/tool-catalog.test.ts": 14,
+ "test/track1-save-time-entity-resolution.test.ts": 19,
+ "test/trajectory-format.test.ts": 6,
+ "test/trajectory.test.ts": 2,
+ "test/transcript-adapters.test.ts": 104,
+ "test/transcript-capture.test.ts": 252,
+ "test/transcript-render.test.ts": 26,
+ "test/transcription-injection.test.ts": 5,
+ "test/transcription.test.ts": 47,
+ "test/transcripts-expand-paths.test.ts": 11,
+ "test/transcripts-max-bytes.test.ts": 8,
+ "test/transcripts-nul.test.ts": 747,
+ "test/transcripts-self-exclusion.test.ts": 11,
+ "test/transcripts-truncated-scan.test.ts": 4,
+ "test/transcripts.test.ts": 23,
+ "test/traverse-graph-dedup.test.ts": 411,
+ "test/traverse-graph-op-default.test.ts": 2310,
+ "test/traverse-paths-row-cap.test.ts": 50670,
+ "test/trust-boundary-contract.test.ts": 5,
+ "test/truthful-catalog.e2e-lite.test.ts": 2685,
+ "test/tty-harness.test.ts": 1321,
+ "test/turn-context.test.ts": 1472,
+ "test/two-pass.test.ts": 516,
+ "test/undo-wave.test.ts": 4,
+ "test/unfederate-read-scope-2928.test.ts": 2272,
+ "test/upgrade-reembed-prompt.test.ts": 426,
+ "test/upgrade-reference-sweep.test.ts": 255,
+ "test/upgrade-skill-publish-prompt-race.test.ts": 3,
+ "test/url-redact.test.ts": 7,
+ "test/utils.test.ts": 12,
+ "test/v0_29-tool-surfaces.test.ts": 21,
+ "test/v81-v82-smoke.test.ts": 324,
+ "test/validate-params.test.ts": 19,
+ "test/vector-ef-search.test.ts": 4441,
+ "test/vector-index-lifecycle.test.ts": 5,
+ "test/voice-gate.test.ts": 9,
+ "test/volunteer-context.test.ts": 498,
+ "test/volunteer-events-delivery.test.ts": 6,
+ "test/voyage-multimodal.test.ts": 22,
+ "test/voyage-response-cap.test.ts": 5,
+ "test/wait-for-completion.test.ts": 7573,
+ "test/watch-command.test.ts": 2419,
+ "test/wave-security-scan.test.ts": 436,
+ "test/whoami.test.ts": 11,
+ "test/whoknows-doctor.test.ts": 6,
+ "test/whoknows.test.ts": 12,
+ "test/worker-conn-resilience-1720.test.ts": 120,
+ "test/worker-job-isolation.test.ts": 2805,
+ "test/worker-lock-renewal-shape.test.ts": 2,
+ "test/worker-lock-renewal.test.ts": 22,
+ "test/worker-pool.test.ts": 244,
+ "test/worker-promote-reconnect.test.ts": 16,
+ "test/worker-rss.test.ts": 22,
+ "test/worker-shutdown-disconnect.test.ts": 2249,
+ "test/worker-supervised-db-probe.test.ts": 683,
+ "test/worker-watchdog-trigger.test.ts": 565,
+ "test/write-through.test.ts": 5393,
+ "test/write-verify-guard.test.ts": 1135,
+ "test/write-vocabulary.test.ts": 13,
+ "test/writeback-config.test.ts": 36,
+ "test/writer.test.ts": 7620,
+ "test/yaml-lite.test.ts": 3,
+ "test/ze-exposure.test.ts": 2246,
+ "test/ze-switch-cli.test.ts": 6035,
+ "test/ze-switch-env-override.test.ts": 3730,
+ "test/zombie-reap.test.ts": 3
}
diff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.md
index 19e1e3526e..afcc57ddc8 100644
--- a/skills/conventions/brain-routing.md
+++ b/skills/conventions/brain-routing.md
@@ -84,7 +84,8 @@ wins over the auto-route. Archived sources are excluded from the count.
CLI commands honoring this chain: `gbrain sync`, `gbrain import`,
`gbrain search`, `gbrain extract` (via `--source-id <id>` since
`--source` is the fs|db data-source axis), `gbrain graph-query`
-(via `--include-foreign` for cross-source traversal).
+(`--source` scopes the walk; `--include-foreign` widens it to every
+source).
**Trust boundary (v0.34.1.0):** the resolver is CLI-layer only.
Operations.ts handlers do NOT read `.gbrain-source` or
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 84ef2b424a..b66c67d01f 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -45,7 +45,7 @@
"context-audit/SKILL.md": "6c811783349f740f039078bef991077bdc85007b2f730897465266e4c31b66da",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1",
- "conventions/brain-routing.md": "cfdc22cb4becebf11deafe6c9a6802d2481e90473aaf36e307d1dd83a048fc3b",
+ "conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "dc357891a86987fbc39e06a21a190119b9900e03a2460af64b278307af1b4289",
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
diff --git a/src/cli.ts b/src/cli.ts
index 8e500f6733..9ef2097c41 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1731,6 +1731,9 @@ export function formatResult(
}
case 'get_page': {
const r = result as any;
+ // `--json` leads (same as get_versions) so an ambiguous_slug envelope
+ // stays machine-readable too.
+ if (params.json === true) return JSON.stringify(r, null, 2) + '\n';
if (r.error === 'ambiguous_slug') {
return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
}
diff --git a/src/commands/autopilot-fanout.ts b/src/commands/autopilot-fanout.ts
index f9a279cf78..43773b6e70 100644
--- a/src/commands/autopilot-fanout.ts
+++ b/src/commands/autopilot-fanout.ts
@@ -20,6 +20,8 @@
* - P1-5: archive recheck happens in the handler (jobs.ts:1146), not
* here, so a source archived between fan-out and worker claim still
* skips cleanly.
+ * - Missing checkout paths are skipped at dispatch time; sources.local_path
+ * is machine-specific shared state and can legitimately point elsewhere.
*
* Phase-scope caveat (codex r1 P0-1): per-source cycle LOCKS let two cycles
* RUN concurrently, but several phases (embed, orphans, purge,
@@ -30,10 +32,11 @@
* row layer; cost duplication is the visible tradeoff).
*/
+import { existsSync } from 'fs';
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 } from '../core/sources-load.ts';
+import { sourceConfigHasRemoteUrl, sourceLocalPathSkipWarning } from '../core/sources-load.ts';
import { AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES } from './autopilot-remediation-policy.ts';
// #2194 fix #2: failure cooldown. A source whose autopilot-cycle keeps
@@ -66,6 +69,8 @@ export interface FanoutOpts {
emit?: (line: string) => void;
/** Sink for non-JSON human log lines; defaults to console.log. */
log?: (line: string) => void;
+ /** Test seam for source checkout availability. */
+ pathExists?: (path: string) => boolean;
}
export interface FanoutResult {
@@ -82,11 +87,15 @@ export interface FanoutResult {
skipped_cap: string[];
/** Source ids skipped because they're in failure cooldown (#2194 fix #2). */
skipped_cooldown: string[];
+ /** Source ids skipped because local_path is unavailable from this machine. */
+ skipped_unavailable_path: string[];
/** True when this tick fell back to the legacy single-job path
* (no sources rows / engine empty). */
legacy_fallback: boolean;
/** True when every enumerated source is inside the freshness window. */
all_sources_fresh: boolean;
+ /** True when every enumerated source is either fresh or skipped locally. */
+ all_sources_handled: boolean;
}
/**
@@ -341,11 +350,26 @@ export function selectSourcesForDispatch(
floorMin = AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES,
recentFailures: Map<string, SourceFailure> = new Map(),
cooldownOpts: CooldownOpts = { baseMin: FAILURE_COOLDOWN_BASE_MIN, capMin: FAILURE_COOLDOWN_CAP_MIN },
-): { dispatch: SourceRow[]; skippedFresh: SourceRow[]; skippedCap: SourceRow[]; skippedCooldown: SourceRow[] } {
+ pathExists: (path: string) => boolean = () => true,
+): {
+ dispatch: SourceRow[];
+ skippedFresh: SourceRow[];
+ skippedCap: SourceRow[];
+ skippedCooldown: SourceRow[];
+ /** Each row carries the warning that excluded it, so the caller logs it
+ * directly instead of recomputing (a second existsSync per row). */
+ skippedUnavailablePath: Array<SourceRow & { skip_warning: string }>;
+} {
const stale: SourceRow[] = [];
const fresh: SourceRow[] = [];
const cooldown: SourceRow[] = [];
+ const unavailablePath: Array<SourceRow & { skip_warning: string }> = [];
for (const s of sources) {
+ const skipWarning = s.local_path ? sourceLocalPathSkipWarning(s.id, s.local_path, pathExists, s.config) : null;
+ if (skipWarning) {
+ unavailablePath.push({ ...s, skip_warning: skipWarning });
+ continue;
+ }
if (!isSourceStale(s, now, floorMin)) { fresh.push(s); continue; }
// #2194 fix #2: a stale source that recently failed is held in cooldown so
// it can't re-dispatch every tick (the storm). Success clears it.
@@ -364,7 +388,7 @@ export function selectSourcesForDispatch(
});
const dispatch = stale.slice(0, fanoutMax);
const skippedCap = stale.slice(fanoutMax);
- return { dispatch, skippedFresh: fresh, skippedCap, skippedCooldown: cooldown };
+ return { dispatch, skippedFresh: fresh, skippedCap, skippedCooldown: cooldown, skippedUnavailablePath: unavailablePath };
}
/**
@@ -434,8 +458,10 @@ export async function dispatchPerSource(
skipped_fresh: [],
skipped_cap: [],
skipped_cooldown: [],
+ skipped_unavailable_path: [],
legacy_fallback: true,
all_sources_fresh: false,
+ all_sources_handled: false,
};
}
@@ -455,7 +481,8 @@ export async function dispatchPerSource(
cooldownOpts = { baseMin: 0, capMin: FAILURE_COOLDOWN_CAP_MIN };
}
- const { dispatch, skippedFresh, skippedCap, skippedCooldown } =
+ const pathExists = opts.pathExists ?? existsSync;
+ const { dispatch, skippedFresh, skippedCap, skippedCooldown, skippedUnavailablePath } =
selectSourcesForDispatch(
sources,
opts.fanoutMax,
@@ -463,8 +490,17 @@ export async function dispatchPerSource(
AUTOPILOT_FULL_CYCLE_FLOOR_MINUTES,
recentFailures,
cooldownOpts,
+ pathExists,
);
+ for (const src of skippedUnavailablePath) {
+ if (opts.jsonMode) {
+ emit(JSON.stringify({ event: 'fanout_source_path_skipped', source_id: src.id, reason: src.skip_warning }));
+ } else {
+ log(src.skip_warning);
+ }
+ }
+
const dispatched: string[] = [];
const coalesced: string[] = [];
for (const src of dispatch) {
@@ -563,8 +599,10 @@ export async function dispatchPerSource(
skipped_fresh: skippedFresh.map(s => s.id),
skipped_cap: skippedCap.map(s => s.id),
skipped_cooldown: skippedCooldown.map(s => s.id),
+ skipped_unavailable_path: skippedUnavailablePath.map(s => s.id),
legacy_fallback: false,
all_sources_fresh: skippedFresh.length === sources.length,
+ all_sources_handled: skippedFresh.length + skippedUnavailablePath.length === sources.length,
};
}
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 227912a1d8..094898710a 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -45,6 +45,7 @@ import { detectInstallMethod } from './upgrade.ts';
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 { resolveAutopilotDispatchTimeoutMs } from './autopilot-timeout.ts';
import {
autopilotRemediationIdempotencyKey,
@@ -65,6 +66,7 @@ import {
MIGRATE_PAUSE_MARKER_PREFIX,
} from '../core/autopilot-paths.ts';
export { autopilotLockPath, autopilotDisabledMarkerPath, autopilotPausedMarkerPath, autopilotLaunchdLabel };
+export { relativeSourceLocalPathSkipWarning as relativeLocalPathSkipWarning };
/**
* v0.37.7.0 #1162 — classify autopilot reconnect-loop errors.
@@ -1079,20 +1081,22 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
try {
const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');
if (await isFederatedV2Enabled(engine)) {
- const { loadAllSources, sourceConfigHasRemoteUrl } = await import('../core/sources-load.ts');
const sources = await loadAllSources(engine);
const intervalMs = baseInterval * 1000;
const now = Date.now();
for (const src of sources) {
if (!src.local_path) continue;
- // #3696: a RELATIVE local_path is meaningless in the daemon
- // (cwd is launchd's, not the registering shell's) — dispatching
- // it would sync a phantom path. Skip loudly; the fix is
- // re-registering with an absolute path (sources add now
- // resolves) or one successful `gbrain sync` (anchor self-heal).
- const relWarn = relativeLocalPathSkipWarning(src.id, src.local_path);
- if (relWarn) {
- process.stderr.write(relWarn + '\n');
+ // 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
+ // path. Skip loudly (sourceLocalPathSkipWarning carries the
+ // fix); under --json the skip is an NDJSON event like every
+ // other daemon line on stderr, never bare prose in the stream.
+ const skipWarn = sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config);
+ if (skipWarn) {
+ process.stderr.write(
+ (jsonMode ? JSON.stringify({ event: 'freshness_source_path_skipped', source_id: src.id, reason: skipWarn }) : skipWarn) + '\n',
+ );
continue;
}
const lastSyncMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0;
@@ -1182,16 +1186,18 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
}
if (submittedToday < maxJobsToday) {
- const { loadAllSources } = await import('../core/sources-load.ts');
const { countExtractAtomsBacklog } = await import('../core/cycle/extract-atoms.ts');
const sources = await loadAllSources(engine);
for (const src of sources) {
if (submittedToday >= maxJobsToday) break; // brain-wide daily cap (fairness)
if (!src.local_path) continue;
- // #3696: same relative-path skip as the freshness loop.
- const relWarn = relativeLocalPathSkipWarning(src.id, src.local_path);
- if (relWarn) {
- process.stderr.write(relWarn + '\n');
+ // Same unavailable-path skip (relative / missing on this
+ // machine) as the freshness loop above, same --json shape.
+ const skipWarn = sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config);
+ if (skipWarn) {
+ process.stderr.write(
+ (jsonMode ? JSON.stringify({ event: 'freshness_source_path_skipped', source_id: src.id, reason: skipWarn }) : skipWarn) + '\n',
+ );
continue;
}
const backlog = await countExtractAtomsBacklog(engine, src.id);
@@ -1389,7 +1395,14 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// keep that behavior, or an all-coalesced tick (single-flight
// suppression) would retake the full-cycle branch every tick and
// starve the targeted-plan path for the whole in-flight window.
- if (result.dispatched.length > 0 || result.coalesced.length > 0 || result.legacy_fallback || result.all_sources_fresh) {
+ // (all_sources_handled subsumes all_sources_fresh: fresh + locally
+ // skipped === every source.)
+ if (
+ result.dispatched.length > 0 ||
+ result.coalesced.length > 0 ||
+ result.legacy_fallback ||
+ result.all_sources_handled
+ ) {
lastFullCycleAt = Date.now();
}
if (jsonMode) {
@@ -1400,6 +1413,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
skipped_fresh: result.skipped_fresh,
skipped_cap: result.skipped_cap,
skipped_cooldown: result.skipped_cooldown,
+ skipped_unavailable_path: result.skipped_unavailable_path,
legacy_fallback: result.legacy_fallback,
fanout_max: fanoutMax,
score,
@@ -1409,7 +1423,8 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
`[dispatch] fanout: ${result.dispatched.length} dispatched` +
`${result.coalesced.length > 0 ? ` (${result.coalesced.length} coalesced onto in-flight)` : ''}, ` +
`${result.skipped_fresh.length} fresh, ${result.skipped_cap.length} capped, ` +
- `${result.skipped_cooldown.length} cooldown ` +
+ `${result.skipped_cooldown.length} cooldown, ` +
+ `${result.skipped_unavailable_path.length} unavailable-path ` +
`(score=${score}, max=${fanoutMax})`,
);
}
@@ -1885,6 +1900,26 @@ ${generateSelfDisableGuard(repoPath, target)}# #3696: daemon cwd = the repo, so
# this line still starts the daemon, and the dispatch loops skip relative
# paths loudly.
cd '${safeRepoPath}' 2>/dev/null || true
+# #4728: the CLI path below was resolved ONCE at --install. On the
+# ephemeral-container target the container layer is wiped on every deploy, so
+# a CLI that lived there vanishes while this wrapper (on the volume) survives,
+# and bash's bare "No such file or directory" named no remedy. The baked path
+# stays primary; only once it is gone do we fall back to PATH — the same
+# resolution the daemon already applies at run time when it spawns its worker
+# child (resolveGbrainCliPath -> which gbrain), so this adds no lookup
+# semantics the install did not already rely on. \`type -P\` only returns an
+# executable file on PATH, ignoring any \`gbrain\` shell function or alias the
+# rc files sourced above may have defined. Logs go to stdout: that is the
+# autopilot.log sink on all four targets (same choice as the boot warning).
+if [ ! -x '${safeGbrainPath}' ]; then
+ _resolved=$(type -P gbrain 2>/dev/null)
+ if [ -n "$_resolved" ]; then
+ echo "$(date -u +%FT%TZ) [autopilot] baked CLI path is gone:" '${safeGbrainPath}' "- using $_resolved"
+ exec "$_resolved" autopilot --repo '${safeRepoPath}'
+ fi
+ echo "$(date -u +%FT%TZ) [autopilot] gbrain CLI not found at" '${safeGbrainPath}' "nor on PATH; re-run: gbrain autopilot --install"
+ exit 1
+fi
exec '${safeGbrainPath}' autopilot --repo '${safeRepoPath}'
`;
writeFileSync(wrapperPath, wrapper, { mode: 0o755 });
@@ -1977,23 +2012,6 @@ export function pgliteDaemonGuardMessage(engineKind: string, force: boolean): st
);
}
-/**
- * #3696 — the autopilot dispatch loops refuse to enqueue work for a source
- * whose local_path is RELATIVE: the daemon's cwd is launchd's (typically `/`),
- * not the shell that registered the source, so the path would resolve to a
- * phantom directory and the sync/extract job would fail (or worse, walk the
- * wrong tree). Returns the stderr warning line when the path must be skipped,
- * or null when it is dispatchable. Pure — the unit-test surface.
- */
-export function relativeLocalPathSkipWarning(sourceId: string, localPath: string): string | null {
- if (isAbsolute(localPath)) return null;
- return (
- `[autopilot] skipping source '${sourceId}': relative local_path ` +
- `'${localPath}' cannot be resolved from a daemon. Re-register with an ` +
- `absolute --path or run 'gbrain sync --source ${sourceId}' once to self-heal.`
- );
-}
-
// v0.37.7.0 #1162 — pure function for plist generation so tests can
// assert ThrottleInterval/KeepAlive shape without an installed daemon.
// #3696: WorkingDirectory pins the daemon's cwd away from launchd's `/`
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index d35d535396..b74ac80022 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -144,6 +144,9 @@ Subcommands (run \`gbrain bootstrap status\` first — it is the resume entrypoi
pre-approval, lifecycle hooks (user scope, or per --project
dir), codex config block, opencode config entry. No
agent.json needed. Idempotent; --remove tears it down.
+ --source ID: the source the hooks + token bind to
+ (default: sources.default, else the sole populated
+ non-default source, else default).
(--local is an accepted no-op alias.)
cloud-setup-script Print the paste-ready cloud environment setup
script (installs the gbrain binary into the
diff --git a/src/commands/check-resolvable.ts b/src/commands/check-resolvable.ts
index 0de7fdd076..9a2dd9bf4c 100644
--- a/src/commands/check-resolvable.ts
+++ b/src/commands/check-resolvable.ts
@@ -301,7 +301,7 @@ export async function runCheckResolvable(args: string[]): Promise<void> {
autoFix = autoFixDryViolations(skillsDir, { dryRun: flags.dryRun });
}
- const report = checkResolvable(skillsDir);
+ const report = checkResolvable(skillsDir, { skillsDirSource: source === 'explicit' ? null : source });
// Exit semantics (D-CX-3):
// default mode: fail iff any errors
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 9be931099a..5461680d07 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -121,6 +121,7 @@ export const FILE_PLANE_API_KEYS: readonly string[] = [
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
+ 'deepseek_api_key',
'litellm_api_key',
'together_api_key',
'google_api_key',
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 6ee1fe8f9f..6a6517dc36 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -748,7 +748,7 @@ export async function buildChecks(
}
}
- const report = checkResolvable(skillsDir);
+ const report = checkResolvable(skillsDir, { skillsDirSource: detected.source === 'explicit' ? null : detected.source });
if (report.errors.length === 0 && report.warnings.length === 0) {
checks.push({
name: 'resolver_health',
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 2b5238f73f..eafe6f1c18 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -412,7 +412,7 @@ export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<C
for (const { slug, source_path: sourcePath } of rows) {
if (dbOnlyDirs.some(dir => slug.startsWith(dir))) continue;
if (sourcePath) {
- const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath);
+ const filePath = resolveSourceLocalFilePath(src.local_path!, sourcePath, slug);
if (filePath && existsSync(filePath)) continue;
} else {
backedWithoutSourcePath ??= collectMarkdownSlugs(src.local_path!);
@@ -509,11 +509,17 @@ type ExtractAtomsBacklogCounter = (engine: BrainEngine, sourceId?: string) => Pr
async function countExtractAtomsBacklogBySource(
engine: BrainEngine,
countBacklog: ExtractAtomsBacklogCounter,
+ sourceIds?: string[],
): Promise<Array<{ source_id: string; backlog: number }> | null> {
try {
- const sources = await engine.executeRaw<{ source_id: string }>(
- `SELECT DISTINCT source_id FROM pages WHERE deleted_at IS NULL ORDER BY source_id`,
- );
+ // Source isolation: a scoped caller (remote run_doctor with a source
+ // grant) only ever sees its own ids — the brain-wide roster is for the
+ // unscoped local/host path.
+ const sources = sourceIds
+ ? [...sourceIds].sort().map((source_id) => ({ source_id }))
+ : await engine.executeRaw<{ source_id: string }>(
+ `SELECT DISTINCT source_id FROM pages WHERE deleted_at IS NULL ORDER BY source_id`,
+ );
const rows: Array<{ source_id: string; backlog: number }> = [];
for (const src of sources) {
const backlog = await countBacklog(engine, src.source_id);
@@ -526,6 +532,22 @@ async function countExtractAtomsBacklogBySource(
}
}
+/** Total backlog: brain-wide when unscoped, else the sum over the granted ids. */
+async function countExtractAtomsBacklogScoped(
+ engine: BrainEngine,
+ countBacklog: ExtractAtomsBacklogCounter,
+ sourceIds?: string[],
+): Promise<number | null> {
+ if (!sourceIds) return countBacklog(engine);
+ let total = 0;
+ for (const id of sourceIds) {
+ const n = await countBacklog(engine, id);
+ if (n === null) return null;
+ total += n;
+ }
+ return total;
+}
+
function buildExtractAtomsDrainCommand(
bySource: Array<{ source_id: string; backlog: number }> | null,
): string {
@@ -635,12 +657,15 @@ async function brainShapeCanCarryCycleStamps(engine: BrainEngine): Promise<boole
*/
export async function computeExtractAtomsBacklogCheck(
engine: BrainEngine,
+ opts: { sourceIds?: string[] } = {},
): Promise<Check> {
const name = 'extract_atoms_backlog';
const approx = 'page backlog only; transcript corpus not counted';
try {
const { countExtractAtomsBacklog } = await import('../../../core/cycle/extract-atoms.ts');
- const backlog = await countExtractAtomsBacklog(engine); // brain-wide
+ // undefined = brain-wide (local doctor); an array = the remote caller's
+ // source grant — counts, roster and drain hints all stay inside it.
+ const backlog = await countExtractAtomsBacklogScoped(engine, countExtractAtomsBacklog, opts.sourceIds);
if (backlog === null) {
return { name, status: 'warn', message: 'backlog query failed (could not count eligible pages)' };
}
@@ -660,7 +685,7 @@ export async function computeExtractAtomsBacklogCheck(
// The incident: pack does NOT run the phase but a real backlog exists →
// it will grow forever without a signal. WARN with the drain command.
if (!declared && backlog > 10) {
- const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog);
+ const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);
const fix = buildExtractAtomsBacklogFixHint(backlogBySource);
return {
name, status: 'warn',
@@ -690,7 +715,7 @@ export async function computeExtractAtomsBacklogCheck(
};
}
if (evidence && (evidence.state === 'never' || evidence.state === 'stale')) {
- const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog);
+ const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);
const drain = buildExtractAtomsDrainCommand(backlogBySource);
const since = evidence.state === 'never'
? 'no full cycle has ever completed'
@@ -738,13 +763,20 @@ export async function computeExtractAtomsBacklogCheck(
* The mirror of extract_atoms_backlog. That check counts pages waiting to be
* extracted; this one counts atoms whose provenance no longer resolves.
*
- * extract_atoms stamps `frontmatter.source_hash` with the first 16 chars of the
- * source page's content_hash, and discovery skips a page while an atom with the
- * matching hash exists. Editing the page moves its content_hash, so the atom is
- * left pointing at a hash no live page carries. Nothing reclaims those atoms:
- * re-extraction mints under a deterministic slug built from the atom TITLE, so
- * it only upserts in place when the new pass happens to produce the same title.
- * A reworded claim lands on a new slug and the old atom stays, unreferenced.
+ * Scope: PAGE-BOUND atoms only (those stamped with a `source_slug`). The page
+ * lane of extract_atoms stamps `frontmatter.source_hash` with the first 16
+ * chars of the source page's content_hash, and discovery skips a page while an
+ * atom with the matching hash exists. Editing the page moves its content_hash,
+ * so the atom is left pointing at a hash no live page carries. The transcript
+ * lane binds atoms to a FILE instead (`source_path`, no `source_slug`) and
+ * stamps sha256(raw file)[:16] — a different function over different input
+ * that can never equal a page's content_hash — so those atoms are counted
+ * separately as `slug_unbound` and excluded from the drift population (#4799
+ * named the bucket, #4806 took it out of the ratio). Nothing reclaims drifted
+ * atoms: re-extraction mints under a deterministic slug built from the atom
+ * TITLE, so it only upserts in place when the new pass happens to produce the
+ * same title. A reworded claim lands on a new slug and the old atom stays,
+ * unreferenced.
*
* Why this needs a signal: a drifted atom is still returned by search, still
* carries a `source_quote`, and still reads as sourced — but its quote can no
@@ -760,7 +792,11 @@ export async function computeExtractAtomsBacklogCheck(
* Diagnostic only. It reports and hints; it never deletes. `source_gone` and
* `source_changed` are split because they warrant different handling and the
* second is by far the larger group — a naive GC keyed on drift alone would
- * delete mostly-recoverable knowledge.
+ * delete mostly-recoverable knowledge. The third bucket, `slug_unbound`, holds
+ * atoms with no `source_slug` at all (transcript-origin atoms bind by
+ * `source_path`, pre-binding-era atoms by neither); their page liveness cannot
+ * be resolved by slug, so they are reported as their own informational count
+ * and never as drift, gone, or part of the WARN ratio.
*/
export async function computeAtomProvenanceDriftCheck(
engine: BrainEngine,
@@ -772,7 +808,7 @@ export async function computeAtomProvenanceDriftCheck(
const WARN_RATIO = 0.1;
try {
const rows = await engine.executeRaw<{
- total: string | number; drifted: string | number;
+ total: string | number; slug_unbound: string | number; drifted: string | number;
source_changed: string | number; source_gone: string | number;
oldest_ext: string | null;
}>(
@@ -786,7 +822,10 @@ export async function computeAtomProvenanceDriftCheck(
`WITH atom AS (
SELECT a.source_id,
a.frontmatter->>'source_hash' AS sh,
- a.frontmatter->>'source_slug' AS ss,
+ -- NULL = slug-unbound: transcript-minted (source_path only) or
+ -- pre-binding-era. \`ss IS NULL\` is THE predicate for that
+ -- population everywhere below (#4799 / #4806).
+ NULLIF(a.frontmatter->>'source_slug', '') AS ss,
CASE WHEN a.frontmatter->>'extracted_at' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}'
THEN a.frontmatter->>'extracted_at' END AS ext
FROM pages a
@@ -795,23 +834,33 @@ export async function computeAtomProvenanceDriftCheck(
AND a.frontmatter->>'source_hash' IS NOT NULL
-- in-flight marker written before the extraction commits
AND a.frontmatter->>'source_hash' NOT LIKE 'pending:%'
+ -- Lookup sets are built ONCE and joined (#4937). A correlated EXISTS in
+ -- the SELECT list is not rewritten to a semi-join — Postgres re-runs it
+ -- per atom over substring(content_hash), which no index serves, so the
+ -- check went O(atoms x same-source pages) and blew health-check budgets.
+ -- DISTINCT is load-bearing: duplicate live content_hash values are a
+ -- real state and would otherwise fan one atom out into several rows.
+ ), live_hashes AS MATERIALIZED (
+ SELECT DISTINCT source_id, substring(content_hash from 1 for 16) AS sh
+ FROM pages WHERE deleted_at IS NULL AND content_hash IS NOT NULL
+ ), live_slugs AS MATERIALIZED (
+ SELECT DISTINCT source_id, slug FROM pages WHERE deleted_at IS NULL
), drift AS (
SELECT atom.*,
- NOT EXISTS (
- SELECT 1 FROM pages p
- WHERE p.source_id = atom.source_id AND p.deleted_at IS NULL
- AND substring(p.content_hash from 1 for 16) = atom.sh
- ) AS drifted,
- EXISTS (
- SELECT 1 FROM pages p
- WHERE p.source_id = atom.source_id AND p.deleted_at IS NULL
- AND p.slug = atom.ss
- ) AS src_alive
+ -- a slug-unbound atom is never drift: its hash is over a file,
+ -- not a page, so the page probe is meaningless (#4806)
+ (atom.ss IS NOT NULL AND h.sh IS NULL) AS drifted,
+ (s.slug IS NOT NULL) AS src_alive
FROM atom
+ LEFT JOIN live_hashes h ON h.source_id = atom.source_id AND h.sh = atom.sh
+ LEFT JOIN live_slugs s ON s.source_id = atom.source_id AND s.slug = atom.ss
)
- SELECT count(*) AS total,
+ SELECT count(*) FILTER (WHERE ss IS NOT NULL) AS total,
+ count(*) FILTER (WHERE ss IS NULL) AS slug_unbound,
count(*) FILTER (WHERE drifted) AS drifted,
count(*) FILTER (WHERE drifted AND src_alive) AS source_changed,
+ -- drifted implies a slug binding, so "gone" is always a binding
+ -- that failed to resolve — never a slug-unbound atom (#4799)
count(*) FILTER (WHERE drifted AND NOT src_alive) AS source_gone,
-- lexicographic min of ISO-shaped strings ≈ chronological min
-- (oldest); informational only, never verdict-bearing
@@ -824,6 +873,7 @@ export async function computeAtomProvenanceDriftCheck(
const num = (v: string | number | null | undefined) => (v == null ? 0 : Number(v));
const total = num(r.total);
+ const slugUnbound = num(r.slug_unbound);
const drifted = num(r.drifted);
const sourceChanged = num(r.source_changed);
const sourceGone = num(r.source_gone);
@@ -834,6 +884,7 @@ export async function computeAtomProvenanceDriftCheck(
const ratio = total > 0 ? drifted / total : 0;
const details = {
total_atoms: total,
+ slug_unbound: slugUnbound,
drifted,
source_changed: sourceChanged,
source_gone: sourceGone,
@@ -841,21 +892,28 @@ export async function computeAtomProvenanceDriftCheck(
oldest_drifted_days: oldestDays ?? undefined,
};
- if (total === 0) return { name, status: 'ok', message: 'no atoms to check', details };
- if (drifted === 0) return { name, status: 'ok', message: `${total} atom(s), all provenance-resolved`, details };
+ // Slug-unbound atoms cannot be page-checked; say so instead of hiding them.
+ const su = slugUnbound > 0
+ ? `; ${slugUnbound} slug-unbound atom(s) (no source_slug: transcript-minted source_path-only, or pre-binding-era) are file-bound and not page-checked`
+ : '';
+ if (total === 0) {
+ return { name, status: 'ok', message: (slugUnbound > 0 ? 'no page-bound atoms to check' : 'no atoms to check') + su, details };
+ }
+ if (drifted === 0) return { name, status: 'ok', message: `${total} atom(s), all provenance-resolved${su}`, details };
if (drifted >= MIN_DRIFTED && ratio > WARN_RATIO) {
const fix =
"review before acting — most drift is an edited source, not a dead one. " +
"List them with: SELECT slug, frontmatter->>'source_slug' FROM pages a WHERE a.type='atom' " +
- "AND a.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id " +
+ "AND a.deleted_at IS NULL AND NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL " +
+ "AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id " +
"AND p.deleted_at IS NULL AND substring(p.content_hash from 1 for 16)=a.frontmatter->>'source_hash')";
return {
name, status: 'warn',
message:
`${drifted}/${total} atom(s) (${details.drift_pct}%) reference a source_hash no live page carries ` +
`— ${sourceChanged} whose source page still exists (edited), ${sourceGone} whose source page is gone` +
- (oldestDays != null ? `; oldest ${oldestDays}d` : '') +
+ (oldestDays != null ? `; oldest ${oldestDays}d` : '') + su +
`. These still surface in search with a source_quote that no current page contains. Fix: ${fix}`,
details,
};
@@ -863,7 +921,7 @@ export async function computeAtomProvenanceDriftCheck(
return {
name, status: 'ok',
- message: `${drifted}/${total} atom(s) drifted (below warn threshold)`,
+ message: `${drifted}/${total} atom(s) drifted (below warn threshold)${su}`,
details,
};
} catch (err) {
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 3924bf3e59..319c03b104 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -184,13 +184,30 @@ export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
*/
export async function checkEvalDrift(engine: BrainEngine): Promise<Check> {
try {
- const { watchedFilesDrifted } = await import('../../../core/eval/drift-watch.ts');
- // Working tree vs HEAD (uncommitted retrieval changes). The fuller
+ const { watchedFilesDrifted, resolveGbrainSourceRoot } = await import('../../../core/eval/drift-watch.ts');
+ // Working tree vs HEAD (uncommitted retrieval changes) in gbrain's OWN
+ // source checkout — never process.cwd(), which is whatever repo the
+ // operator (or the serving process) happens to stand in. The fuller
// version (vs the commit of the last published eval) is wired when
- // eval_results lands; today we just probe for uncommitted retrieval
- // changes so the operator sees them before re-running evals.
- const repoRoot = process.cwd();
+ // eval_results lands.
+ const repoRoot = resolveGbrainSourceRoot();
+ if (repoRoot === null) {
+ return {
+ name: 'eval_drift',
+ status: 'ok',
+ message: 'Not applicable — gbrain is running as an installed package, not a source checkout; retrieval code changes arrive as version bumps (gbrain --version), not as a git diff.',
+ };
+ }
const drifted = watchedFilesDrifted(repoRoot);
+ if (drifted === null) {
+ return {
+ name: 'eval_drift',
+ status: 'ok',
+ // No path here: this check is remote-reachable (run_doctor) and the
+ // server's absolute source root is not the caller's business.
+ message: 'Could not probe retrieval drift (git unavailable or the gbrain source root is not a git work tree).',
+ };
+ }
if (drifted.length === 0) {
return {
name: 'eval_drift',
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index e6bddd6665..9581275258 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -70,10 +70,12 @@ export async function doctorReportRemote(
): Promise<DoctorReport> {
const checks: Check[] = [];
- // 1. Connection
+ // 1. Connection. #4592: confined to the caller's source scope (undefined =
+ // brain-wide, the local/unscoped path) — an admin-scope aggregate on the
+ // remote trust boundary leaks an excluded source's size by subtraction.
let pageCount = 0;
try {
- const stats = await engine.getStats();
+ const stats = await engine.getStats({ sourceIds: opts.sourceIds });
pageCount = stats.page_count ?? 0;
checks.push({
name: 'connection',
@@ -163,10 +165,13 @@ export async function doctorReportRemote(
// schema (event_page_id), NOT a migration verify-hook, per
// migration-verify-hook-never-runs-on-stamped-brains.
try {
+ // Source isolation: a scoped caller counts only its own sources' projections.
const orphans = await engine.executeRaw<{ n: number }>(
`SELECT count(*)::int AS n FROM timeline_entries te
JOIN pages ep ON ep.id = te.event_page_id
- WHERE te.event_page_id IS NOT NULL AND ep.deleted_at IS NOT NULL`,
+ WHERE te.event_page_id IS NOT NULL AND ep.deleted_at IS NOT NULL
+ ${opts.sourceIds ? 'AND ep.source_id = ANY($1::text[])' : ''}`,
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const n = Number(orphans[0]?.n ?? 0);
checks.push(
@@ -184,9 +189,9 @@ export async function doctorReportRemote(
checks.push({ name: 'chronicle_projection_health', status: 'ok', message: 'no event projections yet' });
}
- // 3. Brain score
+ // 3. Brain score (#4592: same scope as the connection count above)
try {
- const health = await engine.getHealth();
+ const health = await engine.getHealth({ sourceIds: opts.sourceIds });
const score = health.brain_score ?? 0;
checks.push({
name: 'brain_score',
@@ -273,8 +278,11 @@ export async function doctorReportRemote(
// returned to the thin-client over MCP.
try {
const { findMisroutedPages } = await import('../../core/multi-source-drift.ts');
+ // Source isolation: a scoped caller's roster (and the sample slugs the
+ // walk returns) stays inside its grant; unscoped = brain-wide.
const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources`,
+ `SELECT id, local_path FROM sources ${opts.sourceIds ? 'WHERE id = ANY($1::text[])' : ''}`,
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const nonDefaultWithPath = sources.filter(s => s.id !== 'default' && s.local_path);
if (sources.length > 1 && nonDefaultWithPath.length > 0) {
@@ -387,8 +395,9 @@ export async function doctorReportRemote(
// #4576 (related gap): extract_atoms_backlog was absent from the
// thin-client surface, so an MCP-only caller couldn't see the backlog at
// all. SQL counts + pack/config reads on the server side — the env that
- // actually runs (or fails to run) the cycle.
- checks.push(await computeExtractAtomsBacklogCheck(engine));
+ // actually runs (or fails to run) the cycle. Source-scoped like the
+ // connection count: the roster + per-source backlog stay inside the grant.
+ checks.push(await computeExtractAtomsBacklogCheck(engine, { sourceIds: opts.sourceIds }));
// v0.39 T7 + T9 — schema-pack health checks (3 checks per v0.38 plan):
// schema_pack_active — active pack resolves cleanly
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index 369deced01..224069dbfc 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -31,7 +31,7 @@ import {
type CyclePhase,
type CycleReport,
} from '../core/cycle.ts';
-import { isResolverUserError, resolveImplicitDefaultSourceId, resolveSourceId } from '../core/source-resolver.ts';
+import { ALL_SOURCES, isResolverUserError, resolveImplicitDefaultSourceId, resolveSourceId } from '../core/source-resolver.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { fetchSource } from '../core/sources-load.ts';
import { existsSync } from 'fs';
@@ -427,6 +427,8 @@ Options:
(explicit phases are honored verbatim). A bare
no --source dream against the default-like source,
and --source default, still run the full cycle.
+ GBRAIN_SOURCE=<id> is equivalent when --source is
+ omitted.
--source-id <id> Alias for --source. Matches the v0.37.7.0+
naming used by import/extract/graph-query.
@@ -709,6 +711,14 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
// `--source <id>` and the autopilot fanout keep the freshness boundary.
let implicitDefaultSourceId: string | null = null;
let fullImplicitSourceCycle = false;
+ // #4778: GBRAIN_SOURCE is tier 2 of the shared resolver, but dream only
+ // entered the resolver behind the --source gate, so an env-scoped bare run
+ // cycled the unscoped brain and never stamped the intended source. The
+ // __all__ sentinel is excluded: unscoped dream already spans every source,
+ // and a '__all__' scope has no local_path (every filesystem phase would be
+ // skipped as no_brain_dir).
+ const envSource = process.env.GBRAIN_SOURCE ?? '';
+ const envScoped = envSource !== '' && envSource !== ALL_SOURCES;
if (opts.source === null && engine !== null) {
try {
implicitDefaultSourceId = await resolveImplicitDefaultSourceId(engine);
@@ -719,20 +729,24 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
}
throw e;
}
- if (opts.dir === null && implicitDefaultSourceId && implicitDefaultSourceId !== 'default') {
+ // Gated on an EMPTY env, not on !envScoped: an explicit GBRAIN_SOURCE=__all__
+ // asks for the whole brain and must not be narrowed to the implicit default.
+ if (opts.dir === null && envSource === '' && implicitDefaultSourceId && implicitDefaultSourceId !== 'default') {
resolvedSourceId = implicitDefaultSourceId;
fullImplicitSourceCycle = true;
}
}
- if (opts.source !== null) {
+ if (opts.source !== null || envScoped) {
if (engine === null) {
console.error(
- 'gbrain dream --source <id> requires a connected brain ' +
- '(no engine available); omit --source or run `gbrain init` first',
+ 'gbrain dream --source <id> / GBRAIN_SOURCE=<id> requires a connected brain ' +
+ '(no engine available); omit the source scope or run `gbrain init` first',
);
process.exit(1);
}
try {
+ // A null explicit falls through to tier 2 (GBRAIN_SOURCE: validate +
+ // assertSourceExists) — the recall.ts pattern.
resolvedSourceId = await resolveSourceId(engine, opts.source);
} catch (e) {
if (isResolverUserError(e)) {
@@ -741,6 +755,12 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Prom
}
throw e; // genuine bugs propagate with stack trace
}
+ // #4700 mirror of the path-derived branch below: an env scope naming the
+ // brain's default-like source is still the canonical default cycle, not
+ // a freshness-only --source cycle.
+ fullImplicitSourceCycle = opts.source === null
+ && implicitDefaultSourceId === resolvedSourceId
+ && resolvedSourceId !== 'default';
// Archived-source guard via fetchSource from sources-load.ts
// (single-row SELECT that projects `archived` and falls back to
// pre-v0.26.5 schemas via isUndefinedColumnError catch — same
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 9d0fdc3a2f..8dd8e4b730 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../core/engine.ts';
import { currentEmbeddingSignature } from '../core/embedding.ts';
import type { ChunkInput } from '../core/types.ts';
-import { carryChunkMetadata, probeEmbedder } from '../core/embed-stale.ts';
+import { carryChunkMetadata, probeEmbedder, resolveProvenanceStamp, stampIfPageProvenanceComplete } from '../core/embed-stale.ts';
import { chunkText } from '../core/chunkers/recursive.ts';
import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from '../core/embed-oversize-heal.ts';
@@ -1849,6 +1849,7 @@ async function embedAllStale(
return true;
};
+ const stamp = await resolveProvenanceStamp(engine, signature); // column resolved once per drain, not per page
try {
// eslint-disable-next-line no-constant-condition
while (true) {
@@ -1972,16 +1973,13 @@ async function embedAllStale(
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
}));
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
- // v0.41.31: stamp provenance after the page's chunks are embedded —
- // but only when EVERY chunk was stale (fully re-embedded this pass).
- // A partially-stale page keeps preserved chunks of unknown/old
- // provenance, so don't claim it's current. (After invalidate, a
- // signature-drifted page IS fully stale → this stamps it.)
- // #3037: not on partial failure — failed chunks stay NULL.
- if (signature && failed === 0 && stale.length === existing.length) {
- await observed(pacer, () =>
- engine.setPageEmbeddingSignature(slug, { sourceId: keySourceId, signature }),
- );
+ // Stamp provenance from DB state, not this batch (#4825): the keyset
+ // drain has no page alignment, so a page straddling a batch boundary
+ // is never wholly in one batch — the batch that lands its last chunk
+ // stamps it. Preserved chunks of other provenance keep the page
+ // unstamped; #3037: failed chunks stay NULL, so skip the round trip.
+ if (stamp && failed === 0) {
+ await observed(pacer, () => stampIfPageProvenanceComplete(engine, slug, keySourceId, stamp));
}
// #3507: a FULLY re-embedded per_chunk_synopsis page landed at the
// title tier — keep the stamped mode honest. Partially-stale pages
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 08470099c9..d60be876f3 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1196,7 +1196,10 @@ async function processPage(
process.stderr.write(
`[extract-conversation-facts] ${page.slug} changed during extraction; leaving it unfinished for replay\n`,
);
- newestEnd = null;
+ // #4869: no terminal, no checkpoint — this claim did not reach a durable
+ // outcome, so it counts as failed (CLI exit 1 / cycle 'warn'), not processed.
+ state.result.pages_failed++;
+ return { newEndIso: null };
}
if (!state.dryRun && newestEnd !== null) {
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 4d982dfd57..f4ba7b217f 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -59,7 +59,7 @@ export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core
import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
-import { pathToSlug, slugifyPath, pruneDir, isSyncable } from '../core/sync.ts';
+import { pathToSlug, slugifyPath, slugifySegment, pruneDir, isSyncable } from '../core/sync.ts';
// v0.41.18.0: withRetry + isRetryableConnError + WithRetryOpts moved to
// src/core/retry.ts as the canonical primitive. Engine methods
// (addLinksBatch/addTimelineEntriesBatch/upsertChunks) now self-retry via
@@ -642,10 +642,15 @@ export async function extractLinksFromFile(
return trimmed;
}
const hints = Array.isArray(dirHint) ? dirHint : (dirHint ? [dirHint] : []);
+ // Both slug grammars, as in makeResolver step 2 (#4855): the folded
+ // basename form and the unfolded page-slug form sync mints.
+ const forms = new Set([normalizeBasename(trimmed), slugifySegment(trimmed)]);
for (const hint of hints) {
if (!hint) continue;
- const candidate = `${hint}/${normalizeBasename(trimmed)}`;
- if (allSlugs.has(candidate)) return candidate;
+ for (const form of forms) {
+ const candidate = `${hint}/${form}`;
+ if (allSlugs.has(candidate)) return candidate;
+ }
}
return null;
},
@@ -684,6 +689,14 @@ export interface ExtractOpts {
dryRun?: boolean;
/** Emit JSON (progress to stderr, result to stdout) instead of human text. */
jsonMode?: boolean;
+ /**
+ * Embedded callers (the cycle) own the report: emit nothing on stdout —
+ * no per-item dry-run lines, no `created N` summary. Independent of
+ * jsonMode, which also selects the stderr batch-error channel (JSON events
+ * vs human text); the cycle used `jsonMode: true` as a stand-in for this
+ * and flipped that channel in a plain `gbrain dream`.
+ */
+ quiet?: boolean;
/**
* Incremental mode: only extract from these specific slugs.
* When provided, skips the full directory walk and reads only the
@@ -755,6 +768,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
const dryRun = !!opts.dryRun;
const jsonMode = !!opts.jsonMode;
+ const quiet = !!opts.quiet;
const result: ExtractResult = { links_created: 0, timeline_entries_created: 0, pages_processed: 0 };
// v0.41.15.0 (D9): resolve workers via the PGLite-clamp wrapper.
@@ -775,7 +789,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
// Nothing changed — skip entirely.
return result;
}
- const r = await extractForSlugs(engine, opts.dir, opts.slugs, opts.mode, dryRun, jsonMode, workers, opts.signal, opts.sourceId, opts.includeFrontmatter);
+ const r = await extractForSlugs(engine, opts.dir, opts.slugs, opts.mode, dryRun, jsonMode, workers, opts.signal, opts.sourceId, opts.includeFrontmatter, quiet);
result.links_created = r.links_created;
result.timeline_entries_created = r.timeline_created;
result.pages_processed = r.pages;
@@ -795,12 +809,12 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
stampRefs = refsWithSnapshotStamps(walkRefs, await snapshotStampTimes(engine, walkRefs));
}
if (opts.mode === 'links' || opts.mode === 'all') {
- const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId);
+ const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);
result.links_created = r.created;
result.pages_processed = r.pages;
}
if (opts.mode === 'timeline' || opts.mode === 'all') {
- const r = await extractTimelineFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId);
+ const r = await extractTimelineFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId, quiet);
result.timeline_entries_created = r.created;
result.pages_processed = Math.max(result.pages_processed, r.pages);
}
@@ -1264,7 +1278,10 @@ async function extractForSlugs(
// Default false preserves the body-only incremental behavior. Gated upstream
// by `autopilot.incremental_extract_include_frontmatter`.
includeFrontmatter: boolean = false,
+ // Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).
+ quiet: boolean = false,
): Promise<{ links_created: number; timeline_created: number; pages: number }> {
+ 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)));
@@ -1315,7 +1332,14 @@ async function extractForSlugs(
linksCreated += await engine.addLinksBatch(snapshot, { auditSite: 'extract.links_inc' }); // gbrain-allow-direct-insert: gbrain extract command — canonical link reconciliation from markdown body
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- if (!jsonMode) console.error(` link batch error (${snapshot.length} rows lost): ${msg}`);
+ // Same two-channel contract as the fs-walk siblings: the cycle runs this
+ // path with jsonMode (stdout belongs to the dream --json report), and a
+ // flush that drops rows must still surface on stderr.
+ if (jsonMode) {
+ process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');
+ } else {
+ console.error(` link batch error (${snapshot.length} rows lost): ${msg}`);
+ }
}
}
@@ -1327,7 +1351,11 @@ async function extractForSlugs(
timelineCreated += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_inc' });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- if (!jsonMode) console.error(` timeline batch error (${snapshot.length} rows lost): ${msg}`);
+ if (jsonMode) {
+ process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');
+ } else {
+ console.error(` timeline batch error (${snapshot.length} rows lost): ${msg}`);
+ }
}
}
@@ -1357,7 +1385,7 @@ async function extractForSlugs(
const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack });
for (const link of links) {
if (dryRun) {
- if (!jsonMode) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
+ if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
linksCreated++;
} else {
linkBatch.push(sourceId
@@ -1372,7 +1400,7 @@ async function extractForSlugs(
const entries = extractTimelineFromContent(content, slug);
for (const entry of entries) {
if (dryRun) {
- if (!jsonMode) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);
+ if (!stdoutQuiet) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);
timelineCreated++;
} else {
timelineBatch.push({ slug: entry.slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail, ...(sourceId ? { source_id: sourceId } : {}) });
@@ -1401,7 +1429,7 @@ async function extractForSlugs(
}
progress.finish();
- if (!jsonMode) {
+ if (!stdoutQuiet) {
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Incremental extract: ${label} ${linksCreated} link(s), ${timelineCreated} timeline entries from ${pagesProcessed}/${slugs.length} page(s)`);
}
@@ -1417,7 +1445,10 @@ async function extractLinksFromDir(
// #1747/#1503: stamp resolved brain source id on batch rows so the
// addLinksBatch JOIN matches non-'default' source pages.
sourceId?: string,
+ // Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).
+ quiet: boolean = false,
): Promise<{ created: number; pages: number }> {
+ const stdoutQuiet = jsonMode || quiet;
const files = walkMarkdownFiles(brainDir);
const allSlugs = new Set(files.map(f => pathToSlug(f.relPath)));
@@ -1472,7 +1503,7 @@ async function extractLinksFromDir(
const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;
if (dryRunSeen.has(key)) continue;
dryRunSeen.add(key);
- if (!jsonMode) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
+ if (!stdoutQuiet) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
created++;
} else {
batch.push(sourceId
@@ -1488,7 +1519,7 @@ async function extractLinksFromDir(
await flush();
progress.finish();
- if (!jsonMode) {
+ if (!stdoutQuiet) {
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${files.length} pages`);
}
@@ -1503,7 +1534,10 @@ async function extractTimelineFromDir(
// #1747/#1503: stamp resolved brain source id so addTimelineEntriesBatch
// matches non-'default' source pages.
sourceId?: string,
+ // Embedded callers own the report: nothing on stdout (see ExtractOpts.quiet).
+ quiet: boolean = false,
): Promise<{ created: number; pages: number }> {
+ const stdoutQuiet = jsonMode || quiet;
const files = walkMarkdownFiles(brainDir);
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
@@ -1546,7 +1580,7 @@ async function extractTimelineFromDir(
const key = `${entry.slug}::${entry.date}::${entry.summary}`;
if (dryRunSeen.has(key)) continue;
dryRunSeen.add(key);
- if (!jsonMode) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);
+ if (!stdoutQuiet) console.log(` ${entry.slug}: ${entry.date} — ${entry.summary}`);
created++;
} else {
batch.push({ slug: entry.slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail, ...(sourceId ? { source_id: sourceId } : {}) });
@@ -1560,7 +1594,7 @@ async function extractTimelineFromDir(
await flush();
progress.finish();
- if (!jsonMode) {
+ if (!stdoutQuiet) {
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Timeline: ${label} ${created} entries from ${files.length} pages`);
}
@@ -2009,6 +2043,8 @@ export async function extractStaleFromDB(
opts: {
dryRun: boolean;
jsonMode: boolean;
+ /** Embedded callers (the cycle) own the report: emit nothing on stdout. */
+ quiet?: boolean;
includeFrontmatter: boolean;
sourceIdFilter?: string;
catchUp: boolean;
@@ -2023,21 +2059,22 @@ export async function extractStaleFromDB(
},
): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number }> {
const { dryRun, jsonMode, includeFrontmatter, sourceIdFilter, catchUp } = opts;
+ const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;
const versionTs = LINK_EXTRACTOR_VERSION_TS;
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
const totalStale = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
if (dryRun) {
- if (jsonMode) {
+ if (jsonMode && !opts.quiet) {
process.stdout.write(JSON.stringify({ action: 'extract_stale_dry_run', stale_pages: totalStale }) + '\n');
} else {
- console.log(`(dry run) ${totalStale} page(s) need link/timeline extraction. Run without --dry-run to extract.`);
+ log(`(dry run) ${totalStale} page(s) need link/timeline extraction. Run without --dry-run to extract.`);
}
return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: totalStale };
}
if (totalStale === 0) {
- if (!jsonMode) console.log('No stale pages — extraction is up to date.');
+ if (!jsonMode) log('No stale pages — extraction is up to date.');
return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: 0 };
}
@@ -2185,17 +2222,17 @@ export async function extractStaleFromDB(
const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
if (!jsonMode) {
- console.log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
+ log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
if (skippedMissingTarget > 0) {
- console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
+ log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
}
if (skippedCrossSource > 0) {
- console.log(`Skipped ${skippedCrossSource} cross-source candidate(s) — target exists only in another source. Enable with \`gbrain config set link_resolution.cross_source true\`, then run \`gbrain extract links --source db\` — a --stale re-run will NOT revisit these pages (their extraction watermark is already stamped) — see docs/architecture/brains-and-sources.md (#2589).`);
+ log(`Skipped ${skippedCrossSource} cross-source candidate(s) — target exists only in another source. Enable with \`gbrain config set link_resolution.cross_source true\`, then run \`gbrain extract links --source db\` — a --stale re-run will NOT revisit these pages (their extraction watermark is already stamped) — see docs/architecture/brains-and-sources.md (#2589).`);
}
if (budgetHit && staleRemaining > 0) {
- console.log(`Time budget reached — ${staleRemaining} page(s) still stale. Re-run 'gbrain extract --stale' (or pass --catch-up) to continue.`);
+ log(`Time budget reached — ${staleRemaining} page(s) still stale. Re-run 'gbrain extract --stale' (or pass --catch-up) to continue.`);
}
- } else {
+ } else if (!opts.quiet) {
process.stdout.write(JSON.stringify({
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
@@ -2216,10 +2253,13 @@ export async function extractStaleFromDB(
* mention link_source is filtered OUT of backlink-count per D12 so
* search ranking semantics are preserved.
*
- * Source isolation: mentions cross-source pages are deliberately
- * suppressed by `findMentionedEntities`'s cross-source guard. Page in
- * source A mentions entity in source B → no link created. v1
- * conservative posture; relaxable in a future wave.
+ * Source isolation: mentions of cross-source pages are suppressed by
+ * `findMentionedEntities`'s cross-source guard (page in source A mentions
+ * entity in source B → no link) UNLESS the operator opted in via
+ * `link_resolution.cross_source` — the same switch wikilink resolution
+ * honours, so the two link sources can't disagree about source isolation.
+ * The switch is folded into the checkpoint fingerprint so flipping it
+ * mid-pause rescans instead of resuming with the old posture.
*/
async function extractMentionsFromDb(
engine: BrainEngine,
@@ -2251,10 +2291,11 @@ async function extractMentionsFromDb(
// fingerprint so adding new entity pages mid-pause invalidates the
// 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);
+ .slice(0, 8) + (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
@@ -2370,6 +2411,7 @@ async function extractMentionsFromDb(
? findMentionedEntities(body, gazetteer, {
fromSlug: slug,
fromSourceId: source_id,
+ allowCrossSource,
})
: [];
diff --git a/src/commands/features.ts b/src/commands/features.ts
index 4bb2f1e866..4c65d2fc7c 100644
--- a/src/commands/features.ts
+++ b/src/commands/features.ts
@@ -199,10 +199,12 @@ export async function scanFeatures(engine: BrainEngine): Promise<FeatureScanResu
});
}
- // No sync configured
+ // No sync configured. Modern sync anchors on sources.local_path; the global
+ // sync.repo_path is only the legacy single-source fallback, which non-default
+ // sources never set (#4767). Legacy key first so it short-circuits the query.
try {
const syncRepo = await engine.getConfig('sync.repo_path');
- if (!syncRepo) {
+ if (!syncRepo && (await engine.listAllSources({ localPathOnly: true })).length === 0) {
recommendations.push({
id: 'no-sync', priority: 2,
title: 'Configure Sync',
diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.ts
index c3416cd49f..efbf8f6bd9 100644
--- a/src/commands/frontmatter.ts
+++ b/src/commands/frontmatter.ts
@@ -478,7 +478,9 @@ async function runGenerate(args: string[]): Promise<void> {
try { if (lstatSync(absPath).isSymbolicLink()) return; } catch { return; }
let content: string;
- try { content = readFileSync(absPath, 'utf-8'); } catch { return; }
+ // #4798: strip a UTF-8 BOM so heading-title inference (and --fix's
+ // written body) match what `gbrain sync` / `import` produce.
+ try { content = readFileSync(absPath, 'utf-8').replace(/^\uFEFF/, ''); } catch { return; }
const inferred = inferFrontmatter(relPath, content);
if (inferred.skipped) {
diff --git a/src/commands/graph-query.ts b/src/commands/graph-query.ts
index 9f0b7cb899..693482f8d8 100644
--- a/src/commands/graph-query.ts
+++ b/src/commands/graph-query.ts
@@ -19,6 +19,7 @@ import type { GraphPath } from '../core/types.ts';
import { TRAVERSE_PATH_ROW_CAP } from '../core/engine-constants.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
+import { resolveSourceId, resolveSourceIdEngineFree, ALL_SOURCES } from '../core/source-resolver.ts';
interface Args {
slug?: string;
@@ -27,6 +28,7 @@ interface Args {
direction: 'in' | 'out' | 'both';
showHelp: boolean;
includeForeign: boolean;
+ source?: string;
}
function parseArgs(args: string[]): Args {
@@ -40,6 +42,11 @@ function parseArgs(args: string[]): Args {
if (d === 'in' || d === 'out' || d === 'both') out.direction = d;
}
else if (a === '--include-foreign') out.includeForeign = true;
+ // A valueless `--source` (last arg) or `--source=` parses to '' so
+ // runGraphQuery can refuse it on EVERY path — '' must never read as
+ // "ambient scope".
+ else if (a === '--source') out.source = i + 1 < args.length ? args[++i] : '';
+ else if (a.startsWith('--source=')) out.source = a.slice('--source='.length);
else if (a === '--help' || a === '-h') out.showHelp = true;
else if (!a.startsWith('-') && !out.slug) out.slug = a;
}
@@ -57,10 +64,17 @@ Options:
founded, advises, mentions, source).
--depth <N> Max traversal depth (default 5).
--direction <dir> 'out' (default), 'in', or 'both'.
+ --source <id> Scope the walk to this source. Defaults to the
+ resolved source (GBRAIN_SOURCE, .gbrain-source,
+ path match, brain default); __all__ spans every
+ source. An unknown source is a hard error. Local
+ installs only: a thin client rejects it (the server
+ scopes the walk to your grant).
--include-foreign Include edges to pages in other sources (v0.37.7.0).
- Off by default; scoped traversal continues as today,
- and a footer reports the count of foreign-source
- edges hidden so users discover they exist.
+ Off by default; the walk stays inside the resolved
+ source, and a footer reports the count of
+ foreign-source edges hidden so users discover they exist.
+ Not forwarded on a thin client.
-h, --help Show this message.
Examples:
@@ -88,7 +102,11 @@ async function countForeignEdges(
engine: BrainEngine,
rootSlug: string,
direction: 'in' | 'out' | 'both',
+ sourceId: string,
): Promise<number> {
+ // The root is (sourceId, rootSlug) — slugs are unique per source, so an
+ // unqualified slug match would count another source's same-slug page's
+ // edges as "hidden" from a walk that never touched it.
// For 'out': from_page is root, count where from.source_id != to.source_id.
// For 'in': to_page is root, count where to.source_id != from.source_id.
// For 'both': either endpoint can be the root; union the two cases.
@@ -97,16 +115,15 @@ async function countForeignEdges(
FROM links l
JOIN pages fp ON l.from_page_id = fp.id
JOIN pages tp ON l.to_page_id = tp.id
- WHERE tp.slug = $1
+ WHERE tp.slug = $1 AND tp.source_id = $2
AND fp.source_id IS NOT NULL
- AND tp.source_id IS NOT NULL
AND fp.source_id <> tp.source_id`
: direction === 'both'
? `SELECT COUNT(*)::text AS n
FROM links l
JOIN pages fp ON l.from_page_id = fp.id
JOIN pages tp ON l.to_page_id = tp.id
- WHERE (fp.slug = $1 OR tp.slug = $1)
+ WHERE ((fp.slug = $1 AND fp.source_id = $2) OR (tp.slug = $1 AND tp.source_id = $2))
AND fp.source_id IS NOT NULL
AND tp.source_id IS NOT NULL
AND fp.source_id <> tp.source_id`
@@ -114,12 +131,11 @@ async function countForeignEdges(
FROM links l
JOIN pages fp ON l.from_page_id = fp.id
JOIN pages tp ON l.to_page_id = tp.id
- WHERE fp.slug = $1
- AND fp.source_id IS NOT NULL
+ WHERE fp.slug = $1 AND fp.source_id = $2
AND tp.source_id IS NOT NULL
AND fp.source_id <> tp.source_id`;
try {
- const rows = await engine.executeRaw<{ n: string }>(sql, [rootSlug]);
+ const rows = await engine.executeRaw<{ n: string }>(sql, [rootSlug, sourceId]);
return Number(rows[0]?.n ?? 0);
} catch {
// Pre-v0.18 brains may not have source_id on pages. Fail-open: no
@@ -140,8 +156,45 @@ export async function runGraphQuery(engine: BrainEngine, argv: string[]) {
// traverse_graph op returns GraphPath[] when link_type or direction is
// set (which the CLI always does); unpackToolResult parses the JSON.
let paths: GraphPath[];
+ // True only when the local walk was narrowed to one source — the footer
+ // reports what that narrowing hid, so it must never print for an unscoped
+ // walk (--include-foreign, --source __all__, or the thin-client path, where
+ // the server scopes to the caller's grant).
+ let scoped = false;
+ // The source the local walk was narrowed to (set only when `scoped`).
+ let sourceId = '';
+ if (args.source === '') {
+ console.error('`--source` requires a value');
+ process.exit(1);
+ }
+ if (args.source !== undefined && args.includeForeign) {
+ // Validating X and then walking every source would make --source a no-op.
+ console.error('pass --source <id> OR --include-foreign, not both (--include-foreign spans every source; --source narrows the walk to one).');
+ process.exit(1);
+ }
const cfg = loadConfig();
if (isThinClient(cfg)) {
+ // The remote traverse_graph op has no source_id param: the server scopes
+ // the walk to the caller's grant. --source used to be dropped silently
+ // (a grant-wide walk with exit 0), contradicting the "unknown source is a
+ // hard error" contract above; reject it the way applyThinClientSourceScope
+ // does for op commands. --include-foreign is meaningless there (the grant
+ // already bounds the walk) — say so instead of pretending it applied.
+ const cannotForwardScope = 'the remote op has no source_id parameter; the server scopes the walk to your grant';
+ if (args.source !== undefined) {
+ console.error(`gbrain graph-query does not accept --source on a thin-client install (${cannotForwardScope}).`);
+ process.exit(1);
+ }
+ // An ambient scope (GBRAIN_SOURCE / .gbrain-source) is just as
+ // un-forwardable — say so instead of letting the user believe it applied.
+ let ambient: string | null = null;
+ try { ambient = resolveSourceIdEngineFree(null); } catch { /* malformed env: the serve's own resolver reports it */ }
+ if (ambient !== null) {
+ console.error(`[thin-client] ambient source scope '${ambient}' is not forwarded (${cannotForwardScope}).`);
+ }
+ if (args.includeForeign) {
+ console.error(`[thin-client] --include-foreign is not forwarded (${cannotForwardScope}).`);
+ }
const raw = await callRemoteTool(cfg!, 'traverse_graph', {
slug: args.slug,
depth: args.depth,
@@ -150,10 +203,18 @@ export async function runGraphQuery(engine: BrainEngine, argv: string[]) {
}, { timeoutMs: 30_000 });
paths = unpackToolResult<GraphPath[]>(raw);
} else {
+ // #4765: the walk used to run unscoped (the traverse_graph op scopes via
+ // sourceScopeOpts; this CLI twin never did), so --include-foreign was
+ // inert and the footer described a filter that never applied. Resolve
+ // the source the way every other local command does; an explicit
+ // --source that fails to resolve throws loudly (#1712 policy).
+ sourceId = await resolveSourceId(engine, args.source ?? null);
+ scoped = !args.includeForeign && sourceId !== ALL_SOURCES;
const walk = await engine.traversePathsDetailed(args.slug, {
depth: args.depth,
linkType: args.linkType,
direction: args.direction,
+ ...(scoped ? { sourceId } : {}),
});
paths = walk.paths;
if (walk.truncated) {
@@ -165,8 +226,8 @@ export async function runGraphQuery(engine: BrainEngine, argv: string[]) {
console.log(`No edges found from ${args.slug}${args.linkType ? ` (--type ${args.linkType})` : ''}.`);
// Still report foreign edges so the user knows they exist in other
// sources even when the scoped traversal returned nothing.
- if (!args.includeForeign && !isThinClient(cfg)) {
- const foreign = await countForeignEdges(engine, args.slug, args.direction);
+ if (scoped) {
+ const foreign = await countForeignEdges(engine, args.slug, args.direction, sourceId);
if (foreign > 0) {
console.error(
`(${foreign} edge${foreign === 1 ? '' : 's'} to foreign-source pages hidden; pass --include-foreign to include them)`,
@@ -183,8 +244,8 @@ export async function runGraphQuery(engine: BrainEngine, argv: string[]) {
// scoped traversal silently dropped. Thin-client path skips this
// (engine query not available); local path runs the count and prints
// the footer when there are hidden edges AND the user didn't opt in.
- if (!args.includeForeign && !isThinClient(cfg)) {
- const foreign = await countForeignEdges(engine, args.slug, args.direction);
+ if (scoped) {
+ const foreign = await countForeignEdges(engine, args.slug, args.direction, sourceId);
if (foreign > 0) {
console.error(
`\n(${foreign} edge${foreign === 1 ? '' : 's'} to foreign-source pages hidden; pass --include-foreign to include them)`,
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 3f4e34f43c..e3a7bd1c96 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -28,6 +28,7 @@ import {
resumeFilter,
} from '../core/import-checkpoint.ts';
import { realpathOrResolve } from '../core/path-confine.ts';
+import { slog } from '../core/console-prefix.ts';
/** Return a refusal when an import target lies outside every admitted root. */
export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {
@@ -213,9 +214,13 @@ export async function runImport(
// always writes to stderr. Stdout stays clean for data output (--json
// payloads)"). Pre-fix, `import --json` prefixed the payload with
// "Found N markdown files", so JSON.parse of stdout failed outright.
+ // The human branch goes through slog() so an in-process caller running in
+ // its own --json mode (`sync --json` → performFullSync → runImport, wrapped
+ // in withHumanLogsToStderr) keeps its stdout clean too; outside any wrap
+ // slog IS console.log.
const info = (msg: string): void => {
if (jsonOutput) console.error(msg);
- else console.log(msg);
+ else slog(msg);
};
// T7 (D9): refuse cleanly when init persisted the deferred-setup sentinel,
@@ -273,17 +278,47 @@ export async function runImport(
// callers (performFullSync, future Step 6 paths) can route to a named
// source.
//
- // v0.37.7.0 #1167+#1222: the CLI surface now also accepts a
- // `--source-id <id>` flag (named to avoid colliding with `--source`
- // which other commands use for different axes). Pre-fix, users
- // passing `gbrain import --source dept-x ...` silently fell back to
- // default because the parser ignored the flag. Now an explicit
- // `--source-id <id>` opt-in routes the import to that source.
- // Programmatic callers continue passing `opts.sourceId` directly;
- // CLI callers' flag wins over opts when both are set.
+ // #1167: the CLI flag shipped as `--source-id <id>`. #4862: `--source <id>`
+ // is an alias — it is what every sibling command and the resolver's own
+ // nudge tell users to pass, import has no competing --source axis, and the
+ // flag registry already accepted it, so pre-alias it was silently IGNORED
+ // (pages landed in default). Both spellings with different values abort.
+ // Programmatic callers continue passing `opts.sourceId` directly; CLI
+ // flags win over opts when both are set. Both the `--source value` and
+ // `--source=value` spellings are accepted (same for --source-id); a missing
+ // value (or a value that is itself a flag) is refused the way sync-delegate
+ // refuses it, never read as "no scope".
const sourceIdIdx = args.indexOf('--source-id');
- const flagSourceId = sourceIdIdx !== -1 ? args[sourceIdIdx + 1] : null;
- let sourceId: string | undefined = flagSourceId ?? opts.sourceId;
+ const sourceIdx = args.indexOf('--source');
+ const readSourceFlag = (flag: string, idx: number): string | null => {
+ const eq = args.find((a) => a.startsWith(`${flag}=`));
+ const v = eq !== undefined ? eq.slice(flag.length + 1) : idx !== -1 ? args[idx + 1] : null;
+ if (v === null) return null;
+ if (v === undefined || v === '' || v.startsWith('--')) {
+ console.error(`${flag} (missing value)`);
+ throw new ImportAbortError(`${flag} (missing value)`);
+ }
+ return v;
+ };
+ const viaSourceId = readSourceFlag('--source-id', sourceIdIdx);
+ const viaSource = readSourceFlag('--source', sourceIdx);
+ if (viaSourceId && viaSource && viaSourceId !== viaSource) {
+ console.error('Pass either --source or --source-id, not both.');
+ throw new ImportAbortError('conflicting source flags');
+ }
+ const flagSourceId = viaSourceId ?? viaSource;
+ let sourceId: string | undefined = opts.sourceId;
+ if (flagSourceId) {
+ // Validate + assert existence through the shared resolver (tier 1), so an
+ // invalid or unregistered id fails once with the same SourceTargetError
+ // sync gives — not once per file on the pages.source_id foreign key.
+ const { resolveSourceWithTier, ALL_SOURCES } = await import('../core/source-resolver.ts');
+ if (flagSourceId === ALL_SOURCES) {
+ console.error(`import writes to one source; \`${ALL_SOURCES}\` is not a write target.`);
+ throw new ImportAbortError('__all__ is not an import target');
+ }
+ sourceId = (await resolveSourceWithTier(engine, flagSourceId)).source_id;
+ }
// v0.41.13 (#1434): when no explicit source / env / opts.sourceId is set,
// fall through to the resolver so the new sole_non_default tier (5.5) can
@@ -360,10 +395,11 @@ export async function runImport(
const flagValues = new Set<number>();
if (workersIdx !== -1) flagValues.add(workersIdx + 1);
if (sourceIdIdx !== -1) flagValues.add(sourceIdIdx + 1);
+ if (sourceIdx !== -1) flagValues.add(sourceIdx + 1);
const dirArg = args.find((a, i) => !a.startsWith('--') && !flagValues.has(i));
if (!dirArg) {
- console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source-id <id>] [--include-gitignored] [--allow-noncanonical-root] [--json]');
+ console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source <id> | --source-id <id>] [--include-gitignored] [--allow-noncanonical-root] [--json]');
throw new ImportAbortError('no import directory given');
}
// #1728: capture the import target ONCE as an absolute real path. Every
@@ -748,16 +784,26 @@ export async function runImport(
const totalTime = ((Date.now() - startTime) / 1000).toFixed(1);
if (jsonOutput) {
+ // `skipped` includes every per-file failure importFile RETURNS (invalid
+ // frontmatter, oversize, symlink, slug mismatch) as well as content-hash
+ // no-ops, and `errors` counts only the thrown ones — so a caller cannot
+ // tell "unchanged" from "failed" by counts alone. The failure ledger is
+ // written only for git-repo dirs (see the gitHead gate below), so a caller
+ // importing a scratch directory has no other channel. Emit the per-file
+ // list so state can be gated per file.
console.log(JSON.stringify({
status: 'success', duration_s: parseFloat(totalTime),
imported, skipped, errors, chunks: chunksCreated,
total_files: allFiles.length,
+ unchanged: skipped - failures.length - malformedFileSkips,
+ malformed_skipped: malformedFileSkips,
+ failures,
}));
} else {
- console.log(`\nImport complete (${totalTime}s):`);
- console.log(` ${imported} pages imported`);
- console.log(` ${skipped} pages skipped (${skipped - errors} unchanged, ${errors} errors)`);
- console.log(` ${chunksCreated} chunks created`);
+ slog(`\nImport complete (${totalTime}s):`);
+ slog(` ${imported} pages imported`);
+ slog(` ${skipped} pages skipped (${skipped - errors} unchanged, ${errors} errors)`);
+ slog(` ${chunksCreated} chunks created`);
}
// v0.39 T7 — end-of-run schema mismatch warn. Fires ONCE per import,
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 838990718a..1dda515a8e 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -2502,7 +2502,7 @@ export async function registerBuiltinHandlers(
const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : 'default';
const page = await engine.getPage(slug, { sourceId });
if (!page) return { skipped: 'page_missing', slug, sourceId };
- const { runFactsBackstop } = await import('../core/facts/backstop.ts');
+ const { runFactsBackstop, coerceNotabilityFilter } = await import('../core/facts/backstop.ts');
const KNOWN_SOURCES = ['sync:import', 'mcp:put_page', 'mcp:extract_facts', 'file_upload', 'code_import', 'hook:writeback'] as const;
const source = (KNOWN_SOURCES as readonly string[]).includes(job.data.source as string)
? (job.data.source as typeof KNOWN_SOURCES[number])
@@ -2520,7 +2520,7 @@ export async function registerBuiltinHandlers(
sessionId: typeof job.data.sessionId === 'string' ? job.data.sessionId : null,
source,
mode: 'inline',
- notabilityFilter: job.data.notabilityFilter === 'high-only' ? 'high-only' : 'all',
+ notabilityFilter: coerceNotabilityFilter(job.data.notabilityFilter),
visibility: job.data.visibility === 'world' ? 'world' : 'private',
...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),
},
@@ -2925,7 +2925,8 @@ export async function registerBuiltinHandlers(
// the per-source lock) the job completes `{ deferred: true }` and retries
// next tick instead of failing — cooperative interleave (CODEX accepted).
registerBuiltinJob(worker, engine, 'extract-atoms-drain', async (job) => {
- const { runExtractAtomsDrainForSource } = await import('../core/cycle/extract-atoms-drain.ts');
+ const { formatDrainProviderFailure, runExtractAtomsDrainForSource } =
+ await import('../core/cycle/extract-atoms-drain.ts');
const { LockUnavailableError } = await import('../core/db-lock.ts');
const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;
const windowSeconds =
@@ -2949,10 +2950,7 @@ export async function registerBuiltinHandlers(
// handler failure. Partial success (>=1 item extracted) keeps
// completing normally, unchanged.
if (result.status === 'provider_failure') {
- throw new Error(
- `extract-atoms-drain: all provider calls failed this batch ` +
- `(batches=${result.batches}, remaining=${result.remaining ?? '?'}) — retrying`,
- );
+ throw new Error(formatDrainProviderFailure(result));
}
return result;
} catch (e) {
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index 90aa2f3308..9f15cda76c 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -17,7 +17,7 @@
*/
import { readFileSync, writeFileSync, readdirSync, statSync, lstatSync, existsSync } from 'fs';
-import { join, relative } from 'path';
+import { join, relative, dirname } from 'path';
import { isAborted } from '../core/abort-check.ts';
import { parseMarkdown, type ParseValidationCode } from '../core/markdown.ts';
import {
@@ -27,6 +27,7 @@ import {
} from '../core/content-sanity.ts';
import { loadOperatorLiterals } from '../core/content-sanity-literals.ts';
import { loadConfig, loadConfigWithEngine, gbrainPath } from '../core/config.ts';
+import { isDurabilityHardened, commitWriteThroughFile } from '../core/brain-repo-durability.ts';
import type { BrainEngine } from '../core/engine.ts';
export interface LintIssue {
@@ -544,6 +545,19 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
const contentSanity = opts.contentSanity ?? await resolveLintContentSanity(opts.engine);
const lintOpts: LintContentOpts = { contentSanity };
+ // Durability-hardened brains (`gbrain sources harden`) promise every write
+ // is committed AND pushed. An uncommitted lint repair would otherwise sit
+ // as drift the cycle's sync phase flags and the post-commit hook never
+ // pushes. Same gate + path-limited helper as put_page write-through
+ // (#2426); covers the cycle, the lint/lint-fix minion handlers and the CLI
+ // alike. Known ceiling: one commit + one backgrounded hook spawn per
+ // repaired page on a large first run (the hook's flock coalesces pushes on
+ // Linux; on macOS a losing concurrent push can log a spurious LOCAL-ONLY
+ // line even though the later push landed) — a single end-of-run
+ // multi-path commit would need a new helper.
+ const repoProbe = isSingleFile ? dirname(opts.target) : opts.target;
+ const commitFixes = !!opts.fix && !opts.dryRun && isDurabilityHardened(repoProbe);
+
let totalIssues = 0;
let totalFixable = 0;
let totalFixed = 0;
@@ -576,6 +590,9 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
totalFixed += fixCount;
if (!opts.dryRun) {
writeFileSync(page, fixed);
+ if (commitFixes) {
+ commitWriteThroughFile(repoProbe, page, relative(repoProbe, page).replace(/\.md$/u, ''));
+ }
}
}
}
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index daa485402b..5ded1b4d82 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -450,13 +450,28 @@ async function fetchRowsLocal(
limit: flags.limit,
});
}
+ // An explicit `--since DURATION` / `--today` cutoff is a "what happened in
+ // this window" question and keeps event-time ordering; `--since-last-run`
+ // resolves from a creation-time cursor (see the since-only arm below).
+ const windowEventTime = !flags.sinceLastRun;
if (flags.entity) {
const slug = (await resolveEntitySlug(engine, sourceId, flags.entity)) ?? flags.entity;
- const rows = await engine.listFactsByEntity(sourceId, slug, {
- activeOnly: !flags.includeExpired,
- limit: flags.limit,
- excludeAuditRows: true,
- });
+ // With a window, entity ANDs onto since in one query (before LIMIT);
+ // without one, the entity arm keeps its valid_from ordering.
+ const rows = resolvedSince
+ ? await engine.listFactsSince(sourceId, resolvedSince, {
+ eventTime: windowEventTime,
+ entitySlug: slug,
+ sessionId: flags.sessionId || undefined,
+ activeOnly: !flags.includeExpired,
+ limit: flags.limit,
+ excludeAuditRows: true,
+ })
+ : await engine.listFactsByEntity(sourceId, slug, {
+ activeOnly: !flags.includeExpired,
+ limit: flags.limit,
+ excludeAuditRows: true,
+ });
// #4720: the bare positional is entity-first, but keyless/casual usage
// treats it as a literal word from fact text (`gbrain recall commas`).
// resolveEntitySlug never returns null for non-empty input (slugify is
@@ -468,8 +483,8 @@ async function fetchRowsLocal(
// semantics (their filter already ran; no fallback surprise). Gating +
// note are shared with the thin-client mirror in runRecallOnce.
if (entityTextFallbackApplies(flags, rows.length)) {
- const textRows = await engine.listFactsSince(sourceId, new Date(0), {
- eventTime: true,
+ const textRows = await engine.listFactsSince(sourceId, resolvedSince ?? new Date(0), {
+ eventTime: resolvedSince ? windowEventTime : true,
activeOnly: !flags.includeExpired,
limit: flags.limit,
grep: flags.entity.toLowerCase(),
@@ -483,6 +498,15 @@ async function fetchRowsLocal(
return rows;
}
if (flags.sessionId) {
+ if (resolvedSince) {
+ return engine.listFactsSince(sourceId, resolvedSince, {
+ eventTime: windowEventTime,
+ sessionId: flags.sessionId,
+ activeOnly: !flags.includeExpired,
+ limit: flags.limit,
+ excludeAuditRows: true,
+ });
+ }
return engine.listFactsBySession(sourceId, flags.sessionId, {
activeOnly: !flags.includeExpired,
limit: flags.limit,
diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.ts
index 96b7011ff7..46dd739817 100644
--- a/src/commands/reindex-code.ts
+++ b/src/commands/reindex-code.ts
@@ -283,7 +283,10 @@ export async function runReindexCode(
reporter.tick();
return;
}
- if (!row.compiled_truth) {
+ // `compiled_truth` is NOT NULL DEFAULT '': an empty file is legitimately '' (every
+ // `__init__.py`). Only a null row is missing; the falsy check counted every empty
+ // file as a failure (#4902).
+ if (row.compiled_truth == null) {
failed++;
failures.push({ slug: row.slug, error: 'missing compiled_truth' });
reporter.tick();
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 93a38a0c3a..60a498d485 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -25,7 +25,7 @@ import { join } from 'node:path';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
-import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';
+import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';
import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
import { OAuthTokenRevocationRequestSchema } from '@modelcontextprotocol/sdk/shared/auth.js';
import type { BrainEngine } from '../core/engine.ts';
@@ -1275,7 +1275,15 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
// parameter, so MCP clients couldn't begin the OAuth flow from a fresh
// 401 — they would silently fail to connect with a generic "couldn't
// reach the MCP server" error.
- const resourceMetadataUrl = `${issuerUrl.toString().replace(/\/$/, '')}/.well-known/oauth-protected-resource`;
+ // RFC 9728 / MCP auth spec: the protected-resource metadata describes the
+ // resource the client connects to (/mcp), not the authorization-server root.
+ // Without resourceServerUrl the SDK falls back to issuerUrl, advertising
+ // `resource: "https://host/"` and 404ing the path-based PRM URL
+ // (/.well-known/oauth-protected-resource/mcp) that clients derive from the
+ // connector URL (#4893). The 401 challenge's resource_metadata URL is
+ // derived from the same value so the two can never drift apart.
+ const mcpResourceUrl = new URL('/mcp', issuerUrl);
+ const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(mcpResourceUrl);
// F9: cookie `secure` flag honors both the request's TLS state (req.secure
// is set when express trust-proxy lands an X-Forwarded-Proto: https) AND
@@ -1300,6 +1308,8 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
// ['read','write','admin'] list left those new scopes invisible.
scopesSupported: [...ALLOWED_SCOPES_LIST],
resourceName: 'GBrain MCP Server',
+ // Advertise /mcp as the protected resource (see mcpResourceUrl above).
+ resourceServerUrl: mcpResourceUrl,
};
// F12: DCR disable lives on the provider's constructor option above. The
@@ -1335,6 +1345,16 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
next();
});
+ // Back-compat alias: with resourceServerUrl set the SDK mounts the PRM only
+ // at the path-based URL, so clients that still probe the bare root (what
+ // gbrain advertised before) would 404 mid-flight. Rewrite the root onto the
+ // SDK's own handler — one document, same cors()/allowedMethods, no copy.
+ const legacyPrmPath = '/.well-known/oauth-protected-resource';
+ app.all(legacyPrmPath, (req: Request, _res: Response, next: NextFunction) => {
+ req.url = new URL(resourceMetadataUrl).pathname;
+ next();
+ });
+
app.use(authRouter);
// ---------------------------------------------------------------------------
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 027d7f8566..2195e17c96 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -334,7 +334,7 @@ export async function runServe(
// the MCP client log "Failed to parse JSONRPC message" for every line.
redirectStdoutLoggingToStderr();
- installStdioLifecycle(engine, args, opts);
+ const activateStdioIdleActivityTracking = installStdioLifecycle(engine, args, opts);
const start = opts.startMcpServer ?? startMcpServer;
@@ -371,13 +371,19 @@ export async function runServe(
try {
await start(engine, { surface, ...(sourceGuard ? { sourceGuard } : {}) });
+ // `--stdio-idle-timeout` arms its timer during lifecycle installation,
+ // but its stdin activity listener must wait until startMcpServer has
+ // attached the MCP SDK transport listener. Attaching any `data` listener
+ // earlier flips stdin into flowing mode and can consume a fast client's
+ // initialize frame before the SDK sees it.
+ activateStdioIdleActivityTracking();
} finally {
if (bootDeadline) clearTimeout(bootDeadline);
}
- // startMcpServer's `await server.connect(transport)` resolves once the
- // SDK has wired up its stdin 'data' listener; that listener keeps the
- // event loop alive. We deliberately do NOT add `await new Promise(() =>
- // {})` here — it would block this async frame and stop the lifecycle
+ // startMcpServer returns after the SDK has wired up its stdin 'data'
+ // listener (and completed its engine-dependent boot); that listener keeps
+ // the event loop alive. We deliberately do NOT add `await new Promise(()
+ // => {})` here — it would block this async frame and stop the lifecycle
// hooks from being able to call process.exit() cleanly.
}
@@ -433,7 +439,7 @@ function installStdioLifecycle(
engine: BrainEngine,
args: string[],
opts: ServeOptions,
-): void {
+): () => void {
const deps: StdioLifecycleDeps = {
stdin: opts.stdin ?? process.stdin,
signals: opts.signals ?? process,
@@ -448,6 +454,7 @@ function installStdioLifecycle(
let shuttingDown = false;
let parentWatchdog: unknown = null;
let idleSweepTimer: unknown = null;
+ let activateIdleActivityTracking = (): void => {};
const beginShutdown = (reason: string): void => {
if (shuttingDown) return;
shuttingDown = true;
@@ -707,6 +714,7 @@ function installStdioLifecycle(
const idleTimeoutSec = parseStdioIdleTimeout(args);
if (idleTimeoutSec > 0) {
let idleTimer: ReturnType<typeof setTimeout> | null = null;
+ let activityListenerAttached = false;
const armIdle = (): void => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(
@@ -716,12 +724,24 @@ function installStdioLifecycle(
idleTimer.unref?.();
};
armIdle();
- // Reset on every chunk. We can't observe SDK-parsed messages from
- // here, but every JSON-RPC frame causes a 'data' event on stdin, so
- // chunk-level granularity is sufficient.
- deps.stdin.on('data', armIdle);
+ activateIdleActivityTracking = (): void => {
+ if (activityListenerAttached || shuttingDown) return;
+ activityListenerAttached = true;
+ // Reset on every chunk. We can't observe SDK-parsed messages from
+ // here, but every JSON-RPC frame causes a 'data' event on stdin, so
+ // chunk-level granularity is sufficient. This listener is activated
+ // only after startMcpServer returns: adding it during lifecycle install
+ // would put stdin in flowing mode before the SDK transport attaches and
+ // race away the initialize frame.
+ deps.stdin.on('data', armIdle);
+ // Restart the countdown now that activity can actually be observed,
+ // so boot time no longer eats into the idle window.
+ armIdle();
+ };
deps.log(`GBrain MCP server: stdio idle timeout = ${idleTimeoutSec}s`);
}
+
+ return activateIdleActivityTracking;
}
/**
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 6918fd2348..a8eaa94150 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -56,6 +56,7 @@ import {
syncLockId,
} from '../core/db-lock.ts';
import {
+ withHumanLogsToStderr,
withSourcePrefix,
slog,
serr,
@@ -592,7 +593,8 @@ See also:
},
);
- console.log(`job_id=${job.id}`);
+ // --json: stdout is JSON lines (the same contract runSync keeps).
+ console.log(args.includes('--json') ? JSON.stringify({ job_id: job.id }) : `job_id=${job.id}`);
}
// The lock layer minus performSync (SyncLockBusyError, formatLockBusyMessage,
@@ -738,10 +740,23 @@ interface TrackedSlugIndex {
*/
slugs: Set<string>;
complete: boolean;
+ /**
+ * Slugs proven ONLY by the anchor tree (no current tracked file derives
+ * to them) -> the anchor paths that proved them, in the caller's path
+ * mode (`pathKey`). Lets the reconcile tell "another file owned this slug
+ * at the anchor" from "the pre-rename state of the very file this rename
+ * just re-imported" (#4597).
+ */
+ anchorOnlyPaths: Map<string, Set<string>>;
}
-function trackedSlugIndex(gitContextRoot: string, anchorCommit?: string): TrackedSlugIndex {
+function trackedSlugIndex(
+ gitContextRoot: string,
+ anchorCommit?: string,
+ pathKey: (rel: string) => string = (rel) => rel,
+): TrackedSlugIndex {
const slugs = new Set<string>();
+ const anchorOnlyPaths = new Map<string, Set<string>>();
let complete = true;
const addSlug = (slug: string): void => { slugs.add(slug); };
// --cached --others --exclude-standard mirrors gitListSyncableFiles (see
@@ -792,6 +807,7 @@ function trackedSlugIndex(gitContextRoot: string, anchorCommit?: string): Tracke
// tree is safe; reads stay bounded by the same size gates and only fire
// for fallback-regime paths.
if (anchorCommit && anchorCommit !== 'HEAD') {
+ const currentSlugs = new Set(slugs);
try {
const epochs = attributeEpochCommits(gitContextRoot, anchorCommit);
const historicalFilter = epochs === null || anyFilterAtAttributeEpochs(gitContextRoot, epochs);
@@ -800,7 +816,13 @@ function trackedSlugIndex(gitContextRoot: string, anchorCommit?: string): Tracke
if (!rel) continue;
if (resolveSlugForPath(rel) !== '' || isCodeFilePath(rel)) continue;
const res = anchorBlobSlugs(gitContextRoot, anchorCommit, rel, historicalFilter);
- for (const s of res.slugs) addSlug(s);
+ for (const s of res.slugs) {
+ addSlug(s);
+ if (currentSlugs.has(s)) continue;
+ let at = anchorOnlyPaths.get(s);
+ if (!at) anchorOnlyPaths.set(s, (at = new Set()));
+ at.add(pathKey(rel));
+ }
if (!res.proofIntact) {
complete = false;
serr(
@@ -819,7 +841,7 @@ function trackedSlugIndex(gitContextRoot: string, anchorCommit?: string): Tracke
);
}
}
- return { slugs, complete };
+ return { slugs, complete, anchorOnlyPaths };
}
/**
@@ -1346,6 +1368,28 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
typeof cfgRows[0]?.config === 'string'
? (JSON.parse(cfgRows[0].config as string) as Record<string, unknown>)
: ((cfgRows[0]?.config ?? {}) as Record<string, unknown>);
+ // #4899: EVERY caller that is not the `--all` fan-out passes no strategy —
+ // the autopilot freshness lane (commands/autopilot.ts -> jobs.ts), the dream
+ // cycle (core/cycle.ts), the MCP `sync` op (core/operations.ts) and the
+ // single-source CLI path below. `isSyncable` then falls back to 'markdown'
+ // (core/sync.ts), which drops every code file in the range. Two consequences:
+ // the run imports nothing yet still advances the anchor (`Update sync state
+ // even with no syncable changes`), freezing the index at HEAD forever; and
+ // every MODIFIED code file reaches the un-syncable delete loop, whose only
+ // exemptions are 'metafile' (#1433) and 'pruned-dir' (#2404), so its page is
+ // soft-deleted.
+ //
+ // Resolve the source's own strategy when the caller states none. An explicit
+ // --strategy still wins, so the `--all` fan-out and the CLI flag are unchanged.
+ if (opts.strategy === undefined && typeof cfg.strategy === 'string') {
+ const persisted = cfg.strategy;
+ if (persisted === 'markdown' || persisted === 'code' || persisted === 'auto') {
+ // Assign the PROPERTY, never `opts = {...opts}`: this block runs inside
+ // `if (opts.sourceId)`, and replacing the object discards that narrowing,
+ // so three downstream call sites stop compiling.
+ opts.strategy = persisted;
+ }
+ }
const remoteUrl = typeof cfg.remote_url === 'string' ? cfg.remote_url : null;
if (remoteUrl) {
const ownSrc = {
@@ -2659,11 +2703,24 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// unreadable fallback-regime file — see trackedSlugIndex), an index miss
// proves nothing, so the row is spared as 'unknown' rather than deleted.
let treeSlugIndex: TrackedSlugIndex | undefined;
- const slugLiveness = (s: string): 'live' | 'stale' | 'unknown' => {
+ const slugLiveness = (s: string, from: string): 'live' | 'stale' | 'unknown' => {
// lastCommit = the commit the brain reflects; its blob is one of the
- // consulted content states (see fallbackSlugsForFile).
- treeSlugIndex ??= trackedSlugIndex(gitContextRoot, lastCommit);
- if (treeSlugIndex.slugs.has(s)) return 'live';
+ // consulted content states (see fallbackSlugsForFile). Anchor paths
+ // are keyed through modePath so they compare against `from` under
+ // #4342 source-root mode too.
+ treeSlugIndex ??= trackedSlugIndex(gitContextRoot, lastCommit, modePath);
+ if (treeSlugIndex.slugs.has(s)) {
+ // #4597: when the ONLY liveness proof is the anchor blob at THIS
+ // rename's own from-path, that proof is the pre-rename state of the
+ // file just re-imported at `to` (the reconcile only runs once the
+ // destination materialized) — the exact duplicate it exists to
+ // remove. Sparing it checkpointed the rename as converged, so the
+ // duplicate never re-entered an incremental diff. Any current-tree
+ // hit, or anchor proof from a DIFFERENT path (the #3583 data-loss
+ // shapes), still spares the row.
+ const onlyAt = treeSlugIndex.anchorOnlyPaths.get(s);
+ if (!onlyAt || ![...onlyAt].every(p => p === from)) return 'live';
+ }
return treeSlugIndex.complete ? 'stale' : 'unknown';
};
@@ -2877,9 +2934,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// 2. Locate the stale row POSITIVELY by `source_path = from`, never
// by the oldSlug guess — after a collision, a path-derived
// fallback slug could name an unrelated (e.g. manually curated)
- // row. No source_path match → nothing is deleted (this also means
- // code-strategy imports, which don't populate source_path, fall
- // back safely to leaving the old row rather than guessing).
+ // row. No source_path match → nothing is deleted (code pages
+ // imported before `importCodeFile` wrote `source_path` (#4900)
+ // still carry NULL until their next import and fall back safely
+ // to leaving the old row rather than guessing).
//
// A failed delete records a `<rename:…>` SENTINEL (not an ordinary
// path failure): the gate hard-blocks the bookmark, and — unlike a
@@ -2938,7 +2996,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
);
continue;
}
- const verdict = slugLiveness(s);
+ const verdict = slugLiveness(s, from);
if (verdict === 'live') {
serr(
` [sync] rename reconcile: skipping live row ${s} — a tracked ` +
@@ -4353,6 +4411,16 @@ 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.
+ return args.includes('--json')
+ ? withHumanLogsToStderr(() => runSyncInner(engine, args))
+ : runSyncInner(engine, args);
+}
+
+async function runSyncInner(engine: BrainEngine, args: string[]) {
// v0.40 Federated Sync v2: `gbrain sync trigger` subcommand
// Routes to runSyncTrigger which queues a 'sync' minion job with
// auto_embed_backfill=true. Falls through to the normal sync path
@@ -4449,8 +4517,9 @@ Options:
ok_count, error_count, skipped_count}). Sources
skipped by --missing-path skip appear with
status 'skipped_missing_path' and their
- local_path. Human banners route to stderr so
- '--json | jq' parses cleanly.
+ local_path. All human output routes to stderr
+ (single-source runs too) so '--json | jq'
+ parses cleanly.
Exit codes: 0 = all sources ok or skipped,
1 = any error, 2 = cost-prompt-not-confirmed.
--yes Accept any interactive prompts (CI / non-TTY).
@@ -4763,7 +4832,7 @@ See also:
// refusal is lifted below.
if (skipFailed) {
const acked = syncAll ? acknowledgeFailures() : acknowledgeFailures(sourceId);
- if (acked.count > 0) console.log(`Acknowledged ${acked.count} pre-existing failure(s).`);
+ if (acked.count > 0) slog(`Acknowledged ${acked.count} pre-existing failure(s).`);
}
// v0.19.0 — `sync --all` iterates all registered sources with a
@@ -4796,7 +4865,7 @@ See also:
);
}
if (!sources || sources.length === 0) {
- console.log('No sources with local_path configured. Use `gbrain sources add <id> --path <path>` first.');
+ slog('No sources with local_path configured. Use `gbrain sources add <id> --path <path>` first.');
return;
}
@@ -5223,9 +5292,9 @@ See also:
// another source's failures.
const failures = unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);
if (failures.length === 0) {
- console.log('No unacknowledged sync failures to retry.');
+ slog('No unacknowledged sync failures to retry.');
} else {
- console.log(`Retrying ${failures.length} previously-failed file(s)...`);
+ slog(`Retrying ${failures.length} previously-failed file(s)...`);
// Don't acknowledge them yet — they must succeed to clear.
}
}
@@ -5307,7 +5376,7 @@ See also:
// Watch mode
let consecutiveErrors = 0;
- console.log(`Watching for changes every ${interval}s... (Ctrl+C to stop)`);
+ slog(`Watching for changes every ${interval}s... (Ctrl+C to stop)`);
while (true) {
try {
@@ -5315,7 +5384,7 @@ See also:
consecutiveErrors = 0;
if (result.status === 'synced') {
const ts = new Date().toISOString().slice(11, 19);
- console.log(`[${ts}] Synced: +${result.added} ~${result.modified} -${result.deleted} R${result.renamed}`);
+ slog(`[${ts}] Synced: +${result.added} ~${result.modified} -${result.deleted} R${result.renamed}`);
}
// Same gate as non-watch: only manage .gitignore on successful sync.
// v0.41.13.0 (T7 / D-V3-5): partial joins the deferred posture.
diff --git a/src/commands/think.ts b/src/commands/think.ts
index 01e854bd7f..fce401875e 100644
--- a/src/commands/think.ts
+++ b/src/commands/think.ts
@@ -156,10 +156,29 @@ prints what would have been the input (exit 0).
// #4508: validate --source before the gather runs — an unknown or
// archived source is a hard exit 1 (SourceTargetError message names
// it), never a silent full-brain gather.
+ // #4652: without --source, resolve the SAME default scope `gbrain
+ // search` gets from makeContext (6-tier chain + the federated set for
+ // ambient tiers) — think used to hand runThink no scope at all, so the
+ // gather spanned every source, including ones registered --no-federated.
+ // Mirrors cli.ts makeContext: an explicit / ambient target that fails
+ // to resolve throws; only a structural pre-init failure (no sources
+ // table) keeps the legacy unscoped gather.
let sourceId: string | undefined;
- if (source !== undefined) {
- const { resolveSourceWithTier } = await import('../core/source-resolver.ts');
- sourceId = (await resolveSourceWithTier(engine, source)).source_id;
+ let allowedSources: string[] | undefined;
+ const { resolveSourceWithTier, localFederatedSourceIds, ALL_SOURCES } =
+ await import('../core/source-resolver.ts');
+ const { isUndefinedTableError } = await import('../core/utils.ts');
+ try {
+ const resolved = await resolveSourceWithTier(engine, source ?? null);
+ // __all__ spans the brain; runThink has no sentinel handling of its
+ // own, so a literal '__all__' sourceId would gather nothing.
+ sourceId = resolved.source_id === ALL_SOURCES ? undefined : resolved.source_id;
+ allowedSources = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ } catch (err) {
+ // Only the structural pre-init failure (no sources table) keeps the
+ // legacy unscoped gather; every other resolver error — an unknown
+ // ambient source, a connection failure, a genuine bug — propagates.
+ if (source !== undefined || !isUndefinedTableError(err)) throw err;
}
result = await runThink(engine, {
question, anchor, rounds, save, take, model, since, until,
@@ -168,8 +187,10 @@ prints what would have been the input (exit 0).
remote: false,
// #3734: activate takes' vector retrieval arm for CLI think.
embedQuestion: (q) => embedQuery(q),
- // #4508: thread the validated scope (RunThinkOpts.sourceId).
+ // #4508/#4652: thread the validated scope (RunThinkOpts.sourceId /
+ // allowedSources — the array wins inside runGather, same as search).
...(sourceId ? { sourceId } : {}),
+ ...(allowedSources ? { allowedSources } : {}),
// #1698: explicit --model → hard error on an unresolvable model (no silent
// degrade to the no-LLM stub). Omitting --model keeps the graceful default path.
modelExplicit: !!model,
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 6652fb185c..5aed86ff26 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -22,6 +22,7 @@ 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';
interface RecentOpts {
days?: number;
@@ -290,7 +291,7 @@ export async function expandPaths(specs: string[]): Promise<string[]> {
}
}
return [...new Set(out)].filter(
- (p) => !isOpenclawCheckpointFile(p) && !isGrokSessionSidecarStrict(p),
+ (p) => !isOpenclawCheckpointFile(p) && !isGrokSessionSidecarStrict(p) && !isClaudeCodeSubagentFile(p),
);
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 734dc3a165..e10cc49590 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -110,7 +110,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
recordUpgradeError({
phase: 'binary-self-update',
fromVersion: oldVersion,
- toVersion: '',
+ toVersion: opts.targetVersion ?? result.targetVersion ?? 'unknown',
error: result.reason,
hint: 'Integrity check failed; existing binary retained. Retry or download manually.',
});
@@ -121,7 +121,7 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
recordUpgradeError({
phase: 'binary-self-update',
fromVersion: oldVersion,
- toVersion: '',
+ toVersion: opts.targetVersion ?? result.targetVersion ?? 'unknown',
error: `${result.reason}${result.error ? `: ${result.error}` : ''}`,
hint: 'Download from https://github.com/garrytan/gbrain/releases',
});
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index 29bf7e50b4..b30118e807 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -335,6 +335,13 @@ export function dimsProviderOptions(
}
return { openaiCompatible: { dimensions: dims } };
}
+ // OpenAI-compatible routers such as OpenRouter serve Gemini embeddings
+ // with the same native 3072 default the header notes for
+ // gemini-embedding-001, so narrower brains (e.g. 1024) otherwise
+ // hard-fail on the first embed without explicit dimensions passthrough.
+ if (bareModelId.startsWith('gemini-embedding') || bareModelId === 'text-embedding-004') {
+ return { openaiCompatible: { dimensions: dims } };
+ }
// DashScope text-embedding-v3 (Matryoshka 64-1024) and Zhipu
// embedding-3 (Matryoshka 256-2048) both accept `dimensions` on the
// OpenAI-compat path. Without this, user-selected non-default dims are
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 39bdc69f37..251b40d037 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -59,6 +59,7 @@ 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 { getProviderCapabilities } from './capabilities.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
import { loadConfig } from '../config.ts';
import type { GBrainConfig } from '../config.ts';
@@ -2917,7 +2918,27 @@ export async function expand(query: string): Promise<string[]> {
return parseExpansionResponse(textResult.text) ?? [];
};
- if (recipe.implementation !== 'openai-compatible') {
+ if (recipe.implementation === 'claude-cli') {
+ // claude-cli is NOT structured-output capable, despite being a 'native'
+ // tier recipe. ClaudeCliLanguageModel.doGenerate ignores
+ // `options.responseFormat` entirely (it renders prompt → `claude
+ // --print` subprocess → text), so generateObject's json_schema request
+ // is dropped on the floor and the CLI answers with markdown-fenced
+ // JSON as ordinary text. generateObject (ai@6) then throws
+ // NoObjectGeneratedError on the fenced text; the outer catch swallows
+ // it without a warn line (only AIConfigError is reported) and expansion
+ // silently degrades to the bare query — on EVERY call, after paying for
+ // the subprocess round trip. The native branch below has no viaText
+ // fallback to catch it.
+ //
+ // The schemaless text path handles this exact shape: parseLlmJson
+ // strips ```json fences (src/core/llm-json.ts) before the
+ // ExpansionSchema validation. Same recovery the openai-compatible
+ // branches already rely on, reached by implementation rather than by
+ // capability flag because claude-cli's transport — not its model — is
+ // what cannot carry a schema.
+ expansions = await viaText();
+ } else if (recipe.implementation !== 'openai-compatible') {
// Native providers (Anthropic, OpenAI, Google) support generateObject's
// structured output natively — unchanged path.
// (Typed structurally: ReturnType<GenerateObjectFn> erases the schema
@@ -3187,18 +3208,25 @@ export interface ChatToolDef {
* schema" the moment the model calls a tool. Surfaced by the SkillOpt eval.
*/
/**
- * Default per-call max output tokens. Thinking-by-default Claude 5 models
- * (`anthropic:claude-*-5`, including routed forms like
- * `openrouter:anthropic/claude-*-5`) burn a large chunk of the budget on internal
- * reasoning before emitting any text, so a 4096 default leaves them with empty
- * final text on the subagent tool loop. Give those models headroom; providers
- * bill actual tokens, not the cap, so it is free for the models that don't use
- * it. Everything else keeps 4096 on purpose: raising the default blanket-wide
- * would exceed some openai-compat providers' hard max-output caps (DeepSeek
- * 8192, gpt-4o 16384) and 400 on them — a regression for exactly the
- * non-Anthropic subagent users the gateway loop exists to serve.
+ * Default per-call max output tokens. Thinking-by-default models burn a large
+ * chunk of the budget on internal reasoning before emitting any text, so a
+ * 4096 default leaves them with empty final text (finish_reason "length") on
+ * the subagent tool loop and on any chat()/toolLoop() caller that omits
+ * maxTokens. Give those models headroom; providers bill actual tokens, not the
+ * cap, so it is free for the models that don't use it. Everything else keeps
+ * 4096 on purpose: raising the default blanket-wide would exceed some
+ * openai-compat providers' hard max-output caps (gpt-4o 16384) and 400 on
+ * them — a regression for exactly the non-Anthropic subagent users the
+ * gateway loop exists to serve.
+ *
+ * "Thinking-by-default" is decided by `isThinkingModel` below: Claude 5 by
+ * name, or any recipe whose chat touchpoint declares `thinking_by_default`
+ * (#4172, e.g. DeepSeek v4). The former "DeepSeek 8192" caveat here described
+ * the retired `deepseek-chat`; v4 accepts and honors a 32000 cap (verified
+ * 2026-09-02: max_tokens=32000 returned 19913 output tokens, finish_reason
+ * "stop"; the same prompt at 8192 truncated with finish_reason "length").
*/
-const DEFAULT_MAX_OUTPUT_TOKENS = 4096;
+export const DEFAULT_MAX_OUTPUT_TOKENS = 4096;
export const THINKING_MODEL_MAX_OUTPUT_TOKENS = 32000;
// Matches Claude 5-family ids behind ANY provider-prefix chain
// (`anthropic:claude-sonnet-5`, `openrouter:anthropic/claude-sonnet-5`,
@@ -3209,10 +3237,26 @@ const THINKING_BY_DEFAULT_MODEL_RE = /(?:^|[:/])(?:anthropic[:/])?claude-[a-z]+-
export function isThinkingByDefaultModel(modelStr: string | undefined): boolean {
return !!modelStr && THINKING_BY_DEFAULT_MODEL_RE.test(modelStr);
}
-function defaultMaxOutputTokens(modelStr: string | undefined): number {
- return isThinkingByDefaultModel(modelStr)
- ? THINKING_MODEL_MAX_OUTPUT_TOKENS
- : DEFAULT_MAX_OUTPUT_TOKENS;
+/**
+ * Name-matched Claude 5 OR recipe-declared `thinking_by_default` (#4172).
+ * Keyed on the declared capability rather than a model-name regex so a
+ * provider's model renames can't silently drop the headroom; `think`'s
+ * maxOutputTokensFor makes the same check. Fail-closed: unknown providers and
+ * chat-less recipes (getProviderCapabilities throws) count as non-thinking.
+ * Shared with the subagent handler's resolveMaxOutputTokens so the two
+ * output-cap defaults cannot drift.
+ */
+export function isThinkingModel(modelStr: string | undefined): boolean {
+ if (isThinkingByDefaultModel(modelStr)) return true;
+ if (!modelStr) return false;
+ try {
+ return getProviderCapabilities(modelStr).supportsThinking;
+ } catch {
+ return false;
+ }
+}
+export function defaultMaxOutputTokens(modelStr: string | undefined): number {
+ return isThinkingModel(modelStr) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : DEFAULT_MAX_OUTPUT_TOKENS;
}
/**
diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.ts
index 8a75c02ac9..0699ca465b 100644
--- a/src/core/ai/provider-env.ts
+++ b/src/core/ai/provider-env.ts
@@ -39,6 +39,7 @@ export function mergedProviderEnv(
if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;
if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;
if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;
+ if (cfg?.deepseek_api_key) fromConfig.DEEPSEEK_API_KEY = cfg.deepseek_api_key;
// Same seam for LiteLLM + Together, closed alongside litellm's chat
// touchpoint (v0.42.61.0 made litellm a full chat provider, so the
// config-plane gap started biting daemon/launchd/MCP contexts the same
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 59b885bfee..738e276d31 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -456,6 +456,38 @@ interface ParsedToolCall {
input: string;
}
+/**
+ * Keys the `<use_tools>` protocol reserves on an entry. `type: "tool_use"`
+ * and a `toolu_*` `id` are tolerated leftovers of the Anthropic tool_use
+ * shape; nothing reads them. Any OTHER `type`/`id` value is a real tool
+ * argument (e.g. the allowlisted `list_pages` op's `type` filter) and stays.
+ */
+function isReservedEntryKey(k: string, v: unknown): boolean {
+ if (k === 'name' || k === 'input') return true;
+ if (k === 'type') return v === 'tool_use';
+ if (k === 'id') return typeof v === 'string' && v.startsWith('toolu_');
+ return false;
+}
+
+/**
+ * Resolve the tool input of one `<use_tools>` entry. The protocol asks for
+ * `{name, input}`, but the model sometimes emits the arguments flat on the
+ * entry itself (`{"name": "brain_search", "query": "..."}`), the Anthropic
+ * tool_use shape with the `input` wrapper dropped. Reading only `e.input`
+ * turned every such call into `{}`, and the tool then failed on its missing
+ * required parameter with nothing the model could act on. When `input` is
+ * absent, the entry's non-reserved keys ARE the input; when it is present
+ * it wins verbatim, stray sibling keys ignored.
+ */
+function resolveEntryInput(e: Record<string, unknown>): unknown {
+ if (e.input !== undefined && e.input !== null) return e.input;
+ const flat: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(e)) {
+ if (!isReservedEntryKey(k, v)) flat[k] = v;
+ }
+ return flat;
+}
+
/**
* Locate and parse the `<use_tools>...</use_tools>` block in the assistant's
* raw text response. Returns the parsed tool calls plus whatever prose
@@ -470,33 +502,56 @@ function extractToolCalls(raw: string): {
} {
const openTag = '<use_tools>';
const closeTag = '</use_tools>';
- const openIdx = raw.indexOf(openTag);
- if (openIdx === -1) {
- return { toolCalls: [], beforeText: raw.trim(), afterText: '' };
+ // No single anchoring rule survives every shape the model emits: a prose
+ // mention of `<use_tools>` BEFORE the block ("Let me use the correct
+ // `<use_tools>` format:") breaks anchoring on the first open tag; a prose
+ // mention of `</use_tools>` before the block breaks anchoring on the first
+ // close tag; and a LITERAL tag inside a JSON string argument (a page body
+ // being written that documents the protocol) breaks "last open tag before
+ // the close" — the inner tag wins, the slice is truncated JSON, and a
+ // valid call is discarded as prose. So: enumerate the (open, close) pairs
+ // outermost-first (earliest open, then each later close) and accept the
+ // first slice that parses as a JSON array. Tags inside argument strings
+ // sit inside an accepted slice or produce a rejected one; they never anchor.
+ // ponytail: O(opens × closes) JSON.parse attempts — tags are a handful per
+ // response; a linear scanner is the upgrade if a payload ever has hundreds.
+ const opens: number[] = [];
+ for (let i = raw.indexOf(openTag); i !== -1; i = raw.indexOf(openTag, i + 1)) opens.push(i);
+ const closes: number[] = [];
+ for (let i = raw.indexOf(closeTag); i !== -1; i = raw.indexOf(closeTag, i + 1)) closes.push(i);
+
+ let parsed: unknown[] | null = null;
+ let openIdx = -1;
+ let closeIdx = -1;
+ let firstError: string | null = null;
+ outer: for (const o of opens) {
+ for (const c of closes) {
+ if (c < o + openTag.length) continue;
+ let inner = raw.slice(o + openTag.length, c).trim();
+ if (inner.startsWith('```')) {
+ inner = inner.replace(/^```(?:json|JSON)?\s*\n?/, '').replace(/\n?```$/, '').trim();
+ }
+ try {
+ const v: unknown = JSON.parse(inner);
+ if (Array.isArray(v)) { parsed = v; openIdx = o; closeIdx = c; break outer; }
+ } catch (e) {
+ firstError ??= e instanceof Error ? e.message : String(e);
+ }
+ }
}
- const closeIdx = raw.indexOf(closeTag, openIdx + openTag.length);
- if (closeIdx === -1) {
- // Unterminated block — recover gracefully.
+ if (parsed === null) {
+ // A malformed block is a LOST tool call — the caller sees prose and the
+ // turn ends as if the model never called anything. Say so on stderr.
+ // (No pair at all — unterminated, absent, or only orphan close tags — and
+ // a non-array payload both recover silently as before.)
+ if (firstError !== null) {
+ process.stderr.write(`[claude-cli] <use_tools> block failed to parse — tool call discarded: ${firstError}\n`);
+ }
return { toolCalls: [], beforeText: raw.trim(), afterText: '' };
}
const beforeText = raw.slice(0, openIdx).trim();
const afterText = raw.slice(closeIdx + closeTag.length).trim();
- let inner = raw.slice(openIdx + openTag.length, closeIdx).trim();
-
- if (inner.startsWith('```')) {
- inner = inner.replace(/^```(?:json|JSON)?\s*\n?/, '').replace(/\n?```$/, '').trim();
- }
-
- let parsed: unknown;
- try {
- parsed = JSON.parse(inner);
- } catch {
- return { toolCalls: [], beforeText: raw.trim(), afterText: '' };
- }
- if (!Array.isArray(parsed)) {
- return { toolCalls: [], beforeText: raw.trim(), afterText: '' };
- }
const toolCalls: ParsedToolCall[] = [];
for (const entry of parsed) {
@@ -514,7 +569,7 @@ function extractToolCalls(raw: string): {
// is deliberately ignored — nothing round-trips it (renderPrompt strips
// ids on replay; the loop pairs results in-memory within one turn).
const id = `toolu_claude_cli_${randomUUIDv7()}`;
- const inputJson = JSON.stringify(e.input ?? {});
+ const inputJson = JSON.stringify(resolveEntryInput(e));
toolCalls.push({ id, name, input: inputJson });
}
diff --git a/src/core/ai/recipes/anthropic.ts b/src/core/ai/recipes/anthropic.ts
index ed03f7bd5e..44c8af3cd8 100644
--- a/src/core/ai/recipes/anthropic.ts
+++ b/src/core/ai/recipes/anthropic.ts
@@ -24,6 +24,7 @@ export const anthropic: Recipe = {
chat: {
models: [
'claude-fable-5',
+ 'claude-fable-5-1',
'claude-opus-5',
'claude-opus-4-8',
'claude-opus-4-7',
@@ -36,6 +37,7 @@ export const anthropic: Recipe = {
supports_prompt_cache: true,
model_context_tokens: {
'claude-fable-5': 1_000_000,
+ 'claude-fable-5-1': 1_000_000,
'claude-opus-5': 1_000_000,
'claude-sonnet-5': 1_000_000,
'claude-opus-4-8': 1_000_000,
diff --git a/src/core/ai/recipes/claude-cli.ts b/src/core/ai/recipes/claude-cli.ts
index eb60e1f1c7..0862679225 100644
--- a/src/core/ai/recipes/claude-cli.ts
+++ b/src/core/ai/recipes/claude-cli.ts
@@ -11,9 +11,10 @@ import type { Recipe } from '../types.ts';
* pick per call: `anthropic:claude-sonnet-4-6` (API key + per-token billing)
* vs `claude-cli:claude-sonnet-4-6` (OAuth subscription, no API key).
*
- * Chat-only. Claude has no first-party embedding model; users wanting an
- * Anthropic chat path with embeddings still combine this with openai/google/
- * voyage for embedding the way the existing `anthropic` recipe documents.
+ * Chat + expansion; no embedding. Claude has no first-party embedding model;
+ * users wanting an Anthropic chat path with embeddings still combine this with
+ * openai/google/voyage for embedding the way the existing `anthropic` recipe
+ * documents.
*
* Auth: `auth_env.required: []` because the CLI handles auth itself. The
* `claude` binary on PATH (or `GBRAIN_CLAUDE_CLI_BIN`) IS the auth surface;
@@ -32,10 +33,47 @@ export const claudeCli: Recipe = {
required: [],
},
touchpoints: {
- // No embedding or expansion touchpoints — chat-only.
+ // No embedding touchpoint — Claude has no first-party embedding model.
+ //
+ // `expansion` IS declared (it was not, pre-fix). Without it,
+ // `isAvailable('expansion')` in gateway.ts returns false for every
+ // claude-cli model, so `expandQuery()` in src/core/search/expansion.ts
+ // returns [query] before any model call — query expansion silently
+ // disappears with no error and no log line, and `gbrain models doctor`
+ // still reports the touchpoint green because its probe calls `chat()`
+ // with an explicit `model:` override and never consults the recipe.
+ // A brain whose tier.utility points at claude-cli therefore lost the
+ // multi-query recall arm that `query` exists to provide.
+ //
+ // instantiateExpansion() in gateway.ts already had a `case 'claude-cli'`
+ // waiting for this declaration; it returns the same
+ // ClaudeCliLanguageModel that chat uses.
+ expansion: {
+ // Cheap model first: `providers explain` / init auto-pick advertise
+ // models[0] for this touchpoint (same convention as the openai recipe).
+ models: [
+ 'claude-haiku-4-5-20251001',
+ 'claude-fable-5',
+ 'claude-fable-5-1',
+ 'claude-opus-5',
+ 'claude-opus-4-8',
+ 'claude-opus-4-7',
+ 'claude-sonnet-5',
+ 'claude-sonnet-4-6',
+ ],
+ // Nominal — the subscription bears the actual bill. Mirrors the chat
+ // touchpoint's rationale below.
+ cost_per_1m_tokens_usd: 3.0,
+ price_last_verified: '2026-06-17',
+ // Same subprocess cold start as chat: `claude -p` routinely takes 5-6s
+ // before emitting a token. The probe's flat 5000ms default would
+ // false-fail on every run.
+ default_timeout_ms: 30_000,
+ },
chat: {
models: [
'claude-fable-5',
+ 'claude-fable-5-1',
'claude-opus-5',
'claude-opus-4-8',
'claude-opus-4-7',
diff --git a/src/core/ai/recipes/minimax.ts b/src/core/ai/recipes/minimax.ts
index 469c482488..553ded55e8 100644
--- a/src/core/ai/recipes/minimax.ts
+++ b/src/core/ai/recipes/minimax.ts
@@ -144,7 +144,14 @@ export const minimax: Recipe = {
'MiniMax-M2.1-highspeed',
'MiniMax-M2',
],
- supports_tools: false,
+ // MiniMax M2+/M3 chat returns OpenAI-compatible tool_calls: a live
+ // tools -> role:tool continuation round-trip was verified (#4782). The
+ // original `false` came from #1977's untested suggested snippet (plain
+ // chat probe only), not from any provider test. Same call as the
+ // Moonshot/Mistral recipes: ordinary tool calls are fine, but the
+ // subagent loop stays refused until a live abort/retry replay pin lands
+ // (see the OpenRouter-family precedent in TODOS).
+ supports_tools: true,
supports_subagent_loop: false,
},
},
diff --git a/src/core/ai/recipes/voyage.ts b/src/core/ai/recipes/voyage.ts
index 70e440e4ba..7424df5b1e 100644
--- a/src/core/ai/recipes/voyage.ts
+++ b/src/core/ai/recipes/voyage.ts
@@ -72,14 +72,20 @@ export const voyage: Recipe = {
// {object: "list", data: [{index, relevance_score}]} — live-wire verified
// 2026-08-15; the gateway's parser accepts both data[] and results[].
reranker: {
- models: ['rerank-2.5', 'rerank-2.5-lite'],
+ // #4938: rerank-3 / rerank-3-lite are Voyage's preview generation on the
+ // same /rerank wire (path + top_param unchanged). default_model stays
+ // rerank-2.5 so an upgrade never moves an install; opt in with
+ // `gbrain config set search.reranker.model voyage:rerank-3`.
+ models: ['rerank-2.5', 'rerank-2.5-lite', 'rerank-3', 'rerank-3-lite'],
default_model: 'rerank-2.5',
path: '/rerank',
top_param: 'top_k',
- // https://docs.voyageai.com/docs/pricing (verified 2026-08-15):
- // rerank-2.5 $0.05/M, rerank-2.5-lite $0.02/M.
+ // https://docs.voyageai.com/docs/pricing (2.5 pair verified 2026-08-15,
+ // rerank-3 pair 2026-09-06): rerank-2.5 / rerank-3 $0.05/M,
+ // rerank-2.5-lite / rerank-3-lite $0.02/M. Per-model billing math goes
+ // through src/core/embedding-pricing.ts; this scalar is a display hint.
cost_per_1m_tokens_usd: 0.05,
- price_last_verified: '2026-08-15',
+ price_last_verified: '2026-09-06',
// Voyage enforces token-based caps (32K per query+document pair,
// ≤1000 documents/request) rather than a byte cap; 5MB is a
// conservative byte-level proxy matching the ZE-era pre-flight so
diff --git a/src/core/autopilot-lock.ts b/src/core/autopilot-lock.ts
index 38474fd6bc..c816b7624f 100644
--- a/src/core/autopilot-lock.ts
+++ b/src/core/autopilot-lock.ts
@@ -1,4 +1,4 @@
-import { execFileSync } from 'node:child_process';
+import { execFileSync, type ExecFileSyncOptionsWithStringEncoding } from 'node:child_process';
import { readFileSync } from 'node:fs';
export type AutopilotLockHolder =
@@ -26,15 +26,36 @@ export function isPidAlive(pid: number): boolean {
export interface ProcessCommandProbeDeps {
/** Injected for tests; defaults to fs.readFileSync of /proc/<pid>/cmdline. */
readCmdlineFile?: (path: string) => Buffer | string;
+ /** Injected for tests; defaults to process.platform. */
+ platform?: NodeJS.Platform;
+ /** Injected for tests; defaults to child_process.execFileSync (ps / powershell). */
+ execFile?: (file: string, args: string[], options: ExecFileSyncOptionsWithStringEncoding) => string;
}
/**
* Best-effort process command lookup. On Linux, /proc/<pid>/cmdline is read
* first (no subprocess, works even when `ps` is unavailable or restricted —
* e.g. minimal containers), falling back to `ps -o args=` elsewhere (#4300).
+ * Windows has neither /proc nor `ps`, so it asks CIM via powershell instead
+ * (#4563) — without this every holder classified as alive-unknown there.
*/
export function readProcessCommand(pid: number, deps: ProcessCommandProbeDeps = {}): string | null {
if (!Number.isFinite(pid) || pid <= 0) return null;
+ const exec = deps.execFile ?? execFileSync;
+ if ((deps.platform ?? process.platform) === 'win32') {
+ // Get-CimInstance, not wmic (removed on Win11 24H2). pid is validated
+ // finite/positive above, so the WQL filter is injection-safe. Return
+ // early: the POSIX probes below are guaranteed to throw on Windows.
+ try {
+ const out = exec('powershell.exe', [
+ '-NoProfile', '-NonInteractive', '-Command',
+ `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object -ExpandProperty CommandLine`,
+ ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000, windowsHide: true }).trim();
+ return out.length > 0 ? out : null;
+ } catch {
+ return null;
+ }
+ }
const readCmdline = deps.readCmdlineFile ?? readFileSync;
try {
const raw = readCmdline(`/proc/${pid}/cmdline`);
@@ -45,7 +66,7 @@ export function readProcessCommand(pid: number, deps: ProcessCommandProbeDeps =
// Not Linux (no /proc) or unreadable — fall through to ps.
}
try {
- const out = execFileSync('ps', ['-p', String(pid), '-o', 'args='], {
+ const out = exec('ps', ['-p', String(pid), '-o', 'args='], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 1000,
@@ -59,7 +80,8 @@ export function readProcessCommand(pid: number, deps: ProcessCommandProbeDeps =
export function looksLikeGbrainAutopilotCommand(command: string): boolean {
const normalized = command.replace(/\\/g, '/').trim();
if (!/(^|\s)autopilot(\s|$)/i.test(normalized)) return false;
- if (/(^|[\/\s])gbrain(?:\.exe)?(\s|$)/i.test(normalized)) return true;
+ // Win32_Process.CommandLine quotes executables under paths with spaces: `"C:/Program Files/gbrain/gbrain.exe" autopilot`.
+ if (/(^|[\/\s])"?gbrain(?:\.exe)?"?(\s|$)/i.test(normalized)) return true;
return /(^|\s)(?:\S+\/)?(?:\.{1,2}\/)?(?:src\/)?cli\.(?:ts|js|mjs)(\s|$)/i.test(normalized)
|| /(^|\s)\S*\/src\/cli\.(?:ts|js|mjs)(\s|$)/i.test(normalized);
}
diff --git a/src/core/binary-self-update.ts b/src/core/binary-self-update.ts
index ea0ba7c891..717c8fcffb 100644
--- a/src/core/binary-self-update.ts
+++ b/src/core/binary-self-update.ts
@@ -100,6 +100,8 @@ export interface BinarySelfUpdateResult {
error?: string;
/** Asset name resolved (when applicable). */
asset?: string;
+ /** Release version resolved from GitHub, even when a later step fails. */
+ targetVersion?: string;
}
/** The release asset basename gbrain publishes for this platform/arch, or null
@@ -342,10 +344,11 @@ export async function runBinarySelfUpdate(
if (!release) {
return { ok: false, reason: 'fetch_failed', asset: assetName };
}
+ const targetVersion = release.tag.replace(/^v/, '').trim();
const url = resolvePlatformAsset(release.assets, platform, arch);
if (!url) {
- return { ok: false, reason: 'no_asset', asset: assetName };
+ return { ok: false, reason: 'no_asset', asset: assetName, targetVersion };
}
// Stage in a temp sibling so the rename is same-filesystem (atomic).
@@ -354,7 +357,7 @@ export async function runBinarySelfUpdate(
await download(url, staged);
} catch (e) {
safeUnlink(staged);
- return { ok: false, reason: 'download_failed', error: errMsg(e), asset: assetName };
+ return { ok: false, reason: 'download_failed', error: errMsg(e), asset: assetName, targetVersion };
}
// Integrity BEFORE chmod/exec: never make an unverified binary executable and
@@ -362,38 +365,38 @@ export async function runBinarySelfUpdate(
const integrityFailure = await verifyIntegrity(staged, assetName, computeDigest, fetchAttestation);
if (integrityFailure) {
safeUnlink(staged);
- return { ok: false, reason: integrityFailure, asset: assetName };
+ return { ok: false, reason: integrityFailure, asset: assetName, targetVersion };
}
try {
chmodSync(staged, 0o755);
} catch (e) {
safeUnlink(staged);
- return { ok: false, reason: 'download_failed', error: errMsg(e), asset: assetName };
+ return { ok: false, reason: 'download_failed', error: errMsg(e), asset: assetName, targetVersion };
}
if (!smoke(staged)) {
safeUnlink(staged);
- return { ok: false, reason: 'smoke_failed', asset: assetName };
+ return { ok: false, reason: 'smoke_failed', asset: assetName, targetVersion };
}
// Downgrade-replay guard: the staged binary must actually be the release it
// claims. A swapped asset serving an older, still-validly-attested binary
// clears digest+builder but reports the wrong version here.
- const expectedVersion = release.tag.replace(/^v/, '').trim();
+ const expectedVersion = targetVersion;
if (expectedVersion && !checkVersion(staged, expectedVersion)) {
safeUnlink(staged);
- return { ok: false, reason: 'version_mismatch', asset: assetName };
+ return { ok: false, reason: 'version_mismatch', asset: assetName, targetVersion };
}
try {
renameSync(staged, targetPath); // atomic on same fs; old binary intact if this throws
} catch (e) {
safeUnlink(staged);
- return { ok: false, reason: 'replace_failed', error: errMsg(e), asset: assetName };
+ return { ok: false, reason: 'replace_failed', error: errMsg(e), asset: assetName, targetVersion };
}
- return { ok: true, asset: assetName };
+ return { ok: true, asset: assetName, targetVersion };
}
function safeUnlink(path: string): void {
diff --git a/src/core/bootstrap/format.ts b/src/core/bootstrap/format.ts
index e647f8968e..3904318aaf 100644
--- a/src/core/bootstrap/format.ts
+++ b/src/core/bootstrap/format.ts
@@ -264,6 +264,10 @@ export interface HarnessReceipt {
/** Serve version at apply time — --status re-checks for skew [F7]. */
serve_version?: string;
source_id: string;
+ /** False when the hooks carry NO `GBRAIN_SOURCE` pin (a live PGLite serve hid
+ * which source it resolves, the --token lane proceeded unpinned and `source_id`
+ * records the federated floor `default`). Absent = pinned to `source_id`. */
+ source_pinned?: false;
token: {
name: string;
/** Row id — the only safe revocation key. */
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index 68b0dafd12..4a5a4d0ada 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -55,6 +55,8 @@ import {
stripAmbientWritebackBlockAt,
} from './instructions-block.ts';
import { createEngine } from '../engine-factory.ts';
+import { isValidSourceId } from '../source-id.ts';
+import { ALL_SOURCES, isResolverUserError, localFederatedSourceIds, resolveSourceWithTier } from '../source-resolver.ts';
import { probeBrainIdentity, type ConnectProbeResult } from '../connect-probe.ts';
import {
buildClaudeMcpAddArgv,
@@ -201,7 +203,15 @@ export function parseHarnessArgs(rest: string[]): HarnessFlags {
out.port = n;
}
const source = value('--source');
- if (source !== undefined) out.source = source;
+ if (source !== undefined) {
+ // Every other flag is validated here; a typo'd id would otherwise mint a
+ // token and wire hooks to a phantom scope (reads return nothing).
+ if (!isValidSourceId(source)) {
+ out.error = `invalid --source '${source}' (a source id matches [a-z0-9-]{1,32}; '${ALL_SOURCES}' is not a hook scope)`;
+ return out;
+ }
+ out.source = source;
+ }
out.tokenName = value('--token-name') ?? out.tokenName;
const token = value('--token');
if (token !== undefined) out.token = token;
@@ -284,6 +294,14 @@ export interface HarnessDeps {
sourceGrant?: string[];
}) => Promise<MintedLegacyToken>;
revokeById?: (id: string) => Promise<boolean>;
+ /** Resolve the source the hooks + token bind to, through the SAME resolver
+ * the serve's resolve-IPC binding uses (resolveSourceWithTier: env →
+ * dotfile → local_path → sources.default → sole non-default → seed
+ * default), plus that source's local federated read set, so the hook lane
+ * reads what search/think read (#4897). `explicit` = --source (validated +
+ * asserted to exist). Throws on an unknown id or an unopenable engine — the
+ * caller decides fail-open vs fail-closed. Tests inject a fake. */
+ resolveHookSource?: (explicit: string | null) => Promise<HookSourceBinding>;
/** Live-PGLite-serve pre-probe for the revoke lane [C9]. */
pgliteLiveServe?: () => boolean;
detectClaude?: () => boolean;
@@ -322,6 +340,7 @@ function resolveDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>
loadFileConfig: deps.loadFileConfig ?? loadConfigFileOnly,
mint: deps.mint ?? defaultMint,
revokeById: deps.revokeById ?? defaultRevokeById,
+ resolveHookSource: deps.resolveHookSource ?? defaultResolveHookSource,
pgliteLiveServe: deps.pgliteLiveServe ?? defaultPgliteLiveServe,
// #4325: config-dir fallback mirrors detectCodex/detectOpencode below —
// CI runners and alias-only shells don't expose a `claude` binary on the
@@ -411,6 +430,35 @@ async function defaultMint(opts: { name: string; scopes: string[]; sourceGrant?:
}
}
+/** The source the hooks + token bind to, and the read grant the token carries. */
+export interface HookSourceBinding {
+ source_id: string;
+ /** The federated read set for an ambient tier (what search/think read);
+ * `[source_id]` for an explicit --source or a non-federated source. */
+ grant: string[];
+}
+
+/** Production hook-source lookup: the SAME resolver the serve's resolve-IPC
+ * binding runs (`resolveSourceWithTier(engine, null)`), so the hooks claim
+ * exactly the source the serve resolves; an explicit --source goes through
+ * tier 1 (shape + existence). NOT fail-open: on a PGLite brain under a live
+ * serve the engine cannot open, and applyHarness decides what that means
+ * (refuse without --source; bind an explicit --source unverified). */
+async function defaultResolveHookSource(explicit: string | null): Promise<HookSourceBinding> {
+ const cfg = loadConfig();
+ if (!cfg) throw new Error('no brain configured (run `gbrain init` first)');
+ const engineConfig = toEngineConfig(cfg);
+ const engine = await createEngine(engineConfig);
+ await engine.connect(engineConfig);
+ try {
+ const resolved = await resolveSourceWithTier(engine, explicit);
+ const grant = (await localFederatedSourceIds(engine, resolved.source_id, resolved.tier)) ?? [resolved.source_id];
+ return { source_id: resolved.source_id, grant };
+ } finally {
+ await engine.disconnect();
+ }
+}
+
async function defaultRevokeById(id: string): Promise<boolean> {
const cfg = loadConfig();
if (!cfg) throw new Error('no brain configured');
@@ -668,6 +716,22 @@ async function cleanupStalePriorTargets(
}
}
+/** A live `gbrain serve` holds this PGLite brain: the two documented escape hatches. */
+function liveServeRefusal(): BootstrapError {
+ return new BootstrapError(
+ 'LIVE_SERVE',
+ 'a live `gbrain serve` holds this PGLite brain, so the harness cannot mint a token — either ' +
+ 'pre-mint one while the serve is stopped (`gbrain auth create bootstrap-harness --scopes read,write`) ' +
+ 'and re-run with --token <value>, or stop the serve, re-run this command, and restart it. ' +
+ '(Postgres brains mint fine while the serve runs.)',
+ );
+}
+
+/** The engine could not open because a live serve holds the PGLite brain (vs any other failure). */
+function isLiveServeFailure(msg: string, d: Pick<Required<HarnessDeps>, 'pgliteLiveServe'>): boolean {
+ return /already open through `gbrain serve`|LiveServeLockError/i.test(msg) || d.pgliteLiveServe();
+}
+
export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Promise<number> {
const d = resolveDeps(rawDeps);
// stdout-for-data discipline: under --json, stdout carries ONLY the final
@@ -862,6 +926,66 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// 4. Plan targets + WRITE-AHEAD receipt [F1/X6] — BEFORE the mint, so a
// crash (or a newer-format receipt refusal) can never leave a live token
// no receipt records.
+ // #4897: without --source the hooks must claim the source the serve's
+ // resolve-IPC listener is bound to — resolved through the SAME chain the
+ // serve runs (env → dotfile → local_path → sources.default → sole
+ // non-default → seed default), or every turn_context is `source_mismatch`.
+ // The token floors on that source's federated read set (what search/think
+ // read): the federated-default mint cannot read a sole non-federated
+ // source (page_count 0). A resolution that lands on the seeded 'default'
+ // (or a `__all__` env) is the federated floor, not a scalar grant (same
+ // guard as dream.ts).
+ let bound: HookSourceBinding;
+ // Live PGLite serve + --token, no --source: the hooks carry NO source pin
+ // (a claim-free request resolves through the serve's own binding).
+ let unpinnedHooks = false;
+ try {
+ bound = await d.resolveHookSource(flags.source ?? null);
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (isResolverUserError(e)) {
+ // A typo'd --source / stale GBRAIN_SOURCE or dotfile: minting a token
+ // to a phantom scope would "succeed" and then read nothing.
+ throw new BootstrapError('SOURCE_UNRESOLVED', msg);
+ }
+ if (flags.source) {
+ // The engine could not open (a live PGLite serve + --token is the
+ // documented path here); the explicit id is the operator's word.
+ d.logError(`WARNING: could not verify --source '${flags.source}' against the brain (${msg}); binding to it unverified.`);
+ bound = { source_id: flags.source, grant: [flags.source] };
+ } else if (isLiveServeFailure(msg, d)) {
+ // A live PGLite serve holds the brain. Without a token the mint below
+ // would refuse anyway — refuse HERE with the same two escape hatches, so
+ // the operator never sees a source-resolution error for a lock problem.
+ if (flags.token === undefined) throw liveServeRefusal();
+ // --token lane (the documented PGLite path): nothing is minted, so the
+ // grant is the operator's own token. Leave the hooks UNPINNED — a hook
+ // request that names no source resolves through the live serve's own
+ // binding, which is exactly the source the serve resolves (#4897). Say
+ // so, and name the override.
+ d.logError(
+ 'WARNING: a live `gbrain serve` holds this PGLite brain, so the harness could not read which source it ' +
+ "serves; wiring the hooks unpinned (they resolve through the live serve). If `gbrain sources list` " +
+ "shows a default other than 'default', re-run with --source <id>.",
+ );
+ bound = { source_id: 'default', grant: ['default'] };
+ unpinnedHooks = true;
+ } else {
+ // Silently binding 'default' here is the #4897 bug reopened: the serve
+ // may resolve a different source and every hook turn would mismatch.
+ throw new BootstrapError(
+ 'SOURCE_UNRESOLVED',
+ `could not resolve the source the serve binds its hooks to (${msg}) — pass --source <id> ` +
+ '(`gbrain sources list` shows the registered ids) and re-run.',
+ );
+ }
+ }
+ const implicitSource =
+ flags.source || bound.source_id === 'default' || bound.source_id === ALL_SOURCES ? null : bound.source_id;
+ const hookSource: string | null = unpinnedHooks ? null : (flags.source ?? implicitSource ?? 'default');
+ if (implicitSource) {
+ d.log(`binding hooks + token to source '${implicitSource}' (the serve's resolved default; pass --source to override).`);
+ }
const guard = guardHarnessReceiptOverwrite(d.gbrainHome);
if (guard.brokenBackupPath) {
d.logError(`WARNING: the harness receipt was unreadable; backed it up to ${guard.brokenBackupPath}.`);
@@ -956,7 +1080,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
url,
...(health.engine ? { engine: health.engine } : {}),
...(health.version ? { serve_version: health.version } : {}),
- source_id: flags.source ?? 'default',
+ source_id: hookSource ?? 'default',
+ ...(unpinnedHooks ? { source_pinned: false as const } : {}),
token: {
name: flags.tokenName,
minted: flags.token === undefined,
@@ -983,20 +1108,15 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
name: flags.tokenName,
scopes: ['read', 'write'],
// [X2] --source is the write floor — a scalar grant, the stdio
- // env-tier mirror. Without it the default mint federates.
- ...(flags.source ? { sourceGrant: [flags.source] } : {}),
+ // env-tier mirror. An implicit non-default source carries its
+ // federated read set (#4897 — the same set search/think read, not a
+ // scalar that would hide every federated sibling). Neither → the
+ // default mint federates.
+ ...(flags.source || implicitSource ? { sourceGrant: bound.grant } : {}),
});
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- if (/already open through `gbrain serve`|LiveServeLockError/i.test(msg) || d.pgliteLiveServe()) {
- throw new BootstrapError(
- 'LIVE_SERVE',
- 'a live `gbrain serve` holds this PGLite brain, so the harness cannot mint a token — either ' +
- 'pre-mint one while the serve is stopped (`gbrain auth create bootstrap-harness --scopes read,write`) ' +
- 'and re-run with --token <value>, or stop the serve, re-run this command, and restart it. ' +
- '(Postgres brains mint fine while the serve runs.)',
- );
- }
+ if (isLiveServeFailure(msg, d)) throw liveServeRefusal();
throw e;
}
token = minted.token;
@@ -1148,7 +1268,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
} else {
const settingsPath = t.scope === 'user' ? d.userSettingsPath : t.path!;
const env: ClaudeHookEnv = {
- GBRAIN_SOURCE: flags.source ?? 'default',
+ ...(hookSource !== null ? { GBRAIN_SOURCE: hookSource } : {}),
GBRAIN_HOOK_LANE: 'harness',
};
const bin = flags.gbrainBin ?? d.gbrainBin;
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index 74fc45f1d9..b45f09d00a 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -42,8 +42,12 @@ import {
/** Env vars embedded in each hook command string [G1, CX-P1.4]. */
export interface ClaudeHookEnv {
- /** Workspace source binding — required so hook context is source-scoped [G1]. */
- GBRAIN_SOURCE: string;
+ /** Workspace source binding so hook context is source-scoped [G1]. Omitted
+ * ONLY by the harness lane when a live PGLite serve hides which source it
+ * resolves: an unpinned hook names no source, so the serve answers with its
+ * own binding instead of rejecting a wrong claim as `source_mismatch`. The
+ * committed carrier (buildPortableClaudeHookCommand) always requires it. */
+ GBRAIN_SOURCE?: string;
/** Set only for --isolated installs (PARENT dir; config appends `.gbrain`). */
GBRAIN_HOME?: string;
/**
@@ -155,7 +159,8 @@ export function buildClaudeHookCommand(
event: ClaudeHookEvent,
env: ClaudeHookEnv,
): string {
- const assignments: string[] = [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`];
+ const assignments: string[] = [];
+ if (env.GBRAIN_SOURCE !== undefined) assignments.push(`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`);
if (env.GBRAIN_HOME) assignments.push(`GBRAIN_HOME=${env.GBRAIN_HOME}`);
if (env.GBRAIN_HOOK_LANE) assignments.push(`GBRAIN_HOOK_LANE=${env.GBRAIN_HOOK_LANE}`);
const parts = ['env', ...assignments, gbrainBin, 'hook', CLAUDE_HOOK_SUBCOMMAND[event]];
@@ -173,6 +178,9 @@ export function claudeCommittedSettingsPath(workspaceDir: string): string {
* instead of erroring every turn.
*/
export function buildPortableClaudeHookCommand(event: ClaudeHookEvent, env: ClaudeHookEnv): string {
+ if (env.GBRAIN_SOURCE === undefined) {
+ throw new Error('the committed hook carrier must be source-scoped [G1] — GBRAIN_SOURCE is required');
+ }
const assignments: string[] = [`GBRAIN_SOURCE=${env.GBRAIN_SOURCE}`];
if (env.GBRAIN_HOME) assignments.push(`GBRAIN_HOME=${env.GBRAIN_HOME}`);
const invoke = ['env', ...assignments, 'gbrain', 'hook', CLAUDE_HOOK_SUBCOMMAND[event]]
diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.ts
index 456618c64a..985404637e 100644
--- a/src/core/bootstrap/host-specs.ts
+++ b/src/core/bootstrap/host-specs.ts
@@ -370,6 +370,19 @@ export function codexSessionsDir(): string {
return join(codexHome(), 'sessions');
}
+/**
+ * Codex ARCHIVED rollout store — (CODEX_HOME || ~/.codex)/archived_sessions/
+ * rollout-*.jsonl. Codex moves a rollout here when a session is archived, and
+ * the store is FLAT: no YYYY/MM/DD nesting, unlike codexSessionsDir (verified
+ * on a live 0.147.0 host — 363 rollouts, zero subdirectories). It is the same
+ * codex-owned trust boundary as the live store, so the hook lane confines to
+ * BOTH; a moved rollout is otherwise refused as outside_projects_dir and is
+ * invisible to the discovery fallback.
+ */
+export function codexArchivedSessionsDir(): string {
+ return join(codexHome(), 'archived_sessions');
+}
+
/**
* Codex hooks file — (CODEX_HOME || ~/.codex)/hooks.json, USER-GLOBAL (no
* per-project scope for the user layer gbrain writes). Written by
diff --git a/src/core/bootstrap/lock.ts b/src/core/bootstrap/lock.ts
index 48900730c8..b999eada16 100644
--- a/src/core/bootstrap/lock.ts
+++ b/src/core/bootstrap/lock.ts
@@ -83,7 +83,10 @@ export type BootstrapErrorCode =
| 'HOME_GUARD'
/** The resolved --workspace (or its cwd default) is the user's home
* directory — refuse before any home-directory-scale git operation runs. */
- | 'HOME_WORKSPACE';
+ | 'HOME_WORKSPACE'
+ /** The harness could not resolve (or verify) the source its hooks + token
+ * must bind to — pass --source <id> explicitly. */
+ | 'SOURCE_UNRESOLVED';
/**
* The bootstrap family's error type. `exitCode` carries dispatcher semantics:
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index 58013266c8..ca6cc518a1 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -54,6 +54,7 @@ import { auditWritebackContract } from './contract.ts';
import {
ensureIpcSecret,
resolveSocketPath,
+ socketHasLiveListener,
startResolveIpcServer,
} from '../context/resolve-ipc.ts';
import { assembleTurnContext } from '../context/turn-context.ts';
@@ -905,10 +906,12 @@ async function checkHooksSmoke(engine: BrainEngine, ws: string, sourceId: string
// in-process IPC server, so it manufactured the exact condition it was
// testing — a serve posture that never binds IPC (the old `serve --http`)
// still passed verify while every production hook degraded to no_serve.
- // A present socket now means "a live serve is the provider; exercise IT";
- // only when NO socket exists do we self-provide (plumbing-only smoke) and
- // say so honestly in the result.
- const liveSocket = existsSync(socketPath);
+ // A LIVE socket now means "a live serve is the provider; exercise IT";
+ // only when nothing listens do we self-provide (plumbing-only smoke) and
+ // say so honestly in the result. Probed, not existsSync'd: a socket file a
+ // dead serve left behind must not read as a live provider (the smoke would
+ // "exercise" a listener that isn't there and fail as no_serve).
+ const liveSocket = await socketHasLiveListener(socketPath);
try {
if (!liveSocket) {
const secret = ensureIpcSecret(dataDir);
diff --git a/src/core/brainstorm/judges.ts b/src/core/brainstorm/judges.ts
index 329ae5a5aa..3c50c99d42 100644
--- a/src/core/brainstorm/judges.ts
+++ b/src/core/brainstorm/judges.ts
@@ -62,6 +62,7 @@ export const MAX_OUTPUT_TOKENS_CEIL = 32_000;
*/
export const ANTHROPIC_OUTPUT_CAPS: Record<string, number> = {
'claude-fable-5': 64_000,
+ 'claude-fable-5-1': 64_000,
'claude-opus-5': 32_000,
'claude-sonnet-5': 64_000,
'claude-opus-4-8': 32_000,
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 74de9812f8..bb30eb8040 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -35,6 +35,7 @@ import { ANTHROPIC_PRICING, type ModelPricing } from '../anthropic-pricing.ts';
import { canonicalLookup } from '../model-pricing.ts';
import { EMBEDDING_PRICING, lookupEmbeddingPrice } from '../embedding-pricing.ts';
import { splitProviderModelId } from '../model-id.ts';
+import { resolveRecipe } from '../ai/model-resolver.ts';
import { isoWeekFilename, resolveAuditDir } from '../audit-week-file.ts';
export type BudgetKind = 'chat' | 'embed' | 'rerank';
@@ -153,10 +154,31 @@ export async function loadPricingOverrides(
}
}
-/** Exact-key override lookup (keys normalized to lowercase at parse time). */
+/**
+ * Recipe-alias normalization shared by the override and table lookups:
+ * `claude-cli:haiku` → `claude-cli:claude-haiku-4-5-20251001`. Bare ids and
+ * unknown providers throw out of resolveRecipe and keep the raw id, so the
+ * downstream chains decide those exactly as before.
+ */
+function canonicalPricingKey(modelId: string): string {
+ try {
+ const { parsed } = resolveRecipe(modelId);
+ return `${parsed.providerId}:${parsed.modelId}`;
+ } catch {
+ return modelId;
+ }
+}
+
+/**
+ * Override lookup (keys normalized to lowercase at parse time): the raw key
+ * first, then the recipe-canonical key — an override written against the
+ * dated id must also price the alias the operator configured, or the alias
+ * silently bills at list price while the table lookup below resolves it.
+ */
function overrideFor(modelId: string, overrides?: PricingOverrides): ModelPricing | null {
if (!overrides) return null;
- return overrides[modelId.trim().toLowerCase()] ?? null;
+ const raw = modelId.trim().toLowerCase();
+ return overrides[raw] ?? overrides[canonicalPricingKey(modelId.trim()).toLowerCase()] ?? null;
}
export class BudgetExhausted extends Error {
@@ -263,7 +285,9 @@ const FREE_LOCAL_CHAT_PROVIDERS: ReadonlySet<string> = new Set([
* - Chat: try the bare model id in ANTHROPIC_PRICING first (legacy keys
* are bare claude-* ids), then the canonical paid-cloud chat table
* for provider-prefixed OpenAI/Google/DeepSeek/Together ids, then the
- * explicit zero-cost local provider set.
+ * explicit zero-cost local provider set. Recipe aliases are normalized
+ * first (`claude-cli:haiku` → `claude-cli:claude-haiku-4-5-20251001`),
+ * so an alias prices exactly like the id it resolves to.
* - Embed: lookupEmbeddingPrice handles the provider:model form; on a miss,
* local-inference providers (FREE_LOCAL_EMBED_PROVIDERS) price at $0 so
* `--max-cost` callers don't hard-fail.
@@ -295,7 +319,16 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
// brainstorm/lsd.
const bare = ANTHROPIC_PRICING[modelId];
if (bare) return bare;
- const { provider: providerId, model: modelTail } = splitProviderModelId(modelId);
+ // Recipe aliases (`claude-cli:haiku`, `anthropic:sonnet`) are not pricing
+ // keys, and the gateway reserves with the string the user configured —
+ // BEFORE alias resolution — so `claude-cli:haiku` under a cap used to TX2
+ // hard-fail with no_pricing while the dated id it maps to priced fine.
+ // Normalize once here; the chain below then prices the canonical id, and
+ // alias vs dated id agree at reserve(), record() and isModelPriceable().
+ // Bare ids and unknown providers keep the raw id (canonicalPricingKey): the
+ // existing chain decides those exactly as before.
+ const key = canonicalPricingKey(modelId);
+ const { provider: providerId, model: modelTail } = splitProviderModelId(key);
if (modelTail) {
const tailHit = ANTHROPIC_PRICING[modelTail];
if (tailHit) return tailHit;
@@ -305,7 +338,7 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
// pricing table (issue #3223) — same provider:model key shape, same
// $/1M-token unit — instead of hand-copying a third pricing surface.
if (kind === 'rerank') {
- const hit = lookupEmbeddingPrice(modelId);
+ const hit = lookupEmbeddingPrice(key);
if (hit.kind === 'known') return { input: hit.pricePerMTok, output: 0 };
}
// v0.40.6.1: zero-price local-inference rerank providers so the budget
@@ -319,7 +352,7 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
// models with a known price (openai:*, google:*, deepseek:*) resolve under
// --max-cost instead of TX2 no_pricing hard-failing at $0. ANTHROPIC_PRICING
// above is only the bare-keyed Claude view.
- const canon = canonicalLookup(modelId);
+ const canon = canonicalLookup(key);
if (canon) return canon;
// Local-inference chat providers cost electricity, not tokens. Checked AFTER
// the canonical table so an explicitly-priced local entry, should one ever be
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 2fa428cb21..93a36fcf32 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -29,7 +29,7 @@
import type { BrainEngine } from './engine.ts';
import { isUndefinedTableError } from './utils.ts';
import { CJK_SLUG_CHARS } from './cjk.ts';
-import { stripCodeBlocks } from './link-extraction.ts';
+import { stripCodeBlocks, isCrossSourceLinksEnabled } from './link-extraction.ts';
// #4222: shared generic-token reject list — same list gates enrichEntity
// minting and drives the junk_entity_hubs doctor check.
import { isGenericEntityToken } from './entity-name-quality.ts';
@@ -105,6 +105,15 @@ export interface FindMentionsOpts {
fromSlug: string;
/** Source id of the page being scanned. Used for cross-source guard. */
fromSourceId: string;
+ /**
+ * Lift the cross-source guard: a mention in source A of an entity that
+ * lives only in source B produces a mention with the entity's own
+ * `source_id`. Callers derive this from `link_resolution.cross_source`
+ * (via `isCrossSourceLinksEnabled`) so the mention scan follows the same
+ * operator opt-in as wikilink resolution. Default false — the historical
+ * same-source-only posture.
+ */
+ allowCrossSource?: boolean;
}
// ============================================================
@@ -501,9 +510,14 @@ export async function buildGazetteer(
}
}
- // Sort each bucket by token-count DESC so maximal-munch walks longest-first.
+ // Sort each bucket by token-count DESC so maximal-munch walks longest-first;
+ // ties break on (source_id, slug) so the pick among same-name entries is
+ // deterministic instead of following DB row order.
for (const bucket of gazetteer.values()) {
- bucket.sort((a, b) => b.tokens.length - a.tokens.length);
+ bucket.sort((a, b) =>
+ (b.tokens.length - a.tokens.length)
+ || a.source_id.localeCompare(b.source_id)
+ || a.slug.localeCompare(b.slug));
}
return gazetteer;
}
@@ -523,9 +537,12 @@ export async function buildGazetteer(
*
* Guards (deterministic):
* - D13 self-link: skip when `fromSlug === entry.slug`.
- * - Cross-source: skip when `fromSourceId !== entry.source_id` (mention
- * in source A of an entity in source B is suppressed; design doc
- * treats this as deliberate isolation in v1, can relax in a follow-up).
+ * - 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).
*
@@ -586,12 +603,25 @@ export function findMentionedEntities(
continue;
}
+ // Same-name twin in the scanning page's own source wins over a foreign
+ // one: bucket order is length-only, so `matched` may be the cross-source
+ // twin even when an own-source entry with identical tokens exists.
+ if (matched.source_id !== opts.fromSourceId) {
+ const want = matched.tokens;
+ const own = bucket.find(
+ e => e.source_id === opts.fromSourceId
+ && e.tokens.length === want.length
+ && e.tokens.every((t, k) => t === want[k]),
+ );
+ if (own) matched = own;
+ }
+
// Guards.
if (matched.slug === opts.fromSlug) {
i += matchedTokens;
continue;
}
- if (matched.source_id !== opts.fromSourceId) {
+ if (!opts.allowCrossSource && matched.source_id !== opts.fromSourceId) {
i += matchedTokens;
continue;
}
@@ -697,6 +727,7 @@ export async function scanStaleMentions(
if (totalPagesWithMentions === 0) return empty;
const gazetteer = await buildGazetteer(engine);
+ const allowCrossSource = await isCrossSourceLinksEnabled(engine);
// Same bounded page set for both queries so the link rows and the bodies
// can never describe different pages.
@@ -761,6 +792,7 @@ export async function scanStaleMentions(
findMentionedEntities(page.body, gazetteer, {
fromSlug: page.slug,
fromSourceId,
+ allowCrossSource,
}).map(m => `${m.source_id}::${m.slug}`),
);
diff --git a/src/core/check-resolvable.ts b/src/core/check-resolvable.ts
index 932a99155e..7de9319cd7 100644
--- a/src/core/check-resolvable.ts
+++ b/src/core/check-resolvable.ts
@@ -11,8 +11,9 @@
*/
import { readFileSync, existsSync, readdirSync } from 'fs';
-import { join, relative } from 'path';
+import { basename, join, relative } from 'path';
import { findResolverFile, findAllResolverFiles, RESOLVER_FILENAMES_LABEL } from './resolver-filenames.ts';
+import type { SkillsDirSource } from './repo-root.ts';
import { loadOrDeriveManifest } from './skill-manifest.ts';
import {
indexResolverTriggers,
@@ -299,7 +300,10 @@ export function extractDelegationTargets(content: string): DelegationRef[] {
*
* @param skillsDir — path to the `skills/` directory
*/
-export function checkResolvable(skillsDir: string): ResolvableReport {
+export function checkResolvable(
+ skillsDir: string,
+ opts?: { skillsDirSource?: SkillsDirSource | null },
+): ResolvableReport {
const issues: ResolvableIssue[] = [];
// Load inputs via the v0.41.11 shared primitive. UNION semantics
@@ -361,44 +365,86 @@ export function checkResolvable(skillsDir: string): ResolvableReport {
entries.filter(e => !e.isGStack).map(e => e.skillPath)
);
- // 1. Check every manifest skill is reachable from RESOLVER.md
+ // 1. Check every manifest skill is reachable from RESOLVER.md. Two
+ // passes: resolve reachability for every skill first (no severity
+ // decision yet), THEN decide how to grade the unreachable ones using the
+ // final tally, THEN construct issues. This lets the severity call factor
+ // in how SPARSE trigger coverage is across the whole directory, not just
+ // whether this one skill has a trigger.
+ const resolved = manifest.map(skill => {
+ const expectedPath = `skills/${skill.path}`;
+ if (resolverSkillPaths.has(expectedPath)) return { skill, reachable: true };
+ // Also check if the skill name appears in any resolver entry
+ const nameInResolver = entries.some(
+ e => e.skillPath.includes(skill.name) || e.trigger.includes(skill.name)
+ );
+ return { skill, reachable: nameInResolver };
+ });
let reachable = 0;
let unreachable = 0;
+ for (const r of resolved) {
+ if (r.reachable) reachable++;
+ else unreachable++;
+ }
- for (const skill of manifest) {
- const expectedPath = `skills/${skill.path}`;
- if (resolverSkillPaths.has(expectedPath)) {
- reachable++;
- } else {
- // Also check if the skill name appears in any resolver entry
- const nameInResolver = entries.some(
- e => e.skillPath.includes(skill.name) || e.trigger.includes(skill.name)
- );
- if (nameInResolver) {
- reachable++;
- } else {
- unreachable++;
- // Find the best section for this skill based on its description
- const section = 'Brain operations'; // default suggestion
- issues.push({
- type: 'unreachable',
- severity: 'error',
- skill: skill.name,
- message: `Skill '${skill.name}' is in manifest but has no trigger row in ${RESOLVER_FILENAMES_LABEL}`,
- action: `Add a trigger row for 'skills/${skill.path}' in RESOLVER.md under ${section}`,
- fix: {
- type: 'add_trigger',
- file: resolverPath,
- section,
- skill_path: `skills/${skill.path}`,
- },
- });
- }
- }
+ // `cwd_walk_up` (tier 1b of autoDetectSkillsDir) accepts ANY ancestor
+ // `skills/` dir with no signal that it is a gbrain skillpack, so a foreign
+ // tool's directory where one skill coincidentally ships `triggers:` would
+ // otherwise score every sibling as a hard unreachable error. Downgrade to a
+ // warning only when ALL hold: found via cwd_walk_up; no resolver file
+ // contributes rows (RESOLVER.md is gbrain-native, so its mere presence stays
+ // strict, but a generic prose AGENTS.md with zero table rows is no signal);
+ // unreachable outnumber reachable (a mostly-migrated real skillpack that
+ // lost its resolver file still fails loudly); and no manifest.json on disk
+ // (an explicit manifest, even a corrupted one, is deliberate skillpack
+ // intent). Higher-confidence tiers (explicit flag, env, install path) stay
+ // strict. A foreign dir with ZERO triggers and no resolver file still
+ // hard-fails via the missing_file branch above; widening that is a
+ // separate follow-up.
+ const foundOnlyEmptyAgentsMd =
+ resolverPathOrNull !== null &&
+ basename(resolverPathOrNull) === 'AGENTS.md' &&
+ !triggerEntries.some(e => e.source === 'resolver_md');
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- skillsDir is the caller-resolved local skills/ dir, never remote input
+ const manifestJsonAbsent = !existsSync(join(skillsDir, 'manifest.json'));
+ const lowConfidenceForeignDir =
+ opts?.skillsDirSource === 'cwd_walk_up' &&
+ (!resolverPathOrNull || foundOnlyEmptyAgentsMd) &&
+ unreachable > reachable &&
+ manifestJsonAbsent;
+
+ for (const { skill, reachable: isReachable } of resolved) {
+ if (isReachable) continue;
+ // Find the best section for this skill based on its description
+ const section = 'Brain operations'; // default suggestion
+ issues.push({
+ type: 'unreachable',
+ severity: lowConfidenceForeignDir ? 'warning' : 'error',
+ skill: skill.name,
+ message: lowConfidenceForeignDir
+ ? `Skill '${skill.name}' is in manifest but has no trigger row in ${RESOLVER_FILENAMES_LABEL} (this skills/ dir was found by walking up from cwd with no resolver rows -- if it belongs to a different tool, this can be ignored)`
+ : `Skill '${skill.name}' is in manifest but has no trigger row in ${RESOLVER_FILENAMES_LABEL}`,
+ action: `Add a trigger row for 'skills/${skill.path}' in RESOLVER.md under ${section}`,
+ fix: {
+ type: 'add_trigger',
+ file: resolverPath,
+ section,
+ skill_path: `skills/${skill.path}`,
+ },
+ });
}
// 2. Check every resolver entry points to a file that exists
- for (const entry of entries) {
+ // Orphans (skill on disk, not in manifest.json) are collected per SKILL,
+ // not per trigger, and worded by where the trigger came from: only a
+ // RESOLVER.md row can be removed from RESOLVER.md; a frontmatter-only
+ // skill needs a manifest.json entry. Value = RESOLVER.md skillPath, or
+ // null when every trigger for the skill came from SKILL.md frontmatter.
+ const orphans = new Map<string, string | null>();
+ // Missing files are likewise one issue per SKILL PATH, not per trigger row
+ // (a skill with six triggers is one missing file, not six).
+ const missingFiles = new Map<string, string>();
+ for (const entry of triggerEntries) {
if (entry.isGStack) continue;
// Resolver uses 'skills/query/SKILL.md', manifest uses 'query/SKILL.md'
@@ -406,28 +452,47 @@ export function checkResolvable(skillsDir: string): ResolvableReport {
const relPath = entry.skillPath.replace(/^skills\//, '');
const fullPath = join(skillsDir, relPath);
- if (!existsSync(fullPath)) {
- issues.push({
- type: 'missing_file',
- severity: 'error',
- skill: entry.skillPath,
- message: `RESOLVER.md references '${entry.skillPath}' but the file doesn't exist`,
- action: `Create the skill at '${fullPath}' or remove the resolver entry`,
- fix: { type: 'create_stub', file: fullPath },
- });
- }
+ if (!existsSync(fullPath)) missingFiles.set(entry.skillPath, fullPath);
// Check if in manifest
const skillName = relPath.replace(/\/SKILL\.md$/, '');
const inManifest = manifest.some(s => s.name === skillName);
if (!inManifest && existsSync(fullPath)) {
+ if (entry.source === 'resolver_md') orphans.set(skillName, entry.skillPath);
+ else if (!orphans.has(skillName)) orphans.set(skillName, null);
+ }
+ }
+ for (const [skillPath, fullPath] of missingFiles) {
+ issues.push({
+ type: 'missing_file',
+ severity: 'error',
+ skill: skillPath,
+ message: `RESOLVER.md references '${skillPath}' but the file doesn't exist`,
+ action: `Create the skill at '${fullPath}' or remove the resolver entry`,
+ fix: { type: 'create_stub', file: fullPath },
+ });
+ }
+ for (const [skillName, resolverSkillPath] of orphans) {
+ if (resolverSkillPath !== null) {
issues.push({
type: 'orphan_trigger',
severity: 'warning',
skill: skillName,
message: `RESOLVER.md has a trigger for '${skillName}' which is not in manifest.json`,
action: `Register '${skillName}' in skills/manifest.json or remove from RESOLVER.md`,
- fix: { type: 'remove_trigger', file: resolverPath, skill_path: entry.skillPath },
+ fix: { type: 'remove_trigger', file: resolverPath, skill_path: resolverSkillPath },
+ });
+ } else {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- skillsDir is the caller-resolved local skills/ dir and skillName is a directory name read from it; display-only path in a diagnostic
+ const skillMdPath = join(skillsDir, skillName, 'SKILL.md');
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same caller-resolved skillsDir; display-only path in a diagnostic
+ const manifestJsonPath = join(skillsDir, 'manifest.json');
+ issues.push({
+ type: 'orphan_trigger',
+ severity: 'warning',
+ skill: skillName,
+ message: `Skill '${skillName}' declares triggers in ${skillMdPath} frontmatter but is not registered in ${manifestJsonPath}`,
+ action: `Add {"name":"${skillName}","path":"${skillName}/SKILL.md"} to manifest.json (or delete the skill directory)`,
});
}
}
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index 8255170746..8f390eb135 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -745,6 +745,13 @@ async function chunkParsedLanguage(
language: SupportedCodeLanguage,
opts: CodeChunkOptions,
): Promise<ChunkAndEdgeResult> {
+ // #4669: a language with no TOP_LEVEL_TYPES entry (yaml, json, toml, css,
+ // html, ...) can only reach the no-semantic-nodes fallback below; skip the
+ // WASM load + parse (same output) and the false "parsing unavailable" alarm.
+ if (!TOP_LEVEL_TYPES[language]) {
+ return { chunks: fallbackChunks(source, filePath, language, opts), edges: [] };
+ }
+
const largeThreshold = opts.largeChunkThresholdTokens ?? 1000;
const chunkTarget = opts.chunkSizeTokens ?? 300;
const timeoutMs = resolveChunkerTimeoutMs();
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.ts
index 0a85dc9414..3aa755496b 100644
--- a/src/core/chunkers/recursive.ts
+++ b/src/core/chunkers/recursive.ts
@@ -20,7 +20,7 @@
* Lossless invariant: non-overlapping portions reassemble to original.
*/
-import { countCJKAwareWords, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';
+import { countCJKAwareWords, isCJKDominant, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';
import { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
import { safeSplitIndex } from '../text-safe.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
@@ -319,9 +319,16 @@ function splitOnWhitespace(text: string, target: number): string[] {
if (text.trim().length === 0) return [];
const pieces: string[] = [];
const charsPerPiece = Math.max(1, target);
- for (let i = 0; i < text.length; i += charsPerPiece) {
- const slice = text.slice(i, i + charsPerPiece);
+ // Cursor advances to wherever safeSplitIndex actually cut, so no astral
+ // pair (emoji, non-BMP CJK) is halved and no code unit is skipped or
+ // repeated. A window too narrow to hold a pair takes the pair whole.
+ let i = 0;
+ while (i < text.length) {
+ let end = safeSplitIndex(text, Math.min(text.length, i + charsPerPiece));
+ if (end <= i) end = Math.min(text.length, i + 2);
+ const slice = text.slice(i, end);
if (slice.trim().length > 0) pieces.push(slice);
+ i = end;
}
return pieces;
}
@@ -385,6 +392,11 @@ function applyOverlap(chunks: string[], overlapWords: number): string[] {
* If a sentence boundary exists within the last N words, start there.
*/
function extractTrailingContext(text: string, targetWords: number): string {
+ // CJK-dominant chunks count chars, not whitespace tokens (see countWords);
+ // the whitespace path below would return '' (whole chunk = one token) or
+ // duplicate most of the chunk. English path is unchanged.
+ if (isCJKDominant(text)) return extractTrailingContextCJK(text, targetWords);
+
const words = text.match(/\S+\s*/g) || [];
if (words.length <= targetWords) return '';
@@ -403,6 +415,42 @@ function extractTrailingContext(text: string, targetWords: number): string {
return trailing;
}
+/**
+ * Sentence end for the CJK overlap aligner: a CJK delimiter needs no trailing
+ * whitespace; an ASCII one still does, so "3.5" inside CJK prose is not a
+ * boundary.
+ */
+const CJK_SENTENCE_END = new RegExp(`[${CJK_SENTENCE_DELIMITERS.join('')}]\\s*|[.!?]\\s+`);
+
+/**
+ * CJK-dominant twin of extractTrailingContext: walks back targetWords
+ * non-whitespace code units (the unit countCJKAwareWords counts), then
+ * aligns to a sentence end the same way. Changes chunk boundaries only for
+ * CJK-dominant pages chunked from now on; re-chunking existing pages needs a
+ * MARKDOWN_CHUNKER_VERSION bump (see TODOS.md).
+ */
+function extractTrailingContextCJK(text: string, targetWords: number): string {
+ if (countCJKAwareWords(text) <= targetWords) return '';
+
+ let count = 0;
+ let i = text.length;
+ while (i > 0 && count < targetWords) {
+ i--;
+ if (!/\s/.test(text[i])) count++;
+ }
+ // Code-unit walk can stop between an astral pair's halves; move the cut to
+ // the pair start (one extra overlap char beats a lone surrogate).
+ const trailing = text.slice(safeSplitIndex(text, i));
+
+ const sentenceEnd = CJK_SENTENCE_END.exec(trailing);
+ if (sentenceEnd && sentenceEnd.index < trailing.length / 2) {
+ const afterSentence = trailing.slice(sentenceEnd.index + sentenceEnd[0].length);
+ if (afterSentence.trim().length > 0) return afterSentence;
+ }
+
+ return trailing;
+}
+
/**
* Word count, CJK-aware (v0.32.7). For Latin-dominant text this behaves
* exactly like the historical `text.match(/\S+/g).length`. When CJK char
diff --git a/src/core/cjk.ts b/src/core/cjk.ts
index 0664114fa6..8654817db0 100644
--- a/src/core/cjk.ts
+++ b/src/core/cjk.ts
@@ -78,15 +78,23 @@ export function hasCJK(s: string): boolean {
*/
export function countCJKAwareWords(s: string): number {
if (s.length === 0) return 0;
+ return isCJKDominant(s)
+ ? s.replace(/\s/g, '').length
+ : (s.match(/\S+/g) || []).length;
+}
+
+/**
+ * The ONE density test behind countCJKAwareWords: true when CJK chars make
+ * up at least CJK_DENSITY_THRESHOLD of the non-whitespace chars. Callers
+ * that need to branch on "would countCJKAwareWords count chars here?" (the
+ * chunker's overlap extractor) route through this so the two cannot drift.
+ */
+export function isCJKDominant(s: string): boolean {
+ const nonWhitespace = s.replace(/\s/g, '').length;
+ if (nonWhitespace === 0) return false;
const cjkMatches = s.match(new RegExp(`[${CJK_SLUG_CHARS}]`, 'g'));
const cjkCount = cjkMatches ? cjkMatches.length : 0;
- const nonWhitespace = s.replace(/\s/g, '').length;
- if (nonWhitespace === 0) return 0;
- const density = cjkCount / nonWhitespace;
- if (density >= CJK_DENSITY_THRESHOLD) {
- return nonWhitespace;
- }
- return (s.match(/\S+/g) || []).length;
+ return cjkCount / nonWhitespace >= CJK_DENSITY_THRESHOLD;
}
/**
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4487d9654d..03535a5120 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -19,17 +19,17 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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': ['--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--json', '--no-embedding', '--redirect-uri', '--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', '--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'],
+ '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'],
'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', '--json', '--path', '--porcelain', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restore-only', '--source', '--stale', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--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', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
+ 'book-mirror': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--follow', '--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', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],
+ 'calibration': ['--ab', '--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--follow', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],
+ 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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'],
'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'],
@@ -45,51 +45,51 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--coverage', '--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', '--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'],
+ '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', '--coverage', '--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', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--serial', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--version'],
+ '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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--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', '--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', '--coverage', '--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', '--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'],
+ 'enrich': ['--access', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--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', '--coverage', '--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', '--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'],
+ '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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],
+ 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--token-ttl', '--type'],
+ '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-status', '--no-embed', '--no-embedding', '--no-federated', '--no-gpg-sign', '--no-verify', '--older-than', '--orphan', '--others', '--path', '--pglite', '--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', '--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', '--probe', '--provenance', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],
+ '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', '--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', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--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', '--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', '--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', '--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': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--surface', '--timeout', '--token-ttl'],
+ '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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--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', '--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', '--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', '--window', '--workers', '--yes'],
- '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', '--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', '--recency', '--reranking', '--reset', '--skip', '--source', '--to', '--version'],
+ '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'],
+ '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', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--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', '--stale-ok', '--stats', '--stdin', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
+ '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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--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'],
'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', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--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', '--reranking', '--reset', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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'],
'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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],
+ 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--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', '--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', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],
+ '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'],
'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'],
@@ -98,7 +98,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--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', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--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', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--version', '--yes'],
+ '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'],
@@ -113,13 +113,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--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', '--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', '--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'],
+ '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', '--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', '--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'],
+ '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-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--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', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],
+ 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--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'],
};
diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.ts
index 798515f076..186eea6540 100644
--- a/src/core/config-db-merge.ts
+++ b/src/core/config-db-merge.ts
@@ -40,6 +40,7 @@ export const DB_MERGED_PROVIDER_KEY_FIELDS = [
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
+ 'deepseek_api_key',
'litellm_api_key',
'together_api_key',
'google_api_key',
diff --git a/src/core/config.ts b/src/core/config.ts
index cc7e0cb583..6078ed7df0 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -65,8 +65,7 @@ export interface GBrainConfig {
* memorableGateAllowed in core/context/hook-heartbeat.ts.
*/
integrations?: { memorable?: { enabled?: boolean } };
- /** Monthly backup-coverage check (src/core/backup/). File-plane: read by
- * engine-free render sites (hook children, the cli.ts startup rail). */
+ /** Monthly backup-coverage check. File-plane for engine-free hook children. */
backup?: { check_enabled?: boolean | string; check_interval_days?: number | string };
database_url?: string;
database_path?: string;
@@ -111,6 +110,7 @@ export interface GBrainConfig {
* voyage_api_key above.
*/
dashscope_api_key?: string;
+ deepseek_api_key?: string;
/**
* LiteLLM proxy API key. File-plane slot folded into the gateway env as
* LITELLM_API_KEY (optional in the litellm recipe — proxies may run
@@ -142,9 +142,8 @@ export interface GBrainConfig {
* auth alternative to the Entra flow below.
*/
azure_openai_api_key?: string;
- /** Azure OpenAI (keyless/Entra). Non-secret endpoint + deployment + Entra opt-in,
- * folded into the gateway env so the azure-openai recipe works in any shell.
- * The bearer token is minted at request time via `az` — no secret stored here. */
+ /** Azure OpenAI (keyless/Entra). Non-secret endpoint/deployment + Entra opt-in;
+ * bearer token is minted at request time via `az` — no secret stored here. */
azure_openai_endpoint?: string;
azure_openai_deployment?: string;
azure_openai_use_entra?: string;
@@ -656,7 +655,12 @@ export function loadConfigFileOnly(): GBrainConfig | null {
* The file list is a superset of Bun's auto-load set across NODE_ENV values
* so the guard doesn't depend on replicating Bun's exact selection logic.
*/
-const CWD_DOTENV_FILES = ['.env', '.env.local', '.env.development', '.env.production', '.env.test'];
+const CWD_DOTENV_FILES = [
+ '.env', '.env.local',
+ '.env.development', '.env.development.local',
+ '.env.production', '.env.production.local',
+ '.env.test', '.env.test.local',
+];
/**
* All values assigned to `key` across the .env files in `dir`. Collecting
@@ -1242,6 +1246,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
+ 'deepseek_api_key',
'litellm_api_key',
'together_api_key',
'google_api_key',
diff --git a/src/core/console-prefix.ts b/src/core/console-prefix.ts
index 1203eeb7ea..0a14f0f70f 100644
--- a/src/core/console-prefix.ts
+++ b/src/core/console-prefix.ts
@@ -40,6 +40,7 @@
* - src/commands/sync.ts (performSync + in-file callees)
* - src/commands/embed.ts (runEmbedCore + helpers)
* - src/core/progress.ts (heartbeat / progress writer)
+ * - src/commands/import.ts (runImport's human-only info() + summary lines)
*
* Anything outside those modules that writes directly to stdout/stderr will
* NOT get the prefix. If you find a delegate-module line that escapes the
@@ -61,6 +62,21 @@ const __prefixStore = new AsyncLocalStorage<string>();
// (the serve process is stdio-MCP for its whole lifetime).
let __stdoutLoggingRedirected = false;
+// CLI `--json` mode: stdout is reserved for the JSON envelope (and any JSON
+// status lines). Scoped, not process-wide: rebinding console.log here would
+// also push the envelope itself to stderr. slog consults it; serr is stderr
+// already; direct console.log(JSON.stringify(..)) sites are untouched.
+const __humanToStderr = new AsyncLocalStorage<true>();
+
+/**
+ * Run `fn` with every `slog` line (prefixed or not) routed to stderr, so a
+ * command's human output cannot interleave with the JSON it emits on
+ * stdout. Propagates through `await` like `withSourcePrefix`; nests with it.
+ */
+export function withHumanLogsToStderr<T>(fn: () => Promise<T>): Promise<T> {
+ return __humanToStderr.run(true, fn);
+}
+
/**
* Route ALL stdout-bound logging to stderr for the lifetime of this
* process. Called once by the stdio MCP serve path before the transport
@@ -131,15 +147,17 @@ export function getSourcePrefix(): string | null {
*/
export function slog(...args: unknown[]): void {
const prefix = getSourcePrefix();
+ const toStderr = __stdoutLoggingRedirected || __humanToStderr.getStore() === true;
if (prefix === null) {
// Back-compat fast path: bare console.log semantics. (Under the stdio
// MCP redirect, console.log is rebound to stderr — see
- // redirectStdoutLoggingToStderr.)
+ // redirectStdoutLoggingToStderr; under withHumanLogsToStderr the line
+ // is routed to stderr here instead.)
// eslint-disable-next-line no-console
- console.log(...args);
+ if (toStderr) console.error(...args); else console.log(...args);
return;
}
- const out = __stdoutLoggingRedirected ? process.stderr : process.stdout;
+ const out = toStderr ? process.stderr : process.stdout;
out.write(prefixLines(formatArgs(args), prefix) + '\n');
}
diff --git a/src/core/context/chronicle-context.ts b/src/core/context/chronicle-context.ts
index f9cf3b33d1..040256f006 100644
--- a/src/core/context/chronicle-context.ts
+++ b/src/core/context/chronicle-context.ts
@@ -44,7 +44,7 @@ export async function loadChronicleContext(
const ontologies: Record<string, OntologyValue[]> = {};
for (const slug of opts.entities ?? []) {
- let vals = await engine.getOntology(slug, scope);
+ let vals = await engine.getOntology(slug, { ...scope, excludePrivate: opts.excludePrivate });
if (opts.remote) vals = vals.filter((v) => !(v.source ?? '').startsWith('life/diary/'));
if (vals.length) ontologies[slug] = vals;
}
diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.ts
index 056b32c861..4b78dc82df 100644
--- a/src/core/context/resolve-ipc.ts
+++ b/src/core/context/resolve-ipc.ts
@@ -52,7 +52,6 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import {
existsSync,
unlinkSync,
- statSync,
chmodSync,
mkdirSync,
readFileSync,
@@ -352,9 +351,9 @@ export interface IpcPathConfig {
* no serve) behind it (v0.45.7 gate, preserved).
*
* Multi-serve note: on Postgres several serves for the SAME database_url
- * share this path; the newest bind wins (same last-serve-wins posture as
- * the PGLite socket after a stale-socket cleanup). Bound-source rejection
- * [CX2-10] still applies per request.
+ * share this path; the first LIVE provider wins — a later serve probes the
+ * socket, finds a live owner, and defers (null binding) instead of unlinking
+ * it (#4896). Bound-source rejection [CX2-10] still applies per request.
*/
export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined): string | null {
if (!cfg) return null;
@@ -677,8 +676,8 @@ function roundTrip(
): Promise<unknown | typeof IPC_UNAVAILABLE> {
// POSIX fast-path only: a Unix domain socket is a real filesystem entry, so
// existsSync() lets the common "no server running" case skip a syscall.
- // On win32, net.createServer()/createConnection() silently translate a
- // plain path into \\.\pipe\<name> — no file is ever created on disk, so
+ // On win32, Bun binds a plain path as a real AF_UNIX socket (afunix.sys
+ // reparse-point file) that Bun's existsSync()/statSync() cannot see, so
// existsSync() is always false here even while a live server is listening
// and a real connection would succeed. Gating on it on Windows made every
// IPC call fail closed unconditionally (verified: a listen()+connect()
@@ -725,9 +724,12 @@ function roundTrip(
// ── Server ────────────────────────────────────────────────────────────────
/**
- * Server: start an IPC listener on `socketPath`. Cleans up a stale socket
- * left by a dead owner first, hardens the parent dir to 0700, and chmods the
- * socket 0600 BEFORE announcing readiness [S3#6]. Returns the net.Server
+ * Server: start an IPC listener on `socketPath`. Probes the path for an owner
+ * first — unless the connect is hard-refused (nothing listens), returns null
+ * and leaves the socket untouched: a serve that accepts, or one too busy to
+ * accept within the probe budget, is the IPC provider (#4896). Only a dead
+ * owner's leftover entry is cleaned up; then hardens the parent dir to 0700, and chmods
+ * the socket 0600 BEFORE announcing readiness [S3#6]. Returns the net.Server
* (caller closes on shutdown). Errors are swallowed (best-effort feature) —
* returns null if the socket can't be bound.
*
@@ -766,8 +768,21 @@ export async function startResolveIpcServer(
chmodSync(dir, 0o700);
} catch { /* best effort */ }
- // Remove a stale socket file if present (a previous serve that didn't clean up).
- cleanupStaleSocket(socketPath);
+ // Only a provably dead owner is displaced (#4896 — a transient serve used
+ // to unlink the long-lived one's socket and take the pathname with it on
+ // exit). 'live' AND 'unknown' (probe timed out: a serve whose event loop
+ // is busy) both defer — this serve runs without IPC rather than risk it.
+ // ponytail: two serves probing within the same few microseconds both see
+ // no owner and the second unlink still displaces the first; a dev/ino
+ // identity re-check around the unlink is the upgrade path if it ever bites.
+ if ((await probeSocketOwner(socketPath)) !== 'dead') return null;
+ // Remove the dead owner's socket file so bind() can succeed. NOT gated on
+ // existsSync/statSync (#4333): on win32 Bun binds a plain path as a real
+ // AF_UNIX socket, which leaves a reparse-point file that Bun's existsSync()/
+ // statSync() cannot see while bind() still fails WSAEADDRINUSE against it —
+ // unlink is the only fs call that observes the entry. ENOENT and EISDIR/
+ // EPERM (a directory we must not touch) are swallowed.
+ try { unlinkSync(socketPath); } catch { /* nothing stale, or not ours to remove */ }
return new Promise((resolve) => {
const server = net.createServer((conn) => {
@@ -862,7 +877,12 @@ export async function startResolveIpcServer(
});
conn.on('error', () => { try { conn.destroy(); } catch { /* noop */ } });
});
- server.on('error', () => resolve(null));
+ server.on('error', (e: NodeJS.ErrnoException) => {
+ if (process.env.GBRAIN_DEBUG === '1') {
+ process.stderr.write(`[resolve-ipc] listen failed (${e.code ?? 'unknown'}) at ${socketPath}\n`);
+ }
+ resolve(null);
+ });
server.listen(socketPath, () => {
// Mode set BEFORE readiness is announced (the resolve() below) [S3#6].
try { chmodSync(socketPath, 0o600); } catch { /* best effort */ }
@@ -979,16 +999,46 @@ async function handleSyncKind<Req extends { protocol: number; secret: string },
}
}
-/** Remove a socket file whose owning process is gone (or any leftover file). */
-export function cleanupStaleSocket(socketPath: string): void {
- try {
- if (existsSync(socketPath)) {
- // A unix socket shows up as a socket file; unlink unconditionally — if a
- // live server holds it, listen() below would fail and we return null.
- const st = statSync(socketPath);
- if (st.isSocket() || st.isFIFO() || st.isFile()) unlinkSync(socketPath);
- }
- } catch {
- /* best effort */
- }
+/**
+ * Is something listening at `socketPath`? The same owner probe the pre-bind
+ * check uses: a leftover socket FILE (dead owner) is not a live provider, so
+ * callers must use this rather than existsSync() to decide "a serve is
+ * here". 'unknown' (probe timed out) counts as live — the conservative
+ * reading, identical to the bind path's "never displace on a timeout".
+ */
+export async function socketHasLiveListener(socketPath: string): Promise<boolean> {
+ return (await probeSocketOwner(socketPath)) !== 'dead';
+}
+
+/**
+ * Who owns `socketPath`? 'live' — something accepted the connect (a serve).
+ * 'dead' — the connect was hard-refused (ENOENT / ECONNREFUSED / ENOTSOCK:
+ * nothing listens; the entry is a dead owner's leftover the caller may
+ * remove). 'unknown' — the CLIENT_TIMEOUT_MS budget lapsed with the connect
+ * neither accepted nor refused (a live serve too busy to accept). The caller must
+ * never clean up on 'unknown': a timeout read as "dead" let a transient
+ * serve displace a long-lived one, the very #4896 symptom. The server side
+ * tolerates the data-less probe: one-request-per-connection means a
+ * connection that closes before its first line is just destroyed.
+ */
+type SocketOwner = 'live' | 'dead' | 'unknown';
+function probeSocketOwner(socketPath: string): Promise<SocketOwner> {
+ return new Promise((resolve) => {
+ let settled = false;
+ const probe = new net.Socket();
+ const finish = (owner: SocketOwner) => {
+ if (settled) return;
+ settled = true;
+ try { probe.destroy(); } catch { /* noop */ }
+ resolve(owner);
+ };
+ // Listeners BEFORE connect(): under `bun test` Bun can emit the ENOENT
+ // for an absent path synchronously inside connect(), which would be an
+ // unhandled 'error' if attached afterwards.
+ probe.once('connect', () => finish('live'));
+ probe.once('error', () => finish('dead'));
+ probe.once('timeout', () => finish('unknown'));
+ probe.setTimeout(CLIENT_TIMEOUT_MS);
+ try { probe.connect(socketPath); } catch { finish('dead'); }
+ });
}
diff --git a/src/core/context/session-state.ts b/src/core/context/session-state.ts
index de74076f1d..e059ea70b8 100644
--- a/src/core/context/session-state.ts
+++ b/src/core/context/session-state.ts
@@ -66,14 +66,6 @@ function normSession(sessionId: string): string {
return String(sessionId).slice(0, ID_MAX_LEN);
}
-/** Normalize a DB timestamp text to ISO 8601 so downstream cursor comparisons
- * are format-stable (PGLite's ::text cast returns local-tz text, not ISO). */
-function toIso(v: string | null): string | null {
- if (!v) return null;
- const t = Date.parse(v);
- return Number.isFinite(t) ? new Date(t).toISOString() : v;
-}
-
function toStringArray(v: unknown): string[] {
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string');
if (typeof v === 'string') {
@@ -100,7 +92,11 @@ export async function getSessionContextState(
surfaced_slugs: unknown;
last_wake_at: string | null;
}>(
- `SELECT standing_entities, surfaced_slugs, last_wake_at::text AS last_wake_at
+ // ISO UTC at the column's microsecond precision (not ::text — PGLite
+ // renders local-tz text, and a JS Date round-trip would re-round the
+ // keyset cursor to milliseconds, re-delivering same-millisecond pages).
+ `SELECT standing_entities, surfaced_slugs,
+ to_char(last_wake_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS last_wake_at
FROM session_context_state
WHERE source_id = $1 AND client_id = $2 AND session_id = $3`,
[sourceId, resolveClientId(clientId), normSession(sessionId)],
@@ -110,7 +106,7 @@ export async function getSessionContextState(
return {
standing_entities: toStringArray(r.standing_entities),
surfaced_slugs: toStringArray(r.surfaced_slugs),
- last_wake_at: toIso(r.last_wake_at ?? null),
+ last_wake_at: r.last_wake_at ?? null,
};
} catch {
return null;
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 8215a13e1e..4966cbc8df 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -546,7 +546,10 @@ async function assembleDelta(
slug: p.slug,
source_id: opts.sourceId,
title: p.title,
- updated_at: p.updated_at instanceof Date ? p.updated_at.toISOString() : String(p.updated_at),
+ // Column-precision cursor: `next_cursor.since` minted from a JS Date
+ // re-selects every same-millisecond row on the next wake.
+ updated_at:
+ p.updated_at_iso ?? (p.updated_at instanceof Date ? p.updated_at.toISOString() : String(p.updated_at)),
}));
} catch {
acc.pages = [];
diff --git a/src/core/creds/redirect.ts b/src/core/creds/redirect.ts
index 53102f5516..15d7b34190 100644
--- a/src/core/creds/redirect.ts
+++ b/src/core/creds/redirect.ts
@@ -62,7 +62,21 @@ export interface ParsedRedirect {
export function parsePastedRedirect(pasted: string, expectedState?: string): ParsedRedirect {
const raw = pasted.trim().replace(/\s+/g, '');
if (raw.length === 0) throw new CredentialError('pasted_wrong_url');
- if (/accounts\.google\.com/i.test(raw)) throw new CredentialError('pasted_wrong_url');
+
+ // The #1 mistake — pasting the CONSENT PAGE url (still on
+ // accounts.google.com) instead of the failed-to-load redirect. Runs on every
+ // paste shape, scheme or not (browsers hide `https://` in the address bar),
+ // so a scheme-less consent URL can't fall through to the bare-code branch.
+ // Decide by HOST, not by substring: since RFC 9207 / OpenID Connect issuer
+ // identification, Google appends `iss=https://accounts.google.com` to every
+ // legitimate loopback redirect's query string, so a substring test over the
+ // whole raw paste flags every real redirect too.
+ const host = raw
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, '')
+ .split(/[/?#]/)[0]
+ .replace(/^[^@]*@/, '')
+ .replace(/:\d*$/, '');
+ if (/(?:^|\.)accounts\.google\.com$/i.test(host)) throw new CredentialError('pasted_wrong_url');
let code: string | null = null;
let state: string | null = null;
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index f98e81070e..bad322456e 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1386,6 +1386,8 @@ async function runPhaseExtract(
// On a 54K-page brain this turns a 10-minute full walk into a sub-second pass.
const result = await runExtractCore(engine, {
mode: 'all',
+ jsonMode: false, // batch errors stay human-readable on stderr, as in a plain `gbrain extract`
+ quiet: true, // the cycle owns the report — no helper summary on stdout (keeps dream --json pure)
dir: brainDir,
slugs: changedSlugs, // undefined = full walk (first run / manual)
signal,
@@ -1414,6 +1416,7 @@ async function runPhaseExtract(
const drained = await extractStaleFromDB(engine, {
dryRun: false,
jsonMode: false,
+ quiet: true, // the cycle owns the report — no helper summary on stdout
includeFrontmatter,
sourceIdFilter: sourceId,
catchUp: false,
@@ -3112,7 +3115,8 @@ function extractTotals(phases: PhaseResult[]): CycleReport['totals'] {
} else if (p.phase === 'sync' && p.details) {
t.pages_synced = Number(p.details.added ?? 0) + Number(p.details.modified ?? 0);
} else if (p.phase === 'extract' && p.details) {
- t.pages_extracted = Number(p.details.linksCreated ?? 0);
+ // Pages, not links: the targeted/fs pass plus the bounded stale drain.
+ t.pages_extracted = Number(p.details.pages_processed ?? 0) + Number(p.details.stale_pages_drained ?? 0);
} else if (p.phase === 'embed' && p.details) {
// In dry-run, use would_embed as the "activity" measure; else embedded.
const dryRun = p.details.dryRun === true;
diff --git a/src/core/cycle/extract-atoms-cost-gate.ts b/src/core/cycle/extract-atoms-cost-gate.ts
new file mode 100644
index 0000000000..e407071ecc
--- /dev/null
+++ b/src/core/cycle/extract-atoms-cost-gate.ts
@@ -0,0 +1,85 @@
+/**
+ * Cost-gate decision for the extract_atoms BudgetTracker.
+ *
+ * Split out of extract-atoms.ts so the decision is a pure, unit-testable
+ * function and the phase file stays under the module-size cap. See the
+ * "cost cap" comment at the tracker construction site in extract-atoms.ts
+ * for the defect this closes.
+ */
+
+import { isAvailable, getEmbeddingModel } from '../ai/gateway.ts';
+import { isModelPriceable, type PricingOverrides } from '../budget/budget-tracker.ts';
+
+/**
+ * Cost-gate decision for the extract_atoms BudgetTracker.
+ *
+ * `enforceCap: true` → construct the tracker with `maxCostUsd`. `false` → run
+ * uncapped (the tracker then warns once on unpriced models instead of throwing)
+ * and `unpricedModel`/`unpricedKind` name the call that made the cap
+ * unenforceable. Pure: no config or gateway access, so it is unit-testable and
+ * the call site stays a one-liner.
+ */
+export interface ExtractAtomsCostGate {
+ enforceCap: boolean;
+ unpricedModel?: string;
+ unpricedKind?: 'chat' | 'embed';
+ /**
+ * Set when an EXPLICIT operator budget kept the cap on over an unpriced
+ * embed route: that route bills at $0 under this tracker (one stderr
+ * warning at the call site). `pricingOverrides` is then the caller's map
+ * plus the $0 row — hand it to the tracker in place of the original.
+ */
+ zeroPricedEmbedModel?: string;
+ pricingOverrides?: PricingOverrides;
+}
+
+/**
+ * Both models that bill under the extract_atoms tracker must be priceable for
+ * a cap to be enforceable: the extraction chat model AND the embedding model
+ * the atom import path calls (pass `null` when embedding is unavailable, in
+ * which case the import runs with `noEmbed` and nothing embeds). Operator
+ * `pricing.overrides` are consulted first, matching BudgetTracker.reserve().
+ *
+ * `explicitBudget` = the operator SET `cycle.extract_atoms.budget_usd`. Only
+ * a *default* cap may be dropped for an unpriced embed route; a ceiling the
+ * operator asked for stays enforced and the embed route is priced at $0
+ * instead (Codex P1). An unpriced CHAT model still drops the cap either way —
+ * it is the billable call the cap exists for, and $0 would enforce a fiction.
+ */
+export function resolveExtractAtomsCostGate(
+ extractModel: string,
+ embedModel: string | null,
+ overrides?: PricingOverrides,
+ opts: { explicitBudget?: boolean } = {},
+): ExtractAtomsCostGate {
+ if (!isModelPriceable(extractModel, 'chat', overrides)) {
+ return { enforceCap: false, unpricedModel: extractModel, unpricedKind: 'chat' };
+ }
+ if (embedModel !== null && !isModelPriceable(embedModel, 'embed', overrides)) {
+ if (opts.explicitBudget) {
+ // Same key normalization as parsePricingOverrides / overrideFor.
+ const key = embedModel.trim().toLowerCase();
+ return {
+ enforceCap: true,
+ zeroPricedEmbedModel: embedModel,
+ pricingOverrides: { ...overrides, [key]: { input: 0, output: 0 } },
+ };
+ }
+ return { enforceCap: false, unpricedModel: embedModel, unpricedKind: 'embed' };
+ }
+ return { enforceCap: true };
+}
+
+/**
+ * The embedding model the atom import will bill under this phase's tracker,
+ * or `null` when embedding is unavailable (the write site then passes
+ * `noEmbed: true` and no embed call happens). Mirrors the write site's own
+ * `isAvailable('embedding')` check so the gate and the import agree.
+ */
+export function resolveEmbedModelForCostGate(): string | null {
+ try {
+ return isAvailable('embedding') ? getEmbeddingModel() : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 83839b7665..83bd6f4407 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -154,6 +154,22 @@ export interface ExtractAtomsDrainResult {
last_error: string | null;
}
+/**
+ * #3813: the Minion handler's provider_failure throw IS the job's error_text
+ * once it dead-letters, so it carries the representative `last_error` (already
+ * secret-redacted + bounded above) — a missing provider key is a one-line
+ * diagnosis instead of an opaque batches/remaining.
+ */
+export function formatDrainProviderFailure(
+ result: Pick<ExtractAtomsDrainResult, 'batches' | 'remaining' | 'last_error'>,
+): string {
+ return (
+ `extract-atoms-drain: all provider calls failed this batch ` +
+ `(batches=${result.batches}, remaining=${result.remaining ?? '?'})` +
+ `${result.last_error ? `; last error: ${result.last_error}` : ''} — retrying`
+ );
+}
+
export async function runExtractAtomsDrain(
deps: ExtractAtomsDrainDeps,
opts: ExtractAtomsDrainOpts,
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 99139a58ba..20cbbe218b 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -68,13 +68,16 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } f
import { importFromContent } from '../import-file.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
-import { BudgetExhausted, BudgetTracker, isModelPriceable } from '../budget/budget-tracker.ts';
+import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
import { upsertExtractRollup } from '../extract/rollup-writer.ts';
import { createHash } from 'crypto';
import { slugifySegment } from '../sync.ts';
import { resolveTierDefault } from '../model-config.ts';
+import { isUndefinedTableError, warnOncePerProcess } from '../utils.ts';
import { normalizeForGrounding } from './synthesize-verify.ts';
+import type { TranscriptPageIndex } from '../transcripts/discover.ts';
const DEFAULT_BUDGET_USD = 0.3;
// #4529 + #4540: per-item extractor caps, overridable via
@@ -305,7 +308,7 @@ quote, or short essay angle. Each atom must:
- Have a clear point (not just descriptive)
- Be specific (not a generic platitude)
-Output a JSON array of atoms (1-3 per transcript, never more than 3).
+Output a JSON array of atoms (0-3 per transcript, never more than 3).
Each atom: {title (≤80 chars), atom_type, body (2-4 sentences),
source_quote (verbatim ≤200 chars), lesson (one sentence), concepts
(1-3 topic labels), virality_score (0-100), emotional_register (one of:
@@ -318,6 +321,10 @@ concept pages (e.g. "captive-portal", "channel-pricing-strategy") — never
entity or brand names. Use the same label for the same topic across atoms;
prefer a label you already used over coining a near-synonym.
+If the transcript has no extractable idea (metadata rows, status dumps,
+empty fields, boilerplate), output exactly [] — never invent an atom and
+never explain in prose.
+
Output ONLY the JSON array, no prose.`;
interface DiscoveredPage {
@@ -529,6 +536,57 @@ export async function atomsExistingForHashes(
}
}
+/**
+ * Composite key for the transcript-state Set. A transcript is identified by
+ * BOTH path and content hash (the table's PK carries both), so neither alone
+ * is a safe Set member: two files can share content, and one file changes hash
+ * when edited. NUL is the separator because it cannot occur in a POSIX path.
+ */
+export function transcriptStateKey(filePath: string, contentHash16: string): string {
+ return `${filePath}\u0000${contentHash16}`;
+}
+
+/**
+ * Batch-read the v146 transcript tombstones for this source, mirroring
+ * `atomsExistingForHashes` — ONE query for the whole corpus rather than N
+ * per-file probes, same fail-soft posture (on error return empty, i.e. treat
+ * everything as live and re-attempt, which is the pre-v146 behaviour).
+ *
+ * Only TOMBSTONED rows are returned. A row carrying an in-progress failure
+ * streak (fail_count 1 or 2) is deliberately still live: those items must keep
+ * being retried until the streak reaches MAX_DETERMINISTIC_FAILURES, exactly as
+ * a page with `atoms_fail_count` below the bound stays in the page backlog.
+ */
+export async function tombstonedTranscriptsForHashes(
+ engine: BrainEngine,
+ sourceId: string,
+ contentHash16s: string[],
+): Promise<Set<string>> {
+ if (contentHash16s.length === 0) return new Set();
+ try {
+ const rows = await engine.executeRaw<{ file_path: string; content_hash: string }>(
+ `SELECT file_path, content_hash
+ FROM extract_atoms_transcript_state
+ WHERE source_id = $1
+ AND tombstoned
+ AND content_hash = ANY($2::text[])`,
+ [sourceId, contentHash16s],
+ );
+ return new Set(rows.map(r => transcriptStateKey(r.file_path, r.content_hash)));
+ } catch (err) {
+ if (isUndefinedTableError(err)) {
+ // Un-migrated brain: the table lands with v146. Once per process, not a
+ // full error line on every cycle until the operator migrates.
+ warnOncePerProcess('extract_atoms.transcript_state_missing',
+ `[extract_atoms] extract_atoms_transcript_state is missing (run gbrain migrate); transcript failure counts and tombstones are off until then.`);
+ return new Set();
+ }
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error(`[extract_atoms] transcript tombstone check failed (assuming none tombstoned): ${msg}`);
+ return new Set();
+ }
+}
+
/**
* The exact two-step model resolution `runPhaseExtractAtoms` uses:
* `models.dream.extract_atoms` DB config wins if set (same plain-`||`
@@ -642,8 +700,23 @@ export async function runPhaseExtractAtoms(
// short-circuit shows a sign of life (closes Issue 2 silent-phase pain).
opts.progress?.heartbeat(`checking existing atoms for ${allHashes16.length} transcripts`);
const existingHashes = await atomsExistingForHashes(engine, sourceId, allHashes16);
+ // v146 READ SIDE. The counter written above is inert without this: transcript
+ // eligibility was gated ONLY by "does an atom row exist for this hash", so a
+ // tombstone nothing consults would leave the item in the pool forever. Pages
+ // need no equivalent edit — their tombstone (`atoms_scan_hash`) is already
+ // read by discoverExtractablePages' SQL, which this change does not touch.
+ const tombstonedTranscriptKeys = await tombstonedTranscriptsForHashes(
+ engine,
+ sourceId,
+ allHashes16,
+ );
for (const t of transcripts) {
- if (existingHashes.has(t.contentHash.slice(0, 16))) {
+ const hash16 = t.contentHash.slice(0, 16);
+ if (existingHashes.has(hash16)) {
+ duplicatesSkipped++;
+ continue;
+ }
+ if (tombstonedTranscriptKeys.has(transcriptStateKey(t.filePath, hash16))) {
duplicatesSkipped++;
continue;
}
@@ -699,6 +772,27 @@ export async function runPhaseExtractAtoms(
if (i < transcriptItems.length) work.push(transcriptItems[i]);
}
+ // #3961 follow-up: transcript-origin atoms get provenance edges too. The
+ // original implementation skipped them ("transcripts are files, not pages,
+ // so there is no from-endpoint to link") — but an imported transcript IS a
+ // page: the conversation page it was rendered into. Resolving it here (one
+ // frontmatter-only query, only when transcript work exists) gives those
+ // atoms the same source-page → atom edge that page-origin atoms get, so the
+ // graph can navigate from a conversation to what was learned from it.
+ let transcriptPageIndex: TranscriptPageIndex | null = null;
+ let resolveTranscriptPages: ((filePath: string, index: TranscriptPageIndex) => string[]) | null = null;
+ if (transcriptItems.length > 0) {
+ try {
+ const { indexTranscriptPages, resolveTranscriptPageSlugs } = await import('../transcripts/discover.ts');
+ transcriptPageIndex = await indexTranscriptPages(engine, sourceId);
+ resolveTranscriptPages = resolveTranscriptPageSlugs;
+ } catch {
+ // Index unavailable — atoms still import, they just carry no edge.
+ transcriptPageIndex = null;
+ resolveTranscriptPages = null;
+ }
+ }
+
// Phase-level no-op: nothing to extract today.
if (work.length === 0 && transcripts.length === 0 && pages.length === 0) {
return {
@@ -740,6 +834,7 @@ export async function runPhaseExtractAtoms(
// matching the pre-refactor fail-soft behavior exactly.
let extractModel = resolveTierDefault('utility');
let budgetCap = DEFAULT_BUDGET_USD;
+ let explicitBudget = false; // operator SET cycle.extract_atoms.budget_usd
// #4529/#4540: the per-item input/output caps were hardcoded (slice(0, 50_000) +
// maxTokens: 4096). Operators on small-context or thinking models need to
// shrink/grow both without a code change; defaults are unchanged.
@@ -751,7 +846,7 @@ export async function runPhaseExtractAtoms(
const configuredBudget = await engine.getConfig('cycle.extract_atoms.budget_usd');
if (configuredBudget) {
const n = Number(configuredBudget);
- if (Number.isFinite(n) && n > 0) budgetCap = n;
+ if (Number.isFinite(n) && n > 0) { budgetCap = n; explicitBudget = true; }
}
// #4529: legacy input-cap key (its own floor of 500 chars, as landed).
// Read FIRST so the newer #4540 max_input_chars key below wins when
@@ -786,22 +881,54 @@ export async function runPhaseExtractAtoms(
// Keep safe defaults on any config-read failure: key-aware utility-tier
// model, $0.30 cap, default input cap (max_input_chars).
}
- // A cost cap is only meaningful for a model the tracker can price.
- // BudgetTracker.reserve() hard-fails with BudgetExhausted(reason:'no_pricing')
- // when the model is absent from the pricing maps AND a cap is set; with no cap
- // it warns once and proceeds. Because this phase always set a cap, every
- // non-Anthropic model tripped that hard-fail on the first item, latched
- // `budgetExhausted`, and skipped the entire workload while reporting ok.
- const priceable = isModelPriceable(extractModel, 'chat');
- if (!priceable) {
+ // A cost cap is only meaningful when the tracker can price EVERY call made
+ // under it. BudgetTracker.reserve() hard-fails with
+ // BudgetExhausted(reason:'no_pricing') when a model is absent from the pricing
+ // maps AND a cap is set; with no cap it warns once and proceeds. Because this
+ // phase always set a cap, every non-Anthropic chat model tripped that
+ // hard-fail on the first item, latched `budgetExhausted`, and skipped the
+ // entire workload while reporting ok.
+ //
+ // The chat model is not the only call under this tracker: the atom write
+ // site below goes through importFromContent, which chunks AND embeds inside
+ // the same withBudgetTracker scope. So the embedding model must be priceable
+ // too. Pre-fix, a $0 local chat model (ollama/llama-server) kept the cap on
+ // while an unpriced embedding route (e.g. `litellm:*`, which is deliberately
+ // NOT assumed free because a proxy can front a paid provider) threw
+ // no_pricing on the FIRST atom import — 0 atoms, `budget_exhausted: true`,
+ // $0 spent, on every run. The operator escape hatch the error message
+ // advertises (`pricing.overrides`, #4312) was also never loaded here, unlike
+ // enrich / ingest-facts / extract-conversation-facts.
+ //
+ // Only a DEFAULT cap may be dropped that way. When the operator set
+ // `cycle.extract_atoms.budget_usd` they asked for a ceiling; the gate keeps
+ // it and bills the unpriced embed route at $0 (warned once, below).
+ const pricingOverrides = await loadPricingOverrides(engine);
+ const costGate = resolveExtractAtomsCostGate(
+ extractModel,
+ resolveEmbedModelForCostGate(),
+ pricingOverrides,
+ { explicitBudget },
+ );
+ if (!costGate.enforceCap) {
+ console.error(
+ `[extract_atoms] ${costGate.unpricedKind} model "${costGate.unpricedModel}" is not in the pricing maps; ` +
+ `running without a cost gate (a cap cannot be enforced on an unpriced model). ` +
+ `Declare an operator rate to restore the cap: ` +
+ `gbrain config set pricing.overrides '{"${costGate.unpricedModel}": <usd-per-1M-tokens>}' (0 for local inference).`,
+ );
+ } else if (costGate.zeroPricedEmbedModel) {
console.error(
- `[extract_atoms] model "${extractModel}" is not in the pricing maps; ` +
- `running without a cost gate (a cap cannot be enforced on an unpriced model).`,
+ `[extract_atoms] embed model "${costGate.zeroPricedEmbedModel}" is not in the pricing maps; ` +
+ `cycle.extract_atoms.budget_usd is set, so the $${budgetCap.toFixed(2)} cap stays enforced and embeds bill at $0 under it. ` +
+ `Declare its real rate to meter them: ` +
+ `gbrain config set pricing.overrides '{"${costGate.zeroPricedEmbedModel}": <usd-per-1M-tokens>}'.`,
);
}
const budgetTracker = new BudgetTracker({
- maxCostUsd: priceable ? budgetCap : undefined,
+ maxCostUsd: costGate.enforceCap ? budgetCap : undefined,
label: 'cycle.extract_atoms',
+ pricingOverrides: costGate.pricingOverrides ?? pricingOverrides,
});
// v0.41.19.0 (T3): throttled yield helper. Fires `opts.yieldDuringPhase`
@@ -830,6 +957,11 @@ export async function runPhaseExtractAtoms(
// ── gbrain#4148 helpers ────────────────────────────────────────────
let malformedOutputs = 0;
const tombstonedForFailures: string[] = [];
+ // v146: transcript tombstones ride a SEPARATE array. `tombstoned_for_failures`
+ // is a list of page SLUGS; transcripts are filesystem paths, and mixing the two
+ // into one array would be a silent type confusion for any future consumer that
+ // resolves those strings as slugs. Both are report-only today.
+ const tombstonedTranscripts: string[] = [];
// #3044 adoption: shared halt policy — auth/billing halt on the first hit,
// a rate_limit streak halts after 3 consecutive failures, a successful
// chat call resets the streak.
@@ -853,13 +985,69 @@ export async function runPhaseExtractAtoms(
} catch { /* fail-soft: page stays rediscoverable */ }
}
+ /**
+ * Stamp the transcript-side tombstone (v146). The file-backed mirror of
+ * `stampAtomsScanHash`: transcripts have no frontmatter, and their discovery
+ * is gated ONLY by `atomsExistingForHashes`, so a transcript that yields no
+ * atom row has nothing to mark it done and is re-attempted every cycle.
+ * Row is (source_id, file_path, content_hash)-keyed, so an edited transcript
+ * is a different row and re-eligibilizes automatically.
+ */
+ async function stampTranscriptTombstone(filePath: string, contentHash: string): Promise<void> {
+ try {
+ await engine.executeRaw(
+ `INSERT INTO extract_atoms_transcript_state
+ (source_id, file_path, content_hash, fail_count, tombstoned, updated_at)
+ VALUES ($1, $2, $3, 0, TRUE, now())
+ ON CONFLICT (source_id, file_path, content_hash)
+ DO UPDATE SET tombstoned = TRUE, updated_at = now()`,
+ [sourceId, filePath, contentHash.slice(0, 16)],
+ );
+ } catch { /* fail-soft: transcript stays rediscoverable */ }
+ }
+
/**
* Durable per-item failure count, keyed to the CURRENT content hash so a
* content edit resets the streak. Returns the new consecutive count, or
- * null for transcripts / on write failure (never blocks the phase).
+ * null on write failure (never blocks the phase).
+ *
+ * v146: transcripts are covered too. Pages keep their frontmatter counter;
+ * transcripts are files with no frontmatter, so theirs lives in
+ * `extract_atoms_transcript_state`. Both reset on a content change for the
+ * same reason — the page counter is hash-keyed, the transcript row IS
+ * hash-keyed — and both feed the same MAX_DETERMINISTIC_FAILURES bound.
*/
- async function recordPageFailureCount(item: { kind: string; slug?: string; contentHash: string }): Promise<number | null> {
- if (item.kind !== 'page' || !item.slug || opts.dryRun) return null;
+ async function recordItemFailureCount(
+ item: { kind: string; slug?: string; filePath?: string; contentHash: string },
+ ): Promise<number | null> {
+ if (opts.dryRun) return null;
+ const hash16 = item.contentHash.slice(0, 16);
+ if (item.kind === 'transcript') {
+ if (!item.filePath) return null;
+ try {
+ const rows = await engine.executeRaw<{ cnt: number | string }>(
+ `INSERT INTO extract_atoms_transcript_state
+ (source_id, file_path, content_hash, fail_count, updated_at)
+ VALUES ($1, $2, $3, 1, now())
+ ON CONFLICT (source_id, file_path, content_hash)
+ DO UPDATE SET fail_count = extract_atoms_transcript_state.fail_count + 1,
+ updated_at = now()
+ RETURNING fail_count AS cnt`,
+ [sourceId, item.filePath, hash16],
+ );
+ const cnt = rows[0]?.cnt;
+ return cnt == null ? null : Number(cnt);
+ } catch (err) {
+ // A strike that never lands means this transcript never tombstones and
+ // re-spends budget forever (#4916's class) — say so. A missing table
+ // was already warned once by the tombstone check above.
+ if (!isUndefinedTableError(err)) {
+ console.error(`[extract_atoms] transcript failure-count write failed for ${item.filePath}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ return null;
+ }
+ }
+ if (item.kind !== 'page' || !item.slug) return null;
try {
const rows = await engine.executeRaw<{ cnt: number | string }>(
`UPDATE pages
@@ -871,7 +1059,7 @@ export async function runPhaseExtractAtoms(
ELSE 1 END)
WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL
RETURNING (frontmatter->>'atoms_fail_count')::int AS cnt`,
- [item.contentHash.slice(0, 16), sourceId, item.slug],
+ [hash16, sourceId, item.slug],
);
const cnt = rows[0]?.cnt;
return cnt == null ? null : Number(cnt);
@@ -925,7 +1113,7 @@ export async function runPhaseExtractAtoms(
if (!parseOutcome.ok) {
malformedOutputs++;
hardFailureCount++;
- const failCount = await recordPageFailureCount(item);
+ const failCount = await recordItemFailureCount(item);
failures.push({
source: originLabel,
error: `malformed model output: ${parseOutcome.reason}` +
@@ -936,9 +1124,15 @@ export async function runPhaseExtractAtoms(
// content hash, tombstone so the backlog floor clears; a content
// edit re-eligibilizes (stamp is hash-keyed). Transient provider
// errors never reach here — they throw and take the catch path.
- if (failCount != null && failCount >= MAX_DETERMINISTIC_FAILURES && !opts.dryRun && item.kind === 'page') {
- await stampAtomsScanHash(item);
- tombstonedForFailures.push(item.slug);
+ // v146: transcripts get the identical bound, via their own store.
+ if (failCount != null && failCount >= MAX_DETERMINISTIC_FAILURES && !opts.dryRun) {
+ if (item.kind === 'page') {
+ await stampAtomsScanHash(item);
+ tombstonedForFailures.push(item.slug);
+ } else {
+ await stampTranscriptTombstone(item.filePath, item.contentHash);
+ tombstonedTranscripts.push(item.filePath);
+ }
}
continue;
}
@@ -954,8 +1148,17 @@ export async function runPhaseExtractAtoms(
// Only stamped after a SUCCESSFUL chat call — LLM failures take the
// catch path below and stay retryable, and malformed output is
// counted above (gbrain#4148), never stamped as success.
- if (!opts.dryRun && item.kind === 'page') {
- await stampAtomsScanHash(item);
+ //
+ // v146: transcripts now stamp too, IMMEDIATELY, exactly as pages do —
+ // a zero-yield is a settled answer about this content, not a failure,
+ // so it needs no streak. Pre-fix transcripts were the one item kind
+ // with no zero-yield marker at all, so an honestly-empty transcript
+ // re-entered the pool and re-spent budget on every cycle forever. The
+ // row is (source_id, file_path, content_hash)-keyed, so editing the
+ // file re-eligibilizes it — which is what makes the permanence safe.
+ if (!opts.dryRun) {
+ if (item.kind === 'page') await stampAtomsScanHash(item);
+ else await stampTranscriptTombstone(item.filePath, item.contentHash);
}
if (item.kind === 'transcript') transcriptsProcessed++;
else pagesProcessed++;
@@ -1057,6 +1260,19 @@ export async function runPhaseExtractAtoms(
from_source_id: sourceId,
to_source_id: sourceId,
});
+ } else if (transcriptPageIndex && resolveTranscriptPages) {
+ // A split session renders one page per part, all sharing a
+ // session id; without per-part offsets the honest attribution is
+ // the whole session, so every part gets the edge.
+ for (const fromSlug of resolveTranscriptPages(item.filePath, transcriptPageIndex)) {
+ provenanceLinks.push({
+ from_slug: fromSlug,
+ to_slug: slug,
+ link_source: 'atom-provenance',
+ from_source_id: sourceId,
+ to_source_id: sourceId,
+ });
+ }
}
totalAtomsExtracted++;
}
@@ -1108,7 +1324,7 @@ export async function runPhaseExtractAtoms(
// suppress a page's atoms.
const message = err instanceof Error ? err.message : String(err);
// #3044: a whole-run LLM outage halts the phase. No
- // recordPageFailureCount here — a global outage says nothing about the
+ // recordItemFailureCount here — a global outage says nothing about the
// content, so it must not pre-charge the per-page tombstone counter.
const decision = llmHalt.observe(err);
if (decision !== 'continue') {
@@ -1123,7 +1339,7 @@ export async function runPhaseExtractAtoms(
const transient =
llmHalt.lastClass() === 'rate_limit' || TRANSIENT_EXTRACT_ERROR_RE.test(message);
if (!transient) {
- await recordPageFailureCount(item);
+ await recordItemFailureCount(item);
hardFailureCount++;
}
failures.push({
@@ -1207,6 +1423,7 @@ export async function runPhaseExtractAtoms(
...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),
malformed_outputs: malformedOutputs,
tombstoned_for_failures: tombstonedForFailures,
+ tombstoned_transcripts: tombstonedTranscripts,
estimated_spend_usd: estimatedSpendUsd,
budget_usd: budgetCap,
model: extractModel,
@@ -1247,33 +1464,101 @@ export function parseAtomsOutcome(raw: string): AtomsParseOutcome {
return direct;
}
-function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {
- // Strip markdown code fences if the LLM wrapped JSON in them.
- let cleaned = raw.trim();
- const fenceMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fenceMatch) cleaned = fenceMatch[1].trim();
-
- // Find the first JSON array bracket.
- const arrayStart = cleaned.indexOf('[');
- if (arrayStart === -1) return { ok: false, reason: 'no JSON array in response' };
- cleaned = cleaned.slice(arrayStart);
+/**
+ * Bound on how many `[` offsets the anchor scan will try. Completions are
+ * already capped by `max_output_tokens`, so this is a belt-and-braces guard
+ * against a pathological bracket-dense response, not a functional limit —
+ * every failing candidate fails at ~offset 0 of its own slice, so the scan is
+ * cheap. Reached-the-cap behaves exactly like found-nothing: the FIRST
+ * offset's outcome is returned, i.e. today's behaviour.
+ */
+const MAX_ARRAY_ANCHOR_CANDIDATES = 64;
+/**
+ * Parse the JSON array anchored at ONE `[` offset, reproducing the historical
+ * two-step exactly: whole-slice parse, then a trim-back to the last `]` to
+ * recover from trailing prose. Split out of parseAtomsOutcomeInner so the
+ * anchor scan can try successive offsets without duplicating the reason
+ * strings — those are asserted by tests and ride the drain's `last_error`.
+ */
+function parseArrayAtOffset(
+ cleaned: string,
+ start: number,
+): { ok: true; parsed: unknown[] } | { ok: false; reason: string } {
+ const slice = cleaned.slice(start);
let parsed: unknown;
try {
- parsed = JSON.parse(cleaned);
+ parsed = JSON.parse(slice);
} catch {
// Try trimming back from the end to recover from trailing prose.
- const arrayEnd = cleaned.lastIndexOf(']');
+ const arrayEnd = slice.lastIndexOf(']');
if (arrayEnd === -1) return { ok: false, reason: 'unterminated JSON array' };
try {
- parsed = JSON.parse(cleaned.slice(0, arrayEnd + 1));
+ parsed = JSON.parse(slice.slice(0, arrayEnd + 1));
} catch {
return { ok: false, reason: 'unparseable JSON array' };
}
}
-
if (!Array.isArray(parsed)) return { ok: false, reason: 'JSON value is not an array' };
- return { ok: true, atoms: atomsFromParsedArray(parsed) };
+ return { ok: true, parsed };
+}
+
+function parseAtomsOutcomeInner(raw: string): AtomsParseOutcome {
+ // Strip markdown code fences if the LLM wrapped JSON in them.
+ let cleaned = raw.trim();
+ const fenceMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fenceMatch) cleaned = fenceMatch[1].trim();
+
+ const firstStart = cleaned.indexOf('[');
+ if (firstStart === -1) return { ok: false, reason: 'no JSON array in response' };
+
+ // ANCHOR SCAN. Pre-fix this committed to `indexOf('[')` — the FIRST bracket
+ // anywhere in the response. Any bracket in a preamble hijacked the anchor,
+ // and a brain whose house style mandates inline `[Source: …]` citations and
+ // `[[wikilink]]` backlinks (or whose transcripts carry `[user]` / `[tool: …]`
+ // role markers) makes the model echo one while narrating, so a response
+ // carrying a perfectly good array was reported `unparseable JSON array`.
+ //
+ // Acceptance requires the candidate to parse AND to yield >= 1 atom-shaped
+ // element (`atomsFromParsedArray` is the single source of truth for
+ // "atom-shaped"). Parseability alone is NOT enough: a zero-yield result is
+ // exactly what TOMBSTONES an item (#2144), so only ONE parseable shape may
+ // produce it — the literal `[]` the #4948 prompt asks for when nothing is
+ // extractable, accepted at ANY offset (a model that echoes a `[Source: …]`
+ // citation before obeying must not lose its honest `[]` to this gate and
+ // burn three strikes into a tombstone + halt). A NON-empty array whose
+ // elements all fail the shape gate is malformed output: it rides the
+ // failure streak like every other parse failure instead of tombstoning the
+ // item forever on the first try.
+ let firstAttempt: ReturnType<typeof parseArrayAtOffset> | null = null;
+ let sawEmptyArray = false;
+ let candidates = 0;
+ for (
+ let start = firstStart;
+ start !== -1 && candidates < MAX_ARRAY_ANCHOR_CANDIDATES;
+ start = cleaned.indexOf('[', start + 1)
+ ) {
+ candidates++;
+ const attempt = parseArrayAtOffset(cleaned, start);
+ // Captured on the FIRST iteration only — every reason string this function
+ // can return still describes the first bracket, unchanged.
+ if (firstAttempt === null) firstAttempt = attempt;
+ if (attempt.ok) {
+ if (attempt.parsed.length === 0) { sawEmptyArray = true; continue; }
+ const atoms = atomsFromParsedArray(attempt.parsed);
+ if (atoms.length > 0) return { ok: true, atoms };
+ }
+ }
+
+ // Nothing yielded a real atom. An honest `[]` anywhere is the zero-yield
+ // success (#4148 keeps "found nothing" distinct from "malformed"); otherwise
+ // fall back to the FIRST offset's outcome — never a later one — so the
+ // failure reason the drain surfaces as `last_error` still describes the
+ // first bracket.
+ if (sawEmptyArray) return { ok: true, atoms: [] };
+ if (firstAttempt === null) return { ok: false, reason: 'no JSON array in response' };
+ if (firstAttempt.ok) return { ok: false, reason: 'array had no atom-shaped elements' };
+ return firstAttempt;
}
/**
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 0f070f7808..a5924cfc0a 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -53,6 +53,8 @@
* backlog through the sanctioned removal path instead of raw SQL.
*/
+import { existsSync, readFileSync } from 'node:fs';
+
import type { BrainEngine } from '../engine.ts';
import { resolveSupersededByRow, type SupersedeTarget } from '../facts/supersede-resolve.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
@@ -70,6 +72,9 @@ import {
} from './phantom-redirect.ts';
import { embed, isAvailable } from '../ai/gateway.ts';
import { isAborted } from '../abort-check.ts';
+import { parseMarkdown } from '../markdown.ts';
+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
+import { acquirePageLock } from '../page-lock.ts';
interface ExistingPageFact {
// v0.46 (#3014) — the row's own fact id. Read so the supersession-drift
@@ -102,6 +107,93 @@ function dedupeFactsByContentKey(facts: FenceExtractedFact[]): FenceExtractedFac
return deduped;
}
+/**
+ * Destructive reconciliation may only trust the pages-table body when it
+ * still matches the canonical Markdown file. The fact writer deliberately
+ * commits Markdown first and then stamps the facts index, while page sync is
+ * asynchronous. In that gap a sweep can observe the old pages.compiled_truth
+ * plus the new fact row and otherwise delete the new row as "stale".
+ *
+ * `unavailable` preserves the existing DB-only/thin-client behaviour. A local
+ * canonical file that exists but cannot be read is fail-closed: destructive
+ * cleanup waits for a healthy sync/read instead of guessing that the cache is
+ * authoritative.
+ */
+async function canonicalCacheState(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+ cachedCompiledTruth: string,
+ cachedTimeline: string,
+): Promise<'fresh' | 'stale' | 'unavailable'> {
+ // sync.write_through=off: the fence writers already treat the file as
+ // non-canonical (fence-write.ts legacy fallback), so a stale mirror file must
+ // not block reconcile here either.
+ if (await isWriteThroughDisabled(engine)) return 'unavailable';
+ const target = await resolvePageWriteTarget(engine, slug, sourceId);
+ if (!target.ok || !existsSync(target.filePath)) return 'unavailable';
+ try {
+ const canonical = parseMarkdown(readFileSync(target.filePath, 'utf-8'), target.filePath);
+ return canonical.compiled_truth === cachedCompiledTruth.trim()
+ && canonical.timeline === cachedTimeline.trim()
+ ? 'fresh'
+ : 'stale';
+ } catch {
+ return 'stale';
+ }
+}
+
+async function refuseDestructiveReconcileOnStaleCache(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+ cachedCompiledTruth: string,
+ cachedTimeline: string,
+ warnings: string[],
+): Promise<boolean> {
+ const state = await canonicalCacheState(
+ engine,
+ slug,
+ sourceId,
+ cachedCompiledTruth,
+ cachedTimeline,
+ );
+ if (state !== 'stale') return false;
+ warnings.push(
+ `${slug}: FACTS_PAGE_CACHE_STALE: canonical Markdown differs from the pages cache; ` +
+ 'refusing destructive fact reconciliation until gbrain sync refreshes the page index.',
+ );
+ return true;
+}
+
+/**
+ * Run one page's destructive reconcile under its page lock (5s, matching the
+ * fence writers in fence-write.ts / forget.ts). A lock still held past the
+ * deadline degrades to a FACTS_PAGE_LOCK_TIMEOUT warning for THAT page and a
+ * null result, so one wedged page cannot abort the remaining slugs of the
+ * phase run. Errors thrown by `fn` itself still propagate.
+ */
+async function underPageLock<T>(
+ slug: string,
+ fn: () => Promise<T>,
+ opts: ExtractFactsOpts,
+ warnings: string[],
+): Promise<T | null> {
+ const handle = await acquirePageLock(slug, { timeoutMs: 5_000, lockRoot: opts.pageLockRoot });
+ if (!handle) {
+ warnings.push(
+ `${slug}: FACTS_PAGE_LOCK_TIMEOUT: page lock held by another writer; ` +
+ 'skipping destructive fact reconciliation for this page until the next run.',
+ );
+ return null;
+ }
+ try {
+ return await fn();
+ } finally {
+ await handle.release();
+ }
+}
+
/**
* Fence-owned DB rows for one page coordinate. Excludes `cli:`-origin
* conversation facts (#1928) — they are not fence-owned, so they must
@@ -167,6 +259,8 @@ export interface ExtractFactsOpts {
* under the worker's 30s force-evict instead of running to completion.
*/
signal?: AbortSignal;
+ /** Override the shared page-lock directory for deterministic tests. */
+ pageLockRoot?: string;
}
export interface ExtractFactsResult {
@@ -524,19 +618,34 @@ export async function runExtractFacts(
if (extracted.length === 0) {
if (existing.length > 0) {
- // The delete targets source_markdown_slug = slug only, so
- // NULL-source_markdown_slug legacy rows survive (the
- // partial-UNIQUE-index keyspace). #1928: `cli:`-origin facts
- // (conversation facts from extract-conversation-facts) are NOT
- // fence-owned — the page carries no `## Facts` fence to recreate
- // them — so they MUST survive this reconcile. #2646: soft-expired
- // legacy rows (forget_fact's record of the forget) likewise
- // survive via preserveExpiredLegacy.
- const deleted = await engine.deleteFactsForPage(slug, sourceId, {
- excludeSourcePrefixes: ['cli:'],
- preserveExpiredLegacy: true,
- });
- result.factsDeleted += deleted.deleted;
+ const deletion = await underPageLock(slug, async () => {
+ if (await refuseDestructiveReconcileOnStaleCache(
+ engine,
+ slug,
+ sourceId,
+ page.compiled_truth ?? '',
+ page.timeline ?? '',
+ result.warnings,
+ )) {
+ return null;
+ }
+ // The delete targets source_markdown_slug = slug only, so
+ // NULL-source_markdown_slug legacy rows survive (the
+ // partial-UNIQUE-index keyspace). #1928: `cli:`-origin facts
+ // (conversation facts from extract-conversation-facts) are NOT
+ // fence-owned — the page carries no `## Facts` fence to recreate
+ // them — so they MUST survive this reconcile. #2646: soft-expired
+ // legacy rows (forget_fact's record of the forget) likewise
+ // survive via preserveExpiredLegacy.
+ return engine.deleteFactsForPage(slug, sourceId, {
+ excludeSourcePrefixes: ['cli:'],
+ preserveExpiredLegacy: true,
+ });
+ }, opts, result.warnings);
+ if (!deletion) {
+ continue;
+ }
+ result.factsDeleted += deletion.deleted;
}
continue;
}
@@ -670,11 +779,27 @@ export async function runExtractFacts(
if (toInsert.length === 0) continue;
- const inserted = await engine.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
+ const insert = () => engine.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
toInsert,
{ source_id: sourceId },
deleteForPageFirst ? { deleteForPageFirst } : undefined,
);
+ const inserted = deleteForPageFirst
+ ? await underPageLock(slug, async () => {
+ if (await refuseDestructiveReconcileOnStaleCache(
+ engine,
+ slug,
+ sourceId,
+ page.compiled_truth ?? '',
+ page.timeline ?? '',
+ result.warnings,
+ )) {
+ return null;
+ }
+ return insert();
+ }, opts, result.warnings)
+ : await insert();
+ if (!inserted) continue;
result.factsInserted += inserted.inserted;
// v0.46 (#3014) — the wipe (when needed) ran inside insertFacts' txn;
// count it here from the atomic result rather than a separate delete.
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index 20a287a5a3..179b1ca3bf 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -48,6 +48,7 @@ import {
import {
parseFactsFence,
renderFactsTable,
+ replaceOrInsertFactsFence,
FACTS_FENCE_BEGIN,
FACTS_FENCE_END,
type ParsedFact,
@@ -239,16 +240,9 @@ function appendPhantomFenceRowsToCanonical(
if (appended === 0) return 0;
- const newFence = renderFactsTable(merged);
- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
- let newBody: string;
- if (beginIdx !== -1 && endIdx !== -1) {
- newBody = body.slice(0, beginIdx) + newFence + body.slice(endIdx + FACTS_FENCE_END.length);
- } else {
- const sep = body.endsWith('\n') ? '\n' : '\n\n';
- newBody = `${body}${sep}## Facts\n\n${newFence}\n`;
- }
+ // Shared placement rule (#4756): replace in place, else insert ABOVE the
+ // timeline sentinel — never a blind EOF append below `## Timeline`.
+ const newBody = replaceOrInsertFactsFence(body, renderFactsTable(merged));
// Atomic write: .tmp first, parse-validate, rename.
const tmpPath = `${canonicalPath}.tmp`;
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index 8e3b25fc05..c484e35420 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -20,13 +20,13 @@
// For T3/T4: deterministic stub narrative.
// 6. Write concept-typed pages with the synthesis mode made explicit.
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import { resolveModel } from '../model-config.ts';
import type { PhaseResult } from '../cycle.ts';
import type { ProgressReporter } from '../progress.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
import { upsertExtractRollup } from '../extract/rollup-writer.ts';
-import { chat as gatewayChat, isAvailable } from '../ai/gateway.ts';
+import { chat as gatewayChat, isAvailable, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';
// #2163: concept pages route through importFromContent (the same
// parse→chunk→embed pipeline put_page uses) instead of a bare engine.putPage,
@@ -51,6 +51,32 @@ const FALLBACK_PRICING: ModelPricing = canonicalLookup('anthropic:claude-sonnet-
const TIER_T1_MIN = 10;
const TIER_T2_MIN = 5;
const TIER_T3_MIN = 2;
+/**
+ * Output cap for the per-concept narrative. 500 sizes the *answer* (a
+ * 1-paragraph summary) and is ample for a non-reasoning model. It is NOT ample
+ * for a thinking-by-default model: reasoning bills as output and counts against
+ * max_tokens, so the budget is spent before any answer text is emitted — hosted
+ * DeepSeek returns empty content (→ `deterministicNarrative` ships a template
+ * stub as 'error_fallback'), while the native deepseek: recipe promotes the
+ * truncated reasoning_content into content (→ chain-of-thought persisted as
+ * the narrative with synthesis_mode 'llm'). This phase resolves at
+ * `tier: 'reasoning'`, so a thinking model here is the expected case.
+ */
+const DEFAULT_SYNTH_MAX_OUTPUT_TOKENS = 500;
+
+/**
+ * Narrative output cap for the resolved model. `isThinkingModel` is the
+ * gateway's shared predicate (name-matched Claude 5 OR recipe-declared
+ * `thinking_by_default`; unknown providers count as non-thinking), the same
+ * check think's maxOutputTokensFor and the subagent handler use. Thinking
+ * models get the gateway's verified THINKING_MODEL_MAX_OUTPUT_TOKENS rather
+ * than a phase-private number: a local 8000 contradicted it, and DeepSeek v4
+ * truncates at 8192-class caps — the reasoning budget was gone before any
+ * answer text.
+ */
+export function resolveSynthMaxOutputTokens(modelStr: string): number {
+ return isThinkingModel(modelStr) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : DEFAULT_SYNTH_MAX_OUTPUT_TOKENS;
+}
export interface SynthesizeConceptsOpts {
brainDir?: string;
@@ -80,6 +106,8 @@ export interface SynthesizeConceptsOpts {
interface AtomGroup {
conceptSlug: string;
+ /** #4589: member atom slugs — the provenance edges are written from these. */
+ atomSlugs: string[];
atomTitles: string[];
atomBodies: string[];
tier: 'T1' | 'T2' | 'T3' | 'T4';
@@ -114,11 +142,16 @@ export async function runPhaseSynthesizeConcepts(
compiled_truth: string;
frontmatter: { concepts?: string[]; imported_from?: string };
}>(
+ // Codex P2: scoped to the cycle source — the provenance edges below
+ // are pinned to it, so a brain-global scan grouped same-slug atoms
+ // from OTHER sources into this source's concepts.
`SELECT slug, title, compiled_truth, frontmatter
FROM pages
WHERE type = 'atom'
+ AND source_id = $1
AND deleted_at IS NULL
AND (frontmatter->>'imported_from') IS NULL`,
+ [opts.sourceId ?? 'default'],
);
atoms = rows
.filter((r) => Array.isArray(r.frontmatter?.concepts) && r.frontmatter.concepts.length > 0)
@@ -144,10 +177,11 @@ export async function runPhaseSynthesizeConcepts(
}
// 2. Group atoms by concept slug
- const groups = new Map<string, { titles: string[]; bodies: string[] }>();
+ const groups = new Map<string, { slugs: string[]; titles: string[]; bodies: string[] }>();
for (const atom of atoms) {
for (const conceptSlug of atom.concept_refs) {
- const existing = groups.get(conceptSlug) ?? { titles: [], bodies: [] };
+ const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [] };
+ existing.slugs.push(atom.slug);
existing.titles.push(atom.title);
existing.bodies.push(atom.body);
groups.set(conceptSlug, existing);
@@ -163,6 +197,7 @@ export async function runPhaseSynthesizeConcepts(
count >= TIER_T1_MIN ? 'T1' : count >= TIER_T2_MIN ? 'T2' : 'T3';
atomGroups.push({
conceptSlug,
+ atomSlugs: data.slugs,
atomTitles: data.titles,
atomBodies: data.bodies,
tier,
@@ -193,6 +228,11 @@ export async function runPhaseSynthesizeConcepts(
let estimatedSpendUsd = 0;
const budgetCap = DEFAULT_BUDGET_USD;
const failures: Array<{ concept: string; error: string }> = [];
+ // #4589 provenance-link problems. Kept OUT of `failures`: that list means
+ // "the LLM call failed → template fallback" downstream (summary wording,
+ // rollup halt_delta / round_completed_delta), which a missing edge is not —
+ // the narrative was synthesized and persisted as-is. Warn-only.
+ const linkWarnings: Array<{ concept: string; warning: string }> = [];
// #3044 adoption: shared halt policy — auth/billing halt on the first
// hit, a rate_limit streak halts after 3 consecutive failures, a
// successful chat call resets the streak.
@@ -234,6 +274,7 @@ export async function runPhaseSynthesizeConcepts(
tier: 'reasoning',
fallback: 'sonnet',
});
+ const synthMaxOutputTokens = resolveSynthMaxOutputTokens(synthModel);
for (const group of atomGroups) {
tierCounts[group.tier]++;
let narrative: string;
@@ -260,7 +301,7 @@ export async function runPhaseSynthesizeConcepts(
.join('\n\n')}`,
},
],
- maxTokens: 500,
+ maxTokens: synthMaxOutputTokens,
});
// Post-await yield (T3): the LLM call is the main TTL hazard
// codex flagged. Throttle inside maybeYield bounds the actual
@@ -331,11 +372,43 @@ export async function runPhaseSynthesizeConcepts(
'',
{ type: 'concept', title: title.replace(/-/g, ' '), tags: [] },
);
- await importFromContent(engine, `concepts/${title}`, md, {
+ const conceptSlug = `concepts/${title}`;
+ await importFromContent(engine, conceptSlug, md, {
noEmbed: !isAvailable('embedding'),
// #4416: target the cycle's resolved source, not the 'default' literal.
sourceId: opts.sourceId,
});
+ // #4589: bank concept<->member-atom provenance edges. The prompt forbids
+ // enumerating atoms in the body and no frontmatter field maps to a link
+ // verb, so without this every concept page lands with zero edges (graph
+ // orphan). Dedicated link_source keeps reconcile passes from pruning
+ // them; both endpoints sit in the cycle's source (an atom living in
+ // another source drops out of the batch JOIN — no cross-source edge).
+ // ON CONFLICT DO NOTHING makes re-runs idempotent, so a failure here is
+ // best-effort: recorded as a warn, the page write stands. Mirrors #3961.
+ const src = opts.sourceId ?? 'default';
+ const provenanceLinks: LinkBatchInput[] = [...new Set(group.atomSlugs)].flatMap((atomSlug) => [
+ { from_slug: conceptSlug, to_slug: atomSlug, link_type: 'synthesized_from', link_source: 'concept-provenance', context: 'member atom', from_source_id: src, to_source_id: src },
+ { from_slug: atomSlug, to_slug: conceptSlug, link_type: 'synthesizes', link_source: 'concept-provenance', context: 'concept synthesized from this atom', from_source_id: src, to_source_id: src },
+ ]);
+ try {
+ const inserted = await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.synthesize_concepts.provenance' }); // gbrain-allow-direct-insert: concept-provenance edges derived from the synthesis itself (no markdown body to reconcile from)
+ // Zero rows back with edges requested means every member atom fell
+ // out of the batch JOIN (not in this source) — unless a prior run
+ // already banked them (ON CONFLICT DO NOTHING also returns 0). A
+ // silent 'ok' here is a graph orphan with a clean receipt.
+ if (inserted === 0 && provenanceLinks.length > 0) {
+ const banked = (await engine.getLinks(conceptSlug, { sourceId: src }))
+ .some((l) => l.link_source === 'concept-provenance');
+ if (!banked) {
+ linkWarnings.push({ concept: group.conceptSlug, warning: `provenance links: 0 of ${provenanceLinks.length} edges landed (member atoms not in source '${src}'?)` });
+ }
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ linkWarnings.push({ concept: group.conceptSlug, warning: `provenance links failed: ${msg}` });
+ console.error(`[synthesize_concepts] provenance links failed for ${conceptSlug} (non-fatal): ${msg}`);
+ }
}
conceptsWritten++;
// v0.41.19.0 (T4): one tick per concept group with running count.
@@ -386,12 +459,13 @@ export async function runPhaseSynthesizeConcepts(
return {
phase: 'synthesize_concepts',
- status: failures.length > 0 ? 'warn' : 'ok',
+ status: failures.length > 0 || linkWarnings.length > 0 ? 'warn' : 'ok',
duration_ms: 0,
summary:
`synthesize_concepts: ${conceptsWritten} concepts ` +
`(T1=${tierCounts.T1} T2=${tierCounts.T2} T3=${tierCounts.T3})` +
- (failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : ''),
+ (failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : '') +
+ (linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : ''),
details: {
concepts_written: conceptsWritten,
tier_counts: tierCounts,
@@ -399,6 +473,7 @@ export async function runPhaseSynthesizeConcepts(
groups_found: atomGroups.length,
atoms_seen: atoms.length,
failures,
+ link_warnings: linkWarnings,
...(abortedGlobalError ? { aborted_global_error: abortedGlobalError } : {}),
estimated_spend_usd: estimatedSpendUsd,
budget_usd: budgetCap,
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index d44f65a71e..341d881584 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -634,10 +634,8 @@ async function runPhaseSynthesizeInner(
const skipReports: Array<{ filePath: string; reason: string }> = [];
const maxCharsPerChunk = computeChunkCharBudget(config.model, config.maxPromptTokens);
- const successfulLegacyKeys = await loadSuccessfulLegacySynthesisKeys(
- engine,
- cycleSourceId,
- );
+ const successfulLegacyKeys = await loadSuccessfulSynthesisKeys(engine, cycleSourceId, 'dream:synth:');
+ const successfulV2Keys = await loadSuccessfulSynthesisKeys(engine, cycleSourceId, 'dream:synth-v2:');
// Per-source daily submission cap (D2D: default 0 = disabled; opt-in
// backstop via dream.synthesize.max_submissions_per_source_per_day).
@@ -703,6 +701,25 @@ async function runPhaseSynthesizeInner(
continue;
}
+ // Same rule for the synth-v2 key family. Without it a transcript whose
+ // children already COMPLETED coalesced onto them via queue.add's
+ // idempotency key — free for the daily cap, but only AFTER the link
+ // manifest (up to 20 searches) was built — and the coalesced children
+ // re-entered writtenRefs, so their old pages were quote-repaired,
+ // restamped and re-embedded every night with nothing new written.
+ const v2Completion = findSynthV2Completion(
+ successfulV2Keys, t.filePath, hash16, opts.sourceId ?? 'default',
+ );
+ if (v2Completion) {
+ skipReports.push({
+ filePath: t.filePath,
+ reason: v2Completion === 'chunked'
+ ? 'already_synthesized_v2_chunked'
+ : 'already_synthesized_v2_single_chunk',
+ });
+ continue;
+ }
+
const chunks = splitTranscriptByBudget(t.content, t.contentHash, maxCharsPerChunk);
// D5 cap hit: log + skip; do NOT write to dream_verdicts. Closes the
@@ -795,6 +812,7 @@ async function runPhaseSynthesizeInner(
// #4117: validated per-lane namespaces.
config.reflectionsPrefix,
config.originalsPrefix,
+ config.mode,
),
model: subagentModel,
max_turns: config.maxTurns,
@@ -2613,6 +2631,7 @@ function buildSynthesisPrompt(
// config-resolved values.
reflectionsPrefix = `${outputRoot}/personal/reflections`,
originalsPrefix = `${outputRoot}/originals/ideas`,
+ mode: 'agentic' | 'oneshot' = 'agentic',
): string {
// #4348: UTC projection retained here on purpose — this is a slug-name
// hint for undated sources, not calendar provenance.
@@ -2629,12 +2648,18 @@ function buildSynthesisPrompt(
? `${t.filePath} (chunk ${chunkIdx + 1}/${chunkTotal})`
: t.filePath;
// #4216 rule-2 wording: with a manifest present, the model is pointed at the
- // pre-resolved candidates FIRST (the search tool stays available on the
- // agentic path; the oneshot path has no tools, and this same prompt must be
- // byte-identical across a oneshot attempt and its agentic fallback).
- const crossRefRule = linkManifestBlock
- ? 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`) to existing brain content. Pick targets from the LINK CANDIDATES above (or another page you write in this response); use the search tool, if available, only when no candidate fits.'
- : 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`) to existing brain content. Use the search tool to find existing pages first.';
+ // pre-resolved candidates FIRST. The agentic prompt keeps its search-tool
+ // guidance; oneshot has no tools, so it may use only pre-resolved candidates
+ // or pages in the same JSON batch. (A oneshot child's prompt is stored as
+ // data.prompt and reused verbatim by its in-job agentic fallback, which
+ // keeps its tools in the schema and merely loses the search hint.)
+ const crossRefRule = mode === 'agentic'
+ ? (linkManifestBlock
+ ? 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`) to existing brain content. Pick targets from the LINK CANDIDATES above (or another page you write in this response); use the search tool, if available, only when no candidate fits.'
+ : 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`) to existing brain content. Use the search tool to find existing pages first.')
+ : (linkManifestBlock
+ ? 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`). Pick its target from the LINK CANDIDATES above or another page in this response.'
+ : 'Cross-reference compulsively: every new page MUST contain at least one wikilink (e.g., `[ref](people/jane-doe)` or `[[people/jane-doe]]`) to another page in this response.');
// OV-7: the write allow-list must live in the PROMPT, not only in the
// put_page tool schema — the oneshot path never sees a tool schema.
const allowedPathsBlock = allowedSlugPrefixes.length > 0
@@ -2650,7 +2675,7 @@ CONTEXT
OUTPUT POLICY (ALL of these are required)
1. Quote the user verbatim. Quotation marks are ONLY for spans reproducible EXACTLY from the transcript below — if you cannot reproduce a span exactly, paraphrase it WITHOUT quotation marks. Do not paraphrase memorable phrasings you can quote exactly.
2. ${crossRefRule}
-3. Do NOT write to any path outside the ALLOWED WRITE PATHS above${allowedSlugPrefixes.length > 0 ? '' : ' (shown in the put_page schema)'}.
+3. Do NOT write to any path outside the ALLOWED WRITE PATHS above${allowedSlugPrefixes.length > 0 ? '' : mode === 'agentic' ? ' (shown in the put_page schema)' : '; if none are listed, return the Task D skip response'}.
4. Slug discipline: lowercase alphanumeric and hyphens only, slash-separated segments. NO underscores, NO file extensions.
5. Self-contained opening: begin every new page's body with a 2-3 sentence summary that a reader unfamiliar with this transcript could understand on its own, before any quotes or detail. Do not assume the reader has the source conversation for context.
6. Preserve concrete facts: carry the specific numbers, dates, dollar amounts, names, and who-decided-what OF the salient content you write about, exactly as the transcript states them. Do not add routine logistics for their own sake.
@@ -2663,16 +2688,18 @@ A. Reflections (self-knowledge, pattern recognition, emotional processing):
B. Originals (new ideas, frames, theses, mental models):
slug: \`${originalsPrefix}/${dateHint}-<idea-slug>-${hashSuffix}\`
-C. People mentions: ${linkManifestBlock ? 'check LINK CANDIDATES (and the search tool, when available) first' : 'search first, when a search tool is available'}; never write over an existing person page (the orchestrator handles people enrichment via timeline entries — your job is the reflection/original synthesis, NOT modifying existing person pages).
+C. People mentions: ${mode === 'agentic'
+ ? (linkManifestBlock ? 'check LINK CANDIDATES (and the search tool, when available) first' : 'search first, when a search tool is available')
+ : (linkManifestBlock ? 'check LINK CANDIDATES first' : 'do not create or modify person pages')}; never write over an existing person page (the orchestrator handles people enrichment via timeline entries — your job is the reflection/original synthesis, NOT modifying existing person pages).
D. If nothing in this transcript meets the bar (significance filter already passed but the content is still routine), return without writing anything.
TRANSCRIPT (${transcriptHeader})
---
${chunkText}
----
-
-When done, briefly list the slugs you wrote in your final message so the orchestrator can audit.`;
+---${mode === 'agentic'
+ ? '\n\nWhen done, briefly list the slugs you wrote in your final message so the orchestrator can audit.'
+ : ''}`;
}
function sanitizeForSlug(s: string): string {
@@ -2752,12 +2779,15 @@ async function collectChildPutPageSlugs(
}
/**
- * D8: load every `completed` legacy job key in the pre-v2 path-based
- * family `dream:synth:<filePath>:<hash16>[:c<i>of<n>]`. Used at fan-out
- * time to detect transcripts already synthesized under an old key shape;
- * those should NOT be re-submitted under v2 keys. (v2 keys start with
- * `dream:synth-v2:` and don't match the LIKE prefix — the queue's own
- * idempotency dedupe already covers them.)
+ * Load every `completed` subagent job key in one synthesis key family for
+ * one source. Called once per phase per family so the submit loop can skip
+ * transcripts already synthesized BEFORE building their link manifest:
+ * - D8 legacy `dream:synth:<filePath>:<hash16>[:c<i>of<n>]` (pre-v2 shape;
+ * must not be re-submitted under v2 keys);
+ * - current `dream:synth-v2:<source>:filename:<basename>:<hash16>[:c<i>of<n>]`
+ * (the queue's idempotency dedupe would coalesce these too, but only after
+ * the manifest build, and the coalesced children would re-enter writtenRefs).
+ * `dream:synth:%` does not match `dream:synth-v2:` keys.
*
* Plain `status = 'completed'` deliberately mirrors the queue-level
* idempotency semantics the legacy keys relied on: a completed job blocks
@@ -2769,9 +2799,10 @@ async function collectChildPutPageSlugs(
* Loads source-scoped completions once per phase; no schema additions
* and no repeated history scan for each transcript.
*/
-async function loadSuccessfulLegacySynthesisKeys(
+async function loadSuccessfulSynthesisKeys(
engine: BrainEngine,
sourceId: string,
+ keyPrefix: 'dream:synth:' | 'dream:synth-v2:',
): Promise<string[]> {
const rows = await engine.executeRaw<{ idempotency_key: string }>(
`SELECT idempotency_key
@@ -2779,12 +2810,46 @@ async function loadSuccessfulLegacySynthesisKeys(
WHERE name = 'subagent'
AND status = 'completed'
AND COALESCE(NULLIF(data->>'source_id', ''), 'default') = $1
- AND idempotency_key LIKE 'dream:synth:%'`,
- [sourceId],
+ AND idempotency_key LIKE $2`,
+ [sourceId, `${keyPrefix}%`],
);
return rows.map(row => row.idempotency_key);
}
+/**
+ * Mirror of findLegacyCompletion for the synth-v2 key family (grammar as
+ * produced by the submit loop / parsed by `parseSynthV2Key`): `'single'` when
+ * the unchunked key completed, `'chunked'` when a FULL `:c0of<n>`..`:c<n-1>of<n>`
+ * set completed, null otherwise (a cancelled row never counts).
+ */
+function findSynthV2Completion(
+ successfulKeys: string[],
+ filePath: string,
+ hash16: string,
+ sourceId: string,
+): 'single' | 'chunked' | null {
+ const prefix =
+ `dream:synth-v2:${encodeURIComponent(sourceId)}` +
+ `:filename:${encodeURIComponent(basename(filePath))}:${hash16}`;
+ const chunkSets = new Map<number, Set<number>>();
+ for (const key of successfulKeys) {
+ if (key === prefix) return 'single';
+ if (!key.startsWith(prefix + ':c')) continue;
+ const chunk = /:c(\d+)of(\d+)$/.exec(key);
+ if (!chunk) continue;
+ const i = Number(chunk[1]);
+ const n = Number(chunk[2]);
+ if (n < 1 || i < 0 || i >= n) continue;
+ let seen = chunkSets.get(n);
+ if (!seen) chunkSets.set(n, seen = new Set());
+ seen.add(i);
+ }
+ for (const [n, seen] of chunkSets) {
+ if (seen.size === n) return 'chunked';
+ }
+ return null;
+}
+
/**
* Match a transcript (by filename + content hash) against completed legacy
* keys. `'single'` when a `dream:synth:<path>:<hash16>` completion exists;
diff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.ts
index cf8313d068..f78d4ebacd 100644
--- a/src/core/cycle/transcript-discovery.ts
+++ b/src/core/cycle/transcript-discovery.ts
@@ -127,19 +127,27 @@ export function isDreamOutput(content: string, bypass = false): boolean {
*/
export const DEFAULT_EXCLUDE_PATTERNS: readonly string[] = ['medical', 'therapy'];
+/** One compiled exclude pattern plus the configured string it came from. */
+interface CompiledExclude {
+ re: RegExp;
+ /** The pattern as the operator wrote it (`medical`, `^therapy:`), used for reporting. */
+ label: string;
+}
+
/**
* Auto-wrap bare-word patterns in `\b<word>\b`. Power users can pass full
* regex (e.g. `^therapy:`) which we honor verbatim. Heuristic: any input
* that's purely alphanumeric+hyphen+underscore is treated as a bare word.
*/
-export function compileExcludePatterns(patterns: string[] | undefined): RegExp[] {
+function compileLabeledExcludePatterns(patterns: string[] | undefined): CompiledExclude[] {
if (!patterns || patterns.length === 0) return [];
- const out: RegExp[] = [];
+ const out: CompiledExclude[] = [];
for (const p of patterns) {
if (!p) continue;
try {
const src = WORD_BOUNDARY_HEURISTIC.test(p) ? `\\b${p}\\b` : p;
- out.push(new RegExp(src, 'i'));
+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- patterns come from the operator's own local config (dream.synthesize.exclude_patterns), never from remote or page content; a malformed pattern is caught below and skipped
+ out.push({ re: new RegExp(src, 'i'), label: p });
} catch (e) {
// Bad regex from user config — skip with stderr warning, don't crash.
const msg = e instanceof Error ? e.message : String(e);
@@ -149,6 +157,39 @@ export function compileExcludePatterns(patterns: string[] | undefined): RegExp[]
return out;
}
+/** Compiled regexes only; see `compileLabeledExcludePatterns` for the labeled form. */
+export function compileExcludePatterns(patterns: string[] | undefined): RegExp[] {
+ return compileLabeledExcludePatterns(patterns).map(c => c.re);
+}
+
+/**
+ * Per-run tally of exclude_patterns hits, reported as ONE stderr line at the
+ * end of discovery so an operator can see WHY a transcript was not
+ * synthesised (before this, an excluded transcript vanished without a
+ * trace and the run just said "no transcripts to process"). The line names
+ * the count and the pattern labels that fired, never a path, basename, or
+ * any transcript content: the patterns exist precisely because the matching
+ * files are sensitive.
+ */
+class ExcludeTally {
+ private excluded = 0;
+ private readonly byLabel = new Map<string, number>();
+
+ record(labels: string[]): void {
+ this.excluded += 1;
+ for (const label of labels) this.byLabel.set(label, (this.byLabel.get(label) ?? 0) + 1);
+ }
+
+ report(): void {
+ if (this.excluded === 0) return;
+ const detail = [...this.byLabel.entries()].map(([label, n]) => `${label}: ${n}`).join(', ');
+ process.stderr.write(
+ `[dream] excluded ${this.excluded} transcript(s) matching exclude_patterns (${detail}); ` +
+ `set dream.synthesize.exclude_patterns to change\n`,
+ );
+ }
+}
+
function hashContent(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex');
}
@@ -162,11 +203,13 @@ function isInDateRange(date: string | null, opts: DiscoverOpts): boolean {
return true;
}
-function matchesAnyExclude(text: string, patterns: RegExp[]): boolean {
- for (const re of patterns) {
- if (re.test(text)) return true;
+/** Labels of every compiled pattern that matches `text` (empty when none). */
+function matchingExcludeLabels(text: string, patterns: CompiledExclude[]): string[] {
+ const hits: string[] = [];
+ for (const { re, label } of patterns) {
+ if (re.test(text)) hits.push(label);
}
- return false;
+ return hits;
}
function listTextFiles(dir: string): string[] {
@@ -215,14 +258,17 @@ function listTextFiles(dir: string): string[] {
* - have date-prefixed basenames outside the requested window
* - have content shorter than `minChars`
* - carry the `dream_generated: true` self-consumption marker (unless `bypassGuard`)
- * - match any compiled exclude pattern (case-insensitive word-boundary by default)
+ * - match any compiled exclude pattern (case-insensitive word-boundary by default);
+ * these are summarised in ONE stderr line at the end (count + pattern labels,
+ * never the files)
*
* Returns sorted by filePath so re-runs are deterministic.
*/
export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[] {
const minChars = opts.minChars ?? 2000;
const bypass = opts.bypassGuard === true;
- const excludeRes = compileExcludePatterns(opts.excludePatterns);
+ const excludes = compileLabeledExcludePatterns(opts.excludePatterns);
+ const tally = new ExcludeTally();
const dirs = [opts.corpusDir, opts.meetingTranscriptsDir].filter(
(d): d is string => typeof d === 'string' && d.length > 0,
);
@@ -247,7 +293,11 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]
process.stderr.write(`[dream] skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);
continue;
}
- if (matchesAnyExclude(content, excludeRes)) continue;
+ const excludeHits = matchingExcludeLabels(content, excludes);
+ if (excludeHits.length > 0) {
+ tally.record(excludeHits);
+ continue;
+ }
results.push({
filePath,
@@ -259,6 +309,7 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]
}
}
+ tally.report();
return results.sort((a, b) => a.filePath.localeCompare(b.filePath));
}
@@ -274,7 +325,7 @@ export function readSingleTranscript(
): DiscoveredTranscript | null {
const minChars = opts.minChars ?? 2000;
const bypass = opts.bypassGuard === true;
- const excludeRes = compileExcludePatterns(opts.excludePatterns);
+ const excludes = compileLabeledExcludePatterns(opts.excludePatterns);
let content: string;
try {
content = readFileSync(filePath, 'utf8');
@@ -289,7 +340,13 @@ export function readSingleTranscript(
process.stderr.write(`[dream] readSingleTranscript skipped ${baseName}: dream_generated marker (self-consumption guard)\n`);
return null;
}
- if (matchesAnyExclude(content, excludeRes)) return null;
+ const excludeHits = matchingExcludeLabels(content, excludes);
+ if (excludeHits.length > 0) {
+ const tally = new ExcludeTally();
+ tally.record(excludeHits);
+ tally.report();
+ return null;
+ }
const ext = filePath.endsWith('.md') ? '.md' : '.txt';
const baseName = basename(filePath, ext);
const dateMatch = DATE_RE.exec(baseName);
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 5518f5f5ed..5267800934 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -138,6 +138,59 @@ export interface EmbedStaleResult {
aborted: boolean;
}
+/** Per-drain stamp context: the signature plus the registry-active column
+ * it is judged against. Resolved ONCE per drain by `resolveProvenanceStamp`
+ * — resolving inside the stamp helper cost a config round-trip per stamped
+ * page per batch, from both keyset drains. */
+export interface ProvenanceStamp { signature: string; column: string }
+
+/** Undefined when no signature is known (gateway unconfigured): nothing to stamp. */
+export async function resolveProvenanceStamp(
+ engine: BrainEngine,
+ signature: string | undefined,
+): Promise<ProvenanceStamp | undefined> {
+ if (!signature) return undefined;
+ const column = (await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name;
+ return { signature, column };
+}
+
+/**
+ * Stamp `pages.embedding_signature` once EVERY chunk on the page carries an
+ * active-column vector written by the signature's model against the CURRENT
+ * chunk_text (`embedded_text_hash = md5(chunk_text)`). Judged from DB state,
+ * not from the caller's batch: `listStaleChunks` pages by ROW with no page
+ * alignment, so a page straddling a batch boundary is never wholly in one
+ * batch — the batch that lands its last chunk stamps it here. A partially
+ * stale page whose preserved chunks carry another model (or a NULL model or
+ * hash) stays unstamped. Both keyset drains (`embed --stale` and the minion
+ * `embed-backfill` handler via `embedStaleForSource`) route through this.
+ * Returns whether the stamp landed.
+ */
+export async function stampIfPageProvenanceComplete(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+ { signature, column }: ProvenanceStamp,
+): Promise<boolean> {
+ // Signature is `<provider:model>:<dims>`; the model part is what
+ // upsertChunks records in content_chunks.model.
+ const model = signature.slice(0, signature.lastIndexOf(':'));
+ const colId = quoteIdentifier(column);
+ const rows = await engine.executeRaw<{ complete: boolean }>(
+ `SELECT count(*) > 0
+ AND bool_and(COALESCE(
+ cc.${colId} IS NOT NULL
+ AND cc.model = $1
+ AND cc.embedded_text_hash = md5(cc.chunk_text), false)) AS complete
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE p.slug = $2 AND p.source_id = $3`,
+ [model, slug, sourceId],
+ );
+ if (rows[0]?.complete !== true) return false;
+ await engine.setPageEmbeddingSignature(slug, { sourceId, signature });
+ return true;
+}
+
/** Probe input for `probeEmbedder`. Exported so tests can detect probe calls. */
export const EMBED_PROBE_TEXT = 'gbrain embedder preflight probe';
@@ -304,6 +357,7 @@ export async function embedStaleForSource(
aborted: false,
};
const signature = opts.embeddingSignature;
+ const stamp = await resolveProvenanceStamp(engine, signature); // column resolved once per drain, not per page
// v0.41.31: invalidate embeddings stamped under a prior model signature so
// the NULL cursor below re-embeds them. GRANDFATHER: NULL signature
@@ -431,13 +485,13 @@ export async function embedStaleForSource(
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
}));
await observed(pacer, () => engine.upsertChunks(slug, merged, { sourceId: keySourceId }));
- // v0.41.31: stamp provenance only when EVERY chunk was stale (fully
- // re-embedded this pass) — a partially-stale page keeps preserved
- // chunks of unknown provenance, so don't claim current. After the
- // invalidate pass above, signature-drifted pages ARE fully stale.
- if (signature && stale.length === existing.length) {
+ // Stamp provenance from DB state, not this batch (#4825): the keyset
+ // drain has no page alignment, so a page straddling a batch boundary
+ // is never wholly in one batch — the batch that lands its last chunk
+ // stamps it. Preserved chunks of other provenance keep it unstamped.
+ if (stamp) {
await observed(pacer, () =>
- engine.setPageEmbeddingSignature(slug, { sourceId: keySourceId, signature }),
+ stampIfPageProvenanceComplete(engine, slug, keySourceId, stamp),
);
}
// #3507: a FULLY re-embedded per_chunk_synopsis page landed at the
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 85f4a0639c..798a3c972d 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -50,6 +50,7 @@ import {
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { hnswIndexExpected } from './vector-index.ts';
import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
+import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
// ============================================================================
// Env-override safety gate (moved from retrieval-upgrade-planner.ts — this
@@ -777,7 +778,9 @@ export interface MigrationStatusReport {
missing_embeddings: number | null;
chunkless_pages: number | null;
signature_census: Array<{ signature: string | null; pages: number }>;
- /** facts rows whose text-space vector is NULL (regenerate on next extract/write). */
+ /** facts rows whose text-space vector is NULL (regenerate on next extract/write),
+ * excluding the audit checkpoint rows extract-conversation-facts writes into
+ * `facts` — those are never embedded and never recalled (#4875). */
facts_pending: number | null;
synopsis_tier_pages: number | null;
/** Stale count vs the live marker's target (else null — no target known);
@@ -847,7 +850,10 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
let factsPending: number | null = null;
try {
const rows = await engine.executeRaw<{ n: number }>(
- `SELECT count(*)::int AS n FROM facts WHERE embedding IS NULL AND expired_at IS NULL`,
+ `SELECT count(*)::int AS n FROM facts
+ WHERE embedding IS NULL AND expired_at IS NULL
+ AND NOT (source = ANY($1::text[]))`,
+ [[...AUDIT_ROW_SOURCES]],
);
factsPending = Number(rows[0]?.n ?? 0);
} catch { /* facts table absent — report null */ }
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index 241c438e73..6e71e8d47f 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -44,10 +44,15 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
'voyage:voyage-finance-2': { pricePerMTok: 0.12 },
'voyage:voyage-law-2': { pricePerMTok: 0.12 },
'voyage:voyage-multimodal-3': { pricePerMTok: 0.12 },
- // Voyage rerankers (same pricing page, verified 2026-08-21). Same
- // budget-tracker rerank-kind fallback rationale as the zerank-2 row below.
+ // Voyage rerankers (same pricing page; 2.5 pair verified 2026-08-21, the
+ // rerank-3 preview pair 2026-09-06). Same budget-tracker rerank-kind
+ // fallback rationale as the zerank-2 row below. Rows carry the list rate:
+ // Voyage's free-token grants are per-account and not modeled here, so
+ // over-reporting inside a grant beats under-reporting past it.
'voyage:rerank-2.5': { pricePerMTok: 0.05 },
'voyage:rerank-2.5-lite': { pricePerMTok: 0.02 },
+ 'voyage:rerank-3': { pricePerMTok: 0.05 },
+ 'voyage:rerank-3-lite': { pricePerMTok: 0.02 },
// voyage-4-nano is deliberately absent: it's the open-weight variant (see
// src/core/ai/recipes/voyage.ts) and Voyage's pricing page lists no hosted
// rate for it. A 0 entry would under-estimate anyone paying for it via the
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 82e4305a4a..b6969097bb 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1757,7 +1757,7 @@ export interface BrainEngine {
/** Meta-ontology: which dimensions exist across the brain, and how widely. */
discoverOntologyDimensions(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<OntologyDimensionStat[]>;
/** Dimensions with ≥2 distinct current-open values from ≥2 provenances. */
- findOntologyConflicts(opts?: { sourceId?: string; sourceIds?: string[]; minConfidence?: number }): Promise<OntologyConflict[]>;
+ findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]>;
// Raw data
/**
@@ -2147,11 +2147,18 @@ export interface BrainEngine {
opts?: FactListOpts,
): Promise<FactRow[]>;
- /** List facts created since a given timestamp within a source. */
+ /**
+ * List facts since a given timestamp within a source (creation time by
+ * default; event time with `eventTime: true`, see FactListOpts). The
+ * optional `entitySlug` / `sessionId` filters AND onto the time window in
+ * the same SQL query, before LIMIT, so a caller composing "this entity (or
+ * session) since T" gets the newest matching rows rather than a
+ * post-filtered slice of the newest-N.
+ */
listFactsSince(
source_id: string,
since: Date,
- opts?: FactListOpts & { entitySlug?: string },
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]>;
/** List facts captured under a session id within a source. */
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 2e219e8894..7b250c563b 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -23,6 +23,7 @@
import type { BrainEngine } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
+import { foldNonDecomposingLatin } from '../latin-fold.ts';
import { isUndefinedTableError } from '../utils.ts';
/**
@@ -448,19 +449,27 @@ async function tryFuzzyMatch(
}
/**
- * Deterministic slugify: lowercase, replace non-alphanumerics with hyphens,
- * collapse repeated hyphens, trim leading/trailing hyphens.
+ * Deterministic slugify: lowercase, fold accents and stroke letters to their
+ * base letter, replace non-alphanumerics with hyphens, collapse repeated
+ * hyphens, trim leading/trailing hyphens.
*
* Exported for tests + callers who want the same fallback shape independently.
*/
export function slugify(raw: string): string {
- return raw
- .toLowerCase()
- .normalize('NFKD')
- // NFKD decomposes accents into combining marks (U+0300..U+036F);
- // strip them before replacing the rest with hyphens so "è" → "e",
- // not "e" + "-".
- .replace(/[̀-ͯ]/g, '')
+ // Stroke letters carry no decomposition, so the mark strip cannot fold them
+ // and the sweep below would DELETE them: "Đăng Example" slugged to
+ // "ang-example". Fold after the strip so composed forms reduce in one pass
+ // ("ǿ" → "ø" → "o").
+ const folded = foldNonDecomposingLatin(
+ raw
+ .toLowerCase()
+ .normalize('NFKD')
+ // NFKD decomposes accents into combining marks (U+0300..U+036F);
+ // strip them before replacing the rest with hyphens so "è" → "e",
+ // not "e" + "-".
+ .replace(/[̀-ͯ]/g, ''),
+ );
+ return folded
.replace(/[^a-z0-9]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '');
diff --git a/src/core/eval/drift-watch.ts b/src/core/eval/drift-watch.ts
index 949d783352..ea79be6de8 100644
--- a/src/core/eval/drift-watch.ts
+++ b/src/core/eval/drift-watch.ts
@@ -13,6 +13,8 @@
import { execSync } from 'child_process';
import { existsSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
/**
* Glob-ish patterns watched for retrieval drift. Each pattern is matched
@@ -49,16 +51,42 @@ export function matchesWatchPattern(path: string, patterns: ReadonlyArray<string
return false;
}
+/** Files that mark a gbrain source checkout (vs an installed package or compiled binary). */
+const CHECKOUT_MARKERS = ['src/cli.ts', 'skills/RESOLVER.md', '.git'] as const;
+
+/**
+ * Locate the gbrain SOURCE CHECKOUT this module was loaded from, or null
+ * when gbrain is running as an installed package (no `.git`) or a compiled
+ * binary (virtual `/$bunfs/` URL). The drift check only means something
+ * against a checkout: an installed CLI has no git diff to inspect.
+ */
+export function resolveGbrainSourceRoot(moduleUrl: string = import.meta.url): string | null {
+ try {
+ let dir = dirname(fileURLToPath(moduleUrl));
+ for (let i = 0; i < 10; i++) {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- dir walks up from this module's own file URL (import.meta.url), never from user input; the markers are literals
+ if (CHECKOUT_MARKERS.every((marker) => existsSync(join(dir, marker)))) return dir;
+ const parent = dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ } catch {
+ // Non-file: module URL (bundler / compiled binary) — not a checkout.
+ }
+ return null;
+}
+
/**
* Return repo-relative paths that have changed in the working tree since
- * the given commit (or HEAD if no commit). Best-effort: returns [] when
- * git is unavailable, the repo lacks the commit, or any other failure.
+ * the given commit (or HEAD if no commit). Returns `null` when the probe
+ * itself failed (repo root missing, git unavailable, not a work tree,
+ * timeout) so callers never mistake "could not check" for "clean".
*
* `commitSha` is a full or short SHA. When omitted, compares HEAD against
* working tree (uncommitted changes only).
*/
-export function filesDriftedSince(repoRoot: string, commitSha?: string): string[] {
- if (!existsSync(repoRoot)) return [];
+export function filesDriftedSince(repoRoot: string, commitSha?: string): string[] | null {
+ if (!existsSync(repoRoot)) return null;
try {
const range = commitSha ? `${commitSha}..HEAD` : 'HEAD';
const args = commitSha
@@ -75,7 +103,7 @@ export function filesDriftedSince(repoRoot: string, commitSha?: string): string[
.map(s => s.trim())
.filter((s): s is string => s.length > 0);
} catch {
- return [];
+ return null;
}
}
@@ -87,6 +115,7 @@ export function watchedFilesDrifted(
repoRoot: string,
commitSha?: string,
patterns: ReadonlyArray<string> = RETRIEVAL_WATCH_PATTERNS,
-): string[] {
- return filesDriftedSince(repoRoot, commitSha).filter((p) => matchesWatchPattern(p, patterns));
+): string[] | null {
+ const files = filesDriftedSince(repoRoot, commitSha);
+ return files === null ? null : files.filter((p) => matchesWatchPattern(p, patterns));
}
diff --git a/src/core/extract-ner.ts b/src/core/extract-ner.ts
index 1b5f6ef555..9a9ad0e7a4 100644
--- a/src/core/extract-ner.ts
+++ b/src/core/extract-ner.ts
@@ -18,6 +18,7 @@
import type { BrainEngine } from './engine.ts';
import type { LinkBatchInput } from './engine.ts';
import { buildGazetteer, findMentionedEntities, type Gazetteer } from './by-mention.ts';
+import { isCrossSourceLinksEnabled } from './link-extraction.ts';
import { inferLinkTypeFromPack } from './schema-pack/link-inference.ts';
import { loadActivePackForLocalEngine, packSupportsNerInference } from './schema-pack/best-effort.ts';
@@ -123,6 +124,7 @@ export async function extractNerLinks(
if (gazetteer.size === 0) {
return { pages: 0, created: 0, pack_unavailable: false };
}
+ const allowCrossSource = await isCrossSourceLinksEnabled(engine);
// Pre-fetch target entity types so inferLinkType has the type signal
// without an N+1 getPage round-trip. Pulls the slug→type map from
@@ -170,6 +172,7 @@ export async function extractNerLinks(
const mentions = findMentionedEntities(body, gazetteer, {
fromSlug: slug,
fromSourceId: source_id,
+ allowCrossSource,
});
if (mentions.length === 0) continue;
diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.ts
index 9d28f154d2..c7a3d4cfcc 100644
--- a/src/core/extract-timeline-from-meetings.ts
+++ b/src/core/extract-timeline-from-meetings.ts
@@ -12,6 +12,10 @@
import type { BrainEngine } from './engine.ts';
import type { TimelineBatchInput } from './engine.ts';
import { buildGazetteer, findMentionedEntities, type Gazetteer } from './by-mention.ts';
+import { isCrossSourceLinksEnabled } from './link-extraction.ts';
+import { computeEffectiveDate } from './effective-date.ts';
+import { parseFrontmatter } from './backfill-effective-date.ts';
+import { isPrivatePage } from './search/private-visibility.ts';
export interface ExtractTimelineFromMeetingsOpts {
dryRun?: boolean;
@@ -44,6 +48,9 @@ interface MeetingRow {
source_id: string;
title: string;
effective_date: string | null;
+ frontmatter: unknown;
+ import_filename: string | null;
+ created_at: string | Date;
updated_at: string | Date;
compiled_truth: string;
timeline: string;
@@ -75,8 +82,8 @@ export async function extractTimelineFromMeetings(
const sourceFilter = opts.sourceIdFilter ? `AND source_id = $1` : '';
const meetingParams = opts.sourceIdFilter ? [opts.sourceIdFilter] : [];
const meetings = await engine.executeRaw<MeetingRow>(
- `SELECT slug, source_id, title, effective_date, updated_at,
- compiled_truth, COALESCE(timeline, '') AS timeline
+ `SELECT slug, source_id, title, effective_date, frontmatter, import_filename,
+ created_at, updated_at, compiled_truth, COALESCE(timeline, '') AS timeline
FROM pages
WHERE ${MEETING_PAGE_PREDICATE}
AND deleted_at IS NULL
@@ -89,9 +96,9 @@ export async function extractTimelineFromMeetings(
return { meetings_scanned: 0, entries_created: 0, entities_touched: 0, batch_errors: 0 };
}
- // 2. Fetch all 'attended' edges (one round-trip, scoped to the loaded
- // meeting source_ids). Build a Map<meetingSlug → attendees[]> for O(1)
- // attendee lookup per meeting.
+ // 2. Fetch all 'attended' edges (one brain-wide round-trip — the SQL is NOT
+ // source-scoped; rows are filtered in JS to the loaded meetings below).
+ // Build a Map<meetingKey → attendees[]> for O(1) attendee lookup per meeting.
const meetingKeys = new Set(meetings.map((m) => `${m.source_id}::${m.slug}`));
const attendedEdges = await engine.executeRaw<AttendedEdgeRow>(
`SELECT pf.slug AS from_slug, pf.source_id AS from_source_id,
@@ -116,11 +123,15 @@ export async function extractTimelineFromMeetings(
// 3. For each meeting, derive entity mentions (gazetteer-based) + merge
// with attendee edges. Each (meeting, entity) produces ONE timeline row.
const gazetteer = opts.gazetteer ?? await buildGazetteer(engine);
+ const allowCrossSource = await isCrossSourceLinksEnabled(engine);
const batch: TimelineBatchInput[] = [];
let entriesCreated = 0;
const entitiesTouched = new Set<string>();
let meetingsScanned = 0;
+ let dateFallbacks = 0;
+ let undated = 0;
+ let privateSkipped = 0;
let batchErrors = 0;
let firstBatchError: string | undefined;
@@ -150,7 +161,32 @@ export async function extractTimelineFromMeetings(
const updatedMs = new Date(meeting.updated_at).getTime();
if (Number.isFinite(updatedMs) && updatedMs <= sinceMs) continue;
}
- if (!meeting.effective_date) continue; // can't write a timeline entry without a date
+ const frontmatter = parseFrontmatter(meeting.frontmatter);
+ // A private meeting must not fan its title/slug/date out onto other pages'
+ // timelines: the row carries no event_page_id (the (event_page_id, date)
+ // unique index allows one row per event, not one per attendee), so the
+ // remote private-event filter could never hide it. Fail closed: skip.
+ if (isPrivatePage(frontmatter)) { privateSkipped++; continue; }
+ // put_page-written pages never get effective_date computed (column stays
+ // NULL); derive it exactly as `gbrain backfill effective_date` would —
+ // same filename recipe (import_filename, else the slug tail) — so a later
+ // backfill + re-run dedups against this row instead of doubling it. The
+ // 'fallback' source is updated_at/created_at: an import timestamp, never
+ // the meeting's date. A row dated from it would survive dedup as a twin of
+ // the correctly dated row, so such meetings are skipped, not dated.
+ let date = meeting.effective_date;
+ if (!date) {
+ const { date: computed, source } = computeEffectiveDate({
+ slug: meeting.slug,
+ frontmatter,
+ filename: meeting.import_filename || meeting.slug.split('/').pop()!,
+ createdAt: new Date(meeting.created_at),
+ updatedAt: new Date(meeting.updated_at),
+ });
+ if (!computed || source === 'fallback') { undated++; continue; }
+ date = computed.toISOString().slice(0, 10);
+ dateFallbacks++;
+ }
meetingsScanned++;
opts.onProgress?.(meetingsScanned, meetings.length, entriesCreated);
@@ -159,10 +195,13 @@ export async function extractTimelineFromMeetings(
const summary = `Discussed in ${meeting.title}`;
const sourceKey = `extract-timeline-from-meetings:${meeting.slug}`;
- // Attendees (from 'attended' links).
+ // Attendees (from 'attended' links). An edge into ANOTHER source fans out
+ // only under `link_resolution.cross_source` — the same gate the mention
+ // lane below applies (the edge fetch above is brain-wide, not scoped).
const attendees = attendeesByMeeting.get(meetingKey) ?? [];
const targets = new Map<string, { slug: string; source_id: string }>();
for (const e of attendees) {
+ if (!allowCrossSource && e.to_source_id !== meeting.source_id) continue;
targets.set(`${e.to_source_id}::${e.to_slug}`, {
slug: e.to_slug,
source_id: e.to_source_id,
@@ -170,14 +209,15 @@ export async function extractTimelineFromMeetings(
}
// Body mentions (gazetteer-based). Skip self-mention (meeting page
- // referencing itself by title). The cross-source guard in
- // findMentionedEntities already drops mentions targeting a different
- // source than the gazetteer entry was built from.
+ // referencing itself by title). Mentions of entities in ANOTHER source
+ // are dropped by findMentionedEntities unless the operator opted in via
+ // `link_resolution.cross_source` (same switch as wikilink resolution).
const body = meeting.compiled_truth + '\n\n' + meeting.timeline;
if (body.trim()) {
const mentions = findMentionedEntities(body, gazetteer, {
fromSlug: meeting.slug,
fromSourceId: meeting.source_id,
+ allowCrossSource,
});
for (const m of mentions) {
targets.set(`${m.source_id}::${m.slug}`, {
@@ -192,7 +232,7 @@ export async function extractTimelineFromMeetings(
batch.push({
slug: t.slug,
source_id: t.source_id,
- date: meeting.effective_date,
+ date,
source: sourceKey,
summary,
});
@@ -202,6 +242,23 @@ export async function extractTimelineFromMeetings(
}
await flush();
+ if (dateFallbacks > 0) {
+ console.error(
+ `[extract timeline] ${dateFallbacks} meeting(s) have no effective_date column value; dated from their frontmatter date or filename instead. ` +
+ `Run \`gbrain backfill effective_date\` to persist it.`,
+ );
+ }
+ if (undated > 0) {
+ console.error(
+ `[extract timeline] ${undated} meeting(s) skipped: no date in frontmatter or filename (import timestamps are never used as the meeting date). ` +
+ `Add a \`date:\` field or a YYYY-MM-DD filename prefix.`,
+ );
+ }
+ if (privateSkipped > 0) {
+ console.error(
+ `[extract timeline] ${privateSkipped} visibility: private meeting(s) skipped: a timeline row on another page cannot be hidden from remote readers.`,
+ );
+ }
return {
meetings_scanned: meetingsScanned,
entries_created: entriesCreated,
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 77e5fc77f4..c4765953eb 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -505,50 +505,64 @@ export function upsertFactRow(
},
];
- const newFence = renderFactsTable(allRows);
+ return { body: replaceOrInsertFactsFence(body, renderFactsTable(allRows)), rowNum: nextRowNum };
+}
+/**
+ * The ONE fence-placement rule, shared by every writer that materializes a
+ * fence into a page body (upsertFactRow, the phantom-redirect canonical
+ * append, the importer's hidden-row merge). Replaces an existing fence in
+ * place; otherwise inserts a fresh `## Facts` section carrying `fenceBlock`.
+ *
+ * #4756: the FIRST fence must land in compiled_truth — ABOVE the timeline
+ * sentinel. splitBody() files everything below the sentinel into
+ * page.timeline, where extract_facts refuses to reconcile it
+ * (FACTS_FENCE_BELOW_SENTINEL) — a blind EOF append on any page that already
+ * had a timeline froze the fence permanently. No sentinel → EOF append.
+ */
+export function replaceOrInsertFactsFence(body: string, fenceBlock: string): string {
const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
- let out: string;
if (beginIdx !== -1 && endIdx !== -1) {
- out = body.slice(0, beginIdx) + newFence + body.slice(endIdx + FACTS_FENCE_END.length);
- } else {
- // #4756: the FIRST fence must land in compiled_truth — ABOVE the timeline
- // sentinel. splitBody() files everything below the sentinel into
- // page.timeline, where extract_facts refuses to reconcile it
- // (FACTS_FENCE_BELOW_SENTINEL) — a blind EOF append on any page that
- // already had a timeline froze the fence permanently.
- const section = `## Facts\n\n${newFence}\n`;
- const sentinelAt = timelineSentinelOffset(body);
- if (sentinelAt !== -1) {
- const head = body.slice(0, sentinelAt);
- const sep = head === '' ? '' : head.endsWith('\n\n') ? '' : head.endsWith('\n') ? '\n' : '\n\n';
- out = `${head}${sep}${section}\n${body.slice(sentinelAt)}`;
- } else {
- const sep = body.endsWith('\n') ? '\n' : '\n\n';
- out = `${body}${sep}${section}`;
- }
+ return body.slice(0, beginIdx) + fenceBlock + body.slice(endIdx + FACTS_FENCE_END.length);
}
- return { body: out, rowNum: nextRowNum };
+ const section = `## Facts\n\n${fenceBlock}\n`;
+ const sentinelAt = timelineSentinelOffset(body);
+ if (sentinelAt !== -1) {
+ const head = body.slice(0, sentinelAt);
+ const sep = head === '' ? '' : head.endsWith('\n\n') ? '' : head.endsWith('\n') ? '\n' : '\n\n';
+ return `${head}${sep}${section}\n${body.slice(sentinelAt)}`;
+ }
+ const sep = body.endsWith('\n') ? '\n' : '\n\n';
+ return `${body}${sep}${section}`;
}
/**
* Char offset of the line start of the first timeline sentinel in `body`,
- * or -1 when none is present. Mirrors the UNAMBIGUOUS sentinel forms of
- * `markdown.ts:findTimelineSplitIndex` (`<!-- timeline -->` /
- * `<!--timeline-->` — what serializeMarkdown emits — plus the decorated
- * `--- timeline ---`). The legacy bare `---` + `## Timeline` fallback is
- * deliberately NOT matched: upsertFactRow receives raw on-disk text that may
- * still carry YAML frontmatter, whose `---` delimiters would false-positive
- * that rule (findTimelineSplitIndex documents the same caveat — it expects
- * body lines). Local rather than imported because this module must stay free
- * of markdown.ts's transitive dependency graph (see the FactKind comment at
- * the top of the file).
+ * or -1 when none is present. Mirrors every sentinel form
+ * `markdown.ts:findTimelineSplitIndex` honours (#4756): `<!-- timeline -->` /
+ * `<!--timeline-->` (what serializeMarkdown emits), the decorated
+ * `--- timeline ---`, and the legacy bare `---` whose next non-empty line is
+ * `## Timeline` / `## History` — the shape the recommended page templates
+ * emit. upsertFactRow receives RAW on-disk text, so a leading YAML
+ * frontmatter block is skipped first (same skip as
+ * timeline-write-through.ts) and its `---` delimiters can't false-positive
+ * the bare-`---` rule. Local rather than imported because this module must
+ * stay free of markdown.ts's transitive dependency graph (see the FactKind
+ * comment at the top of the file).
*/
function timelineSentinelOffset(body: string): number {
+ const lines = body.split('\n');
+ let start = 0;
+ if (lines[0]?.trim() === '---') {
+ for (let i = 1; i < lines.length; i++) {
+ if (lines[i].trim() === '---') { start = i + 1; break; }
+ }
+ }
let offset = 0;
- for (const line of body.split('\n')) {
- const trimmed = line.trim();
+ for (let i = 0; i < start; i++) offset += lines[i].length + 1;
+ for (let i = start; i < lines.length; i++) {
+ const trimmed = lines[i].trim();
if (
trimmed === '<!-- timeline -->' ||
trimmed === '<!--timeline-->' ||
@@ -556,7 +570,15 @@ function timelineSentinelOffset(body: string): number {
) {
return offset;
}
- offset += line.length + 1;
+ if (trimmed === '---' && lines.slice(start, i).join('\n').trim().length > 0) {
+ for (let j = i + 1; j < lines.length; j++) {
+ const next = lines[j].trim();
+ if (next.length === 0) continue;
+ if (/^##\s+(timeline|history)\s*$/i.test(next)) return offset;
+ break;
+ }
+ }
+ offset += lines[i].length + 1;
}
return -1;
}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 90187da584..25a773f49d 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -42,6 +42,19 @@ import type { ResolutionSource } from '../entities/resolve.ts';
import { isFactsBackstopEligible } from './eligibility.ts';
import type { PageType } from '../types.ts';
+/**
+ * Notability-filter vocabulary shared by the durable facts-absorb payload
+ * writer (queue mode below) and its only reader, the minion handler in
+ * commands/jobs.ts. #4870: the reader must accept every value the writer can
+ * send; `coerceNotabilityFilter` is the validated pass-through (unknown or
+ * absent → 'all', the documented default).
+ */
+export const NOTABILITY_FILTERS = ['all', 'high-only', 'medium-and-up'] as const;
+export type FactNotabilityFilter = typeof NOTABILITY_FILTERS[number];
+export function coerceNotabilityFilter(v: unknown): FactNotabilityFilter {
+ return (NOTABILITY_FILTERS as readonly unknown[]).includes(v) ? (v as FactNotabilityFilter) : 'all';
+}
+
export interface FactsBackstopCtx {
engine: BrainEngine;
/** Brain source identifier; default 'default'. */
@@ -63,7 +76,7 @@ export interface FactsBackstopCtx {
mode?: 'queue' | 'inline';
/** Notability filter — D4. Default 'all'; sync uses 'high-only'; the
* ambient-writeback lane uses 'medium-and-up' in salient mode. */
- notabilityFilter?: 'all' | 'high-only' | 'medium-and-up';
+ notabilityFilter?: FactNotabilityFilter;
/** Abort signal for shutdown propagation. */
abortSignal?: AbortSignal;
/** Mirrors OperationContext.remote for trust-aware logging paths. */
@@ -333,7 +346,6 @@ export async function runFactsBackstop(
// re-runnable), never a silent consume.
max_attempts: 5,
backoff_delay: 60_000,
- timeout_ms: 180_000,
},
);
return { mode: 'queue', enqueued: true, queueDepth: 0 };
@@ -463,6 +475,9 @@ async function runPipeline(
turnText: parsedPage.compiled_truth,
isDreamGenerated: false, // eligibility check already rejected dream pages
ref: parsedPage.slug,
+ // #4819: page provenance for DB-only rows. The turn-path entry
+ // (runFactsPipeline) has no page, so it leaves this unset.
+ pageSlug: parsedPage.slug,
},
ctx,
abortSignal,
@@ -497,7 +512,7 @@ async function runPipeline(
* fallback regardless of local_path.
*/
async function runPipelineWithBody(
- input: { turnText: string; isDreamGenerated: boolean; ref?: string },
+ input: { turnText: string; isDreamGenerated: boolean; ref?: string; pageSlug?: string },
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
@@ -520,7 +535,7 @@ async function runPipelineWithBody(
/** The actual pipeline body — always runs inside a BudgetTracker scope (#4210). */
async function runPipelineBodyInner(
- input: { turnText: string; isDreamGenerated: boolean; ref?: string },
+ input: { turnText: string; isDreamGenerated: boolean; ref?: string; pageSlug?: string },
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {
@@ -711,9 +726,11 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
- // #4206: caller event-time fallback + provenance context.
+ // #4206: caller event-time fallback + provenance context. #4819: a
+ // DB-only row has no fence to name the page it came from, so the page
+ // path's slug fills context when the caller passed no sourceSlug.
valid_from: f.valid_from ?? ctx.validFrom,
- context: ctx.sourceSlug ?? null,
+ context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
const result = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
fact_ids.push(result.id);
@@ -798,7 +815,7 @@ async function runPipelineBodyInner(
embedding: f.embedding ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
- context: ctx.sourceSlug ?? null,
+ context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback for unprefixed or fallback-resolved entity slugs (no fenceable page or usable tree)
fact_ids.push(legacyResult.id);
@@ -830,7 +847,7 @@ async function runPipelineBodyInner(
embedding: f.embedding ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
- context: ctx.sourceSlug ?? null,
+ context: ctx.sourceSlug ?? input.pageSlug ?? null,
};
const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
fact_ids.push(legacyResult.id);
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index f9ca8888af..ccf13c3705 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -22,6 +22,7 @@
*/
import { chat, embedOne, isAvailable } from '../ai/gateway.ts';
+import { classifyGlobalLlmError } from '../ai/errors.ts';
import { stripReasoningBlocks } from '../llm-json.ts';
import type { ChatResult } from '../ai/gateway.ts';
import { INJECTION_PATTERNS } from '../think/sanitize.ts';
@@ -29,6 +30,7 @@ import { resolveModel } from '../model-config.ts';
import { normalizeModelId } from '../model-id.ts';
import type { BrainEngine, NewFact, FactKind } from '../engine.ts';
import { normalizeMetricLabel } from './extract-from-fence.ts';
+import { isNullLikeEntity } from './write-single.ts';
/**
* v0.31 (D15): kill-switch for fact extraction.
@@ -347,6 +349,31 @@ export type ExtractFactsOutcome =
error?: unknown;
};
+/**
+ * Bounded diagnostic breadcrumb for the message: the cause's CONSTRUCTOR name
+ * (validated as a plain identifier — never `.name`, never `.message`) plus
+ * the whole-run class `classifyGlobalLlmError` derives from the cause chain
+ * (`auth` / `billing` / `rate_limit`, the same vocabulary ingest_log uses).
+ * Both are closed vocabularies with no interpolated provider text, so a 4xx
+ * body echoing a key / org id cannot ride through. Defense-in-depth, not a
+ * hard boundary: anything unexpected is dropped (never substituted), and a
+ * throwing getter can never mask the real FactsExtractionError.
+ */
+function safeCauseLabel(cause: unknown): string | undefined {
+ try {
+ let ctorName: string | undefined;
+ if (cause instanceof Error) {
+ const ctor: unknown = cause.constructor;
+ const name: unknown = typeof ctor === 'function' ? ctor.name : undefined;
+ if (typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name)) ctorName = name;
+ }
+ const label = [ctorName, classifyGlobalLlmError(cause)].filter(Boolean).join(' ');
+ return label || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Typed carrier for extraction failures that must PROPAGATE (throw) rather
* than collapse to zero counts — `truncated_output` has no underlying error
@@ -361,12 +388,16 @@ export class FactsExtractionError extends Error {
readonly reason: ExtractFailureReason;
readonly model?: string;
constructor(reason: ExtractFailureReason, model?: string, cause?: unknown) {
- // The MESSAGE deliberately carries only reason + model — never
- // `cause.message`. This error's message flows to remote MCP callers
- // (dispatch returns e.message) and into persisted logs (ingest_log,
- // mcp_request_log), and provider 4xx bodies echo partially-redacted API
- // keys / org ids. The full cause stays attached for local debugging.
- super(`[facts-extract] ${reason}${model ? ` (model=${model})` : ''}`);
+ // The MESSAGE carries only reason + model + a bounded cause breadcrumb
+ // (see `safeCauseLabel`) — never `cause.message`. It flows to remote MCP
+ // callers (dispatch returns e.message) and into persisted logs
+ // (ingest_log, mcp_request_log, minion_jobs.error_text), and provider 4xx
+ // bodies echo partially-redacted API keys / org ids. The breadcrumb is
+ // what lets a dead durable job's error_text — all that survives once the
+ // in-process `cause` is gone — tell an auth failure from a transient one.
+ // The full cause stays attached for local debugging.
+ const causeLabel = safeCauseLabel(cause);
+ super(`[facts-extract] ${reason}${model ? ` (model=${model})` : ''}${causeLabel ? ` (cause=${causeLabel})` : ''}`);
this.name = 'FactsExtractionError';
this.reason = reason;
this.model = model;
@@ -593,7 +624,13 @@ export async function extractFactsFromTurnWithOutcome(
// as the entity (self-attribution of a first-person claim from a speaker
// we cannot identify), drop the attribution but KEEP the fact. Third-person
// entities (e.g. "acme") never match this predicate and pass through.
- entity_slug: isUnknownSpeakerLabel(candidate.entity) ? null : (candidate.entity ?? null),
+ // #4755: same for a null-like placeholder STRING ("null", "None", "n/a")
+ // where the prompt asked for JSON null — otherwise the resolver's
+ // fallback adopts the token as the slug and the facts land unreachable
+ // under entity_slug='null'. Same token set the `remember` verb applies.
+ entity_slug: isUnknownSpeakerLabel(candidate.entity) || isNullLikeEntity(candidate.entity)
+ ? null
+ : (candidate.entity ?? null),
source: input.source,
source_session: input.sessionId ?? null,
confidence,
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 0d085dc645..e05306c05c 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -40,13 +40,15 @@ import { dirname, isAbsolute, relative } from 'node:path';
import type { BrainEngine, NewFact, FactVisibility, FactKind } from '../engine.ts';
import type { ResolutionSource } from '../entities/resolve.ts';
-import { inferTypeFromPack } from '../markdown.ts';
+import { inferTypeFromPack, parseMarkdown } from '../markdown.ts';
+import { sanitizeText } from '../batch-rows.ts';
import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts';
import { withPageLock } from '../page-lock.ts';
import { gbrainPath } from '../config.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { isDurabilityHardened, commitWriteThroughFile } from '../brain-repo-durability.ts';
import { upsertFactRow, parseFactsFence } from '../facts-fence.ts';
+import { contentHash } from '../utils.ts';
import { extractFactsFromFenceText } from './extract-from-fence.ts';
import { logStubGuardEvent } from './stub-guard-audit.ts';
@@ -464,6 +466,28 @@ export async function writeFactsToFence(
// either the old content or the new content, never partial.
renameSync(tmpPath, filePath);
+ // #4872: mirror the rewritten file into pages.compiled_truth. get_page
+ // and the extract_facts reconcile read the DB body, not the file — left
+ // stale, a plain get→put round-trip flattens the new row off disk and
+ // the next reconcile deletes it from the facts table. Same recipe as
+ // forget.ts (#4696): parse + sanitize the FILE bytes as import-file.ts
+ // does. Body-only: content_chunks are untouched, so the row KEEPS its
+ // old content_hash and the next sync re-imports + re-chunks. Stamping
+ // the importer's hash here made sync skip the page and left search
+ // blind to the new row forever. Never persist an EMPTY hash: a row
+ // that had none gets a row-shaped hash of its pre-mirror content,
+ // which the rewritten file can't match. Best-effort: the file is
+ // already committed; a stub page with no DB row is created by sync.
+ try {
+ const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);
+ const existing = await engine.getPage(target.slug, { sourceId: target.sourceId });
+ if (existing) {
+ await engine.refreshPageBody(target.slug, target.sourceId,
+ sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
+ existing.content_hash || contentHash(existing));
+ }
+ } catch { /* degrades to the pre-#4872 window (stale until the next sync) */ }
+
// 6. Stamp the DB. extractFactsFromFenceText handles the
// validFrom/validUntil date derivation + the strikethrough
// semantic distinction. We only want to insert the NEW rows
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index a019769d0c..3094173086 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -30,6 +30,12 @@
* mode. These forgets DO NOT survive rebuild — the architecture
* doc names this as the explicit DB-only exception for legacy
* / thin-client state.
+ *
+ * Both tiers ALSO strike the row in `pages.compiled_truth` (#4696): the
+ * extract_facts reconcile reads the DB body, not the file, and treats a
+ * live DB fence row with an expired facts row as drift to heal by
+ * re-inserting the claim active. Without the DB-body strike the routine
+ * dream cycle undid every forget that landed before the next sync.
*/
import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
@@ -38,6 +44,9 @@ import type { BrainEngine } from '../engine.ts';
import { withPageLock } from '../page-lock.ts';
import { resolvePageWriteTarget } from '../write-through.ts';
import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';
+import { parseMarkdown } from '../markdown.ts';
+import { sanitizeText } from '../batch-rows.ts';
+import { contentHash } from '../utils.ts';
export interface ForgetFactResult {
/** True iff the row was found AND a forget was applied (fence or DB). */
@@ -70,6 +79,35 @@ function todayUtc(): string {
.toISOString().slice(0, 10);
}
+const FENCE_BEGIN = '<!--- gbrain:facts:begin -->';
+const FENCE_END = '<!--- gbrain:facts:end -->';
+
+/**
+ * Strike fence row `rowNum` inside `body`: strikethrough on the claim
+ * (already-struck rows stay struck), valid_until = today, `forgotten:
+ * <reason>` appended to context (preserving any existing context). Returns
+ * the rewritten body, or null when the fence lacks the row (DB drifted from
+ * markdown) or its markers — callers fall back to a DB-only expire.
+ */
+function strikeFenceRow(body: string, rowNum: number, reason: string, today: string): string | null {
+ const parsed = parseFactsFence(body);
+ const target = parsed.facts.find(f => f.rowNum === rowNum);
+ if (!target) return null;
+ const existingContext = target.context?.trim() ?? '';
+ const newContext = existingContext
+ ? `${existingContext} | forgotten: ${reason}`
+ : `forgotten: ${reason}`;
+ const updated: ParsedFact[] = parsed.facts.map(f =>
+ f.rowNum === rowNum
+ ? { ...f, active: false, validUntil: today, context: newContext, forgotten: true }
+ : f,
+ );
+ const begin = body.indexOf(FENCE_BEGIN);
+ const end = body.indexOf(FENCE_END, begin + 1);
+ if (begin === -1 || end === -1) return null;
+ return body.slice(0, begin) + renderFactsTable(updated) + body.slice(end + FENCE_END.length);
+}
+
/**
* Forget a fact by id. Routes through the fence when the row carries
* v51 columns + the source has a local_path; falls through to legacy
@@ -103,6 +141,7 @@ export async function forgetFactInFence(
} = {},
): Promise<ForgetFactResult> {
const reason = opts.reason ?? 'forgotten';
+ const today = todayUtc();
const rows = await engine.executeRaw<FactDbRow>(
`SELECT id, source_id, entity_slug, row_num, source_markdown_slug, expired_at, visibility
@@ -130,17 +169,51 @@ export async function forgetFactInFence(
return { ok: false, path: 'already_expired', reason };
}
+ // #4696: a forget that cannot rewrite the file still strikes the row in
+ // the DB body, or the next extract_facts reconcile re-inserts the claim
+ // active at the same row_num (see the module header). Best-effort: the
+ // facts row is already expired, so a failure here only degrades to the
+ // pre-#4696 window. The fence file stays canonical — a later absorb of a
+ // file whose row is still live legitimately revives it.
+ const strikeDbBody = async (): Promise<void> => {
+ if (row.row_num === null || row.source_markdown_slug === null) return;
+ const slug = row.source_markdown_slug;
+ const page = await engine.getPage(slug, { sourceId: row.source_id });
+ if (!page) return;
+ const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, reason, today);
+ if (struck === null) return;
+ // The FILE was not rewritten on this tier, so the row must NOT keep the
+ // importer's hash: sync would see file == row and skip, leaving
+ // content_chunks with the live claim for good. A row-shaped hash over the
+ // struck body can never equal the unchanged file's, so the next sync
+ // re-imports + re-chunks — and, the fence being canonical, legitimately
+ // revives a row the file still carries, in body AND chunks as one state.
+ await engine.refreshPageBody(slug, row.source_id, struck, page.timeline ?? '',
+ contentHash({ ...page, compiled_truth: struck }));
+ };
+
+ // Legacy path — DB-only forget. Doesn't survive `gbrain rebuild` (the
+ // canonical fence is untouched) but does survive the reconcile (#4696).
+ // The DB-body strike is a read-modify-write on pages.compiled_truth, so it
+ // holds the same per-page lock the fence writers do (`locked` = the fence
+ // tier is calling from inside its own withPageLock).
+ const legacyExpire = async (locked = false): Promise<ForgetFactResult> => {
+ const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
+ if (ok && row.source_markdown_slug !== null) {
+ const slug = row.source_markdown_slug;
+ await (locked ? strikeDbBody() : withPageLock(slug, strikeDbBody, { timeoutMs: 5_000 }))
+ .catch(() => { /* best-effort, see above */ });
+ }
+ return { ok, path: 'legacy_db', reason };
+ };
+
// Fence path requires: v51 columns set + source.local_path set.
const canFence =
row.row_num !== null &&
row.source_markdown_slug !== null &&
row.entity_slug !== null;
- if (!canFence) {
- // Legacy path — DB-only forget. Doesn't survive `gbrain rebuild`.
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
- }
+ if (!canFence) return legacyExpire();
// Look up source.local_path.
const sources = await engine.executeRaw<SourceRow>(
@@ -148,10 +221,7 @@ export async function forgetFactInFence(
[row.source_id],
);
const localPath = sources[0]?.local_path ?? null;
- if (!localPath) {
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
- }
+ if (!localPath) return legacyExpire();
const slug = row.source_markdown_slug!;
const targetRowNum = row.row_num!;
@@ -161,10 +231,7 @@ export async function forgetFactInFence(
// human-named vault file, degrading forget to a DB-only expire while the
// fence keeps the live row for the next absorb to resurrect.
const resolved = await resolvePageWriteTarget(engine, slug, row.source_id);
- if (!resolved.ok) {
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
- }
+ if (!resolved.ok) return legacyExpire();
const filePath = resolved.filePath;
const tmpPath = `${filePath}.tmp`;
@@ -172,65 +239,25 @@ export async function forgetFactInFence(
// File deleted out from under us — only the DB has the row.
// Legacy path is the safe behavior; the operator can fix the
// tree mismatch separately.
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
+ return legacyExpire();
}
return withPageLock(slug, async () => {
const body = readFileSync(filePath, 'utf-8');
- const parsed = parseFactsFence(body);
-
- // Find the target row in the fence by row_num.
- const target = parsed.facts.find(f => f.rowNum === targetRowNum);
- if (!target) {
- // Fence is missing the row — DB drifted from markdown. Fall
- // through to legacy expire so the user's intent succeeds; doctor
- // surfaces the drift separately.
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
- }
-
- // Mutate: strike out claim (already-strikethrough rows stay
- // strikethrough), set valid_until = today, append "forgotten:
- // <reason>" to context (preserving any existing context).
- const today = todayUtc();
- const existingContext = target.context?.trim() ?? '';
- const newContext = existingContext
- ? `${existingContext} | forgotten: ${reason}`
- : `forgotten: ${reason}`;
-
- const updated: ParsedFact[] = parsed.facts.map(f =>
- f.rowNum === targetRowNum
- ? {
- ...f,
- active: false, // strikethrough on render
- validUntil: today,
- context: newContext,
- forgotten: true,
- }
- : f,
- );
-
- // Render + atomic .tmp + parse-validate + rename.
- const newFence = renderFactsTable(updated);
- const begin = body.indexOf('<!--- gbrain:facts:begin -->');
- const end = body.indexOf('<!--- gbrain:facts:end -->', begin + 1);
- if (begin === -1 || end === -1) {
- // Race / corruption: fence disappeared between parse and render.
- // Legacy fallback.
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
- }
- const newBody = body.slice(0, begin) + newFence + body.slice(end + '<!--- gbrain:facts:end -->'.length);
+ // Fence missing the row (DB drifted from markdown) or its markers (race /
+ // corruption): fall through to legacy expire so the user's intent
+ // succeeds; doctor surfaces the drift separately.
+ const newBody = strikeFenceRow(body, targetRowNum, reason, today);
+ if (newBody === null) return legacyExpire(true);
+ // Atomic .tmp + parse-validate + rename.
writeFileSync(tmpPath, newBody, 'utf-8');
const tmpBody = readFileSync(tmpPath, 'utf-8');
const validate = parseFactsFence(tmpBody);
if (validate.warnings.length > 0) {
// Quarantine .tmp; leave the canonical file alone; fall back to
// DB expire so the user's forget intent still succeeds.
- const ok = await engine.expireFact(factId); // gbrain-allow-direct-insert: legacy fallback path inside forgetFactInFence — fence rewrite not possible (pre-v51 row / missing local_path / file deleted / row_num drift)
- return { ok, path: 'legacy_db', reason };
+ return legacyExpire(true);
}
renameSync(tmpPath, filePath);
@@ -244,6 +271,27 @@ export async function forgetFactInFence(
[today, factId],
);
+ // #4696: mirror the rewritten file into the DB body, or the reconcile
+ // (which reads pages.compiled_truth) resurrects the claim before the
+ // next sync absorbs the file — and sync is commit-anchored, so that
+ // window lasts until the user commits. Parse + sanitize the FILE bytes
+ // as import-file.ts does. Body-only: content_chunks still carry the
+ // live claim, so the row KEEPS its old content_hash and the next sync
+ // re-imports + re-chunks. Stamping the importer's hash here made sync
+ // skip the page and the struck claim kept surfacing in chunk search.
+ // Never persist an EMPTY hash: a row that had none gets a row-shaped
+ // hash of its pre-mirror content, which the rewritten file can't match.
+ // Best-effort — file + facts row are already correct.
+ try {
+ const reparsed = parseMarkdown(tmpBody, `${slug}.md`);
+ const page = await engine.getPage(slug, { sourceId: row.source_id });
+ if (page) {
+ await engine.refreshPageBody(slug, row.source_id,
+ sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
+ page.content_hash || contentHash(page));
+ }
+ } catch { /* degrades to the pre-#4696 window (stale until the next sync) */ }
+
return { ok: true, path: 'fence', reason };
}, { timeoutMs: 5_000 });
}
diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.ts
index 261e074a41..2dfff4113f 100644
--- a/src/core/google/google-clients.ts
+++ b/src/core/google/google-clients.ts
@@ -4,7 +4,14 @@
* Hand-rolled (no googleapis dep, house style — see github-source.ts):
* - auth via GoogleTokenProvider (vault-backed, auto-refreshing)
* - 401 → forceRefresh() + single retry
- * - 403/429 → Retry-After honored (delta-seconds AND http-date)
+ * - 403/429 → Retry-After honored (delta-seconds AND http-date). A
+ * rate-limit-class response (403 rateLimitExceeded/userRateLimitExceeded,
+ * 403 quota, or 429) gets a MUCH more patient retry budget than other
+ * retryable failures — DEFAULT_RATE_LIMIT_RETRIES, exponential backoff
+ * with jitter capped at 60s — because Gmail's per-user rate limiting
+ * under backfill burst load is common and self-clearing; giving up after
+ * two tries used to poison threads that would have succeeded a few
+ * seconds later.
* - 403 accessNotConfigured → CredentialError 'api_not_enabled' with the
* exact enable deep link (project number extracted from the client id)
* - uniform pageToken pagination with a safety cap
@@ -34,6 +41,34 @@ const PEOPLE_BASE = 'https://people.googleapis.com/v1';
const PAGINATION_CAP = 500;
+/** Retry budget for a 401 needing a token refresh-and-retry. */
+const DEFAULT_RETRIES = 2;
+
+/**
+ * Retry budget for a rate-limit-class response (403 rateLimitExceeded /
+ * userRateLimitExceeded / quota, or 429) — deliberately much larger than
+ * DEFAULT_RETRIES. Gmail's per-user rate limiting under backfill burst load
+ * clears on its own within seconds to low minutes; two tries (~6s total)
+ * gave up before it cleared and poisoned threads that would otherwise have
+ * succeeded.
+ */
+const DEFAULT_RATE_LIMIT_RETRIES = 6;
+
+/** Backoff ceiling for a rate-limit retry with no Retry-After header. */
+const RATE_LIMIT_BACKOFF_CAP_MS = 60_000;
+
+/**
+ * Exponential backoff with EQUAL jitter (half fixed, half random), capped at
+ * RATE_LIMIT_BACKOFF_CAP_MS. Only used when Google didn't send Retry-After —
+ * jitter avoids many gbrain processes hitting the same per-user/per-project
+ * quota resynchronizing their retries in lockstep.
+ */
+export function rateLimitBackoffMs(attempt: number): number {
+ const base = Math.min(RATE_LIMIT_BACKOFF_CAP_MS, 2 ** attempt * 2_000);
+ const half = base / 2;
+ return Math.round(half + Math.random() * half);
+}
+
interface GoogleErrorBody {
error?: {
code?: number;
@@ -58,10 +93,16 @@ export class GoogleApiClient {
async fetchJSON<T>(
url: string,
apiHint: ApiHint,
- opts: { signal?: AbortSignal; retries?: number } = {},
+ opts: { signal?: AbortSignal; retries?: number; rateLimitRetries?: number } = {},
): Promise<T> {
- const retries = opts.retries ?? 2;
- for (let attempt = 0; attempt <= retries; attempt++) {
+ const retries = opts.retries ?? DEFAULT_RETRIES;
+ // Rate-limit-class failures get their OWN (larger) retry budget — see
+ // the class doc comment. The shared `attempt` counter is bounded by
+ // whichever budget is larger; each branch below still checks its own
+ // budget, so a plain 401 exhausts at `retries` exactly as before.
+ const rateLimitRetries = opts.rateLimitRetries ?? DEFAULT_RATE_LIMIT_RETRIES;
+ const maxAttempt = Math.max(retries, rateLimitRetries);
+ for (let attempt = 0; attempt <= maxAttempt; attempt++) {
const token = await this.tokens.getAccessToken();
const res = await this.fetchImpl(url, {
headers: { authorization: `Bearer ${token}` },
@@ -88,9 +129,12 @@ export class GoogleApiClient {
}
}
if (res.status === 403 || res.status === 429) {
- const waitMs = parseRetryAfterMs(res.headers.get('retry-after')) ?? Math.min(60_000, 2 ** attempt * 2_000);
- if (attempt < retries) {
- this.log(`[google] HTTP ${res.status}; retrying in ${Math.round(waitMs / 1000)}s`);
+ const waitMs = parseRetryAfterMs(res.headers.get('retry-after')) ?? rateLimitBackoffMs(attempt);
+ if (attempt < rateLimitRetries) {
+ this.log(
+ `[google] HTTP ${res.status}; retrying in ${Math.round(waitMs / 1000)}s ` +
+ `(rate limit, attempt ${attempt + 1}/${rateLimitRetries})`,
+ );
await new Promise<void>((resolve) => {
const t = setTimeout(resolve, waitMs);
opts.signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 57d7812566..34ba92136b 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -610,6 +610,26 @@ async function applyLoopDetection(
/** How many consecutive fetch failures before a thread is skipped (poison). */
const MAX_THREAD_FAILURES = 3;
+/**
+ * A rate-limit failure is transient and self-clearing (Google's own quota
+ * window, not a problem with this thread) — it must NOT count toward
+ * MAX_THREAD_FAILURES. The google-clients.ts retry loop already retries a
+ * rate-limited request patiently (DEFAULT_RATE_LIMIT_RETRIES, backoff +
+ * jitter) before giving up and throwing this; reaching here means the
+ * client's own retry budget was exhausted, not that the thread is bad.
+ */
+function isRateLimitFailure(e: unknown): boolean {
+ return isCredentialError(e) && e.code === 'rate_limited';
+}
+
+/** One wording for a failed thread fetch, shared by the backfill and delta lanes. */
+function threadFailureMessage(tid: string, rateLimited: boolean, e: unknown): string {
+ return (
+ `[google] thread ${tid} failed${rateLimited ? ' (rate limited; not counted toward the poison threshold)' : ''}: ` +
+ `${e instanceof Error ? e.message : String(e)}`
+ );
+}
+
/**
* Returns true when every gmail thread this run either imported or was
* deliberately skipped (404-vanished, poison ledger). False = real failures
@@ -698,11 +718,21 @@ async function sweepGmail(
progressTick(`thread ${tid} gone`);
continue;
}
- failCounts[tid] = (failCounts[tid] ?? 0) + 1;
+ // Rate-limited failures don't count toward the poison threshold
+ // (transient, self-clearing) — but they still fail the batch so
+ // the floor doesn't skip past a thread nothing has actually
+ // imported yet.
+ const rateLimited = isRateLimitFailure(e);
+ if (!rateLimited) failCounts[tid] = (failCounts[tid] ?? 0) + 1;
batchFailed = true;
summary.failedFiles++;
summary.status = 'partial';
- deps.log(`[google] thread ${tid} failed: ${e instanceof Error ? e.message : String(e)}`);
+ deps.log(threadFailureMessage(tid, rateLimited, e));
+ // A rate limit is per-user, not per-thread: the rest of this batch
+ // would hit the same exhausted quota, and its work is never banked
+ // anyway (batchFailed already holds the floor), so defer it to the
+ // next run instead of burning the retry budget once per thread.
+ if (rateLimited) break;
}
}
// Monotone forward progress: the floor commits per FULLY-SUCCESSFUL
@@ -799,11 +829,19 @@ async function sweepGmail(
progressTick(`thread ${tid} gone`);
continue;
}
- failCounts[tid] = (failCounts[tid] ?? 0) + 1;
+ // Same rate-limit carve-out as the backfill batch loop above: transient,
+ // self-clearing, must not count toward the poison threshold — but it
+ // still holds the delta cursor back (failed++) so nothing is dropped.
+ const rateLimited = isRateLimitFailure(e);
+ if (!rateLimited) failCounts[tid] = (failCounts[tid] ?? 0) + 1;
failed++;
summary.failedFiles++;
summary.status = 'partial';
- deps.log(`[google] thread ${tid} failed: ${e instanceof Error ? e.message : String(e)}`);
+ deps.log(threadFailureMessage(tid, rateLimited, e));
+ // Per-user quota, same as the backfill: the remaining threads would burn
+ // the client's retry budget against the same exhausted window, and the
+ // cursor is already held (failed > 0) so the next run re-lists them.
+ if (rateLimited) break;
}
}
// The delta cursor advances only when every flagged thread landed —
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0c14d44582..cf902ab6cd 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -51,7 +51,7 @@ import { decorateEmbeddingDimError } from './embedding-dim-check.ts';
import { computeCorpusGeneration, loadSourceRow } from './contextual-retrieval-service.ts';
import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';
import { runGuardrails } from './guardrails.ts';
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning } from './facts-fence.ts';
+import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';
/**
@@ -113,19 +113,6 @@ function fenceTagToPseudoPath(lang: string | undefined): string | null {
// MAX_FENCES_PER_PAGE (fence-bomb DOS cap, GBRAIN_MAX_FENCES_PER_PAGE env
// override) moved to fence-scan.ts with the #2862 linear scanner.
-function replaceOrAppendFactsFence(body: string, fenceBlock: string): string {
- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);
- if (beginIdx !== -1) {
- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);
- if (endIdx !== -1) {
- return body.slice(0, beginIdx) + fenceBlock + body.slice(endIdx + FACTS_FENCE_END.length);
- }
- }
-
- const sep = body.endsWith('\n') ? '\n' : '\n\n';
- return `${body}${sep}## Facts\n\n${fenceBlock}\n`;
-}
-
/**
* #2044 / #4548: row-level, visibility-aware fence merge for one page
* column on the remote write-back boundary. Restores non-'world' fence
@@ -159,7 +146,9 @@ function mergeHiddenFactRowsIntoBody(
`the hidden row(s) keep their original numbers.`,
);
}
- return replaceOrAppendFactsFence(incomingBody, renderFactsTable(merge.merged));
+ // Shared #4756 placement rule (the column is already split at the
+ // sentinel here, so this is dedup, not a behaviour change for the importer).
+ return replaceOrInsertFactsFence(incomingBody, renderFactsTable(merge.merged));
}
const gapWarning = factsGapWarning(slug, incomingFacts, existingFacts, false);
if (gapWarning) console.warn(gapWarning);
@@ -1263,7 +1252,7 @@ export async function importFromFile(
return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)` };
}
- let content = readFileSync(filePath, 'utf-8');
+ let content = readFileSync(filePath, 'utf-8').replace(/^\uFEFF/, ''); // #4798: a BOM is encoding noise, not content
// Defense-in-depth for callers that bypass the sync/import classifiers
// (direct importFromFile, reindex, capture paths): a malformed filename is
@@ -1570,6 +1559,14 @@ export async function importCodeFile(
timeline: '',
frontmatter: { language: lang, file: relativePath },
content_hash: hash,
+ // A code page MUST carry its path. The full-sync reconcile finds a
+ // deleted file's page by matching `source_path` against the git tree;
+ // with the column NULL the page is invisible to it and is served
+ // forever. Markdown pages already set it, which is why only the code
+ // walk grew ghosts. Written on every import, not just the first:
+ // putPage COALESCEs, so a NULL here would never overwrite a good value
+ // but would also never backfill a row imported before this line existed.
+ source_path: relativePath,
// `content` is authoritative source text (disk file, or the row's own
// body via reindex-code): an emptied file is a deliberate clear.
}, { ...txOpts, allowEmptyOverwrite: true });
diff --git a/src/core/latin-fold.ts b/src/core/latin-fold.ts
new file mode 100644
index 0000000000..84bdcc4405
--- /dev/null
+++ b/src/core/latin-fold.ts
@@ -0,0 +1,49 @@
+/**
+ * Latin letters whose diacritic is drawn INSIDE the glyph — a stroke, bar, or
+ * ligature rather than a floating accent.
+ *
+ * Unicode assigns these no decomposition mapping, so the usual fold (NFD/NFKD
+ * decompose, then strip combining marks U+0300–U+036F) turns "é" into "e" but
+ * leaves "đ" exactly as it was. What happens next depends on the grammar
+ * downstream, and both outcomes are wrong in the same way:
+ *
+ * - a grammar that keeps only `[a-z0-9]` DELETES the letter
+ * ("Đăng Example" → "ang-example");
+ * - a grammar that keeps all letters KEEPS it unfolded
+ * ("Đức Example" → "đuc-example").
+ *
+ * Neither matches the ASCII form the rest of the pipeline expects, and the
+ * mismatch is silent: a slug nothing resolves to, or a basename lookup that
+ * misses.
+ *
+ * Leaf module by design — text primitives only, no engine or graph imports —
+ * so every grammar that folds accents can share one table.
+ */
+
+/** Keys are lowercase: callers fold after their own lowercasing pass. */
+export const NON_DECOMPOSING_LATIN: Readonly<Record<string, string>> = {
+ đ: 'd', // U+0111 Vietnamese, Croatian, Sami
+ ð: 'd', // U+00F0 Icelandic eth
+ ø: 'o', // U+00F8 Danish, Norwegian, Faroese
+ ł: 'l', // U+0142 Polish
+ ħ: 'h', // U+0127 Maltese
+ ŧ: 't', // U+0167 Northern Sami
+ ı: 'i', // U+0131 Turkish dotless i
+ ß: 'ss', // U+00DF German sharp s
+ æ: 'ae', // U+00E6 Danish, Norwegian, Icelandic
+ œ: 'oe', // U+0153 French
+ þ: 'th', // U+00FE Icelandic thorn
+};
+
+const NON_DECOMPOSING_RE = new RegExp(`[${Object.keys(NON_DECOMPOSING_LATIN).join('')}]`, 'g');
+
+/**
+ * Fold stroke/bar/ligature letters to their base ASCII letters.
+ *
+ * Call AFTER lowercasing (the table is lowercase-keyed) and AFTER the
+ * combining-mark strip, so composed forms reduce in a single pass:
+ * "ǿ" → NFD → "ø" + U+0301 → mark stripped → "ø" → "o".
+ */
+export function foldNonDecomposingLatin(s: string): string {
+ return s.replace(NON_DECOMPOSING_RE, ch => NON_DECOMPOSING_LATIN[ch]);
+}
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index e1f7b53b18..0d1d84c22c 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -16,8 +16,9 @@ import type { PageType, EffectiveDateSource } from './types.ts';
import { ensureWellFormed } from './text-safe.ts';
import { stripCodeBlocks } from './markdown-code.ts';
import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
-import { slugifyPath } from './sync.ts';
+import { slugifyPath, slugifySegment } from './sync.ts';
import { SLUG_WORD_CHARS } 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.
import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';
@@ -48,6 +49,9 @@ 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-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`.
// 2026-08-21: re-bumped for #2367 — normalizeBasename semantics changed
// (non-Latin scripts kept, accents folded like the slug grammar), so
// pre-#2367 extractions must re-run to pick up the newly-resolvable links.
@@ -62,7 +66,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-08-21T00:00:00Z';
+export const LINK_EXTRACTOR_VERSION_TS = '2026-09-06T00:00:00Z';
// ─── Entity references ──────────────────────────────────────────
@@ -237,12 +241,20 @@ 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).
- * The `.md` suffix is REQUIRED (mirrors the FS extractor's mdPattern) so
- * bare parenthetical prose (`[sic](reference)`) never produces a ref.
- * Resolution against the linking page's directory happens in
- * extractPageLinks (this module has no page context here).
+ * #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
+ * `./` / `../` segments (`[Name](../slug.md)`, `[Name](./../slug.md)`): pass 1
+ * only claims `../` targets that carry a directory segment, so a parent-dir
+ * sibling link had no DB candidate at all while the FS walker's join() linked
+ * it — the sweep reconcile then pruned the edge (same class as #4873).
+ * Captures: name, dot-prefix run, relative tail, bare tail. The `.md` suffix
+ * is REQUIRED (mirrors the FS extractor's mdPattern) so bare parenthetical
+ * prose (`[sic](reference)`) never produces a ref. Resolution against the
+ * linking page's directory happens in extractPageLinks (this module has no
+ * page context here).
*/
-const SAME_DIR_MD_RE = /\[([^\]]+)\]\(([^)/:#\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
@@ -381,21 +393,28 @@ export function extractEntityRefs(content: string): EntityRef[] {
markdownRanges.push([match.index, match.index + match[0].length]);
}
- // 1b. #3190: same-directory markdown links — `[Name](slug.md)` (no `/`,
- // no scheme). Pass 1 requires a `dir/` segment, so sibling links in
- // flat directories were silently dropped on the DB path while the FS
- // walker (extractMarkdownLinks → resolveSlug) linked them. Tagged
- // `sameDir: true`; extractPageLinks resolves against the page's dir.
- // Disjoint from pass 1 (its targets always contain `/`).
+ // 1b. #3190/#4873: same-directory markdown links — `[Name](slug.md)`,
+ // `[Name](./slug.md)`, `[Name](../slug.md)` (no scheme). Pass 1 requires
+ // a `dir/` segment, so sibling and dot-relative links were silently
+ // dropped on the DB path while the FS walker (extractMarkdownLinks →
+ // resolveSlug) linked them. Tagged `sameDir: true`; the `..` depth of
+ // the prefix rides on `upLevels` and extractPageLinks resolves against
+ // the page's dir. A `../dir/x.md` span pass 1 already claimed is skipped
+ // so the two passes never double-emit.
const sameDirPattern = new RegExp(SAME_DIR_MD_RE.source, SAME_DIR_MD_RE.flags);
while ((match = sameDirPattern.exec(stripped)) !== null) {
+ const at = match.index;
+ if (markdownRanges.some(([s, e]) => at >= s && at < e)) continue;
const name = match[1];
- let target = match[2];
+ let target = match[3] ?? match[4];
if (target.includes('%')) {
try { target = decodeURIComponent(target); } catch { /* keep raw */ }
}
- refs.push({ name, slug: target, dir: '', sameDir: true });
- markdownRanges.push([match.index, match.index + match[0].length]);
+ 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;
+ refs.push(ref);
+ markdownRanges.push([at, at + match[0].length]);
}
// 2a. v0.17.0 qualified wikilinks: [[source-id:path]] or [[source-id:path|Display]]
@@ -614,8 +633,18 @@ export async function extractPageLinks(
// `[Alice](Alice%20Chen.md)` reaches `people/alice-chen`. Downstream
// existence checks drop targets that aren't pages.
if (ref.sameDir) {
- const dirSegs = slug.includes('/') ? slug.split('/').slice(0, -1) : [];
- const target = slugifyPath([...dirSegs, ref.slug].join('/'));
+ const segs = slug.includes('/') ? slug.split('/').slice(0, -1) : [];
+ // `../` / `./../` prefixes (upLevels) and any mid-path `.`/`..` fold
+ // the way the FS walker's join() does; a run that would climb above
+ // the root is a dangling link there too, so it yields no candidate.
+ let climbed = false;
+ for (const seg of ('../'.repeat(ref.upLevels ?? 0) + ref.slug).split('/')) {
+ if (seg === '' || seg === '.') continue;
+ if (seg !== '..') { segs.push(seg); continue; }
+ if (segs.length === 0) { climbed = true; break; }
+ segs.pop();
+ }
+ const target = climbed ? '' : slugifyPath(segs.join('/'));
if (target && target !== slug) {
const idx = content.indexOf(ref.name);
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
@@ -665,16 +694,21 @@ export async function extractPageLinks(
// Downstream existence checks (resolveCandidateSources / put_page's
// allSlugs filter / addLinksBatch's INNER JOINs) drop the candidate
// when no root page exists, exactly as for slash-shaped refs above.
- let bareDirect = '';
+ // #4855 twin: both slug grammars — sync's slugifyPath keeps stroke
+ // letters (`đuc-example`), normalizeBasename folds them (`duc-example`)
+ // — so `[[Đức Example]]` reaches whichever root page exists with the
+ // flag off. Exact slugs only; downstream existence checks drop the miss.
+ const bareDirect = new Set<string>();
if (slashIdx === -1) {
- bareDirect = slugifyPath(ref.slug);
- // Self-loop guard: `[[own-basename]]` on the root page itself.
- if (bareDirect && bareDirect !== slug) {
+ for (const form of new Set([slugifyPath(ref.slug), normalizeBasename(ref.slug)])) {
+ // 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 litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
candidates.push({
- targetSlug: bareDirect,
- linkType: typeFor(litContext, bareDirect),
+ targetSlug: form,
+ linkType: typeFor(litContext, form),
context: litContext,
linkSource: 'markdown',
});
@@ -707,7 +741,7 @@ export async function extractPageLinks(
// candidate above already covers it (same rule the dir-qualified
// branch applies to its raw literal). Keeping it would double-emit.
matches = (await resolver.resolveBasenameMatches(ref.slug))
- .filter(m => m !== bareDirect);
+ .filter(m => !bareDirect.has(m));
}
if (matches.length === 0) continue;
const idx = content.indexOf(ref.slug);
@@ -1079,14 +1113,24 @@ export interface SlugResolver {
* build/query through these two functions so they cannot drift.
*
* Keying: raw tail + lowercase tail + slugified tail (the final `/`-segment,
- * or the whole slug when it has no `/`). #2367: slugified keys mirror
+ * or the whole slug when it has no `/`). #2367: slugified keys follow
* slugifySegment (NFD → strip accents → NFC → lowercase → SLUG_WORD_CHARS
- * filter); the old ASCII-only strip emptied CJK basenames.
+ * filter) and then fold stroke letters through latin-fold (#4855), so for
+ * names with đ/ø/ł/ß… the key is NOT byte-identical to the page slug sync
+ * mints; the dir-hint candidate step (makeResolver step 2, the FS resolver)
+ * tries both forms. The old ASCII-only strip emptied CJK basenames.
*/
const BASENAME_KEEP_RE = new RegExp(`[^${SLUG_WORD_CHARS}\\s\\-]`, 'gu');
export function normalizeBasename(s: string): string {
- return s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').normalize('NFC')
- .toLowerCase().replace(BASENAME_KEEP_RE, '').trim().replace(/\s+/g, '-');
+ // The accent strip cannot fold stroke letters \u2014 Unicode gives them no
+ // decomposition \u2014 so the shared table runs after it, on both the index and
+ // the query side. Without it a display name keeps the unfolded letter while
+ // 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(),
+ );
+ return folded.replace(BASENAME_KEEP_RE, '').trim().replace(/\s+/g, '-');
}
/** Stable order: shorter slug first (likely closer to brain root), then lexical. */
@@ -1213,15 +1257,21 @@ export function makeResolver(
}
}
- // Step 2: dir-hint + slugify → exact getPage
- const slugified = normalizeBasename(trimmed); // #2367: shared normalizer
+ // Step 2: dir-hint + slugify → exact getPage. Two grammars (#4855):
+ // normalizeBasename (#2367) folds stroke letters to ASCII via latin-fold,
+ // while slugifySegment — the page-slug grammar sync mints — keeps them
+ // (#3417), so a page synced from `Đức Example.md` lives at the unfolded
+ // slug. Exact lookups only, so trying both can never false-positive.
+ const forms = new Set([normalizeBasename(trimmed), slugifySegment(trimmed)]);
for (const hint of hints) {
if (!hint) continue;
- const candidate = `${hint}/${slugified}`;
- const page = await engine.getPage(candidate, opts.sourceId ? { sourceId: opts.sourceId } : undefined); // gbrain-allow-unscoped-getpage: read-only wikilink resolution; unscoped-when-no-source is the documented single-source behavior
- if (page) {
- cache.set(cacheKey, candidate);
- return candidate;
+ for (const form of forms) {
+ const candidate = `${hint}/${form}`;
+ const page = await engine.getPage(candidate, opts.sourceId ? { sourceId: opts.sourceId } : undefined); // gbrain-allow-unscoped-getpage: read-only wikilink resolution; unscoped-when-no-source is the documented single-source behavior
+ if (page) {
+ cache.set(cacheKey, candidate);
+ return candidate;
+ }
}
}
@@ -1702,8 +1752,10 @@ export async function isGlobalBasenameEnabled(engine: BrainEngine): Promise<bool
* and surfaced in the extract summary, never silent (issue #2589: the drop
* was previously indistinguishable from an unresolved link).
*
- * SCOPE: the DB extract paths only (`extract links --source db`,
- * `extract --stale`) — they resolve against the full multi-source slug map.
+ * SCOPE: the DB extract paths (`extract links --source db`, `extract --stale`),
+ * the mention scan (`findMentionedEntities` callers lift their guard under it),
+ * and the serve-resident maintenance sweep (`sweep.ts`, #3757 — it threads the
+ * same flag so its reconcile keeps the edges the CLI lanes created).
* The FS-walk paths (dir-driven, incl. the autopilot cycle's extract phase)
* build their slug set from the walked files of ONE source, so cross-source
* targets aren't resolvable there; FS-walk parity is a filed follow-up.
diff --git a/src/core/llm-json.ts b/src/core/llm-json.ts
index f4090f3d5b..d54f9acecd 100644
--- a/src/core/llm-json.ts
+++ b/src/core/llm-json.ts
@@ -16,20 +16,32 @@
* Strip a reasoning model's chain-of-thought block.
*
* Reasoning models (DeepSeek-R1, MiniMax M2.x/M3, and any model configured to
- * emit visible thinking) put a `<think>` block BEFORE the answer, in the same
+ * emit visible thinking) put a reasoning block BEFORE the answer, in the same
* text channel. That reasoning routinely contains braces, because the model
* drafts its JSON while thinking. This defeats strategy 3 in parseLlmJson: the
* greedy `/\{[\s\S]*\}/` spans from the FIRST brace inside the reasoning to
* the LAST brace of the real answer, so the parse fails and the caller records
* an "unparseable" result even though a perfectly good object was returned.
*
- * Handles both shapes: a closed `<think>…</think>` pair, and a truncated block
- * that was opened and never closed (the model exhausted its output budget).
+ * Also strips `<thinking>`, emitted by some models/proxies that render
+ * reasoning as a tag in the text channel. Deliberately NOT covered:
+ * `<reasoning>` and MiniMax's `◁think▷` sentinel — neither appears in this
+ * repo's providers or fixtures, and this helper is a recovery path, not a
+ * general sanitiser; add a tag only with a captured payload that shows it.
+ *
+ * Handles both shapes: a closed `<think(ing)>…</think(ing)>` pair, and a
+ * truncated block that was opened and never closed (the model exhausted its
+ * output budget). The closed-pair arm backreferences the opening tag so a
+ * `<think>` is only ever closed by `</think>` — that keeps behaviour on
+ * `<think>` input byte-identical to before, with `<thinking>` purely additive;
+ * a MISMATCHED pair still falls through to the open-ended arm exactly as it
+ * did pre-change. Order matters: closed pairs first, then any surviving
+ * unclosed opener to end-of-string.
*/
export function stripReasoningBlocks(raw: string): string {
return raw
- .replace(/<think>[\s\S]*?<\/think>/gi, '')
- .replace(/<think>[\s\S]*$/i, '')
+ .replace(/<(think|thinking)>[\s\S]*?<\/\1>/gi, '')
+ .replace(/<(?:think|thinking)>[\s\S]*$/i, '')
.trim();
}
@@ -39,7 +51,7 @@ export function parseLlmJson<T>(raw: string, opts: { array?: boolean } = {}): T
if (direct !== null) return direct;
// A fallback LADDER, not a pre-filter: the raw text is parsed first, so every
// existing call site behaves byte-for-byte as before and a payload that
- // legitimately contains "<think>" is unaffected. The stripped retry runs only
+ // legitimately contains "<think>"/"<thinking>" is unaffected. The retry runs only
// after the raw parse has already failed, and text with no reasoning block
// strips to itself — so the added cost on the success path is zero.
const stripped = stripReasoningBlocks(raw);
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index aedda5ba24..d17e79eb67 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -1012,7 +1012,10 @@ export function resolvePageFilePath(
* `sources.local_path` points at a subdirectory. A direct join duplicates the
* scope (`.../public/changelog/public/changelog/...`). Find the same Git root
* sync uses without spawning a subprocess, then remove that exact scope.
- * Non-Git vaults and Git-root local paths keep the direct path.
+ * Non-Git vaults and Git-root local paths keep the direct path. Historical
+ * rows may carry a basename-relative `source_path`; when the direct path is
+ * absent and the caller provides the page slug, resolve that spelling under
+ * the slug's directory before reporting the file as missing.
*
* Returns null for an unsafe or non-markdown source path. Callers must still
* enforce their normal realpath containment check before a write.
@@ -1029,9 +1032,19 @@ function splitLocalPathSegments(value: string): string[] {
return (pathSep === '\\' ? value.split(/[\\/]+/) : value.split(/\/+/)).filter(Boolean);
}
+function safeSlugDirSegments(rawSlug: string | null | undefined): string[] | null {
+ if (!rawSlug) return null;
+ const value = rawSlug.trim();
+ if (!value || value.includes('\0') || isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value)) return null;
+ const segments = splitLocalPathSegments(value);
+ if (segments.length === 0 || segments.some(segment => segment === '..')) return null;
+ return segments.slice(0, -1);
+}
+
export function resolveSourceLocalFilePath(
localPath: string,
rawSourcePath: string | null | undefined,
+ pageSlug?: string | null,
): string | null {
if (!rawSourcePath) return null;
const value = rawSourcePath.trim();
@@ -1041,12 +1054,15 @@ export function resolveSourceLocalFilePath(
if (sourceSegments.length === 0 || sourceSegments.some(segment => segment === '..')) return null;
const absoluteLocalPath = resolve(localPath);
+ let sourceScopeSegments: string[] = [];
+ let resolvedSegments = sourceSegments;
let cursor = absoluteLocalPath;
while (true) {
if (existsSync(join(cursor, '.git'))) {
const scope = splitLocalPathSegments(relative(cursor, absoluteLocalPath));
+ sourceScopeSegments = scope;
if (scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index])) {
- return join(absoluteLocalPath, ...sourceSegments.slice(scope.length));
+ resolvedSegments = sourceSegments.slice(scope.length);
}
break;
}
@@ -1054,5 +1070,19 @@ export function resolveSourceLocalFilePath(
if (parent === cursor) break;
cursor = parent;
}
- return join(absoluteLocalPath, ...sourceSegments);
+ const directPath = join(absoluteLocalPath, ...resolvedSegments);
+ if (existsSync(directPath)) return directPath;
+
+ const slugDirSegments = safeSlugDirSegments(pageSlug);
+ if (sourceSegments.length === 1 && slugDirSegments && slugDirSegments.length > 0) {
+ const scopedSlugDir =
+ sourceScopeSegments.length > 0 &&
+ sourceScopeSegments.every((segment, index) => segment === slugDirSegments[index])
+ ? slugDirSegments.slice(sourceScopeSegments.length)
+ : slugDirSegments;
+ const slugRelativePath = join(absoluteLocalPath, ...scopedSlugDir, ...sourceSegments);
+ if (existsSync(slugRelativePath)) return slugRelativePath;
+ }
+
+ return directPath;
}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 61b465d981..ca1ec18ed0 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -6440,6 +6440,67 @@ export const MIGRATIONS: Migration[] = [
END $$;
`,
},
+ {
+ version: 146,
+ name: 'extract_atoms_transcript_state_table',
+ // #4148 follow-on: extend the failure-count / tombstone machinery to
+ // TRANSCRIPT items. Pre-fix `recordPageFailureCount` returned null for
+ // `kind !== 'page'`, so a transcript that deterministically produced
+ // malformed output — or that honestly yielded zero atoms — re-entered
+ // discovery and re-spent LLM budget on EVERY cycle, forever. Pages avoid
+ // this via frontmatter (`atoms_fail_count` / `atoms_fail_hash` /
+ // `atoms_scan_hash`); transcripts are files, not pages, so they have no
+ // frontmatter to carry it and need their own store.
+ //
+ // Precedent: dream_verdicts (v30), the other transcript-keyed cache, whose
+ // comment already establishes why this cannot live in raw_data — "Distinct
+ // from raw_data (page-scoped); transcripts aren't pages" (raw_data.page_id
+ // is NOT NULL REFERENCES pages(id)). It also must NOT be columns on
+ // dream_verdicts itself: that table is documented as rebuildable via
+ // `gbrain dream retriage --force`, which clears it wholesale, and atom
+ // extraction state would be swept away as collateral.
+ //
+ // KEYED (source_id, file_path, content_hash), which adds source_id to the
+ // dream_verdicts shape. dream_verdicts can be source-free because it caches
+ // a content-level judgment ("is this transcript worth processing"), which is
+ // genuinely source-independent. A failure streak and a tombstone GATE
+ // EXTRACTION, and extraction is source-scoped throughout this phase — the
+ // discovery SQL, the NOT EXISTS idempotency subquery, and every putPage all
+ // take sourceId. This file's own header records what happens when that is
+ // forgotten here: "Pre-fix the putPage call was missing the sourceId arg —
+ // atoms always wrote to 'default' regardless of source, which made the NOT
+ // EXISTS guard ineffective on federated brains." An unscoped tombstone would
+ // let one source permanently suppress another source's extraction of the
+ // same file.
+ //
+ // content_hash holds the 16-char prefix, matching `atoms.frontmatter
+ // ->>'source_hash'` and the page-side `atoms_fail_hash`, so every hash
+ // comparison in this phase is on the same unit. Including it in the PK is
+ // what makes "a content edit resets the streak" fall out for free: an edited
+ // transcript is simply a different row, mirroring the page-side hash-keyed
+ // reset.
+ //
+ // RLS: covered by the v35 auto_rls_on_create_table event trigger on
+ // Postgres, same as v126's session_context_state — no explicit ALTER here.
+ // Keep in sync with src/schema.sql and src/core/pglite-schema.ts
+ // (test/schema-bootstrap-coverage.test.ts enforces the PGLite parity).
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (
+ source_id TEXT NOT NULL DEFAULT 'default',
+ file_path TEXT NOT NULL,
+ content_hash TEXT NOT NULL,
+ fail_count INTEGER NOT NULL DEFAULT 0,
+ tombstoned BOOLEAN NOT NULL DEFAULT FALSE,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (source_id, file_path, content_hash)
+ );
+ DROP INDEX IF EXISTS extract_atoms_transcript_state_live_idx;
+ CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx
+ ON extract_atoms_transcript_state (source_id, content_hash)
+ WHERE tombstoned;
+ `,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
index d12565341c..c3b64cb4c7 100644
--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts
+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
@@ -206,9 +206,10 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerO
);
},
releaseSynopsisLease: async (lease) => {
- if (typeof lease === 'number') {
- await releaseLease(engine, lease);
- }
+ // acquireLease coerces the id to a number at the seam; a strict
+ // typeof check here used to skip the release when Postgres handed
+ // the BIGSERIAL back as a native BigInt, idling every slot to TTL.
+ if (lease != null) await releaseLease(engine, lease as number);
},
});
diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.ts
index 20a98f7836..b783551a6c 100644
--- a/src/core/minions/handlers/subagent-oneshot.ts
+++ b/src/core/minions/handlers/subagent-oneshot.ts
@@ -99,7 +99,7 @@ export const ONESHOT_SYSTEM = `You are a knowledge-synthesis engine. You have NO
If nothing in the transcript meets the bar (Task D), respond with:
{"pages": [], "skipped": true, "skip_reason": "<one line>"}
-Hard rules: at most ${MAX_PAGES_PER_RESPONSE} pages; slugs are lowercase, hyphen-separated, slash-delimited, no underscores, no file extensions; never invent wikilink targets that are not in LINK CANDIDATES or this response.`;
+Hard rules: at most ${MAX_PAGES_PER_RESPONSE} pages; slugs are lowercase, hyphen-separated, slash-delimited, no underscores, no file extensions; never invent wikilink targets that are not in LINK CANDIDATES or this response. Every field, especially body, must be a valid JSON string: escape quotes, backslashes, and line breaks; never place unescaped quotes or literal newlines inside a string.`;
export interface OneshotPage {
slug: string;
@@ -401,7 +401,13 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc
}
const parsed = parseOneshotResponse(chatResult.text ?? '');
- if (!parsed) return fb('unparseable');
+ if (!parsed) {
+ // Some providers normalize an output-cap stop to end/other. Usage at the
+ // requested ceiling is the provider-neutral truncation signal (same
+ // heuristic as subagent.ts replayTerminalStopReason), but only for
+ // invalid JSON — a complete valid response at the cap still succeeds.
+ return fb(chatResult.usage.output_tokens >= args.maxOutputTokens ? 'length' : 'unparseable');
+ }
if (parsed.pages.length === 0) {
if (!parsed.skipped) return fb('empty_no_skip');
// Task-D skip: a legitimate zero-write completion.
diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.ts
index 24c40f27db..78078a5102 100644
--- a/src/core/minions/handlers/subagent.ts
+++ b/src/core/minions/handlers/subagent.ts
@@ -52,7 +52,7 @@ import { resolveModel, isAnthropicProvider, isOpenRouterSubagentFamily, TIER_DEF
import { splitProviderModelId, normalizeModelId } from '../../model-id.ts';
import { resolveAnthropicKey } from '../../ai/anthropic-key.ts';
import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';
-import { toolLoop as gatewayToolLoop, isThinkingByDefaultModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../ai/gateway.ts';
+import { toolLoop as gatewayToolLoop, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../ai/gateway.ts';
import type { ChatToolDef, ChatMessage, ChatBlock, ChatResult, ToolHandler } from '../../ai/gateway.ts';
import { classifyCapabilities } from '../../ai/capabilities.ts';
import { runSubagentOneshot, ONESHOT_TOOL_USE_ID_PREFIX } from './subagent-oneshot.ts';
@@ -81,9 +81,9 @@ const DEFAULT_RATE_KEY = 'anthropic:messages';
/**
* Resolve the per-turn output-token cap (#2778). Per-job data wins, then the
* `agent.max_output_tokens` config row, then a model-aware default: 32000 for
- * thinking-by-default Claude 5 models (#4087 — they burn most of the budget on
- * internal reasoning; the flat 8192 default produced zero-tool-call truncated
- * runs even after the gateway learned to detect them), 8192 for everything
+ * thinking-by-default models (#4087 Claude 5 by name, #4172 recipe-declared
+ * such as DeepSeek v4: they burn most of the budget on internal reasoning; the
+ * flat 8192 default produced zero-tool-call truncated runs), 8192 for everything
* else (was a hardcoded 4096 that made pages >~12KB unwritable via put_page).
* Invalid values (NaN / zero / negative) fall through to the next tier.
*/
@@ -99,7 +99,7 @@ export function resolveMaxOutputTokens(
const n = Number(configRaw);
if (Number.isFinite(n) && n > 0) return Math.floor(n);
}
- return isThinkingByDefaultModel(model) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : DEFAULT_MAX_OUTPUT_TOKENS;
+ return isThinkingModel(model) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : DEFAULT_MAX_OUTPUT_TOKENS;
}
/**
diff --git a/src/core/minions/rate-leases.ts b/src/core/minions/rate-leases.ts
index 949ef5b8fc..58e4b4d842 100644
--- a/src/core/minions/rate-leases.ts
+++ b/src/core/minions/rate-leases.ts
@@ -96,13 +96,16 @@ export async function acquireLease(
return { acquired: false, activeCount, maxConcurrent };
}
- const rows = await tx.executeRaw<{ id: number }>(
+ const rows = await tx.executeRaw<{ id: number | bigint }>(
`INSERT INTO subagent_rate_leases (key, owner_job_id, expires_at)
VALUES ($1, $2, now() + ($3::double precision * interval '1 millisecond'))
RETURNING id`,
[key, ownerJobId, ttlMs],
);
- const leaseId = rows[0]!.id;
+ // BIGSERIAL arrives as a native BigInt on Postgres (postgres.js
+ // `types: { bigint }`); PGLite hands back a Number. Coerce once here so
+ // `leaseId` is honestly a number for every caller.
+ const leaseId = Number(rows[0]!.id);
return { acquired: true, leaseId, activeCount: activeCount + 1, maxConcurrent };
});
}
diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.ts
index ec1dbb3cfd..71a525cdf8 100644
--- a/src/core/minions/tools/brain-allowlist.ts
+++ b/src/core/minions/tools/brain-allowlist.ts
@@ -27,6 +27,7 @@ import type { GBrainConfig } from '../../config.ts';
import { operations } from '../../operations.ts';
import type { 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 type { ToolCtx, ToolDef } from '../types.ts';
@@ -304,7 +305,16 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {
sourceId: opts.sourceId,
deferEmbeds: opts.deferEmbeds,
});
- const params = (input && typeof input === 'object') ? input as Record<string, unknown> : {};
+ const raw = (input && typeof input === 'object') ? input as Record<string, unknown> : {};
+ // Same order the MCP dispatchers keep: normalize the optional-param
+ // absent idioms (`null`, `''` on a string) FIRST — the validator's
+ // header calls this load-bearing — then validate, so a missing
+ // required param (or wrong type / unknown enum) is named back to the
+ // model instead of crashing inside the handler, and `since: ""` never
+ // reaches a handler raw.
+ const params = normalizeOptionalParams(op, raw);
+ const validationError = validateParams(op, params);
+ if (validationError) throw new Error(`${toolName}: ${validationError}`);
return op.handler(opCtx, params);
},
};
diff --git a/src/core/minions/worker-registry.ts b/src/core/minions/worker-registry.ts
index 03ccaaea11..21e5b3c57d 100644
--- a/src/core/minions/worker-registry.ts
+++ b/src/core/minions/worker-registry.ts
@@ -142,22 +142,55 @@ function processLiveness(pid: number): 'alive' | 'dead' | 'unknown' {
}
}
+/** Parses portable `ps -o etime=` output (`[[dd-]hh:]mm:ss`) to milliseconds. */
+export function parseEtimeToMs(etime: string): number | null {
+ const raw = etime.trim();
+ if (!raw) return null;
+
+ let days = 0;
+ let rest = raw;
+ const dash = rest.indexOf('-');
+ if (dash !== -1) {
+ days = Number(rest.slice(0, dash));
+ rest = rest.slice(dash + 1);
+ if (!Number.isInteger(days) || days < 0) return null;
+ }
+
+ const parts = rest.split(':');
+ if (parts.length < 2 || parts.length > 3) return null;
+ if (!parts.every(part => part.length > 0 && /^\d+$/.test(part))) return null;
+
+ const numbers = parts.map(Number);
+ const [hours, minutes, seconds] =
+ numbers.length === 3 ? numbers : [0, numbers[0]!, numbers[1]!];
+
+ return (((days * 24 + hours!) * 60 + minutes!) * 60 + seconds!) * 1000;
+}
+
/**
* Best-effort process start time (epoch ms) via `ps`. Used for the PID-reuse
* guard: a stale `worker-<pid>.json` plus an OS-reused pid would otherwise make
* us report an unrelated process's niceness (Codex #8). Returns null when
* undeterminable — callers must NOT treat null as "reused".
+ *
+ * Elapsed time (`etime`) is zone-free. The previous `lstart` path printed a
+ * zoneless local timestamp in the libc zone while `Date.parse` read it in the
+ * runtime zone; the two can differ (bun test pins UTC without exporting TZ,
+ * `TZ=:/etc/localtime` resolves to UTC in ICU, and Bun does not propagate a
+ * runtime `process.env.TZ` change to the ps child), shifting every start by
+ * the offset and dropping live workers on UTC+ hosts (#4885). `etime` is used
+ * instead of Linux-only `etimes` so this also works on macOS.
*/
function processStartMs(pid: number): number | null {
try {
- const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
+ const out = execFileSync('ps', ['-o', 'etime=', '-p', String(pid)], {
encoding: 'utf8',
timeout: 2000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (!out) return null;
- const t = Date.parse(out);
- return Number.isNaN(t) ? null : t;
+ const elapsedMs = parseEtimeToMs(out);
+ return elapsedMs === null ? null : Date.now() - elapsedMs;
} catch {
return null;
}
diff --git a/src/core/model-config.ts b/src/core/model-config.ts
index ed3febef74..3a1f81c915 100644
--- a/src/core/model-config.ts
+++ b/src/core/model-config.ts
@@ -165,20 +165,40 @@ function realEnv(env: Record<string, string | undefined>): Record<string, string
) as Record<string, string>;
}
+/**
+ * Explicit tier→file-plane pin key map (utility→expansion_model, everything
+ * else→chat_model): an unmapped future caller mislabeling the warn would be a
+ * silent doc bug with a ternary.
+ */
+const PIN_KEY_BY_TIER: Record<ModelTier, 'expansion_model' | 'chat_model'> = {
+ utility: 'expansion_model', reasoning: 'chat_model', deep: 'chat_model', subagent: 'chat_model',
+};
+
/**
* Resolve the default model for a tier, honoring which provider keys are
* actually present. When `env` is passed it is used EXCLUSIVELY (no config
* read — hermetic for tests and pre-merged callers); when omitted, the merged
- * env is computed from the file-plane config + process.env.
+ * env is computed from the file-plane config + process.env, and a SERVABLE
+ * file-plane pin for the tier is consulted below the key walk (#3813).
*/
export function resolveTierDefault(
tier: ModelTier,
env?: Record<string, string | undefined>,
): string {
- const merged = env ? realEnv(env) : mergedProviderEnv(throwSafeLoadConfig(), process.env);
+ const fileCfg = env ? null : throwSafeLoadConfig();
+ const merged = env ? realEnv(env) : mergedProviderEnv(fileCfg, process.env);
for (const entry of PROVIDER_TIER_DEFAULTS) {
if (merged[entry.envKey]) return entry.tiers(tier);
}
+ // #3813: no anthropic/openai key. PROVIDER_TIER_DEFAULTS knows only those
+ // two, so a single-provider install (deepseek, openrouter, together, ...)
+ // used to land on the Anthropic floor and every bare-default caller
+ // (extract_atoms, facts classify, page-summary, ...) called a provider with
+ // no key. A servable pin for this tier beats the floor. Sits BELOW the key
+ // walk so keyed installs route byte-for-byte as before.
+ const rawPin = fileCfg?.[PIN_KEY_BY_TIER[tier]]?.trim();
+ const pin = rawPin ? (DEFAULT_ALIASES[rawPin] ?? rawPin) : undefined;
+ if (pin && providerKeyReady(pin, merged)) return pin;
return TIER_DEFAULTS[tier];
}
@@ -250,11 +270,6 @@ function resolveEffectiveModelForTier(
if (providerKeyReady(fullPin, merged)) return { model: fullPin, source: 'file_pin' };
if (!_unservablePinWarningsEmitted.has(fullPin)) {
_unservablePinWarningsEmitted.add(fullPin);
- // Explicit tier→config-key map: an unmapped future caller mislabeling
- // the warn would be a silent doc bug with a ternary.
- const PIN_KEY_BY_TIER: Record<ModelTier, string> = {
- utility: 'expansion_model', reasoning: 'chat_model', deep: 'chat_model', subagent: 'chat_model',
- };
// A prefix-less pin is a DIFFERENT problem than a missing key — saying
// "no usable provider key" for `chat_model: "claude-sonnet-4-6"` sends
// the user hunting for a key problem they may not have.
diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.ts
index 7da9fe4cf4..c00414f474 100644
--- a/src/core/model-pricing.ts
+++ b/src/core/model-pricing.ts
@@ -44,8 +44,9 @@ export interface ModelPricing {
/**
* #4218 — USD per 1M prompt-cache-READ tokens. Optional: present only for
* providers whose published cache pricing we've verified (Anthropic:
- * 0.1x input). Consumers that price cache tokens fall back to the input
- * rate when absent (conservative over-estimate for reads).
+ * 0.1x input by default; Fable 5.1: 0.025x). Consumers that
+ * price cache tokens fall back to the input rate when absent (conservative
+ * over-estimate for reads).
*/
cache_read?: number;
/**
@@ -64,15 +65,23 @@ export interface ModelPricing {
* anthropic: row's cache fields stay derived from its input rate. */
export const ANTHROPIC_CACHE_READ_MULT = 0.1;
export const ANTHROPIC_CACHE_WRITE_5M_MULT = 1.25;
-function anthro(input: number, output: number): ModelPricing {
+function anthro(input: number, output: number, cacheReadMult = ANTHROPIC_CACHE_READ_MULT): ModelPricing {
return {
input,
output,
- cache_read: input * ANTHROPIC_CACHE_READ_MULT,
+ cache_read: input * cacheReadMult,
cache_write: input * ANTHROPIC_CACHE_WRITE_5M_MULT,
};
}
+/** Per-model cache-read multiplier overrides. Anthropic bills cache hits at
+ * ANTHROPIC_CACHE_READ_MULT (0.1x) except where listed here. Keys match
+ * CANONICAL_PRICING keys; the drift guard asserts both directions. */
+export const ANTHROPIC_CACHE_READ_MULT_OVERRIDES: Record<string, number> = {
+ // Fable 5.1 bills cache hits at 0.025x base input ($0.25/MTok on $10).
+ 'anthropic:claude-fable-5-1': 0.025,
+};
+
/**
* Canonical price table. Keys are provider-prefixed (`provider:model`),
* matching the exact id strings consumers pass. One physical model may carry
@@ -86,6 +95,9 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {
// see the anthro() helper + multiplier constants above.
// Fable 5: Anthropic's top tier, above Opus. $10 in / $50 out.
'anthropic:claude-fable-5': anthro(10.00, 50.00),
+ // Fable 5.1: same $10/$50 sticker as Fable 5, but cache hits bill 0.025x
+ // ($0.25/MTok) instead of 0.1x — the only rate that changed.
+ 'anthropic:claude-fable-5-1': anthro(10.00, 50.00, ANTHROPIC_CACHE_READ_MULT_OVERRIDES['anthropic:claude-fable-5-1']),
// Opus 4.x/5: $5 in / $25 out. Opus 5 (new generation) shares the same
// per-token rate as 4.8 (released 2026-05-28) — closes gbrain#1819.
'anthropic:claude-opus-5': anthro( 5.00, 25.00),
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index ca553f0df2..7758cf6b26 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -144,8 +144,10 @@ const run_doctor: Operation = {
handler: async (ctx) => {
const { doctorReportRemote } = await import('../../commands/doctor.ts');
// Source isolation (cross-model P1): a source-bound caller's report must
- // not aggregate other sources' activity. Scope-aware checks (currently
- // volunteer_channels) filter on these ids; unscoped ctx = brain-wide.
+ // 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;
+ // unscoped ctx = brain-wide.
const scope = sourceScopeOpts(ctx);
const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);
return doctorReportRemote(ctx.engine, { sourceIds });
diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.ts
index f3e31b3747..334a481293 100644
--- a/src/core/ops/chronicle.ts
+++ b/src/core/ops/chronicle.ts
@@ -142,7 +142,7 @@ const ontology_get: Operation = {
asof: typeof p.asof === 'string' ? p.asof : undefined,
minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
includeQuarantined: p.include_quarantined === true,
- ...sourceScopeOpts(ctx),
+ ...await readPolicyOpts(ctx),
});
// Remote redaction: never surface diary-sourced ontology to untrusted callers.
return ctx.remote !== false ? rows.filter((r) => !(r.source ?? '').startsWith('life/diary/')) : rows;
@@ -210,7 +210,7 @@ const ontology_conflicts: Operation = {
handler: async (ctx, p) => {
const conflicts = await ctx.engine.findOntologyConflicts({
minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
- ...sourceScopeOpts(ctx),
+ ...await readPolicyOpts(ctx),
});
if (ctx.remote === false) return conflicts;
// Remote: redact diary-sourced values; drop conflicts that no longer have
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts
index 2310f5aebd..cbc1bdd0ff 100644
--- a/src/core/ops/code-intel.ts
+++ b/src/core/ops/code-intel.ts
@@ -8,9 +8,10 @@
* Never import from '../operations.ts' here (cycle).
*/
-import type { Operation } from './contract.ts';
+import type { Operation, OperationContext } from './contract.ts';
import { OperationError } from './contract.ts';
import { routeCodeIntelScope } from './context.ts';
+import type { WalkResult } from '../code-intel/recursive-walk.ts';
import {
CODE_CALLERS_DESCRIPTION,
CODE_CALLEES_DESCRIPTION,
@@ -155,9 +156,37 @@ const code_refs: Operation = {
// --- v0.34 W3: recursive code_blast + code_flow ---
+/**
+ * Stamp the same typed readiness contract code_callers/callees/def/refs carry
+ * onto a recursive walk result. Without it a bare `{result:"not_found"}` (or an
+ * `ok` walk with zero nodes) conflates a genuine miss with an unbuilt or
+ * still-indexing graph, and agents read absence of evidence as "no blast
+ * radius". Runs AFTER the traversal cache so readiness is never cached.
+ * `unsupported_language` is left untouched — it says nothing about the graph.
+ * `ambiguous` (2+ candidates) short-circuits to ready without a query.
+ */
+async function attachWalkReadiness(ctx: OperationContext, walk: WalkResult, sourceId: string | undefined) {
+ if (walk.result === 'unsupported_language') return walk;
+ const count = walk.result === 'ok'
+ ? walk.depth_groups.reduce((total, group) => total + group.nodes.length, 0)
+ : walk.result === 'ambiguous' ? walk.candidates.length : 0;
+ const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ // not_found = the seed symbol never resolved → symbol grain; anything else
+ // is about edge resolution → edge grain. Trust threaded like the siblings.
+ const readiness = await resolveCodeReadiness(ctx.engine, {
+ kind: walk.result === 'not_found' ? 'symbol' : 'edge', count, sourceId, remote: ctx.remote,
+ });
+ return {
+ ...walk,
+ status: readiness.status,
+ ready: readiness.ready,
+ ...(readiness.scoped_source_id ? { scoped_source_id: readiness.scoped_source_id } : {}),
+ };
+}
+
const code_blast: Operation = {
name: 'code_blast',
- description: 'BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Returns: {result, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:"ok", depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:"none"}.',
+ description: 'BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Trust an empty/not_found result only when ready=true; ready=false means impact is unknown and requires a safe fallback. Returns: {result, status, ready, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:"ok", status:"ready", ready:true, depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:"none"}.',
params: {
symbol: { type: 'string', required: true, description: 'Bare or qualified symbol name (e.g. "performSync" or "src/foo::performSync")' },
depth: { type: 'number', description: 'Hop cap (default 5, max 8)' },
@@ -179,7 +208,7 @@ const code_blast: Operation = {
// exactly preserving pre-fix local behavior.
const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
const sourceId = scopedSourceId ?? ctx.sourceId;
- return getCachedOrCompute(
+ const walk = await getCachedOrCompute(
ctx.engine,
{ symbol_qualified: symbol, depth, source_id: sourceId },
() => runRecursiveWalk(ctx.engine, symbol, {
@@ -190,6 +219,7 @@ const code_blast: Operation = {
exact,
}),
);
+ return attachWalkReadiness(ctx, walk, sourceId);
},
cliHints: { name: 'code_blast', hidden: true },
};
@@ -215,7 +245,7 @@ const code_flow: Operation = {
// Single trust+grant resolver (see code_blast).
const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
const sourceId = scopedSourceId ?? ctx.sourceId;
- return getCachedOrCompute(
+ const walk = await getCachedOrCompute(
ctx.engine,
{ symbol_qualified: symbol + ':flow', depth, source_id: sourceId },
() => runRecursiveWalk(ctx.engine, symbol, {
@@ -226,6 +256,7 @@ const code_flow: Operation = {
exact,
}),
);
+ return attachWalkReadiness(ctx, walk, sourceId);
},
cliHints: { name: 'code_flow', hidden: true },
};
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index aa29712690..53479d6500 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -638,6 +638,41 @@ export function federatedSearchScope(
return scope;
}
+/**
+ * #4620 — the #1712 rule on the op path: an EXPLICIT per-call `source_id`
+ * that names no live (unarchived) source fails loudly instead of silently
+ * scoping the read to a source with no rows (page_not_found with a
+ * soft-delete hint, or an empty list). Reachable because a federated_read
+ * grant / `.gbrain-source` dotfile has no FK and outlives `sources remove`.
+ * Call it AFTER `federatedSearchScope` so the grant check has already run —
+ * it can only name a source the caller was granted, never a cross-grant
+ * existence oracle. `__all__` and an omitted param skip it (nothing explicit
+ * to verify). Async on purpose: `resolveRequestedScope` stays sync for its
+ * ~10 engine-free call sites.
+ */
+export async function assertExplicitSourceLive(
+ ctx: OperationContext,
+ sourceIdParam: string | undefined,
+): Promise<void> {
+ if (sourceIdParam === undefined || sourceIdParam === ALL_SOURCES) return;
+ // Point lookup, not listAllSources (wave review): this runs on every
+ // search/query/get_page/list_pages call that names a source, and the full
+ // enumeration hauled every row's config JSONB across the wire each time.
+ // Same liveness predicate as listAllSources' default filter.
+ const live = await ctx.engine.executeRaw<{ ok: number }>(
+ `SELECT 1 AS ok FROM sources WHERE id = $1 AND archived IS NOT TRUE LIMIT 1`,
+ [sourceIdParam],
+ );
+ if (live.length > 0) return;
+ throw new OperationError(
+ 'unknown_source',
+ `source '${sourceIdParam}' does not exist (removed or archived)`,
+ 'Omit source_id to read within your grant, or pick an id from sources_list. ' +
+ 'If a .gbrain-source dotfile or a federated_read grant still names it, update them ' +
+ '(gbrain auth rescope-client <client_id>; gbrain doctor lists dangling grants).',
+ );
+}
+
/**
* #4109 — preflight a page endpoint for a same-source graph mutation
* (add_link / add_timeline_entry).
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 4c019bcb5b..870be3e866 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -177,7 +177,7 @@ const recall: Operation = {
entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first.' },
query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },
budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },
- since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only.' },
+ since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only, on event time (valid_from, falling back to created_at); composes with `entity` and `session_id`. An unparseable value is rejected (invalid_params).' },
session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (facts with superseded_by set), newest first by COALESCE(expired_at, valid_until).' },
@@ -248,8 +248,32 @@ const recall: Operation = {
let rows: FactRows = [];
+ // `since` is parsed once, up front, and a value that does not parse is
+ // rejected instead of silently widening the window: a caller that asked
+ // for "facts since T" must never receive every fact (or none) because
+ // T was malformed.
+ const since = p.since !== undefined ? parseSinceParam(p.since) : null;
+ if (p.since !== undefined && !since) {
+ throw verbError(
+ 'invalid_params',
+ `since is not a parseable timestamp or duration: "${String(p.since).slice(0, 60)}"`,
+ 'Pass an ISO 8601 datetime (e.g. "2026-08-11T00:00:00Z"), Unix epoch millis, or a duration such as "8 hours ago" / "2d".',
+ );
+ }
+ const entityParam = typeof p.entity === 'string' && p.entity.length > 0 ? (p.entity as string) : null;
+ const sessionParam = typeof p.session_id === 'string' && p.session_id.length > 0 ? (p.session_id as string) : null;
+ // Shared per-source opts for the fact-list arms (visibility, grep and the
+ // audit exclusion all filter at the ENGINE level, before each source's
+ // LIMIT, so a hidden newest row never consumes a slot).
+ const listOpts = {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ grep: grep ?? undefined,
+ excludeAuditRows: true,
+ };
+
if (p.supersessions === true) {
- const since = parseSinceParam(p.since);
// Visibility filters at the ENGINE level (before each source's LIMIT),
// same as the sibling fact-list arms — a post-merge filter would let a
// private newest row consume a limit slot and hide an older world row.
@@ -261,63 +285,49 @@ const recall: Operation = {
// valid_until) — ontology supersessions carry valid_until only.
(rec) => rec.expired_at ?? rec.valid_until ?? rec.created_at,
);
- } else if (typeof p.entity === 'string' && p.entity.length > 0) {
+ } else if (since) {
+ // Composed window: `since` ANDs onto `entity` and/or `session_id` in
+ // ONE engine query, so the time cutoff lands before the SQL LIMIT. The
+ // window is measured on EVENT time, COALESCE(valid_from, created_at),
+ // exactly like the since-only arm: "what happened to this entity (or
+ // in this session) since T" is a question about when the underlying
+ // events occurred, not about when a batch extraction wrote the rows.
const { resolveEntitySlug } = await import('../entities/resolve.ts');
rows = mergeNewest(
await Promise.all(factSources.map(async (src) => {
- const slug = (await resolveEntitySlug(ctx.engine, src, p.entity as string)) ?? (p.entity as string);
- return ctx.engine.listFactsByEntity(src, slug, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- grep: grep ?? undefined,
- excludeAuditRows: true,
+ const entitySlug = entityParam
+ ? ((await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam)
+ : undefined;
+ return ctx.engine.listFactsSince(src, since, {
+ ...listOpts,
+ eventTime: true,
+ entitySlug,
+ sessionId: sessionParam ?? undefined,
});
})),
+ byEventTime,
+ );
+ } else if (entityParam) {
+ const { resolveEntitySlug } = await import('../entities/resolve.ts');
+ rows = mergeNewest(
+ await Promise.all(factSources.map(async (src) => {
+ const slug = (await resolveEntitySlug(ctx.engine, src, entityParam)) ?? entityParam;
+ return ctx.engine.listFactsByEntity(src, slug, listOpts);
+ })),
(rec) => rec.valid_from ?? rec.created_at,
);
- } else if (typeof p.session_id === 'string' && p.session_id.length > 0) {
+ } else if (sessionParam) {
rows = mergeNewest(
await Promise.all(factSources.map(src =>
- ctx.engine.listFactsBySession(src, p.session_id as string, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- grep: grep ?? undefined,
- excludeAuditRows: true,
- }),
+ ctx.engine.listFactsBySession(src, sessionParam, listOpts),
)),
byCreated,
);
- } else if (p.since !== undefined) {
- const since = parseSinceParam(p.since);
- if (since) {
- rows = mergeNewest(
- await Promise.all(factSources.map(src =>
- ctx.engine.listFactsSince(src, since, {
- eventTime: true,
- activeOnly: !includeExpired,
- limit,
- visibility,
- grep: grep ?? undefined,
- excludeAuditRows: true,
- }),
- )),
- byEventTime,
- );
- }
} else {
// No filter: return recent across the granted source(s).
rows = mergeNewest(
await Promise.all(factSources.map(src =>
- ctx.engine.listFactsSince(src, new Date(0), {
- eventTime: true,
- activeOnly: !includeExpired,
- limit,
- visibility,
- grep: grep ?? undefined,
- excludeAuditRows: true,
- }),
+ ctx.engine.listFactsSince(src, new Date(0), { ...listOpts, eventTime: true }),
)),
byEventTime,
);
@@ -624,8 +634,30 @@ const delta: Operation = {
}
// NORMALIZE to ISO immediately (red-team F4): the raw string is echoed
// into the injectable `text` block, so an attacker-shaped-but-parseable
- // `since` must never reach rendering verbatim.
- const explicitSince = rawSince !== null ? new Date(Date.parse(rawSince)).toISOString() : null;
+ // `since` must never reach rendering verbatim. A value already in the
+ // canonical microsecond shape `listPages` projects (`next_cursor.since`
+ // passed back) is kept verbatim: rounding it through a JS Date would
+ // re-select every same-millisecond row on the resumed wake.
+ // The verbatim passthrough must round-trip: a calendar-invalid but
+ // Date.parse-able value (2026-02-31T…) would otherwise reach the
+ // ::timestamptz cast raw and surface as an engine error, not invalid_params.
+ if (
+ rawSince !== null &&
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(rawSince) &&
+ new Date(rawSince).toISOString().slice(0, 19) !== rawSince.slice(0, 19)
+ ) {
+ throw verbError(
+ 'invalid_params',
+ `delta: since is not a valid ISO 8601 calendar timestamp: "${rawSince.slice(0, 60)}"`,
+ 'Pass a real calendar datetime, e.g. since: "2026-08-11T00:00:00Z".',
+ );
+ }
+ const explicitSince =
+ rawSince === null
+ ? null
+ : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(rawSince)
+ ? rawSince
+ : new Date(Date.parse(rawSince)).toISOString();
const sessionId = typeof p.session_id === 'string' && p.session_id.trim() ? p.session_id : null;
// Cursor namespace (pre-landing review, fail-closed): 'local' is RESERVED
// for the trusted CLI/hook lane, gated on STRICT ctx.remote === false —
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index f5d2a5288e..4f87eada79 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -26,6 +26,7 @@ import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descr
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
import {
+ assertExplicitSourceLive,
enforceSubagentSlugFence,
slugOutsideCallerFence,
enforceClientSlugFence,
@@ -126,6 +127,8 @@ const get_page: Operation = {
// #3242: federatedSearchScope (not bare sourceScopeOpts) so an unqualified
// read sees pages in `federated: true` sources, matching search/query.
const sourceOpts = federatedSearchScope(ctx, sourceIdParam);
+ // #4620: an explicit source_id must name a live source (after the grant check).
+ await assertExplicitSourceLive(ctx, sourceIdParam);
const fuzzyScope = sourceOpts;
// #4352 remediation: untrusted callers never read `visibility: private`
@@ -1275,9 +1278,14 @@ const list_pages: Operation = {
// #3242 / #4400: federatedSearchScope so unqualified listing spans
// federated sources (same visibility set as search / get_page); an
// explicit per-call source_id (including '__all__') wins, same contract
- // as search/query's sourceIdParam.
- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
+ // as search/query's sourceIdParam. parseSourceIdParam (same as get_page)
+ // rejects whitespace/malformed/non-string ids loudly instead of letting
+ // them silently return [] or, for the CLI's `--source-id ""`, widen to
+ // every source.
+ const sourceIdParam = parseSourceIdParam(p.source_id, 'list_pages', { allowAll: true });
const scope = federatedSearchScope(ctx, sourceIdParam);
+ // #4620: an explicit source_id must name a live source (after the grant check).
+ await assertExplicitSourceLive(ctx, sourceIdParam);
// #4352 remediation: untrusted listing never enumerates
// `visibility: private` pages (slugs + titles are the leak surface here).
// Composes with the #4400 per-call source_id and the v0.34.1 grant scope
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 4107f6caba..6f4594e2ec 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -28,6 +28,7 @@ import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-description
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
import {
+ assertExplicitSourceLive,
federatedSearchScope,
parseSourceIdParam,
resolvePerCallMode,
@@ -206,6 +207,8 @@ const search: Operation = {
// trusted-local federated span is unchanged.
const sourceIdParam = parseSourceIdParam(p.source_id, 'search', { allowAll: true });
const scope = federatedSearchScope(ctx, sourceIdParam);
+ // #4620: an explicit source_id must name a live source (after the grant check).
+ await assertExplicitSourceLive(ctx, sourceIdParam);
// #4352 — untrusted callers never see `visibility: private` pages
// (config-gated; trusted local CLI unchanged).
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
@@ -418,6 +421,8 @@ const query: Operation = {
// #2561: unqualified trusted-local query spans federated sources (per-call
// source_id / remote grants still resolve through resolveRequestedScope).
const querySourceScope = federatedSearchScope(ctx, sourceIdParam);
+ // #4620: an explicit source_id must name a live source (after the grant check).
+ await assertExplicitSourceLive(ctx, sourceIdParam);
// #4352 — same enforcement for the full-control query op (both the image
// searchVector branch and the text hybrid path below).
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 0eab285f4e..716a059af1 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -157,7 +157,11 @@ const sources_list: Operation = {
description:
'List registered sources with page counts and remote_url. v0.28 surfaces ' +
'the new remote_url field so a remote MCP caller can confirm a source is ' +
- 'managed by clone+pull rather than user-supplied path.',
+ 'managed by clone+pull rather than user-supplied path. Results are ' +
+ "confined to the caller's resolved source scope (federated read grant > " +
+ 'bound source; #4433) and carry no marker when rows were withheld, so a ' +
+ 'listing may be incomplete. Only the trusted local CLI (`gbrain sources ' +
+ 'list`) sees the full registry.',
params: {
include_archived: { type: 'boolean', description: 'Include soft-deleted sources.' },
},
@@ -227,7 +231,9 @@ const sources_status: Operation = {
'Per-source diagnostic. Returns clone_state ("healthy" | "missing" | ' +
'"not-a-dir" | "no-git" | "url-drift" | "corrupted" | "not-applicable") ' +
'so a remote MCP caller can diagnose whether the on-disk clone is ' +
- 'syncable without SSH access to the brain host.',
+ "syncable without SSH access to the brain host. Confined to the caller's " +
+ 'resolved source scope (#4433); an out-of-scope id answers not_found, ' +
+ 'indistinguishable from a nonexistent source.',
params: {
id: { type: 'string', required: true, description: "Source id to diagnose, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
},
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 494e587080..e62a189f7e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -97,7 +97,7 @@ import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';
-import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
@@ -2051,6 +2051,8 @@ export class PGLiteEngine implements BrainEngine {
params.push(filters.updatedAfterKeyset.slug);
const slugIdx = params.length;
where.push(
+ // Exact only with a microsecond cursor (`Page.updated_at_iso`); see
+ // the Postgres engine.
`(p.updated_at > $${tsIdx}::timestamptz OR (p.updated_at = $${tsIdx}::timestamptz AND p.slug > $${slugIdx}))`,
);
} else if (filters?.updated_after) {
@@ -2099,7 +2101,7 @@ export class PGLiteEngine implements BrainEngine {
const orderBy = PAGE_SORT_SQL[sortKey];
const { rows } = await this.db.query(
- `SELECT p.* FROM pages p ${tagJoin} ${whereSql}
+ `SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p ${tagJoin} ${whereSql}
ORDER BY ${orderBy} ${limitSql}`,
params
);
@@ -4850,12 +4852,15 @@ export class PGLiteEngine implements BrainEngine {
let scope: string;
if (opts?.sourceIds && opts.sourceIds.length) { params.push(opts.sourceIds); scope = `AND source_id = ANY($${params.length})`; }
else { params.push(opts?.sourceId ?? null); scope = `AND ($${params.length}::text IS NULL OR source_id = $${params.length})`; }
+ // Page-visibility gate on the provenance page, applied BEFORE DISTINCT ON
+ // so the untrusted caller resolves the newest value they may see.
+ const privacy = opts?.excludePrivate ? `AND ${privateProvenanceFilterFragment('facts')}` : '';
const r = await this.db.query(
`SELECT DISTINCT ON (dimension) dimension, value, confidence,
source_markdown_slug AS source, valid_from, valid_until AS valid_to,
COALESCE(dim_status,'active') AS status, id AS fact_id
FROM facts
- WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL ${scope}
+ WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL ${scope} ${privacy}
AND COALESCE(valid_from,'-infinity'::timestamptz) <= COALESCE($2::timestamptz, now())
AND COALESCE(valid_until,'infinity'::timestamptz) > COALESCE($2::timestamptz, now())
AND confidence >= $3
@@ -4883,17 +4888,20 @@ export class PGLiteEngine implements BrainEngine {
});
}
- async findOntologyConflicts(opts?: { sourceId?: string; sourceIds?: string[]; minConfidence?: number }): Promise<OntologyConflict[]> {
+ async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]> {
const minConf = opts?.minConfidence ?? 0;
const params: unknown[] = [minConf];
let scope: string;
if (opts?.sourceIds && opts.sourceIds.length) { params.push(opts.sourceIds); scope = `AND source_id = ANY($${params.length})`; }
else { params.push(opts?.sourceId ?? null); scope = `AND ($${params.length}::text IS NULL OR source_id = $${params.length})`; }
+ // Same provenance-page gate as getOntology, inside the CTE so a conflict
+ // that only exists because of a hidden provenance is never reported.
+ const privacy = opts?.excludePrivate ? `AND ${privateProvenanceFilterFragment('facts')}` : '';
const r = await this.db.query(
`WITH cur AS (
SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id
FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL
- AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 ${scope}
+ AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 ${scope} ${privacy}
)
SELECT entity_slug, dimension,
json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values
@@ -5163,7 +5171,7 @@ export class PGLiteEngine implements BrainEngine {
async listFactsSince(
source_id: string,
since: Date,
- opts?: FactListOpts & { entitySlug?: string },
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
return factsImpl.listFactsSince(this.factsDeps, source_id, since, opts);
}
diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts
index f48284610f..62a26af5c0 100644
--- a/src/core/pglite-engine/facts.ts
+++ b/src/core/pglite-engine/facts.ts
@@ -347,7 +347,7 @@ export async function listFactsSince(
deps: PgliteFactsDeps,
source_id: string,
since: Date,
- opts?: FactListOpts & { entitySlug?: string },
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
const tsExpr = opts?.eventTime === true ? 'COALESCE(valid_from, created_at)' : 'created_at';
const where: string[] = [`${tsExpr} >= $since`];
@@ -356,6 +356,10 @@ export async function listFactsSince(
where.push(`entity_slug = $entitySlug`);
params.entitySlug = opts.entitySlug;
}
+ if (opts?.sessionId) {
+ where.push(`source_session = $sessionId`);
+ params.sessionId = opts.sessionId;
+ }
if (opts?.excludeAuditRows === true) {
where.push(`NOT (source = ANY($auditSources))`);
params.auditSources = [...AUDIT_ROW_SOURCES];
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index bbaa3f0d89..0aa37e0d5d 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -1035,6 +1035,25 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- extract_atoms_transcript_state (migration v146 — #4148 follow-on).
+-- Failure streak + tombstone for TRANSCRIPT extraction items, which are files
+-- and so have no page frontmatter to carry it. See src/schema.sql for the full
+-- rationale (why not raw_data, why not dream_verdicts columns, why source_id is
+-- in the key). content_hash is the 16-char prefix, matching
+-- atoms.frontmatter->>'source_hash'.
+CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (
+ source_id TEXT NOT NULL DEFAULT 'default',
+ file_path TEXT NOT NULL,
+ content_hash TEXT NOT NULL,
+ fail_count INTEGER NOT NULL DEFAULT 0,
+ tombstoned BOOLEAN NOT NULL DEFAULT FALSE,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (source_id, file_path, content_hash)
+);
+CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx
+ ON extract_atoms_transcript_state (source_id, content_hash)
+ WHERE tombstoned;
+
-- chat_usage_log (#4218 / migration v140). See src/schema.sql for rationale.
CREATE TABLE IF NOT EXISTS chat_usage_log (
id BIGSERIAL PRIMARY KEY,
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 5d9f2568a8..43963302b0 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -88,7 +88,7 @@ import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';
-import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';
@@ -1045,6 +1045,9 @@ export class PostgresEngine implements BrainEngine {
// v0.45.7 keyset (updated_at, slug) supersedes updated_after when set.
const keyset = filters?.updatedAfterKeyset;
const updatedCondition = keyset
+ // Exact only when the cursor carries the column's microseconds: callers
+ // resume from `Page.updated_at_iso` (projected below), never from a JS
+ // Date, which would re-select every row in the last row's millisecond.
? sql`AND (p.updated_at > ${keyset.updatedAt}::timestamptz OR (p.updated_at = ${keyset.updatedAt}::timestamptz AND p.slug > ${keyset.slug}))`
: updatedAfter
? sql`AND p.updated_at > ${updatedAfter}::timestamptz`
@@ -1090,7 +1093,7 @@ export class PostgresEngine implements BrainEngine {
// `app.scopes` from filters; when disabled, it's a pass-through.
return await this.withScopedReadTransaction(filters?.sourceIds, filters?.sourceId, async (tx) => {
const rows = await tx`
- SELECT p.* FROM pages p
+ SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p
${tagJoin}
WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}
@@ -4079,6 +4082,9 @@ export class PostgresEngine implements BrainEngine {
const scope = opts?.sourceIds && opts.sourceIds.length
? sql`AND source_id = ANY(${opts.sourceIds})`
: sql`AND (${opts?.sourceId ?? null}::text IS NULL OR source_id = ${opts?.sourceId ?? null})`;
+ // Page-visibility gate on the provenance page, applied BEFORE DISTINCT ON
+ // so the untrusted caller resolves the newest value they may see.
+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privateProvenanceFilterFragment('facts')}`) : sql``;
const rows = await sql<OntologyValue[]>`
SELECT DISTINCT ON (dimension)
dimension, value, confidence,
@@ -4086,7 +4092,7 @@ export class PostgresEngine implements BrainEngine {
COALESCE(dim_status, 'active') AS status, id AS fact_id
FROM facts
WHERE entity_slug = ${entitySlug} AND dimension IS NOT NULL AND expired_at IS NULL
- ${scope}
+ ${scope} ${privacy}
AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE(${asof}::timestamptz, now())
AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE(${asof}::timestamptz, now())
AND confidence >= ${minConf}
@@ -4108,19 +4114,22 @@ export class PostgresEngine implements BrainEngine {
return rows.map((r) => ({ dimension: r.dimension, entities: Number(r.entities), observations: Number(r.observations) }));
}
- async findOntologyConflicts(opts?: { sourceId?: string; sourceIds?: string[]; minConfidence?: number }): Promise<OntologyConflict[]> {
+ async findOntologyConflicts(opts?: PageReadScope & { minConfidence?: number }): Promise<OntologyConflict[]> {
const sql = this.sql;
const minConf = opts?.minConfidence ?? 0;
const scope = opts?.sourceIds && opts.sourceIds.length
? sql`AND source_id = ANY(${opts.sourceIds})`
: sql`AND (${opts?.sourceId ?? null}::text IS NULL OR source_id = ${opts?.sourceId ?? null})`;
+ // Same provenance-page gate as getOntology, inside the CTE so a conflict
+ // that only exists because of a hidden provenance is never reported.
+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privateProvenanceFilterFragment('facts')}`) : sql``;
const rows = await sql<{ entity_slug: string; dimension: string; values: OntologyConflict['values'] }[]>`
WITH cur AS (
SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id
FROM facts
WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL
AND (dim_status IS NULL OR dim_status = 'active')
- AND confidence >= ${minConf} ${scope}
+ AND confidence >= ${minConf} ${scope} ${privacy}
)
SELECT entity_slug, dimension,
json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values
@@ -4430,7 +4439,7 @@ export class PostgresEngine implements BrainEngine {
async listFactsSince(
source_id: string,
since: Date,
- opts?: FactListOpts & { entitySlug?: string },
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
return factsImpl.listFactsSince(this.factsDeps, source_id, since, opts);
}
diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts
index 3d18d193d2..19eca30638 100644
--- a/src/core/postgres-engine/facts.ts
+++ b/src/core/postgres-engine/facts.ts
@@ -349,7 +349,7 @@ export async function listFactsSince(
deps: PgFactsDeps,
source_id: string,
since: Date,
- opts?: FactListOpts & { entitySlug?: string },
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
const sql = deps.sql;
const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
@@ -359,6 +359,7 @@ export async function listFactsSince(
const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
const entitySlug = opts?.entitySlug ?? null;
+ const sessionId = opts?.sessionId ?? null;
const eventTime = opts?.eventTime === true;
const excludeAuditRows = opts?.excludeAuditRows === true;
const grepPat = grepPattern(opts);
@@ -367,6 +368,7 @@ export async function listFactsSince(
WHERE source_id = ${source_id}
AND ${eventTime ? sql`COALESCE(valid_from, created_at)` : sql`created_at`} >= ${since}
${entitySlug ? sql`AND entity_slug = ${entitySlug}` : sql``}
+ ${sessionId ? sql`AND source_session = ${sessionId}` : sql``}
${activeOnly ? sql`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sql``}
${unconsolidatedOnly ? sql`AND consolidated_at IS NULL` : sql``}
${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
diff --git a/src/core/retry.ts b/src/core/retry.ts
index 81f4768876..53945db558 100644
--- a/src/core/retry.ts
+++ b/src/core/retry.ts
@@ -93,6 +93,8 @@ export const BATCH_AUDIT_SITES = [
'extract.stale',
// #3961: atom-provenance edges banked after the completion-receipt flip.
'cycle.extract_atoms.provenance',
+ // #4589: concept<->member-atom provenance edges banked after each concept write.
+ 'cycle.synthesize_concepts.provenance',
// operations.ts MCP put_page auto-link path.
'mcp.put_page.autolink',
// sync.ts/reindex.ts orchestrator labels.
diff --git a/src/core/routing-eval.ts b/src/core/routing-eval.ts
index 9b567a14ef..ac014d2084 100644
--- a/src/core/routing-eval.ts
+++ b/src/core/routing-eval.ts
@@ -84,7 +84,7 @@ export interface RoutingCaseResult {
/**
* Normalize a string for routing comparison:
* - lowercase
- * - replace any non-alphanumeric char with a space
+ * - replace any non-letter/mark/number char with a space
* - collapse whitespace
* - trim
*
@@ -94,10 +94,18 @@ export interface RoutingCaseResult {
* a routing match should do. The cost is slightly over-permissive
* matching; the benefit is reliable matches across quote/punctuation
* variants that agents emit in practice.
+ *
+ * The character class is `\p{L}\p{M}\p{N}` (any Unicode letter, combining
+ * mark, or number) under the `u` flag, not `a-z0-9`. An ASCII-only class
+ * silently drops every non-Latin script — Korean, Chinese, Japanese,
+ * Cyrillic all collapse to an empty string, so a skill with only
+ * non-English triggers can never match any intent through this checker.
+ * `\p{M}` keeps abugida vowel signs and viramas (Devanagari, Thai) and
+ * NFD-decomposed accents attached to their base letter.
*/
export function normalizeText(s: string): string {
if (!s) return '';
- return s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
+ return s.toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu, ' ').trim();
}
/**
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index fe79b9fa2e..f088c77d19 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -794,6 +794,47 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- extract_atoms_transcript_state (migration v146 — #4148 follow-on): failure
+-- streak + tombstone for TRANSCRIPT extraction items. Pages carry this in
+-- frontmatter (atoms_fail_count / atoms_fail_hash / atoms_scan_hash), but
+-- transcripts are files with no frontmatter, so pre-fix a transcript that
+-- deterministically produced malformed output — or that honestly yielded zero
+-- atoms — re-entered discovery and re-spent LLM budget on every cycle forever.
+--
+-- Why its own table. raw_data is page-scoped (page_id NOT NULL REFERENCES
+-- pages(id)) and transcripts aren't pages, exactly as dream_verdicts' own
+-- comment notes. And NOT columns on dream_verdicts: that cache is documented
+-- rebuildable via \`gbrain dream retriage --force\`, which clears it wholesale,
+-- so extraction state stored there would be swept away as collateral.
+--
+-- Why source_id is in the key, unlike dream_verdicts. That table caches a
+-- content-level judgment ("is this transcript worth processing"), which does
+-- not vary by source. A failure streak and a tombstone GATE EXTRACTION, and
+-- extraction is source-scoped throughout the phase — discovery SQL, the NOT
+-- EXISTS idempotency subquery, and every putPage take sourceId. An unscoped
+-- tombstone would let one source permanently suppress another source's
+-- extraction of the same file.
+--
+-- content_hash is the 16-char prefix, matching atoms.frontmatter->>'source_hash'
+-- and the page-side atoms_fail_hash. Having it in the PK is what makes "a
+-- content edit resets the streak" fall out for free: an edited transcript is a
+-- different row, mirroring the page-side hash-keyed reset.
+--
+-- RLS: covered by the v35 auto_rls_on_create_table event trigger, same posture
+-- as session_context_state (v126) and chat_usage_log (v140).
+CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (
+ source_id TEXT NOT NULL DEFAULT 'default',
+ file_path TEXT NOT NULL,
+ content_hash TEXT NOT NULL,
+ fail_count INTEGER NOT NULL DEFAULT 0,
+ tombstoned BOOLEAN NOT NULL DEFAULT FALSE,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (source_id, file_path, content_hash)
+);
+CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx
+ ON extract_atoms_transcript_state (source_id, content_hash)
+ WHERE tombstoned;
+
-- chat_usage_log (#4218 / migration v140): durable per-call chat usage
-- ledger. One row per SUCCESSFUL gateway.chat() call, written fire-and-forget
-- by the chat-usage sink (src/core/ai/chat-usage.ts). cost_usd is a
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 0895d848a0..369c0c2fd8 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -26,6 +26,7 @@
import { createHash } from 'crypto';
import { CR_MODES, type CRMode } from '../types.ts';
import { getFtsLanguage } from '../fts-language.ts';
+import { loadConfigSnapshot, type BulkConfigReader } from '../config-snapshot.ts';
import { getRecipe } from '../ai/recipes/index.ts';
// #3657 seam: the runtime/mode-bundle reranker default has ONE code home
// (ai/defaults.ts — a leaf module, no SDK loads). The three bundles below
@@ -1703,20 +1704,25 @@ export const SEARCH_MODE_KEY = 'search.mode';
/**
* Load the live mode config (mode + per-key overrides) from the brain engine.
- * Runs ONE round-trip per knob currently — the BrainEngine.getConfig interface
- * is single-key. A future v0.34 batch loader can collapse this. Volume is
- * small (~8 keys); call site is once per search.
+ * 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.
*
* 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, so
- * silent fallback is the right shape.
+ * config table predates v0.32.3 and may not exist on very old brains, and an
+ * engine from outside this repo may lack the bulk read; in both cases every
+ * key falls back to a per-key getConfig(), same as before.
*/
export async function loadSearchModeConfig(
- engine: { getConfig(key: string): Promise<string | null> },
+ engine: BulkConfigReader,
): Promise<ResolveSearchModeInput> {
+ const snapshot = await loadConfigSnapshot(engine);
const safeGet = async (k: string): Promise<string | undefined> => {
try {
- const v = await engine.getConfig(k);
+ const v = snapshot ? snapshot[k] : await engine.getConfig(k);
// getConfig's contract is string | null, but guard against engines that
// return non-string junk (e.g. arrays/booleans). A non-string value is
// treated as "not set" so it falls through to the mode-bundle default,
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 8591c8ed7a..040b5351be 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -53,6 +53,20 @@ export function privateTimelineEventFilterFragment(timelineAlias: string): strin
))`;
}
+/**
+ * Fact-row twin for ontology provenance: hide an observation whose provenance
+ * page (`source_markdown_slug`, looked up in the fact's own source) is
+ * private. Non-page provenance (e.g. `manual`) has no page row and passes;
+ * deleted page rows still count (fail-closed). Keys on (facts.source_id, slug),
+ * so a provenance page living in a DIFFERENT source than the fact is not
+ * consulted — fail-open for cross-source provenance, acceptable under source
+ * isolation because ontology_propose stamps the fact with ctx.sourceId.
+ */
+export function privateProvenanceFilterFragment(factAlias: string): string {
+ return `NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id ` +
+ `AND pp.slug = ${factAlias}.source_markdown_slug AND NOT (${privatePagesFilterFragment('pp')}))`;
+}
+
/**
* Row-side twin of privatePagesFilterFragment for pages already fetched
* (get_page / fetch read one row by slug; re-querying just to filter would
diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.ts
index 678d586a30..590ee14e23 100644
--- a/src/core/search/rerank.ts
+++ b/src/core/search/rerank.ts
@@ -28,6 +28,8 @@ import type { SearchResult } from '../types.ts';
import { rerank as gatewayRerank, RerankError, type RerankInput, type RerankResult } from '../ai/gateway.ts';
import { BudgetExhausted } from '../budget/budget-tracker.ts';
import { logRerankFailure, type RerankFailureReason } from '../rerank-audit.ts';
+import { estimateTokens } from '../chunkers/token-estimate.ts';
+import { truncateUtf8 } from '../text-safe.ts';
import { warnOncePerProcess } from '../utils.ts';
/** #4648: the two audited success-shaped pass-through causes. */
@@ -85,6 +87,38 @@ function classifyRerankFailure(err: unknown): RerankFailureReason {
return 'unknown';
}
+// Per-document ceiling for the reranker call. A chunk at the chunker ceiling
+// (DEFAULT_MAX_CHUNK_TOKENS=2000, sized to llama-server's 2048 ubatch) plus the
+// query plus the server-side reranker template cannot fit that same ubatch, so
+// a pooled self-hosted reranker (llama-server, TEI) 500s and applyReranker
+// fails open to raw RRF. 1400 = 2048 minus query/template headroom minus a
+// Qwen-family tokenizer margin (cl100k estimate; Qwen runs ~35% worse on
+// hex-heavy text). The cap applies to every provider, hosted included: prose
+// chunks (~300 words) are untouched; code/CJK chunks at the chunker ceiling
+// lose up to ~1/3 of their tail before scoring — the same trade
+// DEFAULT_MAX_CHUNK_TOKENS already makes on the embed side.
+const RERANK_MAX_DOC_TOKENS = 1400;
+const RERANK_MAX_DOC_CHARS = 6000;
+
+/**
+ * Trim a reranker document to ~RERANK_MAX_DOC_TOKENS (char cap first, then
+ * shrink by measured ratio). Every cut goes through `truncateUtf8` so a shrink
+ * never orphans a UTF-16 surrogate — serde/nlohmann-based servers reject a lone
+ * surrogate in the JSON body, which would trade the 500 for a 400.
+ */
+export function capRerankDoc(text: string): string {
+ // ASCII is <=1 token/char and Qwen-family ~1 token/char on CJK, so a doc
+ // under the token ceiling in chars cannot overflow it: skip the tokenizer.
+ if (text.length <= RERANK_MAX_DOC_TOKENS) return text;
+ let doc = truncateUtf8(text, RERANK_MAX_DOC_CHARS);
+ for (let i = 0; i < 4; i++) {
+ const tokens = estimateTokens(doc);
+ if (tokens <= RERANK_MAX_DOC_TOKENS) break;
+ doc = truncateUtf8(doc, Math.floor(doc.length * (RERANK_MAX_DOC_TOKENS / tokens) * 0.95));
+ }
+ return doc;
+}
+
/**
* Reorder the top `topNIn` results by reranker relevance score. The
* un-reranked tail (any rows past topNIn) preserves its original RRF
@@ -112,7 +146,11 @@ export async function applyReranker(
// Document text — chunk_text is the matched span. Fall back to title if
// empty (shouldn't happen in practice; defensive). Empty docs would
// confuse the reranker, but we still send them — the upstream model decides.
- const documents = head.map(r => r.chunk_text || r.title || '');
+ // Cap each document so a self-hosted reranker (llama-server, TEI) with a
+ // small physical batch never 500s on an oversized code/hex-heavy chunk.
+ // Token-aware, not just char-capped, because hex-dense pages tokenize at
+ // ~1 char/token. See capRerankDoc for what this costs hosted providers.
+ const documents = head.map(r => capRerankDoc(r.chunk_text || r.title || ''));
let reranked: RerankResult[];
try {
diff --git a/src/core/sources-load.ts b/src/core/sources-load.ts
index 661756e097..6b49d124ea 100644
--- a/src/core/sources-load.ts
+++ b/src/core/sources-load.ts
@@ -16,6 +16,8 @@
* implementations even though both run identical SQL through `executeRaw`.
* A shared helper hits the bar at lower cost.
*/
+import { existsSync } from 'fs';
+import { isAbsolute } from 'path';
import type { BrainEngine } from './engine.ts';
export interface SourceRow {
@@ -154,6 +156,45 @@ export function sourceConfigHasRemoteUrl(config: unknown): boolean {
return typeof remoteUrl === 'string' && remoteUrl.trim().length > 0;
}
+function sourceHasRecoverableManagedClone(config: unknown): boolean {
+ const cfg = parseSourceConfig(config);
+ const remoteUrl = cfg.remote_url;
+ if (typeof remoteUrl !== 'string' || remoteUrl.trim().length === 0) return false;
+ return cfg.managed_clone === true;
+}
+
+/**
+ * Warning for a legacy source path that cannot be interpreted safely from a
+ * daemon context. Relative paths are ambiguous; absent absolute paths belong to
+ * another machine or an unmounted checkout unless the row is an owned remote
+ * clone that sync can safely recover by re-cloning.
+ */
+export function sourceLocalPathSkipWarning(
+ sourceId: string,
+ localPath: string,
+ pathExists: (path: string) => boolean = existsSync,
+ config: unknown = {},
+): string | null {
+ const relative = relativeSourceLocalPathSkipWarning(sourceId, localPath);
+ if (relative) return relative;
+ if (pathExists(localPath)) return null;
+ if (sourceHasRecoverableManagedClone(config)) return null;
+ return (
+ `[autopilot] skipping source '${sourceId}': local_path ` +
+ `'${localPath}' does not exist on this machine. Clone/register this ` +
+ `source locally, or let the machine that owns that checkout sync it.`
+ );
+}
+
+export function relativeSourceLocalPathSkipWarning(sourceId: string, localPath: string): string | null {
+ if (isAbsolute(localPath)) return null;
+ return (
+ `[autopilot] skipping source '${sourceId}': relative local_path ` +
+ `'${localPath}' cannot be resolved from a daemon. Re-register with an ` +
+ `absolute --path or run 'gbrain sync --source ${sourceId}' once to self-heal.`
+ );
+}
+
/** True iff the source's config.federated field is the literal boolean true. */
export function isSourceFederated(config: unknown): boolean {
const parsed = parseSourceConfig(config);
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 5c40895dfe..c56e851e53 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -190,6 +190,9 @@ export async function runMaintenanceSweep(
signal: budgetController.signal,
});
report.factsReconciled = r.factsInserted;
+ // The reconcile's refusals (FACTS_PAGE_CACHE_STALE, LOCK_TIMEOUT, …)
+ // ride r.warnings; dropped, a refused pass reads as "nothing to do".
+ for (const w of r.warnings) log(`[sweep] facts reconcile: ${w}`);
if (r.guardTriggered) skip('facts_fence_guard');
if (budgetController.signal.aborted) skip('budget_exhausted:facts_fence');
}
@@ -280,6 +283,7 @@ async function runLinksTimelinePass(
isGlobalBasenameEnabled,
isAutoLinkEnabled,
isAutoTimelineEnabled,
+ isCrossSourceLinksEnabled,
} = await import('./link-extraction.ts');
// Respect the same operator kill switches put_page's inline hooks honor.
@@ -315,7 +319,7 @@ async function runLinksTimelinePass(
// resolveCandidateSources + stampExtracted are the shared helpers the
// extract command exports precisely so sibling walkers can't drift from
// its F10 multi-source resolution (see extract.ts:114).
- const { resolveCandidateSources, stampExtracted } = await import('../commands/extract.ts');
+ const { resolveCandidateSources, stampExtracted, resolveLinkFallbackDefault } = await import('../commands/extract.ts');
const resolver = makeResolver(engine, { mode: 'batch', sourceId });
const globalBasename = await isGlobalBasenameEnabled(engine);
@@ -400,14 +404,28 @@ async function runLinksTimelinePass(
const { fetchSource, isSourceFederated } = await import('./sources-load.ts');
const sourceRow = await fetchSource(engine, sourceId);
const allowCrossSource = sourceRow !== null && isSourceFederated(sourceRow.config);
+ // #3757: thread the same `link_resolution.cross_source` opt-in (#2589) and
+ // configured default source (#4611) the CLI extract lanes pass. Without
+ // them the sweep dropped every edge into a non-default source AND its
+ // reconcile below deleted the ones `extract links --source db` created.
+ const [crossSource, linkDefaultSourceId] = await Promise.all([
+ isCrossSourceLinksEnabled(engine),
+ resolveLinkFallbackDefault(engine),
+ ]);
+ let crossSourceDrops = 0;
for (const { slug, candidates } of pageCandidates) {
for (const c of candidates) {
// #2589: a cross_source drop here means the target exists only in
- // other sources and cross-source links are off — the sweep skips it
- // exactly like the extract paths do (extract.ts counts these; the
- // sweep has no drop ledger).
- const resolved = resolveCandidateSources(c, slug, sourceId, allSlugs, slugToSources, allowCrossSource);
- if (!resolved.ok) continue;
+ // other sources and cross-source links are off — counted in the
+ // skip ledger exactly like the extract paths count it.
+ const resolved = resolveCandidateSources(
+ c, slug, sourceId, allSlugs, slugToSources, allowCrossSource,
+ { crossSource, defaultSourceId: linkDefaultSourceId },
+ );
+ if (!resolved.ok) {
+ if (resolved.reason === 'cross_source') crossSourceDrops++;
+ continue;
+ }
linkBatch.push({
from_slug: resolved.fromSlug,
to_slug: c.targetSlug,
@@ -422,6 +440,7 @@ async function runLinksTimelinePass(
});
}
}
+ if (crossSourceDrops > 0) skip('cross_source_link', crossSourceDrops);
}
// Engine batch primitives self-retry; default auditSite labels apply
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index 0c6dc7ceaf..d73b51645e 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -168,7 +168,7 @@ async function resolveTakesFilePath(
const recordedUri = rows[0]?.source_uri ?? null;
if (sourceLocalPath) {
const recordedPath =
- resolveSourceLocalFilePath(sourceLocalPath, recordedSourcePath) ??
+ resolveSourceLocalFilePath(sourceLocalPath, recordedSourcePath, slug) ??
(() => {
const fromUri = recordedPathFromFileUri(recordedUri, sourceLocalPath);
return fromUri ? join(sourceLocalPath, fromUri) : null;
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 7f426ad65b..9273093221 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -26,8 +26,7 @@ import { buildThinkSystemPrompt, buildThinkUserMessage } from './prompt.ts';
import { resolveCitations, type ParsedCitation } from './cite-render.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
import { resolveModel } from '../model-config.ts';
-import { chat as gatewayChat, probeChatModel, isThinkingByDefaultModel, type ChatResult } from '../ai/gateway.ts';
-import { getProviderCapabilities } from '../ai/capabilities.ts';
+import { chat as gatewayChat, probeChatModel, isThinkingModel, type ChatResult } from '../ai/gateway.ts';
import { AIConfigError } from '../ai/errors.ts';
import { normalizeModelId } from '../model-id.ts';
import { hasAnthropicKey } from '../ai/anthropic-key.ts';
@@ -220,9 +219,11 @@ const DEFAULT_MAX_OUTPUT_TOKENS = 4000;
// on internal reasoning before emitting any answer, so the 4000 default leaves
// `think` with empty or truncated text. Give those models headroom; providers
// bill actual tokens, not the cap. Everything else keeps 4000. Detection is
-// shared with the gateway (`isThinkingByDefaultModel`) so provider-prefixed
-// spellings (openrouter:anthropic/claude-*-5, claude-cli:*) get the same
-// treatment; think keeps its own smaller 16000 cap.
+// the gateway's `isThinkingModel` (Claude 5 by name behind any provider
+// prefix, or a recipe-declared `thinking_by_default` capability — #4172,
+// e.g. DeepSeek v4; fail-closed for unknown providers), so `think` and the
+// gateway's own output-cap default cannot drift; think keeps its own
+// smaller 16000 cap.
const THINKING_DEFAULT_MAX_OUTPUT_TOKENS = 16000;
// OpenAI reasoning models spend output budget on internal reasoning tokens
// the same way — reasoning tokens are billed as output and count against
@@ -242,22 +243,13 @@ const ANTHROPIC_CLAUDE_4X_MODEL_RE = /(?:^|[:/])(?:anthropic[:/])?claude-(?:opus
export function maxOutputTokensFor(modelStr: string): number {
const openaiReasoning =
OPENAI_REASONING_MODEL_RE.test(modelStr) && !OPENAI_CHAT_SNAPSHOT_RE.test(modelStr);
- // Shared name-based predicate (#4087: one source of truth in gateway.ts —
- // provider-prefixed + bare Claude 5 spellings, never 3.5-era models).
- if (isThinkingByDefaultModel(modelStr) || openaiReasoning || ANTHROPIC_CLAUDE_4X_MODEL_RE.test(modelStr)) {
- return THINKING_DEFAULT_MAX_OUTPUT_TOKENS;
- }
- // Recipe-declared thinking-by-default (gbrain#4172, e.g. DeepSeek v4):
- // keyed on the capability, not a model-name regex, so a provider's model
- // renames don't silently drop the headroom. Reasoning bills as output and
+ // Shared predicate (#4087 one source of truth in gateway.ts: Claude 5 by
+ // name — provider-prefixed or bare, never 3.5-era — OR the recipe-declared
+ // thinking_by_default capability, #4172). Reasoning bills as output and
// counts against max_tokens; without headroom the 4000 cap is spent on
// reasoning and think returns truncated/empty JSON.
- try {
- if (getProviderCapabilities(modelStr).supportsThinking) {
- return THINKING_DEFAULT_MAX_OUTPUT_TOKENS;
- }
- } catch {
- // Unknown provider / chat-less recipe — keep the conservative default.
+ if (isThinkingModel(modelStr) || openaiReasoning || ANTHROPIC_CLAUDE_4X_MODEL_RE.test(modelStr)) {
+ return THINKING_DEFAULT_MAX_OUTPUT_TOKENS;
}
return DEFAULT_MAX_OUTPUT_TOKENS;
}
diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.ts
index f09817a364..d3a0921137 100644
--- a/src/core/transcripts/claude-code.ts
+++ b/src/core/transcripts/claude-code.ts
@@ -36,6 +36,22 @@ const CLAUDE_CONTROL_TYPES = new Set([
'attachment',
]);
+/**
+ * True for a Claude Code SUBAGENT log:
+ * `<project>/<session-uuid>/subagents/agent-<id>.jsonl`. Every line in one is
+ * `isSidechain` (the parser skips them all, so the file parses to zero turns)
+ * 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.
+ */
+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);
+}
+
/** Keys that mark a Claude Code project transcript. */
function looksLikeClaudeLine(obj: Record<string, unknown>): boolean {
if (
diff --git a/src/core/transcripts/codex-hook-lane.ts b/src/core/transcripts/codex-hook-lane.ts
index e8d52009b0..12af423c20 100644
--- a/src/core/transcripts/codex-hook-lane.ts
+++ b/src/core/transcripts/codex-hook-lane.ts
@@ -11,10 +11,12 @@
*
* Confinement [S3#8]: the SessionEnd stdin payload is codex-supplied and an
* agent-steerable input; `transcript_path` is confined to the pinned rollout
- * store (codexSessionsDir — CODEX_HOME-resolved, since the spawner IS codex)
- * with the same ladder as the claude root. No WSL cross-OS branch v1
- * (uncharacterized for codex; the reason codes are shared so widening later
- * is additive).
+ * stores (codexSessionsDir AND codexArchivedSessionsDir — both CODEX_HOME-
+ * resolved, since the spawner IS codex) with the same ladder as the claude
+ * root. Archived rollouts are inside the fence because codex MOVES a rollout
+ * there on archive: fencing only the live store refused a still-valid path as
+ * outside_projects_dir. No WSL cross-OS branch v1 (uncharacterized for codex;
+ * the reason codes are shared so widening later is additive).
*
* Engine-free by construction: node:fs/path + host-specs + codex.ts only —
* never discover.ts (it imports BrainEngine); discovery is reimplemented
@@ -31,7 +33,7 @@
import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
import { join } from 'node:path';
-import { codexSessionsDir } from '../bootstrap/host-specs.ts';
+import { codexArchivedSessionsDir, codexSessionsDir } from '../bootstrap/host-specs.ts';
import { isPathContained } from '../path-confine.ts';
import type { ConfineTranscriptResult, ParsedTranscript, ToolCallRecord } from './claude-code-jsonl.ts';
import { capToolCallInput, TRANSCRIPT_HARD_CAP_BYTES, TRANSCRIPT_MAX_BYTES_DEFAULT } from './claude-code-jsonl.ts';
@@ -45,30 +47,55 @@ const HOOK_HEAD_WINDOW_BYTES = 256 * 1024;
/**
* Validate an untrusted codex `transcript_path` from hook stdin — the same
* ladder as claude's confineTranscriptPath, rooted at the codex rollout
- * store. `opts.root` is a TEST SEAM only; production callers use the pinned
- * default.
+ * stores (live + archived). `opts.root` / `opts.archivedRoot` are a TEST SEAM
+ * only; production callers use the pinned defaults.
*/
export function confineCodexTranscriptPath(
p: unknown,
- opts: { root?: string; maxBytes?: number } = {},
+ opts: { root?: string; archivedRoot?: string; maxBytes?: number } = {},
): ConfineTranscriptResult {
if (typeof p !== 'string' || p.length === 0) return { ok: false, reason: 'missing_path' };
if (!p.endsWith('.jsonl')) return { ok: false, reason: 'not_jsonl' };
let st: ReturnType<typeof lstatSync>;
try {
st = lstatSync(p);
- } catch {
+ } catch (err) {
+ // ENOENT (nothing at the path) and ENOTDIR (a path component is a file,
+ // so the path cannot exist AS GIVEN) both mean "no such transcript",
+ // which is the rung hook.ts gates its discovery fallback on. Collapsing
+ // them into `unreadable` — a permission/IO fault the caller must NOT
+ // paper over — is what left a moved rollout unrecoverable. Discovery is
+ // itself id-filtered and root-confined, so routing ENOTDIR there bounds
+ // the blast radius of a malformed payload.
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code === 'ENOENT' || code === 'ENOTDIR') return { ok: false, reason: 'missing_path' };
return { ok: false, reason: 'unreadable' };
}
if (st.isSymbolicLink()) return { ok: false, reason: 'symlink' };
if (!st.isFile()) return { ok: false, reason: 'not_file' };
const cap = opts.maxBytes ?? TRANSCRIPT_HARD_CAP_BYTES;
if (st.size > cap) return { ok: false, reason: 'too_large' };
- const root = opts.root ?? codexSessionsDir();
- if (!isPathContained(p, root)) return { ok: false, reason: 'outside_projects_dir' };
+ const [root, archivedRoot] = codexRootsFor(opts);
+ const contained =
+ isPathContained(p, root) || (archivedRoot !== undefined && isPathContained(p, archivedRoot));
+ if (!contained) return { ok: false, reason: 'outside_projects_dir' };
return { ok: true, path: p, size: st.size };
}
+/**
+ * The confinement/discovery roots for a call. Production (no pinned `root`)
+ * gets BOTH codex-owned stores — live and archived. An explicitly pinned
+ * `root` stays single-root unless `archivedRoot` is pinned too, so the test
+ * seam can never be widened by the widening itself.
+ */
+function codexRootsFor(opts: {
+ root?: string;
+ archivedRoot?: string;
+}): [live: string, archived: string | undefined] {
+ if (opts.root) return [opts.root, opts.archivedRoot];
+ return [codexSessionsDir(), opts.archivedRoot ?? codexArchivedSessionsDir()];
+}
+
export interface ParsedCodexTranscript extends ParsedTranscript {
/** From session_meta (byte 0), surviving even head+tail reads — the stdin
* fallback when the payload's own session_id is missing. */
@@ -184,21 +211,25 @@ export function parseCodexHookTranscript(
const DISCOVERY_DIRENT_CAP = 4096;
/**
- * Bounded newest-first discovery over the rollout store — the fallback for a
- * SessionEnd payload whose transcript_path is null, and the sweep seam for
- * SIGKILL'd sessions (SessionEnd never fires on SIGKILL). Fs-only walk:
- * newest 2 year dirs → newest 2 month dirs → newest 3 day dirs →
- * rollout-*.jsonl files (symlinks rejected). With a session id, the filename
- * must contain it (codex embeds the id in rollout filenames — verified
- * 0.147.0); without one, newest mtime wins and the caller's degrade names
- * the weaker match. Every miss is a typed reason at the caller — discovery
- * is never silent.
+ * Bounded newest-first discovery over the rollout stores — the fallback for a
+ * SessionEnd payload whose transcript_path is null or has MOVED (archived),
+ * and the sweep seam for SIGKILL'd sessions (SessionEnd never fires on
+ * SIGKILL). Fs-only walk of the live store: newest 2 year dirs → newest 2
+ * month dirs → newest 3 day dirs → rollout-*.jsonl files (symlinks
+ * rejected), then a FLAT pass over the archived store, both under one dirent
+ * budget. With a session id, the filename must contain it (codex embeds the
+ * id in rollout filenames — verified 0.147.0); without one, newest mtime
+ * wins across BOTH stores and the caller's degrade names the weaker match.
+ * An id-matched archived hit is a MATCH, not a guess — hook.ts reads
+ * `transcript_discovered_newest` as "guessed" and suppresses the relay on it,
+ * so the archived pass must never relabel a real match. Every miss is a typed
+ * reason at the caller — discovery is never silent.
*/
export function discoverNewestCodexRollout(
sessionId: string | null,
- opts: { root?: string } = {},
+ opts: { root?: string; archivedRoot?: string } = {},
): { path: string; degrade: 'transcript_discovered' | 'transcript_discovered_newest' } | null {
- const root = opts.root ?? codexSessionsDir();
+ const [root, archivedRoot] = codexRootsFor(opts);
let seen = 0;
const numericDesc = (dir: string, take: number): string[] => {
try {
@@ -212,32 +243,48 @@ export function discoverNewestCodexRollout(
return [];
}
};
+ const rolloutsIn = (dir: string): string[] => {
+ try {
+ return readdirSync(dir).filter((f) => f.startsWith('rollout-') && f.endsWith('.jsonl'));
+ } catch {
+ return [];
+ }
+ };
let best: { path: string; mtimeMs: number } | null = null;
- for (const y of numericDesc(root, 2)) {
+ /** Fold one directory's rollouts into `best`; true means the cap tripped. */
+ const consider = (dir: string, files: string[]): boolean => {
+ for (const f of files) {
+ if (++seen > DISCOVERY_DIRENT_CAP) return true;
+ if (sessionId && !f.includes(sessionId)) continue;
+ const p = join(dir, f);
+ try {
+ const st = lstatSync(p);
+ if (st.isSymbolicLink() || !st.isFile()) continue;
+ if (!best || st.mtimeMs > best.mtimeMs) best = { path: p, mtimeMs: st.mtimeMs };
+ } catch {
+ /* raced away — skip */
+ }
+ }
+ return false;
+ };
+
+ let capped = false;
+ dated: for (const y of numericDesc(root, 2)) {
for (const m of numericDesc(join(root, y), 2)) {
for (const d of numericDesc(join(root, y, m), 3)) {
const day = join(root, y, m, d);
- let files: string[];
- try {
- files = readdirSync(day).filter((f) => f.startsWith('rollout-') && f.endsWith('.jsonl'));
- } catch {
- continue;
- }
- for (const f of files) {
- if (++seen > DISCOVERY_DIRENT_CAP) return best ? finish(best, sessionId) : null;
- if (sessionId && !f.includes(sessionId)) continue;
- const p = join(day, f);
- try {
- const st = lstatSync(p);
- if (st.isSymbolicLink() || !st.isFile()) continue;
- if (!best || st.mtimeMs > best.mtimeMs) best = { path: p, mtimeMs: st.mtimeMs };
- } catch {
- /* raced away — skip */
- }
+ if (consider(day, rolloutsIn(day))) {
+ capped = true;
+ break dated;
}
}
}
}
+ // The archived store is FLAT — no YYYY/MM/DD — so the dated walk above can
+ // never reach it (see codexArchivedSessionsDir). Scanned under the SAME
+ // dirent budget, and skipped entirely once the cap has tripped so a
+ // pathological live store still degrades to "not found", never a hang.
+ if (!capped && archivedRoot) consider(archivedRoot, rolloutsIn(archivedRoot));
return best ? finish(best, sessionId) : null;
}
diff --git a/src/core/transcripts/discover.ts b/src/core/transcripts/discover.ts
index 9dfecd41e2..76046bac12 100644
--- a/src/core/transcripts/discover.ts
+++ b/src/core/transcripts/discover.ts
@@ -23,6 +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 { isClaudeCliSelfTranscriptPath } from '../ai/providers/claude-cli-scratch.ts';
export interface DiscoveredFile {
@@ -92,6 +93,11 @@ export function discoverTranscriptFiles(roots?: HarnessRoot[], opts: DiscoverOpt
// bare-UUID directory segment in another harness's tree must never
// hide that harness's legitimate sessions.
if (format === 'grok' && !isGrokChatHistoryFile(p)) continue;
+ // #4796: Claude Code subagent logs (<session>/subagents/agent-*.jsonl)
+ // are all-isSidechain — they parse to zero turns and carry the PARENT
+ // 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;
// #4472: skip gbrain's own claude-cli subprocess sessions (see
// DiscoverOpts.includeSelf) — the scratch-cwd fingerprint survives
// Claude Code's project-dir slugification.
@@ -149,6 +155,81 @@ export async function indexImportedSessions(
return { byHarness, pagesScanned };
}
+/**
+ * Normalize a session identifier so the two names the pipeline gives the same
+ * session compare equal. The conversation page stamps
+ * `transcript_import.session_id` (`20260720_071844_e91dbe`); the corpus file
+ * on disk is named from the same parts with a different separator
+ * (`2026-07-20-071844-e91dbe.md`). Dropping separators and case makes them
+ * comparable without teaching this module either harness's naming scheme.
+ * Identity-safe for the JSONL harnesses too, where the basename stem already
+ * IS the session id (normalizing both sides is a no-op on a match).
+ */
+function sessionKey(raw: string): string {
+ return raw.toLowerCase().replace(/[-_]/g, '');
+}
+
+export interface TranscriptPageIndex {
+ /**
+ * normalized session key → conversation page slugs. A session that split
+ * across parts renders one page per part, all stamped with the same
+ * session_id, so this is one-to-many by design.
+ */
+ bySessionKey: Map<string, string[]>;
+ pagesScanned: number;
+}
+
+/**
+ * Reverse of `indexImportedSessions`: maps a session back to the conversation
+ * PAGE(S) it was rendered into, so a caller holding only a transcript file
+ * path can find the page to attribute it to. Same one-query, frontmatter-only
+ * discipline — conversation bodies run to ~300KB per part and must not be
+ * streamed to read two keys.
+ */
+export async function indexTranscriptPages(
+ engine: BrainEngine,
+ sourceId: string,
+): Promise<TranscriptPageIndex> {
+ const bySessionKey = new Map<string, string[]>();
+ let pagesScanned = 0;
+ const rows = await engine.executeRaw<{ slug: string; frontmatter: unknown }>(
+ `SELECT slug, frontmatter FROM pages
+ WHERE type = 'conversation' AND source_id = $1 AND deleted_at IS NULL`,
+ [sourceId],
+ );
+ for (const row of rows) {
+ pagesScanned++;
+ const fm = (typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter) as
+ | Record<string, unknown>
+ | null;
+ const ti = fm?.transcript_import as { session_id?: string } | undefined;
+ if (!ti || typeof ti.session_id !== 'string' || ti.session_id === '') continue;
+ const key = sessionKey(ti.session_id);
+ if (key === '') continue;
+ const slugs = bySessionKey.get(key);
+ if (slugs) slugs.push(row.slug);
+ else bySessionKey.set(key, [row.slug]);
+ }
+ return { bySessionKey, pagesScanned };
+}
+
+/**
+ * The conversation page(s) a transcript file was rendered into, or [] when the
+ * transcript has not been imported as a page. Matches on the basename stem,
+ * which every supported harness derives from the session id. That
+ * includes the `<session_id>.txt` corpus files gbrain's own hook capture writes
+ * (hook.ts); compaction segments (`<sid>.seg-<hash>.txt`) are not matched.
+ */
+export function resolveTranscriptPageSlugs(
+ filePath: string,
+ index: TranscriptPageIndex,
+): string[] {
+ const base = filePath.split(/[/\\]/).pop() ?? '';
+ const stem = base.replace(/\.(md|markdown|txt|jsonl|json)$/i, '');
+ if (stem === '') return [];
+ return index.bySessionKey.get(sessionKey(stem)) ?? [];
+}
+
/**
* JSONL harnesses name the session in the file basename (claude-code /
* openclaw uuid.jsonl, codex rollout-<id>.jsonl). Grok does not: the
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index 2bb528ddae..c9b45d2a88 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -270,6 +270,12 @@ export async function runTranscriptsIngest(
if (opts.dryRun) {
outcome.statuses = rendered.parts.map(() => 'planned' as const);
result.pages.planned += rendered.parts.length;
+ // #4762: a planned session is new work too, so the --limit gate
+ // above truncates the preview like the real run. A dry run cannot
+ // see hash-skips (no engine reads), so `--dry-run --limit N` shows
+ // the first N eligible sessions — an upper bound on what the write
+ // path would import.
+ newWorkSessions++;
} else {
// The RESOLVED base slug: identity dedup can resolve part 1 to an
// EXISTING page under a different slug (same session id, changed
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index feed32e1d3..f0356edb7b 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -200,6 +200,22 @@ export function escapeAnchorLines(text: string): string {
.join('\n');
}
+/**
+ * Neutralize QUOTED facts/takes fence markers in a message body:
+ * `gbrain:facts:begin` → `gbrain\:facts:begin`. A session that read another
+ * page (context pack, get_page) quotes that page's `<!--- gbrain:facts:begin -->`
+ * verbatim, and the per-message char cap routinely keeps the begin marker
+ * while dropping the end — a live, unbalanced fence on a transcript page that
+ * has no fence (FACTS_FENCE_UNBALANCED on every dream cycle), or a quoted
+ * fence indexed as the transcript's own facts. Every fence consumer is an
+ * exact-substring matcher on the marker token, so the backslash lands INSIDE
+ * the token (a leading space would not break them); the text stays readable
+ * and greppable, matching the backslash idiom of escapeAnchorLines (#4821).
+ */
+export function escapeFenceMarkers(text: string): string {
+ return text.replace(/gbrain:(facts|takes):(begin|end)/g, 'gbrain\\:$1:$2');
+}
+
export interface RenderedPart {
slug: string;
/** Full page content: YAML frontmatter + body. */
@@ -266,7 +282,7 @@ export function renderSessionParts(
const blocks: string[] = messages.map((m) => {
const ts = m.timestamp || lastTs;
lastTs = ts;
- const text = escapeAnchorLines(truncateUtf8(m.text, MESSAGE_CHAR_CAP));
+ const text = escapeFenceMarkers(escapeAnchorLines(truncateUtf8(m.text, MESSAGE_CHAR_CAP)));
const [head, ...rest] = text.split('\n');
const anchor = `**${speakerLabel(m)}** (${anchorTimestamp(ts)}): ${head}`;
return rest.length ? `${anchor}\n${rest.join('\n')}` : anchor;
diff --git a/src/core/types.ts b/src/core/types.ts
index 241f39e325..509a5830e7 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -95,6 +95,14 @@ export interface Page {
emotional_weight?: number;
created_at: Date;
updated_at: Date;
+ /**
+ * `updated_at` at the column's microsecond precision, as an ISO string
+ * (`2026-08-10T12:00:00.000123Z`). Projected by `listPages` so keyset
+ * callers can resume from the exact row (`updatedAfterKeyset.updatedAt`);
+ * a JS Date holds milliseconds only and would re-select every row in the
+ * last row's millisecond. Absent on paths that do not project it.
+ */
+ updated_at_iso?: string;
/**
* v0.26.5: when present, the page is soft-deleted. Hidden from search and
* from `getPage` / `listPages` by default; surface via `include_deleted: true`.
@@ -305,9 +313,12 @@ export interface PageFilters {
* v0.45.7 — keyset cursor for deterministic pagination through pages sharing
* one `updated_at`. `WHERE p.updated_at > ts OR (p.updated_at = ts AND
* p.slug > slug)`. Supersedes `updated_after` when set; pair with
- * `sort: 'updated_asc'` (total order). Used by the `delta` verb's session
+ * `sort: 'updated_asc'` (a total order: updated_at, slug, source_id, id —
+ * slug alone is unique only per source). Used by the `delta` verb's session
* cursor so a >limit same-timestamp cluster pages cleanly instead of
- * livelocking. `slug` empty ⇒ start of the `ts` bucket.
+ * livelocking. `slug` empty ⇒ start of the `ts` bucket. `updatedAt` should
+ * be the row's `updated_at_iso` (column precision); a millisecond-rounded
+ * value re-selects same-millisecond rows.
*/
updatedAfterKeyset?: { updatedAt: string; slug: string };
/**
@@ -396,9 +407,16 @@ export const PAGE_SORT_SQL: Record<NonNullable<PageFilters['sort']>, string> = {
// cluster of pages sharing one updated_at (bulk syncs stamp identical
// now() across a transaction). Without the tiebreaker, rows at the same
// timestamp order arbitrarily and a >limit tie cluster is unpageable.
- updated_asc: 'p.updated_at ASC, p.slug ASC',
+ // The cursor must carry the column's microsecond precision to be exact:
+ // resume from `Page.updated_at_iso`, never from a JS Date. Slug is unique
+ // only per source, so a federated listing needs source_id + id behind it to
+ // stay a total order (same tiebreakers as `slug` below).
+ updated_asc: 'p.updated_at ASC, p.slug ASC, p.source_id ASC, p.id ASC',
created_desc: 'p.created_at DESC',
- slug: 'p.slug ASC',
+ // Slug uniqueness is per (source_id, slug), so a federated listing can hold
+ // the same slug from several sources; source_id + id make slug+offset paging
+ // a TOTAL order (same class as the updated_asc tiebreaker above).
+ slug: 'p.slug ASC, p.source_id ASC, p.id ASC',
};
/**
@@ -1605,7 +1623,12 @@ export interface OntologyConflict {
dimension: string;
values: { value: string; source: string | null; confidence: number; fact_id: number }[];
}
-export interface OntologyReadOpts {
+// excludePrivate (from PageReadScope) drops observations whose provenance page
+// is `visibility: private` BEFORE per-dimension resolution, so an untrusted
+// caller resolves the newest value they may see — never a private one, never
+// a hole where one was. Set by the op layer (readPolicyOpts); engines never
+// decide trust.
+export interface OntologyReadOpts extends PageReadScope {
asof?: string;
minConfidence?: number;
includeQuarantined?: boolean;
diff --git a/src/core/utils.ts b/src/core/utils.ts
index 86199fa254..b9ae15538c 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -225,6 +225,8 @@ export function rowToPage(row: Record<string, unknown>): Page {
emotional_weight: row.emotional_weight == null ? undefined : Number(row.emotional_weight),
created_at: new Date(row.created_at as string),
updated_at: new Date(row.updated_at as string),
+ // Microsecond-exact ISO, projected by listPages for keyset resumption.
+ ...(row.updated_at_iso !== undefined && { updated_at_iso: String(row.updated_at_iso) }),
...(deletedAt !== undefined && { deleted_at: deletedAt }),
// v0.29.1 (columns added in migration v41). Optional in SELECT projection.
...(effectiveDate !== undefined && { effective_date: effectiveDate }),
diff --git a/src/core/worker-pool.ts b/src/core/worker-pool.ts
index be4168ea0d..7e74120acb 100644
--- a/src/core/worker-pool.ts
+++ b/src/core/worker-pool.ts
@@ -60,7 +60,7 @@
* The helper checks `err.tag` against `MUST_ABORT_ERROR_TAGS` BEFORE
* dispatching to onError. Matched errors: set aborted=true, call
* AbortController.abort() (propagates to in-flight onItem via
- * `signal`), rethrow. This makes "cap is a hard ceiling" a structural
+ * `signal`), join the remaining workers, rethrow. This makes "cap is a hard ceiling" a structural
* property of the helper, not a per-caller convention.
*
* Future tagged classes (UnrecoverableError, etc.) add their tag to
@@ -171,6 +171,11 @@ export interface SlidingPoolResult {
* Empty `items` returns immediately with zeroed result. Worker count
* is clamped to `[1, items.length]` so we never spawn more workers
* than work.
+ *
+ * A must-abort error from an item (BudgetExhausted etc.) stops claiming,
+ * aborts the local signal so sibling workers finish their current item and
+ * stop, waits for every worker, then rethrows the error. No worker is left
+ * running detached after the pool has reported failure.
*/
export async function runSlidingPool<T>(opts: SlidingPoolOpts<T>): Promise<SlidingPoolResult> {
const items = opts.items;
@@ -207,6 +212,10 @@ export async function runSlidingPool<T>(opts: SlidingPoolOpts<T>): Promise<Slidi
// that put an `await` between the `nextIdx` read and write OR import
// `worker_threads` alongside this module.
let nextIdx = 0;
+ // First must-abort error. Recorded by the worker that saw it, rethrown
+ // after every worker has finished its current item. (A holder object: TS
+ // does not see assignments made inside the worker closure.)
+ const mustAbort: { failure: { error: unknown } | null } = { failure: null };
async function worker(workerIdx: number): Promise<void> {
while (true) {
@@ -226,14 +235,16 @@ export async function runSlidingPool<T>(opts: SlidingPoolOpts<T>): Promise<Slidi
opts.onProgress?.(result.processed, total);
} catch (err) {
// D13: must-abort error classes (BudgetExhausted, etc.) bypass
- // onError and hard-abort the pool. Rethrowing propagates up
- // through Promise.all; the local abort signals other workers.
+ // onError and hard-abort the pool: the local abort signals the
+ // other workers, every worker finishes its current item, and the
+ // error is rethrown after the join (see the function doc).
if (isMustAbortError(err)) {
result.aborted = true;
result.errored++;
result.failures.push({ idx, label: labelFn(item), error: err });
+ if (!mustAbort.failure) mustAbort.failure = { error: err };
localAbort.abort();
- throw err;
+ return;
}
result.errored++;
result.failures.push({ idx, label: labelFn(item), error: err });
@@ -255,7 +266,7 @@ export async function runSlidingPool<T>(opts: SlidingPoolOpts<T>): Promise<Slidi
} finally {
if (opts.signal) opts.signal.removeEventListener('abort', onCallerAbort);
}
-
+ if (mustAbort.failure) throw mustAbort.failure.error;
return result;
}
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index 13f4c5fb38..7b77d086b3 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -306,7 +306,7 @@ export async function resolvePageWriteTarget(
}
filePath = recordedPath
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- result passes isWriteTargetContained before any write (#4204/#4289 guard)
- ? resolveSourceLocalFilePath(sourceLocalPath, recordedPath) ?? join(sourceLocalPath, `${slug}.md`)
+ ? resolveSourceLocalFilePath(sourceLocalPath, recordedPath, slug) ?? join(sourceLocalPath, `${slug}.md`)
: join(sourceLocalPath, recordedPathFromFileUri(recordedUri, sourceLocalPath) ?? `${slug}.md`); // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- result passes isWriteTargetContained before any write (#4204/#4289 guard)
writeRoot = sourceLocalPath;
scanRoot = sourceLocalPath;
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index 4d0b795b69..dd41be83f9 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -24,7 +24,6 @@ import { loadConfig } from '../core/config.ts';
import {
resolveSocketPathForConfig,
startResolveIpcServer,
- cleanupStaleSocket,
ensureIpcSecretForConfig,
type IpcHandlers,
} from '../core/context/resolve-ipc.ts';
@@ -234,8 +233,9 @@ export async function bindResolveIpcForServe(
close: () => {
if (closed) return;
closed = true;
+ // server.close() unlinks the pathname THIS listener bound; never
+ // blind-unlink the path — it may belong to a newer live serve (#4896).
try { server.close(); } catch { /* noop */ }
- cleanupStaleSocket(resolveSocket);
},
};
} catch {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index e9ba87e547..743544a539 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -17,6 +17,7 @@ import { bindResolveIpcForServe } from './resolve-ipc-binding.ts';
import { resolveMcpInstructions } from './instructions.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';
+import { assertStdioSourceBindable } from './source-preflight.ts';
export async function resolveMcpStdioSourceScope(
engine: BrainEngine,
@@ -173,6 +174,9 @@ export async function trackStdioRpc<T>(work: () => Promise<T>): Promise<T> {
export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean } = {}) {
const config = loadConfig();
+ // Refuse to serve a well-formed GBRAIN_SOURCE that no active source row
+ // backs (see source-preflight.ts). Throws before any transport is attached.
+ await assertStdioSourceBindable(engine);
// MEMORY_VERBS v1 surface mode: 'full' (default — every op, byte-identical
// to pre-surface behavior), 'starter' (WP4 daily-driver set), or 'verbs'
// (exactly the 7 protocol verbs). Enforced BOTH on the advertised list and
diff --git a/src/mcp/source-preflight.ts b/src/mcp/source-preflight.ts
new file mode 100644
index 0000000000..f5a12b0a28
--- /dev/null
+++ b/src/mcp/source-preflight.ts
@@ -0,0 +1,56 @@
+import type { BrainEngine } from '../core/engine.ts';
+import { isValidSourceId, ALL_SOURCES } from '../core/source-id.ts';
+import { isEngineDegraded } from '../core/degraded-marker.ts';
+
+/**
+ * Stdio-lane preflight: a well-formed `GBRAIN_SOURCE` that names NO active
+ * registered source must not serve.
+ *
+ * Why: `resolveMcpStdioSourceScope` deliberately passes a well-formed-but-
+ * unknown env value through as tier 'env' so the opt-in `--source-guard` can
+ * produce its actionable envelope. Without the flag, nothing catches it:
+ * every read scopes to a source that holds zero pages (search/query return
+ * `[]` even with `__all__`) and every write dies on `facts_source_id_fkey`.
+ * A stale `GBRAIN_SOURCE` in a harness MCP config blinds the whole lane
+ * while every health check stays green. Fail loudly at startup instead —
+ * the same posture the CLI env tier already takes (`assertSourceExists` in
+ * source-resolver.ts, whose `archived = false` predicate this mirrors).
+ *
+ * Scope: only the stdio server calls this. HTTP tokens carry their own
+ * source grant. `__all__` and malformed values keep their existing handling
+ * (malformed already falls back to the seed tier in the resolver).
+ * A transient engine error does NOT block startup — this guards config, not
+ * connectivity — and a degraded engine is never touched, so a boot under
+ * the degraded proxy does not spend its reconnect attempt here.
+ */
+export async function assertStdioSourceBindable(
+ engine: BrainEngine,
+ env: string | undefined = process.env.GBRAIN_SOURCE,
+): Promise<void> {
+ if (!env) return;
+ if (env === ALL_SOURCES || !isValidSourceId(env)) return;
+ if (isEngineDegraded(engine)) return;
+ let rows: Array<{ id: string }>;
+ try {
+ rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id = $1 AND archived = false`,
+ [env],
+ );
+ } catch (e) {
+ // Fail-open by design (this guards config, not connectivity) — but never
+ // silently: an operator debugging a blind stdio lane needs to know the
+ // preflight did not run.
+ process.stderr.write(
+ `[gbrain] GBRAIN_SOURCE preflight skipped (could not read sources): ${e instanceof Error ? e.message : String(e)}\n`,
+ );
+ return;
+ }
+ if (rows.length === 0) {
+ throw new Error(
+ `GBRAIN_SOURCE="${env}" is not a registered active source (missing or archived); ` +
+ `refusing to serve a phantom scope (reads would return nothing, writes would fail ` +
+ `on the sources foreign key). Run \`gbrain sources list\`, then set GBRAIN_SOURCE ` +
+ `to a listed id or unset it.`,
+ );
+ }
+}
diff --git a/src/schema.sql b/src/schema.sql
index 203fae90e8..ffcd49e10e 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -790,6 +790,47 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- extract_atoms_transcript_state (migration v146 — #4148 follow-on): failure
+-- streak + tombstone for TRANSCRIPT extraction items. Pages carry this in
+-- frontmatter (atoms_fail_count / atoms_fail_hash / atoms_scan_hash), but
+-- transcripts are files with no frontmatter, so pre-fix a transcript that
+-- deterministically produced malformed output — or that honestly yielded zero
+-- atoms — re-entered discovery and re-spent LLM budget on every cycle forever.
+--
+-- Why its own table. raw_data is page-scoped (page_id NOT NULL REFERENCES
+-- pages(id)) and transcripts aren't pages, exactly as dream_verdicts' own
+-- comment notes. And NOT columns on dream_verdicts: that cache is documented
+-- rebuildable via `gbrain dream retriage --force`, which clears it wholesale,
+-- so extraction state stored there would be swept away as collateral.
+--
+-- Why source_id is in the key, unlike dream_verdicts. That table caches a
+-- content-level judgment ("is this transcript worth processing"), which does
+-- not vary by source. A failure streak and a tombstone GATE EXTRACTION, and
+-- extraction is source-scoped throughout the phase — discovery SQL, the NOT
+-- EXISTS idempotency subquery, and every putPage take sourceId. An unscoped
+-- tombstone would let one source permanently suppress another source's
+-- extraction of the same file.
+--
+-- content_hash is the 16-char prefix, matching atoms.frontmatter->>'source_hash'
+-- and the page-side atoms_fail_hash. Having it in the PK is what makes "a
+-- content edit resets the streak" fall out for free: an edited transcript is a
+-- different row, mirroring the page-side hash-keyed reset.
+--
+-- RLS: covered by the v35 auto_rls_on_create_table event trigger, same posture
+-- as session_context_state (v126) and chat_usage_log (v140).
+CREATE TABLE IF NOT EXISTS extract_atoms_transcript_state (
+ source_id TEXT NOT NULL DEFAULT 'default',
+ file_path TEXT NOT NULL,
+ content_hash TEXT NOT NULL,
+ fail_count INTEGER NOT NULL DEFAULT 0,
+ tombstoned BOOLEAN NOT NULL DEFAULT FALSE,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (source_id, file_path, content_hash)
+);
+CREATE INDEX IF NOT EXISTS extract_atoms_transcript_state_tombstoned_idx
+ ON extract_atoms_transcript_state (source_id, content_hash)
+ WHERE tombstoned;
+
-- chat_usage_log (#4218 / migration v140): durable per-call chat usage
-- ledger. One row per SUCCESSFUL gateway.chat() call, written fire-and-forget
-- by the chat-usage sink (src/core/ai/chat-usage.ts). cost_usd is a
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index c962f2a6b3..ab60c5bd04 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.48.4.0 -->
+<!-- gbrain-template-stamp: 0.48.5.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/build-gateway-config.test.ts b/test/ai/build-gateway-config.test.ts
index 285438d120..5ff76c81db 100644
--- a/test/ai/build-gateway-config.test.ts
+++ b/test/ai/build-gateway-config.test.ts
@@ -215,6 +215,15 @@ describe('buildGatewayConfig config-plane API-key folding', () => {
);
});
+ test('deepseek_api_key folds into gateway env as DEEPSEEK_API_KEY (#4808)', async () => {
+ await withEnv({ DEEPSEEK_API_KEY: undefined }, async () => {
+ const cfg = buildGatewayConfig({
+ deepseek_api_key: 'sk-deepseek-config-plane',
+ } as unknown as GBrainConfig);
+ expect(cfg.env.DEEPSEEK_API_KEY).toBe('sk-deepseek-config-plane');
+ });
+ });
+
// Recurring-class guard: EVERY *_api_key field declared in
// KNOWN_CONFIG_KEYS must reach the gateway env dict. Adding a new
// provider key field to GBrainConfig without folding it in
diff --git a/test/ai/capabilities.test.ts b/test/ai/capabilities.test.ts
index dcc1dda4e8..e5da7bb648 100644
--- a/test/ai/capabilities.test.ts
+++ b/test/ai/capabilities.test.ts
@@ -146,15 +146,20 @@ describe('classifyCapabilities (D6 — three-tier capability verdict)', () => {
});
it('returns unusable:no_subagent_loop when tools work but the recipe declares the loop unsupported', () => {
- // moonshot + mistral declare supports_tools: true, supports_subagent_loop: false.
+ // moonshot + mistral + minimax declare supports_tools: true, supports_subagent_loop: false.
expect(classifyCapabilities('moonshot:kimi-k2.5')).toBe('unusable:no_subagent_loop');
expect(classifyCapabilities('mistral:mistral-large-latest')).toBe('unusable:no_subagent_loop');
+ // #4782: MiniMax M2+/M3 tool calling is live-verified; the loop is not.
+ expect(classifyCapabilities('minimax:MiniMax-M3')).toBe('unusable:no_subagent_loop');
+ const minimax = getProviderCapabilities('minimax:MiniMax-M3');
+ expect(minimax.supportsToolCalling).toBe(true);
+ expect(minimax.supportsParallelTools).toBe(true);
+ expect(minimax.supportsSubagentLoop).toBe(false);
});
it('keeps unusable:no_tools precedence when tool calling is missing too', () => {
- // minimax + nvidia declare BOTH supports_tools: false and
- // supports_subagent_loop: false — the stronger no_tools verdict wins.
- expect(classifyCapabilities('minimax:MiniMax-M2.5')).toBe('unusable:no_tools');
+ // nvidia declares BOTH supports_tools: false and supports_subagent_loop:
+ // false — the stronger no_tools verdict wins.
expect(classifyCapabilities('nvidia:nvidia/nemotron-3-super-120b-a12b')).toBe('unusable:no_tools');
});
diff --git a/test/ai/claude-cli-expansion.test.ts b/test/ai/claude-cli-expansion.test.ts
new file mode 100644
index 0000000000..861cb951ca
--- /dev/null
+++ b/test/ai/claude-cli-expansion.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Query expansion over the `claude-cli` recipe.
+ *
+ * Two independent defects made expansion a silent no-op for any brain whose
+ * expansion model resolves to a `claude-cli:` string (the default when
+ * `models.tier.utility` points there). Both are pinned here, because either
+ * one alone reproduces the same user-visible symptom — `query` degrading to a
+ * single-embedding `search` with no error, no log line, and no `degraded`
+ * stamp:
+ *
+ * 1. The recipe declared no `expansion` touchpoint, so
+ * `isAvailable('expansion')` was false for EVERY claude-cli model and
+ * `expand()` returned `[query]` before any model call.
+ * 2. With the touchpoint declared but the transport unchanged, expand()
+ * took the native generateObject path. ClaudeCliLanguageModel.doGenerate
+ * ignores `options.responseFormat`, so the CLI answers with
+ * markdown-fenced JSON as ordinary text, generateObject (ai@6) throws
+ * NoObjectGeneratedError (swallowed by expand()'s outer catch), and the
+ * native branch has no viaText fallback — expansion paid for a
+ * subprocess round trip on every query and discarded the answer.
+ *
+ * Hermetic: routes through __setGenerateTextTransportForTests /
+ * __setGenerateObjectTransportForTests, so no subprocess, network, or env
+ * variable is touched.
+ */
+
+import { describe, test, expect, afterEach, beforeEach } from 'bun:test';
+import {
+ expand,
+ isAvailable,
+ configureGateway,
+ resetGateway,
+ __setGenerateObjectTransportForTests,
+ __setGenerateTextTransportForTests,
+} from '../../src/core/ai/gateway.ts';
+
+const CLAUDE_CLI_HAIKU = 'claude-cli:claude-haiku-4-5-20251001';
+
+/** Exactly what `claude --print` emits for the expansion prompt: fenced JSON as text. */
+const FENCED_JSON_RESPONSE = [
+ '```json',
+ '{',
+ ' "queries": [',
+ ' "knowledge management practices for employee turnover",',
+ ' "preserving organizational knowledge during staff transitions"',
+ ' ]',
+ '}',
+ '```',
+].join('\n');
+
+beforeEach(() => {
+ configureGateway({ expansion_model: CLAUDE_CLI_HAIKU, env: {} });
+});
+
+afterEach(() => {
+ __setGenerateObjectTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+});
+
+describe('claude-cli query expansion', () => {
+ test('the expansion touchpoint is reachable for a claude-cli model', () => {
+ // Defect 1. The touchpoint is resolved from the RECIPE, not the model id,
+ // so this is false for haiku, sonnet and opus alike when undeclared —
+ // swapping models does not work around it.
+ expect(isAvailable('expansion')).toBe(true);
+ });
+
+ test('expand() recovers queries from a markdown-fenced JSON text response', async () => {
+ // Defect 2. The CLI cannot carry a json_schema, so the transport that
+ // must be exercised is generateText. If expand() reaches for
+ // generateObject here, the real adapter returns no object and the
+ // expansions are silently dropped.
+ let objectTransportCalls = 0;
+ let textTransportCalls = 0;
+
+ __setGenerateObjectTransportForTests(async () => {
+ objectTransportCalls++;
+ // Mirrors the real failure: schema request ignored, no object comes back.
+ return { object: undefined, usage: { inputTokens: 10, outputTokens: 5 } } as any;
+ });
+ __setGenerateTextTransportForTests(async () => {
+ textTransportCalls++;
+ return { text: FENCED_JSON_RESPONSE, usage: { inputTokens: 10, outputTokens: 5 } } as any;
+ });
+
+ const result = await expand('how do teams avoid losing expertise when people leave');
+
+ expect(textTransportCalls).toBe(1);
+ expect(objectTransportCalls).toBe(0);
+ // The original query is always first; the rewrites follow.
+ expect(result[0]).toBe('how do teams avoid losing expertise when people leave');
+ expect(result).toContain('knowledge management practices for employee turnover');
+ expect(result).toContain('preserving organizational knowledge during staff transitions');
+ });
+
+ test('a claude-cli expansion failure still degrades to the bare query', async () => {
+ // Fail-open posture is unchanged by the fix: a dead CLI must not take the
+ // search down with it.
+ __setGenerateTextTransportForTests(async () => {
+ throw new Error('claude CLI not authenticated');
+ });
+
+ const result = await expand('a query that cannot be expanded');
+ expect(result).toEqual(['a query that cannot be expanded']);
+ });
+});
diff --git a/test/ai/gateway-thinking-headroom.test.ts b/test/ai/gateway-thinking-headroom.test.ts
new file mode 100644
index 0000000000..ce8a9e6f4c
--- /dev/null
+++ b/test/ai/gateway-thinking-headroom.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'bun:test';
+import {
+ defaultMaxOutputTokens,
+ isThinkingModel,
+ DEFAULT_MAX_OUTPUT_TOKENS,
+ THINKING_MODEL_MAX_OUTPUT_TOKENS,
+ isThinkingByDefaultModel,
+} from '../../src/core/ai/gateway.ts';
+import { getProviderCapabilities } from '../../src/core/ai/capabilities.ts';
+
+// gbrain#4172: reasoning bills as output and counts against max_tokens. A
+// thinking-by-default model handed the 4096 non-thinking default spends the
+// whole budget reasoning and returns empty content with finish_reason
+// "length", so callers relying on the default see truncated or blank output.
+// `think`'s maxOutputTokensFor keys this off the recipe capability already;
+// these tests pin the same behavior for the gateway's chat() default.
+describe('defaultMaxOutputTokens: recipe-declared thinking headroom (#4172)', () => {
+ it('grants headroom to DeepSeek v4, which declares thinking_by_default', () => {
+ // Guard the premise: if the recipe ever drops the flag, fail here rather
+ // than silently reverting to the 4096 default at runtime.
+ expect(getProviderCapabilities('deepseek:deepseek-v4-flash').supportsThinking).toBe(true);
+ expect(isThinkingModel('deepseek:deepseek-v4-flash')).toBe(true);
+ expect(defaultMaxOutputTokens('deepseek:deepseek-v4-flash')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ expect(defaultMaxOutputTokens('deepseek:deepseek-v4-pro')).toBe(THINKING_MODEL_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);
+ expect(defaultMaxOutputTokens('anthropic:claude-sonnet-5')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ });
+
+ it('keeps the conservative default for non-thinking models', () => {
+ expect(getProviderCapabilities('groq:qwen/qwen3.8-27b').supportsThinking).toBe(false);
+ expect(isThinkingModel('groq:qwen/qwen3.8-27b')).toBe(false);
+ expect(defaultMaxOutputTokens('groq:qwen/qwen3.8-27b')).toBe(DEFAULT_MAX_OUTPUT_TOKENS);
+ });
+
+ it('degrades to the default for unknown providers instead of throwing', () => {
+ // getProviderCapabilities throws for unknown/chat-less recipes; the sizer
+ // must swallow that rather than take down every chat() call.
+ expect(() => defaultMaxOutputTokens('not-a-provider:not-a-model')).not.toThrow();
+ expect(isThinkingModel('not-a-provider:not-a-model')).toBe(false);
+ expect(defaultMaxOutputTokens('not-a-provider:not-a-model')).toBe(DEFAULT_MAX_OUTPUT_TOKENS);
+ expect(defaultMaxOutputTokens(undefined)).toBe(DEFAULT_MAX_OUTPUT_TOKENS);
+ });
+});
diff --git a/test/ai/gateway.test.ts b/test/ai/gateway.test.ts
index 801d685859..81ae08e6e9 100644
--- a/test/ai/gateway.test.ts
+++ b/test/ai/gateway.test.ts
@@ -218,6 +218,19 @@ describe('dims.dimsProviderOptions', () => {
expect(opts).toEqual({ google: { outputDimensionality: 768 } });
});
+ test('OpenAI-compatible gemini-embedding returns dimensions', () => {
+ const opts = dimsProviderOptions('openai-compatible', 'google/gemini-embedding-001', 1024);
+ expect(opts).toEqual({ openaiCompatible: { dimensions: 1024 } });
+ });
+
+ test('OpenAI-compatible text-embedding-004 (legacy Gemini id via a router) returns dimensions', () => {
+ // Routers serve the 768-native legacy id alongside gemini-embedding-*;
+ // without the branch a narrower brain gets the native width and fails on
+ // its first embed with a dim mismatch.
+ const opts = dimsProviderOptions('openai-compatible', 'text-embedding-004', 768);
+ expect(opts).toEqual({ openaiCompatible: { dimensions: 768 } });
+ });
+
test('Anthropic returns undefined (no embedding model)', () => {
const opts = dimsProviderOptions('native-anthropic', 'claude-haiku-4-5', 1536);
expect(opts).toBeUndefined();
diff --git a/test/ai/recipe-minimax.test.ts b/test/ai/recipe-minimax.test.ts
index ced6c03ef8..f08218f754 100644
--- a/test/ai/recipe-minimax.test.ts
+++ b/test/ai/recipe-minimax.test.ts
@@ -65,7 +65,10 @@ describe('recipe: minimax', () => {
const r = getRecipe('minimax')!;
expect(r.touchpoints.chat).toBeDefined();
expect(r.touchpoints.chat!.models).toContain('MiniMax-M3');
- expect(r.touchpoints.chat!.supports_tools).toBe(false);
+ // #4782: M2+/M3 chat returns OpenAI-compatible tool_calls (live two-turn
+ // tools -> role:tool continuation verified), so tools are declared. The
+ // subagent loop stays refused until a live abort/retry replay pin lands.
+ expect(r.touchpoints.chat!.supports_tools).toBe(true);
expect(r.touchpoints.chat!.supports_subagent_loop).toBe(false);
});
diff --git a/test/ai/rerank.test.ts b/test/ai/rerank.test.ts
index 268be4c3fe..fbdb0f7d44 100644
--- a/test/ai/rerank.test.ts
+++ b/test/ai/rerank.test.ts
@@ -543,4 +543,55 @@ describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
await rerank({ query: 'q', documents: ['a'] });
expect(body.model).toBe('rerank-2.5-lite');
});
+
+ // #4938: pre-fix the recipe allowlisted only the rerank-2.5 pair, so
+ // gateway.rerank() threw `Model "rerank-3" is not listed for Voyage AI
+ // reranker` before the request ever reached the transport — an operator
+ // could not opt into Voyage's current generation at all.
+ test('rerank-3 passes the allowlist and reaches the wire (#4938)', async () => {
+ configureVoyage('voyage:rerank-3');
+ let capturedUrl = '';
+ let body: any = null;
+ __setRerankTransportForTests(async (url, init) => {
+ capturedUrl = url;
+ body = JSON.parse(String(init?.body ?? '{}'));
+ return mockResp({
+ object: 'list',
+ data: [{ index: 0, relevance_score: 0.91 }],
+ model: 'rerank-3',
+ });
+ });
+ const out = await rerank({ query: 'q', documents: ['a'], topN: 1 });
+ // Same endpoint + same top-N key as the 2.5 pair: the wire is unchanged.
+ expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
+ expect(body.model).toBe('rerank-3');
+ expect(body.top_k).toBe(1);
+ expect(out).toEqual([{ index: 0, relevanceScore: 0.91 }]);
+ });
+
+ test('rerank-3-lite passes the allowlist (#4938)', async () => {
+ configureVoyage('voyage:rerank-3-lite');
+ let body: any = null;
+ __setRerankTransportForTests(async (_url, init) => {
+ body = JSON.parse(String(init?.body ?? '{}'));
+ return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
+ });
+ await rerank({ query: 'q', documents: ['a'] });
+ expect(body.model).toBe('rerank-3-lite');
+ });
+
+ test('the allowlist still rejects an unlisted Voyage reranker (#4938)', async () => {
+ // The fix widens the allowlist; it must not disable it. A typo'd or
+ // retired model still fails locally instead of burning a wire call.
+ configureVoyage('voyage:rerank-9000');
+ let called = false;
+ __setRerankTransportForTests(async () => {
+ called = true;
+ return mockResp({ results: [] });
+ });
+ await expect(rerank({ query: 'q', documents: ['a'] })).rejects.toThrow(
+ /rerank-9000.*not listed/s,
+ );
+ expect(called).toBe(false);
+ });
});
diff --git a/test/ai/reranker-readiness.test.ts b/test/ai/reranker-readiness.test.ts
index 76e317721c..44f04d9fa9 100644
--- a/test/ai/reranker-readiness.test.ts
+++ b/test/ai/reranker-readiness.test.ts
@@ -64,6 +64,20 @@ describe('rerankerReadiness — default voyage model', () => {
expect(r.modelListed).toBe(true);
expect(r.ready).toBe(true);
});
+
+ // #4938: readiness is the third consumer of the recipe allowlist (after
+ // gateway.rerank() and `gbrain models doctor`). Pre-fix it reported
+ // modelListed:false / ready:false for the rerank-3 pair, so `gbrain search
+ // modes` told an operator their configured reranker would not run.
+ test('the rerank-3 pair is listed and ready on the same key (#4938)', () => {
+ for (const model of ['voyage:rerank-3', 'voyage:rerank-3-lite']) {
+ const r = rerankerReadiness(model, { VOYAGE_API_KEY: 'pa-test' }, { now: BEFORE });
+ expect(r.modelListed).toBe(true);
+ expect(r.ready).toBe(true);
+ // rerank-3 is not a sunset provider — no shutdown clock attached.
+ expect(r.sunset).toBeNull();
+ }
+ });
});
describe('rerankerReadiness — explicit ZeroEntropy model + sunset clock', () => {
diff --git a/test/ai/voyage-reranker-recipe.test.ts b/test/ai/voyage-reranker-recipe.test.ts
index 752ef027fe..9f404a59e2 100644
--- a/test/ai/voyage-reranker-recipe.test.ts
+++ b/test/ai/voyage-reranker-recipe.test.ts
@@ -2,9 +2,14 @@
* v0.46.3 — Voyage reranker touchpoint + canonical-model recipe contract.
*
* Pins:
- * - The voyage recipe declares a reranker touchpoint: rerank-2.5 (default) +
- * rerank-2.5-lite, POST path '/rerank' (base_url_default already ends in
- * /v1 — no /v1/v1 doubling), request top-N key `top_k` via `top_param`.
+ * - The voyage recipe declares a reranker touchpoint: the rerank-2.5 pair
+ * (rerank-2.5 default) + the preview rerank-3 pair, POST path '/rerank'
+ * (base_url_default already ends in /v1 — no /v1/v1 doubling), request
+ * top-N key `top_k` via `top_param`.
+ * - #4938: rerank-3 / rerank-3-lite are in the allowlist (both the gateway's
+ * runtime check and `gbrain models doctor`'s reranker_config probe read
+ * this same array) while default_model stays rerank-2.5 — adding a model
+ * must not move existing installs onto it.
* - `default_model: 'voyage-4'` on the embedding touchpoint — array order is
* quality-sorted (voyage-4-large first) and must NOT drive selection.
* - voyage-code-4 is in the embedding models AND in the flexible-dims set.
@@ -18,7 +23,7 @@ import { describe, test, expect } from 'bun:test';
import { voyage } from '../../src/core/ai/recipes/voyage.ts';
import { zeroentropyai } from '../../src/core/ai/recipes/zeroentropyai.ts';
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
-import { EMBEDDING_PRICING } from '../../src/core/embedding-pricing.ts';
+import { EMBEDDING_PRICING, lookupEmbeddingPrice } from '../../src/core/embedding-pricing.ts';
import { supportsVoyageOutputDimension } from '../../src/core/ai/dims.ts';
import {
NEW_INSTALL_DEFAULT_EMBEDDING_MODEL,
@@ -29,7 +34,7 @@ describe('voyage reranker touchpoint (v0.46.3)', () => {
test('declares rerank-2.5 as the default reranker at /rerank with top_k', () => {
const tp = voyage.touchpoints.reranker;
expect(tp).toBeDefined();
- expect(tp!.models).toEqual(['rerank-2.5', 'rerank-2.5-lite']);
+ expect(tp!.models).toEqual(['rerank-2.5', 'rerank-2.5-lite', 'rerank-3', 'rerank-3-lite']);
expect(tp!.default_model).toBe('rerank-2.5');
expect(tp!.path).toBe('/rerank');
expect(tp!.top_param).toBe('top_k');
@@ -46,6 +51,43 @@ describe('voyage reranker touchpoint (v0.46.3)', () => {
});
});
+describe('voyage rerank-3 allowlist (#4938)', () => {
+ // Both enforcement points — gateway.rerank()'s `tp.models.includes(...)`
+ // guard and `gbrain models doctor`'s reranker_config probe — read this one
+ // array, so listing the model here is what unblocks
+ // `gbrain config set search.reranker.model voyage:rerank-3`.
+ test('rerank-3 and rerank-3-lite are in the reranker allowlist', () => {
+ const models = voyage.touchpoints.reranker!.models;
+ expect(models).toContain('rerank-3');
+ expect(models).toContain('rerank-3-lite');
+ });
+
+ test('the registry copy carries them too (the object doctor + gateway resolve)', () => {
+ const models = getRecipe('voyage')!.touchpoints.reranker!.models;
+ expect(models).toContain('rerank-3');
+ expect(models).toContain('rerank-3-lite');
+ });
+
+ test('adding rerank-3 does NOT move the default off rerank-2.5', () => {
+ // Flipping default_model would silently migrate every install that
+ // resolves the recipe default instead of an explicit config row.
+ expect(voyage.touchpoints.reranker!.default_model).toBe('rerank-2.5');
+ expect(NEW_INSTALL_DEFAULT_RERANKER_MODEL).toBe('voyage:rerank-2.5');
+ });
+
+ test('the 2.5 pair is retained, not replaced', () => {
+ const models = voyage.touchpoints.reranker!.models;
+ expect(models).toContain('rerank-2.5');
+ expect(models).toContain('rerank-2.5-lite');
+ });
+
+ test('wire shape is unchanged — rerank-3 rides the same path + top_param', () => {
+ const tp = voyage.touchpoints.reranker!;
+ expect(tp.path).toBe('/rerank');
+ expect(tp.top_param).toBe('top_k');
+ });
+});
+
describe('voyage canonical embedding model (v0.46.3)', () => {
test('default_model is voyage-4, NOT models[0] (voyage-4-large)', () => {
const tp = voyage.touchpoints.embedding!;
@@ -86,4 +128,22 @@ describe('voyage reranker pricing rows (v0.46.3)', () => {
expect(EMBEDDING_PRICING['voyage:rerank-2.5-lite']?.pricePerMTok).toBe(0.02);
expect(EMBEDDING_PRICING['voyage:voyage-code-4']?.pricePerMTok).toBe(0.12);
});
+
+ test('#4938: every allowlisted reranker resolves a price (no TX2 no_pricing)', () => {
+ // lookupPricing(kind: 'rerank') falls through to the embedding table; a
+ // miss returns null and `--max-cost` callers hard-fail with no_pricing.
+ // An allowlisted-but-unpriced model would make the fix a new footgun.
+ for (const m of voyage.touchpoints.reranker!.models) {
+ const hit = lookupEmbeddingPrice(`voyage:${m}`);
+ expect(hit.kind).toBe('known');
+ }
+ });
+
+ test('#4938: rerank-3 pair carries the post-free-tier list rate', () => {
+ // Priced at the list rate, NOT 0: the 200M complimentary grant is
+ // per-account and unknowable from here, so over-reporting inside the
+ // grant beats under-reporting past it.
+ expect(EMBEDDING_PRICING['voyage:rerank-3']?.pricePerMTok).toBe(0.05);
+ expect(EMBEDDING_PRICING['voyage:rerank-3-lite']?.pricePerMTok).toBe(0.02);
+ });
});
diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.ts
index af71e050c9..27e4f3aa2d 100644
--- a/test/ambient-recall.test.ts
+++ b/test/ambient-recall.test.ts
@@ -220,6 +220,13 @@ describe('delta cursor lifecycle', () => {
expect(r2.text as string).not.toContain('January 1, 2000');
// An UNPARSEABLE string is rejected outright (defense in depth).
await expect(call(del, ctxFor({ remote: false }), { since: 'definitely not a date' })).rejects.toThrow(/parseable|ISO/i);
+ // Wave review: a calendar-INVALID value in the microsecond passthrough shape
+ // is Date.parse-able (JS rolls Feb 31 to Mar 3) but would reach the
+ // ::timestamptz cast raw → engine error. It is invalid_params instead.
+ await expect(call(del, ctxFor({ remote: false }), { since: '2026-02-31T00:00:00.000000Z' })).rejects.toThrow(/calendar|ISO/i);
+ // ...while a valid microsecond cursor still passes through verbatim.
+ const r3 = await call(del, ctxFor({ remote: false }), { since: '2026-02-28T00:00:00.000100Z' });
+ expect(r3.since).toBe('2026-02-28T00:00:00.000100Z');
});
test('remote caller cursor is namespaced by auth client', async () => {
diff --git a/test/anthropic-model-ids.test.ts b/test/anthropic-model-ids.test.ts
index 37270712b0..eff6799a52 100644
--- a/test/anthropic-model-ids.test.ts
+++ b/test/anthropic-model-ids.test.ts
@@ -46,6 +46,12 @@ describe('Anthropic recipe model IDs', () => {
expect(chatModels).toContain('claude-sonnet-5');
});
+ it('Fable 5.1 is chat-only and carries its 1M context window', () => {
+ expect(anthropic.touchpoints?.chat?.models ?? []).toContain('claude-fable-5-1');
+ expect(anthropic.touchpoints?.chat?.model_context_tokens?.['claude-fable-5-1']).toBe(1_000_000);
+ expect(anthropic.touchpoints?.expansion?.models ?? []).not.toContain('claude-fable-5-1');
+ });
+
it('Sonnet 5 is listed for expansion', () => {
expect(anthropic.touchpoints?.expansion?.models ?? []).toContain('claude-sonnet-5');
});
diff --git a/test/autopilot-fanout-wiring.test.ts b/test/autopilot-fanout-wiring.test.ts
index 8c27975d6d..fb31480e22 100644
--- a/test/autopilot-fanout-wiring.test.ts
+++ b/test/autopilot-fanout-wiring.test.ts
@@ -79,13 +79,30 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
// all-coalesced tick (maxPending single-flight suppression) retakes the
// full-cycle branch every tick and starves the targeted-plan path for the
// whole in-flight window.
- expect(AUTOPILOT_SRC).toMatch(
- /result\.dispatched\.length > 0 \|\| result\.coalesced\.length > 0 \|\| result\.legacy_fallback \|\| result\.all_sources_fresh/,
- );
+ const updateIdx = AUTOPILOT_SRC.indexOf('lastFullCycleAt = Date.now()');
+ expect(updateIdx).toBeGreaterThan(-1);
+ const advanceGate = AUTOPILOT_SRC.slice(Math.max(0, updateIdx - 400), updateIdx + 80);
+ expect(advanceGate).toContain('result.coalesced.length > 0');
+ // all_sources_handled subsumes all_sources_fresh (fresh + locally skipped
+ // === every source); the redundant arm is gone (wave review).
+ expect(advanceGate).not.toContain('result.all_sources_fresh');
+ expect(advanceGate).toContain('result.all_sources_handled');
+ });
+
+ test('unavailable-path skips in the daemon loops are NDJSON events under --json, and sources-load is a static import (wave review)', () => {
+ // Bare prose on stderr breaks the --json NDJSON stream every other daemon
+ // line keeps; the two skip sites now emit an event in jsonMode.
+ expect(AUTOPILOT_SRC.match(/event: 'freshness_source_path_skipped'/g)?.length).toBe(2);
+ expect(AUTOPILOT_SRC).not.toContain("await import('../core/sources-load.ts')");
+ // The stale "#3696 RELATIVE path" narration is gone: the skip covers any
+ // unavailable path (relative OR missing on this machine).
+ expect(AUTOPILOT_SRC).not.toContain('a RELATIVE local_path is meaningless');
+ expect(AUTOPILOT_SRC).not.toContain('same relative-path skip as the freshness loop');
});
test('fanout_summary reports coalesced separately from dispatched (honest surfaces)', () => {
expect(AUTOPILOT_SRC).toMatch(/event: 'fanout_summary',[\s\S]{0,200}coalesced: result\.coalesced/);
+ expect(AUTOPILOT_SRC).toMatch(/event: 'fanout_summary',[\s\S]{0,400}skipped_unavailable_path: result\.skipped_unavailable_path/);
});
test('targeted-plan dispatch honors the honest-dispatch contract (red-team finding)', () => {
@@ -102,6 +119,13 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
expect(freshnessBlock).toContain('pull: sourceConfigHasRemoteUrl(src.config)');
});
+ test('freshness sync dispatch skips unavailable source paths before enqueueing', () => {
+ const freshnessIdx = AUTOPILOT_SRC.indexOf('idempotency_key: `autopilot-sync:');
+ expect(freshnessIdx).toBeGreaterThan(-1);
+ const freshnessBlock = AUTOPILOT_SRC.slice(Math.max(0, freshnessIdx - 1400), freshnessIdx + 100);
+ expect(freshnessBlock).toContain('sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config)');
+ });
+
test('#4046: targeted dispatch scopes stable recommendation keys to the interval', () => {
expect(AUTOPILOT_SRC).toContain(
'idempotency_key: autopilotRemediationIdempotencyKey(step.idempotency_key, slot)',
@@ -135,9 +159,7 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
// must update so the next tick doesn't immediately re-fan-out.
// Coalesced counts as work-in-flight (see the dedicated advance-gate
// test below for the full condition).
- expect(AUTOPILOT_SRC).toMatch(
- /result\.dispatched\.length > 0 \|\| result\.coalesced\.length > 0 \|\| result\.legacy_fallback \|\| result\.all_sources_fresh/,
- );
+ expect(AUTOPILOT_SRC).toContain('result.all_sources_handled');
expect(AUTOPILOT_SRC).toMatch(/lastFullCycleAt\s*=\s*Date\.now\(\)/);
});
diff --git a/test/autopilot-fanout.test.ts b/test/autopilot-fanout.test.ts
index 35234d6541..96c5707965 100644
--- a/test/autopilot-fanout.test.ts
+++ b/test/autopilot-fanout.test.ts
@@ -249,6 +249,7 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
jsonMode: true,
emit: (line: string) => events.push(line),
log: (line: string) => logs.push(line),
+ pathExists: (_path: string) => true,
};
return { engine, queue, added, events, logs, fanoutOpts };
}
@@ -287,6 +288,94 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
expect(sourceIds).toEqual(['alpha', 'beta']);
});
+ test('sources whose local_path is missing on this machine are skipped before dispatch', async () => {
+ const present = src('present');
+ present.local_path = '/present/brain';
+ const missing = src('foreign');
+ missing.local_path = '/foreign/brain';
+ const { engine, queue, added, events, fanoutOpts } = makeStubs([present, missing]);
+ fanoutOpts.pathExists = (p) => p === '/present/brain';
+
+ const result = await dispatchPerSource(engine, queue, fanoutOpts);
+
+ expect(result.dispatched).toEqual(['present']);
+ expect(result.skipped_unavailable_path).toEqual(['foreign']);
+ expect(added.length).toBe(1);
+ expect((added[0].data as Record<string, unknown>).source_id).toBe('present');
+ const skipped = events.find(e => e.includes('fanout_source_path_skipped'));
+ expect(skipped).toBeDefined();
+ expect(JSON.parse(skipped!).source_id).toBe('foreign');
+ });
+
+ test('missing managed remote clones still dispatch so sync can re-clone them', async () => {
+ const managed = src('managed', undefined, {
+ remote_url: 'https://github.com/example/repo',
+ managed_clone: true,
+ });
+ managed.local_path = '/missing/managed';
+ const { engine, queue, added, fanoutOpts } = makeStubs([managed]);
+ fanoutOpts.pathExists = () => false;
+
+ const result = await dispatchPerSource(engine, queue, fanoutOpts);
+
+ expect(result.dispatched).toEqual(['managed']);
+ expect(result.skipped_unavailable_path).toEqual([]);
+ expect(added.length).toBe(1);
+ });
+
+ test('all unavailable non-managed sources are handled but not called fresh', async () => {
+ const missing = src('foreign');
+ missing.local_path = '/foreign/brain';
+ const { engine, queue, added, fanoutOpts } = makeStubs([missing]);
+ fanoutOpts.pathExists = () => false;
+
+ const result = await dispatchPerSource(engine, queue, fanoutOpts);
+
+ expect(result.dispatched).toEqual([]);
+ expect(result.skipped_unavailable_path).toEqual(['foreign']);
+ expect(result.all_sources_fresh).toBe(false);
+ expect(result.all_sources_handled).toBe(true);
+ expect(added.length).toBe(0);
+ });
+
+ test('fresh plus unavailable sources are handled without implying every source is fresh', async () => {
+ const NOW = Date.now();
+ const fresh = src('fresh', new Date(NOW - 5 * 60_000).toISOString());
+ const missing = src('foreign');
+ missing.local_path = '/foreign/brain';
+ const { engine, queue, added, fanoutOpts } = makeStubs([fresh, missing]);
+ fanoutOpts.pathExists = (p) => p === fresh.local_path;
+
+ const result = await dispatchPerSource(engine, queue, fanoutOpts);
+
+ expect(result.skipped_fresh).toEqual(['fresh']);
+ expect(result.skipped_unavailable_path).toEqual(['foreign']);
+ expect(result.all_sources_fresh).toBe(false);
+ expect(result.all_sources_handled).toBe(true);
+ expect(added.length).toBe(0);
+ });
+
+ test('relative local_path rows are skipped by the same fan-out guard', () => {
+ const relative = src('legacy');
+ relative.local_path = 'notes/brain';
+ const result = selectSourcesForDispatch(
+ [src('present'), relative],
+ 10,
+ Date.parse('2026-05-22T12:00:00.000Z'),
+ 60,
+ new Map(),
+ { baseMin: 0, capMin: 120 },
+ () => true,
+ );
+
+ expect(result.dispatch.map(s => s.id)).toEqual(['present']);
+ expect(result.skippedUnavailablePath.map(s => s.id)).toEqual(['legacy']);
+ // The row carries the warning that excluded it (dispatchPerSource logs it
+ // directly rather than recomputing it with a second path probe).
+ expect(result.skippedUnavailablePath[0].skip_warning).toContain('legacy');
+ expect(result.skippedUnavailablePath[0].skip_warning).toContain('notes/brain');
+ });
+
test('pull: true only when source.config.remote_url is set', async () => {
const remote = src('remote', undefined, { remote_url: 'https://github.com/x/y' });
const local = src('local');
@@ -335,7 +424,7 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
} as unknown as Parameters<typeof dispatchPerSource>[1];
const result = await dispatchPerSource(engine, queue, {
repoPath: '/tmp', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true,
- emit: (l) => events.push(l), log: () => {},
+ emit: (l) => events.push(l), log: () => {}, pathExists: () => true,
});
// 2 of 3 dispatched (alpha + charlie); boom failed but didn't abort
expect(result.dispatched.sort()).toEqual(['alpha', 'charlie']);
@@ -402,7 +491,7 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
} as unknown as Parameters<typeof dispatchPerSource>[1];
const result = await dispatchPerSource(engine, queue, {
repoPath: '/tmp/brain', slot: 's', timeoutMs: 1, fanoutMax: 4, jsonMode: true,
- emit: (l: string) => events.push(l), log: () => {},
+ emit: (l: string) => events.push(l), log: () => {}, pathExists: () => true,
});
expect(result.dispatched).toEqual(['a']);
expect(result.coalesced).toEqual(['b']);
@@ -420,6 +509,7 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
expect(result.dispatched.length).toBe(0);
expect(result.skipped_fresh.length).toBe(2);
expect(result.all_sources_fresh).toBe(true);
+ expect(result.all_sources_handled).toBe(true);
expect(added.length).toBe(0);
});
@@ -433,5 +523,6 @@ describe('dispatchPerSource — integration with stubbed engine + queue', () =>
expect(result.dispatched).toEqual([]);
expect(result.all_sources_fresh).toBe(false);
+ expect(result.all_sources_handled).toBe(false);
});
});
diff --git a/test/autopilot-install-wrapper.serial.test.ts b/test/autopilot-install-wrapper.serial.test.ts
new file mode 100644
index 0000000000..c46c1fd7eb
--- /dev/null
+++ b/test/autopilot-install-wrapper.serial.test.ts
@@ -0,0 +1,144 @@
+/**
+ * #4728 — the generated autopilot wrapper falls back when the baked CLI path
+ * is gone.
+ *
+ * writeWrapperScript bakes the CLI path once at --install. On the
+ * ephemeral-container target the container layer is wiped on every deploy, so
+ * a CLI that lived there vanishes while the wrapper (on the volume) survives —
+ * and bash's bare "No such file or directory" (exit 127) named no remedy.
+ * These run the FULL generated wrapper under real bash; the #2608 harness in
+ * test/autopilot-install.test.ts deliberately truncates before the exec line,
+ * so the exec path lives here.
+ *
+ * SERIAL: the wrapper prepends dirname(process.execPath) onto PATH at install
+ * time, and on a dev box the real bun dir often also holds a real `gbrain`
+ * shim the fallback would find (and launch!). The rig points process.execPath
+ * at an empty tmp dir so PATH resolution is fully test-controlled —
+ * process-global state that cannot share a shard process. Env goes through
+ * withEnv; everything is restored in finally.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
+import { spawnSync, type SpawnSyncReturns } from 'child_process';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+import { writeWrapperScript } from '../src/commands/autopilot.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NO_GBRAIN_PATH = '/usr/bin:/bin';
+
+interface Rig {
+ /** HOME the wrapper runs under (holds the repo and any .bashrc). */
+ home: string;
+ /** The `which gbrain` hit baked into the wrapper at install time. */
+ bakedBinDir: string;
+ repoDir: string;
+ wrapperPath: string;
+ run: (path: string) => SpawnSyncReturns<string>;
+}
+
+async function withRig(fn: (rig: Rig) => void | Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-4728-home-'));
+ const gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-4728-gbrain-home-'));
+ const bakedBinDir = mkdtempSync(join(tmpdir(), 'gbrain-4728-baked-'));
+ const runtimeDir = mkdtempSync(join(tmpdir(), 'gbrain-4728-runtime-'));
+ // The baked shim reports that IT ran, so the present case proves the
+ // baked path stays primary rather than merely "something exited 0".
+ writeFileSync(join(bakedBinDir, 'gbrain'), '#!/bin/sh\necho "BAKED_RAN $@"\nexit 0\n', { mode: 0o755 });
+ const repoDir = join(home, 'repo-4728');
+ mkdirSync(repoDir, { recursive: true });
+ const originalExecPath = process.execPath;
+ try {
+ await withEnv(
+ { HOME: home, GBRAIN_HOME: gbrainHome, PATH: `${bakedBinDir}:${process.env.PATH ?? ''}` },
+ async () => {
+ process.execPath = join(runtimeDir, 'bun');
+ let wrapperPath: string;
+ try {
+ wrapperPath = writeWrapperScript(repoDir, 'ephemeral-container');
+ } finally {
+ process.execPath = originalExecPath;
+ }
+ const run = (path: string) =>
+ spawnSync('bash', [wrapperPath], { env: { HOME: home, PATH: path }, encoding: 'utf8', timeout: 15_000 });
+ await fn({ home, bakedBinDir, repoDir, wrapperPath, run });
+ },
+ );
+ } finally {
+ process.execPath = originalExecPath;
+ for (const d of [home, gbrainHome, bakedBinDir, runtimeDir]) {
+ rmSync(d, { recursive: true, force: true });
+ }
+ }
+}
+
+describe('#4728 wrapper falls back when the baked CLI path is gone', () => {
+ test('baked path present: byte-for-byte old behavior, no fallback chatter', async () => {
+ await withRig(rig => {
+ const r = rig.run(NO_GBRAIN_PATH);
+ expect(r.status).toBe(0);
+ expect(r.stdout).toContain(`BAKED_RAN autopilot --repo ${rig.repoDir}`);
+ expect(r.stdout).not.toContain('baked CLI path');
+ expect(r.stderr).toBe('');
+ });
+ });
+
+ test('baked path gone, gbrain on PATH: logs the substitution to stdout and execs the PATH one', async () => {
+ await withRig(rig => {
+ rmSync(join(rig.bakedBinDir, 'gbrain')); // the container-layer wipe
+ const fallbackDir = mkdtempSync(join(tmpdir(), 'gbrain-4728-fallback-'));
+ try {
+ writeFileSync(join(fallbackDir, 'gbrain'), '#!/bin/sh\necho "FALLBACK_RAN $@"\nexit 0\n', { mode: 0o755 });
+ const r = rig.run(`${fallbackDir}:${NO_GBRAIN_PATH}`);
+ expect(r.status).toBe(0);
+ // stdout, not stderr: stdout is the autopilot.log sink on all four
+ // targets (same choice as chatBootWarning); autopilot.err is never
+ // surfaced by install output or --status.
+ expect(r.stdout).toContain('baked CLI path is gone');
+ expect(r.stdout).toContain(join(fallbackDir, 'gbrain'));
+ expect(r.stdout).toContain(`FALLBACK_RAN autopilot --repo ${rig.repoDir}`);
+ } finally {
+ rmSync(fallbackDir, { recursive: true, force: true });
+ }
+ });
+ });
+
+ test('baked path gone, nothing on PATH: exit 1 with the --install remediation instead of a bare exec failure (bash 3.2: 126, bash 4+: 127)', async () => {
+ await withRig(rig => {
+ rmSync(join(rig.bakedBinDir, 'gbrain'));
+ const r = rig.run(NO_GBRAIN_PATH);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('gbrain autopilot --install');
+ expect(r.stderr).not.toContain('No such file or directory');
+ });
+ });
+
+ test('a shell function named gbrain (from a sourced rc file) does not satisfy the fallback', async () => {
+ await withRig(rig => {
+ rmSync(join(rig.bakedBinDir, 'gbrain'));
+ // The wrapper sources ~/.bashrc under HOME=rig.home before the guard runs.
+ writeFileSync(join(rig.home, '.bashrc'), 'gbrain() { echo "FUNCTION_RAN $@"; }\n');
+ const r = rig.run(NO_GBRAIN_PATH);
+ expect(r.status).toBe(1);
+ expect(r.stdout).not.toContain('FUNCTION_RAN');
+ expect(r.stdout).toContain('gbrain autopilot --install');
+ });
+ });
+
+ test('the final line is still the bare single-quoted exec the truncation harness anchors on', async () => {
+ await withRig(rig => {
+ const src = readFileSync(rig.wrapperPath, 'utf8');
+ const lines = src.trimEnd().split('\n');
+ const last = lines[lines.length - 1];
+ expect(last).toMatch(/^exec '.*' autopilot --repo '.*'$/);
+ // indexOf("exec '") (used by the #2608 truncation harness and the
+ // launchd-lifecycle ordering pins) must still land on that FINAL line,
+ // not on the fallback.
+ expect(src.slice(src.indexOf("exec '")).trimEnd()).toBe(last);
+ // The guard sits after the repo-cwd pin (#3696 ordering) and before the exec.
+ expect(src.indexOf(`\ncd '`)).toBeLessThan(src.indexOf('exec '));
+ });
+ });
+});
diff --git a/test/autopilot-lock.test.ts b/test/autopilot-lock.test.ts
index 5b5da7e0e5..567505da7f 100644
--- a/test/autopilot-lock.test.ts
+++ b/test/autopilot-lock.test.ts
@@ -171,6 +171,43 @@ describe('readProcessCommand', () => {
expect(readProcessCommand(-5)).toBeNull();
expect(readProcessCommand(Number.NaN)).toBeNull();
});
+
+ test('uses Get-CimInstance on win32 and never touches /proc or ps (#4563)', () => {
+ const calls: Array<[string, string[]]> = [];
+ const cmd = readProcessCommand(1234, {
+ platform: 'win32',
+ readCmdlineFile: () => {
+ throw new Error('should not read /proc on win32');
+ },
+ execFile: (file, args) => {
+ calls.push([file, args]);
+ return 'C:\\Users\\u\\.bun\\bin\\gbrain.exe autopilot --repo C:\\brain\r\n';
+ },
+ });
+ expect(cmd).toBe('C:\\Users\\u\\.bun\\bin\\gbrain.exe autopilot --repo C:\\brain');
+ expect(calls).toHaveLength(1);
+ expect(calls[0][0]).toBe('powershell.exe');
+ expect(calls[0][1].join(' ')).toContain('Get-CimInstance Win32_Process');
+ expect(calls[0][1].join(' ')).toContain('ProcessId=1234');
+ expect(looksLikeGbrainAutopilotCommand(cmd!)).toBe(true);
+ });
+
+ test('win32: returns null when powershell fails or the process is gone (#4563)', () => {
+ expect(readProcessCommand(1234, {
+ platform: 'win32',
+ execFile: () => {
+ throw new Error('no powershell');
+ },
+ })).toBeNull();
+ // Empty CIM output = process exited between kill-0 and the CIM query.
+ expect(readProcessCommand(1234, {
+ platform: 'win32',
+ readCmdlineFile: () => {
+ throw new Error('should not read /proc on win32');
+ },
+ execFile: () => '',
+ })).toBeNull();
+ });
});
describe('looksLikeGbrainAutopilotCommand', () => {
@@ -180,6 +217,10 @@ describe('looksLikeGbrainAutopilotCommand', () => {
expect(looksLikeGbrainAutopilotCommand('bun src/cli.ts autopilot --repo repo')).toBe(true);
});
+ test('matches a Windows command line with the executable quoted under a path with spaces', () => {
+ expect(looksLikeGbrainAutopilotCommand('"C:\\Program Files\\gbrain\\gbrain.exe" autopilot --repo "C:\\my brain"')).toBe(true);
+ });
+
test('rejects unrelated live processes', () => {
expect(looksLikeGbrainAutopilotCommand('/sbin/launchd')).toBe(false);
expect(looksLikeGbrainAutopilotCommand('/usr/bin/python worker.py')).toBe(false);
diff --git a/test/binary-self-update.test.ts b/test/binary-self-update.test.ts
index 4a2ee0aed3..176996628d 100644
--- a/test/binary-self-update.test.ts
+++ b/test/binary-self-update.test.ts
@@ -81,6 +81,7 @@ describe('runBinarySelfUpdate', () => {
});
expect(res.ok).toBe(true);
expect(res.asset).toBe('gbrain-darwin-arm64');
+ expect(res.targetVersion).toBe('9.9.9');
expect(readFileSync(target, 'utf8')).toBe('NEW BINARY');
});
});
@@ -124,6 +125,7 @@ describe('runBinarySelfUpdate', () => {
fetchRelease: async () => ({ tag: 'v9.9.9', assets: [] }),
});
expect(res.reason).toBe('no_asset');
+ expect(res.targetVersion).toBe('9.9.9');
expect(readFileSync(target, 'utf8')).toBe('OLD');
});
});
@@ -141,6 +143,7 @@ describe('runBinarySelfUpdate', () => {
},
});
expect(res.reason).toBe('download_failed');
+ expect(res.targetVersion).toBe('9.9.9');
expect(res.error).toContain('disk full');
expect(readFileSync(target, 'utf8')).toBe('OLD');
});
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index c37958de4a..a8c3420406 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -55,6 +55,7 @@ import type { ConnectProbeResult } from '../src/core/connect-probe.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import { VERSION } from '../src/version.ts';
import { withEnv } from './helpers/with-env.ts';
+import { SourceTargetError } from '../src/core/source-resolver.ts';
const TOKEN_A = `gbrain_${'a'.repeat(64)}`;
const TOKEN_B = `gbrain_${'b'.repeat(64)}`;
@@ -82,6 +83,12 @@ function makeFake(opts: {
probeOk?: boolean;
mintQueue?: Array<{ token: string; id: string }>;
pgliteLive?: boolean;
+ /** What the brain's ambient resolution (no --source) lands on (absent = the seeded default). */
+ implicitSource?: string;
+ /** The federated read set the ambient resolution carries (default: [implicitSource]). */
+ implicitGrant?: string[];
+ /** Make the hook-source lookup throw (a typo'd --source, or an unopenable engine). */
+ hookSourceError?: Error;
} = {}): Fake {
const dir = mkdtempSync(join(tmpdir(), 'gb-harness-'));
const home = join(dir, '.gbrain');
@@ -142,6 +149,12 @@ function makeFake(opts: {
return true;
},
pgliteLiveServe: () => opts.pgliteLive ?? false,
+ resolveHookSource: async (explicit) => {
+ if (opts.hookSourceError) throw opts.hookSourceError;
+ if (explicit) return { source_id: explicit, grant: [explicit] };
+ const id = opts.implicitSource ?? 'default';
+ return { source_id: id, grant: opts.implicitGrant ?? [id] };
+ },
detectClaude: () => true,
detectCodex: () => true,
detectOpencode: () => true,
@@ -172,6 +185,10 @@ describe('parseHarnessArgs', () => {
expect(parseHarnessArgs(['--harness', 'cursor']).error).toMatch(/unknown --harness/);
expect(parseHarnessArgs(['--port', 'nope']).error).toMatch(/invalid --port/);
expect(parseHarnessArgs(['--name', 'My Server']).error).toMatch(/invalid --name/);
+ // --source was the one flag that skipped validation (wave review).
+ expect(parseHarnessArgs(['--source', 'Not Valid']).error).toMatch(/invalid --source/);
+ expect(parseHarnessArgs(['--source', '__all__']).error).toMatch(/invalid --source/);
+ expect(parseHarnessArgs(['--source', 'wiki']).source).toBe('wiki');
});
test('--project is repeatable and resolved', () => {
const f = parseHarnessArgs(['--project', '/a', '--project', '/b']);
@@ -529,6 +546,130 @@ describe('outside-voice hardening (X-batch)', () => {
expect(f2.mintCalls[0].sourceGrant).toBeUndefined();
});
+ test('#4897 no --source: hooks, receipt and token bind to the serve\'s implicit default source', async () => {
+ // A brain whose only populated source is 'workspace' (default = 0 pages):
+ // the serve binds its resolve-IPC listener to 'workspace' via the same
+ // resolver, so a hook claiming 'default' is source_mismatch on every turn.
+ const f = makeFake({ implicitSource: 'workspace' });
+ expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);
+ const hooks = readJson(f.userSettings).hooks as Record<string, unknown[]>;
+ const cmd = ((hooks.SessionStart[0] as { hooks: Array<{ command: string }> }).hooks[0]).command;
+ expect(cmd).toContain('GBRAIN_SOURCE=workspace');
+ expect(cmd).not.toContain('GBRAIN_SOURCE=default');
+ const state = readHarnessReceiptState(f.home) as { receipt: { source_id: string } };
+ expect(state.receipt.source_id).toBe('workspace');
+ // The token gets the same scalar grant `--source workspace` produces —
+ // the federated-default mint cannot read a non-federated sole source.
+ expect(f.mintCalls[0].sourceGrant).toEqual(['workspace']);
+ expect(f.out.join('\n')).toContain("source 'workspace'");
+
+ // Explicit --source still wins over the implicit default.
+ const f2 = makeFake({ implicitSource: 'workspace' });
+ expect(await applyHarness(flags(['--harness', 'claude-code', '--source', 'wiki']), f2.deps)).toBe(0);
+ const hooks2 = readJson(f2.userSettings).hooks as Record<string, unknown[]>;
+ const cmd2 = ((hooks2.SessionStart[0] as { hooks: Array<{ command: string }> }).hooks[0]).command;
+ expect(cmd2).toContain('GBRAIN_SOURCE=wiki');
+ expect(f2.mintCalls[0].sourceGrant).toEqual(['wiki']);
+ expect((readHarnessReceiptState(f2.home) as { receipt: { source_id: string } }).receipt.source_id).toBe('wiki');
+ });
+
+ test("#4897 implicit 'default' is the federated floor, not a scalar grant (wave review)", async () => {
+ // `sources.default = default` is a valid config value: the resolver echoes
+ // it back, but it means "the seeded default" — the same thing the absent
+ // case means. Binding the token to a scalar ['default'] grant would hide
+ // every federated source from the hook lane (allowedSources set → no span).
+ const f = makeFake({ implicitSource: 'default' });
+ expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);
+ expect(f.mintCalls[0].sourceGrant).toBeUndefined();
+ const hooks = readJson(f.userSettings).hooks as Record<string, unknown[]>;
+ const cmd = ((hooks.SessionStart[0] as { hooks: Array<{ command: string }> }).hooks[0]).command;
+ expect(cmd).toContain('GBRAIN_SOURCE=default');
+ expect((readHarnessReceiptState(f.home) as { receipt: { source_id: string } }).receipt.source_id).toBe('default');
+ expect(f.out.join('\n')).not.toContain('binding hooks + token');
+ });
+
+ // Wave review: the hook lane binds through the SAME resolver the serve
+ // runs, an ambient non-default source carries its federated read set, and
+ // a failed lookup is never papered over with 'default'.
+ test("a typo'd --source fails loudly before any mint or receipt (wave review)", async () => {
+ const f = makeFake({
+ hookSourceError: new SourceTargetError('Source "wikk" not found or is archived. Available active sources: run `gbrain sources list`.'),
+ });
+ await expect(applyHarness(flags(['--harness', 'codex', '--source', 'wikk']), f.deps)).rejects.toThrow(/wikk/);
+ expect(f.mintCalls).toHaveLength(0);
+ expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });
+ });
+
+ test('no --source and the lookup fails: refuse with "pass --source" instead of binding default (wave review)', async () => {
+ const f = makeFake({ hookSourceError: new Error('PGLite data dir is held by a live serve') });
+ await expect(applyHarness(flags(['--harness', 'codex']), f.deps)).rejects.toThrow(/pass --source/);
+ expect(f.mintCalls).toHaveLength(0);
+ expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });
+ });
+
+ test('explicit --source with an unopenable engine binds unverified, with a warning (the --token + live-serve path)', async () => {
+ const f = makeFake({ hookSourceError: new Error('PGLite data dir is held by a live serve') });
+ expect(await applyHarness(flags(['--harness', 'codex', '--source', 'wiki']), f.deps)).toBe(0);
+ expect(f.mintCalls[0].sourceGrant).toEqual(['wiki']);
+ expect(f.err.join('\n')).toContain("could not verify --source 'wiki'");
+ });
+
+ // CI e2e (bootstrap-harness-lifecycle): under a LIVE PGLite serve the
+ // documented --token lane must keep working without --source, and the
+ // no-token case must surface the mint's two escape hatches, not a
+ // source-resolution error for what is a lock problem.
+ test('live PGLite serve + no token + no --source: the LIVE_SERVE refusal with both escape hatches, before any mint', async () => {
+ const f = makeFake({
+ pgliteLive: true,
+ hookSourceError: new Error("GBrain's local database is already open through `gbrain serve` (MCP, PID 4242)."),
+ });
+ await expect(applyHarness(flags(['--harness', 'codex']), f.deps)).rejects.toThrow(/pre-mint.*--token|stop the serve/);
+ await expect(applyHarness(flags(['--harness', 'codex']), f.deps)).rejects.not.toThrow(/pass --source/);
+ expect(f.mintCalls).toHaveLength(0);
+ expect(readHarnessReceiptState(f.home)).toEqual({ state: 'absent' });
+ });
+
+ test('live PGLite serve + --token + no --source: wires unpinned with a warning (the documented PGLite lane)', async () => {
+ const f = makeFake({
+ pgliteLive: true,
+ hookSourceError: new Error("GBrain's local database is already open through `gbrain serve` (MCP, PID 4242)."),
+ });
+ expect(await applyHarness(flags(['--harness', 'claude-code', '--token', TOKEN_A]), f.deps)).toBe(0);
+ expect(f.mintCalls).toHaveLength(0);
+ expect(f.err.join('\n')).toMatch(/could not read which source it serves/);
+ expect(f.err.join('\n')).toMatch(/--source <id>/);
+ const hooks = readJson(f.userSettings).hooks as Record<string, unknown[]>;
+ const cmd = ((hooks.SessionStart[0] as { hooks: Array<{ command: string }> }).hooks[0]).command;
+ expect(cmd).not.toContain('GBRAIN_SOURCE=');
+ const receipt = (readHarnessReceiptState(f.home) as { receipt: { source_id: string; source_pinned?: boolean } }).receipt;
+ expect(receipt.source_id).toBe('default');
+ expect(receipt.source_pinned).toBe(false);
+ });
+
+ test('a pinned install records no source_pinned flag (absent = pinned to source_id)', async () => {
+ const f = makeFake({ implicitSource: 'workspace', implicitGrant: ['default', 'workspace'] });
+ expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);
+ const receipt = (readHarnessReceiptState(f.home) as { receipt: { source_id: string; source_pinned?: boolean } }).receipt;
+ expect(receipt.source_id).toBe('workspace');
+ expect(receipt.source_pinned).toBeUndefined();
+ });
+
+ test('--token with a NON-live-serve lookup failure still refuses with "pass --source" (fail-closed stays for real errors)', async () => {
+ const f = makeFake({ hookSourceError: new Error('connection refused: postgres is down') });
+ await expect(applyHarness(flags(['--harness', 'codex', '--token', TOKEN_A]), f.deps)).rejects.toThrow(/pass --source/);
+ expect(f.mintCalls).toHaveLength(0);
+ });
+
+ test('implicit non-default source: the token grant is its federated read set, not a scalar (wave review)', async () => {
+ const f = makeFake({ implicitSource: 'workspace', implicitGrant: ['default', 'workspace'] });
+ expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);
+ expect(f.mintCalls[0].sourceGrant).toEqual(['default', 'workspace']);
+ const hooks = readJson(f.userSettings).hooks as Record<string, unknown[]>;
+ const cmd = ((hooks.SessionStart[0] as { hooks: Array<{ command: string }> }).hooks[0]).command;
+ expect(cmd).toContain('GBRAIN_SOURCE=workspace');
+ expect((readHarnessReceiptState(f.home) as { receipt: { source_id: string } }).receipt.source_id).toBe('workspace');
+ });
+
test('[X3] --no-capture RE-RUN unwires the capture events it previously wired', async () => {
const f = makeFake();
expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);
diff --git a/test/bootstrap-hooks-writers.test.ts b/test/bootstrap-hooks-writers.test.ts
index b35c78f1ae..8fb97e8ab7 100644
--- a/test/bootstrap-hooks-writers.test.ts
+++ b/test/bootstrap-hooks-writers.test.ts
@@ -11,6 +11,7 @@ import { join } from 'node:path';
import { tmpdir } from 'node:os';
import {
buildClaudeHookCommand,
+ buildPortableClaudeHookCommand,
claudeCommittedSettingsPath,
claudeSettingsPath,
registerClaudeMcp,
@@ -295,6 +296,16 @@ describe('buildClaudeHookCommand', () => {
`env GBRAIN_SOURCE=plain-slug 'GBRAIN_HOME=/has space/dir' ${BIN} hook user-prompt`,
);
});
+
+ test('local carrier: an omitted GBRAIN_SOURCE renders NO source pin (harness lane under a live PGLite serve)', () => {
+ const cmd = buildClaudeHookCommand(BIN, 'SessionStart', { GBRAIN_HOOK_LANE: 'harness' });
+ expect(cmd).toBe(`env GBRAIN_HOOK_LANE=harness ${BIN} hook session-start`);
+ expect(cmd).not.toContain('GBRAIN_SOURCE');
+ });
+
+ test('committed carrier: an omitted GBRAIN_SOURCE is refused — the portable command must stay source-scoped', () => {
+ expect(() => buildPortableClaudeHookCommand('SessionStart', {})).toThrow(/source-scoped/);
+ });
});
// ── committed hook carrier [D12] ────────────────────────────────────────────
diff --git a/test/brain-allowlist.serial.test.ts b/test/brain-allowlist.serial.test.ts
index 1c6f28b939..d6c11b11b7 100644
--- a/test/brain-allowlist.serial.test.ts
+++ b/test/brain-allowlist.serial.test.ts
@@ -125,6 +125,34 @@ describe('buildBrainTools', () => {
expect(slug.pattern).toBeUndefined();
});
+ test('execute() names a missing required parameter instead of crashing', async () => {
+ const tools = buildBrainTools({ subagentId: 42, engine, config });
+ const search = tools.find(t => t.name === 'brain_search');
+ expect(search).toBeDefined();
+ const ctx: ToolCtx = { engine, jobId: 1, remote: true };
+ await expect(search!.execute({}, ctx)).rejects.toThrow(/brain_search: Missing required parameter: query/);
+ await expect(search!.execute(undefined, ctx)).rejects.toThrow(/Missing required parameter/);
+ });
+
+ test('execute() rejects a type mismatch and an unknown enum value by name (wave review)', async () => {
+ const tools = buildBrainTools({ subagentId: 42, engine, config });
+ const search = tools.find(t => t.name === 'brain_search')!;
+ const ctx: ToolCtx = { engine, jobId: 1, remote: true };
+ await expect(search.execute({ query: 'x', limit: 'ten' }, ctx)).rejects.toThrow(/brain_search: Parameter "limit" must be a number/);
+ await expect(search.execute({ query: 'x', salience: 'loud' }, ctx)).rejects.toThrow(/brain_search: Parameter "salience" must be one of: off, on, strong/);
+ });
+
+ test('execute() normalizes optional absent idioms (null / "") before validation and the handler (wave review)', async () => {
+ // Same order the MCP dispatchers keep. `updated_after: ""` raw would reach
+ // list_pages' ::timestamptz filter; `type: null` is the JSON-client spelling
+ // of "omitted". Both must land as a plain empty listing, not a crash.
+ const tools = buildBrainTools({ subagentId: 42, engine, config });
+ const listPages = tools.find(t => t.name === 'brain_list_pages')!;
+ const ctx: ToolCtx = { engine, jobId: 1, remote: true };
+ const res = await listPages.execute({ updated_after: '', type: null, limit: 5 }, ctx) as unknown;
+ expect(res).toBeDefined();
+ });
+
test('execute() on put_page with valid namespace slug succeeds', async () => {
const tools = buildBrainTools({ subagentId: 42, engine, config });
const putPage = tools.find(t => t.name === 'brain_put_page');
diff --git a/test/brainstorm/judges-maxtokens.test.ts b/test/brainstorm/judges-maxtokens.test.ts
index d8bb772a94..06c784e407 100644
--- a/test/brainstorm/judges-maxtokens.test.ts
+++ b/test/brainstorm/judges-maxtokens.test.ts
@@ -59,6 +59,11 @@ describe('computeJudgeMaxTokens (pure formula)', () => {
expect(computeJudgeMaxTokens(300, 'claude-sonnet-4-6')).toBe(300 * TOKEN_BUDGET_PER_IDEA + TOKEN_BUDGET_ENVELOPE);
});
+ test('Fable 5.1 keeps the conservative 64K family cap', () => {
+ expect(ANTHROPIC_OUTPUT_CAPS['claude-fable-5-1']).toBe(64_000);
+ expect(computeJudgeMaxTokens(500, 'claude-fable-5-1')).toBe(64_000);
+ });
+
test('96 ideas on legacy Haiku 3.5 (8K cap): CAP binds at 8192 (D11 codex fix)', () => {
// 96 * 150 + 500 = 14_900 > 8192; legacy 3.5 caps at 8K — without
// ANTHROPIC_OUTPUT_CAPS this would have been the next opaque HTTP 400.
diff --git a/test/budget/pricing-overrides.test.ts b/test/budget/pricing-overrides.test.ts
index 11eadc850d..1cc83ab1a4 100644
--- a/test/budget/pricing-overrides.test.ts
+++ b/test/budget/pricing-overrides.test.ts
@@ -132,6 +132,28 @@ describe('BudgetTracker with pricingOverrides (#4312)', () => {
expect(isModelPriceable('litellm:x', 'chat')).toBe(false);
expect(isModelPriceable('litellm:x', 'chat', overrides)).toBe(true);
});
+
+ test('an override keyed on the dated id also prices the recipe alias (wave review)', () => {
+ // lookupPricing resolves `claude-cli:haiku` to the dated id before the
+ // table lookup; overrideFor keyed on the raw string, so an operator rate
+ // written against the dated id was skipped for the alias and the alias
+ // billed at list price ($1/M) instead of the override.
+ const t = new BudgetTracker({
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"claude-cli:claude-haiku-4-5-20251001": {"input": 0.25, "output": 1.25}}'),
+ });
+ t.record({ modelId: 'claude-cli:haiku', inputTokens: 1_000_000, outputTokens: 0, kind: 'chat' });
+ expect(t.totalSpent).toBeCloseTo(0.25, 6);
+ // And the raw-key path still wins when the alias itself is the override key.
+ const t2 = new BudgetTracker({
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"claude-cli:haiku": 0.5}'),
+ });
+ t2.record({ modelId: 'claude-cli:haiku', inputTokens: 1_000_000, outputTokens: 0, kind: 'chat' });
+ expect(t2.totalSpent).toBeCloseTo(0.5, 6);
+ });
});
describe('loadPricingOverrides — config-plane loader', () => {
diff --git a/test/by-mention.test.ts b/test/by-mention.test.ts
index 80f96b2f3b..8669e3692e 100644
--- a/test/by-mention.test.ts
+++ b/test/by-mention.test.ts
@@ -23,6 +23,8 @@
* 15. Determinism across 10 calls
* 16. Self-link guard (D13)
* 17. Cross-source guard
+ * 17b. Cross-source guard lifts under allowCrossSource
+ * 17c. Own-source same-name twin outranks the cross-source twin
* 18. Hardcoded type filter (meeting NOT in gazetteer)
* 19. Min-length + ignore-list interaction
* 20. Code-block + token interaction
@@ -244,6 +246,36 @@ describe('findMentionedEntities — pure cases', () => {
expect(mentions).toEqual([]);
});
+ test('17b. cross-source guard lifts under allowCrossSource — mention carries the entity\'s own source_id', () => {
+ const g = gazetteerFromEntries([
+ { slug: 'companies/acme', source_id: 'team-b', title: 'Acme' },
+ ]);
+ const opts = { fromSlug: 'writing/post-1', fromSourceId: 'team-a' };
+ expect(findMentionedEntities('We met Acme today.', g, opts)).toEqual([]);
+ const mentions = findMentionedEntities('We met Acme today.', g, { ...opts, allowCrossSource: true });
+ expect(mentions).toHaveLength(1);
+ expect(mentions[0]!.slug).toBe('companies/acme');
+ expect(mentions[0]!.source_id).toBe('team-b');
+ });
+
+ test('17c. same-name twin in the scanning page\'s own source outranks the cross-source twin', () => {
+ // Bucket order is length-only, so the foreign twin sits first: without the
+ // own-source preference the guard drops the mention (allowCrossSource off)
+ // or links the foreign page (allowCrossSource on).
+ const g = gazetteerFromEntries([
+ { slug: 'companies/acme', source_id: 'team-b', title: 'Acme' },
+ { slug: 'companies/acme-local', source_id: 'team-a', title: 'Acme' },
+ ]);
+ for (const allowCrossSource of [false, true]) {
+ const mentions = findMentionedEntities('We met Acme today.', g, {
+ fromSlug: 'writing/post-1', fromSourceId: 'team-a', allowCrossSource,
+ });
+ expect(mentions).toHaveLength(1);
+ expect(mentions[0]!.slug).toBe('companies/acme-local');
+ expect(mentions[0]!.source_id).toBe('team-a');
+ }
+ });
+
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/check-resolvable-cli.test.ts b/test/check-resolvable-cli.test.ts
index 84de232e50..12e85c6b6d 100644
--- a/test/check-resolvable-cli.test.ts
+++ b/test/check-resolvable-cli.test.ts
@@ -8,6 +8,7 @@ import {
resolveSkillsDir,
DEFERRED,
} from '../src/commands/check-resolvable.ts';
+import { checkResolvable } from '../src/core/check-resolvable.ts';
// Path to the CLI entry point. Runs through bun directly so tests don't
// require a pre-built binary. Always invoked from the repo root so bun can
@@ -102,6 +103,61 @@ function run(args: string[]): RunResult {
// Unit tests: direct helpers (fast, no subprocess)
// ---------------------------------------------------------------------------
+describe('check-resolvable — unit: orphan_trigger is one warning per skill, worded by source (#4831)', () => {
+ const created: string[] = [];
+ afterEach(() => {
+ for (const d of created) rmSync(d, { recursive: true, force: true });
+ created.length = 0;
+ });
+
+ it('frontmatter-only orphan: one warning naming SKILL.md + manifest.json, no RESOLVER.md fix', () => {
+ const skillsDir = makeFixture(
+ [
+ { name: 'alpha', triggers: ['alpha'] },
+ { name: 'beta', triggers: ['b1', 'b2', 'b3'], inManifest: false, inResolver: false },
+ ],
+ created,
+ );
+ const report = checkResolvable(skillsDir);
+ const orphans = report.warnings.filter(w => w.type === 'orphan_trigger' && w.skill === 'beta');
+ expect(orphans.length).toBe(1);
+ expect(orphans[0].message).toContain('manifest.json');
+ expect(orphans[0].message).toContain('SKILL.md');
+ expect(orphans[0].message).not.toContain('RESOLVER.md has a trigger');
+ expect(orphans[0].action).toContain('manifest.json');
+ expect(orphans[0].action).not.toContain('RESOLVER.md');
+ expect(orphans[0].fix).toBeUndefined();
+ });
+
+ it('RESOLVER.md-only orphan: one warning with the remove_trigger fix', () => {
+ const skillsDir = makeFixture(
+ [
+ { name: 'alpha', triggers: ['alpha'] },
+ { name: 'gamma', triggers: [], inManifest: false },
+ ],
+ created,
+ );
+ const report = checkResolvable(skillsDir);
+ const orphans = report.warnings.filter(w => w.type === 'orphan_trigger' && w.skill === 'gamma');
+ expect(orphans.length).toBe(1);
+ expect(orphans[0].message).toContain('RESOLVER.md');
+ expect(orphans[0].fix?.type).toBe('remove_trigger');
+ expect(orphans[0].fix?.file).toBe(join(skillsDir, 'RESOLVER.md'));
+ });
+
+ it('frontmatter + RESOLVER.md row for the same skill: one warning, keeps the remove_trigger fix', () => {
+ const skillsDir = makeFixture(
+ [{ name: 'alpha', triggers: ['alpha'], inManifest: false }],
+ created,
+ );
+ const report = checkResolvable(skillsDir);
+ const orphans = report.warnings.filter(w => w.type === 'orphan_trigger');
+ expect(orphans.length).toBe(1);
+ expect(orphans[0].skill).toBe('alpha');
+ expect(orphans[0].fix?.type).toBe('remove_trigger');
+ });
+});
+
describe('check-resolvable — unit: parseFlags', () => {
it('parses all known flags', () => {
const f = parseFlags(['--json', '--fix', '--dry-run', '--verbose', '--skills-dir', '/x']);
diff --git a/test/check-resolvable.test.ts b/test/check-resolvable.test.ts
index 8f99a52bf6..9de673b8dc 100644
--- a/test/check-resolvable.test.ts
+++ b/test/check-resolvable.test.ts
@@ -482,3 +482,241 @@ function afterEachCleanup(fn: () => void) {
const { afterEach } = require("bun:test");
afterEach(fn);
}
+
+// ---------------------------------------------------------------------------
+// Low-confidence foreign skills dir: cwd_walk_up (tier 1b) is ungated, so it
+// can land on a directory belonging to a different tool. One skill there
+// coincidentally shipping a `triggers:` field used to flip every OTHER
+// triggerless sibling from the soft "uninitialized" fallback into hard
+// `unreachable` errors. Severity is softened only when ALL hold: found via
+// cwd_walk_up, no resolver file contributes rows, unreachable outnumber
+// reachable, and no manifest.json on disk. Everything else stays strict.
+// ---------------------------------------------------------------------------
+
+function makeSkillWithoutTriggers(dir: string, name: string): void {
+ mkdirSync(join(dir, name), { recursive: true });
+ writeFileSync(
+ join(dir, name, "SKILL.md"),
+ "---\n" +
+ `name: ${name}\n` +
+ "description: belongs to a different tool, no triggers field\n" +
+ "---\n" +
+ "body\n"
+ );
+}
+
+function makeSkillWithTriggers(dir: string, name: string): void {
+ mkdirSync(join(dir, name), { recursive: true });
+ writeFileSync(
+ join(dir, name, "SKILL.md"),
+ "---\n" +
+ `name: ${name}\n` +
+ "description: also unrelated, but happens to declare triggers\n" +
+ "triggers:\n" +
+ " - \"some phrase\"\n" +
+ "---\n" +
+ "body\n"
+ );
+}
+
+// Sparse trigger coverage (3 triggerless : 1 with triggers) -- matches the
+// real-world repro (1 of 26 skills coincidentally had triggers:). No
+// RESOLVER.md, no AGENTS.md, no manifest.json -- deriveManifest() walks
+// the directory listing instead, same as a real foreign tool's skills/
+// dir with no gbrain awareness whatsoever.
+function makeSparseForeignSkillsFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "gbrain-foreign-skills-"));
+ makeSkillWithoutTriggers(dir, "some-unrelated-tool-skill");
+ makeSkillWithoutTriggers(dir, "another-unrelated-skill");
+ makeSkillWithoutTriggers(dir, "yet-another-unrelated-skill");
+ // The one coincidental trigger-bearing skill that defeats the
+ // triggerEntries.length===0 fallback in real-world repros.
+ makeSkillWithTriggers(dir, "coincidentally-has-triggers");
+ return dir;
+}
+
+// Dense trigger coverage (3 with triggers : 1 triggerless) -- a mostly-
+// migrated real skillpack whose RESOLVER.md/AGENTS.md was merely deleted
+// by accident. Must NOT be softened even via cwd_walk_up with no
+// resolver file present (resolver-absence alone isn't proof of "foreign").
+function makeDenseSkillpackFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "gbrain-dense-skillpack-"));
+ makeSkillWithTriggers(dir, "migrated-skill-one");
+ makeSkillWithTriggers(dir, "migrated-skill-two");
+ makeSkillWithTriggers(dir, "migrated-skill-three");
+ makeSkillWithoutTriggers(dir, "not-yet-migrated-skill");
+ return dir;
+}
+
+describe("checkResolvable — low-confidence foreign skills dir", () => {
+ let dir: string;
+ afterEachCleanup(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ test("cwd_walk_up + no RESOLVER.md + sparse triggers: unreachable is downgraded to warning", () => {
+ dir = makeSparseForeignSkillsFixture();
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(3);
+ expect(unreachable.map(i => i.skill).sort()).toEqual([
+ "another-unrelated-skill",
+ "some-unrelated-tool-skill",
+ "yet-another-unrelated-skill",
+ ]);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("warning");
+ }
+ // Downgraded severity must actually move the issues out of errors[]
+ // and into warnings[] (checkResolvable filters on .severity at the
+ // end) -- otherwise health_score still takes the -20 hit.
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(false);
+ expect(report.warnings.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("no skillsDirSource (higher-confidence tiers): unreachable stays a hard error", () => {
+ dir = makeSparseForeignSkillsFixture();
+ const report = checkResolvable(dir);
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(3);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("error");
+ }
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("cwd_walk_up but RESOLVER.md present: stays a hard error (real skillpack, not foreign)", () => {
+ dir = makeSparseForeignSkillsFixture();
+ writeFileSync(
+ join(dir, "RESOLVER.md"),
+ "## Brain operations\n| Trigger | Skill |\n|---------|-------|\n"
+ );
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBeGreaterThan(0);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("error");
+ }
+ });
+
+ test("cwd_walk_up + no RESOLVER.md but DENSE trigger coverage: unreachable stays a hard error", () => {
+ // A mostly-migrated real skillpack whose RESOLVER.md/AGENTS.md was
+ // merely deleted by accident (majority already reachable via
+ // triggers:) must still fail loudly.
+ dir = makeDenseSkillpackFixture();
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(1);
+ expect(unreachable[0].skill).toBe("not-yet-migrated-skill");
+ expect(unreachable[0].severity).toBe("error");
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("cwd_walk_up + no RESOLVER.md + sparse triggers BUT explicit manifest.json: unreachable stays a hard error", () => {
+ // An explicit manifest.json is itself a deliberate "this is a gbrain
+ // skillpack" declaration -- a foreign tool's directory never ships
+ // one. Its presence keeps enforcement strict.
+ dir = makeSparseForeignSkillsFixture();
+ writeFileSync(
+ join(dir, "manifest.json"),
+ JSON.stringify({
+ skills: [
+ { name: "some-unrelated-tool-skill", path: "some-unrelated-tool-skill/SKILL.md" },
+ { name: "another-unrelated-skill", path: "another-unrelated-skill/SKILL.md" },
+ { name: "yet-another-unrelated-skill", path: "yet-another-unrelated-skill/SKILL.md" },
+ { name: "coincidentally-has-triggers", path: "coincidentally-has-triggers/SKILL.md" },
+ ],
+ })
+ );
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(3);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("error");
+ }
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("cwd_walk_up + no RESOLVER.md + sparse triggers BUT MALFORMED manifest.json: unreachable stays a hard error", () => {
+ // loadOrDeriveManifest's `derived` flag is true both when manifest.json
+ // is absent AND when it exists but fails to parse. A corrupted
+ // manifest.json on a real skillpack is exactly what doctor exists to
+ // catch, so the downgrade keys on on-disk absence, not `derived`.
+ dir = makeSparseForeignSkillsFixture();
+ writeFileSync(join(dir, "manifest.json"), "{ this is not valid json");
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(3);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("error");
+ }
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("cwd_walk_up + generic AGENTS.md with no resolver rows + sparse triggers: unreachable is STILL downgraded to warning", () => {
+ // `resolverPathOrNull` is filename-only, not content-aware. A foreign
+ // tool's generic prose AGENTS.md contributes zero resolver rows, so it
+ // must not disable the downgrade; the check keys on a resolver_md-
+ // sourced entry, not `entries.length`.
+ dir = makeSparseForeignSkillsFixture();
+ writeFileSync(
+ join(dir, "AGENTS.md"),
+ "# Agent Instructions\n\nThis is a generic agent configuration file for an unrelated tool. " +
+ "It has no resolver routing table -- just prose.\n"
+ );
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBe(3);
+ expect(unreachable.map(i => i.skill).sort()).toEqual([
+ "another-unrelated-skill",
+ "some-unrelated-tool-skill",
+ "yet-another-unrelated-skill",
+ ]);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("warning");
+ }
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(false);
+ expect(report.warnings.some(i => i.type === "unreachable")).toBe(true);
+ });
+
+ test("cwd_walk_up + AGENTS.md WITH real resolver rows + sparse triggers elsewhere: unreachable stays a hard error", () => {
+ // Inverse of the above: when the found AGENTS.md actually carries a
+ // resolver table (source: 'resolver_md'), it's real routing intent,
+ // not a foreign convention collision -- must NOT be downgraded.
+ dir = makeSparseForeignSkillsFixture();
+ writeFileSync(
+ join(dir, "AGENTS.md"),
+ "## Routing\n\n| trigger | skill |\n| --- | --- |\n" +
+ "| some real trigger | `skills/some-unrelated-tool-skill/SKILL.md` |\n"
+ );
+ const report = checkResolvable(dir, { skillsDirSource: "cwd_walk_up" });
+ const unreachable = report.issues.filter(i => i.type === "unreachable");
+ expect(unreachable.length).toBeGreaterThan(0);
+ for (const issue of unreachable) {
+ expect(issue.severity).toBe("error");
+ }
+ expect(report.errors.some(i => i.type === "unreachable")).toBe(true);
+ });
+});
+
+describe("missing_file is reported once per skill path, not once per trigger row (wave review)", () => {
+ test("three trigger rows for one absent skill file → one missing_file issue", () => {
+ const dir = mkdtempSync(join(tmpdir(), "gbrain-missing-file-"));
+ try {
+ writeFileSync(
+ join(dir, "RESOLVER.md"),
+ "## Test\n| Trigger | Skill |\n|-----|-----|\n" +
+ '| "first" | `skills/ghost-skill/SKILL.md` |\n' +
+ '| "second" | `skills/ghost-skill/SKILL.md` |\n' +
+ '| "third" | `skills/ghost-skill/SKILL.md` |\n',
+ );
+ writeFileSync(join(dir, "manifest.json"), JSON.stringify({ skills: [] }));
+ const report = checkResolvable(dir);
+ const missing = report.issues.filter(i => i.type === "missing_file");
+ expect(missing).toHaveLength(1);
+ expect(missing[0].skill).toBe("skills/ghost-skill/SKILL.md");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/chronicle-ontology-private-visibility.test.ts b/test/chronicle-ontology-private-visibility.test.ts
new file mode 100644
index 0000000000..6c54c4b6de
--- /dev/null
+++ b/test/chronicle-ontology-private-visibility.test.ts
@@ -0,0 +1,153 @@
+/**
+ * Ontology reads under the page-visibility gate (#4352 class).
+ *
+ * The chronicle timeline reads already hide `visibility: private` pages from
+ * untrusted callers (readPolicyOpts). The ontology reads (ontology_get /
+ * ontology_conflicts / volunteer_chronicle's ontologies) join the same pages
+ * through the fact's provenance slug (`facts.source_markdown_slug`) but only
+ * redacted the diary prefix, so a remote caller who could not read a private
+ * page still received every value extracted from it plus that page's slug as
+ * `source`. These tests pin:
+ *
+ * 1. Pre-resolution: a private provenance page drops out BEFORE the
+ * per-dimension DISTINCT ON, so the untrusted caller resolves the newest
+ * value they may see (the older world-sourced one), never a private value
+ * and never a hole where one was. A trusted local caller still sees all.
+ * 2. Conflicts: a disagreement that only exists because of a hidden
+ * provenance is not reported remotely.
+ * 3. The operator opt-out (`search.remote_private_pages=visible`) restores
+ * the pre-gate behavior, same as the sibling reads.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import {
+ REMOTE_PRIVATE_PAGES_KEY,
+ __resetPrivateVisibilityCacheForTests,
+} from '../src/core/search/private-visibility.ts';
+
+let engine: PGLiteEngine;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } as any,
+ dryRun: false,
+ remote: true,
+ transport: 'stdio',
+ sourceId: 'default',
+ ...overrides,
+ } as OperationContext;
+}
+const local = () => ctxOf({ remote: false });
+const remote = () => ctxOf({ remote: true });
+// remote UNDEFINED is the fail-closed `ctx.remote !== false` shape.
+const remoteUndef = () => ctxOf({ remote: undefined as unknown as boolean });
+
+// Every token below lives ONLY on the private page or on rows derived from it.
+const PRIVATE_TOKENS = ['meetings/secret-sync', 'secretvalue'];
+function privateToken(payload: unknown): string | null {
+ const text = JSON.stringify(payload) ?? '';
+ for (const t of PRIVATE_TOKENS) if (text.includes(t)) return t;
+ return null;
+}
+
+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);
+ __resetPrivateVisibilityCacheForTests();
+
+ // Provenance pages: one world, one private.
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title, frontmatter)
+ VALUES ('default', 'meetings/open-sync', 'meeting', 'open sync', '{}'::jsonb),
+ ('default', 'meetings/secret-sync', 'meeting', 'secret sync', '{"visibility":"private"}'::jsonb)`,
+ );
+
+ // A newer private-sourced value and an older world-sourced value that stay
+ // open side by side (the backdated-conflict shape: the second write is
+ // older, so it is inserted without closing the first). Resolution picks the
+ // newer valid_from, so local resolves the private value; an untrusted caller
+ // must resolve the older world value, not a hole. The same pair is a
+ // two-provenance conflict that only exists with the private side present.
+ await engine.mergeOntologyFact({
+ entitySlug: 'people/open-person', dimension: 'role', value: 'secretvalue',
+ source: 'meetings/secret-sync', validFrom: '2026-05-01',
+ });
+ await engine.mergeOntologyFact({
+ entitySlug: 'people/open-person', dimension: 'role', value: 'openvalue',
+ source: 'meetings/open-sync', validFrom: '2026-01-01',
+ });
+ await engine.mergeOntologyFact({
+ entitySlug: 'people/conf-person', dimension: 'role', value: 'secretvalue',
+ source: 'meetings/secret-sync', validFrom: '2026-05-01',
+ });
+ await engine.mergeOntologyFact({
+ entitySlug: 'people/conf-person', dimension: 'role', value: 'yes',
+ source: 'meetings/open-sync', validFrom: '2026-01-01',
+ });
+}, 60_000);
+
+type Val = { dimension: string; value: string; source: string };
+type Conflict = { entity_slug: string; values: { value: string; source: string }[] };
+
+describe('ontology provenance rows follow the page-visibility policy', () => {
+ test('ontology_get: a private provenance page drops before resolution, so remote resolves the older world value', async () => {
+ const seen = await operationsByName.ontology_get.handler(local(), { entity: 'people/open-person' }) as Val[];
+ expect(seen.find((v) => v.dimension === 'role')?.value).toBe('secretvalue'); // anti-vacuity
+
+ for (const c of [remote(), remoteUndef()]) {
+ const rows = await operationsByName.ontology_get.handler(c, { entity: 'people/open-person' }) as Val[];
+ expect(privateToken(rows)).toBeNull();
+ expect(rows.find((v) => v.dimension === 'role')?.value).toBe('openvalue');
+ }
+ });
+
+ test('ontology_conflicts: a disagreement that needs a private provenance is not reported remotely', async () => {
+ const seen = await operationsByName.ontology_conflicts.handler(local(), {}) as Conflict[];
+ expect(seen.some((c) => c.entity_slug === 'people/conf-person')).toBe(true);
+ for (const c of [remote(), remoteUndef()]) {
+ const rows = await operationsByName.ontology_conflicts.handler(c, {}) as Conflict[];
+ expect(rows.some((r) => r.entity_slug === 'people/conf-person')).toBe(false);
+ expect(privateToken(rows)).toBeNull();
+ }
+ });
+
+ test('volunteer_chronicle: ontologies carry no private value or provenance slug', async () => {
+ type Vol = { ontologies: Record<string, { value: string }[]> };
+ const args = { days: 3650, limit: 50, entities: 'people/open-person' };
+ const seen = await operationsByName.volunteer_chronicle.handler(local(), args) as Vol;
+ expect(seen.ontologies['people/open-person'].map((v) => v.value)).toContain('secretvalue');
+
+ for (const c of [remote(), remoteUndef()]) {
+ const vol = await operationsByName.volunteer_chronicle.handler(c, args) as Vol;
+ expect(privateToken(vol)).toBeNull();
+ expect(vol.ontologies['people/open-person'].map((v) => v.value)).toEqual(['openvalue']);
+ }
+ });
+});
+
+describe('operator opt-out matches the sibling reads', () => {
+ test(`${REMOTE_PRIVATE_PAGES_KEY}=visible restores private-provenance values for remote callers`, async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ try {
+ const rows = await operationsByName.ontology_get.handler(remote(), { entity: 'people/open-person' }) as Val[];
+ expect(rows.find((v) => v.dimension === 'role')?.value).toBe('secretvalue');
+ } finally {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, '');
+ __resetPrivateVisibilityCacheForTests();
+ }
+ });
+});
diff --git a/test/chunkers/code-dart.test.ts b/test/chunkers/code-dart.test.ts
index 4eeddcdea3..54247822d5 100644
--- a/test/chunkers/code-dart.test.ts
+++ b/test/chunkers/code-dart.test.ts
@@ -10,7 +10,12 @@
import { describe, test, expect } from 'bun:test';
import { join } from 'node:path';
-import { chunkCodeText, resetChunkerWarnings } from '../../src/core/chunkers/code.ts';
+import {
+ chunkCodeText,
+ registerLanguage,
+ resetChunkerWarnings,
+ unregisterLanguage,
+} from '../../src/core/chunkers/code.ts';
import { DEF_TYPES } from '../../src/commands/code-def.ts';
const ASSETS = join(import.meta.dir, '../../src/assets/wasm');
@@ -118,20 +123,56 @@ describe('chunkCodeText — Dart', () => {
describe('chunker fallback is no longer silent', () => {
test('warns once per language when a grammar cannot be used', async () => {
- // elm and ql still fail to LOAD under the pinned runtime today, which is
- // the same silent shape Dart had. One warning per language, not per file.
+ // Force a LOAD failure on a language that has real semantic support (bash
+ // is in TOP_LEVEL_TYPES) — that is the shape Dart had. Languages without
+ // a TOP_LEVEL_TYPES entry never load a grammar at all (#4669), so they are
+ // not a valid fixture here. unregister FIRST: registerLanguage does not
+ // evict languageCache, so a bash grammar loaded by an earlier test would
+ // otherwise be served from cache and the forced failure would never fire.
resetChunkerWarnings();
+ unregisterLanguage('bash');
+ registerLanguage('bash', { displayName: 'Bash', embeddedPath: '/nonexistent/tree-sitter-bash.wasm' });
const seen: string[] = [];
const original = console.warn;
console.warn = (...args: unknown[]) => { seen.push(String(args[0])); };
try {
- await chunkCodeText('type alias A = { b : Int }\n', 'a.elm');
- await chunkCodeText('type alias B = { c : Int }\n', 'b.elm');
+ await chunkCodeText('foo() {\n echo a\n}\n', 'a.sh');
+ await chunkCodeText('bar() {\n echo b\n}\n', 'b.sh');
} finally {
console.warn = original;
+ unregisterLanguage('bash'); // restore the manifest entry + drop the poisoned cache
+ }
+ const bash = seen.filter(l => l.includes('[gbrain chunker] bash'));
+ expect(bash.length).toBe(1);
+ expect(bash[0]).toContain('semantic parsing unavailable');
+ });
+
+ test('yaml never emits the semantic-parsing-unavailable warning (#4669)', async () => {
+ // yaml has no TOP_LEVEL_TYPES entry, so even a successful parse ends in
+ // text-fallback chunks. The vendored grammar also cannot run under the
+ // pinned runtime, so every .yaml file (and every ```yaml fence, which
+ // import-file routes through 'fence.yaml') used to pay a doomed WASM
+ // parse AND log a false "semantic parsing unavailable" alarm.
+ resetChunkerWarnings();
+ const yamlSrc = 'a: 1\nb:\n c: 2\n';
+ const seen: string[] = [];
+ const original = console.warn;
+ console.warn = (...args: unknown[]) => { seen.push(String(args[0])); };
+ let file: Awaited<ReturnType<typeof chunkCodeText>>;
+ let fence: Awaited<ReturnType<typeof chunkCodeText>>;
+ try {
+ file = await chunkCodeText(yamlSrc, 'x.yaml');
+ fence = await chunkCodeText(yamlSrc, 'fence.yaml');
+ } finally {
+ console.warn = original;
+ }
+ expect(seen.filter(l => l.includes('[gbrain chunker] yaml'))).toEqual([]);
+ // Output is the text fallback, exactly as before the short-circuit.
+ for (const chunks of [file, fence]) {
+ expect(chunks).toHaveLength(1);
+ expect(chunks[0].text).toContain(yamlSrc.trim());
+ expect(chunks[0].metadata.symbolName).toBeNull();
+ expect(chunks[0].metadata.symbolType).toBe('module');
}
- const elm = seen.filter(l => l.includes('[gbrain chunker] elm'));
- expect(elm.length).toBe(1);
- expect(elm[0]).toContain('semantic parsing unavailable');
});
});
diff --git a/test/chunkers/recursive-cjk-overlap.test.ts b/test/chunkers/recursive-cjk-overlap.test.ts
new file mode 100644
index 0000000000..6e5fb0751a
--- /dev/null
+++ b/test/chunkers/recursive-cjk-overlap.test.ts
@@ -0,0 +1,238 @@
+import { describe, test, expect } from 'bun:test';
+import { chunkText } from '../../src/core/chunkers/recursive.ts';
+
+describe('CJK chunk overlap & boundary fixes', () => {
+ test('Chinese sentences align overlap to CJK sentence boundaries', () => {
+ // 40 short Chinese sentences, each 9-10 chars. Whitespace tokenization
+ // treated each sentence as one "word"; overlap either vanished or
+ // spanned whole sentences. The CJK path counts chars and splits on 。!?
+ const sentences = Array.from(
+ { length: 40 },
+ (_, i) => `第${i + 1}句中文测试句子。`,
+ );
+ const text = sentences.join('');
+ const chunks = chunkText(text, { chunkSize: 50, chunkOverlap: 20 });
+ expect(chunks.length).toBeGreaterThan(1);
+
+ // Lossless reconstruction for whitespace-free CJK text.
+ const reconstructed = reconstructFromChunks(chunks);
+ expect(reconstructed).toBe(text);
+
+ // Each chunk after the first should start at a CJK sentence boundary.
+ for (let i = 1; i < chunks.length; i++) {
+ const curr = chunks[i].text;
+ expect(curr[0]).toMatch(/[一-鿿぀-ゟ゠-ヿ가-힯0-9]/);
+ // The first char should be the start of a sentence number, and the
+ // character just before the overlap in the previous chunk should be 。
+ const prev = chunks[i - 1].text;
+ const startInPrev = prev.lastIndexOf(curr.slice(0, Math.min(3, curr.length)));
+ if (startInPrev > 0) {
+ expect(prev[startInPrev - 1]).toBe('。');
+ }
+ }
+ });
+
+ test('mixed CJK + English preserves every non-whitespace character', () => {
+ // Use non-periodic, numbered fragments so any loss or reorder is visible.
+ const blocks: string[] = [];
+ for (let i = 0; i < 40; i++) {
+ blocks.push(`Step ${i + 1} begins here. `);
+ blocks.push(`这是第${i + 1}步中文说明。`);
+ }
+ const text = blocks.join('');
+ const chunks = chunkText(text, { chunkSize: 60, chunkOverlap: 20 });
+ expect(chunks.length).toBeGreaterThan(1);
+
+ // Whitespace may be normalized at chunk boundaries by trimming, so compare
+ // non-whitespace content only.
+ const strip = (s: string) => s.replace(/\s+/g, '');
+ const reconstructed = reconstructFromChunks(chunks);
+ expect(strip(reconstructed)).toBe(strip(text));
+
+ // Spot-check ordering: each step number appears in order.
+ let cursor = 0;
+ for (let n = 1; n <= 40; n++) {
+ const idx = reconstructed.indexOf(`Step ${n}`, cursor);
+ expect(idx).toBeGreaterThanOrEqual(cursor);
+ cursor = idx + 1;
+ }
+ });
+
+ test('overlap span is bounded on varied CJK-dominant text', () => {
+ const sentences: string[] = [];
+ for (let i = 0; i < 60; i++) {
+ sentences.push(`第${i + 1}段混合文本,包含一些英文词汇如${i + 1}number。`);
+ }
+ const text = sentences.join('');
+ const overlapChars = 20;
+ const chunks = chunkText(text, { chunkSize: 60, chunkOverlap: overlapChars });
+ expect(chunks.length).toBeGreaterThan(1);
+
+ // No chunk should be a pure duplicate of its predecessor on varied text,
+ // and the actual overlap must be a suffix of the previous chunk.
+ for (let i = 1; i < chunks.length; i++) {
+ const prev = chunks[i - 1].text;
+ const actualOverlap = overlapLength(prev, chunks[i].text);
+ expect(actualOverlap).toBeGreaterThan(0);
+ // Overlap should not swallow the whole previous chunk.
+ expect(actualOverlap).toBeLessThan(prev.length);
+ // Overlap should be bounded by a small multiple of target overlap chars.
+ expect(actualOverlap).toBeLessThanOrEqual(Math.max(overlapChars, 30) * 3);
+ }
+
+ const strip = (s: string) => s.replace(/\s+/g, '');
+ expect(strip(reconstructFromChunks(chunks))).toBe(strip(text));
+ });
+
+ test('ASCII period inside CJK prose is not a sentence boundary for the overlap', () => {
+ // Overlap window of 16 starts exactly at the "3" of "3.5" (or the ".")
+ // for every sentence. Treating that "." as a sentence end would start the
+ // next chunk at "5相关…"; only a whitespace-followed ASCII terminator
+ // (or a CJK 。!?) may align the overlap.
+ const text = Array.from(
+ { length: 30 },
+ (_, i) => `版本3.5相关内容第${i + 1}条,还有更多。`,
+ ).join('');
+ const chunks = chunkText(text, { chunkSize: 40, chunkOverlap: 16 });
+ expect(chunks.length).toBeGreaterThan(1);
+ for (let i = 1; i < chunks.length; i++) {
+ expect(overlapLength(chunks[i - 1].text, chunks[i].text)).toBeGreaterThan(0);
+ expect(chunks[i].text.startsWith('5相关')).toBe(false);
+ }
+ });
+
+ test('a CJK chunk shorter than the overlap target is not duplicated wholesale', () => {
+ // Every sentence is < 30 chars; the English path returns '' for a chunk
+ // with fewer words than the overlap target, and the CJK path must too.
+ const text = '第一句话很短。第二句话也不长。第三句话稍微长一点点。第四句话结束了。';
+ const chunks = chunkText(text, { chunkSize: 8, chunkOverlap: 30 });
+ expect(chunks.length).toBeGreaterThan(1);
+ for (let i = 1; i < chunks.length; i++) {
+ expect(chunks[i].text.includes(chunks[i - 1].text)).toBe(false);
+ }
+ });
+
+ test('char-slice fallback keeps astral pairs whole and stays lossless', () => {
+ // Delimiter-free, whitespace-free CJK with an emoji every 44 code units
+ // reaches the L4 char-slice path (one whitespace token longer than the
+ // target). A raw slice at a 13-unit stride halves a 🚀 at some boundary;
+ // the safeSplitIndex cursor must cut around the pair without dropping or
+ // repeating a single code unit. (chunkOverlap 0 is treated as the
+ // default 50, so use 1.)
+ const text = ('一二三四五六七八九十'.repeat(4) + '🚀' + '甲乙丙丁').repeat(12);
+ const chunks = chunkText(text, { chunkSize: 13, chunkOverlap: 1 });
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks) {
+ expect(c.text.isWellFormed()).toBe(true);
+ }
+
+ // Tile the source with the chunks: each one must be found at the cursor,
+ // backed up by at most its overlap (1 char, or a whole pair plus 1).
+ let cursor = 0;
+ for (const c of chunks) {
+ let start = -1;
+ for (let k = 0; k <= 4; k++) {
+ if (cursor - k >= 0 && text.startsWith(c.text, cursor - k)) {
+ start = cursor - k;
+ break;
+ }
+ }
+ expect(start).toBeGreaterThanOrEqual(0);
+ cursor = start + c.text.length;
+ }
+ expect(cursor).toBe(text.length);
+ });
+
+ test('emoji survive overlap path at production chunk params', () => {
+ // Production ingest calls chunkText with ONLY { maxTokens } — chunkSize
+ // 300 / overlap 50 / maxChars 6000 defaults apply, and the overlap is
+ // prepended via extractTrailingContext, not the capByChars path.
+ const parts: string[] = [];
+ for (let i = 0; i < 120; i++) {
+ parts.push(`第${i + 1}段中文说明文字,这里有一枚火箭🚀用于测试代理对完整性。`);
+ }
+ const text = parts.join('\n');
+ const chunks = chunkText(text, { maxTokens: 2000 });
+ expect(chunks.length).toBeGreaterThan(1);
+
+ for (const c of chunks) {
+ expect(c.text.isWellFormed()).toBe(true);
+ }
+
+ // Lossless reconstruction (whitespace-normalized) — no glyph dropped,
+ // no glyph duplicated outside designed overlap.
+ const strip = (s: string) => s.replace(/\s+/g, '');
+ expect(strip(reconstructFromChunks(chunks))).toBe(strip(text));
+ });
+
+ test('English chunks are byte-identical to the pre-CJK-overlap output', () => {
+ // Pure ASCII stays on the whitespace-token path. Hard-coded snapshot of
+ // the chunker's output before the CJK overlap branch existed; any drift
+ // here means the English path changed.
+ const sentences = Array.from(
+ { length: 20 },
+ (_, i) => `Sentence ${i + 1} has exactly eight words in it here.`,
+ );
+ const chunks = chunkText(sentences.join(' '), { chunkSize: 40, chunkOverlap: 8 });
+ expect(chunks.map((c) => c.text)).toEqual([
+ 'Sentence 1 has exactly eight words in it here. Sentence 2 has exactly eight words in it here. Sentence 3 has exactly eight words in it here. Sentence 4 has exactly eight words in it here. Sentence 5 has exactly eight words in it here. Sentence 6 has exactly eight words in it here.',
+ '6 has exactly eight words in it here. Sentence 7 has exactly eight words in it here. Sentence 8 has exactly eight words in it here. Sentence 9 has exactly eight words in it here. Sentence 10 has exactly eight words in it here. Sentence 11 has exactly eight words in it here. Sentence 12 has exactly eight words in it here.',
+ '12 has exactly eight words in it here. Sentence 13 has exactly eight words in it here. Sentence 14 has exactly eight words in it here. Sentence 15 has exactly eight words in it here. Sentence 16 has exactly eight words in it here. Sentence 17 has exactly eight words in it here. Sentence 18 has exactly eight words in it here.',
+ '18 has exactly eight words in it here. Sentence 19 has exactly eight words in it here. Sentence 20 has exactly eight words in it here.',
+ ]);
+ chunks.forEach((c, i) => expect(c.index).toBe(i));
+ });
+
+ test('emoji surrogate pairs survive CJK chunk boundaries whole', () => {
+ // Emoji such as 🚀 are astral: each is a UTF-16 surrogate PAIR (2 code
+ // units). Force the maxChars window path with a small cap so every cut
+ // passes through a boundary, and require every pair to stay whole.
+ const parts: string[] = [];
+ for (let i = 0; i < 80; i++) {
+ parts.push(`第${i + 1}段中文测试文本,包含一个火箭标志🚀来测试代理对。`);
+ }
+ const text = parts.join('');
+ const chunks = chunkText(text, { chunkSize: 50, chunkOverlap: 20, maxChars: 120 });
+ expect(chunks.length).toBeGreaterThan(1);
+
+ for (const c of chunks) {
+ expect(c.text.isWellFormed()).toBe(true);
+ }
+
+ // Every 🚀 must survive in full (not dropped, not half). Chunks overlap by
+ // design, so an 🚀 inside an overlap region legitimately appears in two
+ // adjacent chunks — count against the overlap-free reconstruction, not
+ // the raw chunks.
+ const strip = (s: string) => s.replace(/\s+/g, '');
+ const reconstructedEmojis = strip(reconstructFromChunks(chunks)).split('🚀').length - 1;
+ expect(reconstructedEmojis).toBe(text.split('🚀').length - 1);
+
+ // Lossless reconstruction (whitespace-normalized).
+ expect(strip(reconstructFromChunks(chunks))).toBe(strip(text));
+ });
+});
+
+/** Longest prefix of `curr` that is a suffix of `prev` (the designed overlap). */
+function overlapLength(prev: string, curr: string): number {
+ let overlap = 0;
+ for (let k = 1; k <= Math.min(prev.length, curr.length); k++) {
+ if (prev.endsWith(curr.slice(0, k))) overlap = k;
+ }
+ return overlap;
+}
+
+/**
+ * Reconstruct the original text from overlapped chunks by taking each chunk's
+ * prefix up to where the next chunk's overlap begins. For a sequence of chunks
+ * [C0, C1, C2, ...] where C_{i+1} starts with the trailing overlap of C_i,
+ * this returns C0 + (C1 without its overlap prefix) + (C2 without its overlap
+ * prefix) + ...
+ */
+function reconstructFromChunks(chunks: { text: string; index: number }[]): string {
+ if (chunks.length === 0) return '';
+ let out = chunks[0].text;
+ for (let i = 1; i < chunks.length; i++) {
+ out += chunks[i].text.slice(overlapLength(chunks[i - 1].text, chunks[i].text));
+ }
+ return out;
+}
diff --git a/test/ci-local-empty-mounts.test.ts b/test/ci-local-empty-mounts.test.ts
new file mode 100644
index 0000000000..f3679a0ee9
--- /dev/null
+++ b/test/ci-local-empty-mounts.test.ts
@@ -0,0 +1,36 @@
+import { expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+
+// Execute the real runner invocation with Docker replaced by an argv recorder.
+// On macOS /bin/bash is 3.2, where an empty array under nounset is special.
+const line = readFileSync(new URL('../scripts/ci-local.sh', import.meta.url), 'utf8')
+ .split('\n').find(value => value.startsWith('docker compose ') && value.includes('EXTRA_MOUNTS'));
+
+for (const populated of [false, true]) {
+ test(`ci-local runner preserves ${populated ? 'worktree' : 'empty'} mount argv`, () => {
+ expect(line).toBeDefined();
+ const script = [
+ 'set -eu',
+ 'COMPOSE_FILE=compose.yml',
+ 'INNER_CMD="echo test"',
+ populated ? 'EXTRA_MOUNTS=(-v "/tmp/path with spaces:/git:ro")' : 'EXTRA_MOUNTS=()',
+ 'docker() { printf "<%s>\\n" "$@"; }',
+ line!,
+ ].join('\n');
+ const result = spawnSync('/bin/bash', ['-c', script], { encoding: 'utf8' });
+ expect(result.status).toBe(0);
+ expect(result.stderr).toBe('');
+ const expected = ['compose', '-f', 'compose.yml', 'run', '--rm',
+ ...(populated ? ['-v', '/tmp/path with spaces:/git:ro'] : []),
+ 'runner', 'bash', '-c', 'echo test'];
+ expect(result.stdout).toBe(expected.map(value => `<${value}>\n`).join(''));
+ });
+}
+
+// bash >= 4.4 (Linux CI) tolerates "${EXTRA_MOUNTS[@]}" on an empty array under nounset, so the
+// argv repro above only bites on macOS bash 3.2. Pin the safe expansion textually so Linux catches it too.
+test('ci-local runner keeps the bash-3.2-safe empty-array expansion', () => {
+ expect(line).toBeDefined();
+ expect(line).toContain('${EXTRA_MOUNTS[@]+"${EXTRA_MOUNTS[@]}"}');
+});
diff --git a/test/claude-cli-recipe.test.ts b/test/claude-cli-recipe.test.ts
index 7c85bb836f..ca50fddffc 100644
--- a/test/claude-cli-recipe.test.ts
+++ b/test/claude-cli-recipe.test.ts
@@ -16,7 +16,7 @@
* withEnv's save/restore in try/finally is sufficient; no leakage to
* sibling test files in the same bun-test process.
*/
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';
import { writeFileSync, chmodSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -78,7 +78,7 @@ function userMessage(text: string): LanguageModelV2CallOptions['prompt'][number]
}
describe('claude-cli recipe registration', () => {
- test('getRecipe returns chat-only Recipe with the documented models', async () => {
+ test('getRecipe returns chat + expansion Recipe with the documented models', async () => {
const { getRecipe } = await import('../src/core/ai/recipes/index.ts');
const recipe = getRecipe('claude-cli');
expect(recipe).toBeDefined();
@@ -90,11 +90,24 @@ describe('claude-cli recipe registration', () => {
expect(recipe!.touchpoints.chat!.models).toContain('claude-sonnet-4-6');
// Wave rider for #3976: pin the Claude 5 family the CLI already serves.
expect(recipe!.touchpoints.chat!.models).toContain('claude-fable-5');
+ expect(recipe!.touchpoints.chat!.models).toContain('claude-fable-5-1');
expect(recipe!.touchpoints.chat!.models).toContain('claude-opus-5');
expect(recipe!.touchpoints.chat!.models).toContain('claude-opus-4-8');
expect(recipe!.touchpoints.chat!.models).toContain('claude-sonnet-5');
expect(recipe!.touchpoints.embedding).toBeUndefined();
- expect(recipe!.touchpoints.expansion).toBeUndefined();
+ // Expansion IS declared. Without it `isAvailable('expansion')` is false
+ // for every claude-cli model, so expandQuery() returns [query] before any
+ // model call and query expansion vanishes with no error — while `gbrain
+ // models doctor` still shows the touchpoint green (its probe calls chat()
+ // with an explicit model override and never consults the recipe).
+ expect(recipe!.touchpoints.expansion).toBeDefined();
+ expect(recipe!.touchpoints.expansion!.models).toContain('claude-haiku-4-5-20251001');
+ expect(recipe!.touchpoints.expansion!.models).toContain('claude-sonnet-5');
+ // #4794 added claude-fable-5-1 to chat; expansion must carry it too (wave review drift).
+ expect(recipe!.touchpoints.expansion!.models).toContain('claude-fable-5-1');
+ // Subprocess cold start needs the same headroom the chat touchpoint takes;
+ // the probe's flat 5000ms default would false-fail on every run.
+ expect(recipe!.touchpoints.expansion!.default_timeout_ms).toBe(30_000);
});
test('recipe aliases map short names to canonical model ids', async () => {
@@ -370,6 +383,177 @@ describe('claude-cli LanguageModel — tool use', () => {
});
});
+ // Regression: prose that MENTIONS the tag before using it.
+ //
+ // Shape taken from a real dream-synthesis child that produced no page while
+ // its job reported `completed`. The model opened with a self-correction that
+ // named the tag inside backticks, THEN emitted a valid block. The old parser
+ // anchored on `indexOf(openTag)`, landing on the backticked mention, so
+ // `inner` began "` format:\n\n<use_tools>…" — JSON.parse threw and the catch
+ // discarded a complete tool call as prose. Content here is synthetic; only
+ // the structure (mention-then-use, multi-line string payload) is reproduced.
+ test('anchors on the real block when the tag is mentioned in prose first', async () => {
+ await withStubEnv(async () => {
+ stageResponse(
+ baseEnvelope(
+ [
+ 'I used the wrong invocation format. Let me use the correct `<use_tools>` format:',
+ '',
+ '<use_tools>',
+ '[{"name": "search", "input": {"query": "line one\\nline two\\nline three"}}]',
+ '</use_tools>',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('mention then use')],
+ tools: [{ type: 'function', name: 'search', description: '', inputSchema: { type: 'object', properties: {} } }],
+ } as LanguageModelV2CallOptions);
+
+ const calls = result.content.filter(c => c.type === 'tool-call');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({ type: 'tool-call', toolName: 'search' });
+ expect(result.finishReason).toBe('tool-calls');
+ });
+ });
+
+ test('a prose mention of the CLOSE tag before the real block does not drop the call', async () => {
+ // Mirror of the open-tag mention above. The first `</use_tools>` in the
+ // text is a backticked mention with no opening tag ahead of it; anchoring
+ // on it (the old `openIdx === -1` arm) discarded the valid block below.
+ await withStubEnv(async () => {
+ stageResponse(
+ baseEnvelope(
+ [
+ 'Earlier I closed with `</use_tools>` before the JSON. Corrected call:',
+ '',
+ '<use_tools>',
+ '[{"name": "search", "input": {"query": "line one\\nline two"}}]',
+ '</use_tools>',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('close-tag mention then use')],
+ tools: [{ type: 'function', name: 'search', description: '', inputSchema: { type: 'object', properties: {} } }],
+ } as LanguageModelV2CallOptions);
+
+ const calls = result.content.filter(c => c.type === 'tool-call');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({ type: 'tool-call', toolName: 'search', input: '{"query":"line one\\nline two"}' });
+ expect(result.finishReason).toBe('tool-calls');
+ });
+ });
+
+ test('a literal <use_tools> tag inside a JSON string argument does not re-anchor the block', async () => {
+ // A page body that documents the tool protocol carries the OPEN tag inside
+ // the `content` string. Anchoring on "the last open tag before the close"
+ // picked that inner tag, sliced truncated JSON, and discarded the write.
+ await withStubEnv(async () => {
+ const content = 'Protocol: wrap calls in <use_tools> and close them.';
+ stageResponse(
+ baseEnvelope(
+ [
+ 'Writing the protocol page.',
+ '<use_tools>',
+ JSON.stringify([{ name: 'put_page', input: { slug: 'docs/protocol', content } }]),
+ '</use_tools>',
+ 'Done.',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('write the protocol page')],
+ tools: [{ type: 'function', name: 'put_page', description: '', inputSchema: { type: 'object', properties: {} } }],
+ } as LanguageModelV2CallOptions);
+
+ const calls = result.content.filter(c => c.type === 'tool-call');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ type: 'tool-call',
+ toolName: 'put_page',
+ input: JSON.stringify({ slug: 'docs/protocol', content }),
+ });
+ expect(result.content[0]).toMatchObject({ type: 'text', text: 'Writing the protocol page.' });
+ expect(result.finishReason).toBe('tool-calls');
+ });
+ });
+
+ test('a literal </use_tools> tag inside a JSON string argument does not terminate the block early', async () => {
+ // Mirror: the CLOSE tag inside the argument. Anchoring on the first close
+ // tag sliced the JSON mid-string; the parser must skip to the real close.
+ await withStubEnv(async () => {
+ const content = 'Protocol: end every block with </use_tools> on its own line.';
+ stageResponse(
+ baseEnvelope(
+ [
+ '<use_tools>',
+ JSON.stringify([{ name: 'put_page', input: { slug: 'docs/protocol', content } }]),
+ '</use_tools>',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('write the protocol page')],
+ tools: [{ type: 'function', name: 'put_page', description: '', inputSchema: { type: 'object', properties: {} } }],
+ } as LanguageModelV2CallOptions);
+
+ const calls = result.content.filter(c => c.type === 'tool-call');
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ type: 'tool-call',
+ toolName: 'put_page',
+ input: JSON.stringify({ slug: 'docs/protocol', content }),
+ });
+ expect(result.finishReason).toBe('tool-calls');
+ });
+ });
+
+ test('a malformed <use_tools> block is discarded as prose AND reported on stderr', async () => {
+ // A lost tool call must not be silent: the turn ends as if the model
+ // never called anything, so the only trace is this diagnostic.
+ const writes: string[] = [];
+ const stderr = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
+ writes.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write);
+ try {
+ await withStubEnv(async () => {
+ stageResponse(
+ baseEnvelope(
+ [
+ '<use_tools>',
+ '[{"name": "search", "input": {"query": }]',
+ '</use_tools>',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('malformed')],
+ tools: [{ type: 'function', name: 'search', description: '', inputSchema: { type: 'object', properties: {} } }],
+ } as LanguageModelV2CallOptions);
+
+ expect(result.content.filter(c => c.type === 'tool-call')).toHaveLength(0);
+ expect(result.finishReason).toBe('stop');
+ const diag = writes.filter(w => w.startsWith('[claude-cli] <use_tools> block failed to parse'));
+ expect(diag).toHaveLength(1);
+ expect(diag[0]).toContain('tool call discarded');
+ });
+ } finally {
+ stderr.mockRestore();
+ }
+ });
+
test('tolerates fenced JSON inside <use_tools>', async () => {
await withStubEnv(async () => {
stageResponse(
@@ -419,6 +603,55 @@ describe('claude-cli LanguageModel — tool use', () => {
});
});
+ test('flat entries (arguments beside `name`, no `input` wrapper) are parsed as the input', async () => {
+ await withStubEnv(async () => {
+ // The Anthropic tool_use shape with the `input` wrapper dropped. A dream
+ // subagent that emitted this called brain_search eight times in a row
+ // with input {} and never received a result it could use.
+ stageResponse(
+ baseEnvelope(
+ [
+ '<use_tools>',
+ '[',
+ ' {"type": "tool_use", "id": "toolu_01", "name": "search", "query": "n+1 query", "limit": 5},',
+ ' {"name": "search", "input": {"query": "wrapped wins"}, "query": "stray key ignored"},',
+ ' {"name": "search"},',
+ ' {"name": "search", "type": "person", "id": "areas/x"}',
+ ']',
+ '</use_tools>',
+ ].join('\n'),
+ ),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('flat')],
+ tools: [
+ {
+ type: 'function',
+ name: 'search',
+ description: 'Search the brain',
+ inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
+ },
+ ],
+ } as LanguageModelV2CallOptions);
+
+ expect(result.finishReason).toBe('tool-calls');
+ const calls = result.content.filter(c => c.type === 'tool-call') as Array<{ toolName: string; input: string }>;
+ expect(calls).toHaveLength(4);
+ // Flat entry: the non-reserved keys become the input; the Anthropic
+ // tool_use leftovers (type: "tool_use", toolu_* id) and name do not leak in.
+ expect(JSON.parse(calls[0].input)).toEqual({ query: 'n+1 query', limit: 5 });
+ // A wrapped `input` wins verbatim over stray sibling keys.
+ expect(JSON.parse(calls[1].input)).toEqual({ query: 'wrapped wins' });
+ // Nothing beside `name` still yields an empty input.
+ expect(JSON.parse(calls[2].input)).toEqual({});
+ // A `type`/`id` that is NOT the Anthropic leftover is a real argument
+ // (list_pages has a `type` filter) and survives flat mode.
+ expect(JSON.parse(calls[3].input)).toEqual({ type: 'person', id: 'areas/x' });
+ });
+ });
+
test('falls back to text on malformed JSON', async () => {
await withStubEnv(async () => {
stageResponse(
diff --git a/test/cli-dispatch-thin-client.test.ts b/test/cli-dispatch-thin-client.test.ts
index bbf8b9bac8..66f59a3988 100644
--- a/test/cli-dispatch-thin-client.test.ts
+++ b/test/cli-dispatch-thin-client.test.ts
@@ -31,16 +31,12 @@
* to connectEngine normally.
*/
-import { describe, test as testRaw, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync, existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { runCli, runCliBatch, type CliResult } from './helpers/cli-spawn.ts';
-function test(name: string, fn: () => void | Promise<unknown>): void {
- testRaw(name, fn, 30000);
-}
-
// The original hand-rolled spawner stripped this alongside the database
// URLs; cli-spawn.ts strips only the URLs, so keep stripping it here.
const HERMETIC_ENV = { GBRAIN_REMOTE_CLIENT_SECRET: undefined } as const;
diff --git a/test/cli-format-get-page-json.test.ts b/test/cli-format-get-page-json.test.ts
new file mode 100644
index 0000000000..1d22e64af3
--- /dev/null
+++ b/test/cli-format-get-page-json.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'bun:test';
+import { formatResult } from '../src/cli.ts';
+
+/**
+ * `gbrain get <slug> --json` accepted `--json` and silently printed the
+ * markdown serialization anyway (same class as the get_versions fix).
+ */
+describe('formatResult - get_page --json', () => {
+ const page = {
+ slug: 'ops/tasks',
+ type: 'note',
+ title: 'Tasks',
+ compiled_truth: '# Tasks',
+ timeline: '',
+ frontmatter: { status: 'active' },
+ tags: [],
+ content_hash: 'a'.repeat(64),
+ content: '---\nstatus: active\n---\n\n# Tasks\n',
+ };
+
+ test('returns the full machine-readable page including hash and content', () => {
+ expect(JSON.parse(formatResult('get_page', page, { json: true }))).toEqual(page);
+ });
+
+ test('--json on an ambiguous slug emits the error envelope, not human text', () => {
+ const r = { error: 'ambiguous_slug', candidates: ['alice-example', 'alice-example-2'] };
+ expect(JSON.parse(formatResult('get_page', r, { json: true }))).toEqual(r);
+ });
+
+ test('keeps markdown as the default human output', () => {
+ const output = formatResult('get_page', page, {});
+ expect(output).toContain('# Tasks');
+ expect(output).not.toContain('content_hash');
+ });
+
+ test('--json=false stays on the human path', () => {
+ expect(() => JSON.parse(formatResult('get_page', page, { json: false }))).toThrow();
+ });
+});
diff --git a/test/code-intel-source-scope.test.ts b/test/code-intel-source-scope.test.ts
index c1092d24eb..bd293aadd5 100644
--- a/test/code-intel-source-scope.test.ts
+++ b/test/code-intel-source-scope.test.ts
@@ -145,4 +145,83 @@ describe('code reads require trusted local context while remote authorization is
expect(JSON.stringify(defs.defs)).toContain('beta');
expect(JSON.stringify(refs.refs)).toContain('beta');
});
+
+ test('trusted local code_blast and code_flow carry the readiness envelope on a miss', async () => {
+ // A bare {result:'not_found'} conflates "graph not built" with "zero
+ // callers". The graph IS built for srcalpha (symbol-bearing chunks exist),
+ // so a miss on a symbol that lives only in srcbeta must read as a trusted
+ // miss: status 'ready', ready true — the same contract the four siblings
+ // (code_callers/callees/def/refs) already carry.
+ await seedTwoSourceCodeGraph();
+ const ctx = localAlpha();
+ const blast = await operationsByName.code_blast.handler(ctx, { symbol: 'betaSecretFn' }) as { result: string; status?: string; ready?: boolean };
+ const flow = await operationsByName.code_flow.handler(ctx, { entry_point: 'betaSecretFn' }) as { result: string; status?: string; ready?: boolean };
+ expect(blast.result).toBe('not_found');
+ expect(blast.status).toBe('ready');
+ expect(blast.ready).toBe(true);
+ expect(flow.result).toBe('not_found');
+ expect(flow.status).toBe('ready');
+ expect(flow.ready).toBe(true);
+ });
+});
+
+// ─── attachWalkReadiness branches (src/core/ops/code-intel.ts → code-graph-readiness.ts) ───
+
+type WalkEnvelope = {
+ result: string;
+ status?: string;
+ ready?: boolean;
+ scoped_source_id?: string;
+ depth_groups?: { nodes: unknown[] }[];
+};
+
+describe('code_blast / code_flow readiness envelope distinguishes unbuilt, out-of-scope, and ready graphs', () => {
+ test('unseeded brain (no code anywhere) → status not_built, ready false, no scoped_source_id', async () => {
+ // Nothing seeded: beforeEach left every table empty. A miss here is NOT
+ // a trusted miss — the graph was never built — so the envelope must say
+ // so instead of the bare {result:'not_found'} an agent reads as "no callers".
+ const ctx = localAlpha();
+ const blast = await operationsByName.code_blast.handler(ctx, { symbol: 'alphaTargetFn' }) as WalkEnvelope;
+ const flow = await operationsByName.code_flow.handler(ctx, { entry_point: 'alphaCallerFn' }) as WalkEnvelope;
+ for (const walk of [blast, flow]) {
+ expect(walk.result).toBe('not_found');
+ expect(walk.status).toBe('not_built');
+ expect(walk.ready).toBe(false);
+ expect(walk.scoped_source_id).toBeUndefined();
+ }
+ });
+
+ test('ctx scoped to a code-less source while code exists elsewhere → status out_of_scope naming the scoped source', async () => {
+ // The graph IS built (srcalpha + srcbeta hold code) but the caller's
+ // resolved scope is srcgamma, which holds none. That is a scope/grant
+ // problem, not an indexing one: the envelope must carry `scoped_source_id`
+ // so the hint can name the scope instead of misdirecting to `gbrain sync`.
+ await seedTwoSourceCodeGraph();
+ await registerSource('srcgamma');
+ const ctx = ctxOf({ remote: false, sourceId: 'srcgamma' });
+ const blast = await operationsByName.code_blast.handler(ctx, { symbol: 'alphaTargetFn' }) as WalkEnvelope;
+ const flow = await operationsByName.code_flow.handler(ctx, { entry_point: 'alphaCallerFn' }) as WalkEnvelope;
+ for (const walk of [blast, flow]) {
+ expect(walk.result).toBe('not_found');
+ expect(walk.status).toBe('out_of_scope');
+ expect(walk.ready).toBe(false);
+ expect(walk.scoped_source_id).toBe('srcgamma');
+ }
+ });
+
+ test('a walk that returns nodes → status ready, ready true, no scoped_source_id', async () => {
+ await seedTwoSourceCodeGraph();
+ const ctx = localAlpha();
+ // callers of alphaTargetFn in srcalpha: alphaCallerFn + sharedCallerFn
+ const blast = await operationsByName.code_blast.handler(ctx, { symbol: 'alphaTargetFn' }) as WalkEnvelope;
+ // callees of alphaCallerFn in srcalpha: alphaTargetFn
+ const flow = await operationsByName.code_flow.handler(ctx, { entry_point: 'alphaCallerFn' }) as WalkEnvelope;
+ for (const walk of [blast, flow]) {
+ expect(walk.result).toBe('ok');
+ expect((walk.depth_groups ?? []).reduce((n, g) => n + g.nodes.length, 0)).toBeGreaterThan(0);
+ expect(walk.status).toBe('ready');
+ expect(walk.ready).toBe(true);
+ expect(walk.scoped_source_id).toBeUndefined();
+ }
+ });
});
diff --git a/test/codex-hook-lane-archived.test.ts b/test/codex-hook-lane-archived.test.ts
new file mode 100644
index 0000000000..0c12ff9640
--- /dev/null
+++ b/test/codex-hook-lane-archived.test.ts
@@ -0,0 +1,184 @@
+/**
+ * codex hook lane — the two coupled defects that made an archived rollout
+ * unreachable end-to-end:
+ *
+ * 1. `confineCodexTranscriptPath` collapsed EVERY lstat failure to
+ * `unreadable`, so a vanished path never reached hook.ts's
+ * `reason === 'missing_path'` gate and discovery never engaged.
+ * 2. Confinement and discovery both knew only `<codex home>/sessions`, so a
+ * rollout codex had moved to `<codex home>/archived_sessions` was refused
+ * as `outside_projects_dir` and was invisible to the fallback walk.
+ *
+ * The archived store is FLAT (no YYYY/MM/DD nesting), which is why the dated
+ * walk alone could never see it.
+ *
+ * The degrade label matters: hook.ts computes
+ * `discoveryWasGuess = found.degrade === 'transcript_discovered_newest'`, so
+ * an id-MATCHED archived hit must keep `transcript_discovered` — labelling it
+ * `_newest` would misclassify a real match as a guess and suppress the relay.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ confineCodexTranscriptPath,
+ discoverNewestCodexRollout,
+} from '../src/core/transcripts/codex-hook-lane.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gb-cdx-arch-'));
+});
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+const meta = JSON.stringify({
+ timestamp: 't0',
+ type: 'session_meta',
+ payload: { id: 'r-1', session_id: 'cdx-sess-1', timestamp: 't0', cwd: '/repo', cli_version: '0.147.0' },
+});
+
+/** Seed the FLAT archived store under a codex home. */
+function seedArchived(home: string, name = 'rollout-2026-08-20-zzz-sess-arch.jsonl'): string {
+ const arch = join(home, 'archived_sessions');
+ mkdirSync(arch, { recursive: true });
+ const p = join(arch, name);
+ writeFileSync(p, meta + '\n');
+ return p;
+}
+
+describe('confineCodexTranscriptPath — the missing_path rung', () => {
+ test('a vanished path reports missing_path, not unreadable (hook.ts gates discovery on it)', () => {
+ const root = join(dir, 'sessions');
+ const day = join(root, '2026', '08', '25');
+ mkdirSync(day, { recursive: true });
+ expect(confineCodexTranscriptPath(join(day, 'gone.jsonl'), { root })).toEqual({
+ ok: false,
+ reason: 'missing_path',
+ });
+
+ // ENOTDIR — a path component that is a file, not a directory. Also "this
+ // path does not exist as given", so it takes the same rung.
+ const real = join(day, 'rollout-real-sess-a.jsonl');
+ writeFileSync(real, meta + '\n');
+ expect(confineCodexTranscriptPath(join(real, 'nested.jsonl'), { root })).toEqual({
+ ok: false,
+ reason: 'missing_path',
+ });
+ });
+});
+
+describe('confineCodexTranscriptPath — the archived store is inside the fence', () => {
+ test('a rollout under archived_sessions is accepted by the PRODUCTION default (root undefined)', async () => {
+ await withEnv({ CODEX_HOME: dir }, async () => {
+ mkdirSync(join(dir, 'sessions'), { recursive: true });
+ const archived = seedArchived(dir);
+ expect(confineCodexTranscriptPath(archived)).toEqual({
+ ok: true,
+ path: archived,
+ size: expect.any(Number),
+ });
+
+ // The live store still resolves through that same default.
+ const day = join(dir, 'sessions', '2026', '08', '25');
+ mkdirSync(day, { recursive: true });
+ const live = join(day, 'rollout-live-sess-b.jsonl');
+ writeFileSync(live, meta + '\n');
+ expect(confineCodexTranscriptPath(live)).toEqual({ ok: true, path: live, size: expect.any(Number) });
+ });
+ });
+
+ test('PRESERVED: an explicitly pinned root stays single-root — the test seam never widens', async () => {
+ await withEnv({ CODEX_HOME: dir }, async () => {
+ const root = join(dir, 'sessions');
+ mkdirSync(root, { recursive: true });
+ const archived = seedArchived(dir);
+ expect(confineCodexTranscriptPath(archived, { root })).toEqual({
+ ok: false,
+ reason: 'outside_projects_dir',
+ });
+ expect(discoverNewestCodexRollout('sess-arch', { root })).toBeNull();
+ });
+ });
+
+ test('PRESERVED: paths outside BOTH stores are still refused', async () => {
+ await withEnv({ CODEX_HOME: dir }, async () => {
+ mkdirSync(join(dir, 'sessions'), { recursive: true });
+ mkdirSync(join(dir, 'archived_sessions'), { recursive: true });
+
+ const outside = join(dir, 'outside.jsonl');
+ writeFileSync(outside, meta + '\n');
+ expect(confineCodexTranscriptPath(outside)).toEqual({ ok: false, reason: 'outside_projects_dir' });
+
+ // A directory that merely shares the archived NAME but sits elsewhere is
+ // not a root — the widening is two pinned paths, not a name match.
+ const decoy = join(dir, 'nested', 'archived_sessions');
+ mkdirSync(decoy, { recursive: true });
+ const decoyFile = join(decoy, 'rollout-decoy-sess-d.jsonl');
+ writeFileSync(decoyFile, meta + '\n');
+ expect(confineCodexTranscriptPath(decoyFile)).toEqual({ ok: false, reason: 'outside_projects_dir' });
+ });
+ });
+
+ test('PRESERVED: the whole ladder applies to the archived root in the same order', async () => {
+ await withEnv({ CODEX_HOME: dir }, async () => {
+ mkdirSync(join(dir, 'sessions'), { recursive: true });
+ const arch = join(dir, 'archived_sessions');
+ mkdirSync(arch, { recursive: true });
+
+ expect(confineCodexTranscriptPath('')).toEqual({ ok: false, reason: 'missing_path' });
+ expect(confineCodexTranscriptPath(join(arch, 'x.txt'))).toEqual({ ok: false, reason: 'not_jsonl' });
+
+ const evil = join(dir, 'evil.jsonl');
+ writeFileSync(evil, meta + '\n');
+ const link = join(arch, 'rollout-link-sess-e.jsonl');
+ symlinkSync(evil, link);
+ expect(confineCodexTranscriptPath(link)).toEqual({ ok: false, reason: 'symlink' });
+
+ const fat = join(arch, 'rollout-fat-sess-f.jsonl');
+ writeFileSync(fat, 'x'.repeat(64));
+ expect(confineCodexTranscriptPath(fat, { maxBytes: 16 })).toEqual({ ok: false, reason: 'too_large' });
+ });
+ });
+});
+
+describe('discoverNewestCodexRollout — reaches the flat archived store', () => {
+ test('an id match in archived_sessions is found and is NOT labelled a guess', async () => {
+ await withEnv({ CODEX_HOME: dir }, async () => {
+ mkdirSync(join(dir, 'sessions'), { recursive: true });
+ const archived = seedArchived(dir);
+ // Production default: root undefined → both stores.
+ expect(discoverNewestCodexRollout('sess-arch')).toEqual({
+ path: archived,
+ degrade: 'transcript_discovered',
+ });
+ });
+ });
+
+ test('with no id the newest across BOTH stores wins; archived symlinks are still refused', () => {
+ const root = join(dir, 'sessions');
+ const arch = join(dir, 'archived_sessions');
+ const day = join(root, '2026', '08', '25');
+ mkdirSync(day, { recursive: true });
+ mkdirSync(arch, { recursive: true });
+ const live = join(day, 'rollout-live-sess-g.jsonl');
+ const archived = join(arch, 'rollout-arch-sess-h.jsonl');
+ writeFileSync(live, meta + '\n');
+ writeFileSync(archived, meta + '\n');
+ const past = new Date(Date.now() - 60_000);
+ utimesSync(live, past, past); // the archived copy is newer
+
+ expect(discoverNewestCodexRollout(null, { root, archivedRoot: arch })).toEqual({
+ path: archived,
+ degrade: 'transcript_discovered_newest',
+ });
+
+ const evil = join(dir, 'evil2.jsonl');
+ writeFileSync(evil, meta + '\n');
+ symlinkSync(evil, join(arch, 'rollout-linked-sess-i.jsonl'));
+ expect(discoverNewestCodexRollout('sess-i', { root, archivedRoot: arch })).toBeNull();
+ });
+});
diff --git a/test/codex-hook-lane.test.ts b/test/codex-hook-lane.test.ts
index e08acfcb13..f9550af3f9 100644
--- a/test/codex-hook-lane.test.ts
+++ b/test/codex-hook-lane.test.ts
@@ -116,7 +116,10 @@ describe('confineCodexTranscriptPath — the S3#8 ladder on the codex root', ()
expect(confineCodexTranscriptPath(undefined, { root })).toEqual({ ok: false, reason: 'missing_path' });
expect(confineCodexTranscriptPath(join(day, 'x.txt'), { root })).toEqual({ ok: false, reason: 'not_jsonl' });
- expect(confineCodexTranscriptPath(join(day, 'absent.jsonl'), { root })).toEqual({ ok: false, reason: 'unreadable' });
+ // A path that simply is not there is `missing_path`, NOT `unreadable` —
+ // hook.ts gates its discovery fallback on that rung, and `unreadable` is
+ // reserved for a real permission/IO fault.
+ expect(confineCodexTranscriptPath(join(day, 'absent.jsonl'), { root })).toEqual({ ok: false, reason: 'missing_path' });
const outside = join(dir, 'outside.jsonl');
writeFileSync(outside, meta + '\n');
diff --git a/test/codex-plugin-manifest.test.ts b/test/codex-plugin-manifest.test.ts
index ee84fe667b..b83dc1ec1d 100644
--- a/test/codex-plugin-manifest.test.ts
+++ b/test/codex-plugin-manifest.test.ts
@@ -234,10 +234,21 @@ describe('launcher (static)', () => {
expect(text).not.toMatch(/npm install -g gbrain(?!['\w-])(?![^\n]*unrelated)/);
});
- test('the two NEW manifests reference the same launcher path (openclaw intentionally differs)', () => {
+ test('all three manifests reference the shared launcher (#4841)', () => {
expect(codexMcp.mcpServers.gbrain.command).toBe(LAUNCHER);
expect(claudePlugin.mcpServers.gbrain.command).toBe('${CLAUDE_PLUGIN_ROOT}/.agents/gbrain-launcher');
- expect(openclawPlugin.mcpServers.gbrain.command).toBe('./bin/gbrain');
+ expect(openclawPlugin.mcpServers.gbrain.command).toBe(LAUNCHER);
+ expect(openclawPlugin.mcpServers.gbrain.args).toEqual(['serve']);
+ });
+
+ test('the OpenClaw command is a TRACKED file, never a build artifact (#4841)', () => {
+ // OpenClaw resolves a `./`-prefixed command against the plugin root; a
+ // gitignored `bin/gbrain` is never in any install layout, so the server
+ // silently never spawns. existsSync would pass on any dev box that ran
+ // `bun run build` — only git's index tells the truth.
+ const rel = (openclawPlugin.mcpServers.gbrain.command as string).replace(/^\.\//, '');
+ const r = spawnSync('git', ['ls-files', '--error-unmatch', rel], { cwd: ROOT, encoding: 'utf8' });
+ expect(r.status, `${rel} is not tracked: ${r.stderr}`).toBe(0);
});
});
diff --git a/test/config-db-merge.test.ts b/test/config-db-merge.test.ts
index 64c1d20ad4..b6a3d97643 100644
--- a/test/config-db-merge.test.ts
+++ b/test/config-db-merge.test.ts
@@ -109,6 +109,7 @@ describe('applyDbPlaneReadSideMerge — batched read (D2)', () => {
const { engine } = makeBatchEngine({
openai_api_key: 'sk-db-example',
voyage_api_key: 'vg-db-example',
+ deepseek_api_key: 'ds-db-example',
expansion_model: 'openai:gpt-5-mini',
chat_model: 'anthropic:claude-haiku-4-5',
chat_fallback_chain: 'anthropic:claude-haiku-4-5, openai:gpt-5-mini',
@@ -120,6 +121,7 @@ describe('applyDbPlaneReadSideMerge — batched read (D2)', () => {
expect(merged.openai_api_key).toBe('sk-db-example');
expect(merged.voyage_api_key).toBe('vg-db-example');
+ expect(merged.deepseek_api_key).toBe('ds-db-example');
expect(merged.expansion_model).toBe('openai:gpt-5-mini');
expect(merged.chat_model).toBe('anthropic:claude-haiku-4-5');
expect(merged.chat_fallback_chain).toEqual([
diff --git a/test/config-env-hijack.test.ts b/test/config-env-hijack.test.ts
index 3dafe6e022..347e775d05 100644
--- a/test/config-env-hijack.test.ts
+++ b/test/config-env-hijack.test.ts
@@ -39,6 +39,29 @@ describe('dotenvValuesForKey', () => {
}
});
+ test('collects assignments from per-NODE_ENV .local variants (#4895)', () => {
+ // Bun auto-loads `.env.${NODE_ENV}.local` too (development is the default
+ // NODE_ENV), so a DATABASE_URL parked there must be recognised as
+ // file-origin. A name outside Bun's set stays ignored — the list is a
+ // bounded superset, not "anything named .env.*".
+ const dir = tmpProject({
+ '.env.development.local': 'DATABASE_URL=postgres://dev.example.test/app\n',
+ '.env.production.local': 'DATABASE_URL=postgres://prod.example.test/app\n',
+ '.env.test.local': 'DATABASE_URL=postgres://test.example.test/app\n',
+ '.env.staging': 'DATABASE_URL=postgres://staging.example.test/app\n',
+ });
+ try {
+ const values = dotenvValuesForKey('DATABASE_URL', dir);
+ expect(values.has('postgres://dev.example.test/app')).toBe(true);
+ expect(values.has('postgres://prod.example.test/app')).toBe(true);
+ expect(values.has('postgres://test.example.test/app')).toBe(true);
+ expect(values.has('postgres://staging.example.test/app')).toBe(false);
+ expect(values.size).toBe(3);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('handles export prefix, double quotes, comments, and unrelated keys', () => {
const dir = tmpProject({
'.env': [
@@ -86,6 +109,20 @@ describe('effectiveEnvDatabaseUrl (#427 guard)', () => {
}
});
+ test('ignores DATABASE_URL whose value matches a cwd .env.development.local assignment (#4895)', async () => {
+ const dir = tmpProject({ '.env.development.local': `DATABASE_URL=${HIJACK_URL}\n` });
+ try {
+ await withEnv(
+ { GBRAIN_DATABASE_URL: undefined, DATABASE_URL: HIJACK_URL },
+ () => {
+ expect(effectiveEnvDatabaseUrl(dir)).toBeUndefined();
+ },
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('honors an exported DATABASE_URL that differs from the cwd .env', async () => {
const dir = tmpProject({ '.env': `DATABASE_URL=${HIJACK_URL}\n` });
try {
diff --git a/test/config-file-plane-keys.test.ts b/test/config-file-plane-keys.test.ts
index 7f17dc3a7e..1d983008b7 100644
--- a/test/config-file-plane-keys.test.ts
+++ b/test/config-file-plane-keys.test.ts
@@ -201,6 +201,7 @@ const GATEWAY_MAPPED_KEYS = [
'openrouter_api_key',
'voyage_api_key',
'dashscope_api_key',
+ 'deepseek_api_key',
'google_api_key',
] as const;
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
index d7b5ee0f3e..8f24481bc3 100644
--- a/test/config-set.test.ts
+++ b/test/config-set.test.ts
@@ -84,6 +84,7 @@ describe('KNOWN_CONFIG_KEYS', () => {
expect(KNOWN_CONFIG_KEYS).toContain('agent.use_gateway_loop');
expect(KNOWN_CONFIG_KEYS).toContain('openrouter_api_key');
expect(KNOWN_CONFIG_KEYS).toContain('zeroentropy_api_key');
+ expect(KNOWN_CONFIG_KEYS).toContain('deepseek_api_key');
});
test('registers the provider_sunset suppression key (v0.46.3 documented command)', () => {
diff --git a/test/console-prefix.test.ts b/test/console-prefix.test.ts
index 6d0e5e0487..622dd598f9 100644
--- a/test/console-prefix.test.ts
+++ b/test/console-prefix.test.ts
@@ -19,6 +19,7 @@ import {
getSourcePrefix,
slog,
serr,
+ withHumanLogsToStderr,
withSourcePrefix,
} from '../src/core/console-prefix.ts';
@@ -151,3 +152,37 @@ describe('slog / serr line prefixing', () => {
}
});
});
+
+describe('withHumanLogsToStderr (#4888: CLI --json keeps stdout pure)', () => {
+ test('unprefixed slog inside the wrap goes to console.error, never console.log', async () => {
+ const origLog = console.log;
+ const origErr = console.error;
+ const logged: unknown[][] = [];
+ const errored: unknown[][] = [];
+ // eslint-disable-next-line no-console
+ console.log = (...args: unknown[]) => { logged.push(args); };
+ // eslint-disable-next-line no-console
+ console.error = (...args: unknown[]) => { errored.push(args); };
+ try {
+ await withHumanLogsToStderr(async () => { slog('human line'); });
+ expect(logged).toEqual([]);
+ expect(errored).toEqual([['human line']]);
+ // Outside the wrap the back-compat fast path is untouched.
+ slog('after');
+ expect(logged).toEqual([['after']]);
+ } finally {
+ // eslint-disable-next-line no-console
+ console.log = origLog;
+ // eslint-disable-next-line no-console
+ console.error = origErr;
+ }
+ });
+
+ test('prefixed slog inside the wrap writes the prefixed line to stderr; stdout stays untouched', async () => {
+ const { stdout, stderr } = await captureStdio(async () => {
+ await withHumanLogsToStderr(() => withSourcePrefix('foo', async () => { slog('y'); }));
+ });
+ expect(stdout).toBe('');
+ expect(stderr).toBe('[foo] y\n');
+ });
+});
diff --git a/test/context/resolve-ipc.test.ts b/test/context/resolve-ipc.test.ts
index bec25389ac..db88e2852f 100644
--- a/test/context/resolve-ipc.test.ts
+++ b/test/context/resolve-ipc.test.ts
@@ -2,7 +2,8 @@
* Retrieval Reflex resolve IPC round-trip tests (#1981, T3/T5).
*/
import { describe, test, expect, afterEach } from 'bun:test';
-import { mkdtempSync, rmSync, existsSync } from 'node:fs';
+import { mkdtempSync, rmSync, existsSync, symlinkSync, lstatSync } from 'node:fs';
+import net from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -50,11 +51,11 @@ describe('resolve IPC', () => {
rmSync(dir, { recursive: true, force: true });
});
- // Windows regression (community #1294-cluster follow-up). On win32,
- // net.createServer()/createConnection() silently translate a plain path
- // into \\.\pipe\<name> — no file is ever created on disk, so a client-side
- // existsSync(socketPath) pre-check is always false there even while a live
- // server is listening and a real connection would succeed. Verified
+ // Windows regression (community #1294-cluster follow-up). On win32, Bun
+ // binds a plain path as a real AF_UNIX socket whose reparse-point file
+ // Bun's existsSync() cannot see, so a client-side existsSync(socketPath)
+ // pre-check is always false there even while a live server is listening
+ // and a real connection would succeed. Verified
// manually against Bun 1.3.14 / Windows 11 (listen()+connect() round trip
// on the same plain path succeeds while existsSync() on that path stays
// false throughout) — CI here is Ubuntu-only so that positive path can't
@@ -113,18 +114,86 @@ describe('resolve IPC', () => {
const sock = resolveSocketPath(dir);
const s1 = await startResolveIpcServer(sock, async () => null);
servers.push(s1!);
- s1!.close();
+ await new Promise<void>((r) => s1!.close(() => r()));
// bind again at the same path — startResolveIpcServer must unlink the stale file
const s2 = await startResolveIpcServer(sock, async () => null);
expect(s2).not.toBeNull();
servers.push(s2!);
// win32: the rebind itself is the real assertion — s2 must be non-null,
// i.e. listen() didn't fail with an "address in use" equivalent against
- // the stale pipe. existsSync() can't observe a named pipe on Windows
- // (see the round-trip fix above), so the file-presence check is POSIX-only.
+ // the stale socket. existsSync() can't observe the AF_UNIX socket file on
+ // Windows (see the round-trip fix above), so the presence check is POSIX-only.
if (process.platform !== 'win32') {
expect(existsSync(sock)).toBe(true);
}
rmSync(dir, { recursive: true, force: true });
});
+
+ // #4896: a transient serve (claude mcp list, bootstrap smoke, a session's
+ // stdio serve) for the same brain used to unlink the LIVE provider's
+ // socket and bind over it; on exit the pathname vanished and every hook
+ // reported ipc_unavailable until the long-lived serve restarted. A live
+ // owner must make the second start defer (null) and stay reachable.
+ test('live listener at the path: a second startResolveIpcServer defers and leaves the live socket reachable', async () => {
+ const dir = tmpDir();
+ const sock = resolveSocketPath(dir);
+ const block: PointerBlock = { pointers: [], text: 'BLOCK' };
+ const s1 = await startResolveIpcServer(sock, async () => block);
+ servers.push(s1!);
+ const s2 = await startResolveIpcServer(sock, async () => null);
+ if (s2) servers.push(s2);
+ expect(s2).toBeNull();
+ if (process.platform !== 'win32') {
+ expect(existsSync(sock)).toBe(true);
+ }
+ const got = await resolveViaIpc(sock, { candidates: [{ display: 'Alice', query: 'Alice' }] });
+ expect((got as PointerBlock).text).toBe('BLOCK');
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ // wave review (#4896 follow-up): liveness is judged by the connect outcome
+ // alone. An owner that accepts but never answers (busy event loop, a
+ // one-request handler mid-await) is still the provider — the second start
+ // must defer and leave the pathname alone, never remove it and bind over it.
+ test('a listener that accepts but never answers is not displaced: second start defers, socket stays reachable', async () => {
+ const dir = tmpDir();
+ const sock = resolveSocketPath(dir);
+ const silent = net.createServer(() => { /* accept; never respond */ });
+ await new Promise<void>((r) => silent.listen(sock, r));
+ servers.push(silent);
+ const s2 = await startResolveIpcServer(sock, async () => null);
+ if (s2) servers.push(s2);
+ expect(s2).toBeNull();
+ expect(existsSync(sock)).toBe(true);
+ // Still the silent owner's socket: a fresh connect is accepted, not refused.
+ await new Promise<void>((res, rej) => {
+ const c = net.connect(sock);
+ c.once('connect', () => { c.destroy(); res(); });
+ c.once('error', rej);
+ });
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ // #4333: on win32 Bun binds a plain path as a real AF_UNIX socket, which
+ // leaves a reparse-point file that Bun's existsSync()/statSync() cannot
+ // see, yet bind() still fails EADDRINUSE against it after any unclean
+ // exit. A dangling symlink is the POSIX proxy for "entry the existence
+ // gate can't see": existsSync is false, statSync throws ENOENT, and bind()
+ // either fails EADDRINUSE (Linux) or follows the link (macOS). Cleanup
+ // must unlink without consulting the gate. (symlinkSync needs elevation
+ // on Windows, hence the skip.)
+ test.skipIf(process.platform === 'win32')(
+ 'stale entry existsSync cannot see (dangling symlink = win32 AF_UNIX proxy) is cleared before bind',
+ async () => {
+ const dir = tmpDir();
+ const sock = resolveSocketPath(dir);
+ symlinkSync(join(dir, 'gone'), sock);
+ expect(existsSync(sock)).toBe(false);
+ const s = await startResolveIpcServer(sock, async () => null);
+ expect(s).not.toBeNull();
+ servers.push(s!);
+ expect(lstatSync(sock).isSocket()).toBe(true);
+ rmSync(dir, { recursive: true, force: true });
+ },
+ );
});
diff --git a/test/contextual-reindex-lease-release.test.ts b/test/contextual-reindex-lease-release.test.ts
new file mode 100644
index 0000000000..89119001f0
--- /dev/null
+++ b/test/contextual-reindex-lease-release.test.ts
@@ -0,0 +1,84 @@
+/**
+ * #4880 — the contextual re-embed handler must release its synopsis rate
+ * lease on Postgres, where a BIGSERIAL `RETURNING id` arrives as a native
+ * BigInt (postgres.js `types: { bigint: postgres.BigInt }`). A strict
+ * `typeof lease === 'number'` guard never released it and every slot idled
+ * to its TTL. PGLite parses safe-range int8 to Number, so only a fake engine
+ * reproduces the shape.
+ */
+import { describe, expect, test } from 'bun:test';
+import { makeContextualReindexHandler } from '../src/core/minions/handlers/contextual-reindex-per-chunk.ts';
+import type { ReembedPageResult } from '../src/core/contextual-retrieval-service.ts';
+
+type Call = { sql: string; params?: unknown[] };
+const RELEASE_SQL = 'DELETE FROM subagent_rate_leases WHERE id = $1';
+
+/** Answers acquireLease's transaction the way Postgres does (bigint id). */
+function fakeEngine(calls: Call[]) {
+ const engine = {
+ async getPage() { return { source_id: 'default' }; },
+ async getConfig() { return null; },
+ async transaction<T>(fn: (tx: unknown) => Promise<T>) { return fn(engine); },
+ async executeRaw(sql: string, params?: unknown[]) {
+ calls.push({ sql, params });
+ if (sql.includes('count(*)')) return [{ count: '0' }];
+ if (sql.includes('RETURNING id')) return [{ id: 26016n }];
+ return [];
+ },
+ };
+ return engine;
+}
+
+const SUCCESS: ReembedPageResult = {
+ kind: 'success',
+ mode_applied: 'per_chunk_synopsis',
+ chunks_embedded: 1,
+ corpus_generation: 'test-generation',
+};
+
+const JOB = { id: 42, data: { page_slug: 'wiki/example' }, signal: new AbortController().signal } as never;
+
+describe('contextual_reindex_per_chunk synopsis lease release', () => {
+ test('releases the lease acquired through a Postgres-shaped RETURNING id (native BigInt)', async () => {
+ const calls: Call[] = [];
+ const handler = makeContextualReindexHandler({
+ engine: fakeEngine(calls) as never,
+ reembedPage: async (args) => {
+ const lease = await args.acquireSynopsisLease!();
+ await args.releaseSynopsisLease!(lease);
+ return SUCCESS;
+ },
+ });
+ await handler(JOB);
+ expect(calls.filter(c => c.sql === RELEASE_SQL)).toEqual([{ sql: RELEASE_SQL, params: [26016] }]);
+ });
+
+ test('release is not gated on typeof number (the acquire seam owns the coercion)', async () => {
+ const calls: Call[] = [];
+ const handler = makeContextualReindexHandler({
+ engine: fakeEngine(calls) as never,
+ reembedPage: async (args) => {
+ await args.releaseSynopsisLease!(26016n);
+ return SUCCESS;
+ },
+ });
+ await handler(JOB);
+ const releases = calls.filter(c => c.sql === RELEASE_SQL);
+ expect(releases.length).toBe(1);
+ expect(Number(releases[0]!.params![0])).toBe(26016);
+ });
+
+ test('a null lease (never acquired) issues no DELETE (#4880 regression: release is skipped, not misfired)', async () => {
+ const calls: Call[] = [];
+ const handler = makeContextualReindexHandler({
+ engine: fakeEngine(calls) as never,
+ reembedPage: async (args) => {
+ await args.releaseSynopsisLease!(null as never);
+ await args.releaseSynopsisLease!(undefined as never);
+ return SUCCESS;
+ },
+ });
+ await handler(JOB);
+ expect(calls.filter(c => c.sql === RELEASE_SQL)).toEqual([]);
+ });
+});
diff --git a/test/core/budget/budget-tracker.test.ts b/test/core/budget/budget-tracker.test.ts
index 50e47b6994..636efef39a 100644
--- a/test/core/budget/budget-tracker.test.ts
+++ b/test/core/budget/budget-tracker.test.ts
@@ -25,6 +25,7 @@ import {
BudgetTracker,
BudgetExhausted,
extractUsageFromError,
+ isModelPriceable,
_resetBudgetTrackerWarningsForTest,
} from '../../../src/core/budget/budget-tracker.ts';
@@ -229,6 +230,56 @@ describe('BudgetTracker.reserve', () => {
expect(audit.filter((e) => e.event === 'reserve_unpriced').length).toBe(2);
});
+ test('claude-cli:<alias> chat model under a cap prices at the canonical model rate (no no_pricing throw)', () => {
+ // `gbrain enrich --thin` with chat_model = claude-cli:haiku TX2 hard-failed
+ // at reserve() with reason no_pricing at EVERY --max-usd tried: the
+ // gateway reserves with the pre-alias-resolution model string, and
+ // `haiku` is a recipe alias, not a pricing key. lookupPricing resolves
+ // recipe aliases, so the alias prices exactly like the dated id it maps
+ // to — at reserve(), record() and isModelPriceable() alike.
+ expect(isModelPriceable('claude-cli:haiku', 'chat')).toBe(true);
+ const t = new BudgetTracker({ maxCostUsd: 5.0, label: 'test', auditPath });
+ expect(() =>
+ t.reserve({
+ modelId: 'claude-cli:haiku',
+ estimatedInputTokens: 1_000_000,
+ maxOutputTokens: 0,
+ kind: 'chat',
+ }),
+ ).not.toThrow();
+ t.reserve({
+ modelId: 'claude-cli:claude-haiku-4-5-20251001',
+ estimatedInputTokens: 1_000_000,
+ maxOutputTokens: 0,
+ kind: 'chat',
+ });
+ const audit = readAudit();
+ expect(audit.map((e) => e.event)).toEqual(['reserve', 'reserve']);
+ // $1.00/1M input tokens (ANTHROPIC_PRICING['claude-haiku-4-5-20251001']);
+ // the alias and the dated id project the same cost.
+ expect(audit[0].projected_cost_usd).toBeCloseTo(1.0, 6);
+ expect(audit[1].projected_cost_usd).toBe(audit[0].projected_cost_usd);
+ });
+
+ test('claude-cli:<dated-id> resolves Anthropic pricing via the model tail (parity guard for the alias path)', () => {
+ // The DATED id tail ("claude-haiku-4-5-20251001") is itself a bare
+ // ANTHROPIC_PRICING key, so the modelTail fallback prices this call at
+ // the nominal Anthropic per-token rate. The alias path above must land
+ // on exactly this.
+ const t = new BudgetTracker({ maxCostUsd: 5.0, label: 'test', auditPath });
+ expect(() =>
+ t.reserve({
+ modelId: 'claude-cli:claude-haiku-4-5-20251001',
+ estimatedInputTokens: 1_000_000,
+ maxOutputTokens: 0,
+ kind: 'chat',
+ }),
+ ).not.toThrow();
+ const audit = readAudit();
+ expect(audit[0].event).toBe('reserve');
+ expect(audit[0].projected_cost_usd).toBeCloseTo(1.0, 6);
+ });
+
test('v0.40.6.1: rerank kind for llama-server-reranker prices at $0 (no TX2 throw under --max-cost)', () => {
// The FREE_LOCAL_RERANK_PROVIDERS contract — local inference costs
// electricity, not API tokens. Pre-v0.40.6.1 setting --max-cost while
diff --git a/test/core/retry.test.ts b/test/core/retry.test.ts
index dfa789fb23..80e2e3245e 100644
--- a/test/core/retry.test.ts
+++ b/test/core/retry.test.ts
@@ -349,6 +349,8 @@ describe('BATCH_AUDIT_SITES typed enum + isBatchAuditSite guard (D10c codex)', (
'extract.stale',
// #3961: atom-provenance edges banked after the completion-receipt flip.
'cycle.extract_atoms.provenance',
+ // #4589: concept<->member-atom provenance edges banked after each concept write.
+ 'cycle.synthesize_concepts.provenance',
'mcp.put_page.autolink',
'sync.import_file',
'reindex.markdown', 'reindex.multimodal',
diff --git a/test/cycle-dream-output-root.test.ts b/test/cycle-dream-output-root.test.ts
index 1272a46bf9..99c276dbcb 100644
--- a/test/cycle-dream-output-root.test.ts
+++ b/test/cycle-dream-output-root.test.ts
@@ -317,6 +317,24 @@ describe('#4216: buildSynthesisPrompt manifest + allow-list blocks', () => {
expect(prompt).toContain('Use the search tool to find existing pages first.');
});
+ test('oneshot prompt removes tool-use and final-prose instructions; agentic keeps them', () => {
+ const manifest = '\nLINK CANDIDATES\n- [[people/alice-example]] — Alice Example is a founder.';
+ const oneshot = buildSynthesisPrompt(
+ transcript, 'chunk', 0, 1, '', 'wiki', '', manifest,
+ ['wiki/personal/reflections/*'], undefined, undefined, 'oneshot',
+ );
+ const agentic = buildSynthesisPrompt(
+ transcript, 'chunk', 0, 1, '', 'wiki', '', manifest,
+ ['wiki/personal/reflections/*'], undefined, undefined, 'agentic',
+ );
+
+ expect(oneshot).not.toContain('search tool');
+ expect(oneshot).not.toContain('put_page schema');
+ expect(oneshot).not.toContain('final message');
+ expect(agentic).toContain('use the search tool, if available');
+ expect(agentic).toContain('final message');
+ });
+
test('ALLOWED WRITE PATHS block renders from prefixes (OV-7: oneshot never sees a tool schema)', () => {
const prompt = buildSynthesisPrompt(
transcript, 'chunk', 0, 1, '', 'wiki', '', '',
diff --git a/test/cycle-lint-durability.test.ts b/test/cycle-lint-durability.test.ts
new file mode 100644
index 0000000000..834d7086e2
--- /dev/null
+++ b/test/cycle-lint-durability.test.ts
@@ -0,0 +1,89 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execFileSync } from 'child_process';
+import { runPhaseLint } from '../src/core/cycle.ts';
+import { runLintCore } from '../src/commands/lint.ts';
+
+const roots: string[] = [];
+
+afterEach(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+/**
+ * A committed git repo carrying the gbrain durability post-commit hook and
+ * one page whose only lint issue is fixable (ingested_at without created).
+ */
+function hardenedRepoWithNote(opts: { hook?: boolean } = {}): { root: string; page: string } {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-cycle-lint-durability-'));
+ roots.push(root);
+ const page = join(root, 'note.md');
+ writeFileSync(
+ page,
+ `---\ntype: note\ntitle: Durable\nstatus: active\ningested_at: '2026-08-30T12:00:00Z'\n---\n\nBody.\n`,
+ );
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ execFileSync('git', ['config', 'user.name', 'Test'], { cwd: root });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: root });
+ execFileSync('git', ['add', '--', 'note.md'], { cwd: root });
+ execFileSync('git', ['commit', '-qm', 'initial'], { cwd: root });
+ if (opts.hook === false) return { root, page };
+
+ const hook = join(root, '.git', 'hooks', 'post-commit');
+ mkdirSync(join(root, '.git', 'hooks'), { recursive: true });
+ writeFileSync(
+ hook,
+ '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\nexit 0\n',
+ );
+ chmodSync(hook, 0o755);
+ return { root, page };
+}
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
+}
+
+describe('cycle lint durability', () => {
+ test('a hardened corpus commits exactly the page lint fixed', async () => {
+ const { root } = hardenedRepoWithNote();
+
+ const result = await runPhaseLint(root, false, null);
+
+ expect(result.status).toBe('ok');
+ expect(result.details?.fixed).toBe(1);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(git(root, 'log', '-1', '--format=%s')).toBe('gbrain: write-through note');
+ });
+
+ test('a single-file target (gbrain lint --fix page.md) probes the page\'s directory for the hook', async () => {
+ const { root, page } = hardenedRepoWithNote();
+
+ const result = await runLintCore({ target: page, fix: true });
+
+ expect(result.total_fixed).toBe(1);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(git(root, 'log', '-1', '--format=%s')).toBe('gbrain: write-through note');
+ });
+
+ test('a plain git repo without the durability hook repairs but does NOT commit (#4815 regression)', async () => {
+ const { root } = hardenedRepoWithNote({ hook: false });
+
+ const result = await runPhaseLint(root, false, null);
+
+ expect(result.details?.fixed).toBe(1);
+ expect(git(root, 'status', '--porcelain')).toBe('M note.md'); // trimmed ' M note.md' — repair on disk, uncommitted
+ expect(git(root, 'log', '-1', '--format=%s')).toBe('initial');
+ });
+
+ test('dry-run repairs nothing and commits nothing', async () => {
+ const { root } = hardenedRepoWithNote();
+
+ const result = await runPhaseLint(root, true, null);
+
+ expect(result.details?.fixed).toBe(1);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(git(root, 'log', '-1', '--format=%s')).toBe('initial');
+ });
+});
diff --git a/test/cycle-stale-drain.test.ts b/test/cycle-stale-drain.test.ts
index f2396f71ee..46119d3d5c 100644
--- a/test/cycle-stale-drain.test.ts
+++ b/test/cycle-stale-drain.test.ts
@@ -13,14 +13,15 @@
* GBRAIN_HOME is isolated per test because the PGLite cycle path takes a
* file lock at ~/.gbrain/cycle.lock (see cycle-extract-source.test.ts).
*/
-import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, rmSync } from 'fs';
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
import { runCycle } from '../src/core/cycle.ts';
+import { extractStaleFromDB, runExtractCore } from '../src/commands/extract.ts';
let engine: PGLiteEngine;
let brainDir: string;
@@ -64,6 +65,117 @@ afterEach(() => {
});
describe('cycle extract phase stale drain (#4062)', () => {
+ test('extraction totals count scanned pages rather than links', async () => {
+ writeFileSync(join(brainDir, 'quiet.md'), '# Quiet page\nNo outgoing links.\n');
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ const report = await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ expect(report.phases[0]?.details?.linksCreated).toBe(0);
+ expect(report.phases[0]?.details?.pages_processed).toBe(1);
+ expect(report.phases[0]?.details?.stale_pages_drained).toBe(2);
+ expect(report.totals.pages_extracted).toBe(3);
+ });
+ });
+
+ test('working and no-op drains leave stdout available for the cycle JSON report', async () => {
+ writeFileSync(join(brainDir, 'quiet.md'), '# Quiet page\nNo outgoing links.\n');
+ // A checkout page whose [[link]] resolves to another checkout page (both
+ // present in the DB under the same source) so the fs-walk link-extraction
+ // branch actually runs — and writes an edge — under the stdout spy.
+ writeFileSync(join(brainDir, 'linker.md'), '# Linker\nSee [[quiet]].\n');
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('quiet', 'wiki', 'concept', 'Quiet page', 'No outgoing links.', ''),
+ ('linker', 'wiki', 'concept', 'Linker', 'See [[quiet]].', '')`,
+ );
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ try {
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ const first = await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ const second = await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ expect(first.phases[0]?.details?.pages_processed).toBe(2);
+ expect(first.phases[0]?.details?.linksCreated).toBe(1);
+ expect(first.phases[0]?.details?.stale_pages_drained).toBe(2);
+ expect(second.phases[0]?.details?.stale_pages_drained).toBe(0);
+ });
+ expect(log).not.toHaveBeenCalled();
+ expect(stdout).not.toHaveBeenCalled();
+ const links = await engine.getLinks('linker', { sourceId: 'wiki' });
+ expect(links.some(l => l.to_slug === 'quiet')).toBe(true);
+ } finally {
+ log.mockRestore();
+ stdout.mockRestore();
+ }
+ });
+ for (const dryRun of [false, true]) {
+ for (const jsonMode of [false, true]) {
+ test(`quiet stale helper suppresses output (dryRun=${dryRun}, jsonMode=${jsonMode})`, async () => {
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ try {
+ const result = await extractStaleFromDB(engine, {
+ dryRun, jsonMode, quiet: true, includeFrontmatter: false,
+ sourceIdFilter: 'wiki', catchUp: false,
+ });
+ expect(result.pagesProcessed).toBe(dryRun ? 0 : 2);
+ expect(log).not.toHaveBeenCalled();
+ expect(stdout).not.toHaveBeenCalled();
+ } finally {
+ log.mockRestore();
+ stdout.mockRestore();
+ }
+ });
+ }
+ }
+
+ test('standalone stale helper still emits its JSON result', async () => {
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ try {
+ await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false,
+ sourceIdFilter: 'wiki', catchUp: false,
+ });
+ expect(stdout).toHaveBeenCalledTimes(1);
+ const result = JSON.parse(String(stdout.mock.calls[0]?.[0]));
+ expect(result.action).toBe('extract_stale_done');
+ expect(result.pages_processed).toBe(2);
+ } finally {
+ stdout.mockRestore();
+ }
+ });
+
+ test('standalone stale helper prints its human summary when neither quiet nor JSON', async () => {
+ // The quiet/JSON variants above pin silence; this pins that the default
+ // CLI path (`gbrain extract --stale`) still tells the operator what ran.
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ try {
+ const result = await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: false, includeFrontmatter: false,
+ sourceIdFilter: 'wiki', catchUp: false,
+ });
+ expect(result.pagesProcessed).toBe(2);
+ const summary = log.mock.calls.map(c => String(c[0])).find(l => l.startsWith('Extract --stale:'));
+ expect(summary).toBeDefined();
+ expect(summary).toContain('from 2 page(s)');
+ // Human output goes through console.log; nothing is written raw to stdout.
+ expect(stdout).not.toHaveBeenCalled();
+ } finally {
+ log.mockRestore();
+ stdout.mockRestore();
+ }
+ });
+
+ test('DB-only extraction contributes to totals and a working status', async () => {
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ const report = await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ expect(report.phases[0]?.details?.pages_processed).toBe(0);
+ expect(report.phases[0]?.details?.stale_pages_drained).toBe(2);
+ expect(report.totals.pages_extracted).toBe(2);
+ expect(report.status).toBe('ok');
+ });
+ });
+
test('drains stale DB-only pages after the targeted pass and reports staleRemaining', async () => {
await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
const report = await runCycle(engine, {
@@ -105,4 +217,56 @@ describe('cycle extract phase stale drain (#4062)', () => {
expect(Number(extractPhase?.details?.staleRemaining ?? -1)).toBe(0);
});
});
+
+ test('the cycle-shaped slug-scoped extract keeps batch-loss diagnostics on stderr', async () => {
+ // The cycle calls runExtractCore with jsonMode: true so the helper's human
+ // summary never lands ahead of the dream --json report. Quiet must not mean
+ // silent: a flush that drops rows still has to surface on stderr.
+ writeFileSync(join(brainDir, 'alice.md'), '# Alice\nMet [[bob]] today.\n');
+ writeFileSync(join(brainDir, 'bob.md'), '# Bob\nQuiet page.\n');
+ const addLinks = spyOn(engine, 'addLinksBatch').mockRejectedValueOnce(new Error('pool exhausted'));
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ const err = spyOn(console, 'error').mockImplementation(() => {});
+ const stderr = spyOn(process.stderr, 'write').mockReturnValue(true);
+ try {
+ await runExtractCore(engine, { mode: 'all', dir: brainDir, slugs: ['alice'], jsonMode: true, sourceId: 'wiki' });
+ expect(addLinks).toHaveBeenCalledTimes(1);
+ expect(log).not.toHaveBeenCalled();
+ expect(stdout).not.toHaveBeenCalled();
+ const diagnostics = [...err.mock.calls, ...stderr.mock.calls].map(c => String(c[0]));
+ expect(diagnostics.some(d => d.includes('batch_error') && d.includes('pool exhausted'))).toBe(true);
+ } finally {
+ addLinks.mockRestore();
+ log.mockRestore();
+ stdout.mockRestore();
+ err.mockRestore();
+ stderr.mockRestore();
+ }
+ });
+
+ test('the cycle-shaped extract keeps TIMELINE batch-loss diagnostics on stderr too (#4890 sibling branch)', async () => {
+ // Same two-channel contract as the links flush: under jsonMode a dropped
+ // timeline batch must land on stderr as a batch_error event, never on stdout.
+ writeFileSync(join(brainDir, 'carol.md'), '# Carol\n\n## Timeline\n- **2026-01-02** | Signed the term sheet\n');
+ const addTimeline = spyOn(engine, 'addTimelineEntriesBatch').mockRejectedValueOnce(new Error('pool exhausted'));
+ const log = spyOn(console, 'log').mockImplementation(() => {});
+ const stdout = spyOn(process.stdout, 'write').mockReturnValue(true);
+ const err = spyOn(console, 'error').mockImplementation(() => {});
+ const stderr = spyOn(process.stderr, 'write').mockReturnValue(true);
+ try {
+ await runExtractCore(engine, { mode: 'all', dir: brainDir, slugs: ['carol'], jsonMode: true, sourceId: 'wiki' });
+ expect(addTimeline).toHaveBeenCalledTimes(1);
+ expect(log).not.toHaveBeenCalled();
+ expect(stdout).not.toHaveBeenCalled();
+ const diagnostics = [...err.mock.calls, ...stderr.mock.calls].map(c => String(c[0]));
+ expect(diagnostics.some(d => d.includes('"event":"batch_error"') && d.includes('pool exhausted'))).toBe(true);
+ } finally {
+ addTimeline.mockRestore();
+ log.mockRestore();
+ stdout.mockRestore();
+ err.mockRestore();
+ stderr.mockRestore();
+ }
+ });
});
diff --git a/test/cycle-synthesize-daily-cap.test.ts b/test/cycle-synthesize-daily-cap.test.ts
index 287c953d7f..46c50608da 100644
--- a/test/cycle-synthesize-daily-cap.test.ts
+++ b/test/cycle-synthesize-daily-cap.test.ts
@@ -214,6 +214,65 @@ describe('daily cap — engaged', () => {
}
}, 60_000);
+ test('a transcript whose synth-v2 child already completed is skipped before any work; a cancelled row does not count', async () => {
+ const rig = await setupRig();
+ try {
+ const done = await seedPassingFile(rig, '2026-08-05-done.txt');
+ const redo = await seedPassingFile(rig, '2026-08-06-redo.txt');
+ const key = (name: string) => {
+ const content = `conversation in ${name}\n`.repeat(200);
+ const hash16 = createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);
+ return `dream:synth-v2:default:filename:${name}:${hash16}`;
+ };
+ await rig.engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, created_at, finished_at)
+ VALUES ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),
+ ('subagent', 'dream-inline-old-run', 'cancelled', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days')`,
+ [key('2026-08-05-done.txt'), key('2026-08-06-redo.txt')],
+ );
+ const details = await runPhase(rig);
+ const doneSkip = details.skips.find(s => s.filePath === done);
+ expect(doneSkip?.reason).toBe('already_synthesized_v2_single_chunk');
+ expect(details.skips.find(s => s.filePath === redo)).toBeUndefined();
+ expect(details.children_submitted).toBe(1);
+ } finally {
+ await rig.cleanup();
+ }
+ }, 60_000);
+
+ test('a transcript whose synth-v2 CHUNKED set fully completed is skipped; a partial chunk set is resubmitted', async () => {
+ const rig = await setupRig();
+ try {
+ const full = await seedPassingFile(rig, '2026-08-07-chunked-full.txt');
+ const partial = await seedPassingFile(rig, '2026-08-08-chunked-partial.txt');
+ const chunkKey = (name: string, i: number, n: number) => {
+ const content = `conversation in ${name}\n`.repeat(200);
+ const hash16 = createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);
+ return `dream:synth-v2:default:filename:${name}:${hash16}:c${i}of${n}`;
+ };
+ // full: c0of2 + c1of2 completed (a whole set). partial: only c0of3 —
+ // the transcript would ship with holes, so it must be re-synthesized.
+ await rig.engine.executeRaw(
+ `INSERT INTO minion_jobs (name, queue, status, data, idempotency_key, created_at, finished_at)
+ VALUES ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $1, now() - interval '2 days', now() - interval '2 days'),
+ ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $2, now() - interval '2 days', now() - interval '2 days'),
+ ('subagent', 'dream-inline-old-run', 'completed', '{"source_id":"default"}'::jsonb, $3, now() - interval '2 days', now() - interval '2 days')`,
+ [
+ chunkKey('2026-08-07-chunked-full.txt', 0, 2),
+ chunkKey('2026-08-07-chunked-full.txt', 1, 2),
+ chunkKey('2026-08-08-chunked-partial.txt', 0, 3),
+ ],
+ );
+ const details = await runPhase(rig);
+ expect(details.skips.find(s => s.filePath === full)?.reason).toBe('already_synthesized_v2_chunked');
+ expect(details.skips.find(s => s.filePath === partial)).toBeUndefined();
+ // Only the partial transcript submits (small fixture → one chunk).
+ expect(details.children_submitted).toBe(1);
+ } finally {
+ await rig.cleanup();
+ }
+ }, 60_000);
+
test('24h window: a >24h-old submission row does not eat the budget', async () => {
const rig = await setupRig();
try {
diff --git a/test/cycle-synthesize.test.ts b/test/cycle-synthesize.test.ts
index 8cd5092267..8219c87196 100644
--- a/test/cycle-synthesize.test.ts
+++ b/test/cycle-synthesize.test.ts
@@ -7,7 +7,7 @@
* cycle E2E lives in test/e2e/.
*/
-import { describe, test, expect, beforeEach } from 'bun:test';
+import { describe, test, expect, beforeEach, spyOn } from 'bun:test';
import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -32,6 +32,20 @@ beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'gbrain-synth-test-'));
});
+/** Run `fn` with process.stderr.write captured; returns every chunk written. */
+function captureStderr<T>(fn: () => T): { value: T; writes: string[] } {
+ const writes: string[] = [];
+ const spy = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
+ writes.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write);
+ try {
+ return { value: fn(), writes };
+ } finally {
+ spy.mockRestore();
+ }
+}
+
describe('compileExcludePatterns', () => {
test('auto-wraps bare words in word-boundary regex (Q-3)', () => {
const res = compileExcludePatterns(['medical']);
@@ -113,6 +127,70 @@ describe('discoverTranscripts', () => {
expect(out[0].basename).toBe('2026-04-25-comedy');
});
+ test('exclusions are reported ONCE on stderr with the count and the patterns that fired, never the files', () => {
+ makeTranscript('2026-04-25-alpha.txt', 'discussing medical advice ' + 'x'.repeat(3000));
+ makeTranscript('2026-04-25-beta.txt', 'medical notes and a therapy referral ' + 'x'.repeat(3000));
+ makeTranscript('2026-04-25-gamma.txt', 'therapy session ' + 'x'.repeat(3000));
+ makeTranscript('2026-04-25-clean.txt', 'nothing sensitive here ' + 'x'.repeat(3000));
+ const { value: out, writes } = captureStderr(() => discoverTranscripts({
+ corpusDir: tmpDir,
+ minChars: 1000,
+ excludePatterns: ['medical', 'therapy'],
+ }));
+ expect(out.map(t => t.basename)).toEqual(['2026-04-25-clean']);
+
+ const lines = writes.filter(w => w.includes('exclude_patterns'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatch(/^\[dream\] excluded 3 transcript\(s\) matching exclude_patterns \(/);
+ expect(lines[0]).toContain('medical: 2');
+ expect(lines[0]).toContain('therapy: 2'); // beta matches both patterns
+ expect(lines[0]).toContain('dream.synthesize.exclude_patterns');
+ // Never the files: no basename, no path, no transcript content.
+ for (const w of writes) {
+ expect(w).not.toContain('alpha');
+ expect(w).not.toContain('beta');
+ expect(w).not.toContain('gamma');
+ expect(w).not.toContain(tmpDir);
+ expect(w).not.toContain('xxxx');
+ }
+ });
+
+ test('exclusions across BOTH the corpus and meeting-transcript dirs roll up into ONE stderr line', () => {
+ // The tally is per RUN, not per directory: one line, one total, one
+ // pattern count — an operator reading the log must not have to add up
+ // a line per source dir.
+ makeTranscript('2026-04-25-alpha.txt', 'discussing medical advice ' + 'x'.repeat(3000));
+ const meetDir = mkdtempSync(join(tmpdir(), 'gbrain-meet-'));
+ try {
+ writeFileSync(join(meetDir, '2026-04-25-beta.txt'), 'medical notes from the call ' + 'x'.repeat(3000));
+ writeFileSync(join(meetDir, '2026-04-25-clean.txt'), 'nothing sensitive here ' + 'x'.repeat(3000));
+ const { value: out, writes } = captureStderr(() => discoverTranscripts({
+ corpusDir: tmpDir,
+ meetingTranscriptsDir: meetDir,
+ minChars: 1000,
+ excludePatterns: ['medical'],
+ }));
+ expect(out.map(t => t.basename)).toEqual(['2026-04-25-clean']);
+ const lines = writes.filter(w => w.includes('exclude_patterns'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('excluded 2 transcript(s)');
+ expect(lines[0]).toContain('medical: 2');
+ } finally {
+ rmSync(meetDir, { recursive: true, force: true });
+ }
+ });
+
+ test('no exclusion, no exclude_patterns line on stderr', () => {
+ makeTranscript('2026-04-25-clean.txt', 'nothing sensitive here ' + 'x'.repeat(3000));
+ const { value: out, writes } = captureStderr(() => discoverTranscripts({
+ corpusDir: tmpDir,
+ minChars: 1000,
+ excludePatterns: ['medical', 'therapy'],
+ }));
+ expect(out).toHaveLength(1);
+ expect(writes.filter(w => w.includes('exclude_patterns'))).toHaveLength(0);
+ });
+
test('--date filter restricts to one specific YYYY-MM-DD basename', () => {
makeTranscript('2026-04-25-foo.txt', 'a'.repeat(3000));
makeTranscript('2026-04-26-bar.txt', 'b'.repeat(3000));
@@ -185,6 +263,20 @@ describe('readSingleTranscript', () => {
expect(t).toBeNull();
});
+ test('an exclude_patterns hit is reported on stderr without naming the file', () => {
+ const path = makeTranscript('secret-visit.txt', 'medical history ' + 'x'.repeat(3000));
+ const { value: t, writes } = captureStderr(() =>
+ readSingleTranscript(path, { minChars: 1000, excludePatterns: ['medical'] }),
+ );
+ expect(t).toBeNull();
+ const lines = writes.filter(w => w.includes('exclude_patterns'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('excluded 1 transcript(s)');
+ expect(lines[0]).toContain('medical: 1');
+ expect(lines[0]).not.toContain('secret');
+ expect(lines[0]).not.toContain(path);
+ });
+
test('throws on missing file', () => {
expect(() => readSingleTranscript('/nonexistent/foo.txt')).toThrow();
});
diff --git a/test/cycle/extract-atoms-synthesize-concepts.test.ts b/test/cycle/extract-atoms-synthesize-concepts.test.ts
index 107408774e..b862a8af39 100644
--- a/test/cycle/extract-atoms-synthesize-concepts.test.ts
+++ b/test/cycle/extract-atoms-synthesize-concepts.test.ts
@@ -234,6 +234,14 @@ describe('v0.41 T5: runPhaseExtractAtoms via stubbed chat', () => {
});
describe('v0.41 T6: runPhaseSynthesizeConcepts via stubbed chat', () => {
+ /** Persist injected atoms as pages: provenance edges need both endpoints
+ * (the batch JOIN drops absent slugs, and an all-dropped batch is a warn). */
+ async function persistAtoms(atoms: Array<{ slug: string; title: string; body: string }>): Promise<void> {
+ for (const a of atoms) {
+ await engine.putPage(a.slug, { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' });
+ }
+ }
+
test('no-op when no atoms have concept refs', async () => {
const result = await runPhaseSynthesizeConcepts(engine, { _atoms: [] });
expect(result.status).toBe('skipped');
@@ -267,6 +275,7 @@ describe('v0.41 T6: runPhaseSynthesizeConcepts via stubbed chat', () => {
});
}
+ await persistAtoms(atoms);
const chat = stubChat('AI agents are software factories.');
const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, _chat: chat });
expect(result.status).toBe('ok');
@@ -411,6 +420,7 @@ describe('v0.41 T6: runPhaseSynthesizeConcepts via stubbed chat', () => {
body: `Empty body ${i}`,
concept_refs: ['empty-theme'],
}));
+ await persistAtoms(atoms);
const result = await runPhaseSynthesizeConcepts(engine, {
_atoms: atoms,
_chat: stubChat(''),
@@ -683,8 +693,8 @@ describe('#2123: extractor stamps concepts → synthesize_concepts consumes via
expect(extract.details?.atoms_extracted).toBe(2);
// Frontmatter really carries the label (a jsonb array, not a string).
- const stamped = await engine.executeRaw<{ concepts: unknown }>(
- `SELECT frontmatter->'concepts' AS concepts FROM pages WHERE type = 'atom'`,
+ const stamped = await engine.executeRaw<{ slug: string; concepts: unknown }>(
+ `SELECT slug, frontmatter->'concepts' AS concepts FROM pages WHERE type = 'atom'`,
);
expect(stamped.length).toBe(2);
for (const row of stamped) {
@@ -701,5 +711,185 @@ describe('#2123: extractor stamps concepts → synthesize_concepts consumes via
`SELECT slug FROM pages WHERE slug = 'concepts/captive-portal' AND type = 'concept'`,
);
expect(concept.length).toBe(1);
+
+ // #4589 on the REAL path: the provenance edges are keyed on the atom slugs
+ // the DB query returned (not `_atoms` seam input), so each extracted atom
+ // must point back at the concept — 2 atoms, 2 'synthesizes' backlinks.
+ const back = (await engine.getBacklinks('concepts/captive-portal', { sourceId: 'default' }))
+ .filter((l) => l.link_source === 'concept-provenance');
+ expect(back.length).toBe(2);
+ expect(back.every((l) => l.link_type === 'synthesizes')).toBe(true);
+ expect(back.map((l) => l.from_slug).sort()).toEqual(stamped.map((r) => r.slug).sort());
+ });
+});
+
+// #4589 — synthesize_concepts held every member atom's slug in memory at write
+// time and dropped it: the concept page was written through importFromContent
+// (which links code refs only), the prompt forbids enumerating atoms in the
+// body, and no frontmatter field maps to a link verb — so every concept page
+// landed with 0 inbound + 0 outbound edges and dragged doctor's
+// graph_signals_coverage / orphans down. The phase now banks
+// concept -> atom ('synthesized_from') and atom -> concept ('synthesizes')
+// edges under a dedicated link_source ('concept-provenance', so reconcile
+// passes never prune them), scoped to the cycle's source. Mirrors #3961.
+describe('#4589: synthesize_concepts persists concept<->atom provenance edges', () => {
+ const CONCEPT = 'dive-entry-mechanics';
+ const CONCEPT_SLUG = `concepts/${CONCEPT}`;
+ const memberSlugs = [0, 1, 2].map((i) => `atoms/2026-01-01/member-${i}`);
+ const memberAtoms = memberSlugs.map((slug, i) => ({
+ slug,
+ title: `Member ${i}`,
+ body: `Body of member ${i}.`,
+ concept_refs: [CONCEPT],
+ }));
+
+ async function seedMembers(sourceId?: string): Promise<void> {
+ for (const a of memberAtoms) {
+ await engine.putPage(
+ a.slug,
+ { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' },
+ sourceId ? { sourceId } : undefined,
+ );
+ }
+ }
+
+ async function provenanceCount(): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM links WHERE link_source = 'concept-provenance'`,
+ );
+ return rows[0].n;
+ }
+
+ test('writes synthesized_from (concept->atom) and synthesizes (atom->concept) edges', async () => {
+ await seedMembers();
+ // 3 atoms = T3 → deterministic path, no LLM call.
+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
+ expect(result.status).toBe('ok');
+
+ const out = (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'default' }))
+ .filter((l) => l.link_source === 'concept-provenance');
+ expect(out.map((l) => l.to_slug).sort()).toEqual([...memberSlugs].sort());
+ expect(out.every((l) => l.link_type === 'synthesized_from')).toBe(true);
+
+ const back = (await engine.getBacklinks(CONCEPT_SLUG, { sourceId: 'default' }))
+ .filter((l) => l.link_source === 'concept-provenance');
+ expect(back.map((l) => l.from_slug).sort()).toEqual([...memberSlugs].sort());
+ expect(back.every((l) => l.link_type === 'synthesizes')).toBe(true);
+ });
+
+ test('re-running the phase is idempotent (ON CONFLICT DO NOTHING keeps 3+3 rows)', async () => {
+ await seedMembers();
+ await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
+ expect(await provenanceCount()).toBe(6);
+ const second = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
+ expect(second.status).toBe('ok');
+ expect(await provenanceCount()).toBe(6);
+ });
+
+ test('dry-run writes zero provenance edges', async () => {
+ await seedMembers();
+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms, dryRun: true });
+ expect(result.details?.concepts_written).toBe(1);
+ expect(await provenanceCount()).toBe(0);
+ });
+
+ test('edges land in the cycle source only; an atom in another source drops out (no cross-source edge)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('repo-a', 'Repo A') ON CONFLICT (id) DO NOTHING`,
+ );
+ await seedMembers('repo-a');
+ // A same-concept atom that lives in 'default' — the INNER JOIN on
+ // (slug, source_id) must silently drop it rather than link across sources.
+ const stray = { slug: 'atoms/2026-01-01/stray', title: 'Stray', body: 'b', concept_refs: [CONCEPT] };
+ await engine.putPage(stray.slug, { type: 'atom', title: stray.title, compiled_truth: stray.body, timeline: '' });
+
+ const result = await runPhaseSynthesizeConcepts(engine, {
+ _atoms: [...memberAtoms, stray],
+ sourceId: 'repo-a',
+ });
+ expect(result.status).toBe('ok');
+
+ const inRepo = (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'repo-a' }))
+ .filter((l) => l.link_source === 'concept-provenance');
+ expect(inRepo.map((l) => l.to_slug).sort()).toEqual([...memberSlugs].sort());
+ expect(inRepo.every((l) => l.to_source_id === 'repo-a' && l.from_source_id === 'repo-a')).toBe(true);
+ expect(
+ (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'default' }))
+ .filter((l) => l.link_source === 'concept-provenance'),
+ ).toHaveLength(0);
+ expect((await engine.getLinks(stray.slug, { sourceId: 'default' })).length).toBe(0);
+ expect(await provenanceCount()).toBe(6);
+ });
+
+ test('every member atom outside the cycle source → zero edges is warn, not a silent ok (wave review)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('repo-a', 'Repo A') ON CONFLICT (id) DO NOTHING`,
+ );
+ await seedMembers(); // atoms live in 'default' …
+ const result = await runPhaseSynthesizeConcepts(engine, {
+ _atoms: memberAtoms,
+ sourceId: 'repo-a', // … but the phase writes to repo-a, so the batch JOIN drops every edge.
+ });
+ expect(await provenanceCount()).toBe(0);
+ expect(result.status).toBe('warn');
+ // Provenance problems ride `link_warnings`, not `failures` (which means
+ // "LLM-failed → template fallback" downstream and would count a halt).
+ expect(result.details?.failures).toEqual([]);
+ const warnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
+ expect(warnings.some((w) => w.concept === CONCEPT && /0 of 6/.test(w.warning))).toBe(true);
+ // The page write stands (best-effort edges, mirrors the thrown case below).
+ expect(await engine.getPage(CONCEPT_SLUG, { sourceId: 'repo-a' })).not.toBeNull();
+ });
+
+ test('a failed edge write is reported as warn, not swallowed; the concept page still lands', async () => {
+ await seedMembers();
+ const orig = engine.addLinksBatch.bind(engine);
+ engine.addLinksBatch = async () => { throw new Error('links table unavailable'); };
+ try {
+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
+ expect(result.status).toBe('warn');
+ expect(result.details?.failures).toEqual([]);
+ const warnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
+ expect(warnings.some((w) => w.concept === CONCEPT && /links table unavailable/.test(w.warning))).toBe(true);
+ expect(await engine.getPage(CONCEPT_SLUG, { sourceId: 'default' })).not.toBeNull();
+ } finally {
+ engine.addLinksBatch = orig;
+ }
+ });
+});
+
+// ─── wave review: provenance-link problems are warnings, not LLM failures ──
+describe('synthesize_concepts — provenance-link warnings stay out of `failures`', () => {
+ test('zero provenance edges landed → status warn, link_warnings recorded, narrative kept, no halt', async () => {
+ // Atoms are NOT persisted, so the provenance batch JOIN drops every edge.
+ // Pre-fix that was pushed into `failures`, which downstream reads as
+ // "LLM-failed → template fallback": the summary lied about the narrative
+ // (the LLM call succeeded and was persisted as-is), the rollup counted a
+ // halt, and round_completed_delta flipped to 0.
+ const atoms = Array.from({ length: 5 }, (_, i) => ({
+ slug: `orphan-${i}`,
+ title: `Orphan ${i}`,
+ body: `Orphan body ${i}`,
+ concept_refs: ['orphan-theme'],
+ }));
+ const result = await runPhaseSynthesizeConcepts(engine, {
+ _atoms: atoms,
+ _chat: stubChat('A real narrative.'),
+ });
+ expect(result.status).toBe('warn');
+ expect(result.details?.failures).toEqual([]);
+ const linkWarnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
+ expect(linkWarnings).toHaveLength(1);
+ expect(linkWarnings[0].concept).toBe('orphan-theme');
+ expect(linkWarnings[0].warning).toContain('provenance links');
+ expect(result.summary).not.toContain('template fallback');
+ expect((await engine.getPage('concepts/orphan-theme'))?.frontmatter.synthesis_mode).toBe('llm');
+
+ const rollup = await engine.executeRaw<{ halt_count: number; round_completed_count: number }>(
+ `SELECT halt_count, round_completed_count FROM extract_rollup_7d WHERE kind = 'concepts'`,
+ );
+ expect(rollup).toHaveLength(1);
+ expect(Number(rollup[0].halt_count)).toBe(0);
+ expect(Number(rollup[0].round_completed_count)).toBe(1);
});
});
diff --git a/test/cycle/synthesize-concepts-source-scope.test.ts b/test/cycle/synthesize-concepts-source-scope.test.ts
index ace8792c90..cb60d27739 100644
--- a/test/cycle/synthesize-concepts-source-scope.test.ts
+++ b/test/cycle/synthesize-concepts-source-scope.test.ts
@@ -52,8 +52,17 @@ const atoms = [
{ slug: 'a2', title: 'A2', body: 'b2', concept_refs: ['theme'] },
];
+/** Persist the injected atoms in the source under test: the #4589 provenance
+ * edges need both endpoints there, else the phase (rightly) reports a warn. */
+async function persistAtoms(sourceId: string): Promise<void> {
+ for (const a of atoms) {
+ await engine.putPage(a.slug, { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' }, { sourceId });
+ }
+}
+
describe('synthesize_concepts source scoping (#4416)', () => {
test('writes concept page + rollup under opts.sourceId; re-run (update path) survives on a non-default source', async () => {
+ await persistAtoms('personal');
const first = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'personal' });
expect(first.status).toBe('ok');
@@ -79,6 +88,7 @@ describe('synthesize_concepts source scoping (#4416)', () => {
}, 120000);
test('omitting sourceId keeps the legacy default fallback', async () => {
+ await persistAtoms('default');
const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms });
expect(result.status).toBe('ok');
@@ -97,3 +107,39 @@ describe('synthesize_concepts source scoping (#4416)', () => {
expect(rollup.every((r) => r.source_id === 'default')).toBe(true);
}, 120000);
});
+
+// ─── wave review (Codex P2): atom discovery is scoped to the cycle source ──
+describe('synthesize_concepts atom discovery is source-scoped', () => {
+ async function seedAtomPage(slug: string, sourceId: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'atom',
+ title: slug,
+ compiled_truth: `body of ${slug}`,
+ timeline: '',
+ frontmatter: { concepts: ['theme'] },
+ }, { sourceId });
+ }
+
+ test('atoms living in another source are not grouped into this source\'s concepts', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('other', 'Other') ON CONFLICT (id) DO NOTHING`,
+ [],
+ );
+ await seedAtomPage('atoms/o1', 'other');
+ await seedAtomPage('atoms/o2', 'other');
+
+ // The cycle for 'personal' must see NO atoms — the SQL discovery was
+ // brain-global while the provenance edges were pinned to the cycle
+ // source, so same-slug atoms from other sources were grouped in.
+ const personal = await runPhaseSynthesizeConcepts(engine, { sourceId: 'personal' });
+ expect(personal.status).toBe('skipped');
+ expect(personal.details?.reason).toBe('no_atoms');
+ expect(await engine.getPage('concepts/theme', { sourceId: 'personal' })).toBeNull();
+
+ // The owning source still synthesizes them.
+ const other = await runPhaseSynthesizeConcepts(engine, { sourceId: 'other' });
+ expect(other.status).toBe('ok');
+ expect(other.details?.concepts_written).toBe(1);
+ expect(await engine.getPage('concepts/theme', { sourceId: 'other' })).not.toBeNull();
+ });
+});
diff --git a/test/cycle/synthesize-concepts-token-cap.test.ts b/test/cycle/synthesize-concepts-token-cap.test.ts
new file mode 100644
index 0000000000..23beed1770
--- /dev/null
+++ b/test/cycle/synthesize-concepts-token-cap.test.ts
@@ -0,0 +1,108 @@
+// synthesize_concepts resolves its narrative model at `tier: 'reasoning'` yet
+// capped the call at a hardcoded 500 output tokens. On a thinking-by-default
+// model, reasoning bills as output and counts against max_tokens, so the budget
+// is spent before any answer text is emitted: hosted DeepSeek returns empty
+// content with finish_reason "length" (→ 'empty model response' + a template
+// stub narrative), while the native deepseek: recipe promotes the truncated
+// reasoning_content into content (→ truncated chain-of-thought persisted as the
+// concept narrative with synthesis_mode 'llm'). Both shapes are fixed by sizing
+// the cap from the resolved model, the way think's maxOutputTokensFor does.
+//
+// Hermetic: PGLite + injected `_atoms` and `_chat`. No provider credentials and
+// no network.
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import {
+ runPhaseSynthesizeConcepts,
+ resolveSynthMaxOutputTokens,
+} from '../../src/core/cycle/synthesize-concepts.ts';
+import { getProviderCapabilities } from '../../src/core/ai/capabilities.ts';
+import { THINKING_MODEL_MAX_OUTPUT_TOKENS } from '../../src/core/ai/gateway.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
+
+describe('resolveSynthMaxOutputTokens', () => {
+ test('grants the gateway\'s verified thinking cap to a recipe-declared thinking-by-default model', () => {
+ // Guard the premise: if the recipe drops the flag this fails here, loudly.
+ expect(getProviderCapabilities('deepseek:deepseek-v4-flash').supportsThinking).toBe(true);
+ // Not a local constant: a phase-private 8000 contradicted the gateway's
+ // THINKING_MODEL_MAX_OUTPUT_TOKENS (DeepSeek v4 truncates at 8192-class
+ // caps), so the reasoning budget was spent before any answer text.
+ expect(THINKING_MODEL_MAX_OUTPUT_TOKENS).toBeGreaterThan(8192);
+ expect(resolveSynthMaxOutputTokens('deepseek:deepseek-v4-flash')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ });
+
+ test('grants the same cap to a name-matched Claude 5 model', () => {
+ expect(resolveSynthMaxOutputTokens('anthropic:claude-sonnet-5')).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ });
+
+ test('keeps the 500 default for a non-thinking model', () => {
+ expect(getProviderCapabilities('groq:qwen/qwen3.8-27b').supportsThinking).toBe(false);
+ expect(resolveSynthMaxOutputTokens('groq:qwen/qwen3.8-27b')).toBe(500);
+ });
+
+ test('degrades to the default for an unknown provider instead of throwing', () => {
+ expect(resolveSynthMaxOutputTokens('not-a-provider:nope')).toBe(500);
+ });
+});
+
+describe('synthesize_concepts wires the cap into the narrative call', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ });
+
+ /** Five atoms on one concept clears TIER_T2_MIN, which routes the group through chat(). */
+ const t2Atoms = () =>
+ Array.from({ length: 5 }, (_, i) => ({
+ slug: `atoms/a${i}`,
+ concept_refs: ['concepts/x'],
+ body: `body ${i}`,
+ title: `A${i}`,
+ }));
+
+ /** Records the `maxTokens` field of every chat() call the phase makes. */
+ function capturingChat(seen: Array<number | undefined>): (o: ChatOpts) => Promise<ChatResult> {
+ return async (o: ChatOpts) => {
+ seen.push(o.maxTokens);
+ const text = 'narrative text';
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: o.model ?? 'unset',
+ providerId: 'test',
+ };
+ };
+ }
+
+ test('a thinking-by-default models.dream.synthesize gets the gateway thinking cap; a non-thinking one keeps 500', async () => {
+ await engine.setConfig('models.dream.synthesize', 'deepseek:deepseek-v4-flash');
+ const thinking: Array<number | undefined> = [];
+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: capturingChat(thinking) });
+ expect(thinking.length).toBeGreaterThan(0);
+ expect(new Set(thinking)).toEqual(new Set([THINKING_MODEL_MAX_OUTPUT_TOKENS]));
+
+ // An explicit non-thinking model (not "unset"): resolveModel's unset path
+ // falls through to GBRAIN_MODEL and a key-aware tier default, so the 500
+ // pin would otherwise depend on which provider keys the runner has.
+ await engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');
+ const plain: Array<number | undefined> = [];
+ await runPhaseSynthesizeConcepts(engine, { _atoms: t2Atoms(), _chat: capturingChat(plain) });
+ expect(plain.length).toBeGreaterThan(0);
+ expect(new Set(plain)).toEqual(new Set([500]));
+ });
+});
diff --git a/test/delta-cursor-microseconds.test.ts b/test/delta-cursor-microseconds.test.ts
new file mode 100644
index 0000000000..00e6454531
--- /dev/null
+++ b/test/delta-cursor-microseconds.test.ts
@@ -0,0 +1,96 @@
+/**
+ * `delta` cursor exactness at the column's microsecond precision.
+ *
+ * `pages.updated_at` stores microseconds; a cursor minted from a JS Date
+ * (millisecond precision) re-selects every row in the last delivered row's
+ * millisecond on the next wake, so same-millisecond pages are re-delivered
+ * (duplicates under at-least-once, never skips). The cursor now rides
+ * `Page.updated_at_iso` (projected by `listPages`) end to end: the stateless
+ * `next_cursor.since` round-trip and the per-session `last_wake_at` read-back.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+let engine: PGLiteEngine;
+const del = operations.find((o) => o.name === 'delta')!;
+const putPage = operations.find((o) => o.name === 'put_page')!;
+
+function localCtx(): OperationContext {
+ return {
+ engine,
+ config: {} as GBrainConfig,
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ } as OperationContext;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+type VerbResult = Record<string, any>;
+const slugs = (r: VerbResult): string[] => (r.pages as Array<{ slug: string }>).map((p) => p.slug);
+
+async function call(op: typeof del, p: Record<string, unknown>): Promise<VerbResult> {
+ return (await op.handler(localCtx(), p)) as VerbResult;
+}
+
+/** Two pages one microsecond apart inside ONE millisecond, stamped via SQL
+ * (putPage server-stamps now()). `base` is a timestamptz expression. */
+async function seedPair(base: string, params: unknown[] = []): Promise<void> {
+ for (const s of ['a', 'b']) {
+ await call(putPage, { slug: `notes/us-${s}`, content: `# ${s}\n\nbody` });
+ }
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = (${base}) + interval '100 microseconds' WHERE slug = 'notes/us-a'`, params,
+ );
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = (${base}) + interval '101 microseconds' WHERE slug = 'notes/us-b'`, params,
+ );
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+describe('delta — cursor carries column-precision microseconds', () => {
+ test('stateless: next_cursor.since is the exact row timestamp and the resumed wake re-delivers nothing', async () => {
+ await seedPair(`'2026-08-10T12:00:00.000000Z'::timestamptz`);
+ const r1 = await call(del, { since: '2026-08-10T11:59:00Z' });
+ expect(slugs(r1)).toEqual(['notes/us-a', 'notes/us-b']);
+ expect(r1.next_cursor.since).toBe('2026-08-10T12:00:00.000101Z');
+ expect(r1.next_cursor.slug).toBe('notes/us-b');
+
+ const r2 = await call(del, { since: r1.next_cursor.since, since_slug: r1.next_cursor.slug });
+ expect(slugs(r2)).toEqual([]);
+ // The cursor is stable across an empty wake (not re-rounded on echo).
+ expect(r2.next_cursor.since).toBe('2026-08-10T12:00:00.000101Z');
+ });
+
+ test('session: the stored cursor reads back exact, so the third wake re-delivers nothing', async () => {
+ const sid = 'us-session';
+ const r0 = await call(del, { session_id: sid });
+ expect(slugs(r0)).toEqual([]);
+ // Stamp the pair just after the established cursor, inside its millisecond.
+ await seedPair(`SELECT last_wake_at FROM session_context_state WHERE session_id = $1`, [sid]);
+ const r1 = await call(del, { session_id: sid });
+ expect(slugs(r1)).toEqual(['notes/us-a', 'notes/us-b']);
+ expect(r1.next_cursor.since).toMatch(/\.\d{6}Z$/);
+
+ const r2 = await call(del, { session_id: sid });
+ expect(slugs(r2)).toEqual([]);
+ });
+});
diff --git a/test/doctor-atom-provenance-drift.test.ts b/test/doctor-atom-provenance-drift.test.ts
index 16b1cabd82..b02a7cc1da 100644
--- a/test/doctor-atom-provenance-drift.test.ts
+++ b/test/doctor-atom-provenance-drift.test.ts
@@ -9,16 +9,21 @@
* - `pending:` in-flight markers are excluded (they are written before the
* extraction commits and would otherwise all read as drift);
* - warn needs BOTH the ratio and the absolute count, so a brain with a
- * handful of atoms doesn't flap.
+ * handful of atoms doesn't flap;
+ * - slug-unbound atoms (no `source_slug`: transcript-minted source_path-only,
+ * or pre-binding-era) are their own informational count — never drift,
+ * never source_gone, never in the WARN ratio (#4799 + #4806).
*
* Real in-memory PGLite (canonical block, R3+R4).
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { createHash } from 'node:crypto';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { computeAtomProvenanceDriftCheck } from '../src/commands/doctor.ts';
import type { BrainEngine } from '../src/core/engine.ts';
+import { doctorFileSource } from './helpers/doctor-source.ts';
let engine: PGLiteEngine;
@@ -196,6 +201,72 @@ describe('computeAtomProvenanceDriftCheck', () => {
expect(c.message).toContain('relation "pages" does not exist');
});
+ it('does not count transcript-minted (file-bound) atoms as drift (#4806)', async () => {
+ // The transcript lane stamps `source_path` + source_hash = sha256(raw file)[:16]
+ // and NO source_slug. That hash is a different function over different
+ // input than pages.content_hash, so it can never resolve to a page — such
+ // atoms are file-bound and must be reported as their own count, not drift.
+ await seedSource('src-a', 'original body');
+ await seedAtom('atoms/2026-01-01/a-000000', 'src-a', await hashOf('src-a'));
+ for (let i = 0; i < 30; i++) {
+ await engine.putPage(`atoms/2026-01-01/t-${String(i).padStart(6, '0')}`, {
+ type: 'atom', title: `t${i}`, compiled_truth: 'claim body',
+ frontmatter: {
+ type: 'atom',
+ source_path: `/abs/transcripts/2026-01-01-session-${i}.md`,
+ source_hash: createHash('sha256').update(`raw transcript ${i}`).digest('hex').slice(0, 16),
+ extracted_at: new Date().toISOString(),
+ },
+ });
+ }
+ const c = await computeAtomProvenanceDriftCheck(engine);
+ const d = c.details as Record<string, number>;
+ expect(c.status).toBe('ok');
+ expect(d.drifted).toBe(0);
+ expect(d.slug_unbound).toBe(30);
+ expect(d.total_atoms).toBe(1);
+ expect(c.message).toContain('30 slug-unbound');
+
+ // Page-bound drift is still detected alongside the file-bound population.
+ await seedSource('src-a', 'rewritten body');
+ const d2 = (await computeAtomProvenanceDriftCheck(engine)).details as Record<string, number>;
+ expect(d2.drifted).toBe(1);
+ expect(d2.source_changed).toBe(1);
+ expect(d2.source_gone).toBe(0);
+ expect(d2.slug_unbound).toBe(30);
+ }, 120_000);
+
+ it('resolves provenance via materialized same-source lookup sets, not per-atom correlated EXISTS (#4937)', () => {
+ // Postgres only rewrites EXISTS into a semi/anti-join when it sits in
+ // WHERE; in the SELECT list it stays a correlated SubPlan re-run per atom
+ // over an unindexed substring(content_hash) expression — O(atoms x pages),
+ // which blew a 60s health-monitor budget on a 27k-page / 7k-atom brain.
+ const src = doctorFileSource('doctor/checks/extraction-sync.ts');
+ const start = src.indexOf('), drift AS (');
+ expect(start).toBeGreaterThan(0);
+ const end = src.indexOf('SELECT count(*)', start);
+ expect(end).toBeGreaterThan(start);
+ const slice = src.slice(start, end);
+ expect(slice).not.toMatch(/\bEXISTS\s*\(\s*SELECT 1 FROM pages/);
+ expect(slice).toMatch(/LEFT JOIN live_hashes/);
+ expect(slice).toMatch(/LEFT JOIN live_slugs/);
+ });
+
+ it('does not fan out an atom whose source hash is carried by two live pages (#4937)', async () => {
+ // Duplicate live content_hash within one source is a real state (see the
+ // content_hash_duplicates check). A lookup-set join must be DISTINCT or
+ // one atom becomes two rows and every count inflates.
+ const page = { type: 'article', title: 'dup', compiled_truth: 'identical body' };
+ await engine.putPage('dup/a', page);
+ await engine.putPage('dup/b', page);
+ const [ha, hb] = [await hashOf('dup/a'), await hashOf('dup/b')];
+ expect(ha).toBe(hb);
+ await seedAtom('atoms/2026-01-01/dup-000000', 'dup/a', ha);
+ const d = (await computeAtomProvenanceDriftCheck(engine)).details as Record<string, number>;
+ expect(d.total_atoms).toBe(1);
+ expect(d.drifted).toBe(0);
+ });
+
it('warns once both the ratio and the count are exceeded', async () => {
// 30 drifted out of 30 → over MIN_DRIFTED (25) and over WARN_RATIO (0.1).
await seedSource('src-f', 'original body');
@@ -207,4 +278,86 @@ describe('computeAtomProvenanceDriftCheck', () => {
expect(c.message).toContain('30/30');
expect(c.message).toContain('source page is gone');
});
+ it('does not count a slug-unbound atom (source_path only, no source_slug) as source_gone — or as drift at all (#4806)', async () => {
+ // Transcript-origin atoms carry `source_path` but no `source_slug`
+ // (isCompatibleAtomBinding in extract-atoms.ts) -- this is the CURRENT,
+ // ongoing binding kind for every transcript-kind atom, not a shrinking
+ // legacy cohort. They can never match p.slug, so the slug-only liveness
+ // probe reported every one of them as an orphan even while the source
+ // page was alive — measured on a real brain as 702 "gone" atoms whose
+ // source pages all still existed. #4806 then took them out of the drift
+ // population entirely: their hash is over a file, not a page, so a page
+ // probe can never resolve it and must not move the ratio.
+ await seedSource('src-l', 'original body');
+ await engine.putPage('atoms/2026-01-01/l-000000', {
+ type: 'atom', title: 'l', compiled_truth: 'claim body',
+ frontmatter: {
+ type: 'atom',
+ source_path: '/imports/src-l.md',
+ source_hash: await hashOf('src-l'),
+ extracted_at: new Date().toISOString(),
+ },
+ });
+ await seedSource('src-l', 'rewritten body'); // hash moves — but not page-bound, so not drift
+ const d = (await computeAtomProvenanceDriftCheck(engine)).details as Record<string, number>;
+ expect(d.drifted).toBe(0);
+ expect(d.total_atoms).toBe(0);
+ expect(d.source_gone).toBe(0);
+ expect(d.source_changed).toBe(0);
+ expect(d.slug_unbound).toBe(1);
+ });
+
+ it('treats an empty-string source_slug like a missing one — slug-unbound, not page-bound (#4806)', async () => {
+ await seedSource('src-k', 'original body');
+ await engine.putPage('atoms/2026-01-01/k-000000', {
+ type: 'atom', title: 'k', compiled_truth: 'claim body',
+ frontmatter: {
+ type: 'atom', source_slug: '', source_path: '/imports/src-k.md',
+ source_hash: 'deadbeefdeadbeef', extracted_at: new Date().toISOString(),
+ },
+ });
+ const d = (await computeAtomProvenanceDriftCheck(engine)).details as Record<string, number>;
+ expect(d.source_gone).toBe(0);
+ expect(d.slug_unbound).toBe(1);
+ expect(d.total_atoms).toBe(0);
+ expect(d.drifted).toBe(0);
+ });
+
+ it('omits the slug-unbound bucket from the warn message when every drifted atom is slug-bound', async () => {
+ await seedSource('src-q', 'original body');
+ for (let i = 0; i < 30; i++) {
+ await seedAtom(`atoms/2026-01-01/q-${String(i).padStart(6, '0')}`, 'src-q', 'deadbeefdeadbeef');
+ }
+ const c = await computeAtomProvenanceDriftCheck(engine);
+ expect(c.status).toBe('warn');
+ expect((c.details as Record<string, number>).slug_unbound).toBe(0);
+ expect(c.message).not.toContain('slug-unbound');
+ }, 60_000);
+
+ it('names the slug-unbound bucket in the warn message without letting it drive the WARN or the denominator (#4806)', async () => {
+ await seedSource('src-p', 'original body');
+ // 30 page-bound drifted atoms trip the WARN on their own (30/30)...
+ for (let i = 0; i < 30; i++) {
+ await seedAtom(`atoms/2026-01-01/pd-${String(i).padStart(6, '0')}`, 'src-p', 'deadbeefdeadbeef');
+ }
+ // ...and 30 slug-unbound atoms ride along as an informational count only.
+ for (let i = 0; i < 30; i++) {
+ await engine.putPage(`atoms/2026-01-01/p-${String(i).padStart(6, '0')}`, {
+ type: 'atom', title: `p${i}`, compiled_truth: 'claim body',
+ frontmatter: {
+ type: 'atom', source_path: '/imports/src-p.md',
+ source_hash: 'deadbeefdeadbeef', extracted_at: new Date().toISOString(),
+ },
+ });
+ }
+ const c = await computeAtomProvenanceDriftCheck(engine);
+ const d = c.details as Record<string, number>;
+ expect(c.status).toBe('warn');
+ expect(d.total_atoms).toBe(30); // not 60
+ expect(d.drifted).toBe(30);
+ expect(d.slug_unbound).toBe(30);
+ expect(c.message).toContain('30/30');
+ expect(c.message).toContain('0 whose source page is gone');
+ expect(c.message).toContain('30 slug-unbound');
+ }, 60_000);
});
diff --git a/test/doctor-eval-drift-branches.serial.test.ts b/test/doctor-eval-drift-branches.serial.test.ts
new file mode 100644
index 0000000000..ad57613028
--- /dev/null
+++ b/test/doctor-eval-drift-branches.serial.test.ts
@@ -0,0 +1,63 @@
+/**
+ * Pins the two degraded arms of `checkEvalDrift` (src/commands/doctor/checks/search-eval.ts)
+ * that the PGLite-backed doctor tests can never reach from inside a source checkout:
+ *
+ * (a) `resolveGbrainSourceRoot()` → null (installed package / compiled binary):
+ * "Not applicable" — and the git probe is never attempted.
+ * (b) root present but `watchedFilesDrifted()` → null (git unavailable / not a
+ * work tree): "Could not probe" — the probe was attempted against that root.
+ *
+ * Serial (*.serial.test.ts): uses mock.module, which leaks across files in a shared
+ * shard process. Every other drift-watch export stays real via the `...real` spread
+ * (same pattern as test/cycle-start-recovery-throw.serial.test.ts).
+ */
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const real = await import('../src/core/eval/drift-watch.ts');
+
+const FAKE_ROOT = '/tmp/fake-gbrain-src-root';
+let fakeRoot: string | null = null;
+let probedRoots: string[] = [];
+
+mock.module('../src/core/eval/drift-watch.ts', () => ({
+ ...real,
+ resolveGbrainSourceRoot: (): string | null => fakeRoot,
+ watchedFilesDrifted: (repoRoot: string): string[] | null => {
+ probedRoots.push(repoRoot);
+ return null;
+ },
+}));
+
+// Import AFTER the mock so the check's dynamic `import('../../../core/eval/drift-watch.ts')`
+// resolves to the mocked namespace.
+const { checkEvalDrift } = await import('../src/commands/doctor/checks/search-eval.ts');
+
+// checkEvalDrift never touches the engine; a stub keeps the file PGLite-free.
+const engine = {} as unknown as BrainEngine;
+
+beforeEach(() => {
+ probedRoots = [];
+});
+
+describe('checkEvalDrift degraded branches', () => {
+ test('null source root → "Not applicable" and the git probe is skipped', async () => {
+ fakeRoot = null;
+ const c = await checkEvalDrift(engine);
+ expect(c.name).toBe('eval_drift');
+ expect(c.status).toBe('ok');
+ expect(c.message).toContain('Not applicable');
+ expect(probedRoots).toEqual([]);
+ });
+
+ test('root present but probe returns null → "Could not probe" against that root', async () => {
+ fakeRoot = FAKE_ROOT;
+ const c = await checkEvalDrift(engine);
+ expect(c.name).toBe('eval_drift');
+ expect(c.status).toBe('ok');
+ expect(c.message).toContain('Could not probe');
+ expect(c.message).toContain('not a git work tree');
+ expect(c.message).not.toContain('Not applicable');
+ expect(probedRoots).toEqual([FAKE_ROOT]);
+ });
+});
diff --git a/test/doctor-report-remote.serial.test.ts b/test/doctor-report-remote.serial.test.ts
index 0f6992355d..a456c87b1d 100644
--- a/test/doctor-report-remote.serial.test.ts
+++ b/test/doctor-report-remote.serial.test.ts
@@ -13,6 +13,7 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { doctorReportRemote, computeDoctorReport, type DoctorReport, type Check } from '../src/commands/doctor.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
let engine: PGLiteEngine;
let tmpHome: string;
@@ -137,3 +138,67 @@ describe('computeDoctorReport — score + status math', () => {
expect(r.schema_version).toBe(2);
});
});
+
+// #4592 — the thin-client doctor report is an admin-scope aggregate on the same
+// trust boundary as get_stats/get_health: a source-scoped remote grant must not
+// read the brain-wide page count back out of the `connection` check (the same
+// subtraction leak, one op over). Seeded AFTER the fresh-brain suite above so
+// those assertions keep their empty brain.
+describe('doctorReportRemote — source scope (#4592)', () => {
+ const SRCA = 'scopesrca';
+ const SRCB = 'scopesrcb';
+ const message = (r: DoctorReport, name: string) => r.checks.find(c => c.name === name)!.message;
+ const put = (sourceId: string, slug: string) =>
+ engine.putPage(slug, { title: slug, type: 'note', compiled_truth: `# ${slug}\n\nbody\n` }, { sourceId });
+
+ beforeAll(async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('${SRCA}', '${SRCA}'), ('${SRCB}', '${SRCB}') ON CONFLICT (id) DO NOTHING`,
+ );
+ await put(SRCA, 'notes/alpha');
+ await put(SRCA, 'notes/beta');
+ await put(SRCB, 'notes/gamma');
+ });
+
+ test('sourceIds confines the connection page count instead of reporting brain-wide', async () => {
+ const report = await doctorReportRemote(engine, { sourceIds: [SRCA] });
+ expect(message(report, 'connection')).toBe('Connected, 2 pages');
+ });
+
+ test('run_doctor threads a remote federated grant into the count', async () => {
+ const ctx = {
+ engine,
+ remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['admin'], allowedSources: [SRCB] },
+ } as unknown as OperationContext;
+ const report = await operationsByName.run_doctor.handler(ctx, {}) as DoctorReport;
+ expect(message(report, 'connection')).toBe('Connected, 1 pages');
+ });
+
+ test('differential: mutating an EXCLUDED source moves nothing a scoped report shows', async () => {
+ const before = await doctorReportRemote(engine, { sourceIds: [SRCA] });
+ await put(SRCB, 'notes/delta');
+ const after = await doctorReportRemote(engine, { sourceIds: [SRCA] });
+ expect(message(after, 'connection')).toBe(message(before, 'connection'));
+ expect(message(after, 'brain_score')).toBe(message(before, 'brain_score'));
+ });
+
+ 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
+ // granted only SRCA must see a zero backlog and no trace of SRCB anywhere
+ // in the report — details.backlog_by_source, messages, fix hints.
+ const body = 'x'.repeat(600);
+ for (let i = 0; i < 12; i++) {
+ await engine.putPage(`articles/leak-${i}`, { title: `leak-${i}`, type: 'article', compiled_truth: body }, { sourceId: SRCB });
+ }
+ const wide = await doctorReportRemote(engine);
+ const wideBacklog = wide.checks.find(c => c.name === 'extract_atoms_backlog')!;
+ expect(Number((wideBacklog.details as { backlog: number }).backlog)).toBeGreaterThanOrEqual(12);
+
+ const scoped = await doctorReportRemote(engine, { sourceIds: [SRCA] });
+ const scopedBacklog = scoped.checks.find(c => c.name === 'extract_atoms_backlog')!;
+ expect(Number((scopedBacklog.details as { backlog: number }).backlog)).toBe(0);
+ expect(JSON.stringify(scoped)).not.toContain(SRCB);
+ });
+});
diff --git a/test/doctor-search-mode.test.ts b/test/doctor-search-mode.test.ts
index a32009f9cf..c885fe74a9 100644
--- a/test/doctor-search-mode.test.ts
+++ b/test/doctor-search-mode.test.ts
@@ -15,6 +15,10 @@
* still warns.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execSync } from 'child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { checkSearchMode, checkEvalDrift } from '../src/commands/doctor.ts';
import {
@@ -168,4 +172,30 @@ describe('checkEvalDrift [CDX-6]', () => {
expect(c.message).toBeTruthy();
expect(c.message.length).toBeGreaterThan(0);
});
+
+ test("probes gbrain's own checkout, not whatever repo the operator stood in (#4606)", async () => {
+ // Unrelated scratch repo with a staged file that happens to match the
+ // retrieval watch list. Doctor must not report it as gbrain drift.
+ const tmp = mkdtempSync(join(tmpdir(), 'gb-drift-cwd-'));
+ const git = (args: string) =>
+ execSync(`git -c [email protected] -c user.name=t -c commit.gpgsign=false ${args}`, {
+ cwd: tmp,
+ stdio: 'pipe',
+ });
+ git('init -q');
+ git('commit -q --allow-empty -m init');
+ mkdirSync(join(tmp, 'src/core/search'), { recursive: true });
+ writeFileSync(join(tmp, 'src/core/search/zz-unrelated-repo.ts'), 'export {};\n');
+ git('add -A');
+ const prev = process.cwd();
+ process.chdir(tmp);
+ try {
+ const c = await checkEvalDrift(engine);
+ expect(c.status).toBe('ok');
+ expect(c.message).not.toContain('zz-unrelated-repo.ts');
+ } finally {
+ process.chdir(prev);
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
});
diff --git a/test/doctor-silent-death-checks.test.ts b/test/doctor-silent-death-checks.test.ts
index 90f59d82d6..8af187c6be 100644
--- a/test/doctor-silent-death-checks.test.ts
+++ b/test/doctor-silent-death-checks.test.ts
@@ -223,6 +223,22 @@ describe('undeclared_db_only_pages (#2784)', () => {
expect(c.status).toBe('ok');
});
+ test('basename-relative source_path under the slug directory → file-backed', async () => {
+ const repo = makeRepo();
+ mkdirSync(join(repo, '.git'));
+ mkdirSync(join(repo, 'journal'), { recursive: true });
+ writeFileSync(join(repo, 'journal', 'daily-note.md'), '# Daily note');
+ await addSource('src-a', repo);
+ await addPage('journal/daily-note', {
+ sourceId: 'src-a',
+ sourcePath: 'daily-note.md',
+ });
+
+ const c = await checkUndeclaredDbOnlyPages(engine);
+
+ expect(c.status).toBe('ok');
+ });
+
test('derive-phase default prefixes are implicitly declared', async () => {
const repo = makeRepo();
await addSource('src-a', repo);
diff --git a/test/doctor-upgrade-errors-stale.test.ts b/test/doctor-upgrade-errors-stale.test.ts
index fe5690b7fd..2326605437 100644
--- a/test/doctor-upgrade-errors-stale.test.ts
+++ b/test/doctor-upgrade-errors-stale.test.ts
@@ -41,5 +41,7 @@ describe('upgradeErrorResolved (#4517)', () => {
expect(upgradeErrorResolved('garbage', '0.46.28.0', true)).toBe(false);
expect(upgradeErrorResolved('0.46.10.0', 'garbage', true)).toBe(false);
expect(upgradeErrorResolved(undefined as unknown as string, '0.46.28.0', true)).toBe(false);
+ expect(upgradeErrorResolved('', '0.46.28.0', true)).toBe(false);
+ expect(upgradeErrorResolved('unknown', '0.46.28.0', true)).toBe(false);
});
});
diff --git a/test/dream-env-source-scope.test.ts b/test/dream-env-source-scope.test.ts
new file mode 100644
index 0000000000..392ff4cef2
--- /dev/null
+++ b/test/dream-env-source-scope.test.ts
@@ -0,0 +1,162 @@
+/**
+ * #4778 — `GBRAIN_SOURCE=<id> gbrain dream` scopes the cycle like `--source <id>`.
+ *
+ * Pre-fix, dream entered the shared 6-tier source resolver only behind the
+ * `--source` flag gate, so tier 2 (GBRAIN_SOURCE: validate + assertSourceExists)
+ * could never fire. An env-scoped bare run fell through to sources.default /
+ * sole-non-default / directory routing, cycled the wrong corpus, and never
+ * stamped the intended source's freshness — silently, with exit 0, even for an
+ * invalid or unregistered env value.
+ *
+ * Same real-PGLite/no-mocks discipline as test/dream-dir-source-stamp.test.ts,
+ * same GBRAIN_HOME isolation (the cycle's PGLite file lock lives under
+ * ~/.gbrain). Two active non-default sources with distinct on-disk local_paths
+ * are seeded where tier-5.5 sole-non-default routing must NOT be allowed to
+ * satisfy the assertion by accident; cwd stays outside both trees.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach, spyOn } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { ALL_PHASES } from '../src/core/cycle.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runDream } from '../src/commands/dream.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let dirA: string;
+let dirB: string;
+let gbrainHome: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ dirA = mkdtempSync(join(tmpdir(), 'gbrain-dream-env-a-'));
+ dirB = mkdtempSync(join(tmpdir(), 'gbrain-dream-env-b-'));
+ gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-dream-env-home-'));
+}, 60_000);
+
+afterEach(() => {
+ rmSync(dirA, { recursive: true, force: true });
+ rmSync(dirB, { recursive: true, force: true });
+ rmSync(gbrainHome, { recursive: true, force: true });
+});
+
+async function seedSource(id: string, localPath: string): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config, archived, created_at)
+ VALUES ($1, $2, $3, '{}'::jsonb, false, NOW())`,
+ [id, id, localPath],
+ );
+}
+
+async function readLastFullCycleAt(sourceId: string): Promise<string | null> {
+ const rows = await engine.executeRaw<{ config: Record<string, unknown> | null }>(
+ `SELECT config FROM sources WHERE id = $1`,
+ [sourceId],
+ );
+ const raw = rows[0]?.config?.last_full_cycle_at;
+ return typeof raw === 'string' ? raw : null;
+}
+
+/** Run dream expecting a clean exit-1; returns the stderr lines it printed. */
+async function runExpectingExit1(args: string[]): Promise<string[]> {
+ const exitSpy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });
+ const errLines: string[] = [];
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => {
+ errLines.push(a.map(String).join(' '));
+ });
+ try {
+ let threw: unknown;
+ try {
+ await runDream(engine, args);
+ } catch (e) {
+ threw = e;
+ }
+ expect((threw as Error | undefined)?.message).toBe('EXIT');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ return errLines;
+ } finally {
+ exitSpy.mockRestore();
+ errSpy.mockRestore();
+ }
+}
+
+describe('gbrain dream honors GBRAIN_SOURCE like --source (#4778)', () => {
+ test('two-source brain: GBRAIN_SOURCE=source-a stamps source-a only', async () => {
+ await seedSource('source-a', dirA);
+ await seedSource('source-b', dirB);
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: 'source-a' }, async () => {
+ const report = await runDream(engine, ['--phase', 'lint', '--json']);
+ expect(report).toBeTruthy();
+ if (report) expect(['ok', 'clean']).toContain(report.status);
+ // Pre-fix: two non-default sources defeat sole-non-default routing, no
+ // sync.repo_path means no dir derivation, so resolvedSourceId stayed
+ // undefined and runCycle's stamp gate skipped the write.
+ expect(await readLastFullCycleAt('source-a')).not.toBeNull();
+ expect(await readLastFullCycleAt('source-b')).toBeNull();
+ });
+ }, 60_000);
+
+ test('invalid GBRAIN_SOURCE exits 1 with the resolver message (was: exit 0, unscoped)', async () => {
+ await seedSource('source-a', dirA);
+ await seedSource('source-b', dirB);
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: 'NOT!VALID' }, async () => {
+ const errLines = await runExpectingExit1(['--phase', 'lint', '--json']);
+ expect(errLines.some((l) => l.startsWith('Invalid GBRAIN_SOURCE value'))).toBe(true);
+ });
+ }, 60_000);
+
+ test('unregistered GBRAIN_SOURCE exits 1 with the not-found message (was: exit 0, unscoped)', async () => {
+ await seedSource('source-a', dirA);
+ await seedSource('source-b', dirB);
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: 'ghost' }, async () => {
+ const errLines = await runExpectingExit1(['--phase', 'lint', '--json']);
+ expect(errLines.some((l) => l.includes('Source "ghost" not found or is archived.'))).toBe(true);
+ });
+ }, 60_000);
+
+ test('GBRAIN_SOURCE=__all__ spans the brain: never narrowed to the implicit default source (wave review)', async () => {
+ // Two populated-shape sources, sources.default = source-a: a bare run
+ // narrows to source-a (#4700). An EXPLICIT __all__ asks for the whole
+ // brain — the sentinel is excluded from the resolver (a '__all__' scope has
+ // no local_path), but it must also skip the implicit-default narrowing.
+ await seedSource('source-a', dirA);
+ await seedSource('source-b', dirB);
+ await engine.setConfig('sources.default', 'source-a');
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: '' }, async () => {
+ const bare = await runDream(engine, ['--phase', 'lint', '--json']);
+ expect(bare?.brain_dir).toBe(dirA); // the #4700 implicit-default lane
+ });
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: '__all__' }, async () => {
+ const report = await runDream(engine, ['--phase', 'lint', '--json']);
+ expect(report).toBeTruthy();
+ expect(report?.brain_dir).not.toBe(dirA);
+ expect(report?.phases.map((p) => p.phase)).toEqual(['lint']);
+ });
+ }, 60_000);
+
+ test('GBRAIN_SOURCE naming the sole non-default source keeps the full implicit cycle (#4700 no-regression)', async () => {
+ await seedSource('source-a', dirA);
+ await withEnv({ GBRAIN_HOME: gbrainHome, GBRAIN_SOURCE: 'source-a' }, async () => {
+ const report = await runDream(engine, ['--dry-run', '--json']);
+ expect(report).toBeTruthy();
+ // The env names the brain's default-like source, which is the canonical
+ // default cycle — not a freshness-only --source cycle.
+ expect(report?.phases.map((p) => p.phase)).toEqual(ALL_PHASES);
+ for (const p of report?.phases ?? []) {
+ expect((p.details as { reason?: string } | undefined)?.reason).not.toBe('excluded_from_implicit_source_cycle');
+ }
+ });
+ }, 300_000);
+});
diff --git a/test/dream.test.ts b/test/dream.test.ts
index 7a6bf43121..af07bb4153 100644
--- a/test/dream.test.ts
+++ b/test/dream.test.ts
@@ -26,7 +26,7 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';
-import { mkdtempSync, rmSync } from 'fs';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -308,8 +308,17 @@ describe('runDream — output format', () => {
test('--json emits parsable CycleReport JSON with schema_version', async () => {
const lines: string[] = [];
const logSpy = spyOn(console, 'log').mockImplementation((msg: string) => { lines.push(String(msg)); });
- await runDream(engine, ['--dir', repo, '--phase', 'lint', '--json']);
- logSpy.mockRestore();
+ // The JSON payload itself goes through console.log (captured above), so a
+ // raw process.stdout.write during the run can only be a progress/summary
+ // leak that would corrupt the payload — progress belongs on stderr.
+ const stdoutSpy = spyOn(process.stdout, 'write').mockReturnValue(true);
+ try {
+ await runDream(engine, ['--dir', repo, '--phase', 'lint', '--json']);
+ expect(stdoutSpy).not.toHaveBeenCalled();
+ } finally {
+ stdoutSpy.mockRestore();
+ logSpy.mockRestore();
+ }
const parsed = JSON.parse(lines.join('\n'));
expect(parsed.schema_version).toBe('1');
expect(parsed).toHaveProperty('status');
@@ -344,6 +353,26 @@ describe('runDream — output format', () => {
expect(parsed.phases[0].details.would_embed).toBe(1);
});
+ // The extract phase's `Links: created ...` / `Extract --stale: ...` summaries
+ // must not leak onto stdout ahead of the JSON CycleReport either.
+ test('--phase extract --json emits only JSON when the checkout has pages', async () => {
+ mkdirSync(join(repo, 'concepts'), { recursive: true });
+ writeFileSync(join(repo, 'concepts', 'testing.md'), '# Testing\nSee [[concepts/contracts]].\n');
+ writeFileSync(join(repo, 'concepts', 'contracts.md'), '# Contracts\nStay honest.\n');
+
+ const lines: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((msg: string) => { lines.push(String(msg)); });
+ await runDream(engine, ['--dir', repo, '--phase', 'extract', '--json']);
+ logSpy.mockRestore();
+
+ const output = lines.join('\n');
+ expect(output.trimStart().startsWith('{')).toBe(true);
+ const parsed = JSON.parse(output);
+ expect(parsed.phases[0].phase).toBe('extract');
+ expect(parsed.phases[0].details.pages_processed).toBe(2);
+ expect(parsed.totals.pages_extracted).toBe(2);
+ });
+
test('human output for clean status mentions "Brain is healthy"', async () => {
const lines: string[] = [];
const logSpy = spyOn(console, 'log').mockImplementation((msg: string) => { lines.push(String(msg)); });
diff --git a/test/drift-watch.test.ts b/test/drift-watch.test.ts
index 647c16446c..84f4be9245 100644
--- a/test/drift-watch.test.ts
+++ b/test/drift-watch.test.ts
@@ -2,14 +2,41 @@
* v0.32.3 — drift-watch module unit tests.
* Pins the curated watch-list + matchesWatchPattern semantics.
*/
-import { describe, expect, test } from 'bun:test';
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execSync } from 'child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
import {
RETRIEVAL_WATCH_PATTERNS,
matchesWatchPattern,
watchedFilesDrifted,
filesDriftedSince,
+ resolveGbrainSourceRoot,
} from '../src/core/eval/drift-watch.ts';
+const created: string[] = [];
+afterAll(() => {
+ for (const d of created) rmSync(d, { recursive: true, force: true });
+});
+
+/** Unrelated scratch repo with a staged file that matches the watch list. */
+function scratchRepoWithStagedSearchFile(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gb-drift-'));
+ created.push(dir);
+ const git = (args: string) =>
+ execSync(`git -c [email protected] -c user.name=t -c commit.gpgsign=false ${args}`, {
+ cwd: dir,
+ stdio: 'pipe',
+ });
+ git('init -q');
+ git('commit -q --allow-empty -m init');
+ mkdirSync(join(dir, 'src/core/search'), { recursive: true });
+ writeFileSync(join(dir, 'src/core/search/hybrid.ts'), 'export {};\n');
+ git('add -A');
+ return dir;
+}
+
describe('RETRIEVAL_WATCH_PATTERNS canonical list', () => {
test('includes src/core/search/ prefix', () => {
expect(RETRIEVAL_WATCH_PATTERNS).toContain('src/core/search/');
@@ -66,17 +93,51 @@ describe('matchesWatchPattern semantics', () => {
});
});
-describe('filesDriftedSince + watchedFilesDrifted graceful failure', () => {
- test('missing repo root returns empty array', () => {
- expect(filesDriftedSince('/does/not/exist')).toEqual([]);
+describe('filesDriftedSince + watchedFilesDrifted probe failure is distinguishable from a clean tree (#4606)', () => {
+ test('missing repo root returns null, not an empty (clean) list', () => {
+ expect(filesDriftedSince('/does/not/exist')).toBeNull();
+ });
+
+ test('a directory that is not a git work tree returns null', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'gb-nogit-'));
+ created.push(tmp);
+ expect(filesDriftedSince(tmp)).toBeNull();
+ expect(watchedFilesDrifted(tmp)).toBeNull();
+ });
+
+ test('a real repo with a staged watched file reports exactly that file', () => {
+ const repo = scratchRepoWithStagedSearchFile();
+ expect(watchedFilesDrifted(repo)).toEqual(['src/core/search/hybrid.ts']);
});
test('watchedFilesDrifted filters through the same matcher', () => {
// Smoke test: should not throw on this repo. Could be empty.
const out = watchedFilesDrifted(process.cwd());
expect(Array.isArray(out)).toBe(true);
- for (const p of out) {
+ for (const p of out ?? []) {
expect(matchesWatchPattern(p)).toBe(true);
}
});
});
+
+describe('resolveGbrainSourceRoot (#4606)', () => {
+ test('resolves this source checkout from the module location', () => {
+ const root = resolveGbrainSourceRoot();
+ expect(root).not.toBeNull();
+ expect(existsSync(join(root!, 'src', 'cli.ts'))).toBe(true);
+ });
+
+ test('compiled-binary virtual URL resolves to null', () => {
+ expect(resolveGbrainSourceRoot('file:///$bunfs/root/src/core/eval/drift-watch.ts')).toBeNull();
+ });
+
+ test('a package dir without .git is not a source checkout', () => {
+ const pkg = mkdtempSync(join(tmpdir(), 'gb-pkg-'));
+ created.push(pkg);
+ mkdirSync(join(pkg, 'src', 'core', 'eval'), { recursive: true });
+ mkdirSync(join(pkg, 'skills'), { recursive: true });
+ writeFileSync(join(pkg, 'src', 'cli.ts'), '');
+ writeFileSync(join(pkg, 'skills', 'RESOLVER.md'), '');
+ expect(resolveGbrainSourceRoot(`file://${join(pkg, 'src', 'core', 'eval', 'drift-watch.ts')}`)).toBeNull();
+ });
+});
diff --git a/test/e2e/engine-content-privacy.test.ts b/test/e2e/engine-content-privacy.test.ts
index 2d1b3d86b8..dd9823797d 100644
--- a/test/e2e/engine-content-privacy.test.ts
+++ b/test/e2e/engine-content-privacy.test.ts
@@ -38,6 +38,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
}, 120_000);
beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts WHERE source_id = ANY($1::text[])', [SOURCES]);
await engine.executeRaw('DELETE FROM pages WHERE source_id = ANY($1::text[])', [SOURCES]);
await engine.executeRaw('DELETE FROM slug_aliases WHERE source_id = ANY($1::text[])', [SOURCES]);
await engine.unsetConfig('entity_identity.union');
@@ -45,6 +46,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
afterAll(async () => {
if (engine) {
+ await engine.executeRaw('DELETE FROM facts WHERE source_id = ANY($1::text[])', [SOURCES]);
await engine.executeRaw('DELETE FROM sources WHERE id = ANY($1::text[])', [SOURCES]);
await engine.unsetConfig('entity_identity.union');
await engine.disconnect();
@@ -246,6 +248,39 @@ for (const kind of ['pglite', 'postgres'] as const) {
expect(JSON.stringify(await operationsByName.chronicle_since.handler(local, { date: '2026-08-10' }))).toContain(PRIVATE);
});
+ test('Ontology reads drop private-provenance observations before resolution and conflict detection', async () => {
+ await page('meetings/open-sync');
+ await page('meetings/secret-sync', A, true);
+ // Newer private-sourced value + older world-sourced value stay open side
+ // by side (backdated shape); the pair is also a two-provenance conflict.
+ for (const [entitySlug, value, source, validFrom] of [
+ ['people/ontology-subject', PRIVATE, 'meetings/secret-sync', '2026-05-01'],
+ ['people/ontology-subject', 'openvalue', 'meetings/open-sync', '2026-01-01'],
+ ['people/ontology-conflict', PRIVATE, 'meetings/secret-sync', '2026-05-01'],
+ ['people/ontology-conflict', 'yes', 'meetings/open-sync', '2026-01-01'],
+ ] as const) {
+ await engine.mergeOntologyFact({ entitySlug, dimension: 'role', value, source, validFrom, sourceId: A });
+ }
+ const scope = { sourceId: A, excludePrivate: true };
+ expect((await engine.getOntology('people/ontology-subject', scope)).map(v => v.value)).toEqual(['openvalue']);
+ expect((await engine.getOntology('people/ontology-subject', { sourceIds: [A, B], excludePrivate: true })).map(v => v.value)).toEqual(['openvalue']);
+ expect((await engine.getOntology('people/ontology-subject', { sourceId: A })).map(v => v.value)).toEqual([PRIVATE]);
+ expect((await engine.findOntologyConflicts(scope)).map(c => c.entity_slug)).toEqual([]);
+ expect((await engine.findOntologyConflicts({ sourceId: A })).map(c => c.entity_slug)).toEqual(['people/ontology-conflict', 'people/ontology-subject']);
+ for (const remote of [true, undefined]) {
+ const ctx = { engine, remote, sourceId: A, auth: { allowedSources: [A, B] } } as OperationContext;
+ for (const [op, args] of [
+ ['ontology_get', { entity: 'people/ontology-subject' }],
+ ['ontology_conflicts', {}],
+ ['volunteer_chronicle', { days: 1, limit: 1, entities: 'people/ontology-subject' }],
+ ] as const) {
+ expect(JSON.stringify(await operationsByName[op].handler(ctx, args))).not.toContain(PRIVATE);
+ }
+ }
+ const local = { engine, remote: false, sourceId: A } as OperationContext;
+ expect(JSON.stringify(await operationsByName.ontology_get.handler(local, { entity: 'people/ontology-subject' }))).toContain(PRIVATE);
+ });
+
test('takes require both a visible concrete page and an allowed holder in every read arm', async () => {
const visible = await page('people/takes-shared');
const hidden = await page('people/takes-shared', B, true);
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index a7379af581..b19e843962 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -1590,7 +1590,12 @@ describeBoth('Engine parity — ambient recall keyset + session cursor (v0.45.7)
expect(pglite!.standing_entities).toEqual(pg!.standing_entities);
expect(pg!.surfaced_slugs).toEqual(['ks/tie-04']); // single-element keyset slug
expect(pglite!.surfaced_slugs).toEqual(pg!.surfaced_slugs);
- expect(pg!.last_wake_at).toBe(KS_TIE_TS);
+ // last_wake_at is rendered at the column's microsecond precision (#4681:
+ // the keyset cursor must not re-round to milliseconds). Compare instants
+ // and pin the engines to the same text so parity, not a fixed format, is
+ // the contract.
+ expect(new Date(pg!.last_wake_at!).toISOString()).toBe(KS_TIE_TS);
+ expect(pg!.last_wake_at).toMatch(/\.\d{6}Z$/);
expect(pglite!.last_wake_at).toBe(pg!.last_wake_at);
// The read helper JSON.parses string scalars (fail-open), so it would MASK
@@ -1620,7 +1625,7 @@ describeBoth('Engine parity — ambient recall keyset + session cursor (v0.45.7)
]) {
expect(st!.standing_entities).toEqual(entities);
expect(st!.surfaced_slugs).toEqual(['ks/tie-04']);
- expect(st!.last_wake_at).toBe(KS_LATE_TS);
+ expect(new Date(st!.last_wake_at!).toISOString()).toBe(KS_LATE_TS);
}
});
});
diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.ts
index 3f6735a2ce..0a28e0692e 100644
--- a/test/e2e/serve-http-oauth.test.ts
+++ b/test/e2e/serve-http-oauth.test.ts
@@ -357,6 +357,73 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
);
});
+ // =========================================================================
+ // RFC 9728: protected-resource metadata describes /mcp, not the issuer root
+ // =========================================================================
+
+ // The MCP auth spec layers RFC 9728 on top of AS metadata: the *protected
+ // resource* is the streamable-HTTP endpoint the client actually POSTs to
+ // (/mcp), not the authorization-server root. Passing no resourceServerUrl
+ // made the SDK fall back to issuerUrl (AS == RS) and advertise
+ // `resource: "https://host/"`. A client that binds its grant to the
+ // canonical resource URI (RFC 8707) compares that against the
+ // "https://host/mcp" it was configured with, sees a mismatch, and refuses to
+ // treat the connection as authorized — re-running discovery and registering
+ // a fresh DCR client on every attempt, even though the issued bearer works
+ // fine on the wire.
+
+ test('protected-resource metadata advertises /mcp as the resource', async () => {
+ const res = await fetch(`${BASE}/.well-known/oauth-protected-resource/mcp`);
+ expect(res.ok).toBe(true);
+ const meta = await res.json() as any;
+ // The resource is the MCP endpoint, NOT the issuer root.
+ expect(meta.resource).toBe(`${BASE}/mcp`);
+ expect(meta.resource).not.toBe(`${BASE}/`);
+ expect(meta.authorization_servers).toContain(`${BASE}/`);
+ expect(meta.scopes_supported).toEqual(
+ expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),
+ );
+ });
+
+ // Setting resourceServerUrl moves the SDK's document to the path-inserted
+ // location only. Clients that probe the bare root (the pre-RFC-9728
+ // convention, and what gbrain advertised before this fix) must keep
+ // discovering us instead of getting a 404 mid-flight.
+ test('legacy root protected-resource path serves the same resource value', async () => {
+ const res = await fetch(`${BASE}/.well-known/oauth-protected-resource`);
+ expect(res.ok).toBe(true);
+ // Served by the SDK's metadataHandler (URL rewrite, not a hand-built
+ // document), so the root keeps the cors() origin it always had.
+ expect(res.headers.get('access-control-allow-origin')).toBe('*');
+ const meta = await res.json() as any;
+ expect(meta.resource).toBe(`${BASE}/mcp`);
+ });
+
+ // The 401 challenge must name a metadata URL that actually resolves: with
+ // resourceServerUrl set, the SDK mounts the document at the path-inserted
+ // location and no longer at the bare root, so a hardcoded root URL in the
+ // challenge would send clients to a 404. Advertised URL and mounted
+ // document have to move together.
+ test('401 challenge advertises a resource_metadata URL that resolves', async () => {
+ const res = await fetch(`${BASE}/mcp`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
+ });
+ expect(res.status).toBe(401);
+
+ const challenge = res.headers.get('www-authenticate') ?? '';
+ const advertised = challenge.match(/resource_metadata="([^"]+)"/)?.[1];
+ expect(advertised).toBeTruthy();
+
+ const meta = await fetch(advertised!);
+ expect(meta.ok).toBe(true);
+ expect((await meta.json() as any).resource).toBe(`${BASE}/mcp`);
+ });
+
// =========================================================================
// Fix 3: Express 5 compatibility
// =========================================================================
diff --git a/test/e2e/serve-stdio-roundtrip.test.ts b/test/e2e/serve-stdio-roundtrip.test.ts
index 52d2d81009..22856f60e4 100644
--- a/test/e2e/serve-stdio-roundtrip.test.ts
+++ b/test/e2e/serve-stdio-roundtrip.test.ts
@@ -106,10 +106,12 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()
execFixture(['run', 'src/cli.ts', 'import', federatedNotes, '--no-embed', '--source-id', 'federated-source'], env);
// 3. Let the MCP SDK spawn `gbrain serve` (stdio) and run the initialize
- // handshake — exactly what `claude mcp add gbrain -- gbrain serve` does.
+ // handshake with the opt-in idle timeout enabled. This pins the
+ // production wrapper shape that previously let the timeout's activity
+ // listener consume initialize before the SDK transport attached.
transport = new StdioClientTransport({
command: 'bun',
- args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'],
+ args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--stdio-idle-timeout', '14400'],
cwd: process.cwd(),
env, // includes PATH (to find `bun`) + GBRAIN_HOME
});
diff --git a/test/e2e/transcripts-ingest-pglite.test.ts b/test/e2e/transcripts-ingest-pglite.test.ts
index 3ffca66abf..1bbac79957 100644
--- a/test/e2e/transcripts-ingest-pglite.test.ts
+++ b/test/e2e/transcripts-ingest-pglite.test.ts
@@ -240,6 +240,22 @@ describe('dry-run', () => {
const pages = await engine.listPages({ type: 'conversation', sourceId: 'default', limit: 10 });
expect(pages).toHaveLength(0);
});
+
+ test('--limit truncates the dry-run preview the same way it truncates the real run (#4762)', async () => {
+ // Two single-part fixtures, limit 1: the preview must cover ONE session,
+ // not the whole backlog. The second session is reached (sessionsSeen 2)
+ // and then cut by the same gate the write path uses.
+ const r = await runTranscriptsIngest(
+ engine,
+ baseOpts([CODEX_FIXTURE, AGENT_FIXTURE], { dryRun: true, limit: 1 }),
+ );
+ expect(r.sessionsSeen).toBe(2);
+ expect(r.pages.planned).toBe(1);
+ expect(r.pages.imported).toBe(0);
+ expect(r.cleanScan).toBe(false);
+ const pages = await engine.listPages({ type: 'conversation', sourceId: 'default', limit: 10 });
+ expect(pages).toHaveLength(0);
+ });
});
describe('idempotency', () => {
diff --git a/test/e2e/voyage-rerank-live.test.ts b/test/e2e/voyage-rerank-live.test.ts
index 8a0f345582..37dd3fe285 100644
--- a/test/e2e/voyage-rerank-live.test.ts
+++ b/test/e2e/voyage-rerank-live.test.ts
@@ -78,6 +78,40 @@ describe('Voyage live — rerank wire contract', () => {
const out = await rerank({ query: 'hello', documents: ['hello world', 'goodbye'] });
expect(out.length).toBe(2);
}, 30_000);
+
+ // #4938 — the newly allowlisted current generation. Same endpoint, same
+ // `{query, documents, model}` request and `data[{index, relevance_score}]`
+ // response as the 2.5 pair, which is why the recipe needed no path or
+ // top_param change. This is the live confirmation of that claim.
+ for (const model of ['voyage:rerank-3', 'voyage:rerank-3-lite'] as const) {
+ test(`${model} passes the wire with top_k honored (#4938)`, async () => {
+ if (skipAll) {
+ console.warn('[skip] VOYAGE_API_KEY not set');
+ return;
+ }
+ resetGateway();
+ configureGateway({
+ reranker_model: model,
+ env: { VOYAGE_API_KEY: API_KEY! },
+ });
+ const out = await rerank({
+ query: 'What is the capital of France?',
+ documents: [
+ 'The Eiffel Tower is in Paris, the capital of France.',
+ 'Bananas are a good source of potassium.',
+ 'Paris is the capital and largest city of France.',
+ ],
+ topN: 2,
+ });
+ expect(out.length).toBe(2);
+ for (const r of out) {
+ expect(typeof r.index).toBe('number');
+ expect(typeof r.relevanceScore).toBe('number');
+ }
+ expect(out.map((r) => r.index).sort()).toEqual([0, 2]);
+ expect(out[0].relevanceScore).toBeGreaterThanOrEqual(out[1].relevanceScore);
+ }, 30_000);
+ }
});
describe('Voyage live — voyage-4 embed at the new-install width', () => {
diff --git a/test/embed-quarantine.serial.test.ts b/test/embed-quarantine.serial.test.ts
index 8efd51dc2a..d94ccd3faa 100644
--- a/test/embed-quarantine.serial.test.ts
+++ b/test/embed-quarantine.serial.test.ts
@@ -52,6 +52,10 @@ const { __setEmbedTransportForTests } = await import('../src/core/ai/gateway.ts'
__setEmbedTransportForTests(async () => ({ embeddings: [], usage: { tokens: 0 } } as any));
function mockEngine(overrides: Partial<Record<string, any>> = {}): BrainEngine {
+ // Raw SQL the stale drain issues (the page-provenance stamp check) reads an
+ // empty result set unless a test models it — the Proxy's null default would
+ // throw on indexing and count the page as a failed embed.
+ overrides = { executeRaw: async () => [], ...overrides };
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
calls.push({ method, args });
diff --git a/test/embed-stale-signature-pagination.serial.test.ts b/test/embed-stale-signature-pagination.serial.test.ts
new file mode 100644
index 0000000000..07d601cd37
--- /dev/null
+++ b/test/embed-stale-signature-pagination.serial.test.ts
@@ -0,0 +1,188 @@
+/**
+ * Regression tests for `embed --stale` signature reconciliation.
+ *
+ * A page can span the 2,000-row stale cursor boundary, so signatures must be
+ * recorded from the final database state rather than a cursor-batch subset.
+ *
+ * This file installs the process-global gateway transport seam, so it remains
+ * a `.serial.test.ts`; the transport is always fake and never calls an external provider.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import {
+ __setEmbedTransportForTests,
+ configureGateway,
+ resetGateway,
+} from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { ChunkInput } from '../src/core/types.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const DIMS = 1536;
+const MODEL = 'openai:text-embedding-3-large';
+const SIGNATURE = `${MODEL}:${DIMS}`;
+
+type EmbedTransport = (input: { values: string[] }) => Promise<{
+ embeddings: number[][];
+ usage: { tokens: number };
+}>;
+
+let engine: PGLiteEngine;
+let transportBehavior: EmbedTransport;
+let savedConcurrency: string | undefined;
+
+function fakeTransport(input: { values: string[] }) {
+ return Promise.resolve({
+ embeddings: input.values.map(() => new Array(DIMS).fill(0.001)),
+ usage: { tokens: input.values.length * 4 },
+ });
+}
+
+async function seedPage(slug: string, chunks: ChunkInput[]): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'note',
+ title: slug,
+ compiled_truth: `# ${slug}`,
+ });
+ await engine.upsertChunks(slug, chunks);
+}
+
+async function pageSignature(slug: string): Promise<string | null> {
+ const rows = await engine.executeRaw<{ embedding_signature: string | null }>(
+ `SELECT embedding_signature FROM pages WHERE slug = $1 AND source_id = 'default'`,
+ [slug],
+ );
+ return rows[0]?.embedding_signature ?? null;
+}
+
+function staleChunk(index: number, text = `stale chunk ${index}`): ChunkInput {
+ return {
+ chunk_index: index,
+ chunk_text: text,
+ chunk_source: 'compiled_truth',
+ token_count: 4,
+ };
+}
+
+function embeddedChunk(index: number, model = MODEL): ChunkInput {
+ return {
+ ...staleChunk(index, `embedded chunk ${index}`),
+ embedding: new Float32Array(DIMS).fill(0.002),
+ model,
+ };
+}
+
+beforeAll(async () => {
+ savedConcurrency = process.env.GBRAIN_EMBED_CONCURRENCY;
+ process.env.GBRAIN_EMBED_CONCURRENCY = '4';
+ configureGateway({
+ embedding_model: MODEL,
+ embedding_dimensions: DIMS,
+ env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ __setEmbedTransportForTests(async (input) => transportBehavior(input as { values: string[] }) as never);
+
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: DIMS } as never);
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+ if (savedConcurrency === undefined) delete process.env.GBRAIN_EMBED_CONCURRENCY;
+ else process.env.GBRAIN_EMBED_CONCURRENCY = savedConcurrency;
+});
+
+beforeEach(async () => {
+ transportBehavior = fakeTransport;
+ await resetPgliteState(engine);
+});
+
+describe('embed --stale page-level signature reconciliation', () => {
+ test('page split across the 2,000-row cursor boundary is stamped after the pass', async () => {
+ for (let page = 0; page < 40; page++) {
+ const chunkCount = page === 39 ? 49 : 50;
+ await seedPage(
+ `boundary-filler-${page.toString().padStart(2, '0')}`,
+ Array.from({ length: chunkCount }, (_, index) =>
+ staleChunk(index, `filler page ${page} chunk ${index}`),
+ ),
+ );
+ }
+ await seedPage(
+ 'split-page',
+ [staleChunk(0), staleChunk(1)],
+ );
+
+ const result = await runEmbedCore(engine, {
+ stale: true,
+ batchSize: 2_000,
+ catchUp: true,
+ quiet: true,
+ });
+
+ expect(result.embedded).toBe(2_001);
+ expect(await pageSignature('split-page')).toBe(SIGNATURE);
+ }, 120_000);
+
+ test('one failed chunk prevents the page signature stamp', async () => {
+ await seedPage('partial-failure', [
+ staleChunk(0, 'good chunk 0'),
+ staleChunk(1, 'FAIL this chunk'),
+ staleChunk(2, 'good chunk 2'),
+ ]);
+ transportBehavior = async (input) => {
+ if (input.values.some((value) => value.includes('FAIL'))) {
+ throw Object.assign(new Error('bad embedding input'), { status: 400 });
+ }
+ return fakeTransport(input);
+ };
+
+ const result = await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });
+
+ expect(result.embedded).toBe(2);
+ expect(result.failures).toBe(1);
+ expect(await pageSignature('partial-failure')).toBeNull();
+ });
+
+ test('a chunk whose embedded_text_hash does not match current text is not stamped', async () => {
+ await seedPage('hash-mismatch', [embeddedChunk(0), staleChunk(1)]);
+ await engine.executeRaw(
+ `UPDATE content_chunks
+ SET embedded_text_hash = 'not-the-current-text-hash'
+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'hash-mismatch')
+ AND chunk_index = 0`,
+ );
+ const originalInvalidate = engine.invalidateContentDriftEmbeddings.bind(engine);
+ engine.invalidateContentDriftEmbeddings = async () => 0;
+ try {
+ await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });
+ } finally {
+ engine.invalidateContentDriftEmbeddings = originalInvalidate;
+ }
+
+ expect(await pageSignature('hash-mismatch')).toBeNull();
+ });
+
+ test('a preserved chunk from another model prevents the signature stamp', async () => {
+ await seedPage('model-mismatch', [
+ embeddedChunk(0, 'openai:old-embedding-model'),
+ staleChunk(1),
+ ]);
+
+ await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });
+
+ expect(await pageSignature('model-mismatch')).toBeNull();
+ });
+
+ test('a normal single-batch page is still stamped', async () => {
+ await seedPage('single-batch', [staleChunk(0), staleChunk(1)]);
+
+ const result = await runEmbedCore(engine, { stale: true, catchUp: true, quiet: true });
+
+ expect(result.embedded).toBe(2);
+ expect(await pageSignature('single-batch')).toBe(SIGNATURE);
+ });
+});
diff --git a/test/embed-stale.serial.test.ts b/test/embed-stale.serial.test.ts
index 8383ea243a..c346bdcaea 100644
--- a/test/embed-stale.serial.test.ts
+++ b/test/embed-stale.serial.test.ts
@@ -63,6 +63,16 @@ function fakeEmbedFn(texts: string[]): Promise<Float32Array[]> {
);
}
+/** The model `upsertChunks` recorded for `slug`'s chunks (gateway-resolved in
+ * this process). A signature must name it for the provenance stamp to land. */
+async function recordedModel(slug: string): Promise<string> {
+ const rows = await engine.executeRaw<{ model: string }>(
+ `SELECT cc.model FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 LIMIT 1`,
+ [slug],
+ );
+ return rows[0]!.model;
+}
+
describe('embedStaleForSource', () => {
test('empty stale set returns done:true with zero embedded', async () => {
const result = await embedStaleForSource(engine, 'default', {
@@ -417,9 +427,12 @@ describe('signature invalidation is probe-gated (#4283)', () => {
test('working embedder → probe fires once, drifted chunks are invalidated, re-embedded, and counted', async () => {
const { EMBED_PROBE_TEXT } = await import('../src/core/embed-stale.ts');
await seedEmbeddedPage('p1', 3, 'old:model:1536');
+ // The re-embed stamps only a signature naming the model the vectors were
+ // actually written under (#4825), so the target names the recorded model.
+ const target = `${await recordedModel('p1')}:1536`;
const seen: string[] = [];
const result = await embedStaleForSource(engine, 'default', {
- embeddingSignature: 'new:model:1536',
+ embeddingSignature: target,
embedFn: async (texts) => {
seen.push(...texts);
return fakeEmbedFn(texts);
@@ -433,7 +446,7 @@ describe('signature invalidation is probe-gated (#4283)', () => {
const sig = await engine.executeRaw<{ s: string | null }>(
`SELECT embedding_signature AS s FROM pages WHERE slug = 'p1'`,
);
- expect(sig[0]!.s).toBe('new:model:1536');
+ expect(sig[0]!.s).toBe(target);
});
test('no signature drift → no probe call (no embed spend on the common path)', async () => {
@@ -592,3 +605,71 @@ describe('embedStalePages (#4216 phase-end closure)', () => {
expect(sig[0]!.s).toBe('test:model:1536');
});
});
+
+// ────────────────────────────────────────────────────────────────
+// #4825 — listStaleChunks pages by ROW with no page alignment, so a page
+// whose chunks straddle a batch boundary is never wholly in one batch. The
+// old stamp gate compared the batch subset against the whole page and left
+// such pages unstamped forever (a NULL signature is grandfathered).
+// ────────────────────────────────────────────────────────────────
+
+describe('signature stamp for a page split across a cursor batch (#4825)', () => {
+ test('page straddling the batch boundary is stamped once its last chunk lands', async () => {
+ await engine.putPage('probe', { type: 'note', title: 'probe', compiled_truth: 'probe' });
+ await engine.upsertChunks('probe', [{
+ chunk_index: 0, chunk_text: 'probe', chunk_source: 'compiled_truth',
+ token_count: 1, embedding: new Float32Array(1536).fill(0.1),
+ }]);
+ const signature = `${await recordedModel('probe')}:1536`;
+
+ await seedPageWithStaleChunks('a', 1);
+ await seedPageWithStaleChunks('b', 2);
+ // Stale rows drain as (a.0, b.0) then (b.1): 'b' is never whole in one batch.
+ const result = await embedStaleForSource(engine, 'default', {
+ embedFn: fakeEmbedFn,
+ batchSize: 2,
+ embeddingSignature: signature,
+ });
+ expect(result.embedded).toBe(3);
+
+ const sigs = await engine.executeRaw<{ slug: string; s: string | null }>(
+ `SELECT slug, embedding_signature AS s FROM pages WHERE slug IN ('a', 'b') ORDER BY slug`,
+ );
+ expect(sigs.map((r) => r.s)).toEqual([signature, signature]);
+ });
+});
+
+// ────────────────────────────────────────────────────────────────
+// wave review — the provenance stamp resolved the registry-active column on
+// EVERY page it stamped (a config round-trip per page per batch, from both
+// keyset drains). The drain now resolves it once (`resolveProvenanceStamp`)
+// and hands the stamp helper a ProvenanceStamp.
+// ────────────────────────────────────────────────────────────────
+describe('provenance stamp resolves the active embedding column once per drain', () => {
+ test('the config lookups the signature ADDS do not grow with the page count', async () => {
+ const orig = engine.executeRaw.bind(engine);
+ const calls: string[] = [];
+ engine.executeRaw = (async (sql: string, ...rest: any[]) => {
+ calls.push(sql);
+ return orig(sql, ...(rest as []));
+ }) as any;
+ try {
+ // getChunks & co. resolve the column per call whether or not a
+ // signature is set, so measure what the signature adds at a FIXED
+ // page count: pre-fix that was one lookup per stamped page.
+ const configLookups = async (pages: number, signature?: string): Promise<number> => {
+ await resetPgliteState(engine);
+ for (let i = 0; i < pages; i++) await seedPageWithStaleChunks(`p${i}`, 1);
+ calls.length = 0;
+ await embedStaleForSource(engine, 'default', { embedFn: fakeEmbedFn, embeddingSignature: signature });
+ return calls.filter((sql) => sql.includes("'search_embedding_column'")).length;
+ };
+ const sig = 'new:model:1536';
+ const oneSigCost = (await configLookups(1, sig)) - (await configLookups(1));
+ const fourSigCost = (await configLookups(4, sig)) - (await configLookups(4));
+ expect(fourSigCost).toBe(oneSigCost);
+ } finally {
+ engine.executeRaw = orig;
+ }
+ });
+});
diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.ts
index 5d452f9786..9a1c91fae3 100644
--- a/test/embed.serial.test.ts
+++ b/test/embed.serial.test.ts
@@ -57,6 +57,10 @@ __setEmbedTransportForTests(async () => ({ embeddings: [], usage: { tokens: 0 }
// Proxy-based mock engine that matches test/import-file.test.ts pattern.
function mockEngine(overrides: Partial<Record<string, any>> = {}): BrainEngine {
+ // Raw SQL the stale drain issues (the page-provenance stamp check) reads an
+ // empty result set unless a test models it — the Proxy's null default would
+ // throw on indexing and count the page as a failed embed.
+ overrides = { executeRaw: async () => [], ...overrides };
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
calls.push({ method, args });
diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.ts
index 5e6555d94f..dc236ccdb4 100644
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@ -40,6 +40,7 @@ import {
} from '../src/core/embedding-migration.ts';
import { invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
import { estimateCostFromChars } from '../src/core/embedding-pricing.ts';
+import { AUDIT_ROW_SOURCES } from '../src/core/facts/audit-sources.ts';
import { operations } from '../src/core/operations.ts';
let engine: PGLiteEngine;
@@ -570,6 +571,22 @@ describe('#4305 false target stamps + #4306 embed_skip-safe invalidation', () =>
});
});
+describe('#4875 facts_pending excludes audit checkpoint rows', () => {
+ test('terminal / non-extractable / legacy checkpoints are not a pending embedding backlog', async () => {
+ const seed = (source: string, extra = '') => engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, confidence${extra ? ', ' + extra : ''})
+ VALUES ('default', 'e', $1, 'fact', 'private', 'medium', $1, 1.0${extra ? ', now()' : ''})`,
+ [source],
+ );
+ await seed('test'); // the one real pending fact
+ for (const s of AUDIT_ROW_SOURCES) await seed(s); // checkpoints, never embedded
+ await seed('expired-real', 'expired_at'); // expired rows already excluded
+
+ const status = await readMigrationStatus(engine);
+ expect(status.facts_pending).toBe(1);
+ });
+});
+
describe('migrate_embeddings op contract', () => {
const op = operations.find(o => o.name === 'migrate_embeddings')!;
diff --git a/test/engine-keyset-microseconds.test.ts b/test/engine-keyset-microseconds.test.ts
new file mode 100644
index 0000000000..0a77492d55
--- /dev/null
+++ b/test/engine-keyset-microseconds.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+/**
+ * Keyset pagination cursor precision (found 2026-08-28 on the email-facts run).
+ *
+ * `listPages` returns `updated_at` as a JS Date (millisecond precision) while
+ * the column stores microseconds. A caller feeding that Date back as the
+ * `updatedAfterKeyset` cursor hits `p.updated_at > cursor` for every row in
+ * the cursor's millisecond (the last row of each batch re-selected; a batch
+ * of same-millisecond rows never advances). `listPages` now also projects
+ * `updated_at_iso` at column precision; a caller that resumes from it walks
+ * the `(updated_at, slug)` order exactly, index-friendly, whatever the slug
+ * order inside a millisecond.
+ */
+describe('listPages keyset walk with microsecond timestamps', () => {
+ let engine: PGLiteEngine;
+ const N = 25;
+ // Six rows in ONE millisecond whose slug order is the REVERSE of their
+ // microsecond order: rev-05 has the earliest microsecond, rev-00 the latest.
+ const REV = 6;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 0; i < N; i++) {
+ const slug = `ks/page-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} body`, frontmatter: {} });
+ // All 25 rows inside ONE millisecond, one microsecond apart.
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = ('2026-08-10T12:00:00.000100Z'::timestamptz + ($1::int * interval '1 microsecond')) WHERE slug = $2 AND source_id = 'default'`,
+ [i, slug],
+ );
+ }
+ for (let i = 0; i < REV; i++) {
+ const slug = `ks/rev-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} body`, frontmatter: {} });
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = ('2026-08-10T12:00:00.002100Z'::timestamptz + ($1::int * interval '1 microsecond')) WHERE slug = $2 AND source_id = 'default'`,
+ [REV - 1 - i, slug],
+ );
+ }
+ await engine.putPage('ks/later', { type: 'note', title: 'later', compiled_truth: 'later', frontmatter: {} });
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = '2026-08-10T12:00:00.001000Z'::timestamptz WHERE slug = 'ks/later' AND source_id = 'default'`,
+ );
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ async function walk(limit: number): Promise<{ seen: string[]; batches: number }> {
+ const seen: string[] = [];
+ let keyset: { updatedAt: string; slug: string } | undefined;
+ let batches = 0;
+ while (batches < 40) {
+ batches++;
+ const batch = await engine.listPages({
+ type: 'note' as never,
+ sourceId: 'default',
+ limit,
+ sort: 'updated_asc',
+ ...(keyset ? { updatedAfterKeyset: keyset } : {}),
+ });
+ if (batch.length === 0) break;
+ for (const p of batch) seen.push(p.slug);
+ const last = batch[batch.length - 1];
+ expect(last.updated_at_iso).toMatch(/\.\d{6}Z$/);
+ keyset = { updatedAt: last.updated_at_iso!, slug: last.slug };
+ if (batch.length < limit) break;
+ }
+ return { seen, batches };
+ }
+
+ const TOTAL = N + 1 + REV;
+
+ test('yields every row exactly once and terminates', async () => {
+ const { seen, batches } = await walk(10);
+ expect(seen).toHaveLength(TOTAL);
+ expect(new Set(seen).size).toBe(TOTAL);
+ expect(batches).toBeLessThanOrEqual(5);
+ // Within the first millisecond, rows come back ordered by slug.
+ const firstBucket = seen.slice(0, N);
+ expect(firstBucket).toEqual([...firstBucket].sort());
+ });
+
+ test('rows in a later millisecond come after the whole bucket', async () => {
+ const { seen } = await walk(10);
+ expect(seen[N]).toBe('ks/later');
+ });
+
+ test('a batch boundary inside a bucket whose slug order runs against microsecond order skips nothing', async () => {
+ // limit 4 puts boundaries inside the 6-row reversed cluster.
+ const { seen } = await walk(4);
+ expect(seen).toHaveLength(TOTAL);
+ expect(new Set(seen).size).toBe(TOTAL);
+ const rev = seen.filter((s) => s.startsWith('ks/rev-'));
+ // The cluster comes back in microsecond order (the reverse of slug order).
+ expect(rev).toEqual([...rev].sort().reverse());
+ expect(rev).toHaveLength(REV);
+ });
+
+ test('a millisecond-rounded cursor is the documented failure: it re-selects the bucket', async () => {
+ const first = await engine.listPages({ type: 'note' as never, sourceId: 'default', limit: 10, sort: 'updated_asc' });
+ const last = first[first.length - 1];
+ const again = await engine.listPages({
+ type: 'note' as never, sourceId: 'default', limit: 10, sort: 'updated_asc',
+ updatedAfterKeyset: { updatedAt: new Date(last.updated_at).toISOString(), slug: last.slug },
+ });
+ // Rows already returned come back: exactly what resuming from updated_at_iso avoids.
+ expect(again.some((p) => first.some((q) => q.slug === p.slug))).toBe(true);
+ });
+});
diff --git a/test/entity-resolve.test.ts b/test/entity-resolve.test.ts
index a311588ecc..6a2806d1fa 100644
--- a/test/entity-resolve.test.ts
+++ b/test/entity-resolve.test.ts
@@ -184,6 +184,32 @@ describe('slugify', () => {
it('strips accents', () => {
expect(slugify('José García')).toBe('jose-garcia');
});
+
+ // Stroke/bar/ligature letters carry no Unicode decomposition, so the NFKD
+ // pass cannot fold them and the non-alphanumeric sweep used to delete them:
+ // "Đăng Example" slugged to "ang-example", filing facts under an entity slug
+ // that no lookup by name could ever resolve.
+ it('folds stroke letters that NFKD cannot decompose', () => {
+ expect(slugify('Đăng Example')).toBe('dang-example');
+ expect(slugify('Bảo Đào Example')).toBe('bao-dao-example');
+ });
+
+ it('folds the same class across other Latin scripts', () => {
+ expect(slugify('Łukasz Example')).toBe('lukasz-example');
+ expect(slugify('Søren Example')).toBe('soren-example');
+ expect(slugify('Weiß Example')).toBe('weiss-example');
+ expect(slugify('Þór Example')).toBe('thor-example');
+ });
+
+ it('folds a stroke letter that also carries a combining accent', () => {
+ // "ǿ" decomposes to "ø" + U+0301: the mark strips, then the table folds.
+ expect(slugify('Ǿrn Example')).toBe('orn-example');
+ });
+
+ it('keeps a name that is only stroke letters reachable', () => {
+ // Pre-fix this collapsed to the empty string.
+ expect(slugify('Đ')).toBe('d');
+ });
});
// ─────────────────────────────────────────────────────────────────────
diff --git a/test/extract-atoms-array-anchor-scan.test.ts b/test/extract-atoms-array-anchor-scan.test.ts
new file mode 100644
index 0000000000..e71bf6f2a3
--- /dev/null
+++ b/test/extract-atoms-array-anchor-scan.test.ts
@@ -0,0 +1,186 @@
+/**
+ * Atoms-array ANCHOR SCAN (`parseAtomsOutcomeInner`).
+ *
+ * The extractor used to commit to `cleaned.indexOf('[')` — the FIRST left
+ * bracket anywhere in the response. Any bracket in a preamble hijacked that
+ * anchor, so a response carrying a perfectly good atoms array was reported as
+ * `unparseable JSON array` and the page counted a deterministic failure.
+ *
+ * This is not a hypothetical: a brain whose house style mandates inline
+ * `[Source: …]` citations and `[[wikilink]]` backlinks, and whose transcripts
+ * carry `[user]` / `[assistant]` / `[tool: …]` role markers, hands the model
+ * bracketed prose to echo while it narrates its answer.
+ *
+ * THE HAZARD the scan must avoid: `atomsFromParsedArray` skips every element
+ * failing the shape gate, so a parseable-but-wrong array (say an array of
+ * strings lifted out of prose) yields `ok: true, atoms: []`. A zero-yield
+ * result is what TOMBSTONES a page (#2144), so a shape-blind scan would
+ * permanently retire pages that still had real content — worse than the bug.
+ * Acceptance therefore requires >= 1 atom-shaped element, not mere parseability.
+ *
+ * NOTE: assertions go through the PUBLIC `parseAtomsOutcome` entry point, which
+ * exists pre-fix, so a reverted-source run fails on BEHAVIOUR rather than dying
+ * with a module-load SyntaxError (the vacuous failure class in CONTRIBUTING.md).
+ */
+import { describe, expect, test } from 'bun:test';
+import { parseAtomsOutcome } from '../src/core/cycle/extract-atoms.ts';
+
+/** A minimally valid atom: title + atom_type (in ATOM_TYPES) + body. */
+const ATOM = {
+ title: 'Brackets in prose hijack the parse anchor',
+ atom_type: 'insight',
+ body: 'The extractor anchored on the first bracket, not the first array.',
+};
+const ATOM_ARRAY = JSON.stringify([ATOM]);
+
+function atomsOf(raw: string) {
+ const outcome = parseAtomsOutcome(raw);
+ if (!outcome.ok) throw new Error(`expected ok, got reason: ${outcome.reason}`);
+ return outcome.atoms;
+}
+
+describe('anchor scan — bracketed preamble no longer hijacks the parse', () => {
+ test('recovers the array after a preamble carrying a [Source: …] citation', () => {
+ const raw =
+ 'Looking at the page, the claim is supported by ' +
+ '[Source: alice-example, agent session, 2026-09-03], so here are the atoms:\n' +
+ ATOM_ARRAY;
+ expect(atomsOf(raw)).toHaveLength(1);
+ expect(atomsOf(raw)[0]!.title).toBe(ATOM.title);
+ });
+
+ test('recovers the array after a preamble naming a [[wikilink]]', () => {
+ const raw = 'The page backlinks [[people/alice-example]] and [[companies/acme-example]].\n' + ATOM_ARRAY;
+ expect(atomsOf(raw)).toHaveLength(1);
+ });
+
+ test('recovers the array after a transcript [user] role marker in the preamble', () => {
+ const raw = 'The [user] turn sets up the problem and [assistant] answers it.\n' + ATOM_ARRAY;
+ expect(atomsOf(raw)).toHaveLength(1);
+ });
+
+ test('preamble recovery: a parseable-but-WRONG array ahead of the real one is skipped', () => {
+ // `["a","b"]` parses cleanly but yields no atom, so the scan moves on and
+ // recovers the real payload below. NOTE: this passes with OR without the
+ // shape gate (the first-bracket offset fails to parse either way), so it
+ // pins recovery, not the gate — the gate is pinned directly further down.
+ const raw = 'Candidate labels were ["a","b"] before I settled on:\n' + ATOM_ARRAY;
+ const atoms = atomsOf(raw);
+ expect(atoms).toHaveLength(1);
+ expect(atoms[0]!.title).toBe(ATOM.title);
+ });
+
+ test('preamble recovery: an array of atom-shaped-but-empty objects ahead of the real one is skipped', () => {
+ // Objects, but every one fails the shape gate (no title/atom_type/body).
+ const raw = 'Draft skeleton: [{"note":"tbd"},{"note":"tbd"}] — final answer:\n' + ATOM_ARRAY;
+ expect(atomsOf(raw)).toHaveLength(1);
+ });
+});
+
+describe('anchor scan — the shape gate is what accepts a candidate (atoms.length > 0)', () => {
+ // THE HAZARD, pinned directly. In each case a later offset holds an array
+ // that PARSES but yields zero atoms, and no offset holds a real one. A scan
+ // that accepted mere parseability would return `ok: true, atoms: []` — the
+ // zero-yield that tombstones a page — instead of the FIRST offset's failure.
+ test('a parseable array of strings after bracketed prose is NOT accepted', () => {
+ const outcome = parseAtomsOutcome('see [Source: X] then candidate labels ["a","b"]');
+ expect(outcome).toEqual({ ok: false, reason: 'unparseable JSON array' });
+ });
+
+ test('a parseable array of shape-failing objects after bracketed prose is NOT accepted', () => {
+ const outcome = parseAtomsOutcome('see [Source: X] then [{"note":"tbd"}]');
+ expect(outcome).toEqual({ ok: false, reason: 'unparseable JSON array' });
+ });
+});
+
+describe('anchor scan — MAX_ARRAY_ANCHOR_CANDIDATES bounds the scan at 64 offsets', () => {
+ // Each `[tN]` token is one failing `[` offset; the atoms array itself holds
+ // exactly one `[`, so 63 tokens put it at the 64th (last tried) offset and
+ // 64 tokens push it past the cap.
+ const preamble = (n: number) => Array.from({ length: n }, (_, i) => `[t${i}]`).join(' ');
+
+ test('63 bracketed preamble tokens: the array at the 64th offset is still recovered', () => {
+ expect(atomsOf(preamble(63) + ' ' + ATOM_ARRAY)).toHaveLength(1);
+ });
+
+ test("64 bracketed preamble tokens: cap reached, the FIRST offset's failure is returned", () => {
+ const outcome = parseAtomsOutcome(preamble(64) + ' ' + ATOM_ARRAY);
+ expect(outcome).toEqual({ ok: false, reason: 'unparseable JSON array' });
+ });
+});
+
+describe('anchor scan — preserved behaviour', () => {
+ test('an honest empty array is still a zero-yield SUCCESS, not malformed output', () => {
+ // #4148 keeps "malformed output" and "the model found nothing" distinct:
+ // only the latter is a legitimate tombstone. The scan must not blur that
+ // by reclassifying `[]` as a parse failure just because it yields no atom.
+ const outcome = parseAtomsOutcome('[]');
+ expect(outcome.ok).toBe(true);
+ if (outcome.ok) expect(outcome.atoms).toEqual([]);
+ });
+
+ test('an empty array after prose is still a zero-yield success', () => {
+ const outcome = parseAtomsOutcome('Nothing worth extracting here.\n[]');
+ expect(outcome.ok).toBe(true);
+ if (outcome.ok) expect(outcome.atoms).toEqual([]);
+ });
+
+ test('a clean array with no preamble is unchanged', () => {
+ expect(atomsOf(ATOM_ARRAY)).toHaveLength(1);
+ });
+
+ test('a fenced array is unchanged', () => {
+ expect(atomsOf('```json\n' + ATOM_ARRAY + '\n```')).toHaveLength(1);
+ });
+
+ test('trailing prose after a valid array is still recovered', () => {
+ expect(atomsOf(ATOM_ARRAY + '\n\nThose are the atoms I found.')).toHaveLength(1);
+ });
+
+ test('an empty array after BRACKETED prose is a zero-yield success (#4948 rule holds at any offset)', () => {
+ // The #4948 prompt tells the model to answer exactly `[]` when nothing is
+ // extractable. A model that first echoes a bracketed citation and then
+ // obeys used to lose the `[]` to the shape gate: the first offset failed
+ // to parse, no later offset yielded an atom, so the FIRST offset's failure
+ // was returned — three strikes and the transcript was tombstoned + the
+ // phase halted for content that was honestly empty.
+ expect(parseAtomsOutcome('[Source: x] nothing here.\n[]')).toEqual({ ok: true, atoms: [] });
+ expect(parseAtomsOutcome('Checked [[people/alice-example]] — no atoms.\n\n[]')).toEqual({ ok: true, atoms: [] });
+ });
+
+ test('a NON-empty array with no atom-shaped element is a counted failure, not a zero-yield success', () => {
+ // Pre-fix this returned `ok: true, atoms: []` — the zero-yield shape that
+ // tombstones the item FOREVER on the first try — for output that was
+ // simply malformed (wrong keys). Malformed output rides the failure streak
+ // (retries, then the bounded MAX_DETERMINISTIC_FAILURES tombstone), like
+ // every other parse failure; only a literal `[]` is an honest zero-yield.
+ expect(parseAtomsOutcome('[{"claim":"Water is wet","kind":"fact"}]')).toEqual({
+ ok: false,
+ reason: 'array had no atom-shaped elements',
+ });
+ expect(parseAtomsOutcome('["a","b"]')).toEqual({ ok: false, reason: 'array had no atom-shaped elements' });
+ });
+});
+
+describe('anchor scan — failure reasons still describe the FIRST bracket', () => {
+ test('no bracket at all', () => {
+ const outcome = parseAtomsOutcome('I could not extract anything from this content.');
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) expect(outcome.reason).toBe('no JSON array in response');
+ });
+
+ test('an opened-but-never-closed array reports unterminated, not unparseable', () => {
+ const outcome = parseAtomsOutcome('here goes [{"title":"a"');
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) expect(outcome.reason).toBe('unterminated JSON array');
+ });
+
+ test('bracketed prose with no recoverable array anywhere still reports unparseable', () => {
+ // The scan exhausts every candidate and falls back to the FIRST offset's
+ // reason — never a later offset's, which would silently change the string
+ // the drain surfaces as `last_error`.
+ const outcome = parseAtomsOutcome('see [Source: X] and [[people/alice-example]] for details]');
+ expect(outcome.ok).toBe(false);
+ if (!outcome.ok) expect(outcome.reason).toBe('unparseable JSON array');
+ });
+});
diff --git a/test/extract-atoms-drain-handler.test.ts b/test/extract-atoms-drain-handler.test.ts
index ac10a9dbaa..d00330a298 100644
--- a/test/extract-atoms-drain-handler.test.ts
+++ b/test/extract-atoms-drain-handler.test.ts
@@ -7,6 +7,10 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MinionQueue } from '../src/core/minions/queue.ts';
import { MinionWorker } from '../src/core/minions/worker.ts';
import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
+import {
+ formatDrainProviderFailure,
+ type ExtractAtomsDrainResult,
+} from '../src/core/cycle/extract-atoms-drain.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;
@@ -49,4 +53,23 @@ describe('extract-atoms-drain handler', () => {
expect(job.id).toBeGreaterThan(0);
expect(job.name).toBe('extract-atoms-drain');
});
+
+ // #3813: the provider_failure throw is the job's error_text once it
+ // dead-letters. It carried only batches/remaining, so a missing provider key
+ // was invisible from every supported surface even though the drain result
+ // has carried a sanitized representative `last_error`.
+ test('provider_failure error text carries the drain\'s last_error', () => {
+ const result = {
+ status: 'provider_failure',
+ batches: 1,
+ remaining: 151,
+ last_error: 'concepts/alice-example: Anthropic chat requires ANTHROPIC_API_KEY.',
+ } as ExtractAtomsDrainResult;
+ const msg = formatDrainProviderFailure(result);
+ expect(msg).toContain('batches=1');
+ expect(msg).toContain('remaining=151');
+ expect(msg).toContain('ANTHROPIC_API_KEY');
+ // A clean-run shape (no representative error) keeps the original message.
+ expect(formatDrainProviderFailure({ ...result, last_error: null })).not.toContain('last error');
+ });
});
diff --git a/test/extract-atoms-embed-cost-gate.test.ts b/test/extract-atoms-embed-cost-gate.test.ts
new file mode 100644
index 0000000000..411a475804
--- /dev/null
+++ b/test/extract-atoms-embed-cost-gate.test.ts
@@ -0,0 +1,211 @@
+/**
+ * Regression: extract_atoms gated its cost cap on the CHAT model alone, but
+ * the atom write site (importFromContent) also embeds inside the same
+ * withBudgetTracker scope. A $0 local chat model (ollama / llama-server) kept
+ * the cap on, and an unpriced embedding route — `litellm:*`, deliberately not
+ * assumed free because a proxy can front a paid provider — made
+ * BudgetTracker.reserve() throw BudgetExhausted(no_pricing) on the FIRST atom
+ * import. `budgetExhausted` latched, every remaining item was skipped, and the
+ * phase reported 0 atoms / `budget_exhausted: true` / $0 spent on every run.
+ *
+ * The phase also never loaded `pricing.overrides` (#4312), so the operator
+ * fix its own error message advertised did nothing here.
+ *
+ * Pure-helper cases first; the final describe is a PGLite round-trip that
+ * pins the actual defect (an unpriced embed model no longer zeroes the run).
+ * No model calls anywhere — chat is stubbed via the `_chat` seam and the embed
+ * transport via __setEmbedTransportForTests.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { resolveExtractAtomsCostGate } from '../src/core/cycle/extract-atoms-cost-gate.ts';
+import { parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';
+import {
+ configureGateway,
+ resetGateway,
+ isAvailable,
+ __setEmbedTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+
+const FREE_CHAT = 'llama-server:local-27b';
+const UNPRICED_EMBED = 'litellm:nvidia/some-local-embedder';
+
+describe('resolveExtractAtomsCostGate', () => {
+ test('priced chat + priced embed → cap enforced', () => {
+ expect(resolveExtractAtomsCostGate('claude-haiku-4-5-20251001', 'openai:text-embedding-3-large'))
+ .toEqual({ enforceCap: true });
+ });
+
+ test('free local chat + no embedding configured → cap enforced (nothing unpriced bills)', () => {
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, null)).toEqual({ enforceCap: true });
+ });
+
+ test('free local chat + free local embed → cap enforced at $0', () => {
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, 'ollama:nomic-embed-text')).toEqual({ enforceCap: true });
+ });
+
+ test('unpriced chat model disables the cap and names the chat model', () => {
+ expect(resolveExtractAtomsCostGate('groq:llama-3.3-70b', 'openai:text-embedding-3-large')).toEqual({
+ enforceCap: false,
+ unpricedModel: 'groq:llama-3.3-70b',
+ unpricedKind: 'chat',
+ });
+ });
+
+ test('free local chat + UNPRICED embed disables the cap and names the embed model (the defect)', () => {
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED)).toEqual({
+ enforceCap: false,
+ unpricedModel: UNPRICED_EMBED,
+ unpricedKind: 'embed',
+ });
+ });
+
+ test('an operator pricing override for the embed model restores the cap', () => {
+ const overrides = parsePricingOverrides(JSON.stringify({ [UNPRICED_EMBED]: 0 }));
+ expect(overrides).toBeDefined();
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, overrides)).toEqual({ enforceCap: true });
+ });
+
+ test('override lookup is case-insensitive, matching BudgetTracker.reserve()', () => {
+ const overrides = parsePricingOverrides(JSON.stringify({ [UNPRICED_EMBED.toUpperCase()]: 0 }));
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, overrides)).toEqual({ enforceCap: true });
+ });
+
+ // An operator who SET `cycle.extract_atoms.budget_usd` asked for a ceiling.
+ // Dropping the cap because the embed route is unpriced silently turns that
+ // ceiling off (Codex P1); the cap stays and the unpriced embed bills at $0.
+ test('an explicit operator budget keeps the cap on over an unpriced embed route, priced at $0', () => {
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, undefined, { explicitBudget: true })).toEqual({
+ enforceCap: true,
+ zeroPricedEmbedModel: UNPRICED_EMBED,
+ pricingOverrides: { [UNPRICED_EMBED.toLowerCase()]: { input: 0, output: 0 } },
+ });
+ });
+
+ test('the $0 embed row merges into existing operator overrides without clobbering them', () => {
+ const overrides = parsePricingOverrides(JSON.stringify({ 'litellm:gpt-4o': { input: 2.5, output: 10 } }))!;
+ const gate = resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, overrides, { explicitBudget: true });
+ expect(gate.enforceCap).toBe(true);
+ expect(gate.pricingOverrides).toEqual({
+ 'litellm:gpt-4o': { input: 2.5, output: 10 },
+ [UNPRICED_EMBED.toLowerCase()]: { input: 0, output: 0 },
+ });
+ });
+
+ test('an explicit budget never zero-prices an unpriced CHAT model — the cap still drops', () => {
+ // The chat model is the billable call the cap exists for; assuming $0 for
+ // it would enforce a fiction. Only the embed route gets the $0 treatment.
+ expect(resolveExtractAtomsCostGate('groq:llama-3.3-70b', UNPRICED_EMBED, undefined, { explicitBudget: true })).toEqual({
+ enforceCap: false,
+ unpricedModel: 'groq:llama-3.3-70b',
+ unpricedKind: 'chat',
+ });
+ });
+
+ test('without an explicit budget the unpriced embed still drops the (default) cap', () => {
+ expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, undefined, { explicitBudget: false })).toEqual({
+ enforceCap: false,
+ unpricedModel: UNPRICED_EMBED,
+ unpricedKind: 'embed',
+ });
+ });
+});
+
+describe('extract_atoms with a $0 chat model and an unpriced embedding model (PGLite round-trip)', () => {
+ let engine: PGLiteEngine;
+ const DIMS = 1536; // matches the preload's schema width
+
+ beforeAll(async () => {
+ // Hermetic: keyless env, an embedding model with NO pricing entry, and a
+ // stubbed embed transport so isAvailable('embedding') is true and the atom
+ // import really embeds — under the phase's BudgetTracker — without a network.
+ configureGateway({
+ embedding_model: UNPRICED_EMBED,
+ embedding_dimensions: DIMS,
+ env: {},
+ });
+ // Same shape as the ai-sdk embedMany result the gateway consumes (see
+ // test/asymmetric-encoding-contract.test.ts).
+ __setEmbedTransportForTests((async (args: any) => ({
+ embeddings: (args.values as string[]).map(() => Array.from({ length: DIMS }, () => 0.01)),
+ usage: { tokens: 10 * (args.values as string[]).length },
+ })) as any);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('models.dream.extract_atoms', FREE_CHAT);
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ });
+ afterEach(async () => {
+ await engine.unsetConfig('pricing.overrides');
+ await engine.unsetConfig('cycle.extract_atoms.budget_usd');
+ });
+
+ const chat = async (_o: ChatOpts): Promise<ChatResult> => ({
+ text: `[{"title":"Embedded atom","atom_type":"insight","body":"Local inference costs electricity, not tokens."}]`,
+ blocks: [{ type: 'text', text: '' }],
+ stopReason: 'end',
+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: FREE_CHAT,
+ providerId: 'llama-server',
+ });
+
+ test('the unpriced embed no longer zeroes the run: 1 atom, budget not exhausted', async () => {
+ expect(isAvailable('embedding')).toBe(true);
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: '/fake/meeting-a.txt', content: 'transcript content a', contentHash: 'a1b2c3d4e5f60718' }],
+ _pages: [],
+ _chat: chat,
+ });
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+ expect(result.details?.budget_exhausted).toBe(false);
+ expect(result.details?.transcripts_skipped_budget).toBe(0);
+ }, 60000);
+
+ test('an explicit cycle.extract_atoms.budget_usd keeps the cap enforced over the unpriced embed (Codex P1)', async () => {
+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.05');
+ const stderr: string[] = [];
+ const savedError = console.error;
+ console.error = (...a: unknown[]) => { stderr.push(a.map(String).join(' ')); };
+ let result;
+ try {
+ result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: '/fake/meeting-c.txt', content: 'transcript content c', contentHash: 'c1b2c3d4e5f60718' }],
+ _pages: [],
+ _chat: chat,
+ });
+ } finally {
+ console.error = savedError;
+ }
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+ expect(result.details?.budget_exhausted).toBe(false);
+ expect(result.details?.budget_usd).toBe(0.05);
+ const joined = stderr.join('\n');
+ // The cap was NOT dropped — the operator asked for one.
+ expect(joined).not.toContain('running without a cost gate');
+ // ...and the run says so, naming the embed model it bills at $0.
+ expect(joined).toContain(UNPRICED_EMBED);
+ expect(joined).toContain('$0');
+ }, 60000);
+
+ test('with a $0 pricing override for the embed model the cap stays on and the run still extracts', async () => {
+ await engine.setConfig('pricing.overrides', JSON.stringify({ [UNPRICED_EMBED]: 0 }));
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: '/fake/meeting-b.txt', content: 'transcript content b', contentHash: 'b1b2c3d4e5f60718' }],
+ _pages: [],
+ _chat: chat,
+ });
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+ expect(result.details?.budget_exhausted).toBe(false);
+ }, 60000);
+});
diff --git a/test/extract-atoms-empty-array-rule.test.ts b/test/extract-atoms-empty-array-rule.test.ts
new file mode 100644
index 0000000000..c5f3ffaa0e
--- /dev/null
+++ b/test/extract-atoms-empty-array-rule.test.ts
@@ -0,0 +1,81 @@
+/**
+ * extract_atoms prompt — explicit zero-yield rule.
+ *
+ * Metadata-only pages (connector rows, status dumps, boilerplate) gave the
+ * model nothing to extract, and the prompt never said what to do then. Local
+ * and smaller models responded by inventing 1-3 atoms or by explaining in
+ * prose; prose parses as `no JSON array in response`, which is a counted
+ * deterministic failure, so the page burned every retry and was tombstoned
+ * for no reason. The prompt now tells the model to output exactly `[]` for a
+ * content-free transcript, which the parser already treats as an honest
+ * zero-yield (ok: true, atoms: []).
+ *
+ * Pins: the system prompt sent to the model carries the rule. Asserted on
+ * the prompt actually sent through the chat seam, not on source text.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms, parseAtomsOutcome } from '../src/core/cycle/extract-atoms.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+function okChatResult(text: string): ChatResult {
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+ } as ChatResult;
+}
+
+describe('extract_atoms prompt — content-free transcript rule', () => {
+ test('the system prompt tells the model to output exactly [] when nothing is extractable', async () => {
+ let capturedSystem = '';
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'documents/connector-row', content: 'status: open\nowner: alice-example\n', contentHash: 'b'.repeat(16) }],
+ _chat: async (opts: ChatOpts) => {
+ capturedSystem = String(opts.system ?? '');
+ return okChatResult('[]');
+ },
+ });
+ expect(capturedSystem.length).toBeGreaterThan(0); // the seam was hit
+ // The rule names the zero-yield shape AND forbids the two failure modes
+ // (invented atoms, prose).
+ expect(capturedSystem).toMatch(/no extractable idea[\s\S]*output exactly \[\]/);
+ expect(capturedSystem).toMatch(/never invent an atom/);
+ expect(capturedSystem).toMatch(/never explain in prose/);
+ });
+
+ test('[] is an honest zero-yield, not a parse failure (the path the rule steers into)', () => {
+ expect(parseAtomsOutcome('[]')).toEqual({ ok: true, atoms: [] });
+ // The rule must survive a bracketed preamble too: a model that echoes a
+ // `[Source: …]` citation before obeying still yields an honest `[]`.
+ expect(parseAtomsOutcome('[Source: x] nothing here.\n[]')).toEqual({ ok: true, atoms: [] });
+ // Positive control: the prose the rule prevents IS a failure.
+ expect(parseAtomsOutcome('This page has no extractable ideas.')).toEqual({
+ ok: false,
+ reason: 'no JSON array in response',
+ });
+ });
+});
diff --git a/test/extract-atoms-provenance-links.test.ts b/test/extract-atoms-provenance-links.test.ts
index 8a9a2dbe81..c11f41b913 100644
--- a/test/extract-atoms-provenance-links.test.ts
+++ b/test/extract-atoms-provenance-links.test.ts
@@ -8,8 +8,10 @@
* (link_source='atom-provenance', both endpoints in the phase's source) and
* flushes them BEFORE the completion-receipt flip (#4733: a failed provenance
* write leaves the item discoverable for a normal retry instead of stranding
- * a completed page with no edges). Transcript items are skipped — a
- * transcript is a file, not a page, so there is no from-endpoint.
+ * a completed page with no edges). Transcript items resolve their from-endpoint
+ * through the conversation page the transcript was imported into (matched on
+ * the normalized session id); a transcript with no imported page still gets no
+ * edge, because there is genuinely nothing to link to.
*
* Also pins the #4733 atom-identity fix: page-derived atom slugs fold the
* source-page slug into the identity hash so two same-date source pages
@@ -84,7 +86,7 @@ describe('atom provenance backlinks (#3961)', () => {
expect(links.filter(l => l.link_source === 'atom-provenance')).toHaveLength(1);
});
- test('transcript items create NO provenance edges (files are not pages)', async () => {
+ test('an UNIMPORTED transcript creates no provenance edges (no page to link from)', async () => {
const before = await engine.executeRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM links WHERE link_source = 'atom-provenance'`,
);
@@ -99,6 +101,83 @@ describe('atom provenance backlinks (#3961)', () => {
);
expect(after[0]!.n).toBe(before[0]!.n);
});
+
+ test('an IMPORTED transcript links its conversation page → atom', async () => {
+ // The conversation page the transcript was rendered into. The corpus file
+ // on disk names the same session with '-' separators; the page stamps it
+ // with '_' — the resolver normalizes both.
+ await engine.putPage('conversations/sessions/2026-07-20-hermes-e91dbe', {
+ type: 'conversation', title: 'Session', compiled_truth: 'turns', timeline: '',
+ frontmatter: { transcript_import: { harness: 'hermes', session_id: '20260720_071844_e91dbe', part: 1, of: 1 } },
+ });
+
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{
+ filePath: '/corpus/2026-07-20-071844-e91dbe.md',
+ content: 'a session worth distilling',
+ contentHash: 'bbbb111122223333',
+ }],
+ _pages: [],
+ _chat: stubChat('Session atom lands home'),
+ });
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+
+ const links = await engine.getLinks('conversations/sessions/2026-07-20-hermes-e91dbe');
+ const provenance = links.filter(l => l.link_source === 'atom-provenance');
+ expect(provenance).toHaveLength(1);
+ expect(provenance[0]!.to_slug).toContain('session-atom-lands-home');
+ });
+
+ test('a split session links EVERY part page to the atom', async () => {
+ for (const part of [1, 2]) {
+ await engine.putPage(`conversations/sessions/2026-07-22-hermes-split-p${part}`, {
+ type: 'conversation', title: `Split (part ${part} of 2)`, compiled_truth: 'turns', timeline: '',
+ frontmatter: { transcript_import: { harness: 'hermes', session_id: '20260722_090000_split', part, of: 2 } },
+ });
+ }
+
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{
+ filePath: '/corpus/2026-07-22-090000-split.md',
+ content: 'a long session split across two pages',
+ contentHash: 'cccc111122223333',
+ }],
+ _pages: [],
+ _chat: stubChat('Split session atom'),
+ });
+ expect(result.status).toBe('ok');
+
+ for (const part of [1, 2]) {
+ const links = await engine.getLinks(`conversations/sessions/2026-07-22-hermes-split-p${part}`);
+ expect(links.filter(l => l.link_source === 'atom-provenance')).toHaveLength(1);
+ }
+ });
+ test('a hook-captured <session_id>.txt corpus file links its conversation page → atom', async () => {
+ // gbrain's own Stop-hook capture writes the session corpus as
+ // `<session_id>.txt` (hook.ts) and the claude-code adapter stamps that
+ // same UUID into transcript_import.session_id — the stock capture + ingest
+ // flow, so the .txt stem must resolve like the .md/.jsonl ones.
+ await engine.putPage('conversations/sessions/2026-08-01-claude-code-0f1e2d3c', {
+ type: 'conversation', title: 'Hook session', compiled_truth: 'turns', timeline: '',
+ frontmatter: { transcript_import: { harness: 'claude-code', session_id: '0f1e2d3c-aaaa-bbbb-cccc-0123456789ab', part: 1, of: 1 } },
+ });
+
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{
+ filePath: '/corpus/0f1e2d3c-aaaa-bbbb-cccc-0123456789ab.txt',
+ content: 'a hook-captured session worth distilling',
+ contentHash: 'dddd111122223333',
+ }],
+ _pages: [],
+ _chat: stubChat('Hook session atom'),
+ });
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+
+ const links = await engine.getLinks('conversations/sessions/2026-08-01-claude-code-0f1e2d3c');
+ expect(links.filter(l => l.link_source === 'atom-provenance')).toHaveLength(1);
+ });
});
describe('atom identity folds the source locator (#4733)', () => {
diff --git a/test/extract-atoms-transcript-failure-classes.test.ts b/test/extract-atoms-transcript-failure-classes.test.ts
new file mode 100644
index 0000000000..116b486c47
--- /dev/null
+++ b/test/extract-atoms-transcript-failure-classes.test.ts
@@ -0,0 +1,275 @@
+/**
+ * v146 — extract_atoms failure classes for TRANSCRIPT items.
+ *
+ * The transcript half of gbrain#4148. Pre-fix `recordPageFailureCount` opened
+ * with `if (item.kind !== 'page' ...) return null`, and both tombstone stamps
+ * were gated `item.kind === 'page'`, so transcripts had:
+ * - no durable failure count,
+ * - no bounded tombstone for deterministically-malformed output,
+ * - no zero-yield marker at all.
+ * Transcript eligibility is gated ONLY by `atomsExistingForHashes` ("does an
+ * atom row exist for this content hash"), and a failed or empty extraction
+ * leaves no atom row — so such a transcript re-entered the work pool and
+ * re-spent LLM budget on EVERY cycle, forever. TODOS.md P2(b).
+ *
+ * These mirror test/extract-atoms-failure-classes.test.ts, which is the house
+ * convention for this machinery, with the page assertions restated against the
+ * `extract_atoms_transcript_state` table instead of page frontmatter.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ runPhaseExtractAtoms,
+ MAX_DETERMINISTIC_FAILURES,
+} from '../src/core/cycle/extract-atoms.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+function okChatResult(text: string): ChatResult {
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+ } as ChatResult;
+}
+
+const HASH_A = 'a'.repeat(16);
+const HASH_B = 'b'.repeat(16);
+const FILE = '/corpus/session-one.txt';
+const ATOM_JSON = JSON.stringify([
+ { title: 'A durable insight', atom_type: 'insight', body: 'The insight body prose.' },
+]);
+
+/** The transcript work-item seam, mirroring `_pages` in the sibling file. */
+function transcript(filePath: string, contentHash: string) {
+ return { filePath, content: 'transcript prose body', contentHash };
+}
+
+async function stateRow(
+ filePath: string,
+ contentHash: string,
+): Promise<{ fail_count: number; tombstoned: boolean } | undefined> {
+ const rows = await engine.executeRaw<{ fail_count: number | string; tombstoned: boolean | string }>(
+ `SELECT fail_count, tombstoned FROM extract_atoms_transcript_state
+ WHERE source_id = 'default' AND file_path = $1 AND content_hash = $2`,
+ [filePath, contentHash],
+ );
+ const r = rows[0];
+ if (!r) return undefined;
+ return { fail_count: Number(r.fail_count), tombstoned: r.tombstoned === true || r.tombstoned === 't' };
+}
+
+describe('transcript failure counting (v146)', () => {
+ test('malformed output is a COUNTED failure for a transcript, not a silent retry-forever', async () => {
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('no json in sight'),
+ });
+ expect(result.details.malformed_outputs).toBe(1);
+ const failures = result.details.failures as Array<{ error: string }>;
+ expect(failures[0].error).toContain('malformed model output');
+ // Pre-fix the count was null for transcripts, so the message carried no
+ // streak suffix at all — that absence WAS the bug's fingerprint.
+ expect(failures[0].error).toContain('consecutive failure 1 on this content');
+ const row = await stateRow(FILE, HASH_A);
+ expect(row).toBeDefined();
+ expect(row!.fail_count).toBe(1);
+ expect(row!.tombstoned).toBe(false);
+ });
+
+ test(`tombstones only after ${MAX_DETERMINISTIC_FAILURES} consecutive same-content malformed failures`, async () => {
+ const opts = {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('still not json'),
+ };
+ for (let i = 1; i < MAX_DETERMINISTIC_FAILURES; i++) {
+ const r = await runPhaseExtractAtoms(engine, opts);
+ expect(r.details.tombstoned_transcripts).toEqual([]);
+ const row = await stateRow(FILE, HASH_A);
+ expect(row!.fail_count).toBe(i);
+ expect(row!.tombstoned).toBe(false);
+ }
+ const final = await runPhaseExtractAtoms(engine, opts);
+ expect(final.details.tombstoned_transcripts).toEqual([FILE]);
+ const row = await stateRow(FILE, HASH_A);
+ expect(row!.fail_count).toBe(MAX_DETERMINISTIC_FAILURES);
+ expect(row!.tombstoned).toBe(true);
+ });
+
+ test('a content edit resets the streak (state is hash-keyed)', async () => {
+ const mk = (hash: string) => ({
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, hash)],
+ _chat: async (_o: ChatOpts) => okChatResult('nope'),
+ });
+ await runPhaseExtractAtoms(engine, mk(HASH_A));
+ await runPhaseExtractAtoms(engine, mk(HASH_A));
+ expect((await stateRow(FILE, HASH_A))!.fail_count).toBe(2);
+ await runPhaseExtractAtoms(engine, mk(HASH_B)); // edited transcript
+ expect((await stateRow(FILE, HASH_B))!.fail_count).toBe(1);
+ // The old row survives untouched — the streak did not carry over.
+ expect((await stateRow(FILE, HASH_A))!.fail_count).toBe(2);
+ });
+
+ test('transient provider errors are retryable: no count, no tombstone', async () => {
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => { throw new Error('fetch failed: 503 upstream timeout'); },
+ });
+ expect(await stateRow(FILE, HASH_A)).toBeUndefined();
+ });
+});
+
+describe('transcript zero-yield tombstone (v146)', () => {
+ test('an honest empty extraction tombstones IMMEDIATELY, as it does for pages', async () => {
+ // The behaviour with the largest practical effect: pre-fix a transcript
+ // that legitimately yields nothing left no atom row, so it was re-attempted
+ // on every cycle forever. One clean call is a settled answer about this
+ // content and needs no streak.
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('[]'),
+ });
+ expect(result.details.transcripts_processed).toBe(1);
+ expect(result.details.atoms_extracted).toBe(0);
+ const row = await stateRow(FILE, HASH_A);
+ expect(row).toBeDefined();
+ expect(row!.tombstoned).toBe(true);
+ expect(row!.fail_count).toBe(0); // a zero-yield is NOT a failure
+ });
+
+ test('the zero-yield tombstone is honored on the next run (the read side)', async () => {
+ // Without the discovery-filter half, the row above would be written and
+ // then ignored — a counter nothing reads is inert.
+ const empty = async (_o: ChatOpts) => okChatResult('[]');
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default', _pages: [], _transcripts: [transcript(FILE, HASH_A)], _chat: empty,
+ });
+ let calls = 0;
+ const second = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (o: ChatOpts) => { calls++; return empty(o); },
+ });
+ expect(calls).toBe(0); // never reached the LLM again
+ expect(second.details.transcripts_processed).toBe(0);
+ expect(second.details.duplicates_skipped).toBe(1);
+ });
+
+ test('editing a tombstoned transcript re-eligibilizes it', async () => {
+ // This is what makes the permanence safe: the tombstone is bound to the
+ // content that earned it, never to the path.
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('[]'),
+ });
+ let calls = 0;
+ const after = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_B)], // same path, edited content
+ _chat: async (_o: ChatOpts) => { calls++; return okChatResult(ATOM_JSON); },
+ });
+ expect(calls).toBe(1);
+ expect(after.details.atoms_extracted).toBe(1);
+ });
+
+ test('a malformed-output tombstone is honored on the next run too', async () => {
+ const opts = {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('not json'),
+ };
+ for (let i = 0; i < MAX_DETERMINISTIC_FAILURES; i++) {
+ await runPhaseExtractAtoms(engine, opts);
+ }
+ let calls = 0;
+ const after = await runPhaseExtractAtoms(engine, {
+ ...opts,
+ _chat: async (_o: ChatOpts) => { calls++; return okChatResult('not json'); },
+ });
+ expect(calls).toBe(0); // budget no longer burned on this content
+ expect(after.details.duplicates_skipped).toBe(1);
+ });
+
+ test('an in-progress streak does NOT suppress the transcript (only a tombstone does)', async () => {
+ // fail_count 1 or 2 must stay live and keep being retried, mirroring a page
+ // whose atoms_fail_count is below the bound.
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('not json'),
+ });
+ let calls = 0;
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => { calls++; return okChatResult('not json'); },
+ });
+ expect(calls).toBe(1);
+ });
+});
+
+describe('transcript state is source-scoped (v146)', () => {
+ test("one source's tombstone does not suppress the same file under another source", async () => {
+ // The reason source_id is in the key. The phase is source-scoped
+ // throughout — discovery SQL, the NOT EXISTS idempotency subquery, and
+ // every putPage take sourceId — and this file's header records the
+ // federated-brain bug caused by forgetting it once already.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('dept-x', 'dept-x') ON CONFLICT (id) DO NOTHING`,
+ );
+ await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => okChatResult('[]'),
+ });
+ expect((await stateRow(FILE, HASH_A))!.tombstoned).toBe(true);
+
+ let calls = 0;
+ const other = await runPhaseExtractAtoms(engine, {
+ sourceId: 'dept-x',
+ _pages: [],
+ _transcripts: [transcript(FILE, HASH_A)],
+ _chat: async (_o: ChatOpts) => { calls++; return okChatResult(ATOM_JSON); },
+ });
+ expect(calls).toBe(1); // dept-x still extracts it
+ expect(other.details.atoms_extracted).toBe(1);
+ });
+});
diff --git a/test/extract-atoms-transcript-state-errors.test.ts b/test/extract-atoms-transcript-state-errors.test.ts
new file mode 100644
index 0000000000..4436900aaf
--- /dev/null
+++ b/test/extract-atoms-transcript-state-errors.test.ts
@@ -0,0 +1,140 @@
+/**
+ * v146 `extract_atoms_transcript_state` plumbing — error surfacing (wave review).
+ *
+ * Two silent spots in the transcript failure-count / tombstone path:
+ * - recordItemFailureCount's transcript branch swallowed EVERY write error
+ * with `catch { return null; }`, so a transcript whose strike never landed
+ * (connection blip, RLS, a typo'd column) silently never tombstoned and
+ * re-spent budget forever — the exact class #4916 exists to close.
+ * - tombstonedTranscriptsForHashes logged a full error line on EVERY cycle
+ * of an un-migrated brain (the table simply isn't there yet).
+ *
+ * Now: a real write error is reported on stderr; a missing table is a
+ * once-per-process warning (isUndefinedTableError), not a per-cycle error.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runPhaseExtractAtoms, tombstonedTranscriptsForHashes } from '../src/core/cycle/extract-atoms.ts';
+import { _resetWarnOnceForTests } from '../src/core/utils.ts';
+import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+
+function capture(): { errors: string[]; warns: string[]; restore: () => void } {
+ const errors: string[] = [];
+ const warns: string[] = [];
+ const savedError = console.error;
+ const savedWarn = console.warn;
+ console.error = (...a: unknown[]) => { errors.push(a.map(String).join(' ')); };
+ console.warn = (...a: unknown[]) => { warns.push(a.map(String).join(' ')); };
+ return { errors, warns, restore: () => { console.error = savedError; console.warn = savedWarn; } };
+}
+
+function throwingEngine(err: Error): BrainEngine {
+ return { executeRaw: async () => { throw err; } } as unknown as BrainEngine;
+}
+
+describe('tombstonedTranscriptsForHashes — un-migrated brain vs real failure', () => {
+ afterEach(() => _resetWarnOnceForTests());
+
+ test('a missing table warns ONCE per process and never reaches console.error', async () => {
+ const c = capture();
+ try {
+ const engine = throwingEngine(Object.assign(
+ new Error('relation "extract_atoms_transcript_state" does not exist'), { code: '42P01' }));
+ expect(await tombstonedTranscriptsForHashes(engine, 'default', ['a'.repeat(16)])).toEqual(new Set());
+ expect(await tombstonedTranscriptsForHashes(engine, 'default', ['b'.repeat(16)])).toEqual(new Set());
+ } finally {
+ c.restore();
+ }
+ expect(c.errors).toEqual([]);
+ expect(c.warns).toHaveLength(1);
+ expect(c.warns[0]).toContain('extract_atoms_transcript_state');
+ });
+
+ test('any other error is still reported on stderr every time (assuming none tombstoned)', async () => {
+ const c = capture();
+ try {
+ const engine = throwingEngine(new Error('connection reset by peer'));
+ expect(await tombstonedTranscriptsForHashes(engine, 'default', ['a'.repeat(16)])).toEqual(new Set());
+ } finally {
+ c.restore();
+ }
+ expect(c.warns).toEqual([]);
+ expect(c.errors).toHaveLength(1);
+ expect(c.errors[0]).toContain('connection reset by peer');
+ });
+});
+
+describe('recordItemFailureCount — transcript strike write failures are surfaced', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ const prose = async (_o: ChatOpts): Promise<ChatResult> => ({
+ text: 'I could not find anything to extract.',
+ blocks: [{ type: 'text', text: '' }],
+ stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+ });
+
+ /** Same engine, but the transcript-state strike INSERT fails like a flaky connection would. */
+ function withFailingStrike(target: PGLiteEngine, err: Error): BrainEngine {
+ return new Proxy(target, {
+ get(t, prop, recv) {
+ if (prop === 'executeRaw') {
+ return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('INSERT INTO extract_atoms_transcript_state')) throw err;
+ return t.executeRaw(sql, params);
+ };
+ }
+ return Reflect.get(t, prop, recv);
+ },
+ }) as unknown as BrainEngine;
+ }
+
+ test('a real write error is reported on stderr (not swallowed)', async () => {
+ const c = capture();
+ try {
+ await runPhaseExtractAtoms(withFailingStrike(engine, new Error('connection reset by peer')), {
+ sourceId: 'default',
+ _transcripts: [{ filePath: '/fake/meeting-x.txt', content: 'transcript content x', contentHash: 'd1b2c3d4e5f60718' }],
+ _pages: [],
+ _chat: prose,
+ });
+ } finally {
+ c.restore();
+ }
+ const strikeErrors = c.errors.filter((l) => l.includes('failure-count') || l.includes('failure count'));
+ expect(strikeErrors).toHaveLength(1);
+ expect(strikeErrors[0]).toContain('connection reset by peer');
+ expect(strikeErrors[0]).toContain('/fake/meeting-x.txt');
+ }, 60_000);
+
+ test('a missing table is NOT reported by the strike path (the tombstone check already warned once)', async () => {
+ _resetWarnOnceForTests();
+ const c = capture();
+ try {
+ await runPhaseExtractAtoms(withFailingStrike(engine, Object.assign(
+ new Error('relation "extract_atoms_transcript_state" does not exist'), { code: '42P01' })), {
+ sourceId: 'default',
+ _transcripts: [{ filePath: '/fake/meeting-y.txt', content: 'transcript content y', contentHash: 'e1b2c3d4e5f60718' }],
+ _pages: [],
+ _chat: prose,
+ });
+ } finally {
+ c.restore();
+ }
+ expect(c.errors.filter((l) => l.includes('failure-count') || l.includes('failure count'))).toEqual([]);
+ }, 60_000);
+});
diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.ts
index 1af92fedf8..1a61259e46 100644
--- a/test/extract-conversation-facts.test.ts
+++ b/test/extract-conversation-facts.test.ts
@@ -1089,12 +1089,27 @@ describe('runExtractConversationFactsCore', () => {
slug: 'conversations/imessage/alice-example',
sleepMs: 0,
});
- expect(first.pages_processed).toBe(1);
+ // #4869: an unfinished page is a failed claim, not a processed one —
+ // pages_failed is what drives CLI exit 1 / the cycle 'warn' status.
+ expect(first.pages_processed).toBe(0);
+ expect(first.pages_failed).toBe(1);
const terminals = await engine.executeRaw<{ count: string | number }>(
`SELECT COUNT(*) AS count FROM facts WHERE source = $1`,
[TERMINAL_AUDIT_SOURCE],
);
expect(Number(terminals[0]?.count ?? 0)).toBe(0);
+ // Partial facts stay durable for the delete-first replay; no completion
+ // checkpoint key is minted for the old snapshot.
+ const partial = await engine.executeRaw<{ count: string | number }>(
+ `SELECT COUNT(*) AS count FROM facts WHERE source = $1 AND source_markdown_slug = $2`,
+ [PER_SEGMENT_SOURCE_PREFIX, 'conversations/imessage/alice-example'],
+ );
+ expect(Number(partial[0]?.count ?? 0)).toBe(2);
+ const cpKeys = await engine.executeRaw<{ ckey: string }>(
+ `SELECT jsonb_array_elements_text(completed_keys) AS ckey FROM op_checkpoints
+ WHERE op = 'extract-conversation-facts'`,
+ );
+ expect(cpKeys.some((r) => r.ckey.startsWith('default|conversations/imessage/alice-example|'))).toBe(false);
const retry = await runExtractConversationFactsCore(engine, {
sourceId: 'default',
@@ -1103,6 +1118,8 @@ describe('runExtractConversationFactsCore', () => {
});
expect(retry.pages_skipped_completed).toBe(0);
expect(retry.pages_processed).toBe(1);
+ expect(retry.pages_failed).toBe(0);
+ expect(retry.orphan_facts_cleaned).toBe(2);
});
test('raw transcript sidecar edits invalidate the durable outcome', async () => {
diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.ts
index 47af6a2f91..4d5664f057 100644
--- a/test/extract-facts-phase.test.ts
+++ b/test/extract-facts-phase.test.ts
@@ -10,10 +10,15 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
import { parseFactsFence } from '../src/core/facts-fence.ts';
import { importFromContent } from '../src/core/import-file.ts';
+import { acquirePageLock } from '../src/core/page-lock.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
let engine: PGLiteEngine;
@@ -205,6 +210,279 @@ describe('runExtractFacts — happy path', () => {
expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Existing', 'New']);
});
+ test('refuses destructive reconcile when canonical Markdown is newer than the pages cache', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-stale-cache-'));
+ try {
+ // Point the default source at a real canonical tree for this case.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+
+ const cachedBody = FACT_FENCE(
+ `| 1 | Existing | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,
+ );
+ const canonicalBody = FACT_FENCE(
+ `| 1 | Existing | fact | 1.0 | world | medium | 2026-01-01 | | s | |
+| 2 | Newly remembered | event | 1.0 | world | medium | 2026-09-02 | | remember:test | |`,
+ );
+ await putPage('people/alice', cachedBody);
+ await runExtractFacts(engine, { slugs: ['people/alice'] });
+
+ // Reproduce the real ordering: remember writes canonical Markdown and
+ // stamps the new facts row before page sync refreshes compiled_truth.
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'alice.md'), canonicalBody, 'utf-8');
+ await engine.insertFacts(
+ [{
+ fact: 'Newly remembered',
+ kind: 'event',
+ source: 'remember:test',
+ row_num: 2,
+ source_markdown_slug: 'people/alice',
+ }],
+ { source_id: 'default' },
+ );
+
+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });
+ expect(r.factsDeleted).toBe(0);
+ expect(r.factsInserted).toBe(0);
+ expect(r.warnings).toContainEqual(expect.stringContaining('FACTS_PAGE_CACHE_STALE'));
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,
+ );
+ expect(rows.rows.map((row: { fact: string }) => row.fact))
+ .toEqual(['Existing', 'Newly remembered']);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('page lock closes the empty-fence delete race with a concurrent canonical writer', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-empty-race-'));
+ const lockRoot = join(root, '.locks');
+ const slug = 'people/empty-race';
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+ await putPage(slug, '');
+ await engine.insertFacts(
+ [{ fact: 'Previously indexed', kind: 'fact', source: 'old', row_num: 1, source_markdown_slug: slug }],
+ { source_id: 'default' },
+ );
+
+ const held = await acquirePageLock(slug, { lockRoot });
+ expect(held).not.toBeNull();
+ let settled = false;
+ const reconcile = runExtractFacts(engine, { slugs: [slug], pageLockRoot: lockRoot })
+ .finally(() => { settled = true; });
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(settled).toBe(false);
+
+ const canonicalBody = FACT_FENCE(
+ `| 1 | Previously indexed | fact | 1.0 | world | medium | 2026-01-01 | | old | |\n` +
+ `| 2 | Concurrent remember | event | 1.0 | world | medium | 2026-09-02 | | remember:test | |`,
+ );
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'empty-race.md'), canonicalBody, 'utf-8');
+ await engine.insertFacts(
+ [{ fact: 'Concurrent remember', kind: 'event', source: 'remember:test', row_num: 2, source_markdown_slug: slug }],
+ { source_id: 'default' },
+ );
+ await held!.release();
+
+ const r = await reconcile;
+ expect(r.factsDeleted).toBe(0);
+ expect(r.warnings).toContainEqual(expect.stringContaining('FACTS_PAGE_CACHE_STALE'));
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num`,
+ [slug],
+ );
+ expect(rows.rows.map((row: { fact: string }) => row.fact))
+ .toEqual(['Previously indexed', 'Concurrent remember']);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 15_000);
+
+ test('page lock closes the transactional drift-replace race with a concurrent canonical writer', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-drift-race-'));
+ const lockRoot = join(root, '.locks');
+ const slug = 'people/drift-race';
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+ const cachedBody = FACT_FENCE(
+ `| 1 | Canonical cached | fact | 1.0 | world | medium | 2026-01-01 | | cached | |`,
+ );
+ await putPage(slug, cachedBody);
+ await engine.insertFacts(
+ [{ fact: 'Stale indexed row', kind: 'fact', source: 'stale', row_num: 1, source_markdown_slug: slug }],
+ { source_id: 'default' },
+ );
+
+ const held = await acquirePageLock(slug, { lockRoot });
+ expect(held).not.toBeNull();
+ let settled = false;
+ const reconcile = runExtractFacts(engine, { slugs: [slug], pageLockRoot: lockRoot })
+ .finally(() => { settled = true; });
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(settled).toBe(false);
+
+ const canonicalBody = FACT_FENCE(
+ `| 1 | Canonical cached | fact | 1.0 | world | medium | 2026-01-01 | | cached | |\n` +
+ `| 2 | Concurrent remember | event | 1.0 | world | medium | 2026-09-02 | | remember:test | |`,
+ );
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'drift-race.md'), canonicalBody, 'utf-8');
+ await engine.insertFacts(
+ [{ fact: 'Concurrent remember', kind: 'event', source: 'remember:test', row_num: 2, source_markdown_slug: slug }],
+ { source_id: 'default' },
+ );
+ await held!.release();
+
+ const r = await reconcile;
+ expect(r.factsDeleted).toBe(0);
+ expect(r.factsInserted).toBe(0);
+ expect(r.warnings).toContainEqual(expect.stringContaining('FACTS_PAGE_CACHE_STALE'));
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num, id`,
+ [slug],
+ );
+ expect(rows.rows.map((row: { fact: string }) => row.fact))
+ .toEqual(['Stale indexed row', 'Concurrent remember']);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 15_000);
+
+ test('fresh cache: canonical Markdown equal to the pages cache lets destructive reconcile proceed', async () => {
+ // Twin of the stale-refusal test above with ONE difference: the on-disk
+ // file carries the same body as the pages row. Pins the comparison itself,
+ // so a normally synced page is never mistaken for a stale one.
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-fresh-cache-'));
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+ const body = FACT_FENCE(
+ `| 1 | Existing | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,
+ );
+ await putPage('people/alice-fresh', body);
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'alice-fresh.md'), body, 'utf-8');
+ // DB drift the fence does not carry: the reconcile must wipe it.
+ await engine.insertFacts(
+ [{ fact: 'Stale indexed row', kind: 'fact', source: 'stale', row_num: 7, source_markdown_slug: 'people/alice-fresh' }],
+ { source_id: 'default' },
+ );
+
+ const r = await runExtractFacts(engine, { slugs: ['people/alice-fresh'] });
+ expect(r.warnings.some(w => w.includes('FACTS_PAGE_CACHE_STALE'))).toBe(false);
+ expect(r.factsDeleted).toBeGreaterThan(0);
+ expect(r.factsInserted).toBe(1);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-fresh' ORDER BY row_num`,
+ );
+ expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Existing']);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('sync.write_through=off: a stale mirror file never blocks destructive reconcile', async () => {
+ // With write-through off the fence writers already treat the file as
+ // non-canonical (fence-write.ts legacy fallback), so the staleness check
+ // must not hold the DB hostage to a mirror nobody maintains.
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-wt-off-'));
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+ await engine.setConfig('sync.write_through', 'off');
+ _resetWriteThroughCacheForTest();
+ await putPage('people/alice-wt-off', FACT_FENCE(
+ `| 1 | Existing | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,
+ ));
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, 'people', 'alice-wt-off.md'), '# Stale mirror\n\nNothing like the DB body.\n', 'utf-8');
+ await engine.insertFacts(
+ [{ fact: 'Stale indexed row', kind: 'fact', source: 'stale', row_num: 7, source_markdown_slug: 'people/alice-wt-off' }],
+ { source_id: 'default' },
+ );
+
+ const r = await runExtractFacts(engine, { slugs: ['people/alice-wt-off'] });
+ expect(r.warnings.some(w => w.includes('FACTS_PAGE_CACHE_STALE'))).toBe(false);
+ expect(r.factsDeleted).toBeGreaterThan(0);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice-wt-off' ORDER BY row_num`,
+ );
+ expect(rows.rows.map((row: { fact: string }) => row.fact)).toEqual(['Existing']);
+ } finally {
+ await engine.unsetConfig('sync.write_through');
+ _resetWriteThroughCacheForTest();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('a page lock held past the deadline degrades to FACTS_PAGE_LOCK_TIMEOUT and the run continues', async () => {
+ // One wedged page must cost a warning, not the rest of the phase run.
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-facts-lock-timeout-'));
+ const lockRoot = join(root, '.locks');
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE sources SET local_path = $1 WHERE id = 'default'`,
+ [root],
+ );
+ // Wedged page: empty fence + a fence-owned row → the destructive delete path.
+ await putPage('people/wedged', '');
+ await engine.insertFacts(
+ [{ fact: 'Survives the wedge', kind: 'fact', source: 'old', row_num: 1, source_markdown_slug: 'people/wedged' }],
+ { source_id: 'default' },
+ );
+ // Healthy sibling later in the same run: must still reconcile.
+ await putPage('people/healthy', FACT_FENCE(
+ `| 1 | Healthy fact | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,
+ ));
+
+ const held = await acquirePageLock('people/wedged', { lockRoot });
+ expect(held).not.toBeNull();
+ try {
+ const r = await runExtractFacts(engine, { slugs: ['people/wedged', 'people/healthy'], pageLockRoot: lockRoot });
+ expect(r.warnings).toContainEqual(expect.stringContaining('people/wedged: FACTS_PAGE_LOCK_TIMEOUT'));
+ expect(r.factsDeleted).toBe(0);
+ expect(r.factsInserted).toBe(1);
+ } finally {
+ await held!.release();
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/wedged'`,
+ );
+ expect(rows.rows).toHaveLength(1);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 20_000);
+
test('cli:-origin conversation facts (#1928) neither break idempotency nor get wiped', async () => {
await putPage('people/alice', FACT_FENCE(
`| 1 | Fence fact | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,
diff --git a/test/extract-incremental.test.ts b/test/extract-incremental.test.ts
index 21307bb8ae..b87a433fab 100644
--- a/test/extract-incremental.test.ts
+++ b/test/extract-incremental.test.ts
@@ -270,3 +270,40 @@ describe('runExtractCore — incremental frontmatter gate (includeFrontmatter)',
expect(result.links_created).toBeGreaterThan(0);
});
});
+
+// ─── wave review: `quiet` is its own knob, not a side effect of jsonMode ──
+describe('runExtractCore — quiet vs jsonMode on the incremental path', () => {
+ function captureStdout(): { lines: string[]; restore: () => void } {
+ const lines: string[] = [];
+ const saved = console.log;
+ console.log = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };
+ return { lines, restore: () => { console.log = saved; } };
+ }
+
+ test('quiet: true suppresses the human summary line while jsonMode stays false (human stderr channel)', async () => {
+ // The cycle used `jsonMode: true` as a stand-in for "quiet": it hid the
+ // summary, but it ALSO flipped batch errors to JSON events on stderr in a
+ // plain `gbrain dream`. Embedded callers own the report — they say so.
+ await seedPage('people/alice', 'Alice knows [[companies/acme]].');
+ await seedPage('companies/acme', 'Acme.');
+ const out = captureStdout();
+ try {
+ await runExtractCore(engine, { mode: 'all', dir: tempDir, slugs: ['people/alice'], jsonMode: false, quiet: true });
+ } finally {
+ out.restore();
+ }
+ expect(out.lines.filter((l) => l.includes('Incremental extract'))).toEqual([]);
+ });
+
+ test('without quiet the human summary line still prints (CLI behaviour unchanged)', async () => {
+ await seedPage('people/alice', 'Alice knows [[companies/acme]].');
+ await seedPage('companies/acme', 'Acme.');
+ const out = captureStdout();
+ try {
+ await runExtractCore(engine, { mode: 'all', dir: tempDir, slugs: ['people/alice'], jsonMode: false });
+ } finally {
+ out.restore();
+ }
+ expect(out.lines.some((l) => l.startsWith('Incremental extract: created'))).toBe(true);
+ });
+});
diff --git a/test/extract-timeline-from-meetings.test.ts b/test/extract-timeline-from-meetings.test.ts
index a979ed97ff..701eba62ca 100644
--- a/test/extract-timeline-from-meetings.test.ts
+++ b/test/extract-timeline-from-meetings.test.ts
@@ -1,8 +1,9 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';
-import type { Gazetteer } from '../src/core/by-mention.ts';
+import { buildGazetteer, type Gazetteer } from '../src/core/by-mention.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
@@ -32,16 +33,16 @@ async function seedEntity(slug: string, title: string): Promise<void> {
async function seedNote(
slug: string,
- opts: { title: string; legacyType?: string },
+ opts: { title: string; legacyType?: string; body?: string; sourceId?: string },
): Promise<void> {
await engine.putPage(slug, {
type: 'note',
title: opts.title,
- compiled_truth: 'Meeting discussion notes.',
+ compiled_truth: opts.body ?? 'Meeting discussion notes.',
timeline: '',
frontmatter: opts.legacyType ? { legacy_type: opts.legacyType } : {},
effective_date: new Date('2026-04-20T00:00:00.000Z'),
- });
+ }, opts.sourceId ? { sourceId: opts.sourceId } : undefined);
}
async function addAttended(fromSlug: string, toSlug: string): Promise<void> {
@@ -97,6 +98,34 @@ describe('extractTimelineFromMeetings', () => {
const timeline = await engine.getTimeline('people/alice-example', { sourceId: 'default' });
expect(timeline).toHaveLength(0);
});
+
+ it('follows body mentions of an entity in another source only under link_resolution.cross_source', async () => {
+ // Entity lives in 'default'; the meeting lives in 'team-b' and names the
+ // entity in its body (no attended link). Same shape as a multi-source brain
+ // whose entity dictionary sits in one source and meeting notes in another.
+ await seedEntity('people/alice-example', 'Alice Example');
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('team-b', 'Team B') ON CONFLICT (id) DO NOTHING`, []);
+ await seedNote('meetings/partner-sync', {
+ title: 'Partner Sync',
+ legacyType: 'meeting',
+ body: 'Alice Example presented the roadmap.',
+ sourceId: 'team-b',
+ });
+
+ const off = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, () =>
+ extractTimelineFromMeetings(engine, { dryRun: true }));
+ expect(off).toMatchObject({ meetings_scanned: 1, entries_created: 0, entities_touched: 0 });
+
+ const on = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, () =>
+ extractTimelineFromMeetings(engine));
+ expect(on).toMatchObject({ meetings_scanned: 1, entries_created: 1, entities_touched: 1, batch_errors: 0 });
+ const timeline = await engine.getTimeline('people/alice-example', { sourceId: 'default' });
+ expect(timeline).toHaveLength(1);
+ expect(timeline[0]).toMatchObject({
+ source: 'extract-timeline-from-meetings:meetings/partner-sync',
+ summary: 'Discussed in Partner Sync',
+ });
+ });
});
// ─── #4542 — CLI surface: a zero-meeting run must WARN, not mimic success ──
@@ -143,3 +172,166 @@ describe('#4542 zero-meetings warning at the CLI surface', () => {
expect(stderrLines.join('\n')).not.toContain('omit --from-meetings');
});
});
+
+// ─── put_page-written meetings: NULL effective_date column ──
+//
+// Pages written via `put_page` (agent/MCP or bulk custom import, not the
+// file-sync pipeline) never get `effective_date` computed — the column stays
+// NULL even when frontmatter carries a parseable `date:`. The extractor used
+// to `continue` on those rows BEFORE counting them, so a whole agent-written
+// meeting corpus reported "0 meetings matched" with and without --source-id.
+// The date must come from the same recipe `gbrain backfill effective_date`
+// uses (computeEffectiveDate over frontmatter/filename), NOT from updated_at:
+// timeline_entries dedups on (page_id, date, summary, source), so an
+// import-timestamp row would survive as a duplicate next to the correctly
+// dated one written after a later backfill + re-run.
+describe('meetings with NULL effective_date (put_page-style insert)', () => {
+ const SRC = 'bulk-import';
+ async function seedSource(): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('${SRC}', '${SRC}', '{}'::jsonb) ON CONFLICT DO NOTHING`,
+ );
+ }
+
+ it('is still scanned, with and without --source-id', async () => {
+ await seedSource();
+ await engine.putPage('meetings/bulk-1', {
+ type: 'meeting',
+ title: 'Bulk Meeting',
+ compiled_truth: 'Some notes.',
+ timeline: '',
+ frontmatter: { date: '2026-08-01', attendees: ['Alice Example'] },
+ // No effective_date — mimics a raw put_page call.
+ }, { sourceId: SRC });
+
+ const emptyGazetteer: Gazetteer = new Map();
+ const withFilter = await extractTimelineFromMeetings(engine, {
+ gazetteer: emptyGazetteer,
+ sourceIdFilter: SRC,
+ });
+ expect(withFilter.meetings_scanned).toBe(1);
+
+ const withoutFilter = await extractTimelineFromMeetings(engine, { gazetteer: emptyGazetteer });
+ expect(withoutFilter.meetings_scanned).toBe(1);
+ });
+
+ it('writes the timeline entry with the frontmatter date, not the import timestamp', async () => {
+ await seedSource();
+ // Entity in the SAME source as the meeting: body mentions never cross
+ // sources unless link_resolution.cross_source is on.
+ await engine.putPage('people/alice-example', {
+ type: 'person',
+ title: 'Alice Example',
+ compiled_truth: 'Alice Example profile',
+ timeline: '',
+ frontmatter: {},
+ }, { sourceId: SRC });
+ await engine.putPage('meetings/bulk-2', {
+ type: 'meeting',
+ title: 'Bulk Meeting 2',
+ compiled_truth: 'Alice Example joined.',
+ timeline: '',
+ frontmatter: { date: '2026-08-01' },
+ }, { sourceId: SRC });
+
+ const page = await engine.getPage('meetings/bulk-2', { sourceId: SRC });
+ expect(page!.effective_date).toBeNull(); // column genuinely NULL
+
+ const gazetteer = await buildGazetteer(engine);
+ const result = await extractTimelineFromMeetings(engine, { gazetteer, sourceIdFilter: SRC });
+ expect(result.meetings_scanned).toBe(1);
+ expect(result.entries_created).toBe(1);
+
+ const timeline = await engine.getTimeline('people/alice-example', { sourceId: SRC });
+ expect(timeline).toHaveLength(1);
+ // Read the calendar day as text: the runtime `date` off PGLite is a JS Date.
+ const rows = await engine.executeRaw<{ date: string }>(
+ `SELECT date::text AS date FROM timeline_entries WHERE id = $1`, [timeline[0]!.id],
+ );
+ expect(rows[0]!.date).toBe('2026-08-01');
+ });
+});
+
+// ─── wave review: attendee cross-source gate, date sources, private meetings ──
+describe('wave review — attendee gate, date derivation, private meetings', () => {
+ async function seedMeeting(slug: string, frontmatter: Record<string, unknown>, sourceId?: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'meeting',
+ title: `Meeting ${slug.split('/').pop()}`,
+ compiled_truth: 'Notes.',
+ timeline: '',
+ frontmatter,
+ // No effective_date — a raw put_page row.
+ }, sourceId ? { sourceId } : undefined);
+ }
+ const datesBySource = () => engine.executeRaw<{ date: string; source: string }>(
+ `SELECT date::text AS date, source FROM timeline_entries ORDER BY date, source`,
+ );
+
+ it('dates a NULL-effective_date meeting from its slug tail or import_filename, like the effective_date backfill', async () => {
+ await seedEntity('people/alice-example', 'Alice Example');
+ // Slug tail carries the date (the common vault layout: meetings/YYYY-MM-DD-*).
+ await seedMeeting('meetings/2026-05-02-standup', {});
+ await addAttended('meetings/2026-05-02-standup', 'people/alice-example');
+ // Slug has no date; the imported filename does.
+ await seedMeeting('meetings/standup-two', {});
+ await engine.executeRaw(`UPDATE pages SET import_filename = '2026-05-03-standup-two.md' WHERE slug = 'meetings/standup-two'`);
+ await addAttended('meetings/standup-two', 'people/alice-example');
+
+ const result = await extractTimelineFromMeetings(engine, { gazetteer: new Map() });
+ expect(result).toMatchObject({ meetings_scanned: 2, entries_created: 2, batch_errors: 0 });
+ expect((await datesBySource()).map((r) => [r.date, r.source])).toEqual([
+ ['2026-05-02', 'extract-timeline-from-meetings:meetings/2026-05-02-standup'],
+ ['2026-05-03', 'extract-timeline-from-meetings:meetings/standup-two'],
+ ]);
+ });
+
+ it('skips a meeting whose only date is the import timestamp instead of dating it from updated_at', async () => {
+ // Nothing in frontmatter, slug, or filename parses as a date. Pre-fix the
+ // row was dated from updated_at (today) — a twin that survives dedup next
+ // to the correctly dated row a later backfill + re-run writes.
+ await seedEntity('people/alice-example', 'Alice Example');
+ await seedMeeting('meetings/undated-sync', {});
+ await addAttended('meetings/undated-sync', 'people/alice-example');
+
+ const result = await extractTimelineFromMeetings(engine, { gazetteer: new Map() });
+ expect(result).toMatchObject({ meetings_scanned: 0, entries_created: 0, entities_touched: 0 });
+ expect(await datesBySource()).toEqual([]);
+ });
+
+ it('attended edges into another source are gated by link_resolution.cross_source, like body mentions', async () => {
+ await seedEntity('people/alice-example', 'Alice Example'); // source 'default'
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('team-b', 'Team B') ON CONFLICT (id) DO NOTHING`, []);
+ await seedNote('meetings/board-sync', { title: 'Board Sync', legacyType: 'meeting', sourceId: 'team-b' });
+ await engine.addLinksBatch([{
+ from_slug: 'meetings/board-sync', to_slug: 'people/alice-example',
+ link_type: 'attended', link_source: 'manual',
+ from_source_id: 'team-b', to_source_id: 'default',
+ }]);
+
+ const off = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, () =>
+ extractTimelineFromMeetings(engine, { gazetteer: new Map() }));
+ expect(off).toMatchObject({ meetings_scanned: 1, entries_created: 0, entities_touched: 0 });
+
+ const on = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, () =>
+ extractTimelineFromMeetings(engine, { gazetteer: new Map() }));
+ expect(on).toMatchObject({ meetings_scanned: 1, entries_created: 1, entities_touched: 1 });
+ });
+
+ it('a visibility: private meeting never lands on another page\'s timeline', async () => {
+ // The fan-out row carries the meeting's title + slug + date but no
+ // event_page_id (the (event_page_id, date) unique index forbids one per
+ // attendee), so the remote private-event filter could never hide it.
+ await seedEntity('people/alice-example', 'Alice Example');
+ await seedMeeting('meetings/2026-05-04-private-1on1', { visibility: 'private' });
+ await addAttended('meetings/2026-05-04-private-1on1', 'people/alice-example');
+ await seedMeeting('meetings/2026-05-05-public-sync', {});
+ await addAttended('meetings/2026-05-05-public-sync', 'people/alice-example');
+
+ const result = await extractTimelineFromMeetings(engine, { gazetteer: new Map() });
+ expect(result).toMatchObject({ meetings_scanned: 1, entries_created: 1, entities_touched: 1 });
+ expect((await datesBySource()).map((r) => r.source)).toEqual([
+ 'extract-timeline-from-meetings:meetings/2026-05-05-public-sync',
+ ]);
+ });
+});
diff --git a/test/extract.test.ts b/test/extract.test.ts
index 50485abc02..e272e66cab 100644
--- a/test/extract.test.ts
+++ b/test/extract.test.ts
@@ -88,6 +88,32 @@ describe('extractLinksFromFile', () => {
expect(companyLinks[0].to_slug).toBe('companies/acme-example');
});
+ it('frontmatter attendees: a stroke-letter name resolves to the unfolded page slug sync mints (#4855)', async () => {
+ // The FS resolver has no fuzzy fallback, so it must try the sync slug
+ // grammar (which keeps đ) as well as the folded basename form.
+ const content = '---\nattendees: [Đức Example]\ntype: meeting\n---\nNotes.';
+ const allSlugs = new Set(['meetings/sync', 'people/đuc-example']);
+ const links = await extractLinksFromFile(content, 'meetings/sync.md', allSlugs, { includeFrontmatter: true });
+ const attended = links.filter(l => l.link_type === 'attended');
+ expect(attended).toHaveLength(1);
+ expect(attended[0].from_slug).toBe('people/đuc-example');
+ expect(attended[0].to_slug).toBe('meetings/sync');
+ });
+
+ it('frontmatter attendees: a stroke-letter name also resolves to the FOLDED ASCII page slug (#4855)', async () => {
+ // The other half of the dual-form lookup: the basename index keys through
+ // normalizeBasename, which folds đ → d, so a people page minted with an
+ // ASCII slug resolves too. Without the fold the key stays `đuc-example`
+ // and the lookup misses in silence.
+ const content = '---\nattendees: [Đức Example]\ntype: meeting\n---\nNotes.';
+ const allSlugs = new Set(['meetings/sync', 'people/duc-example']);
+ const links = await extractLinksFromFile(content, 'meetings/sync.md', allSlugs, { includeFrontmatter: true });
+ const attended = links.filter(l => l.link_type === 'attended');
+ expect(attended).toHaveLength(1);
+ expect(attended[0].from_slug).toBe('people/duc-example');
+ expect(attended[0].to_slug).toBe('meetings/sync');
+ });
+
it('extracts frontmatter investors array (v0.13: incoming direction)', async () => {
// v0.13: deal page with investors:[yc, threshold] emits INCOMING edges:
// companies/yc → deals/seed invested_in and same for threshold.
diff --git a/test/facts-backstop-integration.test.ts b/test/facts-backstop-integration.test.ts
index 02b31cc954..3f3ad8d97f 100644
--- a/test/facts-backstop-integration.test.ts
+++ b/test/facts-backstop-integration.test.ts
@@ -101,6 +101,31 @@ describe('runFactsPipeline (extract_facts MCP op path) — response shape stabil
expect(r.entity_slugs).toEqual([]);
});
+ test('#4755: a null-like entity STRING from the extractor lands unparented, never under entity_slug=\'null\'', async () => {
+ // The extractor prompt asks for JSON null on subjectless statements; LLMs
+ // routinely emit the string "null" / "None" instead. Pre-fix that token
+ // reached the resolver, fell back to itself as the slug, and the facts
+ // were filed under a page that cannot exist.
+ chatStub([
+ { fact: 'a gap statement with no subject', kind: 'fact', notability: 'medium', entity: 'null' },
+ { fact: 'a second subjectless statement', kind: 'fact', notability: 'medium', entity: 'None' },
+ ]);
+ const r = await runFactsPipeline('turn with no subject', {
+ engine,
+ sourceId: 'default',
+ sessionId: 'null-entity-test',
+ source: 'mcp:extract_facts',
+ });
+ expect(r.inserted).toBe(2);
+ for (const id of r.fact_ids) {
+ const rows = await engine.executeRaw<{ entity_slug: string | null }>(
+ 'SELECT entity_slug FROM facts WHERE id = $1', [id],
+ );
+ expect(rows[0].entity_slug).toBeNull();
+ }
+ expect(r.entity_slugs).toEqual([]);
+ });
+
test('empty extraction → zero counts (no NaN, no undefined)', async () => {
chatStub([]);
const r = await runFactsPipeline('nothing claim-worthy here', {
diff --git a/test/facts-backstop-outcome.serial.test.ts b/test/facts-backstop-outcome.serial.test.ts
index 9f6169f981..ff95b4fea7 100644
--- a/test/facts-backstop-outcome.serial.test.ts
+++ b/test/facts-backstop-outcome.serial.test.ts
@@ -28,6 +28,7 @@ import {
resetGateway,
__setChatTransportForTests,
} from '../src/core/ai/gateway.ts';
+import { AIConfigError } from '../src/core/ai/errors.ts';
import {
runFactsBackstop,
runFactsPipeline,
@@ -164,7 +165,8 @@ describe('keyless vs keyed chat_unavailable', () => {
// Global default would be Anthropic (unservable), but the DB-plane
// extraction override IS servable with the OpenAI key — the engine-aware
// gate must admit the work. Short-lived mode routes to the durable minion
- // (no LLM call executes in-test) so we can also pin the retry policy.
+ // (no LLM call executes in-test) so we can also pin the retry policy and
+ // the handler-default timeout stamped on the submitted row.
process.env.OPENAI_API_KEY = 'sk-test';
await engine.setConfig('facts.extraction_model', 'openai:gpt-4o-mini');
configureGateway({ env: { OPENAI_API_KEY: 'sk-test' } });
@@ -176,13 +178,14 @@ describe('keyless vs keyed chat_unavailable', () => {
expect(r.mode).toBe('queue');
expect((r as { enqueued: boolean }).enqueued).toBe(true);
expect((r as { skipped?: string }).skipped).toBeUndefined();
- const jobs = await engine.executeRaw<{ max_attempts: number; backoff_delay: number }>(
- `SELECT max_attempts, backoff_delay FROM minion_jobs WHERE name = 'facts-absorb'`,
+ const jobs = await engine.executeRaw<{ max_attempts: number; backoff_delay: number; timeout_ms: number | string }>(
+ `SELECT max_attempts, backoff_delay, timeout_ms FROM minion_jobs WHERE name = 'facts-absorb'`,
);
expect(jobs).toHaveLength(1);
// Slow-retry policy (R2-5): config drift is fixed on human timescales.
expect(Number(jobs[0].max_attempts)).toBe(5);
expect(Number(jobs[0].backoff_delay)).toBe(60_000);
+ expect(Number(jobs[0].timeout_ms)).toBe(10 * 60 * 1000);
});
});
@@ -352,4 +355,70 @@ describe('coverage-gap additions (ship review)', () => {
// The cause stays reachable for local debugging.
expect(String((err as { cause?: unknown }).cause)).toContain('401');
});
+
+ test('FactsExtractionError surfaces the cause CONSTRUCTOR name, never its .name or .message', () => {
+ class FakeApiCallError extends Error {
+ constructor(message: string) {
+ super(message);
+ // Deliberately different from the class name, so a test that reads
+ // `.name` instead of `.constructor.name` would fail here — pinning
+ // WHICH property the breadcrumb reads, not just that some name shows up.
+ this.name = 'org_abc123_over_quota';
+ }
+ }
+ const err = new FactsExtractionError('provider_error', 'claude-cli:claude-sonnet-5',
+ new FakeApiCallError('connection reset by peer (org_abc123)'));
+ // The class name is a diagnostic breadcrumb — it survives into the
+ // persisted message so a durable job's `error_text` (which is all that
+ // remains once the in-process `cause` is gone) can still distinguish
+ // "which kind of provider failure" across occurrences.
+ expect(err.message).toContain('(cause=FakeApiCallError)');
+ // The message-carried breadcrumb is the CONSTRUCTOR name, never `.name`
+ // and never `.message` — no room for a provider body to leak through it.
+ expect(err.message).not.toContain('org_abc123');
+ expect(err.message).not.toContain('connection reset');
+ expect(JSON.stringify(err)).not.toContain('org_abc123');
+ });
+
+ test('FactsExtractionError drops a cause-constructor name that is not a plain identifier', () => {
+ // A dependency could in principle construct an Error whose
+ // `constructor.name` is an attacker-chosen string (this needs the
+ // dependency to already run arbitrary code — not a normal provider
+ // error path). The breadcrumb is validated against a plain-identifier
+ // shape and DROPPED (not substituted) rather than trusted verbatim.
+ class WeirdError extends Error {}
+ Object.defineProperty(WeirdError, 'name', { value: 'org_example_secret sk-proj-fake123' });
+ const err = new FactsExtractionError('provider_error', 'openai:gpt-5.2', new WeirdError('x'));
+ expect(err.message).not.toContain('cause=');
+ expect(err.message).not.toContain('org_example_secret');
+ expect(err.message).not.toContain('sk-proj');
+ });
+
+ test('FactsExtractionError appends the whole-run failure class the gateway already computes', () => {
+ // normalizeAIError wraps every provider failure as AIConfigError or
+ // AITransientError, so the class name alone can't tell a 401 from a 400.
+ // classifyGlobalLlmError (the vocabulary ingest_log already uses) walks
+ // the cause chain for the status, so a dead job's error_text reads
+ // `(cause=AIConfigError auth)` while the provider body — and the key it
+ // echoes — still never reaches the message.
+ const err = new FactsExtractionError('provider_error', 'openai:gpt-5.2',
+ new AIConfigError('401 Incorrect API key sk-proj-x', undefined,
+ Object.assign(new Error('x'), { statusCode: 401 })));
+ expect(err.message).toContain('(cause=AIConfigError auth)');
+ expect(err.message).not.toContain('sk-proj');
+ expect(err.message).not.toContain('Incorrect API key');
+ });
+
+ test('FactsExtractionError omits the cause breadcrumb when there is no cause', () => {
+ const err = new FactsExtractionError('truncated_output', 'openai:gpt-5.2');
+ expect(err.message).toBe('[facts-extract] truncated_output (model=openai:gpt-5.2)');
+ expect(err.message).not.toContain('cause=');
+ });
+
+ test('FactsExtractionError omits the cause breadcrumb when cause is not an Error', () => {
+ const err = new FactsExtractionError('provider_error', 'openai:gpt-5.2', 'a raw string cause');
+ expect(err.message).not.toContain('cause=');
+ // The raw cause still stays reachable for local debugging.
+ expect((err as { cause?: unknown }).cause).toBe('a raw string cause');
+ });
});
diff --git a/test/facts-backstop.test.ts b/test/facts-backstop.test.ts
index faac6c766e..92ed198458 100644
--- a/test/facts-backstop.test.ts
+++ b/test/facts-backstop.test.ts
@@ -21,6 +21,9 @@ import {
type ChatResult,
} from '../src/core/ai/gateway.ts';
import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';
let engine: PGLiteEngine;
@@ -408,3 +411,53 @@ describe('runFactsBackstop — sync.write_through opt-out', () => {
}
});
});
+
+// #4870: the durable facts-absorb payload carries the writer's notabilityFilter
+// verbatim (backstop.ts), but the minion handler (commands/jobs.ts) is the only
+// reader of that value — it must honor every value the ctx union permits, not
+// collapse everything but 'high-only' to 'all'. Drive the registered handler
+// directly with a queued 'medium-and-up' payload (reachable at stock master via
+// `gbrain jobs submit facts-absorb --params ...`).
+describe('facts-absorb minion handler honors the queued notabilityFilter (#4870)', () => {
+ test("a queued 'medium-and-up' payload persists high+medium and drops low", async () => {
+ const worker = new MinionWorker(engine, { queue: 'test' });
+ await registerBuiltinHandlers(worker, engine, { quiet: true });
+ const handler = worker.getHandler('facts-absorb');
+ expect(handler).toBeDefined();
+
+ const page = meetingPage();
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth) VALUES ($1, 'default', 'meeting', $1, $2)`,
+ [page.slug, LONG_BODY],
+ );
+ chatStub([
+ { fact: 'queued-medium-up-high', kind: 'event', notability: 'high', entity: 'people/queue-test' },
+ { fact: 'queued-medium-up-medium', kind: 'event', notability: 'medium', entity: 'people/queue-test' },
+ { fact: 'queued-medium-up-low', kind: 'event', notability: 'low', entity: 'people/queue-test' },
+ ]);
+ const job: MinionJobContext = {
+ id: 1,
+ name: 'facts-absorb',
+ data: { slug: page.slug, sourceId: 'default', source: 'mcp:put_page', notabilityFilter: 'medium-and-up' },
+ attempts_made: 0,
+ signal: new AbortController().signal,
+ deadlineAtMs: null,
+ shutdownSignal: new AbortController().signal,
+ updateProgress: async () => {},
+ updateTokens: async () => {},
+ log: async () => {},
+ isActive: async () => true,
+ readInbox: async () => [],
+ };
+ await handler!(job);
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ `SELECT fact FROM facts WHERE fact LIKE 'queued-medium-up-%' ORDER BY fact`,
+ );
+ expect(rows.rows.map((r: { fact: string }) => r.fact)).toEqual([
+ 'queued-medium-up-high',
+ 'queued-medium-up-medium',
+ ]);
+ });
+});
diff --git a/test/facts-fence.test.ts b/test/facts-fence.test.ts
index 22aa794feb..758466a474 100644
--- a/test/facts-fence.test.ts
+++ b/test/facts-fence.test.ts
@@ -635,12 +635,60 @@ Prose here.
expect(fenceAt).toBeLessThan(out.indexOf('<!-- timeline -->'));
});
- test('the legacy bare --- + ## Timeline form is deliberately NOT a sentinel (it would false-positive on frontmatter)', () => {
+ // splitBody rule 3 — a bare `---` whose next non-empty line is
+ // `## Timeline` / `## History` — is the shape the recommended page
+ // templates emit. Left unmatched here, the fence was EOF-appended below
+ // that `---` and filed into page.timeline on the next import.
+ test('the legacy bare --- + ## Timeline form IS a sentinel: the fence lands above it', () => {
const body = `# Entity\n\nProse.\n\n---\n\n## Timeline\n- 2020: Founded\n`;
const { body: out } = upsertFactRow(body, newRow);
- // Not recognized → EOF append (after the timeline text), same as "no sentinel".
- expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeGreaterThan(out.indexOf('## Timeline'));
- expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeGreaterThan(out.indexOf('- 2020: Founded'));
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeGreaterThan(out.indexOf('Prose.'));
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeLessThan(out.indexOf('\n---\n'));
+ const split = splitBody(out);
+ expect(split.compiled_truth).toContain(FACTS_FENCE_BEGIN);
+ expect(split.timeline).not.toContain(FACTS_FENCE_BEGIN);
+ expect(split.timeline).toContain('2020: Founded');
+ });
+
+ test('frontmatter + bare --- + ## Timeline: the frontmatter delimiters are skipped, the body --- is the sentinel', () => {
+ const frontmatter = '---\ntype: person\ntitle: Entity\n---\n';
+ const body = `${frontmatter}\n# Entity\n\nProse.\n\n---\n\n## Timeline\n- 2020: Founded\n`;
+ const { body: out } = upsertFactRow(body, newRow);
+ expect(out.startsWith(frontmatter)).toBe(true);
+ const fenceAt = out.indexOf(FACTS_FENCE_BEGIN);
+ expect(fenceAt).toBeGreaterThan(out.indexOf('Prose.'));
+ expect(fenceAt).toBeLessThan(out.indexOf('\n---\n\n## Timeline'));
+ expect(out.split('---\n')).toHaveLength(4); // two frontmatter delimiters + the sentinel, no extra
+ });
+
+ // The frontmatter skip itself: with NO prose between the closing YAML
+ // delimiter and `## Timeline`, an unskipped closing `---` reads as the
+ // legacy bare-`---` sentinel and the fence lands INSIDE the YAML block.
+ test('frontmatter immediately followed by ## Timeline: the fence lands after the frontmatter, never inside the YAML', () => {
+ const frontmatter = '---\ntype: person\n---\n';
+ const body = `${frontmatter}\n## Timeline\n- 2020: Founded\n`;
+ const { body: out } = upsertFactRow(body, newRow);
+ expect(out.startsWith(frontmatter)).toBe(true);
+ expect(out.split(FACTS_FENCE_BEGIN)).toHaveLength(2); // exactly one fence
+ const fenceAt = out.indexOf(FACTS_FENCE_BEGIN);
+ expect(fenceAt).toBeGreaterThan(out.indexOf('\n---\n')); // below the closing delimiter
+ });
+
+ test('empty frontmatter (bare --- / ---) immediately followed by ## History: fence after the block, never between the delimiters', () => {
+ const frontmatter = '---\n---\n';
+ const body = `${frontmatter}\n## History\n- 1999: Started\n`;
+ const { body: out } = upsertFactRow(body, newRow);
+ expect(out.startsWith(frontmatter)).toBe(true);
+ expect(out.split(FACTS_FENCE_BEGIN)).toHaveLength(2); // exactly one fence
+ const fenceAt = out.indexOf(FACTS_FENCE_BEGIN);
+ expect(fenceAt).toBeGreaterThan(out.indexOf('\n---\n'));
+ });
+
+ test('a bare --- horizontal rule with no ## Timeline after it is NOT a sentinel', () => {
+ const body = `# Entity\n\nProse.\n\n---\n\nMore prose.\n`;
+ const { body: out } = upsertFactRow(body, newRow);
+ expect(out.indexOf(FACTS_FENCE_BEGIN)).toBeGreaterThan(out.indexOf('More prose.'));
+ expect(out.split('---\n')).toHaveLength(2);
});
test('CRLF body: the sentinel line is recognized and the fence lands above it, tail preserved', () => {
diff --git a/test/facts-recall-since-composition.test.ts b/test/facts-recall-since-composition.test.ts
new file mode 100644
index 0000000000..d4a98129c8
--- /dev/null
+++ b/test/facts-recall-since-composition.test.ts
@@ -0,0 +1,213 @@
+/**
+ * `recall` composes `entity`, `session_id` and `since` into ONE engine query.
+ *
+ * The op used to branch `entity` > `session_id` > `since` as an if / else-if
+ * chain: with `entity` set the `since` window was never applied (the entity
+ * arm called listFactsByEntity without a cutoff), and `session_id` + `since`
+ * had the same shape. A caller asking for "facts about X since T" silently
+ * got every fact about X. An unparseable `since` was swallowed the same way
+ * (an empty or unfiltered result instead of an error).
+ *
+ * Pinned here, through the real op via dispatchToolCall and through the CLI's
+ * local fetch path:
+ * - entity + since excludes facts older than the cutoff
+ * - session_id + since likewise, and entity + session_id + since AND together
+ * - the window is EVENT time (COALESCE(valid_from, created_at)), same as the
+ * since-only arm, so a backdated row drops out even though it was written now
+ * - the boundary is inclusive at the cutoff
+ * - the cutoff lands before the SQL LIMIT: a limit never refills with rows
+ * from outside the window
+ * - an unparseable since is rejected with invalid_params
+ * - the CLI's entity-TEXT fallback (a bare positional that resolves to no
+ * entity is retried as a fact-text grep, #4720) keeps the window: an
+ * explicit `--since` on event time, `--since-last-run` on the cursor's
+ * creation-time watermark. Without it a windowed recall for an unknown
+ * term returned the term's whole history.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { rmSync } from 'node:fs';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { runRecall } from '../src/commands/recall.ts';
+import { writeCursor } from '../src/core/recall-cursor-state.ts';
+import { withEnv, emptyHome } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+const HOUR = 60 * 60 * 1000;
+const DAY = 24 * HOUR;
+const NOW = Date.now();
+// Fixed cutoff for the boundary test (well inside every "48 hours ago" window).
+const CUTOFF = new Date(NOW - 2 * HOUR);
+// GBRAIN_HOME for the --since-last-run case (the cursor file lives under it).
+const cursorHome = emptyHome();
+
+async function seed(fact: string, opts: { entity?: string; session?: string; validFrom: Date }): Promise<void> {
+ await engine.insertFact(
+ {
+ fact,
+ kind: 'fact',
+ entity_slug: opts.entity,
+ source: 'test',
+ source_session: opts.session,
+ valid_from: opts.validFrom,
+ visibility: 'world',
+ },
+ { source_id: 'default' },
+ );
+}
+
+async function recallFacts(params: Record<string, unknown>): Promise<string[]> {
+ const result = await dispatchToolCall(engine, 'recall', params, { remote: false, sourceId: 'default' });
+ expect(result.isError).toBeFalsy();
+ const payload = JSON.parse(result.content[0].text);
+ return (payload.facts as { fact: string }[]).map((f) => f.fact);
+}
+
+async function recallCli(args: string[], home = emptyHome()): Promise<string[]> {
+ const origWrite = process.stdout.write;
+ let captured = '';
+ process.stdout.write = ((chunk: string | Uint8Array) => {
+ captured += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString();
+ return true;
+ }) as typeof process.stdout.write;
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await runRecall(engine, [...args, '--json']);
+ });
+ } finally {
+ process.stdout.write = origWrite;
+ }
+ const payload = JSON.parse(captured.trim());
+ return (payload.facts as { fact: string }[]).map((f) => f.fact);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ // Every row is CREATED now; only valid_from (event time) differs, so a
+ // creation-time window would keep all of them.
+ await seed('window-entity-recent', { entity: 'ent-window', validFrom: new Date(NOW - HOUR) });
+ await seed('window-entity-old', { entity: 'ent-window', validFrom: new Date(NOW - 30 * DAY) });
+
+ await seed('window-session-recent', { session: 'sess-window', validFrom: new Date(NOW - HOUR) });
+ await seed('window-session-old', { session: 'sess-window', validFrom: new Date(NOW - 30 * DAY) });
+
+ await seed('triple-match', { entity: 'ent-triple', session: 'sess-a', validFrom: new Date(NOW - HOUR) });
+ await seed('triple-other-session', { entity: 'ent-triple', session: 'sess-b', validFrom: new Date(NOW - HOUR) });
+ await seed('triple-old', { entity: 'ent-triple', session: 'sess-a', validFrom: new Date(NOW - 30 * DAY) });
+
+ await seed('boundary-at-cutoff', { entity: 'ent-boundary', validFrom: CUTOFF });
+ await seed('boundary-before-cutoff', { entity: 'ent-boundary', validFrom: new Date(CUTOFF.getTime() - 1000) });
+
+ await seed('page-in-window', { entity: 'ent-page', validFrom: new Date(NOW - HOUR) });
+ await seed('page-old-1', { entity: 'ent-page', validFrom: new Date(NOW - 10 * DAY) });
+ await seed('page-old-2', { entity: 'ent-page', validFrom: new Date(NOW - 20 * DAY) });
+ await seed('page-old-3', { entity: 'ent-page', validFrom: new Date(NOW - 30 * DAY) });
+
+ // Entity-text fallback rows: no entity, the query term only appears in the
+ // TEXT. Same event-time split as above; the old row's created_at is also
+ // backdated so the creation-time (--since-last-run) window excludes it.
+ await seed('textfb-zebrule recent', { validFrom: new Date(NOW - HOUR) });
+ await seed('textfb-zebrule old', { validFrom: new Date(NOW - 10 * DAY) });
+ await engine.executeRaw(
+ `UPDATE facts SET created_at = now() - interval '10 days' WHERE fact = 'textfb-zebrule old'`,
+ );
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(cursorHome, { recursive: true, force: true });
+});
+
+describe('recall op: entity / session_id / since compose before the SQL LIMIT', () => {
+ test('entity + since excludes facts whose event time is older than the cutoff', async () => {
+ const facts = await recallFacts({ entity: 'ent-window', since: '48 hours ago' });
+ expect(facts).toContain('window-entity-recent');
+ expect(facts).not.toContain('window-entity-old');
+ });
+
+ test('entity without since keeps the full entity card', async () => {
+ const facts = await recallFacts({ entity: 'ent-window' });
+ expect(facts).toContain('window-entity-recent');
+ expect(facts).toContain('window-entity-old');
+ });
+
+ test('session_id + since excludes facts whose event time is older than the cutoff', async () => {
+ const facts = await recallFacts({ session_id: 'sess-window', since: '48 hours ago' });
+ expect(facts).toContain('window-session-recent');
+ expect(facts).not.toContain('window-session-old');
+ });
+
+ test('entity + session_id + since AND together', async () => {
+ const facts = await recallFacts({ entity: 'ent-triple', session_id: 'sess-a', since: '48 hours ago' });
+ expect(facts).toEqual(['triple-match']);
+ });
+
+ test('boundary: a fact whose event time equals the cutoff is included, one second earlier is not', async () => {
+ const facts = await recallFacts({ entity: 'ent-boundary', since: CUTOFF.toISOString() });
+ expect(facts).toContain('boundary-at-cutoff');
+ expect(facts).not.toContain('boundary-before-cutoff');
+ });
+
+ test('limit never refills from outside the window (cutoff lands before LIMIT)', async () => {
+ const facts = await recallFacts({ entity: 'ent-page', since: '48 hours ago', limit: 2 });
+ expect(facts).toEqual(['page-in-window']);
+ // Without the window the same limit returns the two newest by event time.
+ const unbounded = await recallFacts({ entity: 'ent-page', limit: 2 });
+ expect(unbounded).toEqual(['page-in-window', 'page-old-1']);
+ });
+
+ test('an unparseable since is rejected with invalid_params instead of widening the window', async () => {
+ for (const params of [
+ { entity: 'ent-window', since: 'sometime last week' },
+ { session_id: 'sess-window', since: 'sometime last week' },
+ { since: 'sometime last week' },
+ ]) {
+ const result = await dispatchToolCall(engine, 'recall', params, { remote: false, sourceId: 'default' });
+ expect(result.isError).toBe(true);
+ const err = JSON.parse(result.content[0].text);
+ expect(err.error).toBe('invalid_params');
+ expect(String(err.message)).toContain('since');
+ }
+ });
+});
+
+describe('engine: listFactsSince composes sessionId in SQL', () => {
+ test('sessionId ANDs onto the event-time window', async () => {
+ const rows = await engine.listFactsSince('default', new Date(NOW - 2 * DAY), {
+ eventTime: true,
+ sessionId: 'sess-a',
+ });
+ expect(rows.map((r) => r.fact)).toEqual(['triple-match']);
+ });
+});
+
+describe('gbrain recall CLI (local path) composes the same way', () => {
+ test('<entity> --since excludes older facts', async () => {
+ const facts = await recallCli(['ent-window', '--since', '48 hours ago']);
+ expect(facts).toContain('window-entity-recent');
+ expect(facts).not.toContain('window-entity-old');
+ });
+
+ test('--session-id --since excludes older facts', async () => {
+ const facts = await recallCli(['--session-id', 'sess-window', '--since', '48 hours ago']);
+ expect(facts).toContain('window-session-recent');
+ expect(facts).not.toContain('window-session-old');
+ });
+});
+
+describe('gbrain recall CLI entity-text fallback honors the window', () => {
+ test('unknown positional + --since matches by text but only inside the event-time window', async () => {
+ // Sanity: without a window the fallback returns the term's full history.
+ expect((await recallCli(['zebrule'])).sort()).toEqual(['textfb-zebrule old', 'textfb-zebrule recent']);
+ expect(await recallCli(['zebrule', '--since', '48 hours ago'])).toEqual(['textfb-zebrule recent']);
+ });
+
+ test('unknown positional + --since-last-run keeps the cursor watermark (creation time)', async () => {
+ await withEnv({ GBRAIN_HOME: cursorHome }, () => writeCursor('default', new Date(NOW - 2 * DAY)));
+ expect(await recallCli(['zebrule', '--since-last-run'], cursorHome)).toEqual(['textfb-zebrule recent']);
+ });
+});
diff --git a/test/facts-thin-client-provenance.test.ts b/test/facts-thin-client-provenance.test.ts
new file mode 100644
index 0000000000..909cc2d4f9
--- /dev/null
+++ b/test/facts-thin-client-provenance.test.ts
@@ -0,0 +1,138 @@
+/**
+ * #4819 — page provenance for facts on a thin-client install.
+ *
+ * With no `sources.local_path` there is no fence lane: every fact the page
+ * backstop extracts goes through the legacy single-row engine.insertFact.
+ * Those rows must keep `source_markdown_slug` NULL — it is the
+ * fence-ownership key `extract_facts` hard-deletes by (deleteFactsForPage),
+ * so populating it gets the row wiped on the next reconcile of a fence-less
+ * page. The page the claim came from therefore rides `facts.context`, the
+ * #4206 provenance carrier. Before the fix the page path never set it, so a
+ * thin-client row had no provenance in either column.
+ *
+ * Real PGLite + the chat-transport stub; no API keys, no network.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, afterEach } 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 { runFactsBackstop, type FactsBackstopCtx } from '../src/core/facts/backstop.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import {
+ __setChatTransportForTests,
+ resetGateway,
+ type ChatResult,
+} from '../src/core/ai/gateway.ts';
+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+
+let engine: PGLiteEngine;
+let pageLockRoot: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ pageLockRoot = mkdtempSync(join(tmpdir(), 'facts-thin-client-provenance-'));
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(pageLockRoot, { recursive: true, force: true });
+});
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ __resetFactsQueueForTests();
+});
+
+// Clears eligibility's MIN_BODY_CHARS (80) for type 'meeting'.
+const LONG_BODY = 'thin-client provenance meeting note about acme-example '.repeat(4);
+
+function chatStub(fact: string) {
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({
+ facts: [{ fact, kind: 'fact', entity: null, confidence: 1.0, notability: 'medium' }],
+ }),
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'test:stub',
+ providerId: 'test',
+ }));
+}
+
+async function backstopPage(slug: string, extra: Partial<FactsBackstopCtx> = {}): Promise<number> {
+ const r = await runFactsBackstop(
+ { slug, type: 'meeting', compiled_truth: LONG_BODY, frontmatter: {} },
+ { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline', ...extra },
+ );
+ expect(r.mode).toBe('inline');
+ if (r.mode !== 'inline') throw new Error('unreachable');
+ expect(r.skipped).toBeUndefined();
+ expect(r.fact_ids).toHaveLength(1);
+ return r.fact_ids[0];
+}
+
+type FactRow = { context: string | null; row_num: number | null; source_markdown_slug: string | null };
+
+async function factRow(id: number): Promise<FactRow> {
+ const rows = await engine.executeRaw<FactRow>(
+ `SELECT context, row_num, source_markdown_slug FROM facts WHERE id = $1`,
+ [id],
+ );
+ expect(rows).toHaveLength(1);
+ return rows[0];
+}
+
+describe('thin-client facts carry page provenance in facts.context (#4819)', () => {
+ test('precondition: a fresh seed leaves sources.local_path NULL for default', async () => {
+ const rows = await engine.executeRaw<{ local_path: string | null }>(
+ `SELECT local_path FROM sources WHERE id = 'default'`,
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].local_path).toBeNull();
+ });
+
+ test('legacy DB-only insert: context = page slug, source_markdown_slug stays NULL', async () => {
+ chatStub('thin-client provenance fact one');
+ const slug = 'meetings/provenance-alice-example';
+ const row = await factRow(await backstopPage(slug));
+ // Legacy-path preconditions: no fence row number, and the fence-ownership
+ // key stays NULL (guards against the "fill the INSERT column" anti-fix
+ // that makes extract_facts hard-delete the row).
+ expect(row.row_num).toBeNull();
+ expect(row.source_markdown_slug).toBeNull();
+ // The defect: no page provenance anywhere. Fixed = the page slug in context.
+ expect(row.context).toBe(slug);
+ });
+
+ test('a caller-supplied sourceSlug still wins over the page slug', async () => {
+ chatStub('thin-client provenance fact two');
+ const row = await factRow(
+ await backstopPage('meetings/provenance-bob-example', { sourceSlug: 'transcripts/session-1' }),
+ );
+ expect(row.context).toBe('transcripts/session-1');
+ });
+
+ test('the row survives an extract_facts reconcile of its fence-less page', async () => {
+ chatStub('thin-client provenance fact three');
+ const slug = 'meetings/provenance-reconcile-acme-example';
+ await engine.putPage(slug, {
+ title: slug,
+ type: 'meeting',
+ compiled_truth: LONG_BODY,
+ frontmatter: {},
+ timeline: '',
+ });
+ const id = await backstopPage(slug);
+ await runExtractFacts(engine, { slugs: [slug], sourceId: 'default', pageLockRoot });
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT COUNT(*)::text AS n FROM facts WHERE id = $1`,
+ [id],
+ );
+ expect(Number(rows[0].n)).toBe(1);
+ });
+});
diff --git a/test/facts-unknown-speaker-gate.test.ts b/test/facts-unknown-speaker-gate.test.ts
index ca5ab1bb3b..ff13984565 100644
--- a/test/facts-unknown-speaker-gate.test.ts
+++ b/test/facts-unknown-speaker-gate.test.ts
@@ -8,9 +8,10 @@
* confident attribution to someone we cannot identify.
*
* `isUnknownSpeakerLabel` is the deterministic gate the candidate loop uses to
- * null ONLY that self-referential attribution. We test the pure predicate
- * directly (the full extractor loop needs a live LLM; mirroring the existing
- * facts-extract tests, we never call a model here).
+ * null ONLY that self-referential attribution. The predicate is tested directly;
+ * the choke-point wiring (incl. the #4755 null-like-string gate) is pinned by
+ * driving `extractFactsFromTurnWithOutcome` through the chat-transport stub, so
+ * the assertions hit the real candidate loop, never a file-local mirror of it.
*
* POSITIVE (bug repro — fails before the fix, the symbol/gate did not exist):
* anonymous-speaker label → true → loop nulls entity.
@@ -19,8 +20,9 @@
* is preserved exactly as upstream does today.
*/
-import { describe, test, expect } from 'bun:test';
-import { isUnknownSpeakerLabel } from '../src/core/facts/extract.ts';
+import { describe, test, expect, afterEach } from 'bun:test';
+import { isUnknownSpeakerLabel, extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';
+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
describe('isUnknownSpeakerLabel — POSITIVE (anonymous-speaker tokens → nulled)', () => {
const anonymous = [
@@ -83,25 +85,55 @@ describe('isUnknownSpeakerLabel — NEGATIVE (real entities preserved; guard aga
}
});
-describe('gate semantics at the choke point (entity mapping)', () => {
- // Mirrors the exact expression in extractFactsFromTurn's candidate loop:
- // entity_slug: isUnknownSpeakerLabel(candidate.entity) ? null : (candidate.entity ?? null)
- const mapEntity = (entity: string | null | undefined): string | null =>
- isUnknownSpeakerLabel(entity) ? null : (entity ?? null);
+describe('gate semantics at the choke point (extractFactsFromTurnWithOutcome)', () => {
+ afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ });
+
+ // Drives the REAL candidate loop: the chat-transport stub returns one
+ // candidate per entity and we read back the `entity_slug` the extractor
+ // emitted. No engine (every config reader defaults without one), no network.
+ async function emittedEntitySlugs(entities: Array<string | null>): Promise<Array<string | null>> {
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({
+ facts: entities.map((entity, i) => ({
+ fact: `acme-example shipped release ${i + 1} of the widget`,
+ kind: 'fact',
+ entity,
+ confidence: 1.0,
+ notability: 'medium',
+ })),
+ }),
+ blocks: [],
+ stopReason: 'end',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'test:stub',
+ providerId: 'test',
+ }));
+ const outcome = await extractFactsFromTurnWithOutcome({ turnText: 'a conversation turn', source: 'test' });
+ if (!outcome.ok) throw new Error(`extraction skipped: ${outcome.reason}`);
+ expect(outcome.facts.length).toBe(entities.length);
+ return outcome.facts.map(f => f.entity_slug);
+ }
+
+ test('(#4755) null-like placeholder strings → entity nulled; real names preserved', async () => {
+ expect(await emittedEntitySlugs(['null', 'None', 'n/a', 'undefined', 'people/alice-example', 'Nullsoft']))
+ .toEqual([null, null, null, null, 'people/alice-example', 'Nullsoft']);
+ });
- test('(a) first-person self-assertion from anonymous speaker → entity nulled', () => {
+ test('(a) first-person self-assertion from anonymous speaker → entity nulled', async () => {
// LLM echoed the speaker label as the entity for "Speaker A: I'm joining Acme".
- expect(mapEntity('Speaker A')).toBeNull();
+ expect(await emittedEntitySlugs(['Speaker A'])).toEqual([null]);
});
- test('(b) third-person fact from anonymous speaker → entity preserved', () => {
+ test('(b) third-person fact from anonymous speaker → entity preserved', async () => {
// "Speaker A: Acme raised $5M" → entity=acme is CORRECT regardless of speaker.
- expect(mapEntity('acme')).toBe('acme');
- expect(mapEntity('companies/acme')).toBe('companies/acme');
+ expect(await emittedEntitySlugs(['acme', 'companies/acme'])).toEqual(['acme', 'companies/acme']);
});
- test('first-person assertion from a NAMED speaker → attribution preserved', () => {
- // "Anton: I'm joining Acme" → entity=Anton is legitimate.
- expect(mapEntity('Anton')).toBe('Anton');
+ test('first-person assertion from a NAMED speaker → attribution preserved', async () => {
+ // "Charlie: I'm joining Acme" → entity=people/charlie-example is legitimate.
+ expect(await emittedEntitySlugs(['people/charlie-example'])).toEqual(['people/charlie-example']);
});
});
diff --git a/test/features-no-sync.test.ts b/test/features-no-sync.test.ts
new file mode 100644
index 0000000000..bec4bee1b1
--- /dev/null
+++ b/test/features-no-sync.test.ts
@@ -0,0 +1,53 @@
+/**
+ * #4767 — `gbrain features`' "Configure Sync" recommendation must key on the
+ * sources table (modern sync anchors on `sources.local_path`), not only on the
+ * legacy global `sync.repo_path` key, which non-default sources never set. A
+ * multi-source brain with N healthy syncing sources was told it is "not
+ * syncing from git" and pointed at `gbrain sync --repo <path>`.
+ */
+import { describe, expect, test } from 'bun:test';
+import { scanFeatures } from '../src/commands/features.ts';
+import type { BrainEngine, SourceRow } from '../src/core/engine.ts';
+
+// A healthy, populated brain so the sync branch is the only variable.
+function mk(legacyRepo: string | null, sources: SourceRow[], calls: string[] = []): BrainEngine {
+ return {
+ getStats: async () => ({ page_count: 100, link_count: 50, timeline_entry_count: 20 }),
+ getHealth: async () => ({ missing_embeddings: 0, dead_links: 0, embed_coverage: 1, brain_score: 80 }),
+ getConfig: async (key: string) => (key === 'sync.repo_path' ? legacyRepo : null),
+ // Mirrors the real engines: `localPathOnly` drops rows whose local_path is NULL.
+ listAllSources: async (opts?: { localPathOnly?: boolean }) => {
+ calls.push('listAllSources');
+ return opts?.localPathOnly === true ? sources.filter((s) => s.local_path !== null) : sources;
+ },
+ } as unknown as BrainEngine;
+}
+
+const noSync = async (engine: BrainEngine) =>
+ (await scanFeatures(engine)).recommendations.find((r) => r.id === 'no-sync');
+
+describe('#4767: Configure Sync keys on sources.local_path, not only the legacy key', () => {
+ test('a brain whose synced sources are non-default rows is NOT told it is not syncing', async () => {
+ const wiki: SourceRow = { id: 'wiki', name: 'wiki', local_path: '/tmp/wiki', last_sync_at: null, config: {} };
+ expect(await noSync(mk(null, [wiki]))).toBeUndefined();
+ });
+
+ test('no legacy key and no source with a local_path still recommends Configure Sync', async () => {
+ const rec = await noSync(mk(null, []));
+ expect(rec).toBeDefined();
+ expect(rec!.title).toBe('Configure Sync');
+ });
+
+ test('a lone source with NULL local_path (pure-DB, never synced) still recommends Configure Sync', async () => {
+ const dbOnly: SourceRow = { id: 'notes', name: 'notes', local_path: null, last_sync_at: null, config: {} };
+ const rec = await noSync(mk(null, [dbOnly]));
+ expect(rec).toBeDefined();
+ expect(rec!.title).toBe('Configure Sync');
+ });
+
+ test('the legacy sync.repo_path short-circuits without consulting the sources table', async () => {
+ const calls: string[] = [];
+ expect(await noSync(mk('/some/repo', [], calls))).toBeUndefined();
+ expect(calls).toEqual([]);
+ });
+});
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index 3efa91671c..68057d1a6d 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -26,6 +26,7 @@ import { forgetFactInFence } from '../src/core/facts/forget.ts';
import { readRecentStubGuardEvents } from '../src/core/facts/stub-guard-audit.ts';
import { writeSingleFact, isNullLikeEntity } from '../src/core/facts/write-single.ts';
import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { importFromContent } from '../src/core/import-file.ts';
import { resetGateway } from '../src/core/ai/gateway.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -181,6 +182,34 @@ describe('writeFactsToFence — happy path', () => {
expect(body).toContain('Founded Widgets Inc.');
});
+ test('#4872 mirrors the rewritten file into pages.compiled_truth; the next sync re-chunks the new row', async () => {
+ const filePath = join(brainDir, 'people/bob.md');
+ mkdirSync(join(brainDir, 'people'), { recursive: true });
+ const file = '---\ntype: person\ntitle: Bob\nslug: people/bob\n---\n\n# Bob\n\nMet at YC W22.\n';
+ writeFileSync(filePath, file, 'utf-8');
+ expect((await importFromContent(engine, 'people/bob', file, { noEmbed: true, sourceId: 'default' })).status).toBe('imported');
+
+ const result = await writeFactsToFence(
+ engine,
+ { sourceId: 'default', localPath: brainDir, slug: 'people/bob', resolutionSource: 'exact_page' },
+ [baseInput({ fact: 'Founded Widgets Inc.' })],
+ );
+ expect(result.inserted).toBe(1);
+
+ // The DB body get_page / the reconcile read must carry the row remember
+ // just reported stored — otherwise a get→put round-trip flattens it away.
+ const page = await engine.getPage('people/bob', { sourceId: 'default' });
+ expect(page!.compiled_truth).toContain('Founded Widgets Inc.');
+ expect(page!.compiled_truth).toContain('Met at YC W22.');
+ // The mirror is body-only (content_chunks untouched), so it must NOT
+ // claim the importer's hash: the next sync has to see the file as changed
+ // and re-chunk, or search never indexes the remembered row (wave review).
+ const imp = await importFromContent(engine, 'people/bob', readFileSync(filePath, 'utf-8'), { noEmbed: true, sourceId: 'default' });
+ expect(imp.status).toBe('imported');
+ const chunks = await engine.getChunks('people/bob', { sourceId: 'default', requireSafeChunks: true });
+ expect(chunks.map((c) => c.chunk_text).join('\n')).toContain('Founded Widgets Inc.');
+ });
+
test('multi-fact batch appends consecutive row_nums', async () => {
const result = await writeFactsToFence(
engine,
@@ -894,3 +923,23 @@ afterAll(() => {
/* best-effort */
}
});
+
+describe('writeFactsToFence — DB-body mirror never persists an empty content_hash (wave review)', () => {
+ test('a page row with no content_hash gets a non-empty one from the mirror', async () => {
+ const target = { sourceId: 'default', localPath: brainDir, slug: 'people/hashless', resolutionSource: 'exact_page' as const };
+ await writeFactsToFence(engine, target, [baseInput()]);
+ // The fence writer only stub-creates the FILE; sync creates the row. Import
+ // it, then drop the hash to model a row that lost it.
+ const stub = readFileSync(join(brainDir, 'people/hashless.md'), 'utf-8');
+ await importFromContent(engine, 'people/hashless', stub, { noEmbed: true, sourceId: 'default' });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(`UPDATE pages SET content_hash = NULL WHERE slug = 'people/hashless'`);
+
+ const r = await writeFactsToFence(engine, target, [baseInput({ fact: 'Raised a seed round' })]);
+ expect(r.inserted).toBe(1);
+ const page = await engine.getPage('people/hashless', { sourceId: 'default' });
+ expect(page?.compiled_truth).toContain('Raised a seed round');
+ expect(typeof page?.content_hash).toBe('string');
+ expect(page!.content_hash!.length).toBeGreaterThan(0);
+ });
+});
diff --git a/test/forget-reconcile-durability.test.ts b/test/forget-reconcile-durability.test.ts
new file mode 100644
index 0000000000..aeba05f67e
--- /dev/null
+++ b/test/forget-reconcile-durability.test.ts
@@ -0,0 +1,183 @@
+/**
+ * #4696 — a forgotten fact must stay forgotten across the extract_facts
+ * reconcile.
+ *
+ * The reconcile reads `pages.compiled_truth`, not the .md file. forget used
+ * to rewrite the file (fence path) or only expire the DB row (legacy path)
+ * and leave the DB body advertising the row live, so the next reconcile saw
+ * fence-live/row-expired drift and re-inserted the claim active at the same
+ * row_num. Both paths now strike the row in the DB body too.
+ *
+ * Real PGLite; no LLM, no network.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { forgetFactInFence } from '../src/core/facts/forget.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { acquirePageLock } from '../src/core/page-lock.ts';
+
+let engine: PGLiteEngine;
+let brainDir: string;
+
+const SLUG = 'people/alice-example';
+// Two frontmatter keys + tags on purpose: pages.frontmatter is JSONB (key
+// order normalized), so any hash the strike computed could never match the
+// importer's — the mirror must leave the row's content_hash alone.
+const FILE = `---
+title: Alice Example
+type: person
+tags: [founder, example]
+---
+# Alice Example
+
+Body.
+
+## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | Founded acme-example | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |
+<!--- gbrain:facts:end -->
+`;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ brainDir = mkdtempSync(join(tmpdir(), 'forget-reconcile-'));
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(brainDir, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts');
+ await engine.executeRaw('DELETE FROM pages');
+ rmSync(join(brainDir, 'people'), { recursive: true, force: true });
+});
+
+/** Import the page from its file, reconcile once, return the seeded fact id. */
+async function seed(): Promise<number> {
+ mkdirSync(join(brainDir, 'people'), { recursive: true });
+ writeFileSync(join(brainDir, `${SLUG}.md`), FILE, 'utf-8');
+ const imp = await importFromContent(engine, SLUG, FILE, { noEmbed: true, sourceId: 'default' });
+ expect(imp.status).toBe('imported');
+ await runExtractFacts(engine, { slugs: [SLUG] });
+ const rows = await factRows();
+ expect(rows.length).toBe(1);
+ expect(rows[0].expired_at).toBeNull();
+ return Number(rows[0].id);
+}
+
+function factRows() {
+ return engine.executeRaw<{ id: number; expired_at: Date | null }>(
+ `SELECT id, expired_at FROM facts WHERE source_markdown_slug = $1 ORDER BY id`,
+ [SLUG],
+ );
+}
+
+async function expectForgetHeld(id: number): Promise<void> {
+ const page = await engine.getPage(SLUG, { sourceId: 'default' });
+ expect(page!.compiled_truth).toContain('~~Founded acme-example~~');
+
+ await runExtractFacts(engine, { slugs: [SLUG] });
+
+ const rows = await factRows();
+ expect(rows.length).toBe(1);
+ expect(Number(rows[0].id)).toBe(id); // same row, not a re-inserted twin
+ expect(rows[0].expired_at).not.toBeNull();
+}
+
+describe('forget survives the extract_facts reconcile (#4696)', () => {
+ test('fence path: the DB body is struck, so the reconcile is a no-op', async () => {
+ const id = await seed();
+ const r = await forgetFactInFence(engine, id, { reason: 'test' });
+ expect(r).toMatchObject({ ok: true, path: 'fence' });
+ await expectForgetHeld(id);
+ });
+
+ test('fence path: the next sync re-imports and re-chunks the struck row', async () => {
+ const id = await seed();
+ await forgetFactInFence(engine, id, { reason: 'test' });
+ const struck = readFileSync(join(brainDir, `${SLUG}.md`), 'utf-8');
+ expect(struck).toContain('~~Founded acme-example~~');
+ // The DB-body strike leaves content_chunks untouched, so it must not
+ // claim the importer's hash: sync has to re-chunk or the struck claim
+ // keeps surfacing verbatim in chunk search (wave review).
+ const imp = await importFromContent(engine, SLUG, struck, { noEmbed: true, sourceId: 'default' });
+ expect(imp.status).toBe('imported');
+ const chunks = await engine.getChunks(SLUG, { sourceId: 'default', requireSafeChunks: true });
+ expect(chunks.map((c) => c.chunk_text).join('\n')).toContain('~~Founded acme-example~~');
+ });
+
+ test('legacy path (file gone): the DB body is struck, so the reconcile is a no-op', async () => {
+ const id = await seed();
+ rmSync(join(brainDir, `${SLUG}.md`));
+ const r = await forgetFactInFence(engine, id, { reason: 'test' });
+ expect(r).toMatchObject({ ok: true, path: 'legacy_db' });
+ await expectForgetHeld(id);
+ });
+});
+
+// ─── wave review: legacy-tier hash, page lock, never an empty hash ──
+describe('forget DB-body mirror — hash + lock discipline (wave review)', () => {
+ test('legacy path (no local_path): the row stops claiming the unchanged file\'s hash, so the next sync re-imports', async () => {
+ // The legacy tier does NOT rewrite the file. Keeping the importer's hash
+ // on the struck row made the next sync `skipped` the page: the DB body
+ // said struck while content_chunks kept the live claim, forever.
+ const id = await seed();
+ const before = (await engine.getPage(SLUG, { sourceId: 'default' }))!.content_hash;
+ await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
+ try {
+ const r = await forgetFactInFence(engine, id, { reason: 'test' });
+ expect(r).toMatchObject({ ok: true, path: 'legacy_db' });
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ expect(page.compiled_truth).toContain('~~Founded acme-example~~');
+ expect(page.content_hash).toBeTruthy();
+ expect(page.content_hash).not.toBe(before);
+ // The importer's own idempotency check: same file bytes must now re-import.
+ const imp = await importFromContent(engine, SLUG, FILE, { noEmbed: true, sourceId: 'default' });
+ expect(imp.status).toBe('imported');
+ } finally {
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [brainDir]);
+ }
+ });
+
+ test('legacy path honors the page lock: a live holder defers the DB-body strike (Codex P1)', async () => {
+ // strikeDbBody is a read-modify-write on pages.compiled_truth; the fence
+ // writers hold the per-page lock around theirs. Pre-fix the legacy tier
+ // ran it lock-free and could clobber a concurrent fence write.
+ const id = await seed();
+ rmSync(join(brainDir, `${SLUG}.md`));
+ const handle = await acquirePageLock(SLUG, { timeoutMs: 0 });
+ expect(handle).not.toBeNull();
+ try {
+ const r = await forgetFactInFence(engine, id, { reason: 'test' });
+ expect(r).toMatchObject({ ok: true, path: 'legacy_db' }); // the facts row still expires
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ expect(page.compiled_truth).not.toContain('~~'); // strike waited on the lock and gave up
+ } finally {
+ await handle!.release();
+ }
+ }, 20_000);
+
+ test('fence path never persists an empty content_hash', async () => {
+ const id = await seed();
+ await engine.executeRaw(`UPDATE pages SET content_hash = NULL WHERE slug = $1 AND source_id = 'default'`, [SLUG]);
+ const r = await forgetFactInFence(engine, id, { reason: 'test' });
+ expect(r).toMatchObject({ ok: true, path: 'fence' });
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ expect(page.compiled_truth).toContain('~~Founded acme-example~~');
+ expect(typeof page.content_hash).toBe('string');
+ expect(page.content_hash!.length).toBeGreaterThan(0);
+ });
+});
diff --git a/test/frontmatter-cli.test.ts b/test/frontmatter-cli.test.ts
index 0484d99448..c5a13577e1 100644
--- a/test/frontmatter-cli.test.ts
+++ b/test/frontmatter-cli.test.ts
@@ -218,6 +218,32 @@ describe('gbrain frontmatter CLI (B4)', () => {
});
});
+ test('generate --fix on a BOM-prefixed file infers the heading title and writes a BOM-free body (#4798)', async () => {
+ // Under `docs/guides/` the rule's titleStrategy is `heading`, so the title
+ // comes from `# …`. A leading U+FEFF used to defeat the `^#` match (title
+ // fell back to the filename) and then get written back INSIDE the body,
+ // diverging from what `gbrain sync` / `import` produce.
+ const dir = join(tmp, 'docs', 'guides');
+ mkdirSync(dir, { recursive: true });
+ const f = join(dir, 'bom-example.md');
+ writeFileSync(f, '\uFEFF# Title From Heading\n\nbody');
+
+ await withEnv({ GBRAIN_HOME: join(tmp, 'home') }, async () => {
+ const { out, verdict } = await runFm(['generate', tmp, '--fix', '--json']);
+ expect(verdict).toBe(0);
+ const env = JSON.parse(out);
+ expect(env.generated).toBe(1);
+ expect(env.written).toBe(1);
+ expect(env.results[0].title).toBe('Title From Heading');
+ });
+
+ const written = readFileSync(f, 'utf8');
+ expect(written).not.toContain('\uFEFF');
+ expect(written.startsWith('---\n')).toBe(true);
+ expect(written).toContain('title: Title From Heading');
+ expect(written.endsWith('\n# Title From Heading\n\nbody')).toBe(true);
+ });
+
test('validate missing path errors clearly', async () => {
const { err, verdict } = await runFm(['validate', join(tmp, 'does-not-exist.md')]);
expect(verdict).toBe(1);
diff --git a/test/get-page-unknown-source-4620.test.ts b/test/get-page-unknown-source-4620.test.ts
new file mode 100644
index 0000000000..8efbb62db8
--- /dev/null
+++ b/test/get-page-unknown-source-4620.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #4620 — an EXPLICIT per-call `source_id` that names a removed or archived
+ * source fails loudly (`unknown_source`) instead of silently scoping the read
+ * to a source with no rows and answering `page_not_found` (with a soft-delete
+ * hint pointing the wrong way) or `[]`. The #1712 rule (an explicit source
+ * that fails to resolve errors loudly), applied to the op path.
+ *
+ * Reachable in the wild: `oauth_clients.federated_read` has no FK, so a grant
+ * (and a client-side `.gbrain-source` dotfile) keeps naming a source after
+ * `sources remove`, and the thin client pins that id onto every op's
+ * `source_id`. The check runs AFTER resolveRequestedScope's grant check, so
+ * it can only name a source the caller was already granted — never a
+ * cross-grant existence oracle.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const op = (name: string) => operations.find(o => o.name === name)!;
+const DEAD = 'scratch-src';
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default', DEAD] },
+ ...overrides,
+ } as OperationContext;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.putPage(
+ 'notes/example-page',
+ { title: 'Example', type: 'note', compiled_truth: '# Example\n\nlives in default\n' },
+ { sourceId: 'default' },
+ );
+ // Register, then remove: the grant above still names the dead id.
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('${DEAD}', 'scratch')`);
+ await engine.executeRaw(`DELETE FROM sources WHERE id = '${DEAD}'`);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('explicit source_id naming a removed source (#4620)', () => {
+ test('get_page → unknown_source, not page_not_found with a soft-delete hint', async () => {
+ await expect(op('get_page').handler(ctxOf(), { slug: 'notes/example-page', source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ });
+
+ test('list_pages → unknown_source, not a silent []', async () => {
+ await expect(op('list_pages').handler(ctxOf(), { source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ });
+
+ test('search / query → unknown_source, not a silent []', async () => {
+ await expect(op('search').handler(ctxOf(), { query: 'example', source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ await expect(op('query').handler(ctxOf(), { query: 'example', source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ });
+
+ test('an archived source counts as gone (matches the CLI assertSourceExists rule)', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, archived) VALUES ('${DEAD}', 'scratch', true)`);
+ try {
+ await expect(op('get_page').handler(ctxOf(), { slug: 'notes/example-page', source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ } finally {
+ await engine.executeRaw(`DELETE FROM sources WHERE id = '${DEAD}'`);
+ }
+ });
+
+ test('trusted local caller gets the same loud error (#1712 is not a remote-only rule)', async () => {
+ await expect(op('get_page').handler(ctxOf({ remote: false, auth: undefined }), { slug: 'notes/example-page', source_id: DEAD }))
+ .rejects.toMatchObject({ code: 'unknown_source' });
+ });
+});
+
+describe('unchanged paths (#4620 guards)', () => {
+ test('a live explicit source_id still reads the page', async () => {
+ const page = await op('get_page').handler(ctxOf(), { slug: 'notes/example-page', source_id: 'default' }) as { slug: string };
+ expect(page.slug).toBe('notes/example-page');
+ });
+
+ test("'__all__' still resolves to the grant without an existence check", async () => {
+ const page = await op('get_page').handler(ctxOf(), { slug: 'notes/example-page', source_id: '__all__' }) as { slug: string };
+ expect(page.slug).toBe('notes/example-page');
+ });
+
+ test('an out-of-grant source_id is still permission_denied (grant check runs first)', async () => {
+ await expect(op('get_page').handler(ctxOf(), { slug: 'notes/example-page', source_id: 'other' }))
+ .rejects.toMatchObject({ code: 'permission_denied' });
+ });
+
+ test('a genuinely missing page in a live source keeps page_not_found', async () => {
+ await expect(op('get_page').handler(ctxOf(), { slug: 'notes/nope', source_id: 'default' }))
+ .rejects.toMatchObject({ code: 'page_not_found' });
+ });
+});
diff --git a/test/google-clients.test.ts b/test/google-clients.test.ts
index 84eb86662d..fd7c9ff890 100644
--- a/test/google-clients.test.ts
+++ b/test/google-clients.test.ts
@@ -28,6 +28,7 @@ import {
GoogleApiClient,
GoogleCursorExpiredError,
PeopleClient,
+ rateLimitBackoffMs,
type FetchImpl,
} from '../src/core/google/google-clients.ts';
@@ -231,6 +232,27 @@ function b64url(s: string): string {
return Buffer.from(s, 'utf-8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
+// ── rateLimitBackoffMs (pure) ────────────────────────────────────────────────
+
+describe('rateLimitBackoffMs', () => {
+ test('stays within [half, base] of the exponential-backoff schedule and never exceeds the 60s cap', () => {
+ // attempt 0: base=2000, half=1000 → [1000, 2000]
+ // attempt 4: base=32000, half=16000 → [16000, 32000]
+ // attempt 10: base would exceed the cap, so base clamps to 60000 → [30000, 60000]
+ for (const [attempt, [lo, hi]] of [
+ [0, [1000, 2000]],
+ [4, [16000, 32000]],
+ [10, [30000, 60000]],
+ ] as const) {
+ for (let i = 0; i < 20; i++) {
+ const ms = rateLimitBackoffMs(attempt);
+ expect(ms).toBeGreaterThanOrEqual(lo);
+ expect(ms).toBeLessThanOrEqual(hi);
+ }
+ }
+ });
+});
+
// ── GoogleApiClient core: auth, retry, error mapping ─────────────────────────
describe('GoogleApiClient request core', () => {
@@ -269,6 +291,34 @@ describe('GoogleApiClient request core', () => {
expect(h.tokenPosts()).toBe(0); // no refresh on a rate limit
});
+ test('429 with NO Retry-After falls back to the jittered backoff: logs a delay inside the attempt-0 bounds, sleeps, retries once', async () => {
+ let apiCalls = 0;
+ const h = makeHarness(() => {
+ apiCalls++;
+ if (apiCalls === 1) return json({ error: { message: 'rate limit' } }, 429); // no retry-after header
+ return json({ ok: true });
+ });
+ const logs: string[] = [];
+ const client = new GoogleApiClient(h.tokens, h.fetchImpl, (m) => logs.push(m));
+ const t0 = Date.now();
+ const body = await client.fetchJSON<{ ok: boolean }>('https://gmail.googleapis.com/gmail/v1/fake', 'gmail', {
+ rateLimitRetries: 1,
+ });
+ const elapsedMs = Date.now() - t0;
+ expect(body.ok).toBe(true);
+ expect(apiCalls).toBe(2); // exactly one retry
+ expect(h.tokenPosts()).toBe(0);
+ // rateLimitBackoffMs(0) ∈ [1000, 2000] → the log's rounded delay is 1s or 2s, never 0s.
+ const line = logs.find((l) => l.startsWith('[google] HTTP 429; retrying in '));
+ expect(line).toBeDefined();
+ expect(line).toContain('(rate limit, attempt 1/1)');
+ const secs = Number(/retrying in (\d+)s/.exec(line ?? '')?.[1]);
+ expect(secs).toBeGreaterThanOrEqual(1);
+ expect(secs).toBeLessThanOrEqual(2);
+ // The jittered sleep really ran (not a fixed 0 delay): at least the lower bound, minus timer slack.
+ expect(elapsedMs).toBeGreaterThanOrEqual(950);
+ });
+
test('403 accessNotConfigured maps to api_not_enabled with the project deep link', async () => {
const h = makeHarness(() =>
json(
@@ -348,7 +398,7 @@ describe('GoogleApiClient request core', () => {
});
describe('GoogleApiClient retry exhaustion + 403 mapping', () => {
- test("always-429 (Retry-After: 0) exhausts the retries and maps to 'rate_limited'", async () => {
+ test("always-429 (Retry-After: 0) exhausts the RATE-LIMIT retry budget (bigger than the plain retry budget) and maps to 'rate_limited'", async () => {
let apiCalls = 0;
const h = makeHarness(() => {
apiCalls++;
@@ -363,11 +413,76 @@ describe('GoogleApiClient retry exhaustion + 403 mapping', () => {
}
expect(thrown).toBeInstanceOf(CredentialError);
expect((thrown as CredentialError).code).toBe('rate_limited');
- // Default retries=2: attempts 0 and 1 are retried, attempt 2 throws.
- expect(apiCalls).toBe(3);
+ // Default rate-limit retries=6 (bigger than the plain retries=2 used for
+ // 401): attempts 0-5 are retried, attempt 6 throws. This is deliberately
+ // MORE patient than a plain retryable failure — the whole point of this
+ // fix (a 403/429 used to give up after 3 calls and poison the thread).
+ expect(apiCalls).toBe(7);
expect(h.tokenPosts()).toBe(0); // a rate limit never triggers a token refresh
});
+ test('always-429 (Retry-After: 0) honors an explicit smaller rateLimitRetries override', async () => {
+ let apiCalls = 0;
+ const h = makeHarness(() => {
+ apiCalls++;
+ return json({ error: { message: 'rate limit' } }, 429, { 'retry-after': '0' });
+ });
+ const client = new GoogleApiClient(h.tokens, h.fetchImpl);
+ let thrown: unknown;
+ try {
+ await client.fetchJSON('https://gmail.googleapis.com/gmail/v1/fake', 'gmail', {
+ rateLimitRetries: 1,
+ });
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(CredentialError);
+ expect((thrown as CredentialError).code).toBe('rate_limited');
+ expect(apiCalls).toBe(2); // attempt 0 retried, attempt 1 throws
+ });
+
+ test('a 403 quota reason gets the same patient rate-limit retry budget as 429', async () => {
+ let apiCalls = 0;
+ const h = makeHarness(() => {
+ apiCalls++;
+ return json(
+ { error: { code: 403, message: 'Quota exceeded', errors: [{ reason: 'quotaExceeded' }] } },
+ 403,
+ { 'retry-after': '0' },
+ );
+ });
+ const client = new GoogleApiClient(h.tokens, h.fetchImpl);
+ let thrown: unknown;
+ try {
+ await client.fetchJSON('https://gmail.googleapis.com/gmail/v1/fake', 'gmail');
+ } catch (e) {
+ thrown = e;
+ }
+ expect((thrown as CredentialError).code).toBe('rate_limited');
+ expect(apiCalls).toBe(7);
+ });
+
+ test('a 401 still exhausts at its OWN (unchanged, smaller) retry budget even though the rate-limit budget is larger', async () => {
+ let apiCalls = 0;
+ const h = makeHarness(() => {
+ apiCalls++;
+ return json({ error: { code: 401, message: 'Invalid Credentials' } }, 401);
+ });
+ const gmail = new GmailClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID);
+ let thrown: unknown;
+ try {
+ await gmail.getProfile();
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(CredentialError);
+ expect((thrown as CredentialError).code).toBe('upstream');
+ // Default retries=2 for 401 (unaffected by the bigger rate-limit budget):
+ // attempts 0 and 1 retried (with a forceRefresh each), attempt 2 throws.
+ expect(apiCalls).toBe(3);
+ expect(h.tokenPosts()).toBe(2);
+ });
+
test("403 with a non-rate, non-quota reason maps to 'upstream' WITHOUT a retry", async () => {
let apiCalls = 0;
const h = makeHarness(() => {
diff --git a/test/google-redirect.test.ts b/test/google-redirect.test.ts
index ca741551cf..b0006c1ed4 100644
--- a/test/google-redirect.test.ts
+++ b/test/google-redirect.test.ts
@@ -98,6 +98,92 @@ describe('parsePastedRedirect', () => {
);
});
+ it('a consent-page URL carrying a stray code= param is still rejected by host, not sniffed as legit', () => {
+ // Guards the fix itself from over-correcting to "has a code param" —
+ // the decision must stay host-based.
+ expectCodeSync(
+ () =>
+ parsePastedRedirect(
+ 'https://accounts.google.com/o/oauth2/v2/auth?client_id=abc&code=4%2Ffake&state=st',
+ ),
+ 'pasted_wrong_url',
+ );
+ });
+
+ it('a scheme-less consent-page URL (address bar without https://) → pasted_wrong_url', () => {
+ // Browsers hide the scheme in the address bar; the paste then misses the
+ // URL branch and must not fall through to the bare-code branch (which
+ // skips the state check and hands the whole consent URL to token exchange).
+ expectCodeSync(
+ () =>
+ parsePastedRedirect(
+ 'accounts.google.com/o/oauth2/v2/auth?client_id=abc&response_type=code&state=st&code_challenge=zzz',
+ 'st',
+ ),
+ 'pasted_wrong_url',
+ );
+ });
+
+ it('consent-host anchor: look-alike hosts are NOT the consent page and proceed to state binding', () => {
+ // The host test is anchored at `^` or a `.` label boundary. A substring
+ // test would reject both of these; they are not accounts.google.com, so a
+ // code-bearing paste from them parses and binds state like any redirect.
+ for (const host of ['myaccounts.google.com', 'accounts.google.com.evil.com']) {
+ const parsed = parsePastedRedirect(`https://${host}/o/oauth2/v2/auth?code=4%2Fabc&state=st`, 'st');
+ expect(parsed.code).toBe('4/abc');
+ expect(parsed.state).toBe('st');
+ expectCodeSync(
+ () => parsePastedRedirect(`https://${host}/o/oauth2/v2/auth?code=4%2Fabc&state=stale`, 'st'),
+ 'state_mismatch',
+ );
+ }
+ });
+
+ it('consent-host anchor: a port or userinfo on the consent host is still the consent page', () => {
+ // Host normalization drops `user@` and `:port` BEFORE the anchored test.
+ // Without that the tail no longer ends in accounts.google.com: the
+ // scheme-less+port paste would fall through to the bare-code branch and
+ // the userinfo paste would parse as a legitimate redirect.
+ expectCodeSync(
+ () =>
+ parsePastedRedirect(
+ 'accounts.google.com:443/o/oauth2/v2/auth?client_id=abc&response_type=code&state=st&code_challenge=zzz',
+ 'st',
+ ),
+ 'pasted_wrong_url',
+ );
+ expectCodeSync(
+ () =>
+ parsePastedRedirect(
+ 'https://[email protected]/o/oauth2/v2/auth?client_id=abc&code=4%2Ffake&state=st',
+ 'st',
+ ),
+ 'pasted_wrong_url',
+ );
+ });
+
+ it('a real loopback redirect carrying RFC 9207 iss=accounts.google.com parses normally (#regression)', () => {
+ // Google's OAuth 2.0 authorization response now appends
+ // `iss=https://accounts.google.com` (OpenID Connect issuer
+ // identification) to EVERY redirect, including legitimate loopback ones.
+ // A substring test over the whole raw paste used to reject these.
+ const parsed = parsePastedRedirect(
+ 'http://127.0.0.1:41999/?state=st&iss=https%3A%2F%2Faccounts.google.com&code=4%2Fabc&scope=email',
+ 'st',
+ );
+ expect(parsed.code).toBe('4/abc');
+ expect(parsed.state).toBe('st');
+ });
+
+ it('a querystring-only paste carrying iss=accounts.google.com also parses normally', () => {
+ const parsed = parsePastedRedirect(
+ 'code=4%2Fabc&state=st&iss=https%3A%2F%2Faccounts.google.com',
+ 'st',
+ );
+ expect(parsed.code).toBe('4/abc');
+ expect(parsed.state).toBe('st');
+ });
+
it('state mismatch → state_mismatch', () => {
expectCodeSync(
() => parsePastedRedirect('http://127.0.0.1:41999/?code=4%2Fabc&state=stale', 'st'),
diff --git a/test/google-source-materialize.test.ts b/test/google-source-materialize.test.ts
index 2425f81fb4..801b2836d1 100644
--- a/test/google-source-materialize.test.ts
+++ b/test/google-source-materialize.test.ts
@@ -91,6 +91,9 @@ interface FakeGoogle {
historyResponseId: string;
historyExpired: boolean;
failThreads: Set<string>;
+ /** Threads that 429 (rate-limited) on every fetch — retry-after: 0 so tests
+ * don't actually sleep through the client's real backoff schedule. */
+ rateLimitThreads: Set<string>;
contacts: unknown[];
contactsDelta: unknown[];
calendarEvents: unknown[];
@@ -111,6 +114,7 @@ function emptyFx(): FakeGoogle {
historyResponseId: '1000',
historyExpired: false,
failThreads: new Set(),
+ rateLimitThreads: new Set(),
contacts: [],
contactsDelta: [],
calendarEvents: [],
@@ -127,8 +131,8 @@ function b64url(s: string): string {
}
function buildFetch(fx: FakeGoogle): FetchImpl {
- const json = (body: unknown, status = 200): Response =>
- new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+ const json = (body: unknown, status = 200, headers: Record<string, string> = {}): Response =>
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } });
return async (url: string): Promise<Response> => {
const u = new URL(url);
@@ -174,6 +178,11 @@ function buildFetch(fx: FakeGoogle): FetchImpl {
fx.threadFetches++;
fx.onThreadFetch?.();
if (fx.failThreads.has(tid)) return json({ error: { code: 500, message: 'backend error' } }, 500);
+ if (fx.rateLimitThreads.has(tid)) {
+ // retry-after: 0 → the client's real (patient) retry loop still
+ // runs its full attempt budget, but with zero actual delay.
+ return json({ error: { message: 'rate limit' } }, 429, { 'retry-after': '0' });
+ }
const msgs = fx.messages
.filter((m) => m.threadId === tid)
.sort((a, b) => b.internalDateMs - a.internalDateMs); // served newest-first
@@ -579,6 +588,47 @@ describe('google-source materialize', () => {
}
});
+ test('delta lane: a rate-limited thread is not poisoned, the sweep stops at it, and the cursor is held (wave review)', async () => {
+ // The backfill loop broke out of a batch on the first rate-limited thread;
+ // the delta loop kept walking every remaining flagged thread through the
+ // client's full retry budget against the same exhausted per-user quota.
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-delta-ratelimit-'));
+ const fx = emptyFx();
+ gmailFixture(fx);
+ const vault = makeVault();
+ try {
+ await insertGoogleSource(dir);
+ await withHome(async () => {
+ await sweep(dir, fx, vault, {}, 'gmail');
+ expect(readGoogleState(dir).gmail_history_id).toBe('1000');
+
+ // History flags A then B; A is throttled on every fetch.
+ fx.history = [[T_A], [T_B]];
+ fx.historyResponseId = '1010';
+ fx.rateLimitThreads.add(T_A);
+ const callsBefore = fx.calls.length;
+
+ const res = await sweep(dir, fx, vault, {}, 'gmail');
+ expect(res.status).toBe('partial');
+ expect(res.failedFiles).toBe(1);
+ const state = readGoogleState(dir);
+ expect(state.gmail_fail_counts?.[T_A]).toBeUndefined(); // never poisoned
+ expect(state.gmail_history_id).toBe('1000'); // cursor held
+ // The sweep stopped at the throttled thread: B (behind A) was not fetched.
+ expect(fx.calls.slice(callsBefore).some((c) => c.includes(`/threads/${T_B}`))).toBe(false);
+
+ // Quota back: the same window drains (unchanged content → up_to_date)
+ // and the cursor advances.
+ fx.rateLimitThreads.clear();
+ const res2 = await sweep(dir, fx, vault, {}, 'gmail');
+ expect(res2.status).not.toBe('partial');
+ expect(readGoogleState(dir).gmail_history_id).toBe('1010');
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('history 404 falls back to a bookmark window and re-anchors a fresh historyId', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gsrc-expired-'));
const fx = emptyFx();
@@ -838,6 +888,69 @@ describe('google-source materialize', () => {
}
});
+ test('rate-limited thread: partial every run like a real failure, but NEVER poisoned — the ledger stays empty across many runs', async () => {
+ // The production bug this pins: a transient 429/403 rate-limit failure
+ // used to count toward MAX_THREAD_FAILURES exactly like a hard failure,
+ // so a burst of rate limiting during a big backfill would poison
+ // (silently skip, without --full) mail that was never actually bad.
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-ratelimit-'));
+ const fx = emptyFx();
+ gmailFixture(fx);
+ // A thread listed BEHIND the rate-limited one in the same batch (older, so
+ // the newest-first listing puts it after T_B).
+ fx.messages.push(
+ gmsg('18c2f4a9b3d21e08', T_C, daysAgoMs(4), {
+ headers: { From: 'Erin Example <[email protected]>', To: '[email protected]', Subject: 'Older thread' },
+ body: 'An older thread behind the rate-limited one.',
+ }),
+ );
+ const vault = makeVault();
+ try {
+ await insertGoogleSource(dir);
+ await withHome(async () => {
+ fx.rateLimitThreads.add(T_B);
+ // Run this MORE times than MAX_THREAD_FAILURES (3) would take to
+ // poison a hard failure — if rate-limit failures were still counted,
+ // run 4 would already skip T_B instead of retrying it.
+ for (let run = 1; run <= 5; run++) {
+ const res = await sweep(dir, fx, vault, {}, 'gmail');
+ expect(res.status).toBe('partial');
+ expect(res.failedFiles).toBe(1);
+ const state = readGoogleState(dir);
+ // The ledger entry for T_B never appears — a rate-limit failure is
+ // never counted toward the poison threshold, no matter how many
+ // times it happens in a row.
+ expect(state.gmail_fail_counts?.[T_B]).toBeUndefined();
+ expect(state.gmail_backfill_done).toBe(false);
+ }
+
+ // The thread was actually FETCHED every run (never skipped as
+ // poisoned) — proof the loop kept retrying it, not silently giving up.
+ const fetchCalls = fx.calls.filter((c) => c.includes(`/threads/${T_B}`));
+ expect(fetchCalls.length).toBeGreaterThan(0);
+ // ...and once one thread in the batch is rate limited, the rest of the
+ // batch is deferred to the next run instead of hammering the same
+ // exhausted quota: T_C (listed behind T_B) is never fetched while T_B
+ // is throttled. Nothing is lost — the floor didn't advance, so the
+ // next run re-lists it.
+ expect(fx.calls.some((c) => c.includes(`/threads/${T_C}`))).toBe(false);
+
+ // Once the rate limit clears, the thread imports normally and the
+ // backfill completes — nothing was permanently lost.
+ fx.rateLimitThreads.clear();
+ const resFinal = await sweep(dir, fx, vault, {}, 'gmail');
+ expect(resFinal.status).toBe('synced');
+ const stateFinal = readGoogleState(dir);
+ expect(stateFinal.gmail_backfill_done).toBe(true);
+ const slugsFinal = await slugsWhere(`slug LIKE 'emails/%'`);
+ expect(slugsFinal.some((s) => s.includes('contract-question'))).toBe(true);
+ expect(slugsFinal.some((s) => s.includes('older-thread'))).toBe(true);
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
test('contacts: bare tombstone deletes by google_contact_id; a rename moves the page; an unknown tombstone is a no-op', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gsrc-contacts-tomb-'));
const fx = emptyFx();
diff --git a/test/graph-query-thin-client-source-flag.serial.test.ts b/test/graph-query-thin-client-source-flag.serial.test.ts
new file mode 100644
index 0000000000..bc9b304348
--- /dev/null
+++ b/test/graph-query-thin-client-source-flag.serial.test.ts
@@ -0,0 +1,127 @@
+/**
+ * `gbrain graph-query --source <id>` on a thin-client install.
+ *
+ * The help text promises "an unknown source is a hard error", and the local
+ * branch honors it. The thin-client branch used to call the remote
+ * `traverse_graph` op (which has no `source_id` param) and silently drop
+ * both `--source` and `--include-foreign`: the grant-wide walk rendered with
+ * exit 0 and no warning, so a user relying on the flag to confirm a source's
+ * isolation got a misleading answer. Now `--source` is rejected (exit 1, same
+ * policy as applyThinClientSourceScope) and `--include-foreign` warns that it
+ * is not forwarded.
+ *
+ * Serial file: mock.module patches live bindings process-wide (config.ts
+ * isThinClient → true; mcp-client.ts callRemoteTool → recorded).
+ */
+import { describe, test, expect, beforeEach, mock } from 'bun:test';
+import { withEnv } from './helpers/with-env.ts';
+
+type Call = { name: string; params: Record<string, unknown> };
+const calls: Call[] = [];
+
+const realConfig = await import('../src/core/config.ts');
+mock.module('../src/core/config.ts', () => ({
+ ...realConfig,
+ loadConfig: () => ({ engine: 'pglite', remote_mcp: { url: 'https://brain.example.test/mcp', token: 'tok' } }),
+ isThinClient: () => true,
+}));
+
+const realMcpClient = await import('../src/core/mcp-client.ts');
+mock.module('../src/core/mcp-client.ts', () => ({
+ ...realMcpClient,
+ callRemoteTool: async (_cfg: unknown, name: string, params: Record<string, unknown>) => {
+ calls.push({ name, params });
+ return { content: [{ type: 'text', text: JSON.stringify([]) }] };
+ },
+}));
+
+const { runGraphQuery } = await import('../src/commands/graph-query.ts');
+
+class ExitSentinel extends Error {
+ constructor(public readonly code: number) {
+ super(`process.exit(${code})`);
+ }
+}
+
+async function run(args: string[]): Promise<{ code: number; out: string[]; err: string[] }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const savedLog = console.log;
+ const savedError = console.error;
+ const savedExit = process.exit;
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ (process as unknown as { exit: (code?: number) => never }).exit = ((code?: number) => {
+ throw new ExitSentinel(code ?? 0);
+ }) as never;
+ try {
+ // Thin client: the engine is never touched.
+ await runGraphQuery({} as never, args);
+ return { code: 0, out, err };
+ } catch (e) {
+ if (e instanceof ExitSentinel) return { code: e.code, out, err };
+ throw e;
+ } finally {
+ console.log = savedLog;
+ console.error = savedError;
+ (process as unknown as { exit: typeof savedExit }).exit = savedExit;
+ }
+}
+
+beforeEach(() => { calls.length = 0; });
+
+describe('graph-query --source on a thin-client install', () => {
+ test('--source is rejected with exit 1 and never reaches the wire', async () => {
+ const r = await run(['people/alice-example', '--depth', '1', '--source', 'nosuch']);
+ expect(r.code).toBe(1);
+ const stderr = r.err.join('\n');
+ expect(stderr).toContain('--source');
+ expect(stderr).toContain('thin-client');
+ expect(calls).toHaveLength(0);
+ expect(r.out).toHaveLength(0);
+ });
+
+ test('--source=<id> form is rejected the same way', async () => {
+ const r = await run(['people/alice-example', '--source=team']);
+ expect(r.code).toBe(1);
+ expect(calls).toHaveLength(0);
+ });
+
+ test('--include-foreign warns that it is not forwarded (the grant bounds the walk)', async () => {
+ const r = await run(['people/alice-example', '--depth', '1', '--include-foreign']);
+ expect(r.code).toBe(0);
+ expect(r.err.join('\n')).toContain('--include-foreign');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].name).toBe('traverse_graph');
+ // Wire shape unchanged: no source_id / include_foreign leaks onto the op.
+ expect(Object.keys(calls[0].params).sort()).toEqual(['depth', 'direction', 'link_type', 'slug']);
+ });
+
+ test('no scope flags: silent remote walk with the exact wire params', async () => {
+ const r = await run(['people/alice-example', '--depth', '2', '--type', 'attended', '--direction', 'in']);
+ expect(r.code).toBe(0);
+ expect(r.err).toHaveLength(0);
+ expect(calls).toHaveLength(1);
+ expect(calls[0].params).toEqual({ slug: 'people/alice-example', depth: 2, link_type: 'attended', direction: 'in' });
+ });
+
+ // Wave review: a valueless --source used to skip the thin-client refusal
+ // (the parser dropped the flag), and an ambient GBRAIN_SOURCE scope was
+ // dropped with no word — the user believed the walk was scoped.
+ test('a valueless --source is refused before the wire, on the thin client too', async () => {
+ const r = await run(['people/alice-example', '--depth', '1', '--source']);
+ expect(r.code).toBe(1);
+ expect(r.err.join('\n')).toContain('`--source` requires a value');
+ expect(calls).toHaveLength(0);
+ });
+
+ test('an ambient GBRAIN_SOURCE scope prints the cannot-forward note (walk still runs)', async () => {
+ const r = await withEnv({ GBRAIN_SOURCE: 'team-wiki' }, () => run(['people/alice-example', '--depth', '1']));
+ expect(r.code).toBe(0);
+ const stderr = r.err.join('\n');
+ expect(stderr).toContain("ambient source scope 'team-wiki' is not forwarded");
+ expect(stderr).toContain('scopes the walk to your grant');
+ expect(calls).toHaveLength(1);
+ expect(Object.keys(calls[0].params).sort()).toEqual(['depth', 'direction', 'link_type', 'slug']);
+ });
+});
diff --git a/test/graph-query.test.ts b/test/graph-query.test.ts
index 472984566f..d740eee645 100644
--- a/test/graph-query.test.ts
+++ b/test/graph-query.test.ts
@@ -62,6 +62,29 @@ function captureBoth(fn: () => Promise<void>): Promise<{ out: string[]; err: str
})();
}
+/** captureBoth + a process.exit sentinel, for the refusal paths. */
+async function runWithExit(argv: string[]): Promise<{ code: number; out: string[]; err: string[] }> {
+ const savedExit = process.exit;
+ class ExitSentinel extends Error { constructor(public readonly code: number) { super(`exit ${code}`); } }
+ (process as unknown as { exit: (code?: number) => never }).exit = ((code?: number) => {
+ throw new ExitSentinel(code ?? 0);
+ }) as never;
+ let code = 0;
+ try {
+ const { out, err } = await captureBoth(async () => {
+ try {
+ await runGraphQuery(engine, argv);
+ } catch (e) {
+ if (e instanceof ExitSentinel) { code = e.code; return; }
+ throw e;
+ }
+ });
+ return { code, out, err };
+ } finally {
+ (process as unknown as { exit: typeof savedExit }).exit = savedExit;
+ }
+}
+
describe('graph-query command', () => {
beforeEach(async () => {
await truncateAll();
@@ -170,6 +193,74 @@ describe('graph-query foreign-edge footer (#1153)', () => {
expect(joined).toMatch(/--include-foreign/);
});
+ // #4765: the walk itself was never scoped, so carol (other-src) was in the
+ // tree while the footer claimed her edge was hidden, and --include-foreign
+ // only silenced the footer. The default walk is now scoped to the resolved
+ // source; --include-foreign genuinely widens it.
+ test('default traversal is scoped: foreign-source edge is not in the tree (#4765)', async () => {
+ const { out } = await captureBoth(async () => {
+ await runGraphQuery(engine, ['people/alice', '--depth', '1']);
+ });
+ const joined = out.join('\n');
+ expect(joined).toContain('people/bob');
+ expect(joined).not.toContain('people/carol');
+ });
+
+ test('--include-foreign walks the foreign edge', async () => {
+ const { out } = await captureBoth(async () => {
+ await runGraphQuery(engine, ['people/alice', '--depth', '1', '--include-foreign']);
+ });
+ const joined = out.join('\n');
+ expect(joined).toContain('people/bob');
+ expect(joined).toContain('people/carol');
+ });
+
+ test('--source <id> scopes the root (alice is not in other-src)', async () => {
+ const { out } = await captureBoth(async () => {
+ await runGraphQuery(engine, ['people/alice', '--depth', '1', '--source', 'other-src']);
+ });
+ expect(out.join('\n').toLowerCase()).toContain('no edges found');
+ });
+
+ test('--source __all__ spans every source (sentinel never scopes literally)', async () => {
+ const { out, err } = await captureBoth(async () => {
+ await runGraphQuery(engine, ['people/alice', '--depth', '1', '--source=__all__']);
+ });
+ expect(out.join('\n')).toContain('people/carol');
+ // An unscoped walk hid nothing, so the footer must not claim it did.
+ expect(err.join('\n')).not.toMatch(/foreign-source pages hidden/);
+ });
+
+ test('an unknown --source is rejected loudly', async () => {
+ await expect(runGraphQuery(engine, ['people/alice', '--source', 'nope-source'])).rejects.toThrow(/nope-source/);
+ });
+
+ // Wave review: the footer counts foreign edges of the ROOT AS RESOLVED
+ // (source_id, slug), not of every same-slug page in the brain — alice is
+ // not in other-src, so a walk scoped there hid nothing.
+ test('--source <id> footer is relative to the resolved source (no phantom hidden edges)', async () => {
+ const { err } = await captureBoth(async () => {
+ await runGraphQuery(engine, ['people/alice', '--depth', '1', '--source', 'other-src']);
+ });
+ expect(err.join('\n')).not.toMatch(/foreign-source pages hidden/);
+ });
+
+ test('--source <id> with --include-foreign is refused (exit 1), not silently widened', async () => {
+ const r = await runWithExit(['people/alice', '--depth', '1', '--source', 'other-src', '--include-foreign']);
+ expect(r.code).toBe(1);
+ expect(r.err.join('\n')).toMatch(/--include-foreign/);
+ expect(r.out).toHaveLength(0);
+ });
+
+ test('a valueless --source (last arg) or --source= is refused, never read as ambient scope', async () => {
+ for (const argv of [['people/alice', '--depth', '1', '--source'], ['people/alice', '--source=', '--depth', '1']]) {
+ const r = await runWithExit(argv);
+ expect(r.code).toBe(1);
+ expect(r.err.join('\n')).toContain('`--source` requires a value');
+ expect(r.out).toHaveLength(0);
+ }
+ });
+
test('--include-foreign suppresses the footer', async () => {
const { err } = await captureBoth(async () => {
await runGraphQuery(engine, ['people/alice', '--depth', '1', '--include-foreign']);
diff --git a/test/import-file.test.ts b/test/import-file.test.ts
index e23c2f33da..65d4f2a2aa 100644
--- a/test/import-file.test.ts
+++ b/test/import-file.test.ts
@@ -143,6 +143,23 @@ This is the compiled truth.
expect(chunkCall).toBeTruthy();
});
+ test('strips a UTF-8 BOM so the heading title is used (#4798)', async () => {
+ // Written as bytes so no editor can silently strip the BOM from a fixture.
+ const filePath = join(TMP, 'bom-note.md');
+ writeFileSync(filePath, Buffer.concat([
+ Buffer.from([0xef, 0xbb, 0xbf]),
+ Buffer.from('# My Real Title\n\nbody text\n'),
+ ]));
+
+ const engine = mockEngine();
+ const result = await importFile(engine, filePath, 'notes/bom-note.md', { noEmbed: true });
+
+ expect(result.status).toBe('imported');
+ const putCall = (engine as any)._calls.find((c: any) => c.method === 'putPage');
+ expect(putCall.args[1].title).toBe('My Real Title');
+ expect(putCall.args[1].compiled_truth).not.toContain('\uFEFF');
+ });
+
test('skips files larger than MAX_FILE_SIZE (5MB)', async () => {
const filePath = join(TMP, 'big-file.md');
const bigContent = '---\ntitle: Big\n---\n' + 'x'.repeat(5_100_000);
diff --git a/test/import-json-stdout.serial.test.ts b/test/import-json-stdout.serial.test.ts
index 1a58d41803..87cf905aa2 100644
--- a/test/import-json-stdout.serial.test.ts
+++ b/test/import-json-stdout.serial.test.ts
@@ -72,11 +72,12 @@ function seedNotes(prefix: string): string {
return dir;
}
-describe('import --json stdout is parseable JSON (#3637)', () => {
+describe('import --json stdout is parseable JSON (#3637) and lists per-file failures', () => {
test('--json puts one JSON document on stdout and the progress lines on stderr; human mode is unchanged', async () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-3637-'));
const jsonNotes = seedNotes('gbrain-3637-json-');
const humanNotes = seedNotes('gbrain-3637-human-');
+ const mixedNotes = mkdtempSync(join(tmpdir(), 'gbrain-import-failures-'));
try {
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(
@@ -114,6 +115,54 @@ describe('import --json stdout is parseable JSON (#3637)', () => {
expect(json.stdout).not.toContain('Found 2 markdown files');
expect(json.stderr).toContain('Found 2 markdown files');
+ // Per-file failures are listed in the payload. Pre-fix, a file whose
+ // import returned status='skipped' with an error (invalid frontmatter
+ // here) was indistinguishable from a content-hash no-op: `skipped`
+ // counted both, `errors` counted neither, exit code was 0, and the
+ // failure ledger is only written for git-repo dirs. gstack's
+ // memory-ingest stamped such pages as ingested and never retried them.
+ writeFileSync(join(mixedNotes, 'good.md'), '# good\n\nbody\n');
+ writeFileSync(
+ join(mixedNotes, 'broken.md'),
+ '---\ntitle: a: b\ntags: [\n---\n\n# broken\n',
+ );
+ const mixed = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);
+ if (mixed.exitCode !== 0) {
+ console.error('--- import mixed stdout ---\n' + mixed.stdout);
+ console.error('--- import mixed stderr ---\n' + mixed.stderr);
+ }
+ expect(mixed.exitCode).toBe(0);
+ const mixedJson = JSON.parse(mixed.stdout);
+ expect(mixedJson.imported).toBe(1);
+ expect(mixedJson.skipped).toBe(1);
+ expect(mixedJson.errors).toBe(0);
+ expect(mixedJson.unchanged).toBe(0);
+ expect(mixedJson.malformed_skipped).toBe(0);
+ expect(mixedJson.failures).toHaveLength(1);
+ expect(mixedJson.failures[0].path).toBe('broken.md');
+ expect(mixedJson.failures[0].error).toContain('Invalid YAML frontmatter');
+
+ // Re-import the same dir: the good note is now a content-hash no-op and
+ // must land in `unchanged` (not `imported`, not `failures`), while the
+ // broken note fails again and stays a named failure. Pins the
+ // `unchanged = skipped - failures - malformed_skipped` derivation and
+ // that a repeat run still lists the failing file by path.
+ const again = await runCli(['import', mixedNotes, '--no-embed', '--json'], env, 120_000);
+ if (again.exitCode !== 0) {
+ console.error('--- import mixed (re-run) stdout ---\n' + again.stdout);
+ console.error('--- import mixed (re-run) stderr ---\n' + again.stderr);
+ }
+ expect(again.exitCode).toBe(0);
+ const againJson = JSON.parse(again.stdout);
+ expect(againJson.total_files).toBe(2);
+ expect(againJson.imported).toBe(0);
+ expect(againJson.skipped).toBe(2);
+ expect(againJson.errors).toBe(0);
+ expect(againJson.unchanged).toBe(1);
+ expect(againJson.malformed_skipped).toBe(0);
+ expect(againJson.failures.map((f: { path: string }) => f.path)).toEqual(['broken.md']);
+ expect(againJson.failures[0].error).toContain('Invalid YAML frontmatter');
+
// Guard the other direction: without --json the human line stays on
// stdout, so this fix cannot be "fixed" by deleting the output.
const human = await runCli(['import', humanNotes, '--no-embed'], env, 120_000);
@@ -125,7 +174,7 @@ describe('import --json stdout is parseable JSON (#3637)', () => {
expect(human.stdout).toContain('Found 2 markdown files');
expect(human.stdout).toContain('Import complete');
} finally {
- for (const d of [home, jsonNotes, humanNotes]) {
+ for (const d of [home, jsonNotes, humanNotes, mixedNotes]) {
try { rmSync(d, { recursive: true, force: true }); } catch { /* best effort */ }
}
}
diff --git a/test/import-source-id.test.ts b/test/import-source-id.test.ts
index c7af21b2d1..545a8875b3 100644
--- a/test/import-source-id.test.ts
+++ b/test/import-source-id.test.ts
@@ -18,7 +18,8 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { runImport } from '../src/commands/import.ts';
+import { runImport, ImportAbortError } from '../src/commands/import.ts';
+import { SourceTargetError } from '../src/core/source-resolver.ts';
let engine: PGLiteEngine;
@@ -99,4 +100,55 @@ describe('import --source-id (#1167)', () => {
);
expect(rows[0]?.source_id).toBe('dept-x');
});
+
+ // #4862: `--source <id>` is what every sibling command (and the resolver's
+ // own nudge) tells users to pass; import accepted it without error and
+ // silently ignored it. It is now an alias of --source-id.
+ test('--source dept-x routes pages to dept-x (#4862)', async () => {
+ await runImport(engine, [scratchDir, '--source', 'dept-x', '--no-embed', '--json']);
+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages`);
+ expect(rows.length).toBeGreaterThanOrEqual(2);
+ for (const r of rows) expect(r.source_id).toBe('dept-x');
+ });
+
+ test('--source value before the dir is NOT treated as the dir (#4862)', async () => {
+ await runImport(engine, ['--source', 'dept-x', scratchDir, '--no-embed', '--json']);
+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages LIMIT 1`);
+ expect(rows[0]?.source_id).toBe('dept-x');
+ });
+
+ test('--source and --source-id disagreeing aborts instead of picking one (#4862)', async () => {
+ await expect(
+ runImport(engine, [scratchDir, '--source', 'dept-x', '--source-id', 'default', '--no-embed', '--json']),
+ ).rejects.toBeInstanceOf(ImportAbortError);
+ const rows = await engine.executeRaw<{ n: string }>(`SELECT COUNT(*) AS n FROM pages`);
+ expect(parseInt(rows[0].n, 10)).toBe(0);
+ });
+
+ // Wave review: the flag parser mirrors sync-delegate — `--flag=value` is a
+ // form, a missing value is a refusal (never "no scope"), and the value goes
+ // through the shared resolver so a typo fails ONCE with the resolver's own
+ // SourceTargetError instead of N pages.source_id foreign-key failures.
+ test('--source=dept-x form routes pages to dept-x (wave review)', async () => {
+ await runImport(engine, [scratchDir, '--source=dept-x', '--no-embed', '--json']);
+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages`);
+ expect(rows.length).toBeGreaterThanOrEqual(2);
+ for (const r of rows) expect(r.source_id).toBe('dept-x');
+ });
+
+ test('a valueless --source / --source-id (last arg, next flag, --source=) is refused, nothing imported (wave review)', async () => {
+ const countPages = async () => parseInt((await engine.executeRaw<{ n: string }>(`SELECT COUNT(*) AS n FROM pages`))[0].n, 10);
+ await expect(runImport(engine, [scratchDir, '--no-embed', '--json', '--source'])).rejects.toBeInstanceOf(ImportAbortError);
+ await expect(runImport(engine, [scratchDir, '--source', '--no-embed', '--json'])).rejects.toBeInstanceOf(ImportAbortError);
+ await expect(runImport(engine, [scratchDir, '--source=', '--no-embed', '--json'])).rejects.toBeInstanceOf(ImportAbortError);
+ await expect(runImport(engine, [scratchDir, '--no-embed', '--json', '--source-id'])).rejects.toBeInstanceOf(ImportAbortError);
+ expect(await countPages()).toBe(0);
+ });
+
+ test('an unregistered or invalid --source fails with the resolver SourceTargetError before any write (wave review)', async () => {
+ await expect(runImport(engine, [scratchDir, '--source', 'ghost-src', '--no-embed', '--json'])).rejects.toBeInstanceOf(SourceTargetError);
+ await expect(runImport(engine, [scratchDir, '--source-id', 'Not!Valid', '--no-embed', '--json'])).rejects.toBeInstanceOf(SourceTargetError);
+ const rows = await engine.executeRaw<{ n: string }>(`SELECT COUNT(*) AS n FROM pages`);
+ expect(parseInt(rows[0].n, 10)).toBe(0);
+ });
});
diff --git a/test/init-migrate-only.test.ts b/test/init-migrate-only.test.ts
index 0e4faa127d..4fdde8e0d9 100644
--- a/test/init-migrate-only.test.ts
+++ b/test/init-migrate-only.test.ts
@@ -148,7 +148,7 @@ describe('gbrain init --migrate-only — happy path with PGLite config', () => {
// Brain file should exist (schema applied).
expect(existsSync(dbPath)).toBe(true);
- }, 30_000);
+ });
test('idempotent on rerun — second call succeeds without error', async () => {
// Normal path: `first` is the previous test's run against this home —
diff --git a/test/latin-fold.test.ts b/test/latin-fold.test.ts
new file mode 100644
index 0000000000..d8d7a3be4b
--- /dev/null
+++ b/test/latin-fold.test.ts
@@ -0,0 +1,50 @@
+/**
+ * latin-fold — the shared table of Latin letters whose diacritic is drawn
+ * INSIDE the glyph (stroke, bar, ligature). Unicode gives them no
+ * decomposition, so the usual NFD + strip-combining-marks fold leaves them
+ * untouched and every downstream grammar either deletes or keeps the letter
+ * unfolded ("Đức Example" → "uc-example" / "đuc-example"). Both consumers —
+ * `slugify` (entity resolution) and `normalizeBasename` (the FS link
+ * resolver's basename index) — must run the table AFTER their mark strip.
+ */
+import { describe, expect, test } from 'bun:test';
+import { NON_DECOMPOSING_LATIN, foldNonDecomposingLatin } from '../src/core/latin-fold.ts';
+import { slugify } from '../src/core/entities/resolve.ts';
+import { normalizeBasename } from '../src/core/link-extraction.ts';
+
+const stripMarks = (s: string) => s.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
+
+describe('foldNonDecomposingLatin', () => {
+ for (const [letter, ascii] of Object.entries(NON_DECOMPOSING_LATIN)) {
+ const cp = letter.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0');
+ test(`${letter} (U+${cp}) → ${ascii}`, () => {
+ // The reason the row exists: the mark strip alone cannot fold it.
+ expect(stripMarks(letter)).toBe(letter);
+ expect(foldNonDecomposingLatin(letter)).toBe(ascii);
+ });
+ }
+
+ test('folds every occurrence and leaves other letters alone', () => {
+ expect(foldNonDecomposingLatin('løøp straße')).toBe('loop strasse');
+ });
+
+ test('a composed form reduces in one pass after the mark strip (ǿ → ø → o)', () => {
+ expect(foldNonDecomposingLatin(stripMarks('ǿ'))).toBe('o');
+ });
+});
+
+describe('consumers fold the ligature and eth letters', () => {
+ const cases: Array<[string, string]> = [
+ ['Æsir Example', 'aesir-example'],
+ ['Œuvre', 'oeuvre'],
+ ['Ðorðe Example', 'dorde-example'],
+ ];
+ for (const [input, expected] of cases) {
+ test(`slugify(${JSON.stringify(input)}) → ${expected}`, () => {
+ expect(slugify(input)).toBe(expected);
+ });
+ test(`normalizeBasename(${JSON.stringify(input)}) → ${expected}`, () => {
+ expect(normalizeBasename(input)).toBe(expected);
+ });
+ }
+});
diff --git a/test/link-extraction-pack-3190.test.ts b/test/link-extraction-pack-3190.test.ts
index 81ebd8d02a..472b67184a 100644
--- a/test/link-extraction-pack-3190.test.ts
+++ b/test/link-extraction-pack-3190.test.ts
@@ -31,6 +31,7 @@ import {
} from '../src/core/schema-pack/index.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { slugifyPath } from '../src/core/sync.ts';
const nullResolver: SlugResolver = { resolve: async () => null };
@@ -90,6 +91,27 @@ describe('#3190 gate 1 — same-directory markdown links', () => {
);
expect(candidates.map(c => c.targetSlug)).toEqual(['people/alice-chen']);
});
+
+ // #4873: an explicit `./` prefix is the same intent as a bare sibling link
+ // (the FS walker's join(fileDir, target) eats it). The DB path dropped it,
+ // so the #4196 sweep reconcile pruned every FS-created `./` edge.
+ test('#4873 leading ./ same-dir link is a sameDir ref', () => {
+ const refs = extractEntityRefs('See [Beta](./beta.md).');
+ expect(refs).toHaveLength(1);
+ expect(refs[0].slug).toBe('beta');
+ expect(refs[0].sameDir).toBe(true);
+ });
+
+ test('#4873 ./ nested path resolves against the page dir', async () => {
+ const { candidates } = await extractPageLinks(
+ 'docs/readme', 'See [Vietnamese](./i18n/README.vi.md).', {}, 'concept', nullResolver,
+ { 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([]);
+ expect(extractEntityRefs('[x](./https://example.com/a.md)').filter(r => r.sameDir)).toEqual([]);
+ });
});
describe('#3190 gate 2 — pack regex verbs in extractPageLinks', () => {
diff --git a/test/link-extraction-relative-path.test.ts b/test/link-extraction-relative-path.test.ts
index aeb1d89f2c..569d5543d8 100644
--- a/test/link-extraction-relative-path.test.ts
+++ b/test/link-extraction-relative-path.test.ts
@@ -108,3 +108,57 @@ describe('relative markdown-link resolution (nested / subtree-scoped content)',
expect(LINK_EXTRACTOR_VERSION_TS > '2026-08-01T00:00:00Z').toBe(true);
});
});
+
+// A parent-dir SIBLING link (`../y.md`, `./../y.md`) has no directory segment,
+// so pass 1 never claimed it and pass 1b's relative arm only took `./`. The FS
+// walker's join() resolved it, the DB path produced no candidate, and the
+// serve-resident sweep's reconcile pruned the FS-created edge — the #4873
+// class. Every "wiki/y" case below FAILS on the pre-fix regex.
+describe('dot-relative sibling links without a directory segment (#4873 class)', () => {
+ test('`../y.md` resolves one level up from the linking page dir', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/sources/foo', 'See [Y](../y.md).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['wiki/y']);
+ expect(candidates[0].linkSource).toBe('markdown');
+ });
+
+ test('`./../y.md` folds the `./` and climbs once', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/sources/foo', 'See [Y](./../y.md).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['wiki/y']);
+ });
+
+ test('`../../y.md` climbs twice', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/a/b/foo', 'See [Y](../../y.md).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['wiki/y']);
+ });
+
+ test('a `../` run that climbs above the root is dangling — no candidate', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/foo', 'See [Y](../../y.md).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates).toEqual([]);
+ });
+
+ test('extractEntityRefs tags the sibling form sameDir with its `..` depth', () => {
+ const refs = extractEntityRefs('See [Y](./../y.md) and [Z](../../z.md).');
+ expect(refs.map(r => ({ slug: r.slug, sameDir: r.sameDir, upLevels: r.upLevels }))).toEqual([
+ { slug: 'y', sameDir: true, upLevels: 1 },
+ { slug: 'z', sameDir: true, upLevels: 2 },
+ ]);
+ });
+
+ test('`../dir/x.md` stays a pass-1 ref — the widened sameDir arm does not double-emit', async () => {
+ const refs = extractEntityRefs('See [X](../concepts/x.md).');
+ expect(refs).toHaveLength(1);
+ expect(refs[0].sameDir).toBeUndefined();
+ const { candidates } = await extractPageLinks(
+ 'wiki/sources/foo', 'See [X](../concepts/x.md).', {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['wiki/concepts/x']);
+ });
+});
diff --git a/test/link-extraction.test.ts b/test/link-extraction.test.ts
index bbe7dcff5a..54a0975710 100644
--- a/test/link-extraction.test.ts
+++ b/test/link-extraction.test.ts
@@ -1876,9 +1876,11 @@ describe('extractFrontmatterLinks — [[wikilink]] related: values (end-to-end)'
// normalizeBasename previously stripped everything outside [a-z0-9\s-],
// so a CJK basename collapsed to '' (every lookup missed) and accented
// names diverged from slugifySegment ('Café' → 'caf' vs 'cafe'). It now
-// mirrors slugifySegment's normalization (NFD → strip accents → NFC →
-// lowercase → SLUG_WORD_CHARS filter), so display names in any script
-// produce the same key the slug grammar produces.
+// follows slugifySegment's normalization (NFD → strip accents → NFC →
+// lowercase → SLUG_WORD_CHARS filter) and then folds stroke letters to
+// ASCII via latin-fold (#4855) — so the key can differ from a page slug
+// that kept đ/ø/ł; the dir-hint candidate step tries both forms (see the
+// #4855 describe at the end of this file).
describe('normalizeBasename — CJK + accent folding (#2367)', () => {
test('Korean display name normalizes to the slugifySegment form, not empty', () => {
@@ -1901,6 +1903,30 @@ describe('normalizeBasename — CJK + accent folding (#2367)', () => {
.toEqual(['meetings/루카텍-올핸즈-미팅']);
});
+ // Stroke letters (đ ł ø ß …) have no Unicode decomposition, so the accent
+ // strip leaves them unfolded and the key diverges from the ASCII page slug
+ // — the lookup then misses in silence. Each name here carries BOTH a
+ // decomposing accent (folded by the strip) and a stroke letter (folded by
+ // the shared table), so a half-fix handling only one class still fails.
+ test('stroke letters fold to the ASCII form the page slug uses', () => {
+ expect(normalizeBasename('Đức Example')).toBe('duc-example');
+ expect(normalizeBasename('Łukasz Example')).toBe('lukasz-example');
+ expect(normalizeBasename('Søren Example')).toBe('soren-example');
+ });
+
+ test('basename index: a stroke-letter display name hits its ASCII slug tail', () => {
+ const idx = buildBasenameIndex(['people/duc-example', 'people/lukasz-example']);
+ expect(queryBasenameIndex(idx, 'Đức Example')).toEqual(['people/duc-example']);
+ expect(queryBasenameIndex(idx, 'Łukasz Example')).toEqual(['people/lukasz-example']);
+ });
+
+ test('index side folds too, so a stroke-letter slug stays reachable', () => {
+ // Symmetry: both sides run through normalizeBasename, so a page whose own
+ // slug kept the stroke letter still answers to the ASCII display name.
+ const idx = buildBasenameIndex(['people/đuc-example']);
+ expect(queryBasenameIndex(idx, 'Duc Example')).toEqual(['people/đuc-example']);
+ });
+
test('end-to-end: bare CJK wikilink resolves via the basename index', async () => {
const idx = buildBasenameIndex(['meetings/루카텍-올핸즈-미팅']);
const resolver: SlugResolver = {
@@ -2023,3 +2049,65 @@ describe('#4062 — bare [[name]] emits a root-exact direct candidate flag-off',
]);
});
});
+
+// #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
+// slugs, existence-checked downstream — so `[[Đức Example]]` reaches either.
+describe('#4062 — bare [[name]] direct candidate tries both slug grammars', () => {
+ const resolver: SlugResolver = { async resolve() { return null; } };
+
+ test('flag-off: a stroke-letter wikilink emits the folded AND unfolded root slugs', async () => {
+ const r = await extractPageLinks(
+ 'notes/some-page', 'met [[Đức Example]] today', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.map(c => c.targetSlug).sort()).toEqual(['duc-example', 'đuc-example']);
+ expect(new Set(r.candidates.map(c => c.linkSource))).toEqual(new Set(['markdown']));
+ });
+
+ test('flag-off: an ASCII wikilink still emits exactly one candidate (grammars agree)', async () => {
+ const r = await extractPageLinks(
+ 'notes/some-page', 'see [[Example Rail]]', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.map(c => c.targetSlug)).toEqual(['example-rail']);
+ });
+
+ test('flag-off: self-loop guard covers the folded form too', async () => {
+ const r = await extractPageLinks(
+ 'duc-example', 'this is [[Đức Example]] itself', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.map(c => c.targetSlug)).toEqual(['đuc-example']);
+ });
+});
+
+// ─── #4855: the dir-hint candidate step tries BOTH slug grammars ──────────
+//
+// normalizeBasename folds stroke letters to ASCII (latin-fold), but the
+// page-slug grammar (sync.ts slugifySegment, #3417) deliberately keeps them,
+// so a page synced from `Đức Example.md` lives at 'people/đuc-example'. The
+// dir-hint step must try the unfolded form too, or a hint hit turns into a
+// miss — fatal on the FS resolver, which has no fuzzy step 3 to rescue it.
+
+describe('makeResolver — dir-hint step tries both slug grammars (#4855)', () => {
+ function pagesOnly(slugs: string[]): BrainEngine {
+ const lookup = new Set(slugs);
+ return {
+ async getPage(slug: string) { return lookup.has(slug) ? { slug } as any : null; },
+ async findByTitleFuzzy() { return null; },
+ async searchKeyword() { return []; },
+ } as unknown as BrainEngine;
+ }
+
+ test('unfolded page slug (sync grammar) still resolves from the stroke-letter display name', async () => {
+ const r = makeResolver(pagesOnly(['people/đuc-example']));
+ expect(await r.resolve('Đức Example', 'people')).toBe('people/đuc-example');
+ });
+
+ test('folded ASCII page slug resolves from the same display name', async () => {
+ const r = makeResolver(pagesOnly(['people/duc-example']));
+ expect(await r.resolve('Đức Example', 'people')).toBe('people/duc-example');
+ });
+});
diff --git a/test/list-pages-slug-total-order.test.ts b/test/list-pages-slug-total-order.test.ts
new file mode 100644
index 0000000000..dbf97630f3
--- /dev/null
+++ b/test/list-pages-slug-total-order.test.ts
@@ -0,0 +1,51 @@
+/**
+ * `PAGE_SORT_SQL.slug` is a TOTAL order (slug, source_id, id).
+ *
+ * Slug uniqueness is per (source_id, slug), so a federated listing can hold
+ * the same slug from several sources. Under the bare `p.slug ASC`, slug+offset
+ * paging over such a set was not deterministic (a tie cluster wider than the
+ * page could duplicate or skip rows) — the same class the v0.45.7 updated_asc
+ * tiebreaker fixed. Pins the SQL string and the observable paging order.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PAGE_SORT_SQL } from '../src/core/types.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(
+ 'INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING',
+ ['team-alpha'],
+ );
+ const input = { type: 'note', title: 'Shared slug', compiled_truth: 'body' };
+ await engine.putPage('messages/shared', input, { sourceId: 'team-alpha' });
+ await engine.putPage('messages/shared', input);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+});
+
+describe('slug sort is a total order across sources sharing a slug', () => {
+ test('PAGE_SORT_SQL.slug carries source_id + id tiebreakers', () => {
+ expect(PAGE_SORT_SQL.slug).toBe('p.slug ASC, p.source_id ASC, p.id ASC');
+ });
+
+ test('limit=1 paging over two sources yields each row exactly once, in a stable order', async () => {
+ const pages = await Promise.all([0, 1].map(async (offset) => {
+ const [page] = await engine.listPages({
+ sourceIds: ['default', 'team-alpha'],
+ sort: 'slug',
+ limit: 1,
+ offset,
+ });
+ return `${page.source_id}:${page.slug}`;
+ }));
+ expect(pages).toEqual(['default:messages/shared', 'team-alpha:messages/shared']);
+ });
+});
diff --git a/test/list-pages-source-scope.test.ts b/test/list-pages-source-scope.test.ts
index 14bc357128..2212cd18d7 100644
--- a/test/list-pages-source-scope.test.ts
+++ b/test/list-pages-source-scope.test.ts
@@ -25,6 +25,9 @@ function makeCtx(overrides: Partial<OperationContext> = {}): {
calls.push(opts);
return [];
},
+ // #4620: an explicit source_id is checked against the live registry
+ // (a point lookup on `sources`; every id this file names is live).
+ executeRaw: async () => [{ ok: 1 }],
} as any,
config: {} as any,
logger: console as any,
@@ -81,3 +84,17 @@ describe('list_pages — explicit source_id param (#4400)', () => {
expect(calls[0]).toMatchObject({ sourceIds: ['default', 'src-a', 'src-b'] });
});
});
+
+describe('list_pages — source_id is parsed like get_page (#4857)', () => {
+ // Pre-fix the handler took any string through as-is: a whitespace or
+ // malformed id reached the engine and silently returned [], a non-string
+ // was dropped (unscoped listing), and the CLI's `--source-id ""` silently
+ // widened to every source. parseSourceIdParam rejects all of them loudly.
+ test('whitespace, malformed, non-string, and empty source_id are invalid_params before the engine is called', async () => {
+ for (const source_id of [' ', 'not valid!', 42, '']) {
+ const { ctx, calls } = makeCtx({ remote: false });
+ await expect(list_pages.handler(ctx, { source_id })).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(calls).toHaveLength(0);
+ }
+ });
+});
diff --git a/test/list-pages-updated-asc-total-order.test.ts b/test/list-pages-updated-asc-total-order.test.ts
new file mode 100644
index 0000000000..7a7dd4ef3d
--- /dev/null
+++ b/test/list-pages-updated-asc-total-order.test.ts
@@ -0,0 +1,56 @@
+/**
+ * `PAGE_SORT_SQL.updated_asc` is a TOTAL order (updated_at, slug, source_id, id).
+ *
+ * Slug uniqueness is per (source_id, slug), so under a federated scope two
+ * sources can hold the same slug stamped with the same updated_at (a bulk sync
+ * stamps one now() across a transaction). Under `p.updated_at ASC, p.slug ASC`
+ * those two rows ordered arbitrarily, so limit/offset paging could duplicate or
+ * skip one — the same class the `slug` sort's source_id + id tiebreakers fixed.
+ * Pins the SQL string and the observable paging order.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PAGE_SORT_SQL } from '../src/core/types.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(
+ 'INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING',
+ ['team-alpha'],
+ );
+ const input = { type: 'note', title: 'Shared slug', compiled_truth: 'body' };
+ await engine.putPage('messages/shared', input, { sourceId: 'team-alpha' });
+ await engine.putPage('messages/shared', input);
+ // One identical timestamp for both rows: the tie the tiebreakers must break.
+ await engine.executeRaw(
+ `UPDATE pages SET updated_at = '2026-08-10T12:00:00.000100Z'::timestamptz WHERE slug = 'messages/shared'`,
+ );
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+});
+
+describe('updated_asc sort is a total order across sources sharing slug + updated_at', () => {
+ test('PAGE_SORT_SQL.updated_asc carries source_id + id tiebreakers', () => {
+ expect(PAGE_SORT_SQL.updated_asc).toBe('p.updated_at ASC, p.slug ASC, p.source_id ASC, p.id ASC');
+ });
+
+ test('limit=1 paging over two sources yields each row exactly once, in a stable order', async () => {
+ const pages = await Promise.all([0, 1].map(async (offset) => {
+ const [page] = await engine.listPages({
+ sourceIds: ['default', 'team-alpha'],
+ sort: 'updated_asc',
+ limit: 1,
+ offset,
+ });
+ return `${page.source_id}:${page.slug}`;
+ }));
+ expect(pages).toEqual(['default:messages/shared', 'team-alpha:messages/shared']);
+ });
+});
diff --git a/test/llm-json-reasoning-ladder.test.ts b/test/llm-json-reasoning-ladder.test.ts
index 69f5a2a1ad..2d03effa77 100644
--- a/test/llm-json-reasoning-ladder.test.ts
+++ b/test/llm-json-reasoning-ladder.test.ts
@@ -57,6 +57,47 @@ describe('parseLlmJson — reasoning ladder', () => {
expect(parseLlmJson('<think>only reasoning, no answer</think>')).toBeNull();
expect(parseLlmJson('')).toBeNull();
});
+
+ test('recovers the ANSWER from a closed <thinking> block (sibling tag)', () => {
+ // Some models/proxies emit <thinking> rather than <think>.
+ // Pre-fix the tag was unrecognised, the strip was a no-op, and the retry
+ // never ran — so this returned null.
+ const raw = '<thinking>I will answer {"answer":"draft"} probably</thinking>{"answer":"final"}';
+ expect(parseLlmJson<{ answer: string }>(raw)).toEqual({ answer: 'final' });
+ });
+
+ test('is case-insensitive about the <thinking> tag too', () => {
+ const raw = '<THINKING>draft {"answer":"draft"}</THINKING>{"answer":"final"}';
+ expect(parseLlmJson<{ answer: string }>(raw)).toEqual({ answer: 'final' });
+ });
+
+ test('recovers when an unclosed <thinking> tail was truncated (budget exhausted mid-reasoning)', () => {
+ // Twin of the unclosed <think> case above: the answer was emitted, then the
+ // model started a <thinking> block and ran out of tokens before closing it.
+ // The tail must contain a `}` — the raw greedy `{…}` scan then spans from
+ // the answer into the truncated draft and fails, so this only recovers if
+ // the open-ended arm strips <thinking> as well as <think>. (A tail with no
+ // `}` at all parses on the raw arm and never exercises the strip.)
+ const raw = '{"answer":"final"}<thinking>ran out {"a":{"b":1}';
+ expect(parseLlmJson<{ answer: string }>(raw)).toEqual({ answer: 'final' });
+ });
+
+ test('is a ladder for <thinking> as well: valid JSON containing the literal tag is untouched', () => {
+ // Twin of the <think> ladder-ordering guard above. Without it, widening the
+ // tag would silently narrow that protection to half the vocabulary.
+ const raw = '{"note":"the <thinking> tag is literal here"}';
+ expect(parseLlmJson<{ note: string }>(raw)).toEqual({
+ note: 'the <thinking> tag is literal here',
+ });
+ });
+
+ test('a MISMATCHED pair still falls through to the open-ended arm (unchanged semantics)', () => {
+ // The closed-pair arm backreferences its opening tag, so <think>…</thinking>
+ // is not a pair. It is then eaten by the unclosed arm to end-of-string —
+ // exactly what pre-change code did with an unclosed <think>. Nothing is
+ // recoverable here, and null is the honest answer.
+ expect(parseLlmJson('<think>draft {"a":1}</thinking>{"answer":"final"}')).toBeNull();
+ });
});
describe('extractors route through the ladder', () => {
@@ -70,7 +111,7 @@ describe('extractors route through the ladder', () => {
});
test('atoms extractor parses a think-wrapped array instead of halting', () => {
- const raw = '<think>I could emit [ "draft" ]</think>[{"claim":"Water is wet","kind":"fact"}]';
+ const raw = '<think>I could emit [ "draft" ]</think>[{"title":"Water is wet","atom_type":"insight","body":"Observed in the transcript."}]';
const outcome = parseAtomsOutcome(raw);
expect(outcome.ok).toBe(true);
});
@@ -88,6 +129,30 @@ describe('extractors route through the ladder', () => {
if (!outcome.ok) expect(outcome.reason).toBe('unterminated JSON array');
});
+ test('atoms extractor recovers a <thinking>-wrapped array whose reasoning cites [Source: …]', () => {
+ // The real-world shape this fix exists for. parseAtomsOutcomeInner anchors
+ // on the FIRST '[' in the response; a brain whose house style mandates
+ // inline `[Source: …]` citations makes the model echo one while reasoning,
+ // so the anchor lands in the reasoning and the parse dies as
+ // "unparseable JSON array". Verified to fail on unmodified 8c70f62.
+ const raw =
+ '<thinking>The page cites [Source: alice-example, agent session, 2026-01-01], ' +
+ 'so the quote should come from there.</thinking>' +
+ '[{"title":"Water is wet","atom_type":"insight","body":"Observed in the transcript."}]';
+ const outcome = parseAtomsOutcome(raw);
+ expect(outcome.ok).toBe(true);
+ });
+
+ test('atoms extractor recovers a <thinking>-wrapped array whose reasoning names a [[wikilink]]', () => {
+ // Same anchor defect, second bracket source: backlink markup. Also verified
+ // to fail pre-fix with "unparseable JSON array".
+ const raw =
+ '<thinking>It links [[people/alice-example]] and [[companies/acme-example]].</thinking>' +
+ '[{"title":"Backlinks are mandatory","atom_type":"insight","body":"House style requires them."}]';
+ const outcome = parseAtomsOutcome(raw);
+ expect(outcome.ok).toBe(true);
+ });
+
test('atoms extractor: non-reasoning garbage returns the direct reason untouched (strip is a no-op)', () => {
// Regression guard: the ladder must not mask error reporting for models
// that never emit reasoning blocks — stripping changes nothing here, so
diff --git a/test/loops-store.test.ts b/test/loops-store.test.ts
index fd50cf6e0c..0afaffd9e4 100644
--- a/test/loops-store.test.ts
+++ b/test/loops-store.test.ts
@@ -77,19 +77,27 @@ describe('upsertOpenLoop', () => {
});
test('reopen: a closed loop flips back to open (closed_at/closed_by cleared) on conflict', async () => {
- const { id } = await upsertOpenLoop(engine, loop());
- const closed = await closeOpenLoop(engine, 'g1', id, 'done', 'manual');
- expect(closed?.status).toBe('done');
-
- const again = await upsertOpenLoop(engine, loop({ summary: 'they pinged again' }));
- expect(again.created).toBe(false);
- expect(again.id).toBe(id);
-
- const rows = await listOpenLoops(engine, { sourceIds: ['g1'] });
- expect(rows[0].status).toBe('open');
- expect(rows[0].closed_at).toBeNull();
- expect(rows[0].closed_by).toBeNull();
- expect(rows[0].summary).toBe('they pinged again');
+ // SQL now() is constant within a transaction: the fixture must supply
+ // genuinely newer activity, not depend on the database clock advancing.
+ await engine.transaction(async (tx) => {
+ const { id } = await upsertOpenLoop(tx, loop({ lastActivityAt: '2026-08-20T00:00:00.000Z' }));
+ const closed = await closeOpenLoop(tx, 'g1', id, 'done', 'manual');
+ expect(closed?.status).toBe('done');
+
+ const again = await upsertOpenLoop(tx, loop({
+ summary: 'they pinged again',
+ lastActivityAt: '2026-08-24T00:00:00.000Z',
+ }));
+ expect(again.applied).toBe(true);
+ expect(again.created).toBe(false);
+ expect(again.id).toBe(id);
+
+ const rows = await listOpenLoops(tx, { sourceIds: ['g1'] });
+ expect(rows[0].status).toBe('open');
+ expect(rows[0].closed_at).toBeNull();
+ expect(rows[0].closed_by).toBeNull();
+ expect(rows[0].summary).toBe('they pinged again');
+ });
});
test('evidence is REPLACED on upsert, not merged', async () => {
diff --git a/test/markdown.test.ts b/test/markdown.test.ts
index 5dac4fcda5..1c17cd5d47 100644
--- a/test/markdown.test.ts
+++ b/test/markdown.test.ts
@@ -713,6 +713,18 @@ describe('resolveSourceLocalFilePath — POSIX backslash-in-filename (undeclared
expect(resolved).toBe(join(repoRoot, 'Archive', 'POL', '2019-10-03 \\never-written-.md'));
});
+ test('basename-relative source_path can resolve under the page slug directory', () => {
+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-basename-source-path-'));
+ mkdirSync(join(repoRoot, '.git'));
+ mkdirSync(join(repoRoot, 'journal'), { recursive: true });
+ const filePath = join(repoRoot, 'journal', 'daily-note.md');
+ writeFileSync(filePath, '# Daily note');
+
+ const resolved = resolveSourceLocalFilePath(repoRoot, 'daily-note.md', 'journal/daily-note');
+
+ expect(resolved).toBe(filePath);
+ });
+
test('path traversal via a real `/`-separated `..` segment is still rejected', () => {
repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-traversal-'));
mkdirSync(join(repoRoot, '.git'));
diff --git a/test/mcp-stdio-source-preflight.test.ts b/test/mcp-stdio-source-preflight.test.ts
new file mode 100644
index 0000000000..1fc11a3372
--- /dev/null
+++ b/test/mcp-stdio-source-preflight.test.ts
@@ -0,0 +1,86 @@
+import { describe, test, expect, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { assertStdioSourceBindable } from '../src/mcp/source-preflight.ts';
+import { DEGRADED_STATE } from '../src/core/degraded-marker.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+function makeEngine(
+ registeredSources: string[],
+ opts: { throwing?: boolean; archived?: string[] } = {},
+): BrainEngine {
+ return {
+ kind: 'postgres',
+ executeRaw: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ if (opts.throwing) throw new Error('engine down');
+ if (sql.includes('SELECT id FROM sources WHERE id = $1')) {
+ const id = params?.[0];
+ if (typeof id !== 'string' || !registeredSources.includes(id)) return [];
+ // Mirror the real predicate: an archived row is only filtered out when
+ // the query asks for it.
+ if (sql.includes('archived = false') && opts.archived?.includes(id)) return [];
+ return [{ id } as T];
+ }
+ return [];
+ },
+ } as unknown as BrainEngine;
+}
+
+describe('stdio MCP source preflight', () => {
+ test('no GBRAIN_SOURCE: nothing to check', async () => {
+ await expect(assertStdioSourceBindable(makeEngine(['default']), undefined)).resolves.toBeUndefined();
+ await expect(assertStdioSourceBindable(makeEngine(['default']), '')).resolves.toBeUndefined();
+ });
+
+ test('registered source passes', async () => {
+ await expect(assertStdioSourceBindable(makeEngine(['default', 'wiki']), 'wiki')).resolves.toBeUndefined();
+ });
+
+ test('well-formed but unregistered source refuses to serve, naming the value and the fix', async () => {
+ const p = assertStdioSourceBindable(makeEngine(['default']), 'workspace');
+ await expect(p).rejects.toThrow(/GBRAIN_SOURCE="workspace" is not a registered active source/);
+ await expect(assertStdioSourceBindable(makeEngine(['default']), 'workspace')).rejects.toThrow(/gbrain sources list/);
+ });
+
+ test('archived source refuses to serve, same as a missing one', async () => {
+ const engine = makeEngine(['default', 'old-wiki'], { archived: ['old-wiki'] });
+ await expect(assertStdioSourceBindable(engine, 'old-wiki')).rejects.toThrow(/missing or archived/);
+ });
+
+ test('__all__ sentinel and malformed values are left to the resolver', async () => {
+ await expect(assertStdioSourceBindable(makeEngine(['default']), '__all__')).resolves.toBeUndefined();
+ await expect(assertStdioSourceBindable(makeEngine(['default']), 'Not A Valid Id!')).resolves.toBeUndefined();
+ });
+
+ test('engine failure does not block startup (guards config, not connectivity)', async () => {
+ await expect(assertStdioSourceBindable(makeEngine([], { throwing: true }), 'workspace')).resolves.toBeUndefined();
+ });
+
+ test('degraded engine: preflight is skipped without touching executeRaw', async () => {
+ let calls = 0;
+ const engine = {
+ kind: 'postgres',
+ [DEGRADED_STATE]: () => true,
+ executeRaw: async <T>(): Promise<T[]> => { calls++; return []; },
+ } as unknown as BrainEngine;
+ await expect(assertStdioSourceBindable(engine, 'workspace')).resolves.toBeUndefined();
+ expect(calls).toBe(0);
+ });
+
+ // Integration: the guard is wired into startMcpServer and fires BEFORE any
+ // transport attaches. This is the discriminating case for the fix — without
+ // the server.ts wiring, startMcpServer proceeds and this expectation fails.
+ const scratch: string[] = [];
+ afterEach(() => { for (const d of scratch.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+ test('startMcpServer refuses a phantom GBRAIN_SOURCE before attaching a transport', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-preflight-home-'));
+ scratch.push(home);
+ const { startMcpServer } = await import('../src/mcp/server.ts');
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SOURCE: 'phantom-source' }, async () => {
+ await expect(startMcpServer(makeEngine(['default']))).rejects.toThrow(/GBRAIN_SOURCE="phantom-source" is not a registered active source/);
+ });
+ });
+});
diff --git a/test/minions/subagent-oneshot.test.ts b/test/minions/subagent-oneshot.test.ts
index 63f9f571e9..fd0e28c581 100644
--- a/test/minions/subagent-oneshot.test.ts
+++ b/test/minions/subagent-oneshot.test.ts
@@ -21,6 +21,7 @@ import {
runSubagentOneshot,
parseOneshotResponse,
extractWikilinkTargets,
+ ONESHOT_SYSTEM,
type OneshotArgs,
} from '../../src/core/minions/handlers/subagent-oneshot.ts';
import type { ChatResult } from '../../src/core/ai/gateway.ts';
@@ -51,12 +52,16 @@ const SUFFIX = 'abc123';
const GOOD_SLUG_A = `wiki/personal/reflections/2026-08-16-topic-${SUFFIX}`;
const GOOD_SLUG_B = `wiki/originals/ideas/2026-08-16-idea-${SUFFIX}`;
-function chatStub(text: string, stopReason: ChatResult['stopReason'] = 'end'): OneshotArgs['_chat'] {
+function chatStub(
+ text: string,
+ stopReason: ChatResult['stopReason'] = 'end',
+ outputTokens = 50,
+): OneshotArgs['_chat'] {
return (async () => ({
text,
blocks: [{ type: 'text', text }],
stopReason,
- usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ usage: { input_tokens: 100, output_tokens: outputTokens, cache_read_tokens: 0, cache_creation_tokens: 0 },
model: 'anthropic:claude-sonnet-4-6',
providerId: 'anthropic',
})) as OneshotArgs['_chat'];
@@ -82,7 +87,13 @@ async function makeCtx(data: SubagentHandlerData): Promise<MinionJobContext> {
};
}
-function makeArgs(ctx: MinionJobContext, data: SubagentHandlerData, chatText: string, stop: ChatResult['stopReason'] = 'end'): OneshotArgs {
+function makeArgs(
+ ctx: MinionJobContext,
+ data: SubagentHandlerData,
+ chatText: string,
+ stop: ChatResult['stopReason'] = 'end',
+ outputTokens = 50,
+): OneshotArgs {
const tools = buildBrainTools({
subagentId: ctx.id,
engine,
@@ -101,7 +112,7 @@ function makeArgs(ctx: MinionJobContext, data: SubagentHandlerData, chatText: st
leaseKey: 'anthropic:messages',
maxConcurrent: 32,
leaseTtlMs: 120_000,
- _chat: chatStub(chatText, stop),
+ _chat: chatStub(chatText, stop, outputTokens),
};
}
@@ -126,6 +137,12 @@ const VALID_RESPONSE = JSON.stringify({
});
describe('parseOneshotResponse', () => {
+ test('system contract requires JSON string escaping', () => {
+ expect(ONESHOT_SYSTEM).toContain('valid JSON string');
+ expect(ONESHOT_SYSTEM).toContain('unescaped quotes');
+ expect(ONESHOT_SYSTEM).toContain('literal newlines');
+ });
+
test('parses the contract, applies title/type defaults', () => {
const p = parseOneshotResponse('```json\n{"pages":[{"slug":"a/b","body":"text"}],"skipped":false}\n```');
expect(p).not.toBeNull();
@@ -325,6 +342,40 @@ describe('runSubagentOneshot', () => {
expect(outcome).toEqual({ kind: 'fallback', reason: 'length', tokens: FB_TOKENS });
});
+ test("malformed output at the cap → length fallback for ambiguous 'end'/'other' reasons", async () => {
+ for (const stop of ['end', 'other'] as const) {
+ const ctx = await makeCtx(DATA);
+ const outcome = await runSubagentOneshot(
+ makeArgs(ctx, DATA, VALID_RESPONSE.slice(0, 50), stop, 8192),
+ );
+ expect(outcome).toEqual({
+ kind: 'fallback',
+ reason: 'length',
+ tokens: { ...FB_TOKENS, out: 8192 },
+ });
+ }
+ });
+
+ test('malformed output below the cap remains unparseable', async () => {
+ const ctx = await makeCtx(DATA);
+ const outcome = await runSubagentOneshot(
+ makeArgs(ctx, DATA, VALID_RESPONSE.slice(0, 50), 'end', 8191),
+ );
+ expect(outcome).toEqual({
+ kind: 'fallback',
+ reason: 'unparseable',
+ tokens: { ...FB_TOKENS, out: 8191 },
+ });
+ });
+
+ test('valid JSON at the cap is accepted', async () => {
+ const ctx = await makeCtx(DATA);
+ const outcome = await runSubagentOneshot(
+ makeArgs(ctx, DATA, '{"pages":[],"skipped":true,"skip_reason":"routine"}', 'end', 8192),
+ );
+ expect(outcome.kind).toBe('done');
+ });
+
test('duplicate slugs within one batch → bad_slug (second write would silently overwrite the first)', async () => {
const ctx = await makeCtx(DATA);
const resp = JSON.stringify({
diff --git a/test/model-config.serial.test.ts b/test/model-config.serial.test.ts
index 63783dc9e0..9dd6c8aa35 100644
--- a/test/model-config.serial.test.ts
+++ b/test/model-config.serial.test.ts
@@ -20,6 +20,10 @@ import {
_resetDeprecationWarningsForTest,
} from '../src/core/model-config.ts';
import type { GBrainConfig } from '../src/core/config.ts';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { withEnv } from './helpers/with-env.ts';
class StubEngine {
readonly kind = 'pglite' as const;
@@ -503,3 +507,61 @@ describe('providerKeyReady + resolveEffectiveChatModel (shared runtime/report re
});
});
});
+
+// ─── #3813: no anthropic/openai key + a SERVABLE file-plane pin ────────────
+// resolveTierDefault walked PROVIDER_TIER_DEFAULTS (anthropic, openai) and
+// returned the Anthropic TIER_DEFAULTS floor when neither key was present —
+// even when ~/.gbrain/config.json pinned a servable third provider (the
+// DeepSeek-only install from the issue). Every bare `resolveTierDefault(tier)`
+// caller (extract_atoms, facts classify, page-summary, ...) then called a
+// provider with no key. Real config.json under a temp GBRAIN_HOME: the
+// no-env branch is the code path under test, so no injected env here.
+describe('resolveTierDefault — servable file-plane pin beats the Anthropic floor when no anthropic/openai key (#3813)', () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-model-config-pin-'));
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(
+ join(home, '.gbrain', 'config.json'),
+ JSON.stringify({
+ engine: 'pglite',
+ expansion_model: 'deepseek:deepseek-v4-flash',
+ chat_model: 'deepseek:deepseek-v4-pro',
+ }),
+ );
+ process.env.GBRAIN_HOME = home;
+ });
+
+ afterEach(() => {
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('DEEPSEEK_API_KEY only → utility follows expansion_model, other tiers follow chat_model', async () => {
+ await withEnv({ DEEPSEEK_API_KEY: 'sk-test' }, () => {
+ expect(resolveTierDefault('utility')).toBe('deepseek:deepseek-v4-flash');
+ expect(resolveTierDefault('reasoning')).toBe('deepseek:deepseek-v4-pro');
+ expect(resolveTierDefault('deep')).toBe('deepseek:deepseek-v4-pro');
+ });
+ });
+
+ test('no key at all → the pin is unservable → TIER_DEFAULTS unchanged', async () => {
+ await withEnv({ DEEPSEEK_API_KEY: undefined }, () => {
+ expect(resolveTierDefault('utility')).toBe(TIER_DEFAULTS.utility);
+ expect(resolveTierDefault('reasoning')).toBe(TIER_DEFAULTS.reasoning);
+ });
+ });
+
+ test('ANTHROPIC_API_KEY present → key walk wins, the pin is ignored (keyed routing unchanged)', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-ant-test', DEEPSEEK_API_KEY: 'sk-test' }, () => {
+ expect(resolveTierDefault('utility')).toBe(TIER_DEFAULTS.utility);
+ expect(resolveTierDefault('reasoning')).toBe(TIER_DEFAULTS.reasoning);
+ });
+ });
+
+ test('injected env stays hermetic: no config read, so no pin', async () => {
+ await withEnv({ DEEPSEEK_API_KEY: 'sk-test' }, () => {
+ expect(resolveTierDefault('utility', { DEEPSEEK_API_KEY: 'sk-test' })).toBe(TIER_DEFAULTS.utility);
+ });
+ });
+});
diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.ts
index a8860ce149..a048af5bda 100644
--- a/test/model-pricing.test.ts
+++ b/test/model-pricing.test.ts
@@ -17,6 +17,7 @@ import {
CANONICAL_PRICING,
canonicalLookup,
ANTHROPIC_CACHE_READ_MULT,
+ ANTHROPIC_CACHE_READ_MULT_OVERRIDES,
ANTHROPIC_CACHE_WRITE_5M_MULT,
} from '../src/core/model-pricing.ts';
import { ANTHROPIC_PRICING } from '../src/core/anthropic-pricing.ts';
@@ -57,6 +58,16 @@ describe('CANONICAL_PRICING — table integrity', () => {
expect(CANONICAL_PRICING['anthropic:claude-fable-5']).toMatchObject({ input: 10.0, output: 50.0 });
});
+ test('Fable 5.1 uses $0.25 cache reads while Fable 5 remains at $1.00', () => {
+ expect(CANONICAL_PRICING['anthropic:claude-fable-5-1']).toEqual({
+ input: 10.0,
+ output: 50.0,
+ cache_read: 0.25,
+ cache_write: 12.5,
+ });
+ expect(CANONICAL_PRICING['anthropic:claude-fable-5'].cache_read).toBe(1.0);
+ });
+
test('Gemini 2.0 Flash reconciled to $0.10/$0.40; legacy alias agrees', () => {
expect(CANONICAL_PRICING['google:gemini-2.0-flash']).toEqual({ input: 0.1, output: 0.4 });
expect(CANONICAL_PRICING['google:gemini-2-flash']).toEqual(
@@ -74,14 +85,23 @@ describe('CANONICAL_PRICING — table integrity', () => {
// #4218 drift guard extension: cache_read/cache_write are DERIVED from the
// input rate via the exported multipliers — a hand-edited cache number that
// drifts from input*mult fails here.
- test('every anthropic: row carries cache_read = 0.1x input and cache_write = 1.25x input', () => {
+ test('every anthropic: row carries its declared cache-read multiplier and cache_write = 1.25x input', () => {
for (const [key, p] of Object.entries(CANONICAL_PRICING)) {
if (!key.startsWith('anthropic:')) continue;
- expect(p.cache_read).toBeCloseTo(p.input * ANTHROPIC_CACHE_READ_MULT, 10);
+ const mult = ANTHROPIC_CACHE_READ_MULT_OVERRIDES[key] ?? ANTHROPIC_CACHE_READ_MULT;
+ expect(p.cache_read).toBeCloseTo(p.input * mult, 10);
expect(p.cache_write).toBeCloseTo(p.input * ANTHROPIC_CACHE_WRITE_5M_MULT, 10);
}
});
+ test('every cache-read multiplier override names a canonical row with matching cache_read', () => {
+ for (const [key, mult] of Object.entries(ANTHROPIC_CACHE_READ_MULT_OVERRIDES)) {
+ const p = CANONICAL_PRICING[key];
+ expect(p).toBeDefined();
+ expect(p!.cache_read).toBeCloseTo(p!.input * mult, 10);
+ }
+ });
+
test('cache fields, when present, are finite positive with read < input < write', () => {
for (const [key, p] of Object.entries(CANONICAL_PRICING)) {
if (p.cache_read !== undefined) {
diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.ts
index 78b3ed0bed..4da4ea9ab4 100644
--- a/test/phantom-redirect.test.ts
+++ b/test/phantom-redirect.test.ts
@@ -779,3 +779,40 @@ describe('phantom-audit module', () => {
});
});
});
+
+// ─── wave review: #4756 placement rule holds for the phantom-redirect writer ──
+describe('tryRedirectPhantom — fence placement above the timeline sentinel (#4756)', () => {
+ test('a canonical with a `---` + `## Timeline` sentinel and no fence gets `## Facts` ABOVE it, not at EOF', async () => {
+ await withTempDirs(async ({ brainDir }) => {
+ // The recommended page template: prose, then the legacy bare `---`
+ // sentinel followed by `## Timeline`. splitBody() files everything
+ // below the sentinel into page.timeline, where extract_facts refuses
+ // to reconcile a fence (FACTS_FENCE_BELOW_SENTINEL) — a blind EOF
+ // append froze the redirected rows permanently.
+ const canonicalBody = `# alice-example\n\nAlice runs acme-example.\n\n---\n\n## Timeline\n\n- 2026-01-01: Founded Acme\n`;
+ await putPage('people/alice-example', canonicalBody, { type: 'person' });
+ writeMd(brainDir, 'people/alice-example', canonicalBody);
+
+ const phantomBody = FACT_FENCE(
+ `| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |`,
+ );
+ await putPage('alice', phantomBody);
+ writeMd(brainDir, 'alice', phantomBody);
+
+ const phantom = await engine.getPage('alice', { sourceId: 'default' });
+ const result = await tryRedirectPhantom(engine, phantom!, 'default', brainDir, false);
+ expect(result.outcome).toBe('redirected');
+
+ const canonicalMd = readMd(brainDir, 'people/alice-example');
+ expect(canonicalMd).toContain('Founded Acme');
+ const factsAt = canonicalMd.indexOf('## Facts');
+ const sentinelAt = canonicalMd.indexOf('\n---\n');
+ expect(factsAt).toBeGreaterThan(-1);
+ expect(sentinelAt).toBeGreaterThan(-1);
+ expect(factsAt).toBeLessThan(sentinelAt);
+ // Prose above the fence survives; the timeline section is still last.
+ expect(canonicalMd.indexOf('Alice runs acme-example.')).toBeLessThan(factsAt);
+ expect(canonicalMd.indexOf('## Timeline')).toBeGreaterThan(canonicalMd.indexOf('gbrain:facts:end'));
+ });
+ });
+});
diff --git a/test/provider-env.test.ts b/test/provider-env.test.ts
index 97633fc67c..448078e780 100644
--- a/test/provider-env.test.ts
+++ b/test/provider-env.test.ts
@@ -18,6 +18,7 @@ describe('mergedProviderEnv', () => {
const env = mergedProviderEnv(cfg({
openai_api_key: 'sk-o', anthropic_api_key: 'sk-a', voyage_api_key: 'pa-v',
zeroentropy_api_key: 'ze', openrouter_api_key: 'or', dashscope_api_key: 'ds',
+ deepseek_api_key: 'sk-deepseek',
google_api_key: 'gg',
azure_openai_api_key: 'az-secret',
azure_openai_endpoint: 'https://x.openai.azure.com',
@@ -30,6 +31,7 @@ describe('mergedProviderEnv', () => {
expect(env.ZEROENTROPY_API_KEY).toBe('ze');
expect(env.OPENROUTER_API_KEY).toBe('or');
expect(env.DASHSCOPE_API_KEY).toBe('ds');
+ expect(env.DEEPSEEK_API_KEY).toBe('sk-deepseek');
expect(env.GOOGLE_GENERATIVE_AI_API_KEY).toBe('gg');
// #4031: the key was the only member of the Azure group left unfolded —
// config.json looked complete while every keyless-shell embed failed auth.
diff --git a/test/rate-leases.test.ts b/test/rate-leases.test.ts
index 50ba368c1b..75d8f6f0bb 100644
--- a/test/rate-leases.test.ts
+++ b/test/rate-leases.test.ts
@@ -11,6 +11,7 @@ import {
releaseLease,
renewLeaseWithBackoff,
} from '../src/core/minions/rate-leases.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;
@@ -146,3 +147,22 @@ describe('renewLeaseWithBackoff', () => {
expect(await renewLeaseWithBackoff(engine, a.leaseId!)).toBe(false);
});
});
+
+describe('acquireLease id coercion', () => {
+ test('a native BigInt RETURNING id (Postgres int8) is returned as a number', async () => {
+ // postgres.js parses BIGSERIAL as BigInt under `types: { bigint: postgres.BigInt }`;
+ // PGLite hands back a Number, so only a fake tx reproduces the shape.
+ const tx = {
+ async executeRaw(sql: string) {
+ if (sql.includes('count(*)')) return [{ count: '0' }];
+ if (sql.includes('RETURNING id')) return [{ id: 26016n }];
+ return [];
+ },
+ };
+ const fake = { transaction: async <T,>(fn: (t: typeof tx) => Promise<T>) => fn(tx) } as unknown as BrainEngine;
+ const res = await acquireLease(fake, 'k', 1, 2);
+ expect(res.acquired).toBe(true);
+ expect(typeof res.leaseId).toBe('number');
+ expect(res.leaseId).toBe(26016);
+ });
+});
diff --git a/test/reindex-code-empty-file.test.ts b/test/reindex-code-empty-file.test.ts
new file mode 100644
index 0000000000..6a003fb386
--- /dev/null
+++ b/test/reindex-code-empty-file.test.ts
@@ -0,0 +1,65 @@
+/**
+ * An EMPTY source file must still be reindexed, not counted as a failure.
+ *
+ * `reindex-code` guarded with `if (!row.compiled_truth)` and reported
+ * `missing compiled_truth`. `!''` is true, so a legitimately empty file — every
+ * `__init__.py` in every Python package — was counted as a FAILURE and skipped.
+ * `pages.compiled_truth` is NOT NULL DEFAULT '', so the empty string was the
+ * only value that guard could ever fire on (#4902).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runReindexCode } from '../src/commands/reindex-code.ts';
+
+let engine: PGLiteEngine;
+
+// Timeouts are explicit: PGLite's WASM cold start + initSchema is ~20s, well
+// past bun's default hook timeout.
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => {
+ await engine.disconnect();
+}, 60_000);
+beforeEach(async () => { await resetPgliteState(engine); }, 60_000);
+
+async function codePage(slug: string, file: string, content: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'code' as string,
+ page_kind: 'code',
+ title: `${file} (python)`,
+ compiled_truth: content,
+ timeline: '',
+ frontmatter: { language: 'python', file },
+ content_hash: `hash-${slug}`,
+ });
+}
+
+// `noEmbed: true` also keeps the code-model nudge quiet (it is gated on
+// `!opts.noEmbed`), so no env mutation is needed here.
+const opts = { force: true, noEmbed: true, yes: true };
+
+describe('reindex-code handles empty files', () => {
+ test('an empty file is reindexed, not counted as a failure', async () => {
+ await codePage('pkg-__init__-py', 'pkg/__init__.py', '');
+
+ const r = await runReindexCode(engine, opts);
+
+ expect(r.failed).toBe(0);
+ expect(r.reindexed).toBe(1);
+ }, 60_000);
+
+ // CONTROL: a non-empty page must be reindexed too, so a green run above can
+ // never be explained by "reindex does nothing at all".
+ test('a non-empty file is reindexed the same way', async () => {
+ await codePage('pkg-mod-py', 'pkg/mod.py', 'def f():\n return 1\n');
+
+ const r = await runReindexCode(engine, opts);
+
+ expect(r.failed).toBe(0);
+ expect(r.reindexed).toBe(1);
+ }, 60_000);
+});
diff --git a/test/rerank-doc-cap.test.ts b/test/rerank-doc-cap.test.ts
new file mode 100644
index 0000000000..82ef6f323a
--- /dev/null
+++ b/test/rerank-doc-cap.test.ts
@@ -0,0 +1,114 @@
+/**
+ * Reranker document cap — self-hosted rerankers (llama-server, TEI) have a
+ * small physical batch and 500 on an oversized chunk. applyReranker caps each
+ * document to a char AND token ceiling before the call, for every provider
+ * (hosted included: prose chunks are untouched; code/CJK chunks at the chunker
+ * ceiling lose part of their tail before scoring). Hex-dense text (index pages,
+ * hashes) is the hazard the token ceiling exists for: ~1 char/token, so a char
+ * cap alone still overflows the batch.
+ *
+ * Pins:
+ * - short prose passes through untouched
+ * - a long document is cut to the char ceiling
+ * - a hex-dense document under the char ceiling is still cut to the token ceiling
+ * - a cut never orphans a UTF-16 surrogate (a lone surrogate is rejected by
+ * serde/nlohmann-based servers, trading the 500 for a 400)
+ * - the cap is applied on the applyReranker path (via the rerankerFn seam)
+ */
+
+import { describe, test, expect } from 'bun:test';
+import * as rerankMod from '../src/core/search/rerank.ts';
+import type { RerankerOpts } from '../src/core/search/rerank.ts';
+// Namespace import on purpose: with the fix reverted, capRerankDoc is undefined and the
+// tests below FAIL at the call site instead of the file crashing at import (a vacuous
+// non-zero exit is not a discrimination result — see scripts/check-test-discriminates.sh).
+const { applyReranker, capRerankDoc } = rerankMod;
+import { estimateTokens } from '../src/core/chunkers/token-estimate.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import type { RerankInput } from '../src/core/ai/gateway.ts';
+
+const MAX_DOC_CHARS = 6000;
+const MAX_DOC_TOKENS = 1400;
+
+// Deterministic hex-dense text: every 8 chars is a distinct nibble run, so
+// cl100k cannot merge it into long tokens.
+function hexDense(chars: number): string {
+ let out = '';
+ let i = 0;
+ while (out.length < chars) {
+ out += (i++ * 2654435761 >>> 0).toString(16).padStart(8, '0') + ' ';
+ }
+ return out.slice(0, chars);
+}
+
+function result(chunk_text: string, i = 0): SearchResult {
+ return {
+ slug: `doc/${i}`,
+ page_id: i + 1,
+ title: `Doc ${i}`,
+ type: 'note',
+ chunk_text,
+ chunk_source: 'compiled_truth',
+ chunk_id: i + 100,
+ chunk_index: 0,
+ score: 1,
+ stale: false,
+ };
+}
+
+describe('capRerankDoc', () => {
+ test('short prose passes through unchanged', () => {
+ const doc = 'A short chunk about channel pricing strategy.';
+ expect(capRerankDoc(doc)).toBe(doc);
+ });
+
+ test('a long document is cut to the char ceiling', () => {
+ const doc = 'word '.repeat(5000); // 25k chars, ~5k tokens
+ const capped = capRerankDoc(doc);
+ expect(capped.length).toBeLessThanOrEqual(MAX_DOC_CHARS);
+ expect(estimateTokens(capped)).toBeLessThanOrEqual(MAX_DOC_TOKENS);
+ });
+
+ test('hex-dense text under the char ceiling is still cut to the token ceiling', () => {
+ const doc = hexDense(MAX_DOC_CHARS - 100);
+ // Positive control: the input itself overflows the token ceiling.
+ expect(estimateTokens(doc)).toBeGreaterThan(MAX_DOC_TOKENS);
+ const capped = capRerankDoc(doc);
+ expect(capped.length).toBeLessThan(doc.length);
+ expect(estimateTokens(capped)).toBeLessThanOrEqual(MAX_DOC_TOKENS);
+ expect(doc.startsWith(capped)).toBe(true); // a prefix, never rewritten
+ });
+
+ test('a cut never orphans a UTF-16 surrogate (emoji-dense text stays well-formed)', () => {
+ // 6001 UTF-16 units; a naive slice(0, 6000) ends in a lone high surrogate,
+ // and the ratio shrink has arbitrary parity too.
+ const doc = 'a' + '😀'.repeat(3000);
+ const capped = capRerankDoc(doc);
+ expect(capped.isWellFormed()).toBe(true);
+ expect(capped.length).toBeLessThanOrEqual(MAX_DOC_CHARS);
+ expect(estimateTokens(capped)).toBeLessThanOrEqual(MAX_DOC_TOKENS);
+ });
+});
+
+describe('applyReranker applies the cap to every document', () => {
+ test('the reranker receives capped documents', async () => {
+ const results = [result(hexDense(20_000), 0), result('tiny', 1)];
+ let seen: RerankInput | null = null;
+ const opts: RerankerOpts = {
+ enabled: true,
+ topNIn: 30,
+ topNOut: null,
+ rerankerFn: async (input) => {
+ seen = input;
+ return [{ index: 0, relevanceScore: 0.9 }, { index: 1, relevanceScore: 0.1 }];
+ },
+ };
+ await applyReranker('q', results, opts);
+ expect(seen).not.toBeNull();
+ const docs = seen!.documents;
+ expect(docs).toHaveLength(2);
+ expect(docs[0].length).toBeLessThanOrEqual(MAX_DOC_CHARS);
+ expect(estimateTokens(docs[0])).toBeLessThanOrEqual(MAX_DOC_TOKENS);
+ expect(docs[1]).toBe('tiny');
+ });
+});
diff --git a/test/resolve-ipc-binding.test.ts b/test/resolve-ipc-binding.test.ts
index 18af80fc04..a29d7efecd 100644
--- a/test/resolve-ipc-binding.test.ts
+++ b/test/resolve-ipc-binding.test.ts
@@ -13,8 +13,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import net from 'node:net';
import { bindResolveIpcForServe } from '../src/mcp/resolve-ipc-binding.ts';
-import { resolveSocketPath } from '../src/core/context/resolve-ipc.ts';
+import { resolveSocketPath, socketHasLiveListener } from '../src/core/context/resolve-ipc.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -85,12 +86,58 @@ describe('both serve transports bind through the shared helper (#4474)', () => {
expect(src).toContain('ipcBinding?.close()');
});
+ it('an exiting serve never blind-unlinks the socket pathname (#4896)', async () => {
+ // A transient serve that lost the bind to a live provider must not
+ // delete that provider's socket on the way out; Bun's server.close()
+ // already unlinks the pathname the listener itself bound.
+ const src = await readSrc('src/mcp/resolve-ipc-binding.ts').text();
+ expect(src).not.toContain('unlinkSync(resolveSocket)');
+ expect(src).not.toContain('rmSync(resolveSocket');
+ // The blind-unlink helper is gone from the module surface entirely.
+ expect(await readSrc('src/core/context/resolve-ipc.ts').text()).not.toContain('export function cleanupStaleSocket');
+ });
+
+ it('the pre-bind owner probe reads a connect timeout as unknown, never as a dead owner (#4896 follow-up)', async () => {
+ // A 250ms connect timeout used to count as "no live listener" and let the
+ // caller clean the socket away — a long-lived serve with a busy event
+ // loop was displaced, the very symptom #4896 fixed. Only a hard connect
+ // error (ENOENT / ECONNREFUSED) may authorize cleanup.
+ const src = await readSrc('src/core/context/resolve-ipc.ts').text();
+ expect(src).toContain("probe.once('timeout', () => finish('unknown'))");
+ expect(src).toContain("probe.once('error', () => finish('dead'))");
+ expect(src).not.toContain("probe.once('timeout', () => finish(false))");
+ // One budget constant, not a literal that can drift from the client's.
+ expect(src).toContain('probe.setTimeout(CLIENT_TIMEOUT_MS)');
+ expect(src).not.toContain('probe.setTimeout(250)');
+ });
+
it('bootstrap verify prefers a live serve socket over self-creating one', async () => {
// verify.ts:hooks smoke used to ALWAYS start its own IPC server, which
// manufactured the condition under test and masked serve postures that
- // never bind IPC. Pin the live-socket branch.
+ // never bind IPC. Pin the live-socket branch — probed for a listener, not
+ // existsSync'd (a dead serve's leftover socket file is not a provider).
const src = await readSrc('src/core/bootstrap/verify.ts').text();
- expect(src).toContain('const liveSocket = existsSync(socketPath)');
+ expect(src).toContain('const liveSocket = await socketHasLiveListener(socketPath)');
+ expect(src).not.toContain('existsSync(socketPath)');
expect(src).toMatch(/if \(!liveSocket\) \{/);
});
+
+ it('socketHasLiveListener: a leftover file at the socket path is not a live provider; a bound listener is', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-ipc-live-'));
+ const sock = join(dir, 'ipc.sock');
+ try {
+ writeFileSync(sock, '');
+ expect(await socketHasLiveListener(sock)).toBe(false);
+ rmSync(sock);
+ const server = net.createServer();
+ await new Promise<void>((resolveListen) => server.listen(sock, resolveListen));
+ try {
+ expect(await socketHasLiveListener(sock)).toBe(true);
+ } finally {
+ await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
diff --git a/test/routing-eval.test.ts b/test/routing-eval.test.ts
index 8b57d4a15b..26871f9fa8 100644
--- a/test/routing-eval.test.ts
+++ b/test/routing-eval.test.ts
@@ -72,6 +72,32 @@ describe('normalizeText', () => {
expect(normalizeText('')).toBe('');
expect(normalizeText(' !! ')).toBe('');
});
+ it('preserves Korean text instead of stripping it to nothing', () => {
+ expect(normalizeText('한국어 문장 다듬어줘')).toBe('한국어 문장 다듬어줘');
+ });
+ it('preserves Chinese and Japanese text', () => {
+ expect(normalizeText('中文测试')).toBe('中文测试');
+ expect(normalizeText('日本語のテスト')).toBe('日本語のテスト');
+ });
+ it('still strips punctuation from non-Latin scripts', () => {
+ expect(normalizeText('한국어, 다듬어줘!')).toBe('한국어 다듬어줘');
+ });
+ it('a non-English trigger still substring-matches a non-English intent', () => {
+ const index = { skillPhrases: new Map([['fluent-korean', ['한국어 다듬']]]) };
+ const result = structuralRouteMatch('이거 한국어 다듬어줄 수 있어?', index);
+ expect(result.matched).toEqual(['fluent-korean']);
+ });
+ it('preserves combining marks (Devanagari vowel signs, Thai tone marks)', () => {
+ expect(normalizeText('हिन्दी में लिखो')).toBe('हिन्दी में लिखो');
+ expect(normalizeText('ค้นหาบันทึก')).toBe('ค้นหาบันทึก');
+ });
+ it('a mixed placeholder trigger does not collapse onto English intents', () => {
+ // `"<email> 처리됨"` used to normalize to the bare token `email`, a
+ // substring of any English intent that mentions email.
+ const index = { skillPhrases: new Map([['loop-completion', extractTriggerPhrases('"<email> 처리됨"')]]) };
+ const result = structuralRouteMatch('fix the typos in this email before I send it', index);
+ expect(result.matched).toEqual([]);
+ });
});
describe('extractTriggerPhrases', () => {
diff --git a/test/scripts/run-unit-parallel.test.ts b/test/scripts/run-unit-parallel.test.ts
index 3f17c66f02..8e938b7dc2 100644
--- a/test/scripts/run-unit-parallel.test.ts
+++ b/test/scripts/run-unit-parallel.test.ts
@@ -20,7 +20,7 @@
*/
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
-import { execFileSync, spawnSync } from 'child_process';
+import { execFileSync, spawn, spawnSync } from 'child_process';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync, chmodSync, symlinkSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join, resolve } from 'path';
@@ -175,6 +175,80 @@ describe('run-unit-parallel.sh timeout escalation contract', () => {
});
});
+describe('run-unit-parallel.sh operator-interrupt cleanup', () => {
+ it('kills an interrupt-resistant shard when its terminal group receives SIGINT', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-parallel-interrupt-'));
+ let child: ReturnType<typeof spawn> | undefined;
+ let bunPid = 0;
+ try {
+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });
+ mkdirSync(join(root, 'test'), { recursive: true });
+ mkdirSync(join(root, 'bin'), { recursive: true });
+ for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh']) {
+ copyFileSync(resolve(REPO_ROOT, 'scripts', s), join(root, 'scripts', s));
+ chmodSync(join(root, 'scripts', s), 0o755);
+ }
+ copyFileSync(TESTENV_SH_SRC, join(root, 'scripts', 'lib', 'test-env.sh'));
+ writeFileSync(join(root, 'test', 'hang.test.ts'), '// discovered by the shard wrapper\n');
+
+ const fakeBun = join(root, 'bin', 'bun');
+ writeFileSync(fakeBun, `#!/usr/bin/env bash
+[ "${'$'}{1:-}" = "test" ] || exit 0
+echo "$$" > "${join(root, 'bun.pid')}"
+trap '' INT TERM
+while true; do sleep 1; done
+`);
+ chmodSync(fakeBun, 0o755);
+
+ child = spawn('bash', [join(root, 'scripts', 'run-unit-parallel.sh'), '--shards', '1'], {
+ cwd: root,
+ env: {
+ ...process.env,
+ PATH: `${join(root, 'bin')}:${process.env.PATH ?? ''}`,
+ GBRAIN_TEST_NO_MEM_ADAPT: '1',
+ GBRAIN_TEST_SHARD_TIMEOUT: '300',
+ },
+ detached: true,
+ stdio: 'ignore',
+ });
+
+ const deadline = Date.now() + 5_000;
+ while (!existsSync(join(root, 'bun.pid')) && Date.now() < deadline) {
+ await Bun.sleep(25);
+ }
+ expect(existsSync(join(root, 'bun.pid'))).toBe(true);
+ bunPid = Number(readFileSync(join(root, 'bun.pid'), 'utf8').trim());
+
+ const proc = child;
+ const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolveExit) => {
+ proc.once('exit', (code, signal) => resolveExit({ code, signal }));
+ process.kill(-proc.pid!, 'SIGINT');
+ });
+ // handle_interrupt runs cleanup_children then `exit 130` — a raw SIGINT
+ // death would mean the trap never ran (cleanup skipped).
+ expect(exit.code).toBe(130);
+
+ const goneDeadline = Date.now() + 2_000;
+ let liveState = '';
+ do {
+ const probe = spawnSync('ps', ['-o', 'stat=', '-p', String(bunPid)], { encoding: 'utf8' });
+ liveState = (probe.stdout || '').trim();
+ if (!liveState || liveState.startsWith('Z')) break;
+ await Bun.sleep(25);
+ } while (Date.now() < goneDeadline);
+ // A zombie owns no memory and only awaits launchd reaping; any other
+ // state means the cancelled suite is still doing or retaining work.
+ expect(!liveState || liveState.startsWith('Z')).toBe(true);
+ } finally {
+ // Reap the detached tree BEFORE the fixture dir goes: a failed assertion
+ // above must not leave the fake-bun loop (its own process group) alive.
+ if (child?.pid) { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* already gone */ } }
+ if (bunPid) { try { process.kill(bunPid, 'SIGKILL'); } catch { /* already gone */ } }
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 15_000);
+});
+
describe('run-unit-parallel.sh no-timeout-binary fallback (rc from shard wait, not watchdog teardown)', () => {
// Forces the no-gtimeout/no-timeout branch by running the wrapper under a
// curated PATH that has every tool the scripts call EXCEPT timeout
diff --git a/test/scripts/run-unit-shard.test.ts b/test/scripts/run-unit-shard.test.ts
index 1b3a08aa59..e7a343b4f2 100644
--- a/test/scripts/run-unit-shard.test.ts
+++ b/test/scripts/run-unit-shard.test.ts
@@ -15,6 +15,7 @@
import { describe, it, expect } from 'bun:test';
import { execFileSync } from 'child_process';
+import { readFileSync } from 'fs';
import { resolve } from 'path';
const REPO_ROOT = resolve(import.meta.dir, '..', '..');
@@ -54,3 +55,29 @@ describe('run-unit-shard.sh exclusion symmetry', () => {
expect(leaks).toEqual([]);
});
});
+
+describe('run-unit-shard.sh timeout multiplier reach', () => {
+ // GBRAIN_TEST_TIMEOUT_MULTIPLIER scales bun's `--timeout`, which only sets
+ // the DEFAULT per-test ceiling — an explicit `test(name, fn, N)` third
+ // argument overrides it and stays fixed under 4-way container contention.
+ // Files that spawn the CLI through test/helpers/cli-spawn.ts are the ones
+ // the multiplier exists for (a full `bun src/cli.ts` boot, often a PGLite
+ // cold start), and cli-spawn's own kill timer already reaps a hung child,
+ // so a hand-pinned ceiling below the runner default only hides the file
+ // from the multiplier (#4659). Pins at/above the default are left alone.
+ it('cli-spawn consumers pin no per-test timeout below the bunfig default', () => {
+ const bunfig = readFileSync(resolve(REPO_ROOT, 'bunfig.toml'), 'utf-8');
+ const defaultMs = Number(/^timeout\s*=\s*([\d_]+)/m.exec(bunfig)![1].replace(/_/g, ''));
+ const offenders: string[] = [];
+ for (const file of dryRunList()) {
+ const src = readFileSync(resolve(REPO_ROOT, file), 'utf-8');
+ if (!src.includes('helpers/cli-spawn')) continue;
+ // Trailing numeric literal (>= 4 digits) as a call's last argument.
+ for (const m of src.matchAll(/,\s*(\d[\d_]{3,})\s*\)\s*;/g)) {
+ const ms = Number(m[1].replace(/_/g, ''));
+ if (ms < defaultMs) offenders.push(`${file}: ${m[0].trim()} (< ${defaultMs})`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/test/search-mode-config-snapshot.test.ts b/test/search-mode-config-snapshot.test.ts
new file mode 100644
index 0000000000..3a1988c541
--- /dev/null
+++ b/test/search-mode-config-snapshot.test.ts
@@ -0,0 +1,75 @@
+import { test, expect, describe } from 'bun:test';
+import { loadSearchModeConfig, SEARCH_MODE_CONFIG_KEYS } from '../src/core/search/mode.ts';
+
+/**
+ * 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.
+ */
+function countingEngine(rows: Record<string, string>) {
+ const calls = { getConfig: 0, getAllConfig: 0 };
+ return {
+ calls,
+ async getConfig(key: string): Promise<string | null> {
+ calls.getConfig++;
+ return rows[key] ?? null;
+ },
+ async getAllConfig(): Promise<Record<string, string>> {
+ calls.getAllConfig++;
+ return { ...rows };
+ },
+ };
+}
+
+function perKeyOnlyEngine(rows: Record<string, string>) {
+ const { calls, getConfig } = countingEngine(rows);
+ return { calls, getConfig };
+}
+
+describe('loadSearchModeConfig config reads', () => {
+ test('an engine with getAllConfig is read once, with no per-key reads', async () => {
+ const engine = countingEngine({ 'search.mode': 'balanced' });
+ const out = await loadSearchModeConfig(engine);
+ expect(out.mode).toBe('balanced');
+ expect(engine.calls.getAllConfig).toBe(1);
+ expect(engine.calls.getConfig).toBe(0);
+ });
+
+ test('an engine without getAllConfig falls back to one read per key', async () => {
+ // Engines implemented outside this repo may not have the bulk read.
+ const engine = perKeyOnlyEngine({ 'search.mode': 'balanced' });
+ const out = await loadSearchModeConfig(engine);
+ expect(out.mode).toBe('balanced');
+ expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 1);
+ });
+
+ test('the snapshot path returns the same values as per-key reads', async () => {
+ const rows = {
+ 'search.mode': 'tokenmax',
+ 'search.reranker.top_n_in': '15',
+ 'search.autocut_jump': '1.0',
+ 'search.limit': '7',
+ };
+ const viaSnapshot = await loadSearchModeConfig(countingEngine(rows));
+ const perKey = await loadSearchModeConfig(perKeyOnlyEngine(rows));
+ expect(viaSnapshot).toEqual(perKey);
+ expect(viaSnapshot.mode).toBe('tokenmax');
+ });
+
+ test('a failing getAllConfig falls back to per-key reads and still resolves the mode', async () => {
+ const engine = countingEngine({ 'search.mode': 'conservative' });
+ engine.getAllConfig = async () => {
+ engine.calls.getAllConfig++;
+ throw new Error('relation "config" does not exist');
+ };
+ const out = await loadSearchModeConfig(engine);
+ expect(out.mode).toBe('conservative');
+ expect(engine.calls.getAllConfig).toBe(1);
+ expect(engine.calls.getConfig).toBe(SEARCH_MODE_CONFIG_KEYS.length + 1);
+ });
+});
diff --git a/test/serve-stdio-lifecycle.test.ts b/test/serve-stdio-lifecycle.test.ts
index 1adbab37f4..2db6a78d50 100644
--- a/test/serve-stdio-lifecycle.test.ts
+++ b/test/serve-stdio-lifecycle.test.ts
@@ -1,6 +1,7 @@
import { describe, test, expect, afterEach } from 'bun:test';
import { EventEmitter } from 'events';
import { spawnSync } from 'node:child_process';
+import { PassThrough } from 'node:stream';
import {
runServe,
isPidAlive,
@@ -410,6 +411,37 @@ describe('runServe stdio lifecycle', () => {
expect(h.engine.disconnectCalls).toBe(1);
});
+ test('--stdio-idle-timeout leaves stdin paused until the MCP transport listener is attached', async () => {
+ const h = makeHarness();
+ const stdin = new PassThrough();
+ h.opts.stdin = stdin;
+ const initializeFrame = '{"jsonrpc":"2.0","id":1,"method":"initialize"}\n';
+ let sdkReceived = '';
+
+ h.opts.startMcpServer = async () => {
+ // Model a fast MCP client: it writes initialize while startMcpServer is
+ // still booting, immediately before StdioServerTransport adds its data
+ // listener. A paused Readable buffers this frame for the SDK. Any earlier
+ // lifecycle data listener flips the stream to flowing mode and consumes
+ // the frame before the SDK can observe it.
+ stdin.write(initializeFrame);
+ stdin.on('data', (chunk: Buffer) => { sdkReceived += chunk.toString('utf8'); });
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ };
+
+ await runServe(
+ h.engine as unknown as BrainEngine,
+ ['--stdio-idle-timeout', '60'],
+ h.opts,
+ );
+
+ expect(sdkReceived).toBe(initializeFrame);
+
+ h.signals.emit('SIGTERM');
+ await h.exited;
+ stdin.destroy();
+ });
+
test('idle timer is reset on every stdin data chunk', async () => {
const h = makeHarness();
// Use a very short timeout so we can observe the firing/resetting
diff --git a/test/sources-list-scope.test.ts b/test/sources-list-scope.test.ts
index 85f574b117..5e4955bfbb 100644
--- a/test/sources-list-scope.test.ts
+++ b/test/sources-list-scope.test.ts
@@ -129,3 +129,20 @@ describe('sources_list — caller source grant (#4433)', () => {
expect(ids).not.toContain('restricted');
});
});
+
+describe('sources_list / sources_status — description discloses scope filtering (#4811)', () => {
+ // The op description is emitted verbatim into MCP tools/list, so it is the
+ // contract an agent reads. A scoped caller gets a row-filtered listing with
+ // no marker; the description must say so or the caller reads a partial
+ // listing as the full registry.
+ test('sources_list description names the caller source scope', () => {
+ expect(op.description).toMatch(/source scope/i);
+ expect(op.description).toMatch(/gbrain sources list/);
+ });
+
+ test('sources_status description names the scope + not_found posture', () => {
+ const status = operations.find((o) => o.name === 'sources_status')!;
+ expect(status.description).toMatch(/source scope/i);
+ expect(status.description).toMatch(/not_found/);
+ });
+});
diff --git a/test/sources-load.test.ts b/test/sources-load.test.ts
index cd436a48b6..7f1ffb7ea5 100644
--- a/test/sources-load.test.ts
+++ b/test/sources-load.test.ts
@@ -13,6 +13,7 @@ import {
parseSourceConfig,
normalizeSourceConfig,
isSourceFederated,
+ sourceLocalPathSkipWarning,
} from '../src/core/sources-load.ts';
let engine: PGLiteEngine;
@@ -196,3 +197,49 @@ describe('isSourceFederated', () => {
expect(isSourceFederated(['{"remote_url":"x"}', { federated: true }])).toBe(true);
});
});
+
+describe('sourceLocalPathSkipWarning', () => {
+ test('keeps existing absolute checkouts dispatchable', () => {
+ expect(sourceLocalPathSkipWarning('present', '/repos/brain', (p) => p === '/repos/brain')).toBeNull();
+ });
+
+ test('skips relative local_path rows before consulting the filesystem', () => {
+ const asked: string[] = [];
+ const warn = sourceLocalPathSkipWarning('legacy', 'notes/brain', (p) => {
+ asked.push(p);
+ return true;
+ });
+ expect(asked).toEqual([]);
+ expect(warn).toContain("source 'legacy'");
+ expect(warn).toContain('relative local_path');
+ });
+
+ test('skips absolute paths missing from this machine', () => {
+ const warn = sourceLocalPathSkipWarning('foreign', '/missing/brain', () => false);
+ expect(warn).toContain("source 'foreign'");
+ expect(warn).toContain('/missing/brain');
+ expect(warn).toContain('does not exist on this machine');
+ });
+
+ test('allows missing managed remote clones to reach sync recovery', () => {
+ expect(
+ sourceLocalPathSkipWarning(
+ 'managed',
+ '/missing/managed',
+ () => false,
+ { remote_url: 'https://github.com/example/repo', managed_clone: true },
+ ),
+ ).toBeNull();
+ });
+
+ test('still skips missing unowned remote-url paths', () => {
+ const warn = sourceLocalPathSkipWarning(
+ 'foreign',
+ '/Users/other/repo',
+ () => false,
+ { remote_url: 'https://github.com/example/repo' },
+ );
+ expect(warn).toContain("source 'foreign'");
+ expect(warn).toContain('does not exist on this machine');
+ });
+});
diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.ts
index 64861cda17..5d664b6935 100644
--- a/test/subagent-handler.test.ts
+++ b/test/subagent-handler.test.ts
@@ -715,8 +715,10 @@ describe('handler-entry capability gate on the config-resolved model', () => {
// The queue submit gate only sees explicit data.model. A job that omits
// data.model resolves `models.subagent` inside the handler — pre-fix that
// path bypassed the capability check entirely and a tool-incapable model
- // (declared supports_tools: false) ran the loop anyway.
- await engine.setConfig('models.subagent', 'minimax:MiniMax-M2');
+ // (declared supports_tools: false) ran the loop anyway. Fixture is the
+ // nvidia recipe: it still declares supports_tools: false (minimax flipped
+ // to true in #4782, so it no longer exercises the no_tools path).
+ await engine.setConfig('models.subagent', 'nvidia:nvidia/nemotron-3-super-120b-a12b');
try {
const client = new FakeMessagesClient([
{ content: [{ type: 'text', text: 'should never run' }] as any, stop_reason: 'end_turn' },
@@ -740,7 +742,7 @@ describe('handler-entry capability gate on the config-resolved model', () => {
// non-Anthropic models regardless). The gateway path's terminal
// early-return runs before any provider client is constructed, so no
// API key is needed.
- await engine.setConfig('models.subagent', 'minimax:MiniMax-M2');
+ await engine.setConfig('models.subagent', 'nvidia:nvidia/nemotron-3-super-120b-a12b');
await engine.setConfig('agent.use_gateway_loop', 'true');
try {
const client = new FakeMessagesClient([]);
@@ -776,7 +778,7 @@ describe('handler-entry capability gate on the config-resolved model', () => {
// A gateway transcript persists pending dispatch as `tool-call` blocks.
// A replay that still needs the loop to resume on the provider must NOT
// slip past the capability gate via the terminal exception.
- await engine.setConfig('models.subagent', 'minimax:MiniMax-M2');
+ await engine.setConfig('models.subagent', 'nvidia:nvidia/nemotron-3-super-120b-a12b');
await engine.setConfig('agent.use_gateway_loop', 'true');
try {
const client = new FakeMessagesClient([]);
@@ -938,6 +940,9 @@ describe('resolveMaxOutputTokens model-aware default', () => {
expect(resolveMaxOutputTokens(undefined, null, 'openrouter:anthropic/claude-sonnet-5')).toBe(32000);
expect(resolveMaxOutputTokens(undefined, null, 'anthropic:claude-fable-5')).toBe(32000);
});
+ test('recipe-declared thinking models (DeepSeek v4) get 32000 too (#4172)', () => {
+ expect(resolveMaxOutputTokens(undefined, null, 'deepseek:deepseek-v4-flash')).toBe(32000);
+ });
test('non-thinking models keep 8192', () => {
expect(resolveMaxOutputTokens(undefined, null, 'anthropic:claude-sonnet-4-6')).toBe(8192);
expect(resolveMaxOutputTokens(undefined, null, 'anthropic:claude-3-5-sonnet-20241022')).toBe(8192);
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index 7992c9b51b..d7c57d829e 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -27,6 +27,9 @@ import { _resetStdoutRedirectForTests } from '../src/core/console-prefix.ts';
import type { CapabilityReport } from '../src/core/capability.ts';
import { __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
import { runServe, type ServeOptions } from '../src/commands/serve.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
const KEYLESS: CapabilityReport = {
embeddings: { available: false },
@@ -210,6 +213,57 @@ describe('runMaintenanceSweep — link/timeline extraction [CX-P0.3]', () => {
await engine.setConfig('auto_timeline', 'true');
}
});
+
+ // #3757: the sweep shares resolveCandidateSources with `extract links
+ // --source db` but never received the #2589 `link_resolution.cross_source`
+ // opt-in, so a page linking a target that exists only in another source
+ // was dropped silently — and the reconcile then deleted the very edge the
+ // CLI extract had created.
+ describe('cross-source opt-in (#3757)', () => {
+ const CROSS = { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' };
+ const sweep = () => runMaintenanceSweep(engine, {
+ sourceId: 'default', capabilities: KEYLESS, budgetMs: 30_000,
+ });
+ const toSources = () => engine.executeRaw<{ source_id: string }>(
+ `SELECT pt.source_id FROM links l
+ JOIN pages pf ON pf.id = l.from_page_id
+ JOIN pages pt ON pt.id = l.to_page_id
+ WHERE pf.slug = 'notes/n1'`,
+ );
+ beforeEach(async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('vault-a', 'vault-a') ON CONFLICT (id) DO NOTHING`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice-example', 'vault-a', 'person', 'Alice', 'A person page.', '')`,
+ );
+ await seedPage('notes/n1', 'note', 'Talked to [[people/alice-example]] today.');
+ });
+
+ test('flag ON: the edge into the other source is created', async () => {
+ const r = await withEnv(CROSS, sweep);
+ expect(r.linksExtracted).toBe(1);
+ expect(await toSources()).toEqual([{ source_id: 'vault-a' }]);
+ });
+
+ test('flag ON: an edge the CLI extract created survives the sweep reconcile', async () => {
+ await engine.addLinksBatch([{
+ from_slug: 'notes/n1', to_slug: 'people/alice-example', link_type: 'mentions',
+ context: 'ctx', link_source: 'markdown',
+ from_source_id: 'default', to_source_id: 'vault-a', origin_source_id: 'default',
+ }]);
+ const r = await withEnv(CROSS, sweep);
+ expect(r.linksRemoved).toBe(0);
+ expect(await toSources()).toEqual([{ source_id: 'vault-a' }]);
+ });
+
+ test('flag OFF: the drop is counted in the skip ledger, not silent', async () => {
+ const r = await withEnv({ GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined }, sweep);
+ expect(await toSources()).toEqual([]);
+ expect(r.skipped).toContainEqual({ reason: 'cross_source_link', count: 1 });
+ });
+ });
});
describe('runMaintenanceSweep — watermark progress + link reconciliation (#4196)', () => {
@@ -280,6 +334,27 @@ describe('runMaintenanceSweep — watermark progress + link reconciliation (#419
expect(after.map(e => e.link_source).sort()).toEqual(['manual', 'mentions']);
});
+ test('#4873: a ./-relative markdown edge from the FS extractor survives reconcile', async () => {
+ // The FS path (sync / `extract links`) resolves `[Beta](./beta.md)` via
+ // join(fileDir, target) and writes the edge with link_source NULL. The
+ // sweep's desired set must contain it or #4196 prunes a live edge on the
+ // first updated_at bump that doesn't re-run the FS extractor.
+ await seedPageAt('wiki/notes/beta', 'Beta page.', minsAgo(2));
+ await seedPageAt('wiki/notes/alpha', 'See [Beta](./beta.md).', minsAgo(1));
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT f.id, t.id, 'mentions', 'markdown link: [Beta]', NULL
+ FROM pages f, pages t
+ WHERE f.slug = 'wiki/notes/alpha' AND t.slug = 'wiki/notes/beta'`,
+ );
+ const report = await runMaintenanceSweep(engine, {
+ sourceId: 'default', capabilities: KEYLESS, budgetMs: 30_000,
+ });
+ expect(report.linksRemoved).toBe(0);
+ const edges = await engine.getLinks('wiki/notes/alpha', { sourceId: 'default' });
+ expect(edges.map(e => e.to_slug)).toContain('wiki/notes/beta');
+ });
+
test('reconciliation never touches pages outside the sweep batch', async () => {
// A page last updated outside the recentDays window keeps its edges even
// though the sweep runs over the same source.
@@ -914,3 +989,117 @@ describe('runSweep CLI arg parsing [CX2-5]', () => {
expect(out).toContain('budget_exhausted:facts_fence');
});
});
+
+/**
+ * #4611 residual — the sweep is the third caller of the shared
+ * resolveCandidateSources helper and must thread the same two knobs the
+ * extract paths do (`link_resolution.cross_source`, `sources.default`).
+ * Pre-fix it passed none, so on the sweep path the fallback compared against
+ * the LITERAL 'default' and the flag was ignored — and reconciliation then
+ * REMOVED the cross-source edge a flag-on `extract links` had just written.
+ */
+describe('#4611 sweep honors link_resolution.cross_source + sources.default', () => {
+ const sweep = () => runMaintenanceSweep(engine, {
+ sourceId: 'default', capabilities: KEYLESS, budgetMs: 30_000,
+ });
+ const edgesInto = async (toSource: string) => {
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*) AS n FROM links l
+ JOIN pages pf ON pf.id = l.from_page_id
+ JOIN pages pt ON pt.id = l.to_page_id
+ WHERE pf.slug = 'notes/writer-example' AND pf.source_id = 'default'
+ AND pt.slug = 'people/alice-example' AND pt.source_id = $1`,
+ [toSource],
+ );
+ return parseInt(rows[0].n, 10);
+ };
+ async function seedForeignTarget(source: string) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [source],
+ );
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice-example', $1, 'person', 'Alice', 'A person page.', '')`, [source],
+ );
+ await seedPage('notes/writer-example', 'note', 'See [Alice](people/alice-example).');
+ }
+
+ afterEach(async () => {
+ await engine.executeRaw(`DELETE FROM config WHERE key IN ('link_resolution.cross_source', 'sources.default')`);
+ await engine.executeRaw(`UPDATE sources SET config = config - 'federated' WHERE id = 'default'`);
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw(`DELETE FROM sources WHERE id <> 'default'`);
+ });
+
+ test('flag on: a link whose target lives only in another source produces the edge', async () => {
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ await seedForeignTarget('vault-a');
+ await sweep();
+ expect(await edgesInto('vault-a')).toBe(1);
+ });
+
+ test('flag on: the sweep keeps the cross-source edge a flag-on extract just wrote', async () => {
+ await engine.setConfig('link_resolution.cross_source', 'true');
+ await seedForeignTarget('vault-a');
+ await runExtract(engine, ['links', '--source', 'db']);
+ expect(await edgesInto('vault-a')).toBe(1);
+ // extract stamped links_extracted_at; a later edit makes the page stale
+ // again so the sweep's batch actually re-selects (and reconciles) it.
+ await engine.executeRaw(`UPDATE pages SET updated_at = now() WHERE slug = 'notes/writer-example'`);
+ const r = await sweep();
+ expect(r.linksRemoved).toBe(0);
+ expect(await edgesInto('vault-a')).toBe(1);
+ });
+
+ test('flag off, federated origin: the fallback lane follows the configured sources.default', async () => {
+ await engine.setConfig('sources.default', 'main-vault');
+ await engine.executeRaw(
+ `UPDATE sources SET config = jsonb_set(config, '{federated}', 'true'::jsonb) WHERE id = 'default'`,
+ );
+ await seedForeignTarget('main-vault');
+ await sweep();
+ expect(await edgesInto('main-vault')).toBe(1);
+ });
+});
+
+// ─── wave review: the facts pass surfaces the reconcile's refusals ──
+describe('runMaintenanceSweep — facts reconcile warnings reach the sweep log', () => {
+ test('a stale pages cache (canonical file newer than the DB body) logs FACTS_PAGE_CACHE_STALE instead of vanishing', async () => {
+ // runExtractFacts REFUSES destructive reconcile when the canonical file
+ // disagrees with pages.compiled_truth and says so in r.warnings. The sweep
+ // dropped r.warnings on the floor, so an operator saw factsReconciled: 0
+ // and nothing else — indistinguishable from "nothing to do".
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-sweep-stale-cache-'));
+ tmpDirs.push(root);
+ _resetWriteThroughCacheForTest();
+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = 'default'`, [root]);
+ try {
+ await seedPage('people/alice-example', 'person', FENCE_BODY);
+ // A fence-owned DB row the fence no longer carries: the reconcile must
+ // take its destructive branch, which is where the stale-cache refusal lives.
+ await engine.insertFacts(
+ [{ fact: 'Stale indexed row', kind: 'fact', source: 'stale', row_num: 7, source_markdown_slug: 'people/alice-example' }],
+ { source_id: 'default' },
+ );
+ mkdirSync(join(root, 'people'), { recursive: true });
+ // The file carries a row the DB body does not: the cache is stale.
+ writeFileSync(join(root, 'people', 'alice-example.md'), FENCE_BODY.replace(
+ '<!--- gbrain:facts:end -->',
+ '| 3 | Joined the board of widget-co | fact | 1.0 | world | high | 2026-09-01 | | test | |\n<!--- gbrain:facts:end -->',
+ ), 'utf-8');
+
+ const lines: string[] = [];
+ const r = await runMaintenanceSweep(engine, {
+ sourceId: 'default',
+ capabilities: KEYLESS,
+ log: (msg: string) => { lines.push(msg); },
+ });
+ expect(r.factsReconciled).toBe(0);
+ expect(lines.some((l) => l.includes('FACTS_PAGE_CACHE_STALE'))).toBe(true);
+ } finally {
+ await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
+ _resetWriteThroughCacheForTest();
+ }
+ });
+});
diff --git a/test/sync-index-matches-tree.serial.test.ts b/test/sync-index-matches-tree.serial.test.ts
new file mode 100644
index 0000000000..2188e9d557
--- /dev/null
+++ b/test/sync-index-matches-tree.serial.test.ts
@@ -0,0 +1,216 @@
+/**
+ * One invariant, four lifecycle stages (#4899, #4900):
+ *
+ * after ANY sync that reports success, the set of pages for the source
+ * equals the set of syncable files in the working tree.
+ *
+ * The two failure signatures name which fix regressed:
+ *
+ * missing: [...] -> performSyncInner no longer resolves the source's
+ * persisted `config.strategy`, so a caller that passes
+ * no --strategy walks as 'markdown' and code files are
+ * never imported (and modified ones are DELETED).
+ * ghosts: [...] -> importCodeFile no longer writes `source_path`, so the
+ * full-sync delete-reconcile cannot see code pages and
+ * deleted files are served forever.
+ *
+ * The `strategy precedence` block pins the other half of that resolution: an
+ * explicit `strategy` option beats the persisted `config.strategy`, and a
+ * persisted value outside markdown|code|auto is IGNORED (classifySync in
+ * core/sync.ts then falls back to 'markdown'), never honored.
+ *
+ * HONEST LIMIT: drift() derives both sides from gbrain's own enumerator and
+ * slug function, so it pins the sync WIRING, not the enumerator itself. The
+ * literal slug list in S1 is the only assertion here that does not derive
+ * from the code under test; keep it.
+ *
+ * Hermetic: in-memory PGLite + a throwaway git repo under $TMPDIR. No
+ * network, no Neon, no fixtures on disk. ~7s.
+ *
+ * Setup is lazy (ensureSetup) rather than in beforeAll ON PURPOSE: bun caps
+ * HOOKS at a hard 5s and bunfig.toml's `timeout = 60_000` does NOT govern
+ * them (measured: an 8s beforeAll dies at 5002ms under a bare `bun test`,
+ * and passes with --timeout=60000). PGLite connect+initSchema sits right at
+ * that edge, so a beforeAll here would flake on the first cold run after a
+ * rebase — the one run that matters.
+ */
+import { describe, test, expect, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, rmSync, mkdirSync, unlinkSync } from 'fs';
+import { join, relative } from 'path';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { collectSyncableFiles } from '../src/commands/import.ts';
+import { resolveSlugForPath } from '../src/core/sync.ts';
+
+const SID = 'default';
+const STRATEGY = 'auto' as const;
+// No `strategy` key: this is the caller shape used by the dream cycle
+// (core/cycle.ts), the MCP sync op (core/operations.ts), the autopilot
+// freshness lane and the single-source CLI path. Passing one here would
+// make the guard blind to the strategy-resolution patch.
+const OPTS = { noEmbed: true, noExtract: true, noPull: true, sourceId: SID } as const;
+
+// GBRAIN_HOME at module top level, before any src/ import can read config.
+const home = mkdtempSync(join(tmpdir(), 'gb-tw-home-'));
+process.env.GBRAIN_HOME = home;
+
+let engine: PGLiteEngine | null = null;
+let repo = '';
+let setupPromise: Promise<void> | null = null;
+const extraRepos: string[] = [];
+
+const commit = (m: string) =>
+ execSync(`git add -A && git commit -qm ${JSON.stringify(m)}`, { cwd: repo, stdio: 'pipe' });
+
+async function ensureSetup(): Promise<void> {
+ setupPromise ??= (async () => {
+ const e = new PGLiteEngine();
+ await e.connect({});
+ await e.initSchema();
+ await e.executeRaw(
+ `UPDATE sources SET config = coalesce(config,'{}'::jsonb) || '{"strategy":"auto"}'::jsonb WHERE id=$1`,
+ [SID],
+ );
+ engine = e;
+ repo = mkdtempSync(join(tmpdir(), 'gb-tw-repo-'));
+ execSync('git init -q && git config user.email t@t && git config user.name T', { cwd: repo, stdio: 'pipe' });
+ mkdirSync(join(repo, 'lib'), { recursive: true });
+ mkdirSync(join(repo, 'docs'), { recursive: true });
+ writeFileSync(join(repo, 'docs/a.md'), '---\ntype: note\ntitle: A\n---\n\nbody a\n');
+ writeFileSync(join(repo, 'lib/a.dart'), 'class A {}\n');
+ // Mixed case and non-ASCII on purpose: a source_path that is lowercased
+ // or re-encoded on the way in still satisfies isSyncable, so the
+ // reconcile would delete a LIVE page. That shows up here as `missing`.
+ writeFileSync(join(repo, 'lib/MixedCase.dart'), 'class MixedCase {}\n');
+ writeFileSync(join(repo, 'lib/été.dart'), 'class Ete {}\n');
+ commit('init');
+ })();
+ await setupPromise;
+}
+
+async function drift(): Promise<{ missing: string[]; ghosts: string[] }> {
+ const expected = new Set(
+ collectSyncableFiles(repo, { strategy: STRATEGY })
+ .map((abs) => relative(repo, abs))
+ .map((rel) => resolveSlugForPath(rel)),
+ );
+ const rows = await engine!.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL`,
+ [SID],
+ );
+ const actual = new Set(rows.map((r) => r.slug));
+ return {
+ missing: [...expected].filter((s) => !actual.has(s)).sort(),
+ ghosts: [...actual].filter((s) => !expected.has(s)).sort(),
+ };
+}
+
+/** Throwaway repo with one markdown + one code file, committed. */
+function mkMixedRepo(): string {
+ const r = mkdtempSync(join(tmpdir(), 'gb-tw-mixed-'));
+ extraRepos.push(r);
+ execSync('git init -q && git config user.email t@t && git config user.name T', { cwd: r, stdio: 'pipe' });
+ mkdirSync(join(r, 'docs'));
+ mkdirSync(join(r, 'lib'));
+ writeFileSync(join(r, 'docs/x.md'), '---\ntype: note\ntitle: X\n---\n\nbody x\n');
+ writeFileSync(join(r, 'lib/x.ts'), 'export const x = 1;\n');
+ execSync('git add -A && git commit -qm init', { cwd: r, stdio: 'pipe' });
+ return r;
+}
+
+/** Persist `config.strategy` on a fresh source row, the way ensureSetup does for SID. */
+async function addSource(sid: string, strategy: string, localPath: string): Promise<void> {
+ await engine!.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, jsonb_build_object('strategy', $3::text))`,
+ [sid, localPath, strategy],
+ );
+}
+
+async function slugsFor(sid: string): Promise<string[]> {
+ const rows = await engine!.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL`,
+ [sid],
+ );
+ return rows.map((r) => r.slug).sort();
+}
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ if (repo) rmSync(repo, { recursive: true, force: true });
+ for (const r of extraRepos) rmSync(r, { recursive: true, force: true });
+});
+
+describe('index matches tree at every lifecycle stage', () => {
+ test('S1 first sync, caller passes no strategy', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ const r = await performSync(engine!, { repoPath: repo, ...OPTS });
+ expect(r.status).toBe('first_sync');
+ expect(await drift()).toEqual({ missing: [], ghosts: [] });
+ const rows = await engine!.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL`,
+ [SID],
+ );
+ expect(rows.map((r2) => r2.slug).sort()).toEqual(
+ ['docs/a', 'lib-a-dart', 'lib-mixedcase-dart', 'lib-ete-dart'].sort(),
+ );
+ }, 120_000);
+
+ test('S2 incremental ADD of one markdown + one code file', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ writeFileSync(join(repo, 'docs/b.md'), '---\ntype: note\ntitle: B\n---\n\nbody b\n');
+ writeFileSync(join(repo, 'lib/b.dart'), 'class B {}\n');
+ commit('add');
+ await performSync(engine!, { repoPath: repo, ...OPTS });
+ expect(await drift()).toEqual({ missing: [], ghosts: [] });
+ }, 120_000);
+
+ test('S3 incremental DELETE of one markdown + one code file', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ unlinkSync(join(repo, 'docs/b.md'));
+ unlinkSync(join(repo, 'lib/b.dart'));
+ commit('rm');
+ await performSync(engine!, { repoPath: repo, ...OPTS });
+ expect(await drift()).toEqual({ missing: [], ghosts: [] });
+ }, 120_000);
+
+ test('S4 FULL re-sync after a code file was removed', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ unlinkSync(join(repo, 'lib/a.dart'));
+ commit('rm a.dart');
+ await performSync(engine!, { repoPath: repo, ...OPTS, full: true });
+ expect(await drift()).toEqual({ missing: [], ghosts: [] });
+ }, 120_000);
+});
+
+describe('strategy precedence', () => {
+ test('explicit strategy option wins over persisted config.strategy', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ const r = mkMixedRepo();
+ await addSource('prec-explicit', 'auto', r);
+ const res = await performSync(engine!, {
+ repoPath: r, ...OPTS, sourceId: 'prec-explicit', strategy: 'markdown',
+ });
+ expect(res.status).toBe('first_sync');
+ // Persisted 'auto' would have imported lib-x-ts too; only the markdown page lands.
+ expect(await slugsFor('prec-explicit')).toEqual(['docs/x']);
+ }, 120_000);
+
+ test('bogus persisted config.strategy is ignored, not honored', async () => {
+ await ensureSetup();
+ const { performSync } = await import('../src/commands/sync.ts');
+ const r = mkMixedRepo();
+ await addSource('prec-bogus', 'bogus-strategy', r);
+ // No strategy option: the out-of-set persisted value is skipped, classifySync
+ // falls back to 'markdown', and the sync completes with the code file left out.
+ const res = await performSync(engine!, { repoPath: r, ...OPTS, sourceId: 'prec-bogus' });
+ expect(res.status).toBe('first_sync');
+ expect(await slugsFor('prec-bogus')).toEqual(['docs/x']);
+ }, 120_000);
+});
diff --git a/test/sync-json-stdout-clean.test.ts b/test/sync-json-stdout-clean.test.ts
new file mode 100644
index 0000000000..f2cf0deeae
--- /dev/null
+++ b/test/sync-json-stdout-clean.test.ts
@@ -0,0 +1,171 @@
+/**
+ * #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.
+ *
+ * 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.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execSync } 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';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let repoPath: string;
+let home: string;
+
+const FOO = (body: string) => `---\ntype: concept\ntitle: Foo\n---\n\n${body}\n`;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-4888-home-'));
+ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-4888-repo-'));
+ 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, 'topics'), { recursive: true });
+ writeFileSync(join(repoPath, 'topics/foo.md'), FOO('baseline.'));
+ execSync('git add -A && git commit -q -m initial', { cwd: repoPath, stdio: 'pipe' });
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path) VALUES ('default', 'default', $1)
+ ON CONFLICT (id) DO UPDATE SET local_path = EXCLUDED.local_path`,
+ [repoPath],
+ );
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(repoPath, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+});
+
+/** runSync with stdout and stderr split-captured (console.* AND the raw streams). */
+async function run(args: string[]): Promise<{ stdout: string[]; stderr: string[] }> {
+ const { runSync } = await import('../src/commands/sync.ts');
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ const str = (c: unknown) => (typeof c === 'string' ? c : JSON.stringify(c));
+ const origLog = console.log;
+ const origErr = console.error;
+ const origOut = process.stdout.write.bind(process.stdout);
+ const origErrWrite = process.stderr.write.bind(process.stderr);
+ const origExit = process.exit;
+ console.log = (...a: unknown[]) => { stdout.push(a.map(str).join(' ') + '\n'); };
+ console.error = (...a: unknown[]) => { stderr.push(a.map(str).join(' ') + '\n'); };
+ process.stdout.write = ((c: unknown) => { stdout.push(String(c)); return true; }) as typeof process.stdout.write;
+ process.stderr.write = ((c: unknown) => { stderr.push(String(c)); return true; }) as typeof process.stderr.write;
+ process.exit = ((code?: number) => { throw new Error(`__exit__${code}`); }) as typeof process.exit;
+ try {
+ await withEnv(
+ { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_SOURCE: undefined, GBRAIN_ALLOW_DEFAULT_WRITE: undefined },
+ () => runSync(engine, args),
+ );
+ } finally {
+ process.exit = origExit;
+ console.log = origLog;
+ console.error = origErr;
+ process.stdout.write = origOut;
+ process.stderr.write = origErrWrite;
+ }
+ return { stdout, stderr };
+}
+
+const lines = (chunks: string[]) => chunks.join('').split('\n').filter((l) => l.trim().length > 0);
+const parsedAll = (out: string[]) => out.map((l) => JSON.parse(l) as Record<string, unknown>);
+
+describe('#4888: sync --json keeps stdout pure JSON', () => {
+ test('first-sync dry run: every stdout line parses; the preview prose lands on stderr', async () => {
+ const { stdout, stderr } = await run(['--dry-run', '--no-pull', '--no-embed', '--json']);
+ const out = lines(stdout);
+ for (const l of out) expect(() => JSON.parse(l)).not.toThrow();
+ const env = parsedAll(out).find((o) => o.schema_version === 1);
+ expect(env?.sync_status).toBe('dry_run');
+ expect(env?.added).toBe(1);
+ expect(stderr.join('')).toContain('Full-sync dry run');
+ }, 60_000);
+
+ test('first sync (real import): runImport human summary lands on stderr, every stdout line parses', async () => {
+ // performFullSync delegates to runImport, whose "Found N markdown files" /
+ // "Import complete" lines are its own sinks — the --json wrap must cover
+ // them too, or the very first `sync --json | jq` an agent scripts breaks.
+ const { stdout, stderr } = await run(['--no-pull', '--no-embed', '--json']);
+ const out = lines(stdout);
+ for (const l of out) expect(() => JSON.parse(l)).not.toThrow();
+ const env = parsedAll(out).find((o) => o.schema_version === 1);
+ expect(env?.sync_status).toBe('first_sync');
+ const err = stderr.join('');
+ expect(err).toContain('Found 1 markdown files');
+ expect(err).toContain('Import complete');
+ }, 60_000);
+
+ test('incremental dry run: the "Sync dry run" / "Modified:" prose lands on stderr, not stdout', async () => {
+ // A real run sets last_commit; then one committed change to preview.
+ await run(['--no-pull', '--no-embed']);
+ writeFileSync(join(repoPath, 'topics/foo.md'), FOO('changed.'));
+ execSync('git add -A && git commit -q -m change', { cwd: repoPath, stdio: 'pipe' });
+
+ const { stdout, stderr } = await run(['--dry-run', '--no-pull', '--no-embed', '--json']);
+ const out = lines(stdout);
+ for (const l of out) expect(() => JSON.parse(l)).not.toThrow();
+ const env = parsedAll(out).find((o) => o.schema_version === 1);
+ expect(env?.sync_status).toBe('dry_run');
+ expect(env?.modified).toBe(1);
+ const err = stderr.join('');
+ expect(err).toContain('Sync dry run:');
+ expect(err).toContain('Modified: topics/foo.md');
+ }, 60_000);
+
+ test('without --json the preview prose still reaches stdout (interactive output unchanged)', async () => {
+ const { stdout } = await run(['--dry-run', '--no-pull', '--no-embed']);
+ expect(stdout.join('')).toContain('Sync dry run:');
+ }, 60_000);
+
+ // Wave review: the remaining human lines on the --json path.
+ test('--retry-failed --json with no pending failures: the "nothing to retry" line is stderr, stdout parses', async () => {
+ rmSync(join(home, 'sync-failures.jsonl'), { force: true });
+ const { stdout, stderr } = await run(['--retry-failed', '--dry-run', '--no-pull', '--no-embed', '--json']);
+ for (const l of lines(stdout)) expect(() => JSON.parse(l)).not.toThrow();
+ expect(stderr.join('')).toContain('No unacknowledged sync failures to retry.');
+ }, 60_000);
+
+ test('--retry-failed --json with a pending failure: the "Retrying N" line is stderr, stdout parses', async () => {
+ seedFailure();
+ const { stdout, stderr } = await run(['--retry-failed', '--dry-run', '--no-pull', '--no-embed', '--json']);
+ for (const l of lines(stdout)) expect(() => JSON.parse(l)).not.toThrow();
+ expect(stderr.join('')).toContain('Retrying 1 previously-failed file(s)');
+ }, 60_000);
+
+ test('--skip-failed --json: the "Acknowledged N" line is stderr, stdout parses', async () => {
+ seedFailure();
+ const { stdout, stderr } = await run(['--skip-failed', '--dry-run', '--no-pull', '--no-embed', '--json']);
+ for (const l of lines(stdout)) expect(() => JSON.parse(l)).not.toThrow();
+ expect(stderr.join('')).toContain('Acknowledged 1 pre-existing failure(s).');
+ }, 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);
+ expect(out).toHaveLength(1);
+ expect(typeof JSON.parse(out[0]).job_id).toBe('number');
+ }, 60_000);
+});
+
+/** One open ledger row for the default source (the shape sync-failure-ledger writes). */
+function seedFailure(): void {
+ const now = new Date().toISOString();
+ writeFileSync(
+ join(home, 'sync-failures.jsonl'),
+ JSON.stringify({
+ source_id: 'default', path: 'topics/broken.md', error: 'boom', code: 'UNKNOWN', commit: 'abc',
+ first_seen: now, ts: now, attempts: 1, state: 'open', acknowledged: false, acknowledged_at: null,
+ }) + '\n',
+ );
+}
diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.ts
index c975185d00..8077666bb6 100644
--- a/test/sync-rename-reconcile.serial.test.ts
+++ b/test/sync-rename-reconcile.serial.test.ts
@@ -2695,3 +2695,47 @@ describe('#3942: the rename lane must not repoint a foreign-origin page', () =>
.toBe('legacy body');
});
});
+
+describe('#4597: a fallback rename\'s own stale duplicate converges under incremental sync', () => {
+ // Negative control lives above: "the anchor tree is enumerated on its own
+ // paths" (from=people/alpha.md, anchor proof at the emoji path) pins that
+ // anchor proof from a DIFFERENT path than the reconciled rename's from
+ // still spares the row. This case is the self-referential sub-case only.
+ test('the anchor blob at the rename\'s own from-path is not liveness proof: the pre-rename row is removed and the next run is quiet', async () => {
+ const { performSync } = await import('../src/commands/sync.ts');
+ const repo = mkRepo({
+ '\u{1F389}.md': exoticMd,
+ 'people/alpha.md': personMd('Alpha', 'Alpha is a person.'),
+ });
+ await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+ expect(await engine.getPage('party-notes')).not.toBeNull();
+
+ // Occupied destination forces the fallback lane (updateSlug throws).
+ await engine.putPage('notes/party', {
+ type: 'person', title: 'Occupant', compiled_truth: 'occupies the destination slug',
+ }, { sourceId: 'default' });
+
+ // The exotic file moves to an ORDINARY path and drops its slug: line
+ // (identical body, so `diff -M` reports a rename, not delete + add).
+ // The destination derives its slug from the path now; the only state
+ // still naming `party-notes` is the anchor blob at the rename's own
+ // from-path — the pre-rename content of the file just re-imported.
+ mkdirSync(join(repo, 'notes'), { recursive: true });
+ execSync('git mv "\u{1F389}.md" notes/party.md', { cwd: repo, stdio: 'pipe' });
+ writeFileSync(join(repo, 'notes/party.md'), exoticMd.replace('slug: Party-Notes\n', ''));
+ execSync('git add -A && git commit -m "move party notes to an ordinary path"', { cwd: repo, stdio: 'pipe' });
+
+ const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+ expect(result.status).toBe('synced');
+ const dest = await engine.getPage('notes/party');
+ expect(dest).not.toBeNull();
+ expect(dest!.compiled_truth).toContain('Party notes live here.');
+ // The stale half of the rename is gone (soft-deleted, 72h recoverable)...
+ expect(await engine.getPage('party-notes')).toBeNull();
+
+ // ...and the incremental path is converged: no sentinel, no wedge.
+ const quiet = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });
+ expect(quiet.status).toBe('up_to_date');
+ expect(await engine.getPage('party-notes')).toBeNull();
+ });
+});
diff --git a/test/think-cli-source-flag.serial.test.ts b/test/think-cli-source-flag.serial.test.ts
index b475872645..e616de293e 100644
--- a/test/think-cli-source-flag.serial.test.ts
+++ b/test/think-cli-source-flag.serial.test.ts
@@ -42,6 +42,30 @@ mock.module('../src/core/config.ts', () => ({
isThinClient: () => false,
}));
+// #4652: pin the ambient tier. The stub engine has no getConfig, so the real
+// tier-5 lookup would throw and a swallow-into-legacy-unscoped path would
+// look identical to the bug. Explicit ids still hit the real resolver so the
+// unknown-source exit-1 contract below stays real.
+const realResolver = await import('../src/core/source-resolver.ts');
+// Bind the real function BEFORE mocking: the namespace binding is re-pointed
+// at the mock, so calling through `realResolver.` later would recurse.
+const realResolveSourceWithTier = realResolver.resolveSourceWithTier;
+/** What the AMBIENT (no --source) resolution does; tests flip it per case. */
+const ambient: { mode: 'default' | 'target_error' | 'structural' } = { mode: 'default' };
+mock.module('../src/core/source-resolver.ts', () => ({
+ ...realResolver,
+ resolveSourceWithTier: async (engine: unknown, explicit: string | null | undefined) => {
+ if (explicit) return realResolveSourceWithTier(engine as never, explicit);
+ if (ambient.mode === 'target_error') {
+ throw new realResolver.SourceTargetError('Source "ghost-src" not found or is archived.');
+ }
+ if (ambient.mode === 'structural') throw new Error('relation "sources" does not exist');
+ return { source_id: 'default', tier: 'seed_default' as const };
+ },
+ localFederatedSourceIds: async (_engine: unknown, _id: string, tier: string) =>
+ tier === 'seed_default' ? ['default', 'team-wiki'] : undefined,
+}));
+
const { runThinkCli } = await import('../src/commands/think.ts');
/** Stub engine: assertSourceExists's query resolves only 'workspace'. */
@@ -109,14 +133,60 @@ describe('#4508 think --source CLI surface', () => {
expect(captured.opts[0].calibrationHolder).toBe('holder-example');
});
- test('omitting --source keeps the default scope (no sourceId key)', async () => {
+ // #4652: without --source, think used to hand runThink no scope at all, so
+ // the gather spanned every source (including `--no-federated` ones) while
+ // `gbrain search` on the same brain honored the resolved default + its
+ // federated set. The CLI now resolves the same scope search does.
+ test('omitting --source resolves the default source and its federated set (#4652)', async () => {
const r = await runCli(['plain', 'question']);
expect(r.code).toBe(0);
+ expect(captured.opts[0].sourceId).toBe('default');
+ expect(captured.opts[0].allowedSources).toEqual(['default', 'team-wiki']);
+ });
+
+ test('explicit --source stays scalar (no federated widening)', async () => {
+ const r = await runCli(['plain', 'question', '--source', 'workspace']);
+ expect(r.code).toBe(0);
+ expect(captured.opts[0].sourceId).toBe('workspace');
+ expect(captured.opts[0].allowedSources).toBeUndefined();
+ });
+
+ test('--source __all__ spans the brain instead of scoping to the literal sentinel', async () => {
+ const r = await runCli(['plain', 'question', '--source', '__all__']);
+ expect(r.code).toBe(0);
expect(captured.opts[0].sourceId).toBeUndefined();
+ expect(captured.opts[0].allowedSources).toBeUndefined();
});
test('think --help documents --source', async () => {
const r = await runCli(['--help']);
expect(r.out.join('\n')).toContain('--source');
});
+
+ // Wave review: the catch used to swallow EVERY ambient resolver error into
+ // an unscoped gather — only the structural pre-init failure may do that.
+ test('an ambient SourceTargetError (stale GBRAIN_SOURCE / dotfile) is exit 1, never an unscoped gather', async () => {
+ ambient.mode = 'target_error';
+ try {
+ const r = await runCli(['plain', 'question']);
+ expect(r.code).toBe(1);
+ expect(r.err.join('\n')).toContain('ghost-src');
+ expect(captured.opts).toHaveLength(0);
+ } finally {
+ ambient.mode = 'default';
+ }
+ });
+
+ test('a structural pre-init failure (no sources table) keeps the legacy unscoped gather', async () => {
+ ambient.mode = 'structural';
+ try {
+ const r = await runCli(['plain', 'question']);
+ expect(r.code).toBe(0);
+ expect(captured.opts).toHaveLength(1);
+ expect(captured.opts[0].sourceId).toBeUndefined();
+ expect(captured.opts[0].allowedSources).toBeUndefined();
+ } finally {
+ ambient.mode = 'default';
+ }
+ });
});
diff --git a/test/transcript-render.test.ts b/test/transcript-render.test.ts
index 9e41bf05b5..c6c90c170b 100644
--- a/test/transcript-render.test.ts
+++ b/test/transcript-render.test.ts
@@ -17,6 +17,8 @@ import {
renderSessionParts,
} from '../src/core/transcripts/render.ts';
import { parseConversation } from '../src/core/conversation-parser/parse.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, stripFactsFence } from '../src/core/facts-fence.ts';
+import { TAKES_FENCE_BEGIN, parseTakesFence } from '../src/core/takes-fence.ts';
import type { ParsedSession } from '../src/core/transcripts/types.ts';
function session(messages: ParsedSession['messages'], meta: Partial<ParsedSession['meta']> = {}): ParsedSession {
@@ -139,6 +141,49 @@ describe('anchor-escape [P0: hostile BODIES cannot forge messages]', () => {
expect(parsed.messages[0].text).toBe('hello there');
});
+ // #4821: a session that quoted another page's facts/takes fence (context
+ // pack, get_page) must not carry a LIVE fence marker into the transcript
+ // page — the 4000-char message cap routinely keeps the begin marker and
+ // drops the end, manufacturing FACTS_FENCE_UNBALANCED on every dream cycle.
+ test('a quoted facts:begin marker (end truncated away) does not become a live, unbalanced fence', () => {
+ const quoted = session([
+ { role: 'user', timestamp: '2026-08-02T09:00:03.000Z', text: `Page body:\n${FACTS_FENCE_BEGIN}\n| # | claim | kind |` },
+ { role: 'assistant', timestamp: '2026-08-02T09:00:04.000Z', text: 'Noted.' },
+ ]);
+ const body = splitBody(renderSessionParts(redactSession(quoted, { userPatternsPath: '/nonexistent' })).parts[0].content);
+ expect(parseFactsFence(body).warnings).toEqual([]);
+ expect(body.includes(FACTS_FENCE_BEGIN)).toBe(false);
+ // Still readable/greppable: the marker text survives, only the token is neutralized.
+ expect(body).toContain('facts:begin');
+ expect(parseConversation(body).messages).toHaveLength(2);
+ });
+
+ test('a fully quoted facts fence is not indexed as the TRANSCRIPT page\'s facts, nor stripped from its chunk text', () => {
+ const fence = [
+ FACTS_FENCE_BEGIN,
+ '',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|',
+ '| 1 | acme-example raised a seed round | event | 0.9 | public | notable | | | | |',
+ '',
+ FACTS_FENCE_END,
+ ].join('\n');
+ const quoted = session([
+ { role: 'user', timestamp: '2026-08-02T09:00:03.000Z', text: `Here is the page:\n${fence}\nthoughts?` },
+ ]);
+ const body = splitBody(renderSessionParts(redactSession(quoted, { userPatternsPath: '/nonexistent' })).parts[0].content);
+ expect(parseFactsFence(body).facts).toHaveLength(0);
+ expect(stripFactsFence(body)).toBe(body);
+ });
+
+ test('a quoted takes:begin marker does not raise a takes-fence warning', () => {
+ const quoted = session([
+ { role: 'user', timestamp: '2026-08-02T09:00:03.000Z', text: `Quoting:\n${TAKES_FENCE_BEGIN}\n| # | take |` },
+ ]);
+ const body = splitBody(renderSessionParts(redactSession(quoted, { userPatternsPath: '/nonexistent' })).parts[0].content);
+ expect(parseTakesFence(body).warnings.filter((w) => w.startsWith('TAKES_FENCE_'))).toEqual([]);
+ });
+
test('YAML-hostile titles serialize safely; issue refs are NOT over-redacted', () => {
const nasty = session(BASIC.messages, { title: 'quote" colon: [brackets] re #4106', harness: 'chatgpt' });
const r = renderSessionParts(redactSession(nasty, { userPatternsPath: '/nonexistent' }));
diff --git a/test/transcripts-self-exclusion.test.ts b/test/transcripts-self-exclusion.test.ts
index 36cddf53ce..fcc2346951 100644
--- a/test/transcripts-self-exclusion.test.ts
+++ b/test/transcripts-self-exclusion.test.ts
@@ -22,8 +22,10 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, readdirSync
import { spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join, basename } from 'node:path';
-import { discoverTranscriptFiles } from '../src/core/transcripts/discover.ts';
+import { buildStatusRows, discoverTranscriptFiles } from '../src/core/transcripts/discover.ts';
import type { HarnessRoot } from '../src/core/transcripts/detect.ts';
+import { isClaudeCodeSubagentFile } from '../src/core/transcripts/claude-code.ts';
+import { expandPaths } from '../src/commands/transcripts.ts';
import {
CLAUDE_CLI_CWD_PREFIX,
claudeCliCwdDir,
@@ -46,6 +48,19 @@ beforeAll(() => {
const selfProject = join(projectsRoot, `-private-tmp-${CLAUDE_CLI_CWD_PREFIX}12345`);
mkdirSync(selfProject, { recursive: true });
writeFileSync(join(selfProject, 'session-self.jsonl'), '{"type":"user"}\n', 'utf-8');
+ // #4796: a Claude Code SUBAGENT log — <project>/<session-uuid>/subagents/agent-<id>.jsonl.
+ // Every line is isSidechain and carries the PARENT session id; it is not a session.
+ const sess = join(userProject, '61c79e08-716f-44df-b962-05d702a4a739');
+ mkdirSync(join(sess, 'subagents'), { recursive: true });
+ writeFileSync(
+ join(sess, 'subagents', 'agent-a5364e53aee2dd757.jsonl'),
+ '{"type":"user","isSidechain":true,"sessionId":"61c79e08-716f-44df-b962-05d702a4a739","message":{"role":"user","content":"x"}}\n',
+ 'utf-8',
+ );
+ // Strictness pin: a user project whose slug merely ENDS in "subagents" is a real project.
+ const subagentsProject = join(projectsRoot, '-Users-alice-subagents');
+ mkdirSync(subagentsProject, { recursive: true });
+ writeFileSync(join(subagentsProject, 'session-subproj.jsonl'), '{"type":"user"}\n', 'utf-8');
roots = [{ format: 'claude-code', root: projectsRoot, extension: '.jsonl' }];
});
@@ -79,6 +94,42 @@ describe('transcript discovery — claude-cli self-session exclusion (#4472)', (
});
});
+describe('transcript discovery — claude-code subagent log exclusion (#4796)', () => {
+ test('subagent logs are not sessions: discovery skips them, real projects still surface', () => {
+ const names = discoverTranscriptFiles(roots).map((f) => basename(f.path));
+ expect(names).not.toContain('agent-a5364e53aee2dd757.jsonl');
+ expect(names).toContain('session-user.jsonl');
+ expect(names).toContain('session-subproj.jsonl');
+ });
+
+ test('predicate is strict: parent dir literally `subagents` AND basename agent-*.jsonl', () => {
+ const proj = '/Users/alice/.claude/projects/-Users-alice-code-myapp';
+ const sess = `${proj}/61c79e08-716f-44df-b962-05d702a4a739`;
+ expect(isClaudeCodeSubagentFile(`${sess}/subagents/agent-a5364e53aee2dd757.jsonl`)).toBe(true);
+ expect(isClaudeCodeSubagentFile(`${proj}/s.jsonl`)).toBe(false);
+ expect(isClaudeCodeSubagentFile(`${proj}/subagents.jsonl`)).toBe(false);
+ expect(isClaudeCodeSubagentFile(`${proj}/agent-abc.jsonl`)).toBe(false);
+ expect(isClaudeCodeSubagentFile('/Users/alice/.claude/projects/-Users-alice-subagents/agent-abc.jsonl')).toBe(false);
+ expect(isClaudeCodeSubagentFile(`${sess}/subagents/61c79e08-716f-44df-b962-05d702a4a739.jsonl`)).toBe(false);
+ });
+
+ test('explicit-path lane (expandPaths over the projects root) drops them too', async () => {
+ const paths = await expandPaths([projectsRoot]);
+ expect(paths.some((p) => p.endsWith('agent-a5364e53aee2dd757.jsonl'))).toBe(false);
+ expect(paths.some((p) => p.endsWith('session-user.jsonl'))).toBe(true);
+ });
+
+ test('status gap table carries no phantom not-yet-imported backlog', () => {
+ const imported = {
+ byHarness: new Map([['claude-code', new Set(['session-user', 'session-subproj'])]]),
+ pagesScanned: 2,
+ };
+ const row = buildStatusRows(discoverTranscriptFiles(roots), imported, roots).find((r) => r.format === 'claude-code')!;
+ expect(row.found).toBe(2);
+ expect(row.gapFiles).toBe(0);
+ });
+});
+
describe('claude-cli scratch sweep (#4472)', () => {
test('removes dead-PID dirs; keeps live-PID, own-PID, and non-matching dirs', () => {
const base = mkdtempSync(join(tmpdir(), 'gb-self-excl-sweep-'));
diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.ts
index eaf49b6677..e4a317eb1b 100644
--- a/test/upgrade.serial.test.ts
+++ b/test/upgrade.serial.test.ts
@@ -1,10 +1,11 @@
import { describe, test, expect } from 'bun:test';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
import { dirname, join } from 'path';
import { tmpdir } from 'os';
import * as upgradeModule from '../src/commands/upgrade.ts';
import { resolveBunGlobalRoot } from '../src/commands/upgrade.ts';
import { formatMarker } from '../src/core/self-upgrade.ts';
+import type { BinarySelfUpdateResult } from '../src/core/binary-self-update.ts';
import { VERSION } from '../src/version.ts';
// We can't easily mock process.execPath in bun, so we test the upgrade
@@ -256,11 +257,15 @@ describe('runUpgrade target verification (#4366)', () => {
* the same successful-no-op shape as `bun update` on an exact-tag Git
* pin (the issue's install);
* - a PATH-first `gbrain` shim that keeps reporting `observedVersion`;
- * - a pre-seeded upgrade-available marker so cache retention is observable.
+ * - a pre-seeded upgrade-available marker so cache retention is observable;
+ * - with `binaryResult`, the driver runs under a copy of bun named `gbrain`
+ * (detectInstallMethod keys on execPath's basename) and the driver mocks
+ * runBinarySelfUpdate to return that result, reaching the binary branch.
*/
async function runUpgradeAgainstFakeInstall(opts: {
observedVersion: string;
targetVersion?: string;
+ binaryResult?: BinarySelfUpdateResult;
}): Promise<{ home: string; exitCode: number; stderr: string }> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-upgrade-target-'));
const bin = join(home, 'bin');
@@ -279,12 +284,26 @@ describe('runUpgrade target verification (#4366)', () => {
// The driver lives OUTSIDE the repo so detectInstallMethod() cannot see a
// node_modules/.git ancestor and falls through to the clawhub shim.
const driverPath = join(home, 'driver.ts');
+ const mockPrelude = opts.binaryResult
+ ? `import { mock } from 'bun:test';\n` +
+ `mock.module('${repoRoot}src/core/binary-self-update.ts', () => ({\n` +
+ ` runBinarySelfUpdate: async () => (${JSON.stringify(opts.binaryResult)}),\n` +
+ `}));\n`
+ : '';
writeFileSync(
driverPath,
- `import { runUpgrade } from '${repoRoot}src/commands/upgrade.ts';\n` +
+ mockPrelude +
+ `import { runUpgrade } from '${repoRoot}src/commands/upgrade.ts';\n` +
`const t = process.env.TEST_TARGET_VERSION;\n` +
`await runUpgrade(['--swap-only'], t ? { targetVersion: t } : {});\n`,
);
+ let bunExec = 'bun';
+ if (opts.binaryResult) {
+ bunExec = join(home, 'exec', 'gbrain');
+ mkdirSync(dirname(bunExec));
+ copyFileSync(process.execPath, bunExec);
+ chmodSync(bunExec, 0o755);
+ }
const env: Record<string, string | undefined> = {
...process.env,
@@ -295,7 +314,7 @@ describe('runUpgrade target verification (#4366)', () => {
delete env.TEST_TARGET_VERSION;
if (opts.targetVersion) env.TEST_TARGET_VERSION = opts.targetVersion;
- const proc = Bun.spawn(['bun', 'run', driverPath], {
+ const proc = Bun.spawn([bunExec, 'run', driverPath], {
cwd: repoRoot,
env,
stdout: 'pipe',
@@ -356,4 +375,30 @@ describe('runUpgrade target verification (#4366)', () => {
rmSync(home, { recursive: true, force: true });
}
});
+
+ // A failed binary swap must still name the release it attempted. With no
+ // caller target (plain `gbrain upgrade`), to_version comes from the release
+ // tag runBinarySelfUpdate resolved — never '' — so doctor can say which
+ // version failed to install.
+ for (const [reason, error] of [
+ ['smoke_failed', undefined],
+ ['version_mismatch', undefined],
+ ['replace_failed', 'EACCES: permission denied'],
+ ] as const) {
+ test(`binary self-update ${reason} records to_version = attempted release`, async () => {
+ const { home } = await runUpgradeAgainstFakeInstall({
+ observedVersion: OLD,
+ binaryResult: { ok: false, reason, targetVersion: TARGET, error },
+ });
+ try {
+ const errPath = join(home, '.gbrain', 'upgrade-errors.jsonl');
+ const records = readFileSync(errPath, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));
+ const rec = records.find((r) => r.phase === 'binary-self-update');
+ expect(rec?.to_version).toBe(TARGET);
+ expect(rec?.error).toBe(error ? `${reason}: ${error}` : reason);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+ }
});
diff --git a/test/worker-pool.test.ts b/test/worker-pool.test.ts
index 96200b09ae..b3c1178b2e 100644
--- a/test/worker-pool.test.ts
+++ b/test/worker-pool.test.ts
@@ -369,6 +369,28 @@ describe('runSlidingPool — BudgetExhausted bypass (D13)', () => {
expect(aborted).toBe(0);
});
+ test('a must-abort error is rethrown only after in-flight siblings finish', async () => {
+ let done = 0;
+ class FakeBudget extends Error {
+ readonly tag = 'BUDGET_EXHAUSTED' as const;
+ }
+ await expect(
+ runSlidingPool({
+ items: [200, 1, 2, 3],
+ workers: 2,
+ onItem: async (ms: number) => {
+ if (ms === 1) throw new FakeBudget('cap');
+ await new Promise((r) => setTimeout(r, ms));
+ done++;
+ },
+ }),
+ ).rejects.toMatchObject({ tag: 'BUDGET_EXHAUSTED' });
+ // The 200 ms item was mid-flight when the cap hit and ran to completion
+ // BEFORE the pool rejected (no worker left running detached past the
+ // caller's catch); nothing after the cap was claimed.
+ expect(done).toBe(1);
+ });
+
test('isMustAbortError + MUST_ABORT_ERROR_TAGS exposed and stable', () => {
expect(MUST_ABORT_ERROR_TAGS.has('BUDGET_EXHAUSTED')).toBe(true);
expect(isMustAbortError({ tag: 'BUDGET_EXHAUSTED' })).toBe(true);
diff --git a/test/worker-registry.serial.test.ts b/test/worker-registry.serial.test.ts
index b127a9cde3..061fbba382 100644
--- a/test/worker-registry.serial.test.ts
+++ b/test/worker-registry.serial.test.ts
@@ -13,6 +13,7 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync, existsSync, readdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
+import { withEnv } from './helpers/with-env.ts';
let home: string;
const origHome = process.env.GBRAIN_HOME;
@@ -43,6 +44,26 @@ describe('classifyLiveness (Codex #9)', () => {
});
});
+describe('parseEtimeToMs (PID-reuse guard, timezone-free)', () => {
+ test('parses every portable ps etime shape', async () => {
+ const { parseEtimeToMs } = await reg();
+ expect(parseEtimeToMs('00:00')).toBe(0);
+ expect(parseEtimeToMs('00:42')).toBe(42_000);
+ expect(parseEtimeToMs('01:23')).toBe(83_000);
+ expect(parseEtimeToMs('12:34:56')).toBe(((12 * 3600) + (34 * 60) + 56) * 1000);
+ expect(parseEtimeToMs('3-04:05:06')).toBe(((3 * 86400) + (4 * 3600) + (5 * 60) + 6) * 1000);
+ expect(parseEtimeToMs(' 01:00 ')).toBe(60_000);
+ });
+
+ test('returns null when elapsed time cannot be determined', async () => {
+ const { parseEtimeToMs } = await reg();
+ expect(parseEtimeToMs('')).toBeNull();
+ expect(parseEtimeToMs('garbage')).toBeNull();
+ expect(parseEtimeToMs('not:a:number:at:all')).toBeNull();
+ expect(parseEtimeToMs('Mon Sep 7 00:30:32 2026')).toBeNull(); // the old lstart shape
+ });
+});
+
describe('register + read round trip', () => {
test('registerWorker writes under gbrainPath; readWorkers returns the live worker', async () => {
const { registerWorker, readWorkers, workerRegistryDir } = await reg();
@@ -67,6 +88,23 @@ describe('register + read round trip', () => {
expect(readWorkers(() => 10).length).toBe(0);
});
+ test('#4885: a live worker survives a runtime zone that differs from the one ps prints in', async () => {
+ const { registerWorker, readWorkers } = await reg();
+ // Bun re-resolves the runtime zone on reassignment but does not hand the
+ // mutation to the ps child, so a zone-dependent start-time parse drifts by
+ // the offset (+12h here) and drops a live worker. etime is zone-free.
+ await withEnv({ TZ: 'Etc/GMT+12' }, async () => {
+ const cleanup = registerWorker({
+ pid: process.pid, queue: 'default', nice_requested: 10, nice_effective: 10, started_at: Date.now(),
+ });
+ try {
+ expect(readWorkers(() => 10).length).toBe(1);
+ } finally {
+ cleanup();
+ }
+ });
+ });
+
test('cleanup unlinks the entry file', async () => {
const { registerWorker, workerRegistryDir } = await reg();
const cleanup = registerWorker({