Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.29.0 fix: the community wave — 38 contributor PRs + 49 verified fixes + the fence-merge data-loss closure (#4567)
Sina Matian492b5528238d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex c7c1059549..8dfa600566 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.28.0",+ "version": "0.46.29.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/mcp.json b/.codex-plugin/mcp.jsonindex 13a38a285d..c827db3637 100644--- a/.codex-plugin/mcp.json+++ b/.codex-plugin/mcp.json@@ -56,6 +56,7 @@"MINIMAX_API_KEY","MISTRAL_API_KEY","MOONSHOT_API_KEY",+ "NAN_API_KEY","NVIDIA_API_KEY","OLLAMA_API_KEY","OLLAMA_BASE_URL",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex f840564f37..1253a2f078 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.46.28.0",+ "version": "0.46.29.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.mdindex 98644ee080..d84f4d77c5 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.28.0 -->+<!-- gbrain-runbook-stamp: 0.46.29.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f4ad38eac6..11e460188f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,70 @@All notable changes to GBrain will be documented in this file.+## [0.46.29.0] - 2026-08-24++The community wave: 38 contributor PRs landed (37 authors credited below) plus+49 more verified issue fixes — everything filed or rebased since the megawave,+re-trialed against it, and integrated with the same reproduce-first discipline.++### Privacy & data integrity+- **Remote write-backs can no longer drop invisible fence rows.** A remote+ caller that reads a page (seeing only world-visible facts), edits prose, and+ writes back now gets a row-level visibility-aware merge: rows it couldn't+ see are restored at their stable row numbers; its own edits and deletions of+ visible rows are honored exactly. Covers timeline-embedded fences too, and+ forgotten/struck claims round-trip without resurrection (#4548 #4554 #4546,+ extending community warn-work from #4553/#4555/#4547 — thank you).+- Ambient-recall deltas honor page visibility for remote callers (#4549 via+ community PR #4550); timeline fences are stripped from remote page reads+ (#4546 via #4547).+- Per-call salience/recency modes and intent-pattern config now fold into the+ query-cache key (knobs v=26; also folds the keyword-fallback knob and closes+ a negative-offset cache gap from community PRs #3617/#4414) — one-time+ cache re-warm on upgrade.+- WSL transcript-path translation confines strictly to the known Claude config+ tree (#4522), and hook transcripts translate Windows drive paths at all.++### Community wave (38 PRs, landed with credit)+Highlights: doctor schema-column drift detection (#4425) and wedged-queue+worker-liveness split (#4400); sync working-tree drift visibility with+`--working-tree` (#3974); parallel source-resolution for large repos (#4411);+PGLite embed-backfill admission gate with typed drain outcomes (#4512);+openrouter Anthropic-route subagent loops (#4514, also fixing the replay+matrix); UTF-16-safe truncation in extract paths (#4529); CJK cross-modal+recall (#4538); bench metric correctness (#4453); a new opt-in third-party+reranker recipe (nan.builders, #4491 — off unless you configure a key); plus+25 more fixes across doctor, search, sync, schema, gateway, and CLI surfaces.++### Verified issue fixes (49)+- Cycle: extractor input/output/pacing config caps (#4540), drain errors+ surfaced (#4539), atoms truncation UTF-16-safe (#4528 with #4529).+- Sync/import: YAML-error files named with a validate hint (#4543), leading+ blank line before frontmatter tolerated (#4526), break-lock resolves the+ ambient source chain (#4412 — the under-serve e2e defect), image imports+ incremental (#4521).+- Doctor: orphans definition unified with health's islanded semantics+ (#4524, `mode:'inbound'` for the legacy view), upgrade-error warns+ auto-resolve when provably superseded but fail closed otherwise (#4517),+ schema ledger can't mask missing columns (#4421 with #4425).+- MCP/ops: OAuth refresh maps to invalid_grant instead of 500 (#4532),+ remote put_page documents unreconciled wikilinks (#4525), migrate-engine+ preserves timestamps and reports real removal counts (#4527).+- CLI: `--explain` reaches extract/whoknows/onboard instead of being+ swallowed globally (#4541), zero-meeting extractions warn instead of+ silently succeeding (#4542).+- Plus 30 more across think, dream, takes, transcripts, jobs, search,+ schema-packs, embedding limits (#4530), and test infrastructure.++### To take advantage of v0.46.29.0+```bash+gbrain upgrade+gbrain migrate # v141 (extract-rollup expected-limit config)+gbrain doctor # new drift + liveness checks run automatically+```+First queries re-warm the semantic cache (knobs v=26). Code chunks re-chunk+once on upgrade (CHUNKER_VERSION 6) for decorated-def support.+## [0.46.28.0] - 2026-08-21The megawave: 111 verified issues fixed in one release — every remaining@@ -3105,6 +3169,69 @@ Every scoreboard row carries a `seam` label: the `openclaw` row exercises the sh- CLI exit codes for the new command route through the shared write-fence + aliveness-grace exit seam, so PGLite's WASM exit-code stomping and Bun's exit-time stdout discard can't corrupt the CI contract.To take advantage of v0.44.0.0: run `gbrain eval brainbench` — no setup, no keys, no brain required. If it ever reports something broken after an upgrade, `bun evals/brainbench/generator/gen.ts` rebuilds the corpus byte-identically and `gbrain eval brainbench --update-baseline` re-derives the baseline from an actual run; both are safe to re-run any time.++## [0.43.1.0] - 2026-08-10++**Sync no longer stays silent about files you haven't committed.**++Incremental sync is commit-driven: files written into a brain repo but never+committed were invisible — sync printed "Already up to date." while the pages+sat outside the brain (observed in the wild: 100+ notes missing for weeks, and+a nightly cycle reporting a clean "+0 added" over them every night). Sync now+counts that uncommitted drift through the exact filters imports use, reports+it in results and on stderr, and the nightly dream cycle flags it as a warning+instead of clean convergence. Uncommitted renames count too (as an add plus a+delete), so a rename-only dirty tree can't slip back into silence.++### Added+- **`gbrain sync --working-tree`** — opt-in import of uncommitted working-tree+ state (untracked files plus uncommitted edits and deletes) through the same+ merge path detached-HEAD syncs have always used. Persist it with+ `gbrain config set sync.include_working_tree true`; the config is honored by+ every caller — CLI, nightly dream cycle, and background sync jobs alike.+ The help text carries a caution: untracked means *everything* untracked, so+ review `git status` before enabling it as standing config.+- **Local models for atom extraction.** The dream cycle's `extract_atoms`+ phase can now run on a config-selected local model (e.g. Ollama) without+ hosted API keys, with two new tuning knobs:+ `cycle.extract_atoms.page_discovery_budget` and+ `cycle.extract_atoms.max_source_chars`.++### Changed+- Sync results carry an `uncommitted` drift summary (surfaced via `sync_brain`+ over MCP and in `gbrain dream --json` phase details), and `gbrain sync`+ prints a NOTE naming the counts and the remedy on both "up to date" and+ synced runs.+- The dream cycle's sync phase reports `warn` with the drift count when a+ brain repo has uncommitted syncable files.++### Fixed+- The silent untracked-file gap described above.+- Working-tree imports respect the mass-delete safety valve: an uncommitted+ tree that would delete more than half a source's pages (a mid-rebase+ checkout, an accidental `rm -rf`) is refused loudly instead of swept, with+ the same escape hatch as the reconcile valve.+- The working-tree probe fails open: if git can't produce the manifest within+ budget, drift counting skips with a note instead of erroring the sync+ (an explicit `--working-tree` request still fails closed with the reason).++### To take advantage of v0.43.1.0++```bash+gbrain upgrade+```++The sync fix needs no configuration. If sync starts warning about uncommitted+files, that is the fix working — commit them, or opt in with+`gbrain config set sync.include_working_tree true` after reviewing what's+untracked.++To run atom extraction on a local model, point the phase at it:+`gbrain config set models.dream.extract_atoms ollama:llama3.2:3b` (any local+tag works), then tune `cycle.extract_atoms.page_discovery_budget` (pages+considered per run, default 50) and `cycle.extract_atoms.max_source_chars`+(per-page prompt cap, default 50000) to taste.+## [0.43.0.0] - 2026-08-08**Your agent now has five memory verbs it can actually reach.** Cathedral 1 freezes@@ -25154,7 +25281,7 @@ GBrain v0.13.1 ships the Knowledge Runtime delta on top of v0.13.0's frontmatter- **`gbrain integrity --auto --confidence 0.8`** repairs the 1,424 bare-tweet citations in your brain without human review. Three-bucket confidence: auto-repair ≥0.8, review queue 0.5–0.8, skip <0.5. Resumable via `~/.gbrain/integrity-progress.jsonl`.- **`gbrain resolvers list`** introspects the typed plugin registry. Two builtins ship: `url_reachable` (HEAD check + SSRF guard) and `x_handle_to_tweet` (X API v2 with confidence scoring). Every result carries `{value, confidence, source, fetchedAt, costEstimate, raw}`.-- **`gbrain config set budget.daily_cap_usd 10`** puts a hard wall on resolver spend. Concurrent reserves serialize via `SELECT FOR UPDATE`. TTL auto-reclaim handles process death between reserve and commit.+- **`BudgetLedger` (`src/core/enrichment/budget.ts`) ships as scope + resolver-scoped daily spend ledger infrastructure.** Concurrent reserves serialize via `SELECT FOR UPDATE`; TTL auto-reclaim handles process death between reserve and commit. **Correction (see #3748): this was never wired to an enforced spend cap.** No resolver call path invokes `BudgetLedger.reserve()`, and `budget.` was never registered in `KNOWN_CONFIG_KEY_PREFIXES` — `gbrain config set budget.daily_cap_usd 10` is rejected without `--force`, and a forced write is never read by anything. Treat resolver spend as unmetered until a future release wires the ledger into the resolver call path and registers the config key.- **BrainWriter + pre-commit validators** make the Philip-Leung hallucination class structurally impossible. `Scaffolder` builds every tweet URL from API output, never LLM text. `SlugRegistry` detects name collisions at create time. Four validators (citation, link, back-link, triple-HR) run on write. `writer.lint_on_put_page=true` enables observability before the strict-mode flip.- **Quiet-hours on Minion jobs** stop the 3am DM. Set `quiet_hours: {start:22, end:7, tz:"America/Los_Angeles", policy:"defer"}` on a job. Worker checks at claim time (not dispatch). Wrap-around windows supported.diff --git a/TODOS.md b/TODOS.mdindex f4c7007f36..c4023ce5a3 100644--- a/TODOS.md+++ b/TODOS.md@@ -1698,6 +1698,41 @@ Deferred from the BrainBench wave (eng-reviewed; plan + GSTACK REVIEW REPORT atdev shells match keyless CI by definition; tests that want keys inject themexplicitly. Escape hatch `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` (set byscripts/run-e2e.sh).++## sync --working-tree follow-ups (filed v0.43.1.0)++Deferred findings from the v0.43.1.0 ship reviews (adversarial + specialists).+The shipped fix is safe without them; these harden the opt-in further.++- [ ] **P1 — doctor.test.ts subagent_capability test is not hermetic.** `checkSubagentCapability`'s ANTHROPIC_API_KEY drift check reads the real `~/.gbrain/config.json` via `loadConfig()`, so the "ok path" unit test fails on any dev machine with a non-Anthropic chat_model and no ANTHROPIC_API_KEY env (passes in CI). Pre-existing on master (files identical); stub the file-config read in the test or inject it into the check.+- [ ] **P2 — estimator blind spot.** The inline cost estimator prices attached+ working-tree files at $0 by design (#2139 phantom-cost class), so a+ persisted `sync.include_working_tree` + inline embed can spend past+ `sync.cost_gate_min_usd` on a large dirty tree. Price the working-tree+ manifest when the opt-in is resolved true.+- [ ] **P2 — checkpoint/resume vs the workingTree flag.** `op_checkpoint` is+ keyed (sourceId, lastCommit) and records neither the flag nor a working-tree+ fingerprint: a killed `--working-tree` run resumed as a plain sync completes+ commit-only and reports clean `synced` over a mixed snapshot; a working-tree+ path banked pre-kill then edited before resume keeps the stale content.+ Record the flag in the checkpoint key or invalidate on mismatch.+- [ ] **P3 — perpetually-dirty trees vs --ff-only pull.** include_working_tree+ users run dirty trees by definition; any remote change touching a dirty file+ wedges pull → partial/pull_failed until manually resolved. Consider+ auto-stash-pull-pop or a clearer remedy in the pull_failed message.+- [ ] **P3 — drift missing from dry_run/partial results.** `uncommitted` rides+ only up_to_date/synced; dry-run and partial JSON consumers see stderr only.+ The `sync --all --json` per-source envelope also omits it (explicit field+ projection in sync.ts) — add `uncommitted` there when fixing this.+- [ ] **P3 — collapse the two working-tree git subprocesses** into one+ `git status --porcelain=v2 -z` pass (halves per-sync probe overhead), and+ memoize the manifest per (gitContextRoot, headCommit) for `--all` sweeps+ over monorepo-scoped sources.+- [ ] **P4 — warn fatigue.** A perpetually-dirty vault now warns every night;+ consider a dampener (warn on count change, re-warn weekly) so+ blocked_by_failures/pull_failed stay visible.++## #2416 follow-ups (query-steering wave)- [x] **P2 — MCP-envelope `hint` field for concept-shaped `search` calls.**@@ -1860,6 +1895,40 @@ master before starting, several fixes landed independently).means the repair feature silently dies). Any future pglite upgrade wave must revisit BOTHtogether and re-derive the ControlFileData offset table for the new PG major.+## synthesize_concepts mints orphans the orphan check then penalizes (filed v0.42.74.0)++The `synthesize_concepts` dream phase writes concept pages that nothing links to,+and the `orphans` phase in the same cycle counts them against the brain score. One+cycle creates the pages, another docks you for them, and the count grows every night+the phase runs. Observed on a real brain: the phase reported N concepts synthesized+and the orphan report listed exactly N orphaned `concepts/` slugs — a 1:1 match, all+of them machine-generated in that run.++This reads to an operator as a curation failure ("I wrote concept pages and never+linked them") when nothing was hand-authored at all. It also makes the brain-score+orphan component drift downward as a direct function of how often the cycle runs,+which inverts the intent of the metric.++- [ ] **P1 — decide whether synthesized concepts belong in the orphan denominator.**+ Two candidate fixes, and they are not equivalent. (a) Wire concepts into the graph+ at synthesis time: when the phase extracts a concept from a set of pages, link those+ pages to the concept node. This is the better outcome — a concept page nothing can+ reach is close to useless for retrieval too, so the orphan signal is telling the+ truth and the synthesis step is what's incomplete. (b) Add `concepts/` to+ `DENY_PREFIXES` in `src/core/orphan-policy.ts`, the way `extracts/` and `atoms/`+ already are. Cheap, but it silences a real reachability problem rather than fixing+ it. Prefer (a); fall back to (b) only if concept nodes are deliberately+ retrieval-only and never meant to be graph-reachable.+- [ ] **P2 — near-duplicate concepts suggest the extractor needs a merge step.**+ The same run produced several near-synonym concept nodes (three variants of one+ adjectival stem, four of one noun stem). Whatever the orphan decision, an extractor+ emitting near-duplicates inflates the node count and splits inbound links across+ synonyms. Consider a similarity merge before write.+- [ ] **P3 — imported calendar days are a separate leaf class.** `meetings/calendar/+ <year>/<date>` pages are dated machine imports with no expected inbound links, the+ same class as the `daily` first-segment exclusion but not matched by it. Either+ broaden the convention defaults or document that calendar-import prefixes want a+ per-brain `orphans.exclude_prefixes` entry.## serve --http takes-holders + agent-voice hardening follow-ups (filed v0.42.74.0)Deferred from the #2529/#2477 security-fix wave (plan-eng-review + codex outside@@ -1889,7 +1958,38 @@ voice CLEARED). None block the wave.clause (`src/mcp/http-transport.ts` validateToken). Apply the same pattern —one fewer write per request on the `serve --http` hot path.Where: `src/core/oauth-provider.ts`.-+## nightly dream digest (filed v0.42.73.1)++Operators wire `gbrain dream --json` into a notifier (Telegram, Slack, email) through a+hand-rolled shell wrapper, then `jq` the counters out of it. That shape is fragile and+produces a low-signal report. Both problems are ours to fix, not the operator's.++- [ ] **P1 — `gbrain dream --digest` — a notification-ready summary gbrain owns.**+ Today every operator re-implements the same `jq` pipeline against `.totals` and+ `.phases[]`. Three failure modes follow. (a) The wrapper guesses at our schema, so a+ field rename degrades it silently. (b) Deltas are impossible — a wrapper has nowhere to+ persist last night's totals, so it can only print levels, and an orphan count carries no+ information without a trend. (c) Wrappers redirect with `2>&1`, which merges our stderr+ progress stream into the `--json` stdout payload and makes the report unparseable; the+ usual `|| echo '?'` fallback then renders a dead monitor as a healthy one. Emit a+ formatted digest directly so none of this is the caller's problem.+- [ ] **P1 — report by exception, with deltas.** A quiet night is `synced=0 extracted=0+ embedded=0` — three zeros in the headline while the `warn` phases and the+ needs-a-human items go unmentioned. Invert it: collapse healthy phases into a single+ status line, lead with `warn`/`error` phases, and render every counter as a delta+ against the prior run. Persist prior-run totals so the delta is real. A phase reporting+ `0 fixes applied` for N consecutive nights while its backlog grows is the signal worth+ paging on, and no level-only report can express it.+- [ ] **P2 — fold `advisor` into the digest's action section.** Every number in a nightly+ report should carry the command that acts on it. `src/core/advisor/` already computes a+ ranked action list from brain state across its collectors; the digest's+ "waiting on you" section should call it rather than grow a second ranking heuristic.+- [ ] **P2 — surface skipped-because-disabled phases.** A dream run can skip many phases+ purely on config flags. That is invisible in the totals, so a brain can quietly do far+ less work than its operator believes for months. Name the disabled phases in the digest.+- [ ] **P3 — document the stdout/stderr contract at the point of use.** `--json` callers+ must not merge streams. Say so in the `dream` help text and in the cron/scheduling+ guide, next to the example wrapper.## v0.42.67.0 follow-ups (Windows build tooling)Filed as follow-ups from v0.42.67.0 (`.gitattributes` LF pin for `*.sh` +@@ -4530,7 +4630,9 @@ contributor traps.## v0.37.6.0 OpenRouter recipe follow-ups (v0.37.x+ / v0.38.x)-- [ ] **v0.37.x: Verify `tool_use_id` stability through OpenRouter with a live test, then decide whether to relax the subagent-loop gate.** v0.37.6.0 shipped `supports_subagent_loop: false` on the OR recipe as informational only; the flag is now enforced — `classifyCapabilities()` in `src/core/ai/capabilities.ts` refuses the subagent tier on it (`unusable:no_subagent_loop`), and the legacy path additionally hard-rejects non-Anthropic providers via `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. OR proxies Anthropic-direct models that DO support stable `tool_use_id` by contract, but OR's response normalization may strip or re-encode them. A short live test: spin up a real OR account, run a subagent loop via `openrouter:anthropic/claude-haiku-4.5`, deliberately abort mid-loop, retry. Assert tool_use_id blocks are byte-identical across attempts (the test itself needs a temporary bypass of the classifier gate, since `classifyCapabilities()` now refuses the OR recipe outright). If they are, BOTH gates need relaxing — the OR recipe's `supports_subagent_loop: false` flag (enforced by `classifyCapabilities()`) and the legacy `isAnthropicProvider()` check — to allow Anthropic models proxied through OR, giving users OR's price/availability story for subagent work. This is a deeper structural change than a recipe-flag flip; needs its own /plan-eng-review pass. Filed during v0.37.6.0 codex review.+- [x] **OpenRouter Anthropic subagent loop.** Anthropic routes (`openrouter:anthropic/…`) now declare `supports_subagent_loop` via a per-id predicate. `isAnthropicProvider` stays false (Messages SDK cannot speak OR); the handler auto-routes those jobs through `gateway.toolLoop()` when `agent.use_gateway_loop` is off. Live abort/retry: `test/e2e/openrouter-anthropic-subagent-replay.live.test.ts` (skip-gated on `OPENROUTER_API_KEY`). Other OR families stay refused.++- [ ] **v0.37.x: Live-test non-Anthropic OpenRouter families (DeepSeek / OpenAI / Gemini) for the subagent loop.** Same abort/retry pin as Anthropic-via-OR before flipping the predicate wider.- [ ] **v0.37.x: Quarterly OR catalog refresh.** v0.37.6.0 ships 8 curated chat slugs (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) with `price_last_verified: '2026-05-20'`. OR's catalog churns weekly; specific slugs get deprecated, renamed, or merged. Refresh cadence: every 90 days, walk https://openrouter.ai/models, prune deprecated slugs, add new frontier IDs that match the recipe's curation logic (frontier-tier + cheap-routing entry points). Bump `price_last_verified`. The shape-test regression in `test/ai/recipe-openrouter.test.ts` (`MODEL_SHAPE` regex) means typos surface immediately; the catalog refresh is about discovery, not validation.diff --git a/VERSION b/VERSIONindex 4b854a3d3b..600f7521e8 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.28.0\ No newline at end of file+0.46.29.0\ No newline at end of filediff --git a/docker-compose.ci.yml b/docker-compose.ci.ymlindex 787899d3a5..c8604f26cb 100644--- a/docker-compose.ci.yml+++ b/docker-compose.ci.yml@@ -5,9 +5,13 @@# `bun run ci:local:diff` (see scripts/ci-local.sh).## All services are pulled as `image:` (no build) so `docker compose pull`-# refreshes everything. The bun version floats with `oven/bun:1` to track CI's-# `bun-version: latest`. Named volumes isolate the Linux container's deps from-# the host's darwin-arm64 deps and keep bun + postgres data warm across runs.+# refreshes everything. #4479: the bun tag is PINNED (default 1.3.14, matching+# the host/dev bun) instead of floating with `oven/bun:1` — a floating tag+# resolved to a newer bun than the host and produced container-only behavior+# skew during release gates. Override per-run with GBRAIN_CI_BUN_TAG (e.g.+# GBRAIN_CI_BUN_TAG=1 to deliberately test against latest). Named volumes+# isolate the Linux container's deps from the host's darwin-arm64 deps and+# keep bun + postgres data warm across runs.## Why 4 postgres services: bun's E2E suite shares one DB across 36 files and# uses TRUNCATE CASCADE in setupDB(). Running files in parallel against ONE DB@@ -120,7 +124,8 @@ services:condition: service_healthyrunner:- image: oven/bun:1+ # #4479: pinned to the host bun version by default (see header comment).+ image: oven/bun:${GBRAIN_CI_BUN_TAG:-1.3.14}working_dir: /appdepends_on:postgres-1:diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 01dd22027f..be27359379 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -109,7 +109,7 @@ Every non-localOnly operation on the MCP surface: 118 tools across 22 areas. **S| Tool | Description | Scope | Starter | Gate ||---|---|---|---|---|| `add_link` | Create link between pages | write | | |-| `find_orphans` | Find pages with no inbound wikilinks. | read | | |+| `find_orphans` | Find disconnected pages. | read | | || `get_backlinks` | List incoming links to a page | read | yes | || `get_links` | List outgoing links from a page | read | | || `list_link_sources` | List distinct link_source provenances in the brain with edge counts (e.g. | read | yes | |diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex ddc45c8da5..fd58ad3257 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -51,7 +51,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 (#2139); `--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 regression for the cost-preview fix), `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 prior 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 (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `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) not the old 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 — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer 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 #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); 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 no longer exits 2 — it auto-defers; #2139.) 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). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. 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 (#1970). 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 (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, 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 (#2426 — "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` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping 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 `willEmbedSynchronously` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, parallel) 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, or `--serial`) 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 embeds to capped backfill jobs and exits 0 (NEVER exit 2 — the wedged-cron fix); `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 | posture_tokenmax`) + a paste-ready `hint`; `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 (#753/#774): `--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 #1433 metafile posture); an all-excluded run warns loudly (NAV-4). 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`: 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)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: 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`.+- `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 prior 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 (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `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) not the old 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 — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer 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 #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); 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 no longer exits 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; #2139.) 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). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. 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 (#1970). 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 (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, 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 (#2426 — "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` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping 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` (#2139). 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 (#753/#774): `--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 #1433 metafile posture); an all-excluded run warns loudly (NAV-4). 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`: 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)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: 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`.- `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`.- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. 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; replaces bare `catch {}` blocks in `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).- `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)` (#1972) — 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 #2084 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`.@@ -60,12 +60,14 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `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 no longer removes 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 (#2576; 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/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 naive walkers slipped through and inflated MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (#2404; 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 (closes #923 + #202). `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 (closes #889). 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 imported by a pre-gate release 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'` (#2404) 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. Closes the phantom-import bug class where syncing a worktree-with-submodules walked into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger (issue #1939; formerly inline "Bug 9" in `sync.ts`). 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 12 codes (`SLUG_MISMATCH`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `NESTED_QUOTES`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `INVALID_UTF8`, `STATEMENT_TIMEOUT`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`) plus `UNKNOWN` (also recognizes `PAGE_JUNK_PATTERN` from the content-sanity gate); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`MISSING_CLOSE`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings, `FILE_TOO_LARGE` covers `import-file.ts:199, 352, 401`, `SYMLINK_NOT_ALLOWED` covers `:347`. 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 has blocked the bookmark past `failHours`; 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 relocated out of `src/commands/sync.ts` as a pure move; the façade re-exports them, and `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the pre-existing `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. `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.+- `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 relocated out of `src/commands/sync.ts` as a pure move; the façade re-exports them, and `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the pre-existing `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. `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op. Its queue context is engine-aware: only an explicitly worker-backed surface may promise job deferral; otherwise non-interactive cost deferral returns `manual_drain_required` with exact per-source `gbrain embed --stale --source <id>` commands and never writes or claims an embed-backfill row.+- `src/core/sync-embed-backfill.ts` — Sync command’s engine-aware embedding-delivery seam. It derives separate worker-backed deferral and multi-source fan-out eligibility, keeps automatic-submission policy distinct from capability, invokes the shared cost gate for `--all` and single-source runs, propagates intrinsic large-sync deferral into final delivery outcomes, resolves backfill results through the centralized submitter, formats one truthful human status, and builds the single-source JSON envelope. Keeping these pieces together prevents cost-gate, queue, human, and machine surfaces from drifting while the size-ratcheted `src/commands/sync.ts` façade stays at its committed ceiling.- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them, the #2788 class) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.- `src/core/disk-walk.ts` — `walkBrainRepo(repoPath)` returns `Map<slug, {size, mtimeMs}>` from one recursive `readdirSync`. Skips dot-dirs, `node_modules`, non-`.md` files. Used by `gbrain storage status` to replace per-page `existsSync + statSync` (~400K syscalls on 200K-page brains → tens).-- `src/core/git-head.ts` — local git HEAD freshness probe for `gbrain doctor`. `isSourceUnchangedSinceSync(localPath, lastCommit, opts?)` returns true iff `localPath` is a git repo whose current HEAD matches `lastCommit`; when `opts.requireCleanWorkingTree` is true also requires a clean working tree (mirrors `gbrain sync`'s force-walk gate at `sync.ts:1075` so doctor and sync agree on "is there work to do?"). `requireCleanWorkingTree` is `boolean | 'ignore-untracked'` — in `'ignore-untracked'` mode the clean probe runs `git status --porcelain --untracked-files=no` so a quiet repo with stray untracked dirs (`?? companies/`, `?? media/`) is still "unchanged" (sync's incremental path keys off the commit diff and never imports untracked files); `GitCleanProbe` gains an `ignoreUntracked?` second arg. Two probe seams (`_setGitHeadProbeForTests`, `_setGitCleanProbeForTests`) keep unit tests R2-compliant (no `mock.module`). Uses `execFileSync` with array args so shell metachars in `local_path` cannot escape to a shell (the regression test runs real `execFileSync` against `'/nonexistent/$(touch <sentinel>)/repo'` and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) preserving the caller's prior time-based behavior. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (`sources.chunker_version` vs `CHUNKER_VERSION` from `src/core/chunkers/code.ts`). Pinned by `test/core/git-head.test.ts` (incl. the shell-injection regression guard).-- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); pure `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → 0; else/null-content → wall-clock). `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.+- `src/core/git-head.ts` — local git HEAD freshness probe for `gbrain doctor`. `isSourceUnchangedSinceSync(localPath, lastCommit, opts?)` returns true iff `localPath` is a git repo whose current HEAD matches `lastCommit`; when `opts.requireCleanWorkingTree` is true also requires a clean working tree (mirrors `gbrain sync`'s force-walk gate at `sync.ts:1075` so doctor and sync agree on "is there work to do?"). `requireCleanWorkingTree` is `boolean | 'ignore-untracked'` — in `'ignore-untracked'` mode the clean probe runs `git status --porcelain --untracked-files=no` so a quiet repo with stray untracked dirs (`?? companies/`, `?? media/`) is still "unchanged" (sync's incremental path keys off the commit diff and does not import untracked files by default — it counts them as `uncommitted` drift with a stderr warning; `--working-tree` opts into importing them); `GitCleanProbe` gains an `ignoreUntracked?` second arg. Two probe seams (`_setGitHeadProbeForTests`, `_setGitCleanProbeForTests`) keep unit tests R2-compliant (no `mock.module`). Uses `execFileSync` with array args so shell metachars in `local_path` cannot escape to a shell (the regression test runs real `execFileSync` against `'/nonexistent/$(touch <sentinel>)/repo'` and asserts the sentinel is never created). Fail-open on every error (missing path, not a git repo, git not installed, timeout, NULL inputs, dirty-probe errored → false) preserving the caller's prior time-based behavior. The chunker-version-match check lives in the caller (doctor.ts) because it depends on engine state (`sources.chunker_version` vs `CHUNKER_VERSION` from `src/core/chunkers/code.ts`). Pinned by `test/core/git-head.test.ts` (incl. the shell-injection regression guard).+- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.+- `src/core/source-health.ts` — per-source health metrics for `gbrain sources status` + doctor's `federation_health`. Commit-relative staleness: `newestCommitMs(localPath)` = HEAD committer time via `git log -1 --format=%ct` (fail-open null; NO working-tree mtime parsing — committed content only, robust against the porcelain-mtime bug farm); `lagFromContentMs(contentMs|null, lastSyncMs|null, nowMs, ceilingSeconds?)` = remote/column comparator (null lastSync → null; negative wall-clock → skew passthrough; `contentMs <= lastSync` → **`max(0, wallClock - ceiling)`**; else/null-content → wall-clock). Core logic is pure; only the DEFAULT `ceilingSeconds` reads env, via `resolveStalenessCeilingSeconds()` (`GBRAIN_STALENESS_CEILING_HOURS` overriding `GBRAIN_SYNC_FRESHNESS_FAIL_HOURS`, default 72) — pass the 4th arg for determinism. The caught-up branch RAMPS rather than returning a flat 0: a flat 0 meant a source whose clone vanished reported fresh forever (the dead-daemon class), while a hard step to the ceiling would trip `federation_health` (24h) and `sync_freshness` (24h/72h) in the same instant and skip the warn tier — the alert-storm shape the caught-up branch exists to prevent. Ramping keeps the escalation ordered. `computeAllSourceMetrics(engine, sources, {probeContent?})`: LOCAL (`probeContent:true`, `gbrain sources status`) → `isSourceUnchangedSinceSync(..., {requireCleanWorkingTree:'ignore-untracked'}) ? 0 : wall-clock` (live commit-hash catches HEAD moving to an old-dated commit a timestamp compare would miss); REMOTE (default, `federation_health` on the HTTP MCP path) → `lagFromContentMs(row.newest_content_at, ...)`, NO git subprocess (trust boundary). `commitTimeMs(localPath, sha)` is the `newestCommitMs` sibling pinned to an arbitrary commit (committer time via `git show -s --format=%ct <sha>`, fail-open null, execFileSync array args) — the resumable sync stamps `newest_content_at` against its pinned target commit, not whatever HEAD raced to. Pinned by `test/source-health.test.ts`.- `src/core/npm-squat-check.ts` — classifies `gbrain` PATH entries as real, foreign npm package, broken, or unknown for doctor's `npm_squat` check. On Windows it normalizes Git Bash/MSYS drive paths (`/c/...` → `C:/...`) and tries the native `.exe` suffix before reporting a broken entry; non-Windows classification keeps the original single-candidate behavior. Pinned by `test/npm-squat-check.test.ts`.- `src/core/git-remote.ts` — SSRF-hardened git invocations for remote-source `cloneRepo`, `pullRepo`, and `fetchRemote(repoPath, branch)` (the last added for the sync cost-estimator's fetch-first path, #2139, so a cost preview / dry-run fetches through the same hardened flags + `GIT_TERMINAL_PROMPT=0` as real sync rather than a less-protected route). Exports two distinct flag constants because `git`'s argv grammar treats them differently: `GIT_SSRF_FLAGS` (3 `-c` config flags — `protocol.allow=user`, `protocol.file.allow=never`, `http.allowRedirects=false`) is global config, spread BEFORE the subcommand verb; `GIT_SSRF_SUBCOMMAND_FLAGS = ['--no-recurse-submodules']` is subcommand-scoped, spread AFTER the verb (a combined array would spread `--no-recurse-submodules` before the verb where real git rejects it exit 129). `cloneRepo` argv: `git <GIT_SSRF_FLAGS> clone <GIT_SSRF_SUBCOMMAND_FLAGS> --depth=1 [--branch X] -- <url> <dir>`. `pullRepo` argv: `git <GIT_SSRF_FLAGS> -C <dir> pull <GIT_SSRF_SUBCOMMAND_FLAGS> --ff-only`. Pinned by `test/git-remote.test.ts` position-anchored regression guard (`argv.indexOf('--no-recurse-submodules') > argv.indexOf(verb)`). Also exports the durability-side helpers that power `gbrain sources harden/pull`: `GIT_ENV_AUTH` (the no-prompt env minus the askpass `/bin/false` overrides, so an auth'd push/fetch can consult the repo's configured credential helper while `GIT_TERMINAL_PROMPT=0` still fails fast on a missing credential), `divergenceSafePull(repoPath, branch)` (fetch + `pull --rebase`; returns `skipped_dirty` on a dirty tree, `conflict_aborted` on a rebase conflict after `rebase --abort` so the tree is never left mid-rebase, else `up_to_date`/`advanced`), `detectDefaultBranch` (origin/HEAD → current branch → `main`), `pushProbe(repoPath, branch)` (authenticated `push --dry-run` that proves push access and classifies `auth`/`protected`/`unreachable`), and `isWorkingTreeDirty`. These auth'd paths route their `protocol.file.allow` through `GBRAIN_GIT_ALLOW_FILE_TRANSPORT` (default `never`; set `=1` for self-hosted filesystem remotes), unlike clone/pull which stay strict.- `src/core/brain-repo-durability.ts` + `src/commands/sources-harden.ts` — brain-repo git durability. `hardenBrainRepo(opts)` makes a brain's working tree durable, idempotently: divergence-safe pull, a LOCAL untracked `.git/hooks/post-commit` auto-push safety net (never committed — a pulled commit can't rewrite executed code next to the token; installed into the active `core.hooksPath` dir and excluded via `.git/info/exclude` when that dir is tracked), a committed `scripts/brain-commit-push.sh` that refuses to exit 0 without a confirmed push and stages+commits BEFORE any pull so a dirty tree of modified pages (the write-through shape) can still be committed — the push-retry's rebase-on-reject handles a remote that advanced (#2426; hook + helper render from ONE bash push-retry template — DRY at the TS source, not by the hook sourcing a repo-controlled script), durability rules patched into the active resolver file (`findResolverFile` → RESOLVER.md > AGENTS.md; taxonomy rendered from the bundled `_brain-filing-rules.json`), a minimal DB-free pull cron (launchd/crontab running `gbrain sources pull --path <dir>` so it never opens the PGLite single-writer lock), and a push-probe verify (no heartbeat commit). Credential is REPO-scoped (`acceptPat` from `--pat-file`/`GBRAIN_GITHUB_PAT`, warns on loose perms; reuses an existing repo-local `credential.helper`, else a `0600` store wired via repo-local config); the token is redacted everywhere via `redactSecretsInText` and never enters the repo, remote URL, logs, or `DurabilityReport`. `unhardenBrainRepo` removes the cron/hook/credential wiring (ownership-fingerprinted); `sources remove` runs it only AFTER the source row's DELETE commits (a refused or raced delete leaves the scaffolding intact; post-commit teardown failure is loud but non-fatal). CLI: `gbrain sources harden <id|--all>` / `pull <id>|--path <dir>` / `unharden <id>`; auto-harden fires on `sources add --url ... --pat-file` for managed clones (`--no-harden` opts out). `sources pull --path` is dispatched in `src/cli.ts` BEFORE `connectEngine` so the cron stays DB-free. CLI-only (writes executables + an OS cron + a credential helper on the host); never exposed over MCP. Tests: `test/brain-repo-durability.serial.test.ts`, `test/git-remote-durable.serial.test.ts`, `test/brain-durability-hook.serial.test.ts`, `test/durability-cron.test.ts`.@@ -128,8 +130,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/search/hybrid.ts` — Cathedral II `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; existing callers leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, behavior is byte-for-byte unchanged, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` is the engines' out-channel for searchVector's bounded pagination escalation (one dense page filling the inner candidate pool escalates the pool ×4 up to 3 times; HNSW-backed columns additionally cap at the `ef_search` ceiling, while exact-scan columns above the index dim ceiling are bounded by the escalation count alone); hybrid passes the collector and owns the emit, fired when the loop ends with the pre-DISTINCT pool still full — at the substrate cap or after the escalation budget. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (new optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error.- `docs/eval-capture.md` — stable NDJSON schema reference for gbrain-evals consumers.- `test/public-exports.test.ts` — runtime contract test (R2). Imports each of the 17 public subpaths via package name and pins a canary symbol per module. Paired with `scripts/check-exports-count.sh`.-- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff. `BATCH_SIZE=100` (per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection). `estimateEmbeddingCostUsd(tokens)` prices against the currently-configured model's rate via `currentEmbeddingPricePerMTok()` (resolves the per-1M-token rate via `lookupEmbeddingPrice(gatewayGetModel())` from `embedding-pricing.ts`, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table). `EMBEDDING_COST_PER_1K_TOKENS` retained for back-compat with direct importers/tests. `currentEmbeddingSignature(): string` returns the embedding-provenance signature `<provider:model>:<dims>` (e.g. `openai:text-embedding-3-large:1536`) stamped onto `pages.embedding_signature` at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via `pages.chunker_version`) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (See `src/core/sync-delta.ts` + `src/core/spend-posture.ts` for the #2139 cost-gate supporting modules.) `willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode` is the single source of truth for whether `gbrain sync --all` embeds at sync time (`'inline'`) or defers to per-source `embed-backfill` minion jobs (`'deferred'`) — mirrors `sync.ts`'s `effectiveNoEmbed` resolution exactly (`v2Enabled && !serialFlag && !noEmbed → deferred`) so cost gate and embed decision can't drift. `shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): boolean` is the pure cost-gate decision: blocks ONLY when `mode === 'inline' && costUsd > floorUsd` — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and `posture === 'tokenmax'` never blocks (the operator declared cost isn't the constraint; an `off`/`unlimited` floor is `Infinity` and so is never exceeded). Pinned by `test/sync-cost-preview.test.ts` + `test/embedding-signature-stale.test.ts`.-- `src/core/embed-retry.ts` — embed retry/backoff primitives + the title-tier restamp helper, peeled from `src/commands/embed.ts` (layering fix: `src/core/import-file.ts` and `src/core/embed-stale.ts` consume these, and a core→commands import meant every import-file consumer eagerly loaded the embed COMMAND module — one value import away from a real ESM cycle). `embedBatchWithBackoff` wraps `embedBatch` with rate-limit-aware retry: detects 429s via the wrapped error's `cause.status` (message-match fallback), also retries transient gateway 502/503/504 (#3966), parses provider retry-delay hints, jitters ±30% so concurrent workers don't resynchronize, passes `maxRetries: 0` through so the AI SDK's own retry stack doesn't multiply attempts, and threads an external AbortSignal into both the sleep and the in-flight HTTP call. `restampIfDemotedToTitleTier` (#3507) restamps a `per_chunk_synopsis` page's CR state to `'title'` after a plain re-embed so `contextual_retrieval_mode` keeps describing the vectors actually in the column (the reindex sweep restores the synopsis tier later). `src/commands/embed.ts` re-exports everything here (façade rule) so historical import sites and tests never chase the peel.- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper (#2139), consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (#1970 discipline — a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`, relocated here from sync.ts). NO dirty/untracked probe — attached-HEAD incremental sync imports only the commit diff, so pricing dirty files would re-introduce phantom costs on a busy brain. `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`.+- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff. `BATCH_SIZE=100` (per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection). `estimateEmbeddingCostUsd(tokens)` prices against the currently-configured model's rate via `currentEmbeddingPricePerMTok()` (resolves the per-1M-token rate via `lookupEmbeddingPrice(gatewayGetModel())` from `embedding-pricing.ts`, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table). `EMBEDDING_COST_PER_1K_TOKENS` retained for back-compat with direct importers/tests. `currentEmbeddingSignature(): string` returns the embedding-provenance signature `<provider:model>:<dims>` (e.g. `openai:text-embedding-3-large:1536`) stamped onto `pages.embedding_signature` at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via `pages.chunker_version`) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (See `src/core/sync-delta.ts` + `src/core/spend-posture.ts` for the #2139 cost-gate supporting modules.) `willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode` retains the package-exported compatibility contract for downstream TypeScript and JavaScript consumers. The command-internal `resolveWorkerBackedSyncEmbedMode({deferEligible, noEmbed})` uses the engine-aware admission result, so PGLite/unknown runtimes stay inline while worker-backed Postgres preserves v2 deferral even with one runnable source; source count separately controls fan-out. `shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): boolean` is the pure cost-gate decision: blocks ONLY when `mode === 'inline' && costUsd > floorUsd` — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and `posture === 'tokenmax'` never blocks (the operator declared cost isn't the constraint; an `off`/`unlimited` floor is `Infinity` and so is never exceeded). Pinned by `test/sync-cost-preview.test.ts` + `test/embedding-signature-stale.test.ts`.+- `src/core/embed-retry.ts` — embed retry/backoff primitives + the title-tier restamp helper, peeled from `src/commands/embed.ts` (layering fix: `src/core/import-file.ts` and `src/core/embed-stale.ts` consume these, and a core→commands import meant every import-file consumer eagerly loaded the embed COMMAND module — one value import away from a real ESM cycle). `embedBatchWithBackoff` wraps `embedBatch` with rate-limit-aware retry: detects 429s via the wrapped error's `cause.status` (message-match fallback), also retries transient gateway 502/503/504 (#3966), parses provider retry-delay hints, jitters ±30% so concurrent workers don't resynchronize, passes `maxRetries: 0` through so the AI SDK's own retry stack doesn't multiply attempts, and threads an external AbortSignal into both the sleep and the in-flight HTTP call. `restampIfDemotedToTitleTier` (#3507) restamps a `per_chunk_synopsis` page's CR state to `'title'` after a plain re-embed so `contextual_retrieval_mode` keeps describing the vectors actually in the column (the reindex sweep restores the synopsis tier later). `src/commands/embed.ts` re-exports everything here (façade rule) so historical import sites and tests never chase the peel.+- `src/core/sync-delta.ts` — the single "what changed since last_commit" helper (#2139), consumed by BOTH `performSyncInner` (sync executor) and `estimateInlineNewTokens` (cost estimator) so the gate's dollar figure can't drift from what the sync imports. `computeSyncDelta(repoPath, fromCommit, toCommit, {detachedManifest?, detached?})` → `{status:'ok', manifest}` | `{status:'unavailable', reason:'anchor_missing'|'diff_failed'}`. Anchor reachability via `git cat-file -t` (#1970 discipline — a gc'd bookmark is `anchor_missing`, but a present-but-non-ancestor bookmark is still diffed tree-to-tree), then `git diff --name-status -M from..to` parsed by `buildSyncManifest`; merges the detached working-tree manifest when detached (`buildDetachedWorkingTreeManifest`, relocated here from sync.ts). NO dirty/untracked probe in the estimator — pricing dirty files would re-introduce phantom costs on a busy brain. The executor imports only the commit diff on attached HEADs BY DEFAULT, but now counts uncommitted working-tree files (untracked + dirty) as `SyncResult.uncommitted` drift and, with `--working-tree` / config `sync.include_working_tree`, merges the working-tree manifest into the delta so attached repos can import uncommitted state (the estimator does not price that opt-in). `execFileSync` array-args (shell-injection safe), 30s / 100 MiB budget. Test seam `_setGitRunnerForTests`. Pinned by `test/sync-delta.test.ts`.- `src/core/spend-posture.ts` — spend-control surface (#2139). `resolveSpendPosture(engine): 'gated'|'tokenmax'` (DB-plane `spend.posture`, fail-open `gated`); `tokenmax` makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). `parseUsdLimit(raw, def, {allowZero?})` accepts `off`/`unlimited`/`none` → `Infinity`; `formatUsdLimit(n)` renders `Infinity` as the string `'unlimited'` (never raw — `JSON.stringify(Infinity)` is `null`); `usdLimitToCap(n)` maps `Infinity` → `undefined` at the BudgetTracker boundary so ledger rows never serialize null. `normalizeSpendPosture`/`isValidSpendPosture` back the `config set` validation. Doc: `docs/operations/spend-controls.md`. Pinned by `test/sync-cost-preview.test.ts` + `test/spend-off-switch.test.ts`.- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, falling back to `DEFAULT_EMBEDDING_DIMENSIONS=1536`, an OpenAI default not a Voyage one). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase, #4123) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/ZeroEntropy/Perplexity config that used to skip validation (and silently produce wrong-width vectors) now matches and fails loudly at init when its `dims` is invalid.- `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). `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.@@ -137,6 +140,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `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 — #1400; `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 configured reranker via `getRerankerModel()`, 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. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | 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()` accessor + `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 (regression 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"; new 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 the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). 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` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:<model>`, silently disabling vector search. `configureGateway` no longer backfills `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`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook (#4194/CDX-7): 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'` (#4088): 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 (#4201): `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, #4087) 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 (#4121 — they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`, so their spend was previously invisible to every cap and ledger): 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). `__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 regression in `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 by regression). `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 deleted in the September removal release.- `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). Same wave adds: `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` (closes file-plane / DB-plane divergence where doctor said "not configured" while live search was actively reranking — the field-plane `getRerankerModel()` read nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.+- `src/core/ai/recipes/nan.ts` — nan.builders openai-compatible reranker recipe. `POST {base}/v1/rerank` → `results[{index, relevance_score}]`, leaf-only (`base_url_default` ends `/v1`; bare `/rerank` and `/compatible-api/v1/reranks` both 404). Model id is the literal `rerank` (a Qwen3-Reranker-8B deployment). `auth_env.required: ['NAN_API_KEY']`.- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (#4114; gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is enforced by `classifyCapabilities()` in `src/core/ai/capabilities.ts` (verdict `unusable:no_subagent_loop` — `enforceSubagentCapable()` in `src/core/model-config.ts` consumes the verdict: tool-less/unknown models fall back to `TIER_DEFAULTS.subagent` with a warn; tool-capable providers without prompt caching run with a once-per-model cost warn); the legacy Anthropic-direct path additionally gates on `isAnthropicProvider()` in `src/core/model-config.ts` when `agent.use_gateway_loop` is off. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).- `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)`. 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 reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). 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 (#1262): `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`.@@ -248,7 +252,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.- `src/core/zombie-reap.ts` — idempotent `installSigchldHandler()` so JS-spawned children get reaped via Bun's internal `waitpid()`. Bun (like Node) only auto-reaps when a SIGCHLD listener is registered; without it, every child the worker spawns (shell jobs, embed batches, sub-agents) becomes a zombie on exit and holds connection slots. Called once at module load from `src/cli.ts` (Windows platform guard — SIGCHLD doesn't exist on Windows). Cross-file leak guard via `_uninstallSigchldHandlerForTests()`. Layer 1 of the three-layer zombie defense; Layer 2 is tini-as-PID-1 wrapping the worker subtree (via `src/core/minions/spawn-helpers.ts`); Layer 3 is the container's own tini for hard Bun crashes.- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs on every lane that can strand a queue: supervisor beforeSpawn, bare `gbrain jobs work` startup (skipped under GBRAIN_SUPERVISED=1 — the supervisor already ran it; autopilot children never set the flag, so autopilot spawns/respawns recover too), and dream-cycle start (cycle.ts, next to the #1972 lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The #4145 lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The #4145 lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor.ts` `subagent_provider` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed).+- `src/core/minions/embed-backfill-admission.ts` — Centralized, dependency-light embed-backfill admission contract shared by the public `MinionQueue.add` boundary, CLI, MCP operations, automatic submitters, sync cost reporting, and doctor remediation. `embedBackfillWorkerSurface` recognizes only explicit `postgres` as worker-backed; the declared engine-kind switch is compile-time exhaustive, while untyped/cast unknown runtime values still fail closed as `no_worker_surface`. `assertEmbedBackfillQueueAdmission` refuses before any database/config access unless the explicit PGLite inline-worker trust is present, validates payload source IDs through the canonical `source-id.ts` contract before rendering any remedy, and `embedBackfillManualDrainCommand(sourceId)` is the single injection-safe exact `gbrain embed --stale --source <id>` recovery command.+- `src/core/embed-backfill-submit.ts` — Automatic per-source embed-backfill submitter with a true discriminated result union: `submitted` requires `jobId` plus an explicit spend-bypass payload, `cooldown` requires a reason plus a numeric remaining duration or explicit `null` for active work, `spend_capped` requires cap/spend payloads, and `no_worker_surface` requires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the moved-out generic abort listener now fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape was the unhandledRejection crash class during PgBouncer rotation). Gaps closed: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips now counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) #4145 verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete can no longer remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe now runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress (#1801). Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`) on the `db_dead` unhealthy payload. `getHandler(name)` is the read-only registry accessor run-child uses.- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) no longer permanently gives up (#1994/#2227): the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment no longer reads a healthy supervisor as "not running" (#2227). `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog (#1801): `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions (#1815). Queue-scoped singleton (#1849): the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (an earlier revision mixed in a config-derived DB identity, which let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire — fixed). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` no longer both run with conflicting `--max-rss`; the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is now brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit now records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion).- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). New opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so the old `!this._child.killed` guard made a follow-up SIGKILL after an ignored SIGTERM a silent no-op (#1801; the bug also lived in the `shutdown()` drain). `restartCurrentChild(graceMs)` (#1801 wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry (#1994/#2227): the `run()` loop no longer fires `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` adds `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).@@ -296,7 +302,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.- `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 regression 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 — the #2194/#2227 mixed-scope fix) 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 gains 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 #2849 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).+- `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 regression 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 — the #2194/#2227 mixed-scope fix) 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 gains 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 #2849 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 new 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.v0.46: 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 (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `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` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds 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 (stale lock from a crashed process no longer blocks). (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 (#2608): `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).@@ -571,7 +577,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche- `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 (#4043; 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) → 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 previously blocked 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.- `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). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip).-- `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 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/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). 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.- `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).diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 9722bbf0f6..9bc1acad6c 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -42,13 +42,15 @@ gbrain sync --repo /path/to/brain && gbrain embed --stale```- `gbrain sync --repo <path>` -- one-shot incremental sync. Detects changes via- `git diff`, imports only what changed. For small changesets (<= 100 files),- embeddings are generated inline during import — unless the inline cost gate- intervenes: when the estimated embedding spend crosses the configured floor- in a non-interactive session (cron, `--json`), sync auto-defers embeds to a- capped `embed-backfill` job instead of spending silently. Either way the- chunks get embedded; a deferred run just finishes asynchronously. See- [spend controls](../operations/spend-controls.md).+ `git diff`, imports only what changed. **Commit-driven:** it imports+ *committed* changes; uncommitted edits and untracked files are counted and+ reported as drift, not silently ignored (see Tricky Spot 6). For small+ changesets (<= 100 files), embeddings are generated inline during import —+ unless the inline cost gate intervenes: when the estimated embedding spend+ crosses the configured floor in a non-interactive session (cron, `--json`),+ sync auto-defers embeds to a capped `embed-backfill` job instead of spending+ silently. Either way the chunks get embedded; a deferred run just finishes+ asynchronously. See [spend controls](../operations/spend-controls.md).- `gbrain embed --stale` -- backfill embeddings for any chunks that don't havethem. Safety net for large syncs (>100 files) or prior `--no-embed` runs.On a keyless brain (installed with `--no-embedding`), a bare stale embed@@ -175,6 +177,22 @@ vars — incident-time escape hatches, not everyday knobs.`kind: "import"` so downstream tools can validate the contract beforedeciding whether to resume.+6. **Sync imports commits, not your working tree.** Files written into the+ brain repo but never committed are invisible to incremental sync. Sync+ won't stay silent about them: it prints a NOTE with the drift counts+ (`N uncommitted file(s) not synced`), the sync result object carries an+ `uncommitted` summary (surfaced via `sync_brain` over MCP and in+ `gbrain dream --json` phase details), and the nightly dream cycle reports+ the sync phase as `warn` instead of a clean run. The fix is to commit the files. If your+ workflow legitimately writes without committing, opt in to importing+ uncommitted state with `gbrain sync --working-tree` (one run) or+ `gbrain config set sync.include_working_tree true` (standing config,+ honored by every caller including the dream cycle). Caution before making+ it standing config: untracked means everything `git status` lists as+ untracked — unignored scratch files and secrets included — so review+ `git status` first. Gitignored files stay excluded either way (use+ `--include-gitignored` for those).+## How to Verify1. **Edit a file and search for the change.** Edit a brain markdown file,diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex ea08943adc..1ea2a9da8b 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -174,7 +174,15 @@ Two details that are easy to miss:empty commit (`git commit --allow-empty`) — isn't enough. Registrationchecks for real tracked content (`git ls-tree HEAD` scoped to the path),not just a resolvable `HEAD`, so this footgun is caught immediately- instead of surfacing later as a sync that imports nothing.+ instead of surfacing later as a sync that imports nothing. For files that+ are deliberately untracked or `.gitignore`d but should still sync, use+ `gbrain sync --include-gitignored` — it forces a full filesystem walk so+ periodic syncs see ignored/untracked syncable content the git-object walk+ skips (`gbrain import <dir> --include-gitignored` is the one-shot import+ equivalent). Doctor's `multi_source_drift` advice names this case (#4490):+ a slug stuck at `default` whose file is untracked won't be recreated by a+ plain re-sync, so reach for the flag (or commit the file) before any+ delete step.- **`--force` registers the source anyway**, skipping the check. Use this ifyou're registering a path before an automated pipeline gets around to`git init`-ing it. GBrain never auto-`git init`s a `--path` source fordiff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex bb0b243e05..c6e1ba14c4 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -57,6 +57,13 @@ The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to m| `migrate embeddings` consent gate | — (plan + estimate before provider migration) | — | TTY y/N prompt / non-TTY refuse + exit 2 | `--yes` | estimate marked informational, but **still prompts** (guards a destructive schema rebuild, not just spend) || `enrich` / `onboard --auto` | `--max-usd` (per-call) | — | refuse without a cap (non-TTY) | `--max-usd off` | runs uncapped (still ledgered) || Image-OCR per-run ceiling (#3973) | `embedding_image_ocr_max_images` / `embedding_image_ocr_max_usd` | `200` images / `$1.00` (estimated) | skips OCR over-cap (import continues; skips counted in `ocr_skipped_budget`, surfaced by doctor `ocr_health`) | `0` disables that cap | **not** bypassed (per-run cap, not a tracker gate) |+| Dream `extract_atoms` phase budget | `cycle.extract_atoms.budget_usd` | `0.30` | caps the phase's budget tracker | — | **not** consulted (phase budget enforces regardless) |++The `extract_atoms` cap is enforced only for models in the pricing maps. A model+the tracker cannot price — e.g. a local Ollama model selected via+`models.dream.extract_atoms` — runs without a cost gate after a one-line stderr+warning (a USD cap cannot be enforced on an unpriced model; local models incur+no API spend).### Sync inline-embed cost gate@@ -65,7 +72,12 @@ Fires only when sync embeds **inline** (federated_v2 off, or `--serial` withoutjobs and the gate is informational. The estimate prices the **delta** — the files thissync will actually import (fetched-first, so it sees commits the run is about to pull) —not the whole tree. A busy brain with a dirty working tree but caught-up commits-estimates `$0`, because an attached-HEAD sync imports only the committed diff.+estimates `$0`, because an attached-HEAD sync imports only the committed diff by+default. The `--working-tree` / `sync.include_working_tree` opt-in is the one+exception: it imports uncommitted files that the estimator deliberately does not+price (pricing dirty files on every attached repo would bring back the+phantom-cost class the delta estimate exists to kill), so the gate can+underestimate an explicit working-tree run.Behavior above the floor:- **TTY:** prompts `[y/N]`.diff --git a/llms-full.txt b/llms-full.txtindex 0485700a4e..e621cc9776 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3042,13 +3042,15 @@ gbrain sync --repo /path/to/brain && gbrain embed --stale```- `gbrain sync --repo <path>` -- one-shot incremental sync. Detects changes via- `git diff`, imports only what changed. For small changesets (<= 100 files),- embeddings are generated inline during import — unless the inline cost gate- intervenes: when the estimated embedding spend crosses the configured floor- in a non-interactive session (cron, `--json`), sync auto-defers embeds to a- capped `embed-backfill` job instead of spending silently. Either way the- chunks get embedded; a deferred run just finishes asynchronously. See- [spend controls](../operations/spend-controls.md).+ `git diff`, imports only what changed. **Commit-driven:** it imports+ *committed* changes; uncommitted edits and untracked files are counted and+ reported as drift, not silently ignored (see Tricky Spot 6). For small+ changesets (<= 100 files), embeddings are generated inline during import —+ unless the inline cost gate intervenes: when the estimated embedding spend+ crosses the configured floor in a non-interactive session (cron, `--json`),+ sync auto-defers embeds to a capped `embed-backfill` job instead of spending+ silently. Either way the chunks get embedded; a deferred run just finishes+ asynchronously. See [spend controls](../operations/spend-controls.md).- `gbrain embed --stale` -- backfill embeddings for any chunks that don't havethem. Safety net for large syncs (>100 files) or prior `--no-embed` runs.On a keyless brain (installed with `--no-embedding`), a bare stale embed@@ -3175,6 +3177,22 @@ vars — incident-time escape hatches, not everyday knobs.`kind: "import"` so downstream tools can validate the contract beforedeciding whether to resume.+6. **Sync imports commits, not your working tree.** Files written into the+ brain repo but never committed are invisible to incremental sync. Sync+ won't stay silent about them: it prints a NOTE with the drift counts+ (`N uncommitted file(s) not synced`), the sync result object carries an+ `uncommitted` summary (surfaced via `sync_brain` over MCP and in+ `gbrain dream --json` phase details), and the nightly dream cycle reports+ the sync phase as `warn` instead of a clean run. The fix is to commit the files. If your+ workflow legitimately writes without committing, opt in to importing+ uncommitted state with `gbrain sync --working-tree` (one run) or+ `gbrain config set sync.include_working_tree true` (standing config,+ honored by every caller including the dream cycle). Caution before making+ it standing config: untracked means everything `git status` lists as+ untracked — unignored scratch files and secrets included — so review+ `git status` first. Gitignored files stay excluded either way (use+ `--include-gitignored` for those).+## How to Verify1. **Edit a file and search for the change.** Edit a brain markdown file,diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 49465788c2..a6509dff15 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.28.0",+ "version": "0.46.29.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 344a0b1082..da6261bc54 100644--- a/package.json+++ b/package.json@@ -171,7 +171,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.28.0",+ "version": "0.46.29.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex 0af0983d93..0fa902f2e7 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.46.28.0",+ "version": "0.46.29.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 — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json b/plugin-variants/gbrain-coding/.codex-plugin/mcp.jsonindex 13a38a285d..c827db3637 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/mcp.json@@ -56,6 +56,7 @@"MINIMAX_API_KEY","MISTRAL_API_KEY","MOONSHOT_API_KEY",+ "NAN_API_KEY","NVIDIA_API_KEY","OLLAMA_API_KEY","OLLAMA_BASE_URL",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex 3dabc979d3..be44980c77 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.46.28.0",+ "version": "0.46.29.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 — 18 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex 716fb87d91..740728e562 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.29.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-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex ac9af03505..3ee39299c3 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.46.28.0",+ "version": "0.46.29.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 — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json b/plugin-variants/gbrain-daily/.codex-plugin/mcp.jsonindex 13a38a285d..c827db3637 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/mcp.json@@ -56,6 +56,7 @@"MINIMAX_API_KEY","MISTRAL_API_KEY","MOONSHOT_API_KEY",+ "NAN_API_KEY","NVIDIA_API_KEY","OLLAMA_API_KEY","OLLAMA_BASE_URL",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex c2e74d54f4..dc61c9fb13 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.46.28.0",+ "version": "0.46.29.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 — 17 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex e9952cbfdb..b8d59119c2 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.29.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/README.md b/plugin/README.mdindex be13b293f5..88ead63c75 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->+<!-- gbrain-plugin-tree-stamp: 0.46.29.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/ci-local.sh b/scripts/ci-local.shindex f4b26d6b16..0be11d9457 100755--- a/scripts/ci-local.sh+++ b/scripts/ci-local.sh@@ -124,7 +124,7 @@ figitleaks dir . --redact --no-bannergitleaks git . --redact --no-banner --log-opts="origin/master..HEAD"-# Step 1: pull. Refreshes pgvector + oven/bun:1 (both are `image:` not `build:`).+# Step 1: pull. Refreshes pgvector + the pinned oven/bun tag (both are `image:` not `build:`).if [ "$NO_PULL" = "0" ]; thenecho "[ci-local] Pulling base images (use --no-pull to skip)..."docker compose -f "$COMPOSE_FILE" pull 2>&1 | tail -5@@ -247,6 +247,10 @@ echo \"[runner] Tier 3: PGLite snapshot fixture (idempotent; rebuilds on hash dr# warn+slow path). Concurrency-safe via the script's mkdir lock (D5.8).bun run build:pglite-snapshotexport GBRAIN_PGLITE_SNAPSHOT=test/fixtures/pglite-snapshot.tar+# #4479: 4-way shard contention makes subprocess/PGLite tests ~6x slower per+# file in the container than natively — timeout-class failures that pass on+# the host. Scale the per-test ceiling for the container lane (overridable).+export GBRAIN_TEST_TIMEOUT_MULTIPLIER=\${GBRAIN_TEST_TIMEOUT_MULTIPLIER:-6}echo \"[runner] resolving E2E file selection (--diff aware)\"${DIFF_E2E_PREP}mkdir -p /tmp/shard-logs@@ -313,7 +317,7 @@ fiINNER_CMD=$(cat <<'EOF'set -euo pipefailecho "[runner] bun version: $(bun --version)"-# oven/bun:1 omits git; many unit tests use mkdtemp + git init for fixtures.+# The oven/bun image omits git; many unit tests use mkdtemp + git init for fixtures.if ! command -v git >/dev/null 2>&1; thenecho "[runner] Installing git (debian apt)..."apt-get update -qq >/dev/nulldiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d5c77bb051..41d29fec6b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,31 +3,31 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/commands/doctor.ts 4443 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)+src/commands/doctor.ts 4572 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)src/core/operations.ts 315 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring-src/core/postgres-engine.ts 6166 ratchet grown v0.46.26.0 megawave (#4218 #3986 #4352) + master v0.46.26.0 private-queue token bootstrap probe-src/core/pglite-engine.ts 6062 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns+src/core/postgres-engine.ts 5607 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+src/core/pglite-engine.ts 6090 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 migratesrc/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)-src/commands/sync.ts 4530 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-src/core/ai/gateway.ts 4494 ratchet grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312)-src/cli.ts 3723 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297)-src/core/cycle.ts 3171 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery-src/commands/serve-http.ts 3294 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844)-src/commands/jobs.ts 3111 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating-src/core/search/hybrid.ts 2845 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352)-src/core/engine.ts 2495 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218)+src/commands/sync.ts 4684 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+src/core/ai/gateway.ts 4515 ratchet 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)+src/cli.ts 3741 ratchet 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+src/core/cycle.ts 3186 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+src/commands/serve-http.ts 3319 ratchet grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper+src/commands/jobs.ts 3115 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)+src/core/search/hybrid.ts 2954 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+src/core/engine.ts 2509 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted countsrc/commands/autopilot.ts 2641 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)-src/commands/extract.ts 2332 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4)-src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copy-src/core/import-file.ts 2142 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374)-src/core/cycle/synthesize.ts 2792 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer-src/commands/embed.ts 1896 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix)+src/commands/extract.ts 2385 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+src/commands/extract-conversation-facts.ts 2052 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts+src/core/import-file.ts 2181 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+src/core/cycle/synthesize.ts 2818 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+src/commands/embed.ts 1901 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 wiringsrc/core/types.ts 1946 ratchet grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218)src/commands/skillpack.ts 1360 ratchetsrc/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic leasesrc/commands/init.ts 1950 ratchet grown v0.46.x keyless capability noticessrc/commands/integrations.ts 1736 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit)-src/core/minions/handlers/subagent.ts 1825 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+src/core/minions/handlers/subagent.ts 1834 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 loopsrc/commands/bootstrap.ts 2010 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness)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 wavesrc/commands/sources.ts 1790 ratchet grown v0.46.22.0 phone wave: github source kind (#4104)@@ -36,5 +36,5 @@ src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0src/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/core/bootstrap/harness.ts 1947 ratchetsrc/commands/hook.ts 1559 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245)-src/core/chunkers/code.ts 1556 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes)-src/core/config.ts 1503 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation)+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 1520 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 keysdiff --git a/scripts/run-unit-shard.sh b/scripts/run-unit-shard.shindex 51c33c7144..fa83f1e4a4 100755--- a/scripts/run-unit-shard.sh+++ b/scripts/run-unit-shard.sh@@ -81,8 +81,19 @@ if [ "$DRY_RUN" = "1" ]; thenexit 0fi-echo "[unit-shard ${SHARD:-(unsharded)}] running ${#files[@]} files"+# #4479: per-shard timeout multiplier. 4-way shard contention in the CI+# container makes subprocess/PGLite tests ~6x slower per file than native,+# producing timeout-class failures that pass natively. The 60s per-test+# ceiling scales by GBRAIN_TEST_TIMEOUT_MULTIPLIER (integer, default 1;+# ci-local's container lane sets it). Non-integer values fall back to 1.+MULT="${GBRAIN_TEST_TIMEOUT_MULTIPLIER:-1}"+if ! printf '%s' "$MULT" | grep -qE '^[0-9]+$' || [ "$MULT" -lt 1 ]; then+ MULT=1+fi+TEST_TIMEOUT_MS=$((60000 * MULT))++echo "[unit-shard ${SHARD:-(unsharded)}] running ${#files[@]} files (timeout=${TEST_TIMEOUT_MS}ms)"if [ -n "$MAX_CONC" ]; then- exec bun test --max-concurrency="$MAX_CONC" --timeout=60000 "${files[@]}"+ exec bun test --max-concurrency="$MAX_CONC" --timeout="$TEST_TIMEOUT_MS" "${files[@]}"fi-exec bun test --timeout=60000 "${files[@]}"+exec bun test --timeout="$TEST_TIMEOUT_MS" "${files[@]}"diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 228b05a887..ede97149e7 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -84,12 +84,14 @@ test/destructive-guard.test.ts FK-RESTRICT lifecycle (clientsReferencingSource +test/destructive-guard.test.ts assessDestructiveImpact 5 readFileSynctest/destructive-guard.test.ts formatters (display helpers) 4 readFileSynctest/destructive-guard.test.ts purgeExpiredSources — clone cleanup containment 1 readFileSync+test/detached-stderr.test.ts jobs.ts detach branch (source pin, #4418) 2 readFileSynctest/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helpertest/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSynctest/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helpertest/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — structural rendering (source-grep) 6 doctor-source-helpertest/doctor-orphan-ratio.test.ts cross-surface parity contract 3 doctor-source-helper,readFileSynctest/doctor-orphan-ratio.test.ts runOrphanRatioCheck — thin-client surface (D11) 1 readFileSync+test/doctor-schema-column-diff.test.ts doctor schema_version wires the column diff (#4421) 1 doctor-source-helpertest/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton — honors the recorded pid_file (custom --pid-file) 2 doctor-source-helpertest/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton — pid_file fallback (source-grep) 1 doctor-source-helpertest/doctor-volunteer-channels.test.ts checkVolunteerChannels 9 doctor-source-helper,readFileSync@@ -129,6 +131,7 @@ test/exit-classification.test.ts consumer wire-up — helper used by all 3 sitestest/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 2 readFileSynctest/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSynctest/extract-workers.test.ts extract.ts → workers wiring (T7) 10 readFileSync+test/facts-backstop-remedy-verb.test.ts facts backstop thin-client-fallback remedy verb (#4489) 3 readFileSynctest/features.test.ts CLI routing 2 bun-filetest/fence-extraction.test.ts Layer 8 D2 — markdown fence extraction 18 readFileSynctest/filing-rules-resolution.serial.test.ts per-source filing-rules resolution 3 readFileSync@@ -186,6 +189,7 @@ test/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing btest/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSynctest/openclaw-plugin-manifest.test.ts root OpenClaw plugin manifest 2 readFileSynctest/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSync+test/pglite-repair-command.serial.test.ts gbrain pglite-repair — interactive confirm wiring (#4318 residual) 1 readFileSynctest/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 readFileSynctest/phantom-redirect-per-source-lock.test.ts phantom-redirect lock contract 3 readFileSynctest/postgres-engine-singleton-ownership.test.ts postgres-engine / module-singleton ownership (#1471) 7 readFileSync@@ -213,6 +217,7 @@ test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coveratest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/serve-http-github-webhook.test.ts handler wiring (source pin) 1 readFileSynctest/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 readFileSync+test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSynctest/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSynctest/skillify-scaffold.test.ts applyScaffold 3 readFileSynctest/skillify-scaffold.test.ts planScaffold 13 readFileSync@@ -231,6 +236,7 @@ test/skillpack-scrub-legacy.test.ts runScrubLegacy 8 readFileSynctest/sources-webhook.test.ts Webhook sync job extraction contract 1 readFileSynctest/spend-off-switch.test.ts reindex / onboard off-switch dispatch (regression guards) 3 bun-filetest/supervisor.test.ts recovery hook timeout bound (structural) 1 readFileSync+test/sync-failures.test.ts #4543 blocked output names failing files 4 bun-file,doctor-source-helpertest/sync-failures.test.ts Bug 9 — doctor surfaces sync failures 2 doctor-source-helpertest/sync-failures.test.ts Bug 9 — sync.ts CLI flag wiring 6 bun-file,doctor-source-helpertest/sync.test.ts buildSyncManifest 9 bun-file@@ -246,6 +252,7 @@ test/thin-client-routing-audit.test.ts thin-client routing audit — v0.32 ROUTEtest/timing-safe.test.ts extraction contract 1 readFileSynctest/tool-catalog.test.ts freshness guard 2 readFileSynctest/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSync+test/upgrade-skill-publish-prompt-race.test.ts gbrain upgrade — skill-publish prompt wiring (#4318 residual) 3 readFileSynctest/upgrade.serial.test.ts detectInstallMethod heuristic (source analysis) 13 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane A — defaults sweep 8 readFileSynctest/v0_37_fix_wave.serial.test.ts v0.37 Lane B — init paths 3 readFileSyncdiff --git a/src/cli.ts b/src/cli.tsindex f980b66109..535d3c82e2 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -736,6 +736,22 @@ async function main() {// tail to a slow pipe reader when the exit grace lapses — see// writeStdoutFinal.if (output) await writeStdoutFinal(output);+ // #4488: an op that reports failure IN-BAND (`{status: 'error'}` — e.g.+ // put_page over unparseable frontmatter) used to print the envelope and+ // exit 0, so scripts read a never-written page as success. Echo the error+ // to stderr and set the failure verdict. No-op statuses ('skipped',+ // 'unchanged', …) stay exit 0 — a no-op is not a failure.+ if (+ typeof result === 'object' && result !== null && !Array.isArray(result) &&+ (result as { status?: unknown }).status === 'error'+ ) {+ const detail = (result as { error?: unknown }).error;+ console.error(+ `gbrain ${command}: operation reported status 'error'` ++ (typeof detail === 'string' && detail ? ` — ${detail}` : '') + '.',+ );+ setCliExitVerdict(1);+ }maybePrintConceptNudge(op.name, params);} catch (e: unknown) {// v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`@@ -3609,6 +3625,8 @@ BRAIN (capture / ideate / explore — v0.37/v0.38)[--save|--no-save] [--limit N]lsd <question> [--json] Lateral Synaptic Drift: inverted-judge brainstorm[--save|--no-save] [--limit N] rewarding far-from-obvious + axiomatic inversions+ think "<question>" [--anchor <s>] Multi-hop cited synthesis across pages + takes + graph+ [--save] [--source <id>] Full flags: gbrain think --helpSOURCES (multi-repo / multi-brain)sources list Show registered sourcesdiff --git a/src/commands/code-def.ts b/src/commands/code-def.tsindex 191c952dff..a7c8289d5e 100644--- a/src/commands/code-def.ts+++ b/src/commands/code-def.ts@@ -27,47 +27,14 @@ export interface CodeDefResult {snippet: string;}-// v0.41 D2: SQL DDL targets (table/view/index/procedure/schema/database/-// trigger) are first-class definitions in the SQL sense. The chunker's-// normalizeSymbolType maps create_table → 'table' etc, so adding the SQL-// kinds here is what makes `gbrain code-def users` work against SQL.-// Method-level + member definitions. normalizeSymbolType only canonicalizes-// some node types; the rest fall through `type.replace(/_/g, ' ')`, so-// tree-sitter's method_declaration → 'method declaration', struct_specifier →-// 'struct specifier', protocol_declaration → 'protocol declaration', etc.-// Without these, code-def is blind to every method, constructor, field, C-// struct, and Swift protocol — which is most of an OO codebase. The plain-// 'struct' entry above never matched for the same reason (C emits the-// 'struct specifier' fallback form).-export const DEF_TYPES = [- 'function', 'class', 'interface', 'type', 'enum', 'struct', 'trait', 'module', 'contract',- 'table', 'view', 'index', 'procedure', 'schema', 'database', 'trigger',- 'method declaration', 'method definition', 'constructor declaration',- 'field declaration', 'field definition', 'struct specifier', 'protocol declaration',- // Dart: normalizeSymbolType has no rule for these four, so they arrive as- // the node type with underscores replaced. class_definition/enum_declaration/- // type_alias/function_signature already normalize into the list above.- 'mixin declaration', 'extension declaration',- 'getter signature', 'setter signature',- // #3789 residual audit — every remaining definition-shaped fallthrough of- // normalizeSymbolType across TOP_LEVEL_TYPES + NESTED_EMIT_CONFIG. Without- // these, symbols the chunker HAS indexed are invisible to code-def (Java- // records, C#/Kotlin properties, Rust structs/traits, Go type declarations,- // Solidity contracts — the bare 'contract'/'trait'/'struct' entries above- // are never produced by normalizeSymbolType, only these fallthrough forms).- 'property declaration', 'record declaration', // C#/Kotlin, Java- 'struct declaration', 'object declaration', // C#/Swift, Kotlin- 'namespace declaration', 'file scoped namespace declaration', // C#- 'trait declaration', // PHP- 'trait definition', 'object definition', // Scala- 'contract declaration', 'modifier definition', 'event definition', // Solidity- 'namespace definition', 'template declaration', 'declaration', 'preproc def', // C/C++- 'type declaration', 'const declaration', 'var declaration', // Go- 'struct item', 'trait item', 'impl item', 'mod item', // Rust- 'type item', 'const item', 'static item', // Rust- 'lexical declaration', 'variable declaration', // TS/JS top-level const/let/var- 'local declaration', // Lua-];+// #4511: DEF_TYPES moved to src/core/chunkers/def-types.ts — the ONE shared+// list for this lookup allowlist AND the chunker's merge guard (a symbol type+// code-def can resolve must never have its symbol_name erased by+// small-sibling merging). Re-exported here so existing importers keep their+// surface.+import { DEF_TYPES } from '../core/chunkers/def-types.ts';++export { DEF_TYPES };export async function findCodeDef(engine: BrainEngine,diff --git a/src/commands/doctor-asset-paths.ts b/src/commands/doctor-asset-paths.tsindex 168a207f27..80f44b037a 100644--- a/src/commands/doctor-asset-paths.ts+++ b/src/commands/doctor-asset-paths.ts@@ -16,14 +16,20 @@* this platform — report it as foreign so the caller SKIPS the stat* instead of inventing a path that will never exist.*- * Kept in its own module (not doctor.ts) so the pure tests don't pull the- * 7k-line doctor dep graph, and so open PRs rewriting the image_assets block- * (e.g. a `resolveImageAssetPath` helper) can adopt it with a one-line call.+ * The drive-shape detection, wsl.conf parse, and mechanical translation live+ * in `src/core/wsl-paths.ts` (shared with the hook transcript confinement,+ * #4522); this module keeps the doctor-facing policy and re-exports the+ * helpers its tests and callers always imported.*/-import { readFileSync } from 'node:fs';import { join, posix, win32 } from 'node:path';+import {+ WINDOWS_DRIVE_PATH_RE,+ detectWslMountRoot,+ parseWslAutomountRoot,+ translateWindowsPath,+} from '../core/wsl-paths.ts';-const WINDOWS_DRIVE_RE = /^([A-Za-z]):[\\/](.*)$/;+export { detectWslMountRoot, parseWslAutomountRoot };export interface AssetPathResolution {/** Absolute path to stat, or null when the path is unresolvable here. */@@ -44,14 +50,10 @@ export function resolveAssetPath(opts: { platform?: NodeJS.Platform; wslMountRoot?: string | null } = {},): AssetPathResolution {const platform = opts.platform ?? process.platform;- if (platform !== 'win32') {- const m = WINDOWS_DRIVE_RE.exec(storagePath);- if (m) {- const root = opts.wslMountRoot !== undefined ? opts.wslMountRoot : detectWslMountRoot();- if (root === null) return { abs: null, foreign: true };- const abs = `${root.replace(/\/+$/, '')}/${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}`;- return { abs, foreign: false };- }+ if (platform !== 'win32' && WINDOWS_DRIVE_PATH_RE.test(storagePath)) {+ const root = opts.wslMountRoot !== undefined ? opts.wslMountRoot : detectWslMountRoot();+ if (root === null) return { abs: null, foreign: true };+ return { abs: translateWindowsPath(storagePath, root), foreign: false };}// Platform-appropriate absoluteness (not the host's) so injected-platform// tests behave identically everywhere; in production platform === host.@@ -74,48 +76,3 @@ export function resolveImageAssetPath(): AssetPathResolution {return resolveAssetPath(storagePath, sourceLocalPath ?? fallbackRepoRoot);}--/**- * Extract the `[automount] root` value from /etc/wsl.conf content.- * Defaults to `/mnt` (WSL's own default) when absent/unparseable.- */-export function parseWslAutomountRoot(conf: string): string {- let inAutomount = false;- for (const raw of conf.split(/\r?\n/)) {- const line = raw.replace(/[#;].*$/, '').trim();- if (line.startsWith('[')) {- inAutomount = /^\[automount\]$/i.test(line);- continue;- }- if (!inAutomount) continue;- const m = /^root\s*=\s*"?([^"]+?)"?\s*$/.exec(line);- if (m) return m[1];- }- return '/mnt';-}--let cachedWslMountRoot: string | null | undefined;--/**- * Detect the WSL Windows-drive automount root. Returns null when not running- * under WSL (including macOS and plain Linux). Memoized per process.- */-export function detectWslMountRoot(): string | null {- if (cachedWslMountRoot === undefined) cachedWslMountRoot = computeWslMountRoot();- return cachedWslMountRoot;-}--function computeWslMountRoot(): string | null {- if (process.platform !== 'linux') return null;- try {- // The standard WSL tell: kernel version string names Microsoft.- if (!/microsoft/i.test(readFileSync('/proc/version', 'utf8'))) return null;- } catch {- return null;- }- try {- return parseWslAutomountRoot(readFileSync('/etc/wsl.conf', 'utf8'));- } catch {- return '/mnt'; // WSL default when wsl.conf is absent.- }-}diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 06efdb287d..f1f077326b 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../core/engine.ts';+import { EMBED_SKIP_FILTER_FRAGMENT } from '../core/embed-skip.ts';// Leaf module (no flag surface of its own) — see that file for why this// isn't imported from extract-conversation-facts.ts directly (#4135).import { ALLOWED_TYPES } from '../core/facts/conversation-types.ts';@@ -382,6 +383,36 @@ export function computeDoctorReport(checks: Check[]): DoctorReport {* still get the full check set.*/+/**+ * #4517: is the latest upgrade-errors.jsonl record superseded? True when the+ * running binary version is at/past the version the failed upgrade was moving+ * to AND the schema ledger is current (no pending migrations) — i.e. a later+ * (or retried) upgrade demonstrably finished the job. Pure + exported for+ * tests. Compares ALL dot-segments (the canonical `compareVersions` stops at+ * 3, which would treat 0.31.4.1 == 0.31.4.0); a malformed version fails+ * closed (keeps warning).+ */+export function upgradeErrorResolved(+ failedToVersion: string,+ binaryVersion: string,+ schemaCurrent: boolean,+): boolean {+ if (!schemaCurrent) return false;+ if (typeof failedToVersion !== 'string' || typeof binaryVersion !== 'string') return false;+ const a = binaryVersion.replace(/^v/, '').split('.');+ const b = failedToVersion.replace(/^v/, '').split('.');+ if (a.length === 0 || b.length === 0) return false;+ const len = Math.max(a.length, b.length);+ for (let i = 0; i < len; i++) {+ const da = parseInt(a[i] ?? '0', 10);+ const db = parseInt(b[i] ?? '0', 10);+ if (!Number.isFinite(da) || !Number.isFinite(db) || Number.isNaN(da) || Number.isNaN(db)) return false;+ if (da > db) return true;+ if (da < db) return false;+ }+ return true; // equal → the failed target version is now running+}+/*** v0.42 self_upgrade_health. Surfaces the self-upgrade mode, whether an update* is pending (from the cache), and any recent failed auto-upgrade attempts.@@ -443,6 +474,64 @@ export function checkSelfUpgradeHealth(): Check {}}+/**+ * Upgrade-error trail (v0.13+). `gbrain upgrade` silently swallows+ * best-effort failures in `gbrain post-upgrade`; the failure record is+ * appended to `~/.gbrain/upgrade-errors.jsonl` so we can surface it here+ * with a paste-ready recovery hint. Without this, users end up with+ * half-upgraded brains and no signal.+ *+ * #4517: a failure record on its own doesn't mean the brain is STILL+ * broken — the recovery hint (e.g. `apply-migrations --yes`) may have+ * already fixed it. Suppression requires BOTH proofs: the installed+ * binary's own version is at/past the record's `to_version` (the failed+ * upgrade demonstrably completed filesystem-side) AND the schema ledger is+ * current (`config.version >= LATEST_VERSION` — the DB half of the upgrade+ * also finished). A binary alone can lie: `self-upgrade` swaps the binary+ * before `post-upgrade` runs migrations, which is exactly the failure this+ * trail records. When the schema can't be verified (no engine, unreadable+ * version), the warn stays — fail-closed. A superseded record downgrades to+ * an explicit status:'ok' line (rather than silence) so the operator sees+ * the past failure was resolved, not swallowed.+ * `upgradeErrorResolved` above is the pure decision fn.+ */+export async function checkUpgradeErrors(+ engine: Pick<BrainEngine, 'getConfig'> | null,+): Promise<Check | null> {+ try {+ const errPath = gbrainPath('upgrade-errors.jsonl');+ if (!existsSync(errPath)) return null;+ const lines = readFileSync(errPath, 'utf-8').split('\n').filter(l => l.trim());+ if (lines.length === 0) return null;+ const latest = JSON.parse(lines[lines.length - 1]) as {+ ts: string; phase: string; from_version: string; to_version: string; hint: string;+ };+ const date = latest.ts.slice(0, 10);+ let schemaCurrent = false;+ if (engine) {+ try {+ const v = parseInt((await engine.getConfig('version')) || '0', 10);+ schemaCurrent = v >= LATEST_VERSION;+ } catch { /* unverifiable → keep warning */ }+ }+ if (upgradeErrorResolved(latest.to_version, GBRAIN_BINARY_VERSION, schemaCurrent)) {+ return {+ name: 'upgrade_errors',+ status: 'ok',+ message: `Past post-upgrade failure on ${date} (${latest.from_version} → ${latest.to_version}) superseded: binary now ${GBRAIN_BINARY_VERSION}, schema current.`,+ };+ }+ return {+ name: 'upgrade_errors',+ status: 'warn',+ message: `Post-upgrade failure on ${date} (${latest.from_version} → ${latest.to_version}, phase: ${latest.phase}). Recovery: ${latest.hint}`,+ };+ } catch {+ // Read/parse failure is itself best-effort; skip silently.+ return null;+ }+}+/*** Re-exported from `src/core/env-number.ts`, which now owns the implementation* AND the warn-once memo. `source-health.ts` needs the hours resolver for the@@ -752,31 +841,10 @@ export async function buildChecks(// handles the "schema v7+ but no prefs" case.}- // 3b. Upgrade-error trail (v0.13+). `gbrain upgrade` silently swallows- // best-effort failures in `gbrain post-upgrade`; the failure record is- // appended to ~/.gbrain/upgrade-errors.jsonl so we can surface it here- // with a paste-ready recovery hint. Without this, users end up with- // half-upgraded brains and no signal.- try {- const home = process.env.HOME || '';- const errPath = join(home, '.gbrain', 'upgrade-errors.jsonl');- if (existsSync(errPath)) {- const lines = readFileSync(errPath, 'utf-8').split('\n').filter(l => l.trim());- if (lines.length > 0) {- const latest = JSON.parse(lines[lines.length - 1]) as {- ts: string; phase: string; from_version: string; to_version: string; hint: string;- };- const date = latest.ts.slice(0, 10);- checks.push({- name: 'upgrade_errors',- status: 'warn',- message: `Post-upgrade failure on ${date} (${latest.from_version} → ${latest.to_version}, phase: ${latest.phase}). Recovery: ${latest.hint}`,- });- }- }- } catch {- // Read/parse failure is itself best-effort; skip silently.- }+ // 3b. Upgrade-error trail (v0.13+). See checkUpgradeErrors for the #4517+ // staleness re-verification semantics (binary version + schema ledger).+ const upgradeErrorsCheck = await checkUpgradeErrors(engine);+ if (upgradeErrorsCheck) checks.push(upgradeErrorsCheck);// 3b-ter. Self-upgrade health (#3747). Pure local-file check (config +// upgrade cache + audit trail; no DB) that was only ever pushed by the@@ -1923,8 +1991,54 @@ export async function buildChecks(try {const version = await engine.getConfig('version');schemaVersion = parseInt(version || '0', 10);- if (schemaVersion >= LATEST_VERSION) {- checks.push({ name: 'schema_version', status: 'ok', message: `Version ${schemaVersion} (latest: ${LATEST_VERSION})` });+ if (schemaVersion > LATEST_VERSION) {+ // Forward skew: another node migrated the shared DB past what this+ // client knows (multi-node brain, hub + spokes on one Postgres). This+ // client will read/write tables, columns, and indexes it doesn't know+ // about — more dangerous than backward skew, which at least blocks on+ // the next `apply-migrations`. See #2036. Takes precedence over the+ // column diff below: an ahead DB is a superset of this client's+ // expected columns, and "upgrade this client" is the real fix.+ checks.push({+ name: 'schema_version',+ status: 'warn',+ message: `Version ${schemaVersion} is AHEAD of this client's latest known version (${LATEST_VERSION}). ` ++ `Another node migrated this DB past what this client knows — upgrade this client before writing.`,+ });+ } else if (schemaVersion >= LATEST_VERSION) {+ // #4421: the ledger counter alone can lie — a PgBouncer transaction-+ // mode pooler can swallow an ALTER TABLE while the migration runner+ // still advances config.version, leaving the ledger "current" over a+ // physically narrower table. Add a READ-ONLY column diff via+ // detectMissingColumns (#4425 — the detection half of+ // schema-verify.ts's verifySchema, no self-heal): when live columns+ // are missing, downgrade to warn naming them with the migrate-only+ // re-run hint. Diff failure is best-effort — the ledger ok stands.+ // Dynamic import is deliberate: the positional source guard in+ // test/doctor-schema-column-diff.test.ts pins that the diff consult+ // lives INSIDE this ledger-current branch.+ let columnDiffWarned = false;+ try {+ const { detectMissingColumns } = await import('../core/schema-verify.ts');+ const diff = await detectMissingColumns(engine);+ if (diff.missing.length > 0) {+ const sample = diff.missing.slice(0, 5).map(m => `${m.table}.${m.column}`).join(', ');+ const more = diff.missing.length > 5 ? ` (+${diff.missing.length - 5} more)` : '';+ checks.push({+ name: 'schema_version',+ status: 'warn',+ message:+ `Version ${schemaVersion} (latest: ${LATEST_VERSION}) but ${diff.missing.length} expected column(s) ` ++ `are missing from the live schema: ${sample}${more}. The migration ledger advanced past a swallowed ` ++ `ALTER TABLE (PgBouncer transaction-mode is the usual cause). Fix: gbrain init --migrate-only ` ++ `(runs the schema self-heal); if it persists, connect directly to Postgres (not the pooler) first.`,+ });+ columnDiffWarned = true;+ }+ } catch { /* read-only diff is best-effort; ledger ok stands */ }+ if (!columnDiffWarned) {+ checks.push({ name: 'schema_version', status: 'ok', message: `Version ${schemaVersion} (latest: ${LATEST_VERSION})` });+ }} else if (schemaVersion === 0) {checks.push({name: 'schema_version',@@ -1943,6 +2057,10 @@ export async function buildChecks(checks.push({ name: 'schema_version', status: 'warn', message: 'Could not check schema version' });}+ // Note: the #4421/#4425 live-column drift diff (detectMissingColumns) is+ // wired INSIDE the schema_version ledger-current branch above — one+ // column-drift wiring, not a separate check.+// Note: we intentionally DO NOT fail on "schema v7+ but no preferences.json".// That's a valid fresh-install state after `gbrain init` — the migration// orchestrator writes preferences, but `init` alone doesn't run it. The@@ -2840,6 +2958,16 @@ export async function buildChecks(// counting pages whose body (compiled_truth + timeline, UTF-8 bytes// via octet_length per Codex r2 #13) exceeds the block threshold.// Status warn when 1+ rows; never fail (oversize is now a soft state).+ // Excludes frontmatter.embed_skip pages via the canonical+ // EMBED_SKIP_FILTER_FRAGMENT (src/core/embed-skip.ts) — key existence,+ // not a boolean value comparison, matching every other embed-skip+ // consumer in the codebase. The warn message itself says "existing+ // oversized pages can be ... accepted as non-embeddable" (i.e.+ // embed_skip set), so a page that already took that accepted+ // remediation must not still count against this check — otherwise the+ // warning can never clear for a page an operator already resolved the+ // documented way (found via dogfooding: a page with embed_skip set+ // kept re-appearing in this check's output every run).// - scraper_junk_pages: capped 1000-most-recent default + --content-audit// opt-in for full scan (D10 mirrors --index-audit precedent). Applies// the assessor per-page on title + 2KB head-slice + frontmatter.@@ -2865,6 +2993,7 @@ export async function buildChecks(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) AS bytesFROM pages pWHERE p.deleted_at IS NULL+ AND ${EMBED_SKIP_FILTER_FRAGMENT}AND (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, ''))) > $1ORDER BY bytes DESCLIMIT 100`,@@ -2874,7 +3003,7 @@ export async function buildChecks(checks.push({name: 'oversized_pages',status: 'ok',- message: `No pages exceed ${bytesBlock} bytes`,+ message: `No pages exceed ${bytesBlock} bytes (excluding embed_skip pages, which already took the accepted non-embeddable remediation)`,});} else {const oversizeRows = rows as unknown as Array<{ slug: string; source_id: string; bytes: number }>;diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 96ddbdaf11..0b8e75d4b3 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -649,11 +649,16 @@ export async function computeExtractHealthCheck(eval_fail_count: number;halt_count: number;round_completed_count: number;+ expected_limit_count: number;rollup_write_failures: number;last_updated_at: Date | string | null;};- const rows = await engine.executeRaw<RollupRow>(+ // #4482: expected_limit_count (migration v141) counts runs that stopped+ // at an EXPECTED budget/deadline cap — successful partial progress, not+ // failures. Pre-v141 brains lack the column; retry without it (caps read+ // as 0, i.e. "unknown" — old conflated halt rows keep today's semantics).+ const rollupQuery = (withExpected: boolean) =>`SELECTkind,SUM(cost_usd) AS cost_7d_usd,@@ -661,14 +666,21 @@ export async function computeExtractHealthCheck(SUM(eval_fail_count) AS eval_fail_count,SUM(halt_count) AS halt_count,SUM(round_completed_count) AS round_completed_count,+ ${withExpected ? 'SUM(expected_limit_count)' : '0'} AS expected_limit_count,SUM(rollup_write_failures) AS rollup_write_failures,MAX(updated_at) AS last_updated_atFROM extract_rollup_7dWHERE day >= CURRENT_DATE - 7GROUP BY kind- ORDER BY kind`,- [],- );+ ORDER BY kind`;+ let rows: RollupRow[];+ try {+ rows = await engine.executeRaw<RollupRow>(rollupQuery(true), []);+ } catch (err) {+ const msg = (err as Error).message || String(err);+ if (!/expected_limit_count/i.test(msg)) throw err;+ rows = await engine.executeRaw<RollupRow>(rollupQuery(false), []);+ }if (rows.length === 0) {return {@@ -689,6 +701,7 @@ export async function computeExtractHealthCheck(eval_fail_count: number;halt_count: number;round_completed_count: number;+ expected_limit_count: number;halt_rate: number;last_updated_at: string | null;};@@ -696,7 +709,12 @@ export async function computeExtractHealthCheck(const kinds: KindAggregate[] = rows.map(r => {const halts = Number(r.halt_count) || 0;const completed = Number(r.round_completed_count) || 0;- const total = halts + completed;+ const expectedLimits = Number(r.expected_limit_count) || 0;+ // #4482: cap stops join the DENOMINATOR (they are runs, and successful+ // ones) but not the numerator — the failure rate measures failures,+ // not self-imposed capacity limits. A backlog-bigger-than-budget brain+ // whose every run banks progress and stops at the cap reads 0%.+ const total = halts + completed + expectedLimits;return {kind: r.kind,cost_7d_usd: Number(r.cost_7d_usd) || 0,@@ -704,6 +722,7 @@ export async function computeExtractHealthCheck(eval_fail_count: Number(r.eval_fail_count) || 0,halt_count: halts,round_completed_count: completed,+ expected_limit_count: expectedLimits,halt_rate: total > 0 ? halts / total : 0,last_updated_at: r.last_updated_at? new Date(r.last_updated_at).toISOString()@@ -755,10 +774,17 @@ export async function computeExtractHealthCheck(};}+ // #4482: cap-hits stay observable as a capacity signal (backlog bigger+ // than the per-run budget — will drain over future runs), without being+ // conflated with the failure-rate warning above.+ const totalExpectedLimits = kinds.reduce((acc, k) => acc + k.expected_limit_count, 0);+ const capNote = totalExpectedLimits > 0+ ? `; ${totalExpectedLimits} run(s) stopped at expected budget/deadline caps (capacity, not failures)`+ : '';return {name,status: 'ok',- message: `${kinds.length} kind(s) tracked, all halt rates below 10%`,+ message: `${kinds.length} kind(s) tracked, all halt rates below 10%${capNote}`,details: {schema_version: 1,kinds,diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.tsindex fc41abdb53..1cd53d6cbd 100644--- a/src/commands/doctor/checks/queue-jobs.ts+++ b/src/commands/doctor/checks/queue-jobs.ts@@ -308,7 +308,10 @@ export async function computeQueueHealthCheck(* Exported so `test/doctor.test.ts` drives it directly. Reads* GBRAIN_WEDGED_QUEUE_WARN_MINUTES (default 15).*/-export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Check> {+export async function computeWedgedQueueCheck(+ engine: BrainEngine,+ opts: { readWorkers?: () => Array<{ queue: string }> } = {},+): Promise<Check> {if (engine.kind !== 'postgres') {return { name: 'wedged_queue', status: 'ok', message: 'PGLite — no queue to check' };}@@ -329,8 +332,7 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<ChecWHERE queue NOT LIKE 'dream-inline-%'GROUP BY queue`,);- const wedged: string[] = [];- const wedgedQueueNames: string[] = [];+ const wedged: { queue: string; label: string }[] = [];for (const r of rows) {const activeHealthy = Number(r.active_healthy ?? 0);const waiting = Number(r.waiting ?? 0);@@ -338,36 +340,99 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec// Conservative: only flag stale-after-progress (non-null mins past// threshold). The null-completions case is the supervisor's job.if (activeHealthy === 0 && waiting > 0 && mins !== null && mins > thresholdMin) {- wedged.push(`'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`);- wedgedQueueNames.push(r.queue);+ wedged.push({+ queue: r.queue,+ label: `'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`,+ });}}if (wedged.length === 0) {return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };}- // Queue-aware restart hint: the bare stop/start pair bounces the DEFAULT- // worker — for a non-default wedged queue that advice restarts the wrong- // process. Name the queue in the start command. Queue names are- // producer-controlled and this hint gets copy-pasted (by operators AND- // remediation agents), so embedded quotes are escaped for the shell.- const shellQuote = (q: string) => `'${q.replace(/'/g, String.raw`'\''`)}'`;- const nonDefault = wedgedQueueNames.filter(q => q !== 'default');- const hints: string[] = [];- if (nonDefault.length < wedgedQueueNames.length || nonDefault.length === 0) {- hints.push('`gbrain jobs supervisor stop && gbrain jobs supervisor start`');+ // #3063: "worker alive but not claiming work" would be a false claim+ // for a queue no worker process was ever subscribed to. Split the+ // wedged set by whether a registered live worker actually exists for+ // that queue (getLiveWorkers() self-cleans dead entries), so the+ // advisory repair matches the real fault instead of misdirecting the+ // operator toward restarting a worker that was never there — a queue+ // with no worker needs `start`, not `stop && start`.+ let liveWorkers: Array<{ queue: string }> = [];+ let registryReadable = true;+ try {+ // Lazy import mirrors computeQueueHealthCheck's own registry access+ // above — the registry module stays off this file's eager import+ // graph and only loads once a wedge actually needs the signal.+ const getLiveWorkers = opts.readWorkers+ ?? (await import('../../../core/minions/worker-registry.ts')).readWorkers;+ liveWorkers = getLiveWorkers();+ } catch {+ // A registry read error must not turn this check green (the queue is+ // demonstrably wedged) — but it also must not fabricate a liveness+ // verdict either way. Fall through to the liveness-unknown wording.+ registryReadable = false;}- for (const q of nonDefault) {- hints.push(`\`gbrain jobs supervisor stop && gbrain jobs supervisor start --queue ${shellQuote(q)}\``);+ if (!registryReadable) {+ return {+ name: 'wedged_queue',+ status: 'fail',+ message:+ `Wedged queue(s) — worker registry unreadable, worker liveness unknown: ` ++ `${wedged.map((w) => w.label).join('; ')}. ` ++ `If a worker is running for the queue, restart it: ` ++ '`gbrain jobs supervisor stop && gbrain jobs supervisor start [--queue <name>]`; ' ++ 'if none is, start one: `gbrain jobs supervisor start --queue <name> --detach`.',+ details: {+ wedged_queues: wedged.length,+ worker_registry_unreadable: true,+ threshold_minutes: thresholdMin,+ },+ };+ }+ const liveQueues = new Set(liveWorkers.map((w) => w.queue));+ const stuck = wedged.filter((w) => liveQueues.has(w.queue));+ const noWorker = wedged.filter((w) => !liveQueues.has(w.queue));++ const messageParts: string[] = [];+ if (stuck.length > 0) {+ // Queue-aware restart hint (upstream v0.46.26.0): the bare stop/start+ // pair bounces the DEFAULT worker — for a non-default wedged queue+ // that advice restarts the wrong process. Name the queue in the+ // start command. Queue names are producer-controlled and this hint+ // gets copy-pasted (by operators AND remediation agents), so+ // embedded quotes are escaped for the shell.+ const shellQuote = (q: string) => `'${q.replace(/'/g, String.raw`'\''`)}'`;+ const stuckQueueNames = stuck.map((w) => w.queue);+ const nonDefault = stuckQueueNames.filter((q) => q !== 'default');+ const hints: string[] = [];+ if (nonDefault.length < stuckQueueNames.length || nonDefault.length === 0) {+ hints.push('`gbrain jobs supervisor stop && gbrain jobs supervisor start`');+ }+ for (const q of nonDefault) {+ hints.push(`\`gbrain jobs supervisor stop && gbrain jobs supervisor start --queue ${shellQuote(q)}\``);+ }+ messageParts.push(+ `Wedged queue(s) — worker alive but not claiming work: ${stuck.map((w) => w.label).join('; ')}. ` ++ `Restart the worker so it rebuilds a fresh DB pool: ${hints.join(', ')}, ` ++ `then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,+ );+ }+ if (noWorker.length > 0) {+ messageParts.push(+ `No worker subscribed to queue(s): ${noWorker.map((w) => w.label).join('; ')}. ` ++ `Start one: \`gbrain jobs supervisor start --queue <name> --detach\` ` ++ `or \`gbrain jobs work --queue <name>\`.`,+ );}- const restartHint = hints.join(', ');return {name: 'wedged_queue',status: 'fail',- message:- `Wedged queue(s) — worker alive but not claiming work: ${wedged.join('; ')}. ` +- `Restart the worker so it rebuilds a fresh DB pool: ${restartHint}, ` +- `then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,- details: { wedged_queues: wedged.length, threshold_minutes: thresholdMin },+ message: messageParts.join(' '),+ details: {+ wedged_queues: wedged.length,+ stuck_worker_queues: stuck.length,+ no_worker_queues: noWorker.length,+ threshold_minutes: thresholdMin,+ },};} catch (e) {// Pre-migration brains / transient errors: advisory check stays ok.diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.tsindex 17fd872f7e..9049d6eb52 100644--- a/src/commands/doctor/checks/routing-federation.ts+++ b/src/commands/doctor/checks/routing-federation.ts@@ -7,6 +7,7 @@import { existsSync, readFileSync } from 'fs';import type { BrainEngine } from '../../../core/engine.ts';import { gbrainPath } from '../../../core/config.ts';+import { embedBackfillWorkerSurface } from '../../../core/minions/embed-backfill-admission.ts';import { isUndefinedTableError, isUndefinedColumnError } from '../../../core/utils.ts';import type { Check } from '../../doctor.ts';@@ -98,13 +99,16 @@ export async function checkFederationHealth(engine: BrainEngine): Promise<Check>const warns: string[] = [];const fails: string[] = [];for (const m of metrics) {+ const embedRemedy = embedBackfillWorkerSurface(engine).status === 'no_worker_surface'+ ? `gbrain embed --stale --source ${m.source_id}`+ : `gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'`;// Fail thresholds first (most severe)if (m.lag_seconds !== null && m.lag_seconds > 24 * 3600) {fails.push(`${m.source_id}: stale ${Math.floor(m.lag_seconds / 3600)}h — run \`gbrain sync trigger --source ${m.source_id}\``);continue;}if (m.embed_coverage_pct < 50 && m.total_chunks > 1000) {- fails.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage (${m.total_chunks.toLocaleString()} chunks) — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);+ fails.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage (${m.total_chunks.toLocaleString()} chunks) — run \`${embedRemedy}\``);continue;}// Warns@@ -112,7 +116,7 @@ export async function checkFederationHealth(engine: BrainEngine): Promise<Check>warns.push(`${m.source_id}: federated source ${Math.floor(m.lag_seconds / 3600)}h+ stale — run \`gbrain sync trigger --source ${m.source_id}\``);}if (m.embed_coverage_pct < 95 && m.total_chunks > 100) {- warns.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);+ warns.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage — run \`${embedRemedy}\``);}if (m.failed_jobs_24h >= 3) {warns.push(`${m.source_id}: ${m.failed_jobs_24h} failures in 24h — check \`gbrain jobs list --status failed\``);@@ -495,4 +499,3 @@ export function checkCyclePhaseScope(): Check {return { name: 'cycle_phase_scope', status: 'warn', message: `Check failed: ${msg}` };}}-diff --git a/src/commands/doctor/checks/verbs-reflex.ts b/src/commands/doctor/checks/verbs-reflex.tsindex 1d73290e18..308f038ae1 100644--- a/src/commands/doctor/checks/verbs-reflex.ts+++ b/src/commands/doctor/checks/verbs-reflex.ts@@ -111,11 +111,14 @@ export function buildRetrievalReflexCheck(skillsDir: string | null): Check {viablePathVisible = false;}+ // #4474: when the socket is absent, say the operational truth plainly —+ // ONLY a running `gbrain serve` (stdio or --http) binds it, and until+ // one does every lifecycle hook degrades to no_serve on this brain.const runtimeMsg = firedRecently? `active (last fired ${lastFired})`: viablePathVisible? 'enabled; not observed firing yet'- : 'enabled but no observed activity and no visible resolve path (host capability may still supply it; policy skill carries otherwise)';+ : 'enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise)';const status: Check['status'] = firedRecently || viablePathVisible ? 'ok' : 'warn';const skillHint = skillInstalleddiff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.tsindex c3724403b5..ad76d42f96 100644--- a/src/commands/doctor/schema-pack-checks.ts+++ b/src/commands/doctor/schema-pack-checks.ts@@ -137,13 +137,21 @@ export async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<C* brain deletes the correctly-routed row).*/export function multiSourceDriftAdvice(count: number, sampleStr: string): string {+ // #4490: cause (3) + the --include-gitignored pointer must precede the+ // delete step — an operator whose file is simply not git-tracked would+ // otherwise re-sync (which imports nothing for that file) and then delete+ // a row nothing will recreate.return (`${count} page slug(s) appear at 'default' but NOT at the intended source ` +- `(e.g., ${sampleStr}). Two possible causes: (1) pre-v0.30.3 putPage misroutes; ` +- `(2) the intended source never completed initial sync and the default page is unrelated. ` ++ `(e.g., ${sampleStr}). Three possible causes: (1) pre-v0.30.3 putPage misroutes; ` ++ `(2) the intended source never completed initial sync and the default page is unrelated; ` ++ `(3) the file behind the slug is not git-tracked in the source repo — the sync walker ` ++ `reads through git objects, so a re-sync imports nothing for it. ` +`Verify with 'gbrain sources status', then re-sync with ` +- `'gbrain sync --source <id> --full' (reconciles drift without deleting data). ` +- `If a misrouted default-source row remains after re-sync, remove it with ` ++ `'gbrain sync --source <id> --full' (reconciles drift without deleting data); ` ++ `for cause (3), commit the file or use 'gbrain sync --source <id> --include-gitignored' ` ++ `(full filesystem walk that also picks up ignored/untracked syncable files). ` ++ `Only if a misrouted default-source row remains after that, remove it with ` +`'GBRAIN_SOURCE=default gbrain delete <slug>' — delete targets the active source, ` +`so pin it to 'default' explicitly.`);diff --git a/src/commands/dream.ts b/src/commands/dream.tsindex 3e3f51db3d..7a29770558 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -41,7 +41,13 @@ interface DreamArgs {json: boolean;dryRun: boolean;pull: boolean;- phase: CyclePhase | null;+ /**+ * #4493: every explicitly-named (or --input/--drain-implied) phase, order+ * preserved, deduped. Empty = full/default cycle. Previously a single+ * `phase` scalar read from the FIRST --phase flag, so repeats were+ * silently dropped.+ */+ phases: CyclePhase[];dir: string | null;help: boolean;/** v0.21: ad-hoc transcript file path; implies --phase synthesize. */@@ -118,22 +124,31 @@ function collectFlagValues(args: string[], flag: string): string[] | null {}function parseArgs(args: string[]): DreamArgs {- const phaseIdx = args.indexOf('--phase');+ // #4493: collect EVERY --phase occurrence. `args.indexOf('--phase')` used+ // to read only the FIRST flag, so `--phase a --phase b --phase c` silently+ // ran phase a alone and exited 0 with a report covering one phase. Each+ // value is validated, order is preserved, repeats of the same value+ // collapse (same contract as the repeated --source handling below).+ const phaseValues = collectFlagValues(args, '--phase');+ if (phaseValues === null) {+ console.error('--phase <name>: missing value. Usage: gbrain dream --phase <name>');+ process.exit(2);+ }// issue #2860 (Codex P3): captured BEFORE --input/--drain get a chance to- // implicitly default `phase` below, so --once's validation can require+ // implicitly default `phases` below, so --once's validation can require// the user actually TYPED --phase, not merely that some phase ended up// resolved. Without this, `--input <f> --once` and `--drain --once`// slip past the "explicit --phase required" contract (the derived- // `phase` value is already non-null by the time that check runs) and+ // phase value is already non-null by the time that check runs) and// --once becomes silently ineffective for both.- const phaseWasExplicit = phaseIdx !== -1;- const rawPhase = phaseIdx !== -1 ? args[phaseIdx + 1] : null;- let phase = rawPhase && (ALL_PHASES as string[]).includes(rawPhase)- ? (rawPhase as CyclePhase)- : null;- if (rawPhase && !phase) {- console.error(`Unknown phase "${rawPhase}". Valid: ${ALL_PHASES.join(', ')}`);- process.exit(1);+ const phaseWasExplicit = phaseValues.length > 0;+ let phases: CyclePhase[] = [];+ for (const rawPhase of phaseValues) {+ if (!(ALL_PHASES as string[]).includes(rawPhase)) {+ console.error(`Unknown phase "${rawPhase}". Valid: ${ALL_PHASES.join(', ')}`);+ process.exit(1);+ }+ if (!phases.includes(rawPhase as CyclePhase)) phases.push(rawPhase as CyclePhase);}const dirIdx = args.indexOf('--dir');@@ -175,7 +190,7 @@ function parseArgs(args: string[]): DreamArgs {}// --input implies --phase synthesize.- if (inputFile && !phase) phase = 'synthesize';+ if (inputFile && phases.length === 0) phases = ['synthesize'];// v0.41.13: --source <id> (and the --source-id alias) drives per-source// cycle scoping. Resolution rules:@@ -229,9 +244,9 @@ function parseArgs(args: string[]): DreamArgs {windowSeconds = parseInt(raw, 10);}if (drain) {- if (!phase) phase = 'extract_atoms';- else if (phase !== 'extract_atoms') {- console.error(`--drain currently supports only --phase extract_atoms (got "${phase}")`);+ if (phases.length === 0) phases = ['extract_atoms'];+ else if (phases.length > 1 || phases[0] !== 'extract_atoms') {+ console.error(`--drain currently supports only --phase extract_atoms (got "${phases.join(', ')}")`);process.exit(2);}}@@ -264,12 +279,22 @@ function parseArgs(args: string[]): DreamArgs {);process.exit(2);}+ // #4493 corollary: --once bypasses ONE phase's enabled gate; with several+ // named phases there is no single target, and force-enabling them all at+ // once is the surprise-spend risk #2860 exists to prevent.+ if (once && phases.length > 1 && !wantsHelp) {+ console.error(+ `--once supports a single --phase target; got [${phases.join(', ')}]. ` ++ 'Run each phase in its own --phase <name> --once invocation.',+ );+ process.exit(2);+ }return {json: args.includes('--json'),dryRun: args.includes('--dry-run'),pull: args.includes('--pull'),- phase,+ phases,dir,help: args.includes('--help') || args.includes('-h'),inputFile,@@ -369,7 +394,9 @@ Options:but skips the synthesis subagents."--dry-run" does NOT mean "zero LLM calls."--json Emit the CycleReport as JSON (agent-readable)- --phase <name> Run a single phase: ${ALL_PHASES.join(' | ')}+ --phase <name> Run only the named phase(s). Repeatable — every named+ phase runs, in canonical cycle order (#4493).+ Valid: ${ALL_PHASES.join(' | ')}--once With --phase <name>: run that phase once even if itsown dream.<phase>.enabled / cycle.<phase>.enabledconfig gate is false. Never reads or writes config —@@ -576,7 +603,7 @@ async function runDrain(if (opts.dryRun) {const remaining = await countExtractAtomsBacklog(engine, extractionSourceId);if (opts.json) {- console.log(JSON.stringify({ phase: 'extract_atoms', status: 'ok', dry_run: true, extracted: 0, skipped: 0, remaining, batches: 0, stopped: 'window' }, null, 2));+ console.log(JSON.stringify({ phase: 'extract_atoms', status: 'ok', dry_run: true, extracted: 0, skipped: 0, remaining, batches: 0, stopped: 'window', failure_count: 0, last_error: null }, null, 2));} else {console.log(`[drain] dry-run: ${remaining ?? '?'} page(s) eligible for atom extraction (no work done)`);}@@ -611,6 +638,16 @@ async function runDrain(throw e;}+ // #4539: surface WHY the drain underperformed. Pre-fix the phase's+ // failures[] was collapsed to bare counts inside the drain adapter, so a+ // run that failed on every item printed only `stopped: no_progress` and the+ // operator had to re-run the phase by hand to see the provider/parse error.+ // Stderr (not stdout): progress/diagnostics never pollute the data stream.+ if (result.failure_count > 0) {+ process.stderr.write(+ `[drain] ${result.failure_count} item failure(s)${result.last_error ? `; last error: ${result.last_error}` : ''}\n`,+ );+ }if (opts.json) {console.log(JSON.stringify(result, null, 2));} else {@@ -742,7 +779,9 @@ export async function runDream(engine: BrainEngine | null, args: string[]): Promreturn runDrain(engine, opts, resolvedSourceId, brainDir);}- const phases: CyclePhase[] | undefined = opts.phase ? [opts.phase] : undefined;+ // #4493: pass EVERY named phase through (runCycle already accepts the+ // array); empty means the full/default cycle.+ const phases: CyclePhase[] | undefined = opts.phases.length > 0 ? opts.phases : undefined;const report = await runCycle(engine, {brainDir,@@ -755,9 +794,9 @@ export async function runDream(engine: BrainEngine | null, args: string[]): PromsynthFrom: opts.from ?? undefined,synthTo: opts.to ?? undefined,synthBypassDreamGuard: opts.bypassDreamGuard,- // issue #2860: opts.phase is guaranteed non-null here when opts.once is- // set (parseArgs enforces --once requires --phase).- onceForPhase: opts.once ? opts.phase! : undefined,+ // issue #2860: exactly one phase is guaranteed here when opts.once is+ // set (parseArgs enforces --once requires a single explicit --phase).+ onceForPhase: opts.once ? opts.phases[0]! : undefined,});if (opts.json) {diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 15db5d092a..2b796ea268 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -3,6 +3,7 @@ import { currentEmbeddingSignature } from '../core/embedding.ts';import type { ChunkInput } from '../core/types.ts';import { carryChunkMetadata, probeEmbedder } from '../core/embed-stale.ts';import { chunkText } from '../core/chunkers/recursive.ts';+import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';import { createProgress, type ProgressReporter } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';@@ -784,13 +785,15 @@ async function embedPage(let chunks = await engine.getChunks(slug, opts);if (chunks.length === 0) {const inputs: ChunkInput[] = [];+ // #4530: respect the active embedding model's per-input token limit.+ const chunkOpts = { maxTokens: resolveMaxChunkTokens() };if (page.compiled_truth.trim()) {- for (const c of chunkText(page.compiled_truth)) {+ for (const c of chunkText(page.compiled_truth, chunkOpts)) {inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'compiled_truth' });}}if (page.timeline.trim()) {- for (const c of chunkText(page.timeline)) {+ for (const c of chunkText(page.timeline, chunkOpts)) {inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'timeline' });}}@@ -1228,13 +1231,15 @@ async function healChunklessPages(const buildInputs = (compiledTruth: string, timeline: string): ChunkInput[] => {const inputs: ChunkInput[] = [];+ // #4530: respect the active embedding model's per-input token limit.+ const chunkOpts = { maxTokens: resolveMaxChunkTokens() };if (compiledTruth.trim()) {- for (const c of chunkText(compiledTruth)) {+ for (const c of chunkText(compiledTruth, chunkOpts)) {inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'compiled_truth' });}}if (timeline.trim()) {- for (const c of chunkText(timeline)) {+ for (const c of chunkText(timeline, chunkOpts)) {inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'timeline' });}}diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 3e3788b5fc..4c3eb6df6a 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -182,6 +182,14 @@ export function enrichFingerprint(opts: {order: EnrichOrder;thinThreshold: number;model: string;+ /**+ * #3629 residual: the pre-LLM grounding gate decides against exactly this+ * knob, so a banked skip must not outlive a relaxed --min-context — a+ * non-default value is a genuinely different run. Folded only when it+ * differs from MIN_CONTEXT_CHARS so every existing default-config+ * checkpoint keeps its key (no one-time re-bill on upgrade).+ */+ minContextChars?: number;}): string {return fingerprint({sourceId: opts.sourceId,@@ -189,6 +197,9 @@ export function enrichFingerprint(opts: {order: opts.order,thinThreshold: opts.thinThreshold,model: opts.model,+ ...(opts.minContextChars !== undefined && opts.minContextChars !== MIN_CONTEXT_CHARS+ ? { minContextChars: opts.minContextChars }+ : {}),});}@@ -397,10 +408,14 @@ async function enrichOneLocked(ctx: EnrichOneCtx, candidate: EnrichCandidate): P// reports skip=true for blank raw too, so discriminate on the raw text.if (parsed.skip && (raw ?? '').trim().length > 0) {ctx.result.pages_model_skip = (ctx.result.pages_model_skip ?? 0) + 1;+ // A real grounding verdict — durable until the checkpoint TTL/--force.+ ctx.done.add(completedKey(sourceId, slug));} else {ctx.result.pages_empty_output = (ctx.result.pages_empty_output ?? 0) + 1;+ // Synthesis-failure shape (#2085), usually transient provider trouble —+ // banking it would suppress the page for the full checkpoint TTL, so it+ // stays out of `done` and is re-attempted on the next run.}- ctx.done.add(completedKey(sourceId, slug));return;}@@ -482,13 +497,15 @@ export async function runEnrichCore(const workersResolved = resolveWorkersWithClamp(engine, opts.workers, 'enrich', 0);const workers = workersResolved.workers;- const fp = enrichFingerprint({ sourceId, types, order, thinThreshold, model });+ const fp = enrichFingerprint({ sourceId, types, order, thinThreshold, model, minContextChars });const cpKey = checkpointKey(fp);// #3629: load the checkpoint BEFORE enumerating candidates. SKIP'd pages// stay thin (nothing is written), so they re-enter the candidate list on// every run — the checkpoint is the ONLY thing that stops them re-billing.- if (opts.force) await clearOpCheckpoint(engine, cpKey);+ // #3629 residual: --dry-run promises "no checkpoint advance"; a dry-run+ // --force must not destroy the real checkpoint either.+ if (opts.force && !dryRun) await clearOpCheckpoint(engine, cpKey);const done = new Set<string>(opts.force ? [] : await loadOpCheckpoint(engine, cpKey));// Candidate enumeration — ONE source-aware, memory-bounded SQL query.diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 8e8e55428f..935c9729c3 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -92,9 +92,10 @@ import { parseWorkers, resolveWorkersWithClamp } from '../core/sync-concurrency.import { withRefreshingLock, LockUnavailableError } from '../core/db-lock.ts';import { assertFactsEmbeddingDimMatchesConfig } from '../core/embedding-dim-check.ts';import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';-import { upsertExtractRollup } from '../core/extract/rollup-writer.ts';+import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';+import { resolveEntitySlug } from '../core/entities/resolve.ts';// Re-exported verbatim so existing importers (this file's own helpers below// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,@@ -1104,11 +1105,12 @@ async function processPage(state.result.facts_extracted += extracted.length;if (!state.dryRun && extracted.length > 0) {- // Eng-v2 C1 / E11: page-global row_num. Each fact in this batch gets- // a unique row_num within (source_id, source_markdown_slug); the- // accumulator increments across the segment loop.- const rows = extracted.map((fact, i) => ({+ // Eng-v2 C1 / E11: page-global row_num stays unique across segments.+ const rows = await Promise.all(extracted.map(async (fact, i) => ({...fact,+ entity_slug: fact.entity_slug+ ? await resolveEntitySlug(state.engine, state.sourceId, fact.entity_slug)+ : null,row_num: rowNum + i,source_markdown_slug: page.slug,source: PER_SEGMENT_SOURCE_PREFIX,@@ -1121,7 +1123,7 @@ async function processPage(: {}),context:fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,- }));+ })));const ins = await state.engine.insertFacts(rows, { source_id: state.sourceId }); // gbrain-allow-direct-insert: canonical bulk extraction path for conversation pages — fences-as-system-of-record doesn't apply because conversations don't carry `## Facts` fences (the chat-log shape is the source-of-truth)pageInsertedTotal += ins.inserted;state.result.facts_inserted += ins.inserted;@@ -1652,13 +1654,20 @@ async function writeRunReceiptAndRollup(// Rollup UPSERT: ALWAYS fire so doctor's extract_health sees the// cycle ran (even no-op runs are signal — they prove the extractor// was alive). Best-effort per F-OUT-19.- const incomplete = halted || result.pages_failed > 0;+ //+ // #4482: a run that stopped ONLY because it hit its per-source budget cap+ // is working as designed (partial progress banked; the backlog drains over+ // future runs) — record it as expected_limit_delta, not halt_delta, so+ // doctor's extract_health failure rate stops warning on normal+ // bigger-backlog-than-budget operation. Per-page failures stay error halts.await upsertExtractRollup(engine, {kind: 'facts.conversation',source_id: sourceId,cost_delta: result.spent_usd ?? 0,- round_completed_delta: incomplete ? 0 : 1,- halt_delta: incomplete ? 1 : 0,+ ...classifyRunStop({+ budget_exhausted: halted,+ error: result.pages_failed > 0,+ }),});}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 7dddd300b6..9523d2d90a 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -196,20 +196,33 @@ function refsWithSnapshotStamps(* v0.42.7 (#1696): pure cross-source resolution for one extracted link* candidate. Validates both endpoints exist (else the batch JOIN drops the row),* then picks from_source_id / to_source_id: prefer the origin page's source,- * fall back to 'default', else skip (never push a wrong-source edge). Returns- * null when the candidate should be skipped. Shared by extractLinksFromDB and- * extractStaleFromDB so the F10 multi-source resolution can't drift.+ * fall back to 'default', else skip (never push a wrong-source edge). Shared+ * by extractLinksFromDB and extractStaleFromDB so the F10 multi-source+ * resolution can't drift.+ *+ * v0.46.28.0 (#2589): the failure case now carries a `reason` instead of a+ * bare `null`. A target that resolves via `global_basename` to a page that+ * exists ONLY in a source other than the origin's or 'default' was+ * indistinguishable from a genuinely-missing target — both silently dropped+ * the candidate and both counted (misleadingly) as "target page doesn't+ * exist". This stays default-deny by design: cross-source edges remain+ * unwritten (source isolation — see CLAUDE.md), but callers can now+ * attribute the drop correctly instead of reporting a wrong reason.*/+export type CandidateSourceResolution =+ | { ok: true; fromSlug: string; fromSourceId: string; toSourceId: string }+ | { ok: false; reason: 'missing_target' | 'missing_from' | 'cross_source' };+export function resolveCandidateSources(c: LinkCandidate,pageSlug: string,pageSourceId: string,allSlugs: Set<string>,slugToSources: Map<string, string[]>,-): { fromSlug: string; fromSourceId: string; toSourceId: string } | null {+): CandidateSourceResolution {const fromSlug = c.fromSlug ?? pageSlug;- if (!allSlugs.has(c.targetSlug)) return null;- if (!allSlugs.has(fromSlug)) return null;+ if (!allSlugs.has(c.targetSlug)) return { ok: false, reason: 'missing_target' };+ if (!allSlugs.has(fromSlug)) return { ok: false, reason: 'missing_from' };const fromSources = slugToSources.get(fromSlug) ?? [];const fromSourceId = fromSources.includes(pageSourceId) ? pageSourceId: (fromSources.includes('default') ? 'default' : fromSources[0]);@@ -220,9 +233,9 @@ export function resolveCandidateSources(} else if (targetSources.includes('default')) {toSourceId = 'default';} else {- return null;+ return { ok: false, reason: 'cross_source' };}- return { fromSlug, fromSourceId, toSourceId };+ return { ok: true, fromSlug, fromSourceId, toSourceId };}// isRetryableConnError reference retained for any inline classification at@@ -760,6 +773,9 @@ Extraction:survive). Fixes drift the stale_mentions doctor check reports (#3674).gbrain extract <links|timeline|all> --ner --source dbgbrain extract <timeline|all> --from-meetings --source db+ Scans only meeting pages (type 'meeting', or 'note' with+ frontmatter.legacy_type 'meeting'). REPLACES the default timeline+ pass — it does not add to it.--since DATE filters on updated_at — the page row's last DB-write time("touched since"): import, sync, enrich, and extraction stamps all advance@@ -1041,6 +1057,20 @@ export async function runExtract(engine: BrainEngine, args: string[]) {if (!jsonMode) {console.log(`Timeline from meetings: ${r.entries_created} entries on ${r.entities_touched} entity pages from ${r.meetings_scanned} meetings`);}+ // #4542: a zero-meeting brain used to print "0 entries ... from 0+ // meetings" and exit 0 — indistinguishable from success. Easy to hit+ // because --from-meetings REPLACES the default timeline pass (this+ // branch runs solo), so users expecting "meetings AND the usual pass"+ // silently got neither. Warn on stderr, name the predicate, and point+ // at the way out.+ if (r.meetings_scanned === 0) {+ console.error(+ `[extract timeline] WARN: 0 meetings matched — --from-meetings only scans pages ` ++ `WHERE type = 'meeting' (or type = 'note' with frontmatter.legacy_type = 'meeting'). ` ++ `Note this flag REPLACES the default timeline pass (it does not add to it); ` ++ `omit --from-meetings to extract timeline entries from all pages.`,+ );+ }// #2057 (codex): batch failures are no longer swallowed silently — make// them visible at the command surface (and non-zero exit) instead of// printing a clean "N entries" success over failed inserts.@@ -1621,6 +1651,10 @@ async function extractLinksFromDB(let processed = 0, created = 0;// #2576: skipped-candidate counter — see extractStaleFromDB's twin.let skippedMissingTarget = 0;+ // #2589: target resolved (via global_basename) to a page that exists only+ // in a source other than the origin's or 'default' — default-deny by+ // design (source isolation), but distinct from a genuinely missing target.+ let skippedCrossSource = 0;// v0.42.7 (#1696): pages whose links we extracted this run — stamped after// the loop so a manual `gbrain extract links|all --source db` clears the// links_extraction_lag doctor signal. Non-dry-run only.@@ -1669,10 +1703,15 @@ async function extractLinksFromDB(for (const c of extracted.candidates) {// v0.32.8 F10 cross-source link resolution, extracted to the shared pure// helper in v0.42.7 (#1696) so extract --stale reuses the exact same- // endpoint-validation + from/to source-id picking (null = skip: missing- // endpoint OR target only in a non-origin/non-default source).+ // endpoint-validation + from/to source-id picking. #2589: the reason+ // is now distinguished (missing endpoint vs. target only in a+ // non-origin/non-default source) so the two don't get counted as one.const resolved = resolveCandidateSources(c, slug, source_id, allSlugs, slugToSources);- if (!resolved) { skippedMissingTarget++; continue; }+ if (!resolved.ok) {+ if (resolved.reason === 'cross_source') skippedCrossSource++;+ else skippedMissingTarget++;+ continue;+ }const { fromSlug, fromSourceId, toSourceId } = resolved;if (dryRunSeen) {@@ -1732,6 +1771,9 @@ async function extractLinksFromDB(if (skippedMissingTarget > 0) {console.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} candidate(s) whose target page exists only in another source (cross-source edges are not written — see docs/architecture/brains-and-sources.md).`);+ }if (includeFrontmatter && unresolved.length > 0) {// Top-20 preview of unresolvable frontmatter names so the user can// see where the graph has holes (codex tension 6.4).@@ -1884,7 +1926,7 @@ export async function extractStaleFromDB(*/timeBudgetMs?: number;},-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number }> {+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number }> {const { dryRun, jsonMode, includeFrontmatter, sourceIdFilter, catchUp } = opts;const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;const versionTs = LINK_EXTRACTOR_VERSION_TS;@@ -1943,6 +1985,10 @@ export async function extractStaleFromDB(// persisted. Counted so a dropped reference is observable in the summary// instead of vanishing silently (the failure mode that hid bug 2).let skippedMissingTarget = 0;+ // #2589: target resolved (via global_basename) to a page that exists only+ // in a source other than the origin's or 'default' — default-deny by+ // design (source isolation), but distinct from a genuinely missing target.+ let skippedCrossSource = 0;for (;;) {const rows = await engine.listStalePagesForExtraction({@@ -1962,7 +2008,11 @@ export async function extractStaleFromDB();for (const c of extracted.candidates) {const r = resolveCandidateSources(c, page.slug, page.source_id, allSlugs, slugToSources);- if (!r) { skippedMissingTarget++; continue; }+ if (!r.ok) {+ if (r.reason === 'cross_source') skippedCrossSource++;+ else skippedMissingTarget++;+ continue;+ }linkRows.push({from_slug: r.fromSlug, to_slug: c.targetSlug, link_type: c.linkType,context: c.context, link_source: c.linkSource, origin_slug: c.originSlug,@@ -2030,6 +2080,9 @@ export async function extractStaleFromDB(if (skippedMissingTarget > 0) {console.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} candidate(s) whose target page exists only in another source (cross-source edges are not written — see docs/architecture/brains-and-sources.md).`);+ }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.`);}@@ -2037,10 +2090,10 @@ export async function extractStaleFromDB(process.stdout.write(JSON.stringify({action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,- skipped_missing_target: skippedMissingTarget,+ skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,}) + '\n');}- return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget };+ return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource };}/**diff --git a/src/commands/jobs.ts b/src/commands/jobs.tsindex 8dd9faeb0c..635682c852 100644--- a/src/commands/jobs.ts+++ b/src/commands/jobs.ts@@ -8,6 +8,8 @@ import type { FactsBackstopResult } from '../core/facts/backstop.ts';// Leaf module (no flag surface of its own) — see that file for why this// isn't imported from extract-conversation-facts.ts directly (#4135).import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';+import { assertEmbedBackfillQueueAdmission } from '../core/minions/embed-backfill-admission.ts';+import { isProtectedJobName } from '../core/minions/protected-names.ts';import { MinionQueue, deriveWedgeSignal } from '../core/minions/queue.ts';import { MinionWorker } from '../core/minions/worker.ts';import {@@ -635,7 +637,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):switch (sub) {case 'submit': {- const name = args[1];+ const name = args[1]?.trim();if (!name) {console.error('Error: job name required. Usage: gbrain jobs submit <name>');process.exit(1);@@ -688,13 +690,19 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const queueName = parseFlag(args, '--queue') ?? 'default';const dryRun = hasFlag(args, '--dry-run');const follow = hasFlag(args, '--follow');- // v0.36.5.0: --redact-secrets is a CLI convenience that merges- // `redact_secrets: true` into the params before validation. Equivalent- // to passing it in --params JSON; flag form is faster to type.- if (hasFlag(args, '--redact-secrets') && name.trim() === 'shell') {+ // v0.36.5.0: --redact-secrets merges the equivalent --params JSON convenience.+ if (hasFlag(args, '--redact-secrets') && name === 'shell') {data.redact_secrets = true;}+ // Dry-run reports real admission; follow starts and awaits an inline worker.+ const trusted = {+ ...(isProtectedJobName(name) ? { allowProtectedSubmit: true } : {}),+ ...(follow && name === 'embed-backfill' ? { allowPgliteInlineWorker: true } : {}),+ };+ try { assertEmbedBackfillQueueAdmission(engine, name, data, trusted); }+ catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }+if (dryRun) {console.log(`[DRY RUN] Would submit job:`);console.log(` Name: ${name}`);@@ -719,25 +727,15 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):return;}- try {- await queue.ensureSchema();- } catch (e) {- console.error(e instanceof Error ? e.message : String(e));- process.exit(1);- }-- // The CLI path is a trusted submitter. Pass {allowProtectedSubmit: true}- // ONLY for protected names, not blanket-set for every submission, so any- // future protected name forces explicit opt-in at the call site.- const { isProtectedJobName } = await import('../core/minions/protected-names.ts');- const trusted = isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;+ try { await queue.ensureSchema(); }+ catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }// v0.35.8.0: pre-enqueue shell-job validation. Validates `inherit:`// closed enum, rejects secret env-keys, fail-fasts on missing config.// Throws UnrecoverableError BEFORE `queue.add` so a bad payload never// lands in `minion_jobs.data`. Defense-in-depth re-validation happens// in the worker handler. See: src/core/minions/handlers/shell-validate.ts- if (name.trim() === 'shell') {+ if (name === 'shell') {try {const { validateShellJobParams } = await import('../core/minions/handlers/shell-validate.ts');validateShellJobParams(data);@@ -766,7 +764,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// Submission audit log (operational trace, not forensic insurance).try {const { logShellSubmission } = await import('../core/minions/handlers/shell-audit.ts');- if (name.trim() === 'shell') {+ if (name === 'shell') {const inheritNames = Array.isArray(data.inherit)? (data.inherit as unknown[]).filter((s): s is string => typeof s === 'string'): undefined;@@ -788,7 +786,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):// regardless of the submitter's own `GBRAIN_ALLOW_SHELL_JOBS` — the submitter// env is a weak proxy for the worker env (they may run on different machines),// so the warning remains useful any time the job might sit in 'waiting'.- if (!follow && name.trim() === 'shell') {+ if (!follow && name === 'shell') {process.stderr.write(`\n⚠ Shell jobs require GBRAIN_ALLOW_SHELL_JOBS=1 on the worker process.\n` +` Your job was queued (id=${job.id}) but will sit in 'waiting' until a\n` +@@ -1980,23 +1978,23 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):const cliPath = parseFlag(args, '--cli-path') ?? resolveGbrainCliPath();// --detach: fork a background supervisor, print PID payload, exit 0.- // Implementation: re-exec the same CLI as a detached child without --detach,- // inheriting stderr (so JSONL events still flow to the parent's tail-f- // if they wanted to follow logs) but detaching stdin/stdout.+ // #4418: the child gets a DURABLE stderr sink (audit-dir log, null-device+ // fallback) instead of inheriting the invoker's stderr — an inherited+ // capture pipe closing killed the worker (SIGPIPE 141) and then the+ // supervisor itself on their next stderr write. See detached-stderr.ts.if (detach) {- const { spawn } = await import('child_process');- const childArgs = process.argv.slice(2).filter(a => a !== '--detach');- const child = spawn(process.execPath, [process.argv[1], ...childArgs], {- detached: true,- stdio: ['ignore', 'ignore', 'inherit'],- env: process.env,- });- child.unref();+ const { spawnDetachedSupervisor } = await import('../core/minions/detached-stderr.ts');+ const started = spawnDetachedSupervisor(+ process.execPath,+ process.argv[1],+ process.argv.slice(2).filter(a => a !== '--detach'),+ );const payload = {event: 'started',- supervisor_pid: child.pid,+ supervisor_pid: started.pid,pid_file: pidFile,detached: true,+ ...(started.stderrPath ? { stderr_log: started.stderrPath } : {}),};console.log(JSON.stringify(payload));process.exit(0);@@ -2177,9 +2175,11 @@ export async function registerBuiltinHandlers(: 'sync_handler',});if (submission.status === 'submitted') {- embedJobId = submission.jobId ?? null;- } else {+ embedJobId = submission.jobId;+ } else if (submission.status === 'cooldown' || submission.status === 'spend_capped' || submission.status === 'no_worker_surface') {embedSkipReason = submission.status;+ } else {+ submission satisfies never;}} else {embedSkipReason = 'feature_flag_disabled';@@ -2499,7 +2499,11 @@ export async function registerBuiltinHandlers(visibility: job.data.visibility === 'world' ? 'world' : 'private',...(typeof job.data.model === 'string' && job.data.model ? { model: job.data.model } : {}),},- );+ ).catch(async (err: unknown) => {+ const { writeFactsAbsorbFailure } = await import('../core/facts/absorb-log.ts');+ await writeFactsAbsorbFailure(engine, slug, err, sourceId);+ throw err;+ });// Execution-time chat_unavailable in a KEYED worker is config drift —// throw (typed) so minion retry/backoff parks it as a VISIBLE, re-runnable// failure instead of consuming the job and silently losing the facts. Adiff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex 0ab47ef013..407a6b32dc 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -434,6 +434,23 @@ export async function copyPageToTarget(content_hash: page.content_hash,}), { ...sourceOpts, allowEmptyOverwrite: true });+ // #4527: putPage stamps created_at/updated_at with now() (PageInput has no+ // timestamp fields), so without this every migrated page loses its+ // chronology — recency ranking, `--since` filters, and timeline ordering+ // all silently reset to the migration date. Restore the source row's+ // timestamps directly; COALESCE keeps the putPage-stamped value if the+ // source engine ever hands back a NULL (never expected, but a copy must+ // not null out a NOT NULL column).+ if (page.created_at != null || page.updated_at != null) {+ await target.executeRaw(+ `UPDATE pages+ SET created_at = COALESCE($1, created_at),+ updated_at = COALESCE($2, updated_at)+ WHERE slug = $3 AND source_id = $4`,+ [page.created_at ?? null, page.updated_at ?? null, page.slug, page.source_id ?? 'default'],+ );+ }+// Copy chunks with embeddings.const chunks = await source.getChunksWithEmbeddings(page.slug, sourceOpts);if (chunks.length > 0) {@@ -453,8 +470,11 @@ export async function copyPageToTarget(await target.addTag(page.slug, tag, sourceOpts);}- // Copy timeline- const timeline = await source.getTimeline(page.slug, sourceOpts);+ // Copy timeline. #4485: getTimeline defaults to LIMIT 100 (newest-first)+ // in both engines, so a page with a longer history silently lost everything+ // past its newest 100 entries — pass an explicit unbounded limit (max int4,+ // safely above any real per-page timeline).+ const timeline = await source.getTimeline(page.slug, { ...sourceOpts, limit: 2_147_483_647 });for (const entry of timeline) {await target.addTimelineEntry(page.slug, {date: entry.date,@@ -1071,7 +1091,21 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]// warnings and keeps going so the user sees the full picture.console.log('\nVerifying target...');try {- await verifyTarget(targetEngine, sourceStats.page_count);+ // #4485: compare timeline counts too — the LIMIT-100 truncation class of+ // bug (a bounded read inside the copy) is invisible to the page-count+ // check, so verify pins the row-level tables it can count cheaply on+ // both sides. wave-g: counts are scoped to the COPIED page set (live+ // pages), not the whole table — the copy iterates listPages() output,+ // which excludes soft-deleted pages, so a soft-deleted source page that+ // still owns timeline rows produced a false WARN under whole-table+ // counts. Both sides use the identical predicate.+ let sourceTimelineCount: number | undefined;+ try {+ const rows = await sourceEngine.executeRaw<{ count: string }>(COPIED_TIMELINE_COUNT_SQL);+ sourceTimelineCount = Number(rows[0]?.count ?? NaN);+ if (!Number.isFinite(sourceTimelineCount)) sourceTimelineCount = undefined;+ } catch { /* older schema: skip the timeline parity check */ }+ await verifyTarget(targetEngine, sourceStats.page_count, sourceTimelineCount);} catch (e) {console.warn(` Verification could not complete: ${e instanceof Error ? e.message : String(e)}`);}@@ -1079,12 +1113,28 @@ export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]await targetEngine.disconnect();}+/**+ * wave-g (#4485 follow-up): timeline parity counts rows over the COPIED page+ * set — timeline entries whose page is live (`deleted_at IS NULL`). The+ * migration copies listPages() output, which excludes soft-deleted pages, so+ * whole-table counts false-WARNed whenever a soft-deleted page still owned+ * timeline rows on the source. Shared by the source read and verifyTarget so+ * the two sides can never drift; throws on pre-deleted_at schemas, which the+ * callers' try/catch already fail-opens to "skip the parity check".+ * Exported for the test surface only.+ */+export const COPIED_TIMELINE_COUNT_SQL =+ `SELECT count(*)::text AS count+ FROM timeline_entries te+ JOIN pages p ON p.id = te.page_id+ WHERE p.deleted_at IS NULL`;+/*** Lightweight doctor-style verify run against the migrated target.* Prints a small table of signals; does not exit. Callers own engine* lifecycle.*/-async function verifyTarget(engine: BrainEngine, expectedPages: number): Promise<void> {+async function verifyTarget(engine: BrainEngine, expectedPages: number, expectedTimelineEntries?: number): Promise<void> {const stats = await engine.getStats();if (stats.page_count === expectedPages) {console.log(` ok pages: ${stats.page_count} (matches source)`);@@ -1092,6 +1142,24 @@ async function verifyTarget(engine: BrainEngine, expectedPages: number): Promiseconsole.warn(` WARN pages: ${stats.page_count} (source had ${expectedPages})`);}+ // #4485: row-level parity for the timeline table — a bounded read inside+ // the copy (the old LIMIT-100 truncation) passes the page-count check just+ // fine, so the verify step counts the rows themselves. wave-g: scoped to+ // the copied (live) page set on BOTH sides — see COPIED_TIMELINE_COUNT_SQL.+ if (expectedTimelineEntries !== undefined) {+ try {+ const rows = await engine.executeRaw<{ count: string }>(COPIED_TIMELINE_COUNT_SQL);+ const targetTimeline = Number(rows[0]?.count ?? NaN);+ if (targetTimeline === expectedTimelineEntries) {+ console.log(` ok timeline entries: ${targetTimeline} (matches source)`);+ } else {+ console.warn(` WARN timeline entries: ${targetTimeline} (source had ${expectedTimelineEntries})`);+ }+ } catch (e) {+ console.warn(` WARN timeline entries: could not count (${e instanceof Error ? e.message : String(e)})`);+ }+ }+try {const health = await engine.getHealth();const pct = (health.embed_coverage * 100).toFixed(0);diff --git a/src/commands/orphans.ts b/src/commands/orphans.tsindex 645dd51e26..093a91ee86 100644--- a/src/commands/orphans.ts+++ b/src/commands/orphans.ts@@ -1,18 +1,23 @@/**- * gbrain orphans — Surface pages with no inbound wikilinks.+ * gbrain orphans — Surface disconnected pages.*- * Deterministic: zero LLM calls. Queries the links table for pages with- * no entries where to_page_id = pages.id. By default filters out- * auto-generated pages and pseudo-pages where no inbound links is expected.+ * Deterministic: zero LLM calls. #4524: the DEFAULT definition is+ * 'islanded' — no live inbound AND no live outbound link — matching+ * get_health.orphan_pages so doctor and this command agree by construction.+ * `--mode inbound` restores the legacy no-inbound-only view (pages that+ * link out but are never linked TO). By default filters out auto-generated+ * pages and pseudo-pages where being disconnected is expected.** Usage:- * gbrain orphans # list orphans grouped by domain+ * gbrain orphans # list islanded pages grouped by domain+ * gbrain orphans --mode inbound # legacy: pages with no inbound links* gbrain orphans --json # JSON output for agent consumption* gbrain orphans --count # just the number* gbrain orphans --include-pseudo # include auto-generated/pseudo pages*/import type { BrainEngine } from '../core/engine.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { createProgress, startHeartbeat } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import {@@ -85,11 +90,15 @@ export async function queryOrphanPages(* consumer that needs the same exclusion logic (AUTO_SUFFIX_PATTERNS,* PSEUDO_SLUGS, RAW_SEGMENT, DENY_PREFIXES, FIRST_SEGMENT_EXCLUSIONS).* Two consumers sharing one definition = doctor and `gbrain orphans`- * cannot disagree on the orphan count.+ * cannot disagree on the orphan count. #4524 extended that guarantee to+ * get_health.orphan_pages: `findOrphanPages` now DEFAULTS to health's+ * 'islanded' definition (no live inbound AND no live outbound), so all+ * three surfaces report the same number; pass `mode: 'inbound'` for the+ * legacy no-inbound-only view.*/export async function findOrphans(engine: BrainEngine,- opts: { includePseudo?: boolean; sourceId?: string; sourceIds?: string[] } = {},+ opts: { includePseudo?: boolean; sourceId?: string; sourceIds?: string[]; mode?: 'inbound' | 'islanded' } = {},): Promise<OrphanResult> {const includePseudo = !!opts.includePseudo;// v0.41.29.0: `sourceId` (scalar, from `--source` + single-source MCP@@ -112,9 +121,10 @@ export async function findOrphans(let excludedAll: number;const overrides = includePseudo ? undefined : await loadOrphanPolicyOverrides(engine);try {- allOrphans = await engine.findOrphanPages(- sourceIds ? { sourceIds } : sourceId ? { sourceId } : undefined,- );+ allOrphans = await engine.findOrphanPages({+ ...(sourceIds ? { sourceIds } : sourceId ? { sourceId } : {}),+ ...(opts.mode ? { mode: opts.mode } : {}),+ });// v0.41.29.0 (Codex F6): correct the `total_linkable` denominator.// Enumerate ALL live pages (scoped) and count excluded-by-slug across// the WHOLE set — not just among orphans. The old@@ -226,21 +236,36 @@ export async function runOrphans(engine: BrainEngine, args: string[]) {// purpose — NOT resolveSourceWithTier, which would pick a default source// when the flag is absent and silently scope a bare `gbrain orphans`.let sourceId: string | undefined;+ // #4524: --mode inbound|islanded picks the orphan definition. Default+ // 'islanded' (health's definition) so doctor / get_health / orphans agree.+ let mode: 'inbound' | 'islanded' | undefined;for (let i = 0; i < args.length; i++) {if (args[i] === '--source' && i + 1 < args.length) {sourceId = args[++i] || undefined;+ } else if (args[i] === '--mode' && i + 1 < args.length) {+ const raw = args[++i];+ if (raw !== 'inbound' && raw !== 'islanded') {+ console.error(`Invalid --mode "${raw}". Use: inbound or islanded`);+ setCliExitVerdict(1);+ return;+ }+ mode = raw;}}if (args.includes('--help') || args.includes('-h')) {console.log(`Usage: gbrain orphans [options]-Find pages with no inbound wikilinks.+Find disconnected pages. Default definition is 'islanded' (no live inbound+AND no live outbound link) — the same definition get_health.orphan_pages+and doctor use, so all three surfaces agree by construction (#4524).Options:--json Output as JSON (for agent consumption)--count Output just the number of orphans--include-pseudo Include auto-generated and pseudo pages in results+ --mode <m> Orphan definition: islanded (default) | inbound+ (legacy: pages with no inbound links, even if they link out)--source <id> Scope the scan to one brain source (default: brain-wide)--help, -h Show this help@@ -250,7 +275,7 @@ Summary line: N orphans out of M linkable pages (K total; K-M excluded)return;}- const result = await findOrphans(engine, { includePseudo, sourceId });+ const result = await findOrphans(engine, { includePseudo, sourceId, mode });if (count) {console.log(String(result.total_orphans));diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.tsindex 14f80d4ae1..27df5e0895 100644--- a/src/commands/pglite-repair.ts+++ b/src/commands/pglite-repair.ts@@ -20,7 +20,7 @@* repair does not help — `gbrain reinit-pglite` is the rebuild path.*/-import { createInterface } from 'readline';+import { promptYesNo } from '../core/confirm-prompt.ts';import { loadConfig, gbrainPath } from '../core/config.ts';import { acquireLock, releaseLock, LiveServeLockError, msSinceLastReap } from '../core/pglite-lock.ts';import {@@ -100,23 +100,6 @@ function emitError(jsonOutput: boolean, code: string, message: string): void {}}-async function promptYesNo(question: string): Promise<boolean> {- // W0 fix-wave (Tier-1 #15): non-interactive stdin (CI, pipes, spawned- // agents) must resolve to the safe default instead of hanging forever —- // this prompt had no TTY guard and no close/EOF handler, so a piped or- // closed stdin parked the process permanently.- if (!process.stdin.isTTY) return false;- // Prompt on stderr: stdout stays clean for --json payloads.- const rl = createInterface({ input: process.stdin, output: process.stderr });- return new Promise((resolve) => {- rl.on('close', () => resolve(false)); // EOF (^D) = decline, never hang- rl.question(`${question} [y/N] `, (answer) => {- rl.close();- resolve(/^y(es)?$/i.test(answer.trim()));- });- });-}-export async function runPgliteRepair(args: string[]): Promise<number> {let opts: RepairCmdOpts;try {@@ -223,7 +206,9 @@ export async function runPgliteRepair(args: string[]): Promise<number> {console.error(`About to reset the WAL of ${dataDir} in place.`);console.error('Data files are preserved; un-checkpointed transactions may be lost.');console.error('The current pg_wal + pg_control are kept in a sibling backup directory.');- const confirmed = await promptYesNo('Repair now?');+ // Prompt on stderr (not the confirm-prompt default of stdout): stdout+ // stays clean for --json payloads.+ const confirmed = await promptYesNo('Repair now? [y/N] ', { output: process.stderr });if (!confirmed) {if (opts.jsonOutput) {console.log(JSON.stringify({ status: 'aborted', reason: 'user_declined' }));diff --git a/src/commands/schema.ts b/src/commands/schema.tsindex 34de458849..b34eb4653f 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -27,6 +27,7 @@ import {addTypeToPack,invalidatePackCache,loadActivePack,+ loadResolvedPackByName,removeAliasFromType,removeLinkTypeFromPack,removePrefixFromType,@@ -728,7 +729,24 @@ async function runLintCmd(args: string[]): Promise<void> {let pack: SchemaPackManifest | null;if (name) {const p = packPathByName(name);- try { pack = p ? loadPackFromFile(p) : null; } catch { pack = null; }+ let raw: SchemaPackManifest | null;+ try { raw = p ? loadPackFromFile(p) : null; } catch { raw = null; }+ if (raw) {+ // #4501: lint the MERGED manifest (extends chain + borrow_from+ // resolved), matching the no-name branch's loadActivePack path —+ // a child pack referencing inherited parent types must not fail+ // raw-manifest lint. Fall back to the raw child (with a stderr+ // warning) when the chain can't be resolved, e.g. missing parent.+ try {+ pack = (await loadResolvedPackByName(name)).manifest;+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ console.error(`warn: could not resolve extends chain for pack \`${name}\` (${msg}); linting raw manifest only`);+ pack = raw;+ }+ } else {+ pack = null;+ }} else {pack = (await loadActivePack({ cfg, remote: false })).manifest;}diff --git a/src/commands/search.ts b/src/commands/search.tsindex cd70ad798a..5f7d473e45 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -69,7 +69,7 @@ function formatModesText(report: SearchModesReport): string {const b = report.bundles[mode];const active = mode === report.active_mode ? ' ← active' : '';lines.push(` ${mode.padEnd(13)}${active}`);- lines.push(` cache=${b.cache_enabled} intentWeighting=${b.intentWeighting}`);+ lines.push(` cache=${b.cache_enabled} intentWeighting=${b.intentWeighting} keywordOrFallback=${b.keywordOrFallback}`);lines.push(` tokenBudget=${b.tokenBudget ?? 'none'} searchLimit=${b.searchLimit} expansion=${b.expansion}`);}lines.push('');diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 1eb8617108..938aac9c18 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -54,6 +54,8 @@ import {} from '../mcp/surface.ts';import { writeSurfaceChangeAudit } from '../core/surface-audit.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';+import { bindResolveIpcForServe } from '../mcp/resolve-ipc-binding.ts';+import { resolveMcpStdioSourceScope } from '../mcp/server.ts';import { loadConfig } from '../core/config.ts';import { buildError, serializeError } from '../core/errors.ts';import { VERSION } from '../version.ts';@@ -3272,6 +3274,22 @@ ${bootstrapFromEnv`);});+ // #4474: bind the resolve-IPC unix socket under --http too. This is the+ // exact posture `gbrain bootstrap harness` targets — without the listener+ // every wired lifecycle hook (SessionStart / UserPromptSubmit / PreCompact)+ // degrades to `no_serve` forever, and on a PGLite brain there is no local+ // recovery (the http serve owns the single-writer lock, so a second stdio+ // serve can't provide the socket). Shares the stdio path's wiring via+ // bindResolveIpcForServe; best-effort — failure to bind never blocks the+ // HTTP server.+ const ipcBinding = await bindResolveIpcForServe(+ engine,+ (await resolveMcpStdioSourceScope(engine)).sourceId,+ );+ if (ipcBinding.socketPath) {+ console.error(` Resolve IPC: ${ipcBinding.socketPath}`);+ }+// SIGTERM/SIGHUP route through process-cleanup's pass and then// `process.exit`, which skips cli.ts's finally-teardown — so on those// signals the PGLite write handle was never closed. An unclosed PGLite@@ -3283,12 +3301,19 @@ ${bootstrapFromEnv// the same clean close the SIGINT path already gets via the cli// teardown. Deregistered on normal return so the cli finally remains// the single owner of orderly shutdown.+ const deregisterIpcCleanup = registerCleanup('resolve-ipc-close', async () => {+ ipcBinding.close();+ });const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', () =>engine.disconnect(),);try {await waitForHttpServerLifecycle(httpServer);} finally {+ // Close the IPC listener + reap the socket file on orderly shutdown+ // (abnormal termination goes through the registered cleanup above).+ ipcBinding.close();+ deregisterIpcCleanup();deregisterEngineCleanup();}}diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex ff83951908..bb8dd5d915 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -1,6 +1,6 @@import { spawnSync } from 'node:child_process';import type { BrainEngine } from '../core/engine.ts';-import { startMcpServer } from '../mcp/server.ts';+import { startMcpServer, stdioRpcsInFlightCount } from '../mcp/server.ts';import { VERB_NAMES } from '../core/verbs.ts';import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';import {@@ -11,12 +11,16 @@ import {type LoopStallWatchdogOpts,type WatchdogHandle,} from '../core/process-watchdog.ts';-import {- delegatedSyncSettleMs,- isDelegatedSyncRunning,- maybeDrainDeferredEmbeds,- shutdownDelegatedSync,-} from '../core/serve-sync-runner.ts';+// #4409: serve-sync-runner is deliberately NOT imported statically. The #4362+// static import put its 370-line module (plus dependency graph) on EVERY serve+// boot — heavy enough for a one-shot client's stdin EOF to win the race against+// the first tool-call response on the plugin path — and it defeated the+// GBRAIN_SERVE_SYNC_IPC=0 kill switch (mcp/server.ts guards only ITS dynamic+// import). The three consumers below (shutdown chain, idle sweep) load it+// lazily; a never-loaded runner trivially has no delegated sync running.+// Guarded by test/serve-stdin-eof-drain.test.ts's source-text check.+type ServeSyncRunnerModule = typeof import('../core/serve-sync-runner.ts');+const loadSyncRunner = (): Promise<ServeSyncRunnerModule> => import('../core/serve-sync-runner.ts');// Maximum time the stdio path will wait for engine.disconnect() (PGLite// close + advisory lock release) before forcing exit. Keeps a wedged@@ -129,6 +133,13 @@ export interface ServeOptions {// to resolveServeStallWatchdogMs(GBRAIN_SERVE_STALL_WATCHDOG_MS) — opt-in,// 15s floor, garbage values warn and stay off.stallWatchdogMs?: number;+ // Test seam (#4409): live in-flight stdio RPC count consulted by the+ // stdin-EOF drain. Defaults to mcp/server.ts's stdioRpcsInFlightCount.+ pendingRpcs?: () => number;+ // Test seam (#4409): stdin-EOF drain bound in ms; 0 = immediate shutdown+ // (pre-#4409 behavior). Defaults to GBRAIN_SERVE_EOF_DRAIN_MS (30s when+ // unset; lenient parse).+ eofDrainMs?: number;}/**@@ -369,6 +380,27 @@ export async function runServe(// hooks from being able to call process.exit() cleanly.}+// #4409: stdin-EOF drain bound. Long enough for a real tool call (a query+// with embedding + LLM expansion) to finish; short enough that a genuinely+// wedged handler can't pin the PGLite lock forever after the parent left.+const DEFAULT_EOF_DRAIN_MS = 30_000;++// Env resolution for the stdin-EOF drain bound. Lenient like+// resolveBootTimeoutMs: a typo'd env var must not turn the data-loss fix+// into a shutdown failure. 0 disables the drain (immediate exit).+function resolveEofDrainMs(): number {+ const raw = process.env.GBRAIN_SERVE_EOF_DRAIN_MS;+ if (raw === undefined || raw.trim() === '') return DEFAULT_EOF_DRAIN_MS;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) {+ console.error(+ `[gbrain serve] ignoring invalid GBRAIN_SERVE_EOF_DRAIN_MS=${JSON.stringify(raw)} — using default ${DEFAULT_EOF_DRAIN_MS}ms`,+ );+ return DEFAULT_EOF_DRAIN_MS;+ }+ return Math.floor(n);+}+// Env resolution for the boot deadline. Lenient (warn + default) rather// than throw: this is an incident-time escape hatch, and a typo'd env var// must not turn a boot-safety net into a boot failure of its own.@@ -445,29 +477,43 @@ function installStdioLifecycle(// A running delegated sync extends the deadline by exactly its settle// bound: shutdownDelegatedSync must finish its abort+settle against the// live engine BEFORE disconnect, and a fixed 5s would force-exit mid-- // settle (second-outside-voice finding EV1).- const settleExtensionMs = isDelegatedSyncRunning() ? delegatedSyncSettleMs() : 0;- const deadline = setTimeout(() => {- deps.log(- `GBrain MCP server: cleanup deadline (${CLEANUP_DEADLINE_MS + settleExtensionMs}ms) exceeded — forcing exit`,- );- deps.exit(0);- }, CLEANUP_DEADLINE_MS + settleExtensionMs);- deadline.unref?.();+ // settle (second-outside-voice finding EV1). #4409: the runner loads+ // lazily inside the chain (module-cache hit when a sync ever ran; a+ // fresh load trivially reports no sync running), so the deadline arms+ // at the base bound first and re-arms with the settle extension once+ // the runner state is known.+ let deadline: ReturnType<typeof setTimeout> | undefined;+ const armDeadline = (ms: number): void => {+ deadline = setTimeout(() => {+ deps.log(+ `GBrain MCP server: cleanup deadline (${ms}ms) exceeded — forcing exit`,+ );+ deps.exit(0);+ }, ms);+ deadline.unref?.();+ };+ armDeadline(CLEANUP_DEADLINE_MS);Promise.resolve()// Idempotent shared promise — mcp/server.ts's shutdown races here on// the same signals; whichever runs first does the abort+settle, the// other awaits it. Must precede disconnect (settle writes need the// live engine; the disconnect-mode drain is allowAbort:false).- .then(() => shutdownDelegatedSync())+ .then(() => loadSyncRunner())+ .then((runner) => {+ if (runner.isDelegatedSyncRunning()) {+ if (deadline) clearTimeout(deadline);+ armDeadline(CLEANUP_DEADLINE_MS + runner.delegatedSyncSettleMs());+ }+ return runner.shutdownDelegatedSync();+ }).then(() => engine.disconnect()).catch((err: unknown) => {const msg = err instanceof Error ? err.message : String(err);deps.log(`GBrain MCP server: cleanup error: ${msg}`);}).finally(() => {- clearTimeout(deadline);+ if (deadline) clearTimeout(deadline);deps.exit(0);});};@@ -499,9 +545,46 @@ function installStdioLifecycle(// `mcpStdio` is the injectable form; default reads the env once at// install time so tests stay isolated (no process.env mutation).const mcpStdioMode = opts.mcpStdio ?? (process.env.MCP_STDIO === '1');+ // #4409: a one-shot MCP client writes its frames and closes stdin+ // immediately. Node delivers 'end' AFTER all 'data' events, and the SDK+ // parses every received frame synchronously during 'data' (handler start+ // is queued as a microtask) — so at EOF time requests can be in flight+ // with no response written yet. Treating EOF as an immediate shutdown+ // silently dropped those responses (the codex-plugin door went red on+ // exactly this shape). Drain in-flight RPCs — bounded — before the+ // graceful exit; idle servers still exit promptly (one timer tick).+ // GBRAIN_SERVE_EOF_DRAIN_MS tunes the bound; 0 restores immediate exit.+ const pendingRpcs = opts.pendingRpcs ?? stdioRpcsInFlightCount;+ const eofDrainMs = opts.eofDrainMs ?? resolveEofDrainMs();+ let eofDrainStarted = false;+ const drainThenShutdown = (reason: string): void => {+ if (shuttingDown || eofDrainStarted) return;+ eofDrainStarted = true;+ void (async () => {+ if (eofDrainMs > 0) {+ // One macrotask so already-parsed requests' handlers (microtasks)+ // start and increment the counter before the first check.+ await new Promise<void>((r) => setTimeout(r, 0));+ if (pendingRpcs() > 0) {+ deps.log(+ `GBrain MCP server: stdin EOF with ${pendingRpcs()} in-flight request(s) — draining before exit (bound ${eofDrainMs}ms; GBRAIN_SERVE_EOF_DRAIN_MS)`,+ );+ const deadlineAt = Date.now() + eofDrainMs;+ while (pendingRpcs() > 0 && Date.now() < deadlineAt && !shuttingDown) {+ await new Promise<void>((r) => setTimeout(r, 25));+ }+ }+ // One extra macrotask: the SDK sends the response in a .then AFTER+ // the handler resolves — let that stdout write get issued before+ // the cleanup chain starts.+ await new Promise<void>((r) => setTimeout(r, 0));+ }+ beginShutdown(reason);+ })();+ };if (!deps.stdin.isTTY && !mcpStdioMode) {- deps.stdin.once('end', () => beginShutdown('stdin-end'));- deps.stdin.once('close', () => beginShutdown('stdin-close'));+ deps.stdin.once('end', () => drainThenShutdown('stdin-end'));+ deps.stdin.once('close', () => drainThenShutdown('stdin-close'));}// Parent-process watchdog. Some hosts (launchd, cron, certain MCP@@ -566,9 +649,12 @@ function installStdioLifecycle(const sweepEnabled = opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0');if (sweepEnabled) {const runIdleSweep = opts.sweep ?? (async (e: BrainEngine) => {+ // #4409: the runner loads lazily here too — the sweep fires after+ // 10-20 min of idle, well off the boot path this fix protects.+ const runner = await loadSyncRunner();// A delegated sync owns the event loop right now — sweeping under it// is pointless contention; the next idle tick catches up.- if (isDelegatedSyncRunning()) return;+ if (runner.isDelegatedSyncRunning()) return;// Lazy import keeps the sweep core off the serve boot path.const { runMaintenanceSweep } = await import('../core/sweep.ts');await runMaintenanceSweep(e, {@@ -577,7 +663,7 @@ function installStdioLifecycle(});// Deferred-embed drain: delegated syncs always run noEmbed (the #2139// cost gate lives in runSync); the lock owner closes that loop here.- await maybeDrainDeferredEmbeds(e);+ await runner.maybeDrainDeferredEmbeds(e);});let stdinSawData = false;let sweepInFlight = false;diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 87065bcdf8..79e7cc0ad2 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1009,7 +1009,6 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):try {const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');if (!(await isFederatedV2Enabled(engine))) return;-const { loadAllSources } = await import('../core/sources-load.ts');const { computeAllSourceMetrics } = await import('../core/source-health.ts');const sources = await loadAllSources(engine, { includeArchived: false });@@ -1026,7 +1025,9 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):console.log(` → embed-backfill skipped (cooldown). Manually trigger with: gbrain jobs submit embed-backfill --params '{"sourceId":"${id}"}'`);} else if (sub.status === 'spend_capped') {console.log(` → embed-backfill skipped (24h spend cap $${sub.spendCapUsd} reached for this source).`);- }+ } else if (sub.status === 'no_worker_surface') {+ console.log(` → embed-backfill not queued (${sub.engineKind} has no recognized persistent worker); run: gbrain embed --stale --source ${id}`);+ } else { sub satisfies never; }} catch (err) {// Federation flip already succeeded; embed-backfill is a follow-up nicety.console.error(` → embed-backfill submission failed (flip succeeded): ${err instanceof Error ? err.message : String(err)}`);diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 62fe8bc760..095d5492d1 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -14,7 +14,7 @@ import {unacknowledgedSyncFailures,acknowledgeFailures,loadSyncFailures,- formatCodeBreakdown,+ formatCodeBreakdown, formatFailedFileList,applySyncFailureGate,isSkippablePath,resolveAutoSkipThreshold,@@ -27,7 +27,6 @@ import {buildDetachedWorkingTreeManifest,} from '../core/sync-delta.ts';import { CHUNKER_VERSION } from '../core/chunkers/code.ts';-import { willEmbedSynchronously } from '../core/embedding.ts';import type { SyncManifest } from '../core/sync.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -80,7 +79,14 @@ import { AbortError } from '../core/abort-check.ts';// below also has a re-export block at its original site in this file so// existing importers keep working; these imports are the symbols the code// remaining here still uses directly.-import { runInlineCostGate } from '../core/sync-cost-gate.ts';+import {+ buildSingleSyncJsonEnvelope,+ formatSyncEmbedBackfillOutcome,+ resolveSingleSyncEmbedPlan,+ resolveSyncAllEmbedPlan,+ resolveSyncEmbedBackfill,+ type SyncEmbedBackfillOutcome,+} from '../core/sync-embed-backfill.ts';import {git,isPathSafe,@@ -228,6 +234,7 @@ export interface SyncResult {chunksCreated: number;/** Pages re-embedded during this sync's auto-embed step. 0 if --no-embed or skipped. */embedded: number;+ embedDeferralReason?: 'large_sync';pagesAffected: string[];failedFiles?: number; // count of parse failures (Bug 9)/**@@ -251,6 +258,14 @@ export interface SyncResult {* in job results where daemon stderr is invisible.*/type_warnings?: Array<{ kind: 'alias_of' | 'undeclared'; type: string; canonical?: string; directory?: string; count: number }>;+ /**+ * Working-tree files invisible to commit-driven sync (attached HEAD without+ * --working-tree): untracked/added, modified, and deleted counts AFTER the+ * same scope/exclude/isSyncable filters imports use. Uncommitted renames are+ * decomposed as add(new path) + delete(old path). Absent when zero, or when+ * the working tree was imported (detached HEAD or --working-tree).+ */+ uncommitted?: { added: number; modified: number; deleted: number };/*** v0.41.13.0 partial-sync fields (only set when status === 'partial').*@@ -355,6 +370,17 @@ export interface SyncOpts {* changes in diffs, so sync uses the full filesystem walker when this is set.*/includeGitignored?: boolean;+ /**+ * Import uncommitted working-tree state (untracked files + uncommitted+ * tracked edits/deletes) on an ATTACHED HEAD, via the same manifest-merge+ * path detached-HEAD syncs have always used. Off by default: commit-driven+ * sync stays the contract, and uncommitted drift is counted + reported+ * either way (see SyncResult.uncommitted). CLI `--working-tree`; persist+ * with config `sync.include_working_tree=true`. NOTE: the inline cost+ * estimator does not price working-tree files on attached repos, so the+ * gate can underestimate an explicit --working-tree run.+ */+ workingTree?: boolean;/*** Number of parallel workers for the import phase. When > 1, each worker* gets its own small Postgres connection pool and files are dispatched via@@ -1121,14 +1147,95 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syconst currentVersion = String(CHUNKER_VERSION);const versionMismatch = storedVersion !== null && storedVersion !== currentVersion;const versionNeverSet = storedVersion === null && opts.sourceId !== undefined;- const detachedWorkingTreeManifest = detachedHead ? buildDetachedWorkingTreeManifest(gitContextRoot) : null;- const hasDetachedWorkingTreeChanges = detachedWorkingTreeManifest !== null &&- (detachedWorkingTreeManifest.added.length > 0 ||- detachedWorkingTreeManifest.modified.length > 0 ||- detachedWorkingTreeManifest.deleted.length > 0 ||- detachedWorkingTreeManifest.renamed.length > 0);-- if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !hasDetachedWorkingTreeChanges) {+ // Untracked-gap fix: the working-tree manifest is now built for attached+ // HEADs too, not just detached ones. Detached HEAD (pre-existing semantics)+ // or a resolved workingTree opt-in → the manifest merges into the delta+ // below and uncommitted state IMPORTS. Attached without the opt-in → NOT+ // imported, but counted through the same scope/exclude/isSyncable filters+ // imports use and reported as `uncommitted` drift + a stderr warning.+ // Before this, "Already up to date." printed while untracked files sat+ // invisible — sync reported convergence it had not achieved.+ //+ // The config fallback resolves HERE (not the CLI layer) so EVERY caller —+ // dream cycle, minion sync jobs, sync_brain — honors the persisted+ // `sync.include_working_tree` the warnings recommend. Per-call flag wins;+ // the config read is best-effort (a config error never breaks a sync).+ let workingTreeResolved = opts.workingTree;+ if (workingTreeResolved === undefined) {+ try {+ workingTreeResolved = (await engine.getConfig('sync.include_working_tree')) === 'true';+ } catch { workingTreeResolved = false; }+ }+ const importWorkingTree = detachedHead || workingTreeResolved === true;+ // Fail-open guard: the manifest builder shells out under a 30s/100MiB git+ // budget and THROWS on breach; a monster untracked dir must not convert+ // every previously-working up-to-date sync into a hard error. Drift+ // counting degrades to empty with a stderr note; an EXPLICIT working-tree+ // import request fails closed with the reason (importing without the+ // manifest would silently skip the very files the caller asked for).+ let workingTreeManifest: SyncManifest;+ try {+ workingTreeManifest = buildDetachedWorkingTreeManifest(gitContextRoot);+ } catch (e) {+ if (importWorkingTree) {+ throw new Error(+ `working-tree manifest unavailable (${e instanceof Error ? e.message.slice(0, 160) : String(e)}) — ` ++ `cannot import uncommitted state; re-run without --working-tree or fix the repo state`,+ );+ }+ serr('[sync] working-tree drift probe failed — drift counting skipped this run.');+ workingTreeManifest = { added: [], modified: [], deleted: [], renamed: [] };+ }++ // #753/#774 scope filter (hoisted above the up_to_date gate so the drift+ // counter here and the delta filter below apply IDENTICAL predicates):+ // git-diff paths are git-root-relative; when a subpath scope is active, only+ // paths under it participate. Back-compat: syncScopeRelPath is '' when+ // scope == root, so inScope is always true and the filters reduce to the+ // pre-#774 behavior exactly.+ const inScope = (p: string): boolean =>+ !scoped || p === syncScopeRelPath || p.startsWith(syncScopeRelPath + '/');+ // --exclude patterns match the SCOPE-relative path (what the user of a+ // scoped source thinks in), same form runImport matches on full sync.+ const scopeRel = (p: string): string =>+ scoped && p.startsWith(syncScopeRelPath + '/') ? p.slice(syncScopeRelPath.length + 1) : p;+ const excluded = (p: string): boolean =>+ opts.exclude !== undefined && opts.exclude.length > 0 && matchesAnyGlob(scopeRel(p), opts.exclude);+ const syncOpts = opts.strategy ? { strategy: opts.strategy } : undefined;++ // Filtered working-tree counts. Renames decompose as add(to) + delete(from)+ // — the same decomposition the import path applies — so a rename-only dirty+ // tree still reports drift instead of reproducing the silent gap this+ // counter exists to close (a staged `git mv` populates only `renamed`).+ const wtCounts = {+ added: workingTreeManifest.added.filter(p => inScope(p) && !excluded(p) && isSyncable(p, syncOpts)).length ++ workingTreeManifest.renamed.filter(r => inScope(r.to) && !excluded(r.to) && isSyncable(r.to, syncOpts)).length,+ modified: workingTreeManifest.modified.filter(p => inScope(p) && !excluded(p) && isSyncable(p, syncOpts)).length,+ deleted: workingTreeManifest.deleted.filter(p => inScope(p) && isSyncable(p, syncOpts)).length ++ workingTreeManifest.renamed.filter(r => inScope(r.from) && isSyncable(r.from, syncOpts)).length,+ };+ const wtSyncableTotal = wtCounts.added + wtCounts.modified + wtCounts.deleted;+ // Fast-path gate: detached HEADs keep the pre-existing RAW-manifest gate;+ // attached repos gate on SYNCABLE changes so a stray unsyncable scratch+ // file can't defeat the up_to_date fast path on every scheduled run.+ const hasWorkingTreeChanges = detachedHead+ ? (workingTreeManifest.added.length > 0 ||+ workingTreeManifest.modified.length > 0 ||+ workingTreeManifest.deleted.length > 0 ||+ workingTreeManifest.renamed.length > 0)+ : wtSyncableTotal > 0;++ let uncommittedDrift: { added: number; modified: number; deleted: number } | undefined;+ if (!importWorkingTree && wtSyncableTotal > 0) {+ uncommittedDrift = wtCounts;+ serr(+ `[sync] ${wtSyncableTotal} uncommitted file(s) are invisible to ` ++ `commit-driven sync (${wtCounts.added} untracked/added, ${wtCounts.modified} modified, ${wtCounts.deleted} deleted). ` ++ `Commit them, or run 'gbrain sync --working-tree' to import uncommitted state.`,+ );+ }++ if (lastCommit === headCommit && !versionMismatch && !versionNeverSet && !(importWorkingTree && hasWorkingTreeChanges)) {// #3068: the pull failed and nothing local advanced — this run imported// NOTHING and the remote may hold commits we could not fetch. Reporting// `up_to_date` here (and bumping the heartbeat below) is exactly the@@ -1172,6 +1279,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SychunksCreated: 0,embedded: 0,pagesAffected: [],+ ...(uncommittedDrift ? { uncommitted: uncommittedDrift } : {}),};}@@ -1202,7 +1310,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy// `unavailable`, fall back to the authoritative full reconcile instead of// throwing — a slow correct reconcile beats a hard error or a silent walk.const delta = computeSyncDelta(gitContextRoot, lastCommit, pin, {- detachedManifest: detachedWorkingTreeManifest,+ detachedManifest: importWorkingTree ? workingTreeManifest : null,});if (delta.status === 'unavailable') {serr(@@ -1213,21 +1321,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy}const manifest = delta.manifest;- // #753/#774 scope filter: git-diff paths are git-root-relative; when a- // subpath scope is active, only paths under it participate. Back-compat:- // syncScopeRelPath is '' when scope == root, so inScope is always true and- // the filters below reduce to the pre-#774 behavior exactly.- const inScope = (p: string): boolean =>- !scoped || p === syncScopeRelPath || p.startsWith(syncScopeRelPath + '/');- // --exclude patterns match the SCOPE-relative path (what the user of a- // scoped source thinks in), same form runImport matches on full sync.- const scopeRel = (p: string): string =>- scoped && p.startsWith(syncScopeRelPath + '/') ? p.slice(syncScopeRelPath.length + 1) : p;- const excluded = (p: string): boolean =>- opts.exclude !== undefined && opts.exclude.length > 0 && matchesAnyGlob(scopeRel(p), opts.exclude);-- // Filter to syncable files (strategy-aware + scope-aware + exclude-aware)- const syncOpts = opts.strategy ? { strategy: opts.strategy } : undefined;+ // Scope/exclude/isSyncable filter lambdas (`inScope`/`scopeRel`/`excluded`/+ // `syncOpts`) are hoisted above the up_to_date gate — the untracked-gap+ // drift counter shares them so both apply identical predicates.// #1970 (F-C): a rename whose DESTINATION is unsyncable drops out of BOTH// `renamed` (only `r.to` is kept below) AND `deleted` (git emits it as `R`,// not `D`), leaving the OLD page stale. Fold the source side into the delete@@ -1292,6 +1388,34 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Syfiltered.renamed = filtered.renamed.map(r => ({ from: scopeRel(r.from), to: scopeRel(r.to) }));}+ // Working-tree mass-delete valve: merged working-tree deletes bypass the+ // full-reconcile valve (#2828), but the hazard is the same — a transient+ // uncommitted tree state (mid-rebase checkout, accidental rm -rf) hit by a+ // scheduled --working-tree/config sync must not sweep the source. Same+ // ratio + same env escape hatch. Deletes are skipped loudly; adds and+ // modifies still import, and committing the deletions (or+ // GBRAIN_ALLOW_MASS_RECONCILE=1) re-enables them.+ if (importWorkingTree && !detachedHead && filtered.deleted.length >= 10 && !massReconcileAllowed()) {+ try {+ const rows = await engine.executeRaw<{ count: number }>(+ opts.sourceId+ ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`+ : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,+ opts.sourceId ? [opts.sourceId] : [],+ );+ const pageCount = Number(rows[0]?.count ?? 0);+ if (pageCount > 0 && filtered.deleted.length > pageCount * MASS_RECONCILE_RATIO) {+ serr(+ `\n WARNING: refusing to delete ${filtered.deleted.length} page(s) from a working-tree ` ++ `sync (> ${Math.round(MASS_RECONCILE_RATIO * 100)}% of ${pageCount} page(s)). An uncommitted ` ++ `tree deleting this much is almost always transient (mid-rebase, accidental rm) — commit the ` ++ `deletions to apply them, or re-run with GBRAIN_ALLOW_MASS_RECONCILE=1. Adds/modifies still import.\n`,+ );+ filtered.deleted = [];+ }+ } catch { /* valve is best-effort — a count failure must not block the sync */ }+ }+// NAV-4: warn when --exclude filtered out every candidate change — almost// always a mistyped pattern, and otherwise indistinguishable from// "up to date" in the output.@@ -2469,8 +2593,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy} else {serr(`\nSync blocked: ${fileFailCount} file(s) failed to parse:\n` +- `${codeBreakdown}\n\n` +- `Fix the frontmatter and re-run, or use 'gbrain sync --skip-failed' to ` ++ `${codeBreakdown}\n${formatFailedFileList(failedFiles)}\n\n` ++ `Pinpoint a file with 'gbrain frontmatter validate <path>' (--fix auto-repairs), ` ++ `fix the frontmatter and re-run, or use 'gbrain sync --skip-failed' to ` +`acknowledge and move on. A file that keeps failing auto-skips after ` +`${resolveAutoSkipThreshold()} consecutive syncs.`,);@@ -2747,8 +2872,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SychunksCreated,embedded,pagesAffected,+ ...(totalChanges > 100 && embedSlugs.length > 0 ? { embedDeferralReason: 'large_sync' as const } : {}),malformedSkipped: malformedSkipped.length,...(typeWarningsEnabled && typeWarnings.length > 0 ? { type_warnings: typeWarnings } : {}),+ ...(uncommittedDrift ? { uncommitted: uncommittedDrift } : {}),};}@@ -2902,8 +3029,9 @@ async function performFullSync(} else {serr(`\nFull sync blocked: ${fileFailCount} file(s) failed:\n` +- `${codeBreakdown}\n\n` +- `Fix the YAML in those files and re-run, or use '--skip-failed'. A file ` ++ `${codeBreakdown}\n${formatFailedFileList(result.failures)}\n\n` ++ `Pinpoint a file with 'gbrain frontmatter validate <path>' (--fix auto-repairs), ` ++ `fix the YAML and re-run, or use '--skip-failed'. A file ` +`that keeps failing auto-skips after ${resolveAutoSkipThreshold()} consecutive syncs.`,);}@@ -3205,6 +3333,14 @@ Options:--include-gitignored Include otherwise-syncable files matched by .gitignore.Forces a full filesystem walk so periodic syncs seeignored untracked content.+ --working-tree Also import uncommitted working-tree state (untracked+ files + uncommitted edits/deletes). Default: committed+ changes only — uncommitted drift is counted and warned,+ never silently ignored. Persist with+ 'gbrain config set sync.include_working_tree true'.+ Caution: imports untracked files as-is — unignored+ scratch files and secrets included; review 'git status'+ before enabling, especially as persisted config.--dry-run Show what would be synced without writing.--skip-failed Acknowledge previously-recorded sync failures sothe bookmark can advance past unparseable files.@@ -3270,6 +3406,11 @@ See also:const retryFailed = args.includes('--retry-failed');const noSchemaPack = args.includes('--no-schema-pack'); // v0.41.37.0 #1569const includeGitignored = args.includes('--include-gitignored');+ // Untracked-gap fix: --working-tree imports uncommitted working-tree state.+ // The config fallback (sync.include_working_tree) resolves inside+ // performSync so every caller honors it; the CLI passes undefined when the+ // flag is absent.+ const workingTree = args.includes('--working-tree') ? true : undefined;const syncAll = args.includes('--all');let missingPathMode: MissingPathMode = 'fail';try {@@ -3347,7 +3488,16 @@ See also:process.exit(worstExit);}const sourceArg = args.find((a, i) => args[i - 1] === '--source');- const sourceId = sourceArg ?? 'default';+ // #4412: this branch used to hardcode `sourceArg ?? 'default'` while the+ // sync itself resolves through the full ambient chain (--source >+ // GBRAIN_SOURCE > dotfile > cwd > sole-non-default). Under+ // GBRAIN_SOURCE=<src>, `sync --force-break-lock` inspected+ // gbrain-sync:default — absent — printed "nothing to break", exit 0, and+ // left the dead holder's row on gbrain-sync:<src>; the follow-up sync+ // then refused for the 60s takeover grace. Resolve the SAME source the+ // sync would lock.+ const { resolveSourceWithTier: resolveBreakSource } = await import('../core/source-resolver.ts');+ const sourceId = (await resolveBreakSource(engine, sourceArg || null)).source_id;const lockKey = `gbrain-sync:${sourceId}`;const exit = await runBreakLock(engine, lockKey, sourceId, {force: forceBreakLock,@@ -3564,23 +3714,6 @@ See also:const { isFederatedV2Enabled } = await import('../core/feature-flags.ts');const v2Enabled = await isFederatedV2Enabled(engine);- // v0.42.42.0 (#2139) cost gate — shared `runInlineCostGate`. Under- // federated_v2 + parallel, embedding is DEFERRED to per-source backfill- // jobs (own spend cap) so the gate is FYI-only. Inline mode (v2 off, or- // --serial without --no-embed) gates on the DELTA estimate: below floor- // proceeds; above floor in a non-TTY/--json session AUTO-DEFERS embeds- // (exit 0, never exit 2 — the wedged-cron fix); a TTY prompts. Skipped- // entirely when --no-embed is set.- let autoDeferEmbeds = false;- if (!noEmbed) {- const mode = willEmbedSynchronously({ v2Enabled, serialFlag, noEmbed });- const gate = await runInlineCostGate(engine, {- sources, mode, dryRun, jsonOut, yesFlag, full, includeGitignored, label: 'sync --all',- });- if (gate.action === 'stop') return;- autoDeferEmbeds = gate.autoDeferEmbeds;- }-// v0.40.5.0 Federated Sync v2 (master) + v0.40.6.0 layering (this branch):// master added parallel fan-out via pMapAllSettled, embed-backfill auto-// submit, --serial / --max-sources / --no-auto-embed flags, and feature-@@ -3645,6 +3778,20 @@ See also:return;}+ // v0.42.42.0 (#2139) cost gate — shared with single-source sync. Above+ // the floor, non-interactive runs keep importing (never exit 2), but the+ // delivery statement is capability-aware: background queue only when a+ // worker can drain it, otherwise an exact manual command.+ const embedPlan = await resolveSyncAllEmbedPlan(engine, runnableSources, {+ v2Enabled, serialFlag, noEmbed, noAutoEmbed, dryRun, jsonOut, yesFlag, full, includeGitignored,+ });+ if (embedPlan.stop) return;+ const {+ workerSurface: backfillSurface, fanOutEligible, effectiveNoEmbed, shouldBackfill,+ } = embedPlan;++ const embedBackfillBySource = new Map<string, SyncEmbedBackfillOutcome>();+// Per-source result accumulator for the optional --json envelope.type PerSourceResult = {sourceId: string;@@ -3673,13 +3820,8 @@ See also:const runOne = async (src: typeof sources[number]): Promise<SyncResult> => {const cfg = (src.config || {}) as { strategy?: 'markdown' | 'code' | 'auto' };- // D18: parallel path defers embed; auto-enqueue embed-backfill after.- // v0.42.42.0 (#2139): `autoDeferEmbeds` (the inline gate tripped in a- // non-TTY session) ALSO forces deferral — global by design (the gate's- // decision unit is the aggregate estimate; deferral strictly dominates- // the exit-2 it replaced for every source).- const effectiveNoEmbed =- (v2Enabled && !serialFlag && !noEmbed ? true : noEmbed) || autoDeferEmbeds;+ // D18/#2139: planned fan-out or a cost-gate auto-defer skips inline+ // embedding; the post-run delivery below reports/queues each source.// v0.41.13.0 (T6 / D-V3-3 / D-V4-mech-6) — per-source AbortController.//// When the user passes --timeout, each source gets its OWN@@ -3709,6 +3851,7 @@ See also:noExtract,skipFailed, retryFailed, noSchemaPack,includeGitignored,+ workingTree,sourceId: src.id,strategy: cfg.strategy,concurrency,@@ -3739,31 +3882,25 @@ See also:) {manageGitignoreAtGitRoot(src.local_path!, engine.kind);}- // D18: auto-enqueue embed-backfill per source (unless opted out).- // v0.41.13.0 (T7 / D-V3-5): partial excluded — the next clean sync- // re-walks the diff and re-decides whether to enqueue embed for- // pages whose content actually changed.- // v0.42.42.0 (#2139): `autoDeferEmbeds` enqueues even on the v2-OFF- // legacy path — otherwise the gate's auto-defer would strand- // NULL-embedded chunks with no queued job to embed them.+ // Deliver planned or intrinsic >100-file deferrals. Intrinsic delivery+ // is v2-only on worker-backed engines; no-worker engines still need a+ // manual outcome. This preserves the worker-backed v2-off rollback.if (- (v2Enabled || autoDeferEmbeds) &&- !noAutoEmbed &&+ (shouldBackfill || (+ result.embedDeferralReason === 'large_sync' &&+ (v2Enabled || backfillSurface.status === 'no_worker_surface')+ )) &&!dryRun &&result.status !== 'dry_run' &&result.status !== 'up_to_date' &&result.status !== 'partial') {try {- const { submitEmbedBackfill } = await import('../core/embed-backfill-submit.ts');- const sub = await submitEmbedBackfill(engine, src.id, { reason: 'sync_all' });- if (sub.status === 'submitted') {- writeHuman(` → embed-backfill job ${sub.jobId} queued for ${src.name}`);- } else if (sub.status === 'cooldown') {- writeHuman(` → embed-backfill skipped (cooldown) for ${src.name}`);- } else if (sub.status === 'spend_capped') {- writeHuman(` → embed-backfill skipped (24h spend cap $${sub.spendCapUsd}) for ${src.name}`);- }+ const outcome = await resolveSyncEmbedBackfill(engine, src.id, {+ reason: 'sync_all', autoSubmitDisabled: noAutoEmbed,+ });+ embedBackfillBySource.set(src.id, outcome);+ writeHuman(` → ${formatSyncEmbedBackfillOutcome(outcome, src.name)}`);} catch (e) {process.stderr.write(` → embed-backfill submission failed for ${src.name}: ${e instanceof Error ? e.message : String(e)}\n`);}@@ -3771,9 +3908,6 @@ See also:return result;};- const parallelEligible =- v2Enabled && !serialFlag && engine.kind !== 'pglite' && runnableSources.length > 1;-// v0.42.42.0 (#2139, D13C): the v0.40.6.0 (D15) refusal of --skip-failed /// --retry-failed under parallel sync is LIFTED. It existed because the// failure ledger was once brain-global with racing acks; #1939 made the@@ -3785,13 +3919,13 @@ See also:// Effective parallelism — surfaced in the --json envelope so consumers// know how the run was actually dispatched. 1 in the serial fallback,// capped at min(sourceCount, --max-sources, 8) in the parallel path.- const effectiveParallel = parallelEligible+ const effectiveParallel = fanOutEligible? Math.min(runnableSources.length, maxSources ?? 8): 1;process.on('SIGINT', onAllSigint);try {- if (parallelEligible) {+ if (fanOutEligible) {const { pMapAllSettled } = await import('../core/parallel.ts');const cap = effectiveParallel;@@ -3898,6 +4032,9 @@ See also:...(r.result.type_warnings ? { type_warnings: r.result.type_warnings } : {}),} : {}),...(r.error ? { error: r.error } : {}),+ ...(embedBackfillBySource.has(r.sourceId)+ ? { embed_backfill: embedBackfillBySource.get(r.sourceId) }+ : {}),}));console.log(JSON.stringify({schema_version: 1,@@ -3940,7 +4077,7 @@ See also:const singleSourceInterrupt = new AbortController();const onSingleSourceSigint = () => { try { singleSourceInterrupt.abort(new Error('SIGINT')); } catch { /* */ } };const opts: SyncOpts = {- repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, noSchemaPack, includeGitignored, sourceId,+ repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, noSchemaPack, includeGitignored, workingTree, sourceId,strategy: strategyArg, concurrency,srcSubpath,exclude: excludePatterns.length > 0 ? excludePatterns : undefined,@@ -3956,22 +4093,25 @@ See also:// the gate can never wedge an existing cron; it converts silent ungated// inline spend into informed inline-or-deferred spend.let singleSourceAutoDefer = false;+ let singleSourceNoWorkerSurface = false;if (!noEmbed && !dryRun && !watch) {const gateRows = await engine.executeRaw<{ local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null }>(`SELECT local_path, config, last_commit, chunker_version FROM sources WHERE id = $1`,[sourceId],);if (gateRows.length > 0) {- const gateSources = [{+ const gate = await resolveSingleSyncEmbedPlan(engine, {+ sourceId,local_path: gateRows[0].local_path ?? repoPath ?? null,config: gateRows[0].config ?? {},last_commit: gateRows[0].last_commit,chunker_version: gateRows[0].chunker_version,- }];- const gate = await runInlineCostGate(engine, {- sources: gateSources, mode: 'inline', dryRun: false, jsonOut, yesFlag, full, includeGitignored, label: 'sync',+ }, {+ dryRun: false,+ jsonOut, yesFlag, full, includeGitignored, noAutoEmbed,});- if (gate.action === 'stop') return;+ singleSourceNoWorkerSurface = gate.workerSurface.status === 'no_worker_surface';+ if (gate.stop) return;if (gate.autoDeferEmbeds) {opts.noEmbed = true;singleSourceAutoDefer = true;@@ -4007,7 +4147,7 @@ See also:if (singleSourceTimer !== undefined) clearTimeout(singleSourceTimer);process.off('SIGINT', onSingleSourceSigint);}- printSyncResult(result);+ printSyncResult(result, jsonOut ? process.stderr : process.stdout);// #3068: a pull_failed partial is NOT a success — unlike timeout-class// partials (which converge on retry), a failing pull will not self-heal.// Exit non-zero so cron/monitoring sees the wedge instead of a green run.@@ -4043,24 +4183,27 @@ See also:// v0.42.42.0 (#2139, Step 4b): the inline gate auto-deferred this run's// embeds (non-TTY, above floor) — enqueue a capped backfill job so the// NULL-embedded chunks get embedded out of band instead of being stranded.+ let singleEmbedBackfill: SyncEmbedBackfillOutcome | undefined;if (- singleSourceAutoDefer &&+ (singleSourceAutoDefer || (+ singleSourceNoWorkerSurface && result.embedDeferralReason === 'large_sync'+ )) &&result.status !== 'dry_run' &&result.status !== 'up_to_date' &&result.status !== 'partial') {try {- const { submitEmbedBackfill } = await import('../core/embed-backfill-submit.ts');- const sub = await submitEmbedBackfill(engine, sourceId, { reason: 'sync_autodefer' });- if (sub.status === 'submitted') {- process.stderr.write(` → embed-backfill job ${sub.jobId} queued (deferred inline embed).\n`);- } else if (sub.status === 'cooldown') {- process.stderr.write(` → embed-backfill skipped (cooldown); run \`gbrain embed --stale\` to drain now.\n`);- }+ singleEmbedBackfill = await resolveSyncEmbedBackfill(engine, sourceId, {+ reason: 'sync_autodefer', autoSubmitDisabled: noAutoEmbed,+ });+ process.stderr.write(` → ${formatSyncEmbedBackfillOutcome(singleEmbedBackfill)}.\n`);} catch (e) {process.stderr.write(` → embed-backfill submission failed: ${e instanceof Error ? e.message : String(e)}\n`);}}+ if (jsonOut) {+ console.log(JSON.stringify(buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill)));+ }return;}@@ -4237,6 +4380,8 @@ export async function syncOneSource(/** v0.42.7 #1696: propagate --no-extract into every per-source sync. */noExtract?: boolean;includeGitignored?: boolean;+ /** Untracked-gap fix: propagate --working-tree into every per-source sync. */+ workingTree?: boolean;},): Promise<{ result: SyncResult; log: string }> {const cfg = (src.config || {}) as { strategy?: 'markdown' | 'code' | 'auto' };@@ -4252,6 +4397,7 @@ export async function syncOneSource(retryFailed: shared.retryFailed,noSchemaPack: shared.noSchemaPack,includeGitignored: shared.includeGitignored,+ workingTree: shared.workingTree,sourceId: src.id,strategy: cfg.strategy,concurrency: shared.concurrency,@@ -4464,20 +4610,28 @@ async function maybeExtractionNudge(engine: BrainEngine, sourceId?: string): Pro* Render a SyncResult to a Writable sink.** `sink` defaults to `process.stdout` so existing single-source callers- * see identical output. The `--all` parallel path passes `process.stderr`- * when `--json` is set, so banners stay off stdout and the JSON envelope- * pipes cleanly through `jq` (D4).+ * see identical output. The `--all` and single-source paths pass+ * `process.stderr` when `--json` is set, so banners stay off stdout and the+ * JSON envelope pipes cleanly through `jq` (D4).*/export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = process.stdout) {const write = (line: string) => sink.write(line + '\n');+ const writeUncommittedNote = (u: NonNullable<SyncResult['uncommitted']>) =>+ write(+ ` NOTE: ${u.added + u.modified + u.deleted} uncommitted file(s) not synced ` ++ `(${u.added} untracked/added, ${u.modified} modified, ${u.deleted} deleted) — ` ++ `commit them or run 'gbrain sync --working-tree'.`,+ );switch (result.status) {case 'up_to_date':write('Already up to date.');+ if (result.uncommitted) writeUncommittedNote(result.uncommitted);break;case 'synced':write(`Synced ${result.fromCommit?.slice(0, 8)}..${result.toCommit.slice(0, 8)}:`);write(` +${result.added} added, ~${result.modified} modified, -${result.deleted} deleted, R${result.renamed} renamed`);write(` ${result.chunksCreated} chunks created${result.embedded > 0 ? `, ${result.embedded} pages embedded` : ''}`);+ if (result.uncommitted) writeUncommittedNote(result.uncommitted);break;case 'first_sync':write(`First sync complete. Checkpoint: ${result.toCommit.slice(0, 8)}`);@@ -4498,7 +4652,7 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = p`Do NOT use --skip-failed for provider errors.`,);} else {- write(` Fix the files then re-run 'gbrain sync', or 'gbrain sync --skip-failed' to move on.`);+ write(` Pinpoint with 'gbrain frontmatter validate <path>', fix, then re-run 'gbrain sync', or 'gbrain sync --skip-failed' to move on.`);}break;}diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex 8866886444..13c1292e9a 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -687,6 +687,16 @@ async function cmdExtract(engine: BrainEngine, rest: string[]): Promise<void> {process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);return;}+ // #4473: takes are markdown-canonical — pages the fence writer refused are+ // skipped (never written DB-only). Say so instead of silently undercounting.+ if (result.pages_skipped > 0) {+ const reasons = [...new Set(result.skipped.map((s) => s.reason))].join(', ');+ process.stderr.write(+ `[takes extract] ${result.pages_skipped} page(s) skipped (${reasons}) — takes are ` ++ `markdown-canonical; a page with no locatable .md file is not written. ` ++ `Configure sync.repo_path (or the source's local_path) and re-run.\n`,+ );+ }process.stdout.write(`takes extract --from-pages: ${result.claims_extracted} claim(s) from ${result.pages_scanned} page(s)` +(dryRun ? ' (dry-run)' : '') + '\n',diff --git a/src/commands/think.ts b/src/commands/think.tsindex ad6c7ca233..210868c8cc 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -55,8 +55,12 @@ Options:provider/model or a bare alias. An explicit --model thatcan't be resolved is a hard error (exit 1) — never asilent no-LLM degrade.+ --source <id> Scope evidence gathering to this source. An unknown+ or archived source is a hard error (exit 1).--since YYYY-MM-DD Start of temporal window--until YYYY-MM-DD End of temporal window+ --with-calibration Inject the active calibration profile (anti-bias rewrite)+ --calibration-holder <h> Holder whose calibration profile to use (default: self)--json Output as JSON--help Show this help@@ -72,8 +76,11 @@ prints what would have been the input (exit 0).return;}- // Strip flags from positional args- const flagNames = ['--anchor', '--rounds', '--model', '--since', '--until'];+ // Strip flags from positional args.+ // #4508: --source and --calibration-holder were MISSING here — the flag and+ // its value joined the positional question, so `think "q" --source X`+ // echoed `# --source X q` and silently ignored the scope.+ const flagNames = ['--anchor', '--rounds', '--model', '--since', '--until', '--source', '--calibration-holder'];const positional: string[] = [];for (let i = 0; i < args.length; i++) {const a = args[i];@@ -101,6 +108,9 @@ prints what would have been the input (exit 0).// profile gets injected per D22 placement (after retrieval, before question).const withCalibration = flagPresent(args, '--with-calibration');const calibrationHolder = flagValue(args, '--calibration-holder');+ // #4508: parse --source; validated (existence + shape) in the local branch+ // below where a real engine is available.+ const source = flagValue(args, '--source');if (take && !anchor) {console.error('--take requires --anchor (the take row needs a target page)');@@ -126,6 +136,14 @@ prints what would have been the input (exit 0).'with the `viaSubagent` context if you need persistence.',);}+ if (source !== undefined) {+ // #4508: the remote `think` op scopes by the server's session/auth, not+ // a per-call param — say so instead of silently dropping the flag.+ console.error(+ '[thin-client] --source is scoped by the remote server (session/auth) ' ++ 'and cannot be overridden per call — the flag is not forwarded.',+ );+ }const raw = await callRemoteTool(cfg!, 'think', {question, anchor, rounds, model, since, until,// save/take intentionally NOT forwarded — server would ignore them;@@ -134,8 +152,18 @@ prints what would have been the input (exit 0).result = unpackToolResult<any>(raw);} else {try {+ // #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.+ let sourceId: string | undefined;+ if (source !== undefined) {+ const { resolveSourceWithTier } = await import('../core/source-resolver.ts');+ sourceId = (await resolveSourceWithTier(engine, source)).source_id;+ }result = await runThink(engine, {question, anchor, rounds, save, take, model, since, until,+ // #4508: thread the validated scope (RunThinkOpts.sourceId).+ ...(sourceId ? { sourceId } : {}),// #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.tsindex 429f74cfc8..82048ba2fb 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -73,6 +73,8 @@ interface IngestCliOpts {all?: boolean;json?: boolean;quiet?: boolean;+ /** #4472: include gbrain's own claude-cli subprocess sessions in discovery. */+ includeSelf?: boolean;}/**@@ -112,6 +114,7 @@ export function parseIngestArgs(args: string[]): IngestCliOpts | { help: true }if (a === '--embed') { opts.embed = true; continue; }if (a === '--facts') { opts.facts = true; continue; }if (a === '--all') { opts.all = true; continue; }+ if (a === '--include-self') { opts.includeSelf = true; continue; }if (a === '--format') {const v = args[++i] as TranscriptFormat | undefined;if (!v || !FORMATS.includes(v)) {@@ -190,6 +193,9 @@ skip). Embedding is OFF by default; run the embed backfill later or opt in.--all Import every session log discovered under the harnessroots (claude/codex/openclaw projects + the hermes store)+ --include-self Also discover gbrain's OWN claude-cli subprocess sessions+ (recorded by Claude Code for the provider's scratch cwds;+ excluded by default to avoid a self-ingestion loop)--format F claude-code | codex | openclaw | hermes | chatgpt |claude-export (auto-detected when omitted)--dry-run Parse + redact + report; writes nothing@@ -342,7 +348,9 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {// histories); with it, import the discovered set.if (parsed.paths.length === 0) {const { discoverTranscriptFiles } = await import('../core/transcripts/discover.ts');- const discovered = discoverTranscriptFiles();+ // #4472: discovery excludes gbrain's own claude-cli subprocess sessions+ // (self-ingestion loop) unless --include-self is passed.+ const discovered = discoverTranscriptFiles(undefined, { includeSelf: parsed.includeSelf });if (discovered.length === 0) {console.log('discovery: no session logs found under the harness roots');return;diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 70e899f8e0..b0fe23edcc 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -666,14 +666,24 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {let enabled = false;if (isTty) {const { createInterface } = await import('readline');+ // #4318 residual: rl.close() must not run before the answer's+ // resolveAns() — the unguarded rl.on('close', ...) below would+ // otherwise settle the promise `false` first (the close event+ // fires synchronously during rl.close()), so an operator+ // pressing Enter to accept this [Y/n]-default-yes prompt would+ // always land on "declined" regardless of what they typed.enabled = await new Promise<boolean>((resolveAns) => {const rl = createInterface({ input: process.stdin, output: process.stdout });+ let answered = false;rl.question('[gbrain] Enable skill publishing now? (recommended) [Y/n] ', (answer) => {- rl.close();+ answered = true;const a = answer.trim().toLowerCase();resolveAns(a === '' || a === 'y' || a === 'yes');+ rl.close();+ });+ rl.on('close', () => {+ if (!answered) resolveAns(false);});- rl.on('close', () => resolveAns(false));});} else {console.log('[AGENT] Relay this to your operator. Recommended: enable it.');diff --git a/src/core/ai/anthropic-key.ts b/src/core/ai/anthropic-key.tsindex 64bd18e014..c1969b3a1a 100644--- a/src/core/ai/anthropic-key.ts+++ b/src/core/ai/anthropic-key.ts@@ -57,6 +57,16 @@ export function setGatewayAnthropicKeySnapshot(key: string | undefined): void {_gatewayEnvKeySnapshot = key;}+/**+ * Read-only view of the gateway env snapshot for presence probes (#3944+ * follow-up: chatApiKeyConfigured). A non-undefined value means a DB-plane+ * key was merged into the RUNNING gateway env — i.e. chat is actually+ * servable — without exposing a raw engine.getConfig read to the planner.+ */+export function getGatewayAnthropicKeySnapshot(): string | undefined {+ return _gatewayEnvKeySnapshot;+}+export function hasAnthropicKey(): boolean {return resolveAnthropicKey() !== undefined;}diff --git a/src/core/ai/capabilities.ts b/src/core/ai/capabilities.tsindex 3957b9f7ac..63cacbef97 100644--- a/src/core/ai/capabilities.ts+++ b/src/core/ai/capabilities.ts@@ -14,7 +14,7 @@* gateway's `toolLoop()` consumes to decide:* - REFUSE at submit when tool-calling is unsupported (D6 — useless loop)* - REFUSE at submit/dispatch when the recipe declares- * `supports_subagent_loop: false` (unstable tool_use_id through a proxy)+ * `supports_subagent_loop: false` (or a per-id predicate returns false)* - WARN at submit when prompt caching is unavailable (D6 — cost regression)* - INFO at submit when parallel tools unsupported (D6 — just slower)*@@ -112,9 +112,12 @@ export function getProviderCapabilities(modelString: string): ProviderCapabiliticonst promptCache = chat.supports_prompt_cache;+ const subagentLoop = chat.supports_subagent_loop;return {supportsToolCalling: chat.supports_tools === true,- supportsSubagentLoop: chat.supports_subagent_loop === true,+ supportsSubagentLoop: typeof subagentLoop === 'function'+ ? subagentLoop(parsed.modelId)+ : subagentLoop === true,supportsPromptCaching: typeof promptCache === 'function'? promptCache(parsed.modelId): promptCache === true,diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.tsindex d85bba182a..c3399b4e68 100644--- a/src/core/ai/chat-usage.ts+++ b/src/core/ai/chat-usage.ts@@ -60,11 +60,34 @@ export function currentChatPhase(): string | null {return __chatPhaseStore.getStore() ?? null;}-let _sink: ChatUsageSink | null = null;+/**+ * #4480: sink REGISTRY (stack), not a last-wins scalar. A multi-engine+ * process (migrate-engine source+target, doctor probes, tests) used to lose+ * its ledger permanently: the most recently created engine overwrote the+ * sink, and once that engine disconnected every later record was swallowed+ * by a closed engine. Registration now returns a deregister handle; the+ * engine factory calls it on engine.disconnect, restoring the previous live+ * sink. Records route to the TOP live entry (still single-writer —+ * simultaneous multi-brain attribution stays documented best-effort).+ */+interface SinkEntry { sink: ChatUsageSink }+let _sinks: SinkEntry[] = [];-/** Register (or clear, with null) the process-wide usage sink. Last wins. */+/** Register a usage sink. Returns an idempotent deregister handle. */+export function registerChatUsageSink(sink: ChatUsageSink): () => void {+ const entry: SinkEntry = { sink };+ _sinks.push(entry);+ return () => {+ _sinks = _sinks.filter((e) => e !== entry);+ };+}++/**+ * Legacy scalar API (tests + one-shot callers): clears the registry and+ * installs `sink` as the only entry (null = clear).+ */export function setChatUsageSink(sink: ChatUsageSink | null): void {- _sink = sink;+ _sinks = sink ? [{ sink }] : [];}/**@@ -108,7 +131,7 @@ export function recordChatUsage(input: {cache_write_tokens?: number;};}): void {- const sink = _sink;+ const sink = _sinks.length > 0 ? _sinks[_sinks.length - 1]!.sink : null;if (!sink) return;try {const record: ChatUsageRecord = {diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 3f47021dda..0c151f9ac2 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -31,12 +31,12 @@ import { createAnthropic } from '@ai-sdk/anthropic';import { createOpenAICompatible } from '@ai-sdk/openai-compatible';import { z } from 'zod';+import { truncateUtf8 } from '../text-safe.ts';import {BudgetTracker,extractUsageFromError as _extractUsageFromError,type BudgetKind,} from '../budget/budget-tracker.ts';-import type {AIGatewayConfig,EmbedMultimodalOpts,@@ -1783,7 +1783,7 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32Aconst resolveTarget = opts?.embeddingModel ?? getEmbeddingModel();const tracker = __budgetStore.getStore() ?? null;const { model, recipe, modelId } = await resolveEmbeddingProvider(resolveTarget);- const truncated = texts.map(t => (t ?? '').slice(0, MAX_CHARS));+ const truncated = texts.map(t => truncateUtf8(t ?? '', MAX_CHARS));// Reserve up front for the worst-case batch token count. Embeddings have// no output rate, so maxOutputTokens=0. record() at the end uses the@@ -2967,9 +2967,19 @@ export type ChatRole = 'system' | 'user' | 'assistant' | 'tool';* on the rebuilt part in toModelMessages(), and carried through the replay shim* (adaptContentBlocksToChatBlocks). Attached ONLY when the provider sent one —* blocks from providers without per-part state stay byte-identical.+ *+ * `reasoning` blocks are the same #4201 shape applied to OpenAI's Responses+ * API reasoning models (o-series, gpt-5.x family): every response `reasoning`+ * part carries `providerMetadata.openai.itemId` (+ optional+ * `reasoningEncryptedContent`), and OpenAI's server REJECTS a later turn whose+ * history has a `function_call` item with no matching `reasoning` item —+ * "Item '<fc_id>' of type 'function_call' was provided without its required+ * 'reasoning' item: '<rs_id>'." A reasoning-model tool-loop conversation dies+ * on turn 2 without this: `chat()` previously never captured the part at all.*/export type ChatBlock =| { type: 'text'; text: string; providerMetadata?: Record<string, unknown> }+ | { type: 'reasoning'; text: string; providerMetadata?: Record<string, unknown> }| { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown; providerMetadata?: Record<string, unknown> }| { type: 'tool-result'; toolCallId: string; toolName: string; output: unknown; isError?: boolean; providerMetadata?: Record<string, unknown> };@@ -3085,15 +3095,16 @@ export function toModelMessages(messages: ChatMessage[]): unknown[] {}return {role: m.role,- // Drop text blocks whose `text` isn't a string: reasoning models- // (DeepSeek v4, etc.) surface `text: null/undefined` thinking parts that- // AI SDK v6's Zod schema rejects, poisoning the whole call. `''` is valid- // and kept.+ // Drop text/reasoning blocks whose `text` isn't a string: reasoning+ // models (DeepSeek v4, etc.) surface `text: null/undefined` thinking+ // parts that AI SDK v6's Zod schema rejects, poisoning the whole call.+ // `''` is valid and kept.content: blocks- .filter((b) => b.type !== 'text' || typeof b.text === 'string')+ .filter((b) => (b.type !== 'text' && b.type !== 'reasoning') || typeof b.text === 'string').map((b) => {// #4201: `providerOptions` echoes per-part provider state (e.g.- // Gemini 3.x thoughtSignature) — attached only when captured.+ // Gemini 3.x thoughtSignature, OpenAI reasoning-item id) — attached+ // only when captured.if (b.type === 'text') {return {type: 'text' as const,@@ -3101,6 +3112,13 @@ export function toModelMessages(messages: ChatMessage[]): unknown[] {...(b.providerMetadata ? { providerOptions: b.providerMetadata } : {}),};}+ if (b.type === 'reasoning') {+ return {+ type: 'reasoning' as const,+ text: b.text,+ ...(b.providerMetadata ? { providerOptions: b.providerMetadata } : {}),+ };+ }if (b.type === 'tool-call') {return {type: 'tool-call' as const,@@ -3781,13 +3799,16 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {if (Array.isArray(rawContent) && rawContent.length > 0) {for (const part of rawContent) {// #4201: capture per-part providerMetadata (Gemini 3.x thoughtSignature- // arrives on functionCall/text parts and must be echoed back next turn).- // `reasoning` parts stay deliberately dropped: the echo requirement is- // on functionCall parts; reasoning text never re-enters the transcript.+ // and OpenAI reasoning-item ids arrive on functionCall/reasoning/text+ // parts and must be echoed back next turn — see the ChatBlock doc+ // comment for the OpenAI Responses API's specific requirement).const partMeta = part.providerMetadata && typeof part.providerMetadata === 'object'? { providerMetadata: part.providerMetadata as Record<string, unknown> }: {};if (part.type === 'text') blocks.push({ type: 'text', text: part.text, ...partMeta });+ else if (part.type === 'reasoning') {+ blocks.push({ type: 'reasoning', text: typeof part.text === 'string' ? part.text : '', ...partMeta });+ }else if (part.type === 'tool-call') {blocks.push({type: 'tool-call',diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.tsindex 540b779d9a..59b885bfee 100644--- a/src/core/ai/providers/claude-cli-language-model.ts+++ b/src/core/ai/providers/claude-cli-language-model.ts@@ -36,8 +36,11 @@import { randomUUIDv7 } from 'bun';import { spawn } from 'node:child_process';import { mkdirSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';+import {+ claudeCliConfigDir,+ claudeCliCwdDir,+ sweepDeadClaudeCliScratchDirs,+} from './claude-cli-scratch.ts';import type {LanguageModelV2,LanguageModelV2CallOptions,@@ -51,10 +54,17 @@ import type {function claudeBin(): string {return process.env.GBRAIN_CLAUDE_CLI_BIN ?? 'claude';}-const CLAUDE_CWD = join(tmpdir(), `gbrain-claude-cli-cwd-${process.pid}`);+// #4472: the per-PID dir names + the transcript-fingerprint predicate live in+// claude-cli-scratch.ts so transcript discovery can exclude the sessions these+// subprocess cwds mint under ~/.claude/projects/ without importing this module.+const CLAUDE_CWD = claudeCliCwdDir();let cwdEnsured = false;function ensureCleanCwd(): string {if (!cwdEnsured) {+ // #4472: the per-PID naming leaks one scratch dir per crashed/killed+ // gbrain process forever — sweep dead-PID leftovers once per process at+ // provider init. Best-effort: a sweep failure never breaks a chat call.+ try { sweepDeadClaudeCliScratchDirs(); } catch { /* best-effort */ }mkdirSync(CLAUDE_CWD, { recursive: true });cwdEnsured = true;}@@ -62,7 +72,7 @@ function ensureCleanCwd(): string {}// #4119 — opt-in hermetic config dir for the child. See resolveHermeticConfigDir.-const CLAUDE_HERMETIC_CONFIG = join(tmpdir(), `gbrain-claude-cli-config-${process.pid}`);+const CLAUDE_HERMETIC_CONFIG = claudeCliConfigDir();let hermeticEnsured = false;/*** Resolve the CLAUDE_CONFIG_DIR the child should run with whendiff --git a/src/core/ai/providers/claude-cli-scratch.ts b/src/core/ai/providers/claude-cli-scratch.tsnew file mode 100644index 0000000000..0c0ae1aba9--- /dev/null+++ b/src/core/ai/providers/claude-cli-scratch.ts@@ -0,0 +1,92 @@+/**+ * #4472 — the claude-cli provider's per-PID scratch dirs, split into a tiny+ * dependency-light module so transcript discovery (src/core/transcripts/+ * discover.ts) can recognize the fingerprint without importing the whole+ * provider (and its @ai-sdk surface).+ *+ * Why discovery must know: each `claude --print` subprocess runs with+ * cwd = <tmpdir>/gbrain-claude-cli-cwd-<pid> (context isolation — no local+ * CLAUDE.md to auto-discover), and Claude Code records a session transcript+ * for that cwd under ~/.claude/projects/<slugified-cwd>/. Those sessions are+ * gbrain's OWN internal LLM calls — importing them back into the brain 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 fingerprint.+ */++import { readdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++/** Basename prefix of the per-PID cwd the claude-cli subprocess runs in. */+export const CLAUDE_CLI_CWD_PREFIX = 'gbrain-claude-cli-cwd-';+/** Basename prefix of the per-PID hermetic CLAUDE_CONFIG_DIR (#4119). */+export const CLAUDE_CLI_CONFIG_PREFIX = 'gbrain-claude-cli-config-';++/** The per-PID scratch cwd path for this process. */+export function claudeCliCwdDir(pid: number = process.pid): string {+ return join(tmpdir(), `${CLAUDE_CLI_CWD_PREFIX}${pid}`);+}++/** The per-PID hermetic-config scratch path for this process (#4119). */+export function claudeCliConfigDir(pid: number = process.pid): string {+ return join(tmpdir(), `${CLAUDE_CLI_CONFIG_PREFIX}${pid}`);+}++/**+ * True when a discovered transcript path belongs to a gbrain claude-cli+ * subprocess session (the slugified scratch-cwd fingerprint appears in the+ * harness project dir).+ */+export function isClaudeCliSelfTranscriptPath(path: string): boolean {+ return path.includes(CLAUDE_CLI_CWD_PREFIX);+}++function isPidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (err) {+ // EPERM = alive but owned by another user; anything else (ESRCH) = dead.+ return (err as NodeJS.ErrnoException).code === 'EPERM';+ }+}++/**+ * Sweep dead-PID scratch dirs (cwd + hermetic-config) left behind by+ * crashed/killed gbrain processes — the per-PID naming means nothing ever+ * reclaimed them. Called once at provider init; every step is best-effort+ * (a sweep failure must never break a chat call). Returns the number of+ * dirs removed. `baseDir` is injectable for tests.+ */+export function sweepDeadClaudeCliScratchDirs(baseDir: string = tmpdir()): number {+ let removed = 0;+ let entries: string[];+ try {+ entries = readdirSync(baseDir);+ } catch {+ return 0;+ }+ for (const name of entries) {+ const prefix = name.startsWith(CLAUDE_CLI_CWD_PREFIX)+ ? CLAUDE_CLI_CWD_PREFIX+ : name.startsWith(CLAUDE_CLI_CONFIG_PREFIX)+ ? CLAUDE_CLI_CONFIG_PREFIX+ : null;+ if (!prefix) continue;+ const pidText = name.slice(prefix.length);+ if (!/^\d+$/.test(pidText)) continue; // not our naming shape — leave it+ const pid = Number(pidText);+ if (!Number.isSafeInteger(pid) || pid <= 0) continue;+ if (pid === process.pid) continue;+ if (isPidAlive(pid)) continue;+ try {+ rmSync(join(baseDir, name), { recursive: true, force: true });+ removed++;+ } catch {+ /* best-effort */+ }+ }+ return removed;+}diff --git a/src/core/ai/recipes/index.ts b/src/core/ai/recipes/index.tsindex ccdf487d7c..ab43ee4a1b 100644--- a/src/core/ai/recipes/index.ts+++ b/src/core/ai/recipes/index.ts@@ -25,6 +25,7 @@ import { zhipu } from './zhipu.ts';import { azureOpenAI } from './azure-openai.ts';import { zeroentropyai } from './zeroentropyai.ts';import { llamaServerReranker } from './llama-server-reranker.ts';+import { nan } from './nan.ts';import { moonshot } from './moonshot.ts';import { mistral } from './mistral.ts';import { nvidia } from './nvidia.ts';@@ -50,6 +51,7 @@ const ALL: Recipe[] = [zhipu,azureOpenAI,zeroentropyai,+ nan,moonshot,mistral,nvidia,diff --git a/src/core/ai/recipes/nan.ts b/src/core/ai/recipes/nan.tsnew file mode 100644index 0000000000..58c30263a1--- /dev/null+++ b/src/core/ai/recipes/nan.ts@@ -0,0 +1,54 @@+import type { Recipe } from '../types.ts';++/**+ * nan.builders (https://api.nan.builders) reranker. OpenAI-compatible+ * surface: `POST {base}/v1/rerank` with `{model, query, documents, top_n?}`,+ * response `{results: [{index, relevance_score}]}` — rides+ * gateway.rerank()'s native path with only the recipe-pluggable `path`+ * override (v0.40.6.1).+ *+ * Live-verified 2026-08-22 against the hosted endpoint: `/v1/rerank` with+ * model `rerank` (a Qwen3-Reranker-8B deployment) returns 200+ * `results[].relevance_score`. The base URL already ends in `/v1`, so+ * `${base_url}${path}` → `…/v1/rerank`. Bare `/rerank` and+ * `/compatible-api/v1/reranks` both 404 — only the `/v1`-anchored leaf+ * serves rerank.+ *+ * This is a SEPARATE recipe, reranker-only in scope: it declares only the+ * `reranker` touchpoint and no embedding surface. nan.builders does expose an+ * OpenAI-compatible embeddings surface on the same base URL; it is simply not+ * added here — rerank is the use case behind this recipe, and an embedding+ * recipe can be added later without touching this one.+ *+ * The model id is the literal `rerank`. Auth is `NAN_API_KEY` (the name the+ * provider's own docs use; matches the repo's <PROVIDER>_API_KEY convention).+ * No per-1M price is declared — the service is quota-based, so the budget+ * tracker treats it as unpriced (warn-once path) unless a caller sets a cap.+ */+export const nan: Recipe = {+ id: 'nan',+ name: 'nan.builders (reranker)',+ tier: 'openai-compat',+ implementation: 'openai-compatible',+ base_url_default: 'https://api.nan.builders/v1',+ auth_env: {+ required: ['NAN_API_KEY'],+ setup_url: 'https://nan.builders/docs/getting-started',+ },+ touchpoints: {+ reranker: {+ // Model id served by nan.builders today (Qwen3-Reranker-8B).+ models: ['rerank'],+ default_model: 'rerank',+ // Defensive ceiling; gateway pre-flights and fails open.+ max_payload_bytes: 5_000_000,+ // Openai-compatible leaf: `{base}/v1/rerank`.+ path: '/rerank',+ // Hosted API: cross-region latency can exceed the 5s gateway default.+ default_timeout_ms: 30_000,+ },+ },+ setup_hint:+ 'Get an API key at https://nan.builders/ (docs: https://nan.builders/docs/getting-started), ' ++ 'then `export NAN_API_KEY=...` and `gbrain config set search.reranker.model nan:rerank`.',+};diff --git a/src/core/ai/recipes/nvidia.ts b/src/core/ai/recipes/nvidia.tsindex 1a8916a70a..bd833417aa 100644--- a/src/core/ai/recipes/nvidia.ts+++ b/src/core/ai/recipes/nvidia.ts@@ -58,6 +58,16 @@ export const nvidia: Recipe = {// supported via explicit embedding_dimensions (2048 or 4096).default_dims: 1024,dims_options: [1024, 2048, 4096],+ // #4530: hard per-INPUT token caps (distinct from the batch budget).+ // nv-embedqa-e5-v5 is an e5-family encoder with the original 512-token+ // pre-training context; the hosted endpoint rejects any single input+ // over it with a non-transient 400 ("Input length N exceeds maximum+ // allowed token size 512"). Declaring it here makes the chunker split+ // chunks to fit (resolveMaxChunkTokens). Only confirmed limits are+ // declared — models absent from the map keep the default cap.+ max_input_tokens: {+ 'nvidia/nv-embedqa-e5-v5': 512,+ },// Conservative split; hosted NVIDIA embedding endpoints require// input_type and may reject large payloads before tokenizing.max_batch_tokens: 8192,diff --git a/src/core/ai/recipes/ollama.ts b/src/core/ai/recipes/ollama.tsindex dbeb10c31f..83c342e928 100644--- a/src/core/ai/recipes/ollama.ts+++ b/src/core/ai/recipes/ollama.ts@@ -59,6 +59,7 @@ export const ollama: Recipe = {supports_tools: false,supports_subagent_loop: false,supports_prompt_cache: false,+ supports_structured_outputs: false,// Provider-wide routing ceiling only; Ollama still enforces each loaded// model's actual context window at request time.max_context_tokens: 128_000,diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.tsindex 69a35b19fc..b3ac723ea5 100644--- a/src/core/ai/recipes/openrouter.ts+++ b/src/core/ai/recipes/openrouter.ts@@ -47,6 +47,16 @@ export function openrouterRequiresExplicitPromptCache(modelId: string): booleanreturn modelId.trim().toLowerCase().startsWith('anthropic/claude-');}+/**+ * OpenRouter Anthropic routes share Anthropic's tool-call envelope (and the+ * gateway loop already keys replay on gbrain_tool_use_id, not the raw+ * provider id). Other proxied families stay refused until they get their+ * own live abort/retry evidence (TODOS.md OpenRouter follow-up).+ */+export function openrouterSupportsSubagentLoop(modelId: string): boolean {+ return modelId.trim().toLowerCase().startsWith('anthropic/');+}+/*** Rewrite the last system message's string content into OpenRouter's* documented Anthropic caching shape: a content-part array carrying@@ -147,14 +157,12 @@ export const openrouterCompatFetch = (async (* downstream agent stacks (OpenClaw deployments, etc.) get their own* attribution on OR's leaderboard instead of polluting gbrain's.*- * Subagent loops: `supports_subagent_loop: false` is enforced by- * `classifyCapabilities()` in `src/core/ai/capabilities.ts` — the subagent- * tier refuses OR-proxied models at submit or handler dispatch because tool_use_id- * stability across crashes/replays can't be guaranteed through the proxy.- * (The legacy Anthropic-direct path additionally gates on- * `isAnthropicProvider()` in `src/core/model-config.ts` when- * `agent.use_gateway_loop` is off.) Relaxing this is a deeper architectural- * change tracked in TODOS.md.+ * Subagent loops: Anthropic routes (`anthropic/…`) declare+ * `supports_subagent_loop` so classifyCapabilities() allows them. The+ * handler still refuses the Anthropic-direct SDK for `openrouter:*` and+ * auto-routes those jobs through `gateway.toolLoop()` — OR is not a native+ * Anthropic provider. Other OR families stay refused until they get a live+ * abort/retry pin (TODOS.md).*/export const openrouter: Recipe = {id: 'openrouter',@@ -240,8 +248,7 @@ export const openrouter: Recipe = {'deepseek/deepseek-chat',],supports_tools: true,- // Enforced — classifyCapabilities() refuses the subagent tier on this flag.- supports_subagent_loop: false,+ supports_subagent_loop: openrouterSupportsSubagentLoop,// Family-scoped: OpenAI routes cache automatically; Anthropic routes// cache via the compat fetch shim's cache_control rewrite.supports_prompt_cache: openrouterSupportsPromptCache,diff --git a/src/core/ai/types.ts b/src/core/ai/types.tsindex d7f134395a..b9846ccb99 100644--- a/src/core/ai/types.ts+++ b/src/core/ai/types.ts@@ -53,6 +53,20 @@ export interface EmbeddingTouchpoint {* `default_dims`, so a recipe can declare only the models it knows.*/model_dims?: Readonly<Record<string, number>>;+ /**+ * #4530: per-model maximum tokens PER SINGLE INPUT, keyed like model_dims+ * (partial by design — declare only the models whose limit is known).+ * Distinct from max_batch_tokens (whole-request budget): some hosted+ * encoders enforce a hard per-input cap far below any batch budget —+ * nvidia/nv-embedqa-e5-v5 rejects any single input over 512 tokens with a+ * non-transient 400, so chunks over the cap can never embed. When the+ * ACTIVE embedding model declares a value here, the markdown chunker caps+ * emitted chunks at floor(limit × EMBED_INPUT_SAFETY) estimated tokens+ * (resolveMaxChunkTokens in src/core/embedding-input-limit.ts) — SPLIT,+ * never truncated. Models absent from the map keep+ * DEFAULT_MAX_CHUNK_TOKENS.+ */+ max_input_tokens?: Readonly<Record<string, number>>;dims_options?: number[]; // for Matryoshka-aware providerscost_per_1m_tokens_usd?: number;price_last_verified?: string; // ISO date@@ -272,9 +286,11 @@ export interface ChatTouchpoint {supports_tools: boolean;/*** Stable enough across crashes/replays to drive a Minions subagent loop.- * Strictly stronger than supports_tools.+ * Strictly stronger than supports_tools. Boolean for recipe-wide behavior;+ * predicate when only some routed model ids are loop-safe (OpenRouter+ * Anthropic routes vs other proxied families).*/- supports_subagent_loop: boolean;+ supports_subagent_loop: boolean | ((modelId: string) => boolean);/*** Prompt caching honored for this chat touchpoint. Static booleans cover* native providers; openai-compatible aggregators may decide per model iddiff --git a/src/core/bench/correctness-gate.ts b/src/core/bench/correctness-gate.tsindex 017d82b37a..f8c4529281 100644--- a/src/core/bench/correctness-gate.ts+++ b/src/core/bench/correctness-gate.ts@@ -24,6 +24,7 @@ import {computeFirstRelevantHit,computeRecallAtK,DEFAULT_QRELS_THRESHOLDS,+ makeRef,refKey,type QrelsFile,type QrelsEntry,@@ -69,9 +70,9 @@ export interface CorrectnessResult {per_query: PerQueryResult[];}-/** Build the canonical `${source_id}::${slug}` set for a SearchResult-like array. */-function toRefKeySet(results: Array<{ source_id?: string; slug: string }>): string[] {- return results.map(r => `${r.source_id ?? 'default'}::${r.slug}`);+/** Build the canonical, insertion-ordered page-key set for a SearchResult-like array. */+function toRefKeySet(results: Array<{ source_id?: string; slug: string }>): Set<string> {+ return new Set(results.map(r => makeRef(r.source_id ?? 'default', r.slug)));}async function runOneQuery(@@ -83,7 +84,7 @@ async function runOneQuery(let retrieved: string[];try {const raw = await searchFn(engine, entry.query, { limit: k });- retrieved = toRefKeySet(raw);+ retrieved = [...toRefKeySet(raw)];} catch (err) {return {query_id: entry.query_id,diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.tsindex 34824df190..fc4ee69dc0 100644--- a/src/core/bootstrap/verify.ts+++ b/src/core/bootstrap/verify.ts@@ -864,26 +864,41 @@ async function checkHooksSmoke(engine: BrainEngine, ws: string, sourceId: string}let server: { close: () => void } | null = null;const prevSource = process.env.GBRAIN_SOURCE;+ const socketPath = resolveSocketPath(dataDir);+ // #4474: prefer the REAL socket. Pre-fix the smoke ALWAYS started its own+ // 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);try {- const secret = ensureIpcSecret(dataDir);- server = await startResolveIpcServer(- resolveSocketPath(dataDir),- {- resolve: async () => null,- turn_context: (req) =>- assembleTurnContext(engine, {- sourceId,- window: req.window,- ...(req.priorContextText !== undefined ? { priorContextText: req.priorContextText } : {}),- ...(req.sessionId !== undefined ? { sessionId: req.sessionId } : {}),- ...(req.maxBytes !== undefined ? { maxBytes: req.maxBytes } : {}),- }),- },- { secret, boundSourceId: sourceId },- );- if (!server) {- return { id, ok: true, warn: true, detail: 'could not bind the IPC socket (a live serve owns it?) — smoke skipped; the live serve itself is the IPC provider' };+ if (!liveSocket) {+ const secret = ensureIpcSecret(dataDir);+ server = await startResolveIpcServer(+ socketPath,+ {+ resolve: async () => null,+ turn_context: (req) =>+ assembleTurnContext(engine, {+ sourceId,+ window: req.window,+ ...(req.priorContextText !== undefined ? { priorContextText: req.priorContextText } : {}),+ ...(req.sessionId !== undefined ? { sessionId: req.sessionId } : {}),+ ...(req.maxBytes !== undefined ? { maxBytes: req.maxBytes } : {}),+ }),+ },+ { secret, boundSourceId: sourceId },+ );+ if (!server) {+ return { id, ok: true, warn: true, detail: 'could not bind the IPC socket (a live serve owns it?) — smoke skipped; the live serve itself is the IPC provider' };+ }}+ // Provenance suffix for every outcome below: which listener answered.+ const via = liveSocket+ ? 'via the live serve’s IPC socket'+ : `via a verify-owned IPC server (no live serve socket at ${socketPath} — hooks stay degraded (no_serve) until a running \`gbrain serve\` binds it)`;process.env.GBRAIN_SOURCE = sourceId;// USER_PROMPT_DEADLINE_MS is the hook's own budget — the smoke compares// against the same constant it enforces (no drifting hardcoded copy).@@ -903,22 +918,26 @@ async function checkHooksSmoke(engine: BrainEngine, ws: string, sourceId: stringif (elapsed >= USER_PROMPT_DEADLINE_MS) {// [A7] Real latency is a non-gating benchmark — the hard deadline// assertion lives in the hook tests against an injected slow-IPC stub.- return { id, ok: true, warn: true, detail: `context block delivered but in ${elapsed}ms (over the ${USER_PROMPT_DEADLINE_MS}ms budget on this box) — watch hook latency` };+ return { id, ok: true, warn: true, detail: `context block delivered but in ${elapsed}ms (over the ${USER_PROMPT_DEADLINE_MS}ms budget on this box) ${via} — watch hook latency` };}- return { id, ok: true, detail: `context block delivered in ${elapsed}ms (${out.trim().length} chars)` };+ // #4474: a self-provided listener is a plumbing-only pass — production+ // hooks still need a live serve to bind the socket, so it WARNS.+ return liveSocket+ ? { id, ok: true, detail: `context block delivered in ${elapsed}ms (${out.trim().length} chars) ${via}` }+ : { id, ok: true, warn: true, detail: `context block delivered in ${elapsed}ms (${out.trim().length} chars) ${via}` };}// Empty stdout must be a DOCUMENTED degradation — read the heartbeat it wrote.const tail = await readHeartbeatTail(1);const reason = tail[tail.length - 1]?.reason ?? 'empty_block';if (reason === 'empty_block' || reason === 'empty_window') {- return { id, ok: true, warn: true, detail: `empty context block in ${elapsed}ms (documented degradation: ${reason}) — plumbing works, brain has nothing to volunteer yet` };+ return { id, ok: true, warn: true, detail: `empty context block in ${elapsed}ms (documented degradation: ${reason}) ${via} — plumbing works, brain has nothing to volunteer yet` };}if (reason === 'deadline' || reason === 'ipc_unavailable' || reason === 'server_budget') {// [A7] Latency-shaped degradations don't gate verify (slow CI box ≠// broken install); the reason is named so a human can judge.- return { id, ok: true, warn: true, detail: `hook degraded on latency (${reason}) in ${elapsed}ms — non-gating; re-run on an idle machine if it persists` };+ return { id, ok: true, warn: true, detail: `hook degraded on latency (${reason}) in ${elapsed}ms ${via} — non-gating; re-run on an idle machine if it persists` };}- return { id, ok: false, detail: `hook degraded (${reason}) in ${elapsed}ms — stdin→IPC→stdout plumbing is not healthy` };+ return { id, ok: false, detail: `hook degraded (${reason}) in ${elapsed}ms ${via} — stdin→IPC→stdout plumbing is not healthy` };} catch (e) {return { id, ok: false, detail: `hooks smoke failed: ${(e as Error).message}` };} finally {diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.tsindex e7b5e15241..e41765eff6 100644--- a/src/core/brain-score-recommendations.ts+++ b/src/core/brain-score-recommendations.ts@@ -4,6 +4,7 @@ import { canonicalLookup } from './model-pricing.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from './embedding-pricing.ts';import { getRecipe } from './ai/recipes/index.ts';import { parseModelId } from './ai/model-resolver.ts';+import { getGatewayAnthropicKeySnapshot } from './ai/anthropic-key.ts';/*** v0.40.x: env-var name → file/DB config field, for hosted embedding providers@@ -57,19 +58,25 @@ export const HOSTED_EMBED_KEY_CONFIG: Record<string, string> = {*//*** #3944: chat-key presence for the remediation planner, judged on the planes- * both planner surfaces can rely on — process env + the FILE config plane.- * NOT `engine.getConfig()`: a DB-only `anthropic_api_key` is only usable on- * paths that ran the loadConfigWithEngine DB merge before configuring the- * gateway, and doctor's planner (remediation/context.ts) judges the file- * plane (#2662 is the same rule for embed keys). Pre-fix, autopilot read the- * DB plane here while doctor read the file plane, so autopilot dispatched- * chat jobs doctor classified as blocked. Shared by- * loadRecommendationContext and the autopilot dispatch loop.+ * both planner surfaces can rely on — process env, the FILE config plane,+ * and the gateway env snapshot (a DB-plane key that loadConfigWithEngine+ * already merged into the RUNNING gateway, i.e. a key that is actually+ * serving chat right now). NOT a raw `engine.getConfig()` read: a DB-only+ * key that never reached the gateway is unusable on planner paths, and the+ * raw read is what diverged autopilot from doctor pre-#3944 (doctor's+ * planner judges the file plane, #2662 is the same rule for embed keys).+ * The snapshot keeps both surfaces CONVERGENT — it flows through this one+ * shared helper — while a genuinely-usable key no longer reads as missing.+ * Shared by loadRecommendationContext and the autopilot dispatch loop.*/export function chatApiKeyConfigured(fileCfg: { anthropic_api_key?: unknown } | null | undefined,): boolean {- return !!(process.env.ANTHROPIC_API_KEY || fileCfg?.anthropic_api_key);+ return !!(+ process.env.ANTHROPIC_API_KEY ||+ fileCfg?.anthropic_api_key ||+ getGatewayAnthropicKeySnapshot()+ );}export function embeddingProviderConfigured(diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.tsindex 71e3c94249..8255170746 100644--- a/src/core/chunkers/code.ts+++ b/src/core/chunkers/code.ts@@ -20,6 +20,7 @@import { chunkText as recursiveChunk } from './recursive.ts';import { buildQualifiedName } from './qualified-names.ts';+import { MERGE_PROTECTED_SYMBOL_TYPES } from './def-types.ts';import { estimateTokens, estimateEmbedTokens, estimateEmbedTokensCeiling, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';import { safeSplitIndex } from '../text-safe.ts';import {@@ -132,7 +133,14 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:// TOP_LEVEL_TYPES / NESTED_EMIT_CONFIG, so decorated code emitted ZERO// semantic chunks and its text vanished from the index entirely. The bump// forces a full re-chunk so existing Python pages recover the lost symbols.-export const CHUNKER_VERSION = 5;+//+// v6 (#4511): mergeSmallSiblings no longer folds named definitions into+// anonymous `symbolType: 'merged'` chunks (merging nulls out symbol_name, so+// a merged definition was unreachable by code-def — a flat file of short+// top-level defs indexed to ZERO symbols). Chunk boundaries change for every+// previously-merged file, so the bump forces a re-chunk that recovers the+// erased symbols.+export const CHUNKER_VERSION = 6;// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)let Parser: typeof import('web-tree-sitter') | null = null;@@ -923,6 +931,16 @@ function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunk// header (empty parent path, but holds the class declaration) and to// nested leaves (non-empty parent path).const hasScopedChunks = chunks.some(c => (c.metadata.parentSymbolPath ?? []).length > 0);+ // #4511: merging nulls out symbolName, and code-def resolves names against+ // chunk rows, so a merged definition is unreachable — a flat file of short+ // top-level defs indexed to ZERO symbols (protection previously happened+ // only as a side effect of hasScopedChunks, which flat files never set).+ // Upstream intent is to merge import/const RUNS, not definitions — enforce+ // exactly that: a named definition never starts a merge group and is never+ // accumulated into one. The set is a derived view of code-def's DEF_TYPES+ // (def-types.ts), so the lookup allowlist and this guard cannot drift.+ const isDefChunk = (c: CodeChunk): boolean =>+ c.metadata.symbolName != null && MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType);const merged: CodeChunk[] = [];let i = 0;while (i < chunks.length) {@@ -934,7 +952,7 @@ function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunk// class body's 3 × 10-token methods are each their own chunk on// purpose — merging would erase the (in ClassName) scope header// Layer 6 just added.- if (currentTokens >= mergeThreshold || hasScopedChunks || currentIsScoped) {+ if (currentTokens >= mergeThreshold || hasScopedChunks || currentIsScoped || isDefChunk(current)) {merged.push({ ...current, index: merged.length });i++;continue;@@ -945,6 +963,7 @@ function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunklet j = i + 1;while (j < chunks.length) {const next = chunks[j]!;+ if (isDefChunk(next)) break; // #4511: never fold a definition into a runconst nextTokens = estimateTokens(next.text);if (groupTokens + nextTokens > chunkTarget) break;group.push(next);diff --git a/src/core/chunkers/def-types.ts b/src/core/chunkers/def-types.tsnew file mode 100644index 0000000000..fbf3254405--- /dev/null+++ b/src/core/chunkers/def-types.ts@@ -0,0 +1,80 @@+/**+ * Definition-shaped symbol types (normalized, post-`normalizeSymbolType`) —+ * the ONE list shared by `gbrain code-def`'s lookup allowlist+ * (src/commands/code-def.ts re-exports DEF_TYPES from here) and the chunker's+ * merge guard (#4511), so the two can't drift: a symbol type code-def can+ * resolve must never have its `symbol_name` erased by small-sibling merging.+ */++// v0.41 D2: SQL DDL targets (table/view/index/procedure/schema/database/+// trigger) are first-class definitions in the SQL sense. The chunker's+// normalizeSymbolType maps create_table → 'table' etc, so adding the SQL+// kinds here is what makes `gbrain code-def users` work against SQL.+// Method-level + member definitions. normalizeSymbolType only canonicalizes+// some node types; the rest fall through `type.replace(/_/g, ' ')`, so+// tree-sitter's method_declaration → 'method declaration', struct_specifier →+// 'struct specifier', protocol_declaration → 'protocol declaration', etc.+// Without these, code-def is blind to every method, constructor, field, C+// struct, and Swift protocol — which is most of an OO codebase. The plain+// 'struct' entry above never matched for the same reason (C emits the+// 'struct specifier' fallback form).+export const DEF_TYPES = [+ 'function', 'class', 'interface', 'type', 'enum', 'struct', 'trait', 'module', 'contract',+ 'table', 'view', 'index', 'procedure', 'schema', 'database', 'trigger',+ 'method declaration', 'method definition', 'constructor declaration',+ 'field declaration', 'field definition', 'struct specifier', 'protocol declaration',+ // Dart: normalizeSymbolType has no rule for these four, so they arrive as+ // the node type with underscores replaced. class_definition/enum_declaration/+ // type_alias/function_signature already normalize into the list above.+ 'mixin declaration', 'extension declaration',+ 'getter signature', 'setter signature',+ // #3789 residual audit — every remaining definition-shaped fallthrough of+ // normalizeSymbolType across TOP_LEVEL_TYPES + NESTED_EMIT_CONFIG. Without+ // these, symbols the chunker HAS indexed are invisible to code-def (Java+ // records, C#/Kotlin properties, Rust structs/traits, Go type declarations,+ // Solidity contracts — the bare 'contract'/'trait'/'struct' entries above+ // are never produced by normalizeSymbolType, only these fallthrough forms).+ 'property declaration', 'record declaration', // C#/Kotlin, Java+ 'struct declaration', 'object declaration', // C#/Swift, Kotlin+ 'namespace declaration', 'file scoped namespace declaration', // C#+ 'trait declaration', // PHP+ 'trait definition', 'object definition', // Scala+ 'contract declaration', 'modifier definition', 'event definition', // Solidity+ 'namespace definition', 'template declaration', 'declaration', 'preproc def', // C/C+++ 'type declaration', 'const declaration', 'var declaration', // Go+ 'struct item', 'trait item', 'impl item', 'mod item', // Rust+ 'type item', 'const item', 'static item', // Rust+ 'lexical declaration', 'variable declaration', // TS/JS top-level const/let/var+ 'local declaration', // Lua+];++/**+ * #4511 — DEF_TYPES entries that stay MERGEABLE: the small-declaration RUN+ * forms `mergeSmallSiblings` exists for (import runs, const/var runs, C+ * `#define`/prototype runs, Kotlin top-level `val` runs). Everything else in+ * DEF_TYPES names a substantive definition whose `symbol_name` must survive+ * chunk merging, or code-def can never find it again.+ */+const MERGEABLE_RUN_TYPES = new Set([+ 'lexical declaration', 'variable declaration', // TS/JS const/let/var+ 'const declaration', 'var declaration', // Go+ 'local declaration', // Lua+ 'declaration', 'preproc def', // C/C++ prototypes, globals, #define+ 'property declaration', // Kotlin top-level val/var+]);++/**+ * #4511 — symbol types `mergeSmallSiblings` must never fold into an anonymous+ * `symbolType: 'merged'` chunk (merging nulls out `symbol_name`, and code-def+ * resolves names against chunk rows, so a merged definition is unreachable).+ * Derived view of DEF_TYPES (minus the run forms above) plus the two wrapper+ * forms code-def also resolves: 'export statement' (TS/JS export wrapper, in+ * findCodeDef's SQL allowlist) and 'decorated definition' (Python decorator+ * wrapper — normally unwrapped to function/class, kept as a belt-and-braces+ * entry should the unwrap miss).+ */+export const MERGE_PROTECTED_SYMBOL_TYPES: ReadonlySet<string> = new Set([+ ...DEF_TYPES.filter((t) => !MERGEABLE_RUN_TYPES.has(t)),+ 'export statement',+ 'decorated definition',+]);diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex 703acb6acd..e8ca556ee6 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -53,6 +53,17 @@ export interface ChunkOptions {chunkSize?: number; // target words per chunk (default 300)chunkOverlap?: number; // overlap words (default 50)maxChars?: number; // hard cap on any chunk's char length (default 6000)+ /**+ * #4530: hard cap on any chunk's ESTIMATED embedding tokens (default+ * DEFAULT_MAX_CHUNK_TOKENS). Callers on strict per-input embedding models+ * (e.g. nvidia/nv-embedqa-e5-v5's 512) thread+ * resolveMaxChunkTokens() (src/core/embedding-input-limit.ts) so oversize+ * text is SPLIT to fit — never truncated, never left permanently+ * unembeddable. Chunk boundaries are unchanged for callers that don't pass+ * it (or whose model has no declared limit), so MARKDOWN_CHUNKER_VERSION+ * does not bump.+ */+ maxTokens?: number;}export interface TextChunk {@@ -78,6 +89,12 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {const chunkSize = opts?.chunkSize || 300;const chunkOverlap = opts?.chunkOverlap || 50;const maxChars = opts?.maxChars || 6000;+ // #4530: per-call token budget, clamped to the historical default so a+ // misconfigured larger value can't emit chunks the rest of the pipeline+ // (tsvector limits, context assembly) was never sized for.+ const maxTokens = opts?.maxTokens && opts.maxTokens > 0+ ? Math.min(opts.maxTokens, DEFAULT_MAX_CHUNK_TOKENS)+ : DEFAULT_MAX_CHUNK_TOKENS;if (!text || text.trim().length === 0) return [];@@ -95,7 +112,7 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {const wordCount = countWords(stripped);if (wordCount <= chunkSize) {// Single-chunk path: still apply the maxChars cap.- const capped = capByChars(stripped.trim(), maxChars);+ const capped = capByChars(stripped.trim(), maxChars, maxTokens);return capped.map((t, i) => ({ text: t, index: i }));}@@ -108,7 +125,7 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {// exceed 8192 OpenAI embedding tokens at any word count).const capped: string[] = [];for (const chunk of withOverlap) {- capped.push(...capByChars(chunk.trim(), maxChars));+ capped.push(...capByChars(chunk.trim(), maxChars, maxTokens));}return capped.map((t, i) => ({ text: t, index: i }));}@@ -139,19 +156,24 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {* safe" note rested on maxChars=6000 and stride=5500 both being even;* deriving the window from density retired that guarantee.)*/-function capByChars(text: string, maxChars: number, knownEst?: number): string[] {+function capByChars(+ text: string,+ maxChars: number,+ maxTokens: number = DEFAULT_MAX_CHUNK_TOKENS,+ knownEst?: number,+): string[] {if (text.length === 0) return [];const est = knownEst ?? probeEmbedTokens(text);- const window = est <= DEFAULT_MAX_CHUNK_TOKENS+ const window = est <= maxTokens? maxChars- : Math.max(1, Math.min(maxChars, Math.floor((text.length * DEFAULT_MAX_CHUNK_TOKENS) / est)));+ : Math.max(1, Math.min(maxChars, Math.floor((text.length * maxTokens) / est)));if (text.length <= window) {// Emitting the text whole is the one path that skips the per-slice// re-check below, so a PROBED estimate has to be confirmed exactly first:// a sparse ASCII head can under-read a dense CJK tail.if (knownEst !== undefined || text.length <= DENSITY_PROBE_CHARS) return [text];const exact = estimateEmbedTokens(text);- return exact <= DEFAULT_MAX_CHUNK_TOKENS ? [text] : capByChars(text, maxChars, exact);+ return exact <= maxTokens ? [text] : capByChars(text, maxChars, maxTokens, exact);}// The stride keeps its nominal window-minus-overlap value. Evening the// windows out (as the header-budget hard split does) is WRONG here: that@@ -169,11 +191,11 @@ function capByChars(text: string, maxChars: number, knownEst?: number): string[]const slice = text.slice(i, end).trim();if (slice.length > 0) {const sliceEst = estimateEmbedTokens(slice);- if (sliceEst > DEFAULT_MAX_CHUNK_TOKENS) {+ if (sliceEst > maxTokens) {// Denser than the text average — re-derive locally, reusing the exact// figure just measured (it also guarantees window < slice.length, so// the recursion strictly shrinks).- out.push(...capByChars(slice, maxChars, sliceEst));+ out.push(...capByChars(slice, maxChars, maxTokens, sliceEst));} else {out.push(slice);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d2e9c5d544..1cd5b8ca09 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -22,14 +22,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'autopilot': ['--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--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', '--save', '--source', '--stale', '--status', '--surface', '--swap-only', '--take', '--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'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],- 'book-mirror': ['--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', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--remediate', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--stdin', '--surface', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'book-mirror': ['--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', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--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-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', '--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', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],- 'calibration': ['--ab', '--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', '--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', '--regenerate', '--repo', '--restore-only', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],- 'call': ['--aliases', '--all', '--all-sources', '--apply', '--as-context', '--auto-fix', '--background', '--brain', '--budget', '--by-mention', '--catch-up', '--check', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--once', '--page', '--param', '--params', '--password', '--path', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--qrels', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--take', '--target', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],- 'capture': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--repo', '--restore-only', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],- 'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],+ 'calibration': ['--ab', '--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', '--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', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],+ 'call': ['--aliases', '--all', '--all-sources', '--anchor', '--apply', '--as-context', '--auto-fix', '--background', '--brain', '--budget', '--by-mention', '--catch-up', '--check', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--once', '--page', '--param', '--params', '--password', '--path', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--qrels', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--take', '--target', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],+ 'capture': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--stats', '--stdin', '--surface', '--timeout', '--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'],'claw-test': ['--ab', '--agent', '--all', '--auto', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--output-format', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],@@ -41,57 +41,57 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'config': ['--all', '--brain', '--column', '--coverage-override', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--fast', '--federated-read', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--markdown', '--model', '--multimodal', '--no-embedding', '--no-federated', '--pattern', '--pglite', '--recency', '--reset', '--source', '--surface', '--token-ttl', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--delete-brain', '--env', '--force', '--grant-types', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],- 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--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', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--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', '--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-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--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-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': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-mention', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--qrels', '--quiet', '--rebuild', '--receipt-dir', '--recency', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--sample', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],+ 'doctor': ['--ab', '--abbrev-ref', '--abi', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--audit-rejects', '--auto', '--auto-fix', '--auto-update', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--build-index', '--by-mention', '--by-type', '--cached', '--check', '--column', '--compile', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--date', '--days', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--exclusive', '--explain', '--fast', '--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', '--grant-types', '--harness', '--health-interval', '--help', '--history', '--home', '--http', '--id', '--ignore-env-override', '--ignore-missing-key', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--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-mutate', '--no-verify', '--oauth-client-secret', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--preset', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--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-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': ['--against', '--aliases', '--all', '--allow-regression', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-mention', '--by-type', '--by-type-floor', '--cancel-unmatched', '--check', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--drain-implied', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--qrels', '--quiet', '--rebuild', '--receipt-dir', '--recency', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--sample', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--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', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--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'],- 'enrich': ['--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', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--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', '--reenrich-after', '--remediate', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--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-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dim', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--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', '--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', '--version', '--with-code-intel', '--yes'],- 'export': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--explain', '--federated', '--fix', '--follow', '--full', '--help', '--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', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--full', '--help', '--include-frontmatter', '--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', '--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'],+ 'embed': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--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'],+ 'enrich': ['--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', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--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', '--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-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--check', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dim', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--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', '--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', '--version', '--with-code-intel', '--yes'],+ 'export': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--explain', '--federated', '--fix', '--follow', '--full', '--help', '--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', '--follow', '--from-meetings', '--full', '--help', '--include-frontmatter', '--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'],'features': ['--all', '--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', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--type', '--verbose', '--workers'],- 'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--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': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--repo', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],+ 'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--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': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],'founder': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--timeout', '--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-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],'graph-query': ['--brain', '--depth', '--direction', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--timeout', '--token-ttl', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-limit', '--brain', '--budget-ms', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--once', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--show-current', '--show-toplevel', '--source', '--stale', '--stats', '--status', '--surface', '--timeout', '--token', '--token-ttl'],- 'import': ['--all', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--workers'],+ 'import': ['--all', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--since', '--skip-failed', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--workers'],'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--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', '--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', '--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', '--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', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--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', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--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', '--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', '--yes'],- 'lint': ['--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--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', '--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', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--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', '--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'],'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', '--help', '--include-flagged', '--include-frontmatter', '--index-audit', '--infer-dates', '--input', '--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', '--rebuild', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--run-id', '--safe', '--scope', '--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', '--compile', '--days', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--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', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--undo-wave', '--url', '--use-captured-snapshot', '--version', '--with-calibration', '--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', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--input', '--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', '--rebuild', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--run-id', '--safe', '--scope', '--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', '--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', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--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': ['--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', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--offset', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],- 'orphans': ['--background', '--brain', '--brain-wide-max-cost-usd', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout'],+ 'onboard': ['--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', '--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', '--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', '--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', '--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', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],- 'protocol': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'protocol': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--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', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--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', '--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': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--repo', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],- 'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--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', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--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', '--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'],+ 'recall': ['--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', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--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', '--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', '--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-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],- 'reindex-search-vector': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--json', '--migrate-only', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--yes'],- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--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', '--parallel', '--path', '--pglite', '--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', '--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-empty', '--brain', '--break-lock', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--dir', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--fast', '--fix', '--force', '--force-break-lock', '--format', '--from-pages', '--full', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--interval', '--is-ancestor', '--issuer-url', '--json', '--key', '--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', '--parallel', '--path', '--pglite', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--short', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--scopes', '--source', '--surface', '--timeout', '--token-ttl'],- 'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--url'],+ 'repair-jsonb': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abbrev-ref', '--abort', '--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', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--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', '--http', '--id', '--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', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--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', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--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', '--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'],'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],'salience': ['--brain', '--days', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--slug-prefix', '--source', '--surface', '--timeout', '--token-ttl'],'schema': ['--alias', '--aliases', '--all', '--apply', '--as-filing-rules', '--asof', '--brain', '--by-mention', '--compile', '--dims', '--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'],@@ -100,18 +100,18 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--verbose', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime', '--max-runtime-min', '--model', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models', '--verbose', '--yes'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force', '--force-unlock', '--format', '--from', '--from-pages', '--frontmatter', '--full', '--harness', '--help', '--homepage', '--http', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-embedding', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--surface', '--target', '--tier', '--token-ttl', '--trust', '--url', '--verbose', '--verify', '--workspace', '--yes'],- 'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],+ 'skillpack-check': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strict', '--timeout', '--yes'],'smoke-test': ['--brain', '--help', '--json', '--source'],'sources': ['--abbrev-ref', '--abort', '--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', '--clone-dir', '--compile', '--confirm-destructive', '--count', '--days', '--detect', '--diff-filter', '--dir', '--dry-run', '--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', '--http', '--id', '--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', '--set', '--short', '--show-toplevel', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--surface', '--symbol-kind', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],- 'status': ['--ab-relational', '--abbrev-ref', '--abi', '--abort', '--against', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-regression', '--apply', '--asof', '--auto', '--background', '--baseline', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-per-day', '--budget-usd-retrieval', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--committed-baseline', '--compare', '--compare-limit', '--compile', '--concurrency', '--concurrent', '--config-a', '--config-b', '--confirm-destructive', '--content', '--content-audit', '--corpus', '--cost-estimate', '--count', '--cycles', '--date', '--days', '--deadline-ms', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--distance-min', '--drain', '--dry-run', '--embedder', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expand', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-capture', '--from-meetings', '--from-pages', '--full', '--git-path', '--gold', '--grounding-min', '--hard-deadline', '--harness', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-holdout', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--json', '--judge', '--judge-model', '--justification', '--k', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-pair-chars', '--max-rss', '--max-runtime', '--max-sources', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--migrate-only', '--min-context', '--min-recall', '--missing-path', '--mode', '--model', '--modes', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-cache', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-llm', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--out', '--output', '--output-dir', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parity-baseline', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--receipt-dir', '--reenrich-after', '--refresh', '--refresh-cache', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--rrf-k', '--run-id', '--runs', '--sample', '--sampling', '--save', '--scope', '--scopes', '--section', '--seed', '--serial', '--session', '--session-id', '--severity', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--strict', '--suite', '--suites', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--task', '--thin', '--thin-threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-env', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--trusted-extraction', '--type', '--types', '--until', '--update-baseline', '--url', '--usefulness-min', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--what', '--where', '--who', '--window', '--with-code-intel', '--with-db', '--workers', '--yes'],+ 'status': ['--ab-relational', '--abbrev-ref', '--abi', '--abort', '--against', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-regression', '--apply', '--asof', '--auto', '--background', '--baseline', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-per-day', '--budget-usd-retrieval', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--committed-baseline', '--compare', '--compare-limit', '--compile', '--concurrency', '--concurrent', '--config-a', '--config-b', '--confirm-destructive', '--content', '--content-audit', '--corpus', '--cost-estimate', '--count', '--cycles', '--date', '--days', '--deadline-ms', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--distance-min', '--drain', '--dry-run', '--embedder', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expand', '--explain', '--fast', '--federated', '--ff-only', '--file', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-capture', '--from-meetings', '--from-pages', '--full', '--git-path', '--gold', '--grounding-min', '--hard-deadline', '--harness', '--help', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-holdout', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--json', '--judge', '--judge-model', '--justification', '--k', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-pair-chars', '--max-rss', '--max-runtime', '--max-sources', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--migrate-only', '--min-context', '--min-recall', '--missing-path', '--mode', '--model', '--modes', '--multimodal', '--name', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-cache', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-llm', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--offset', '--older-than', '--order', '--orphan', '--others', '--out', '--output', '--output-dir', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parity-baseline', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--receipt-dir', '--recency', '--reenrich-after', '--refresh', '--refresh-cache', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--rrf-k', '--run-id', '--runs', '--salience', '--sample', '--sampling', '--save', '--scope', '--scopes', '--section', '--seed', '--serial', '--session', '--session-id', '--severity', '--short', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--strict', '--suite', '--suites', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--task', '--thin', '--thin-threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-env', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--trusted-extraction', '--type', '--types', '--until', '--update-baseline', '--url', '--usefulness-min', '--verbose', '--verify', '--version', '--walk-depth', '--watch', '--what', '--where', '--who', '--window', '--with-code-intel', '--with-db', '--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', '--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', '--all', '--all-sources', '--allow-empty', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--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', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--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', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--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', '--yes'],+ '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', '--all', '--all-sources', '--allow-empty', '--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', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--git-path', '--hard-deadline', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--interval', '--is-ancestor', '--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', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--serial', '--short', '--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', '--brain', '--bucket-size', '--by', '--claim', '--dir', '--domain', '--dry-run', '--evidence', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embedding', '--no-federated', '--outcome', '--path', '--quality', '--reject', '--repo', '--restore-only', '--row', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--surface', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],- 'think': ['--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--max-usd', '--mcp-only', '--model', '--no-embedding', '--rounds', '--save', '--since', '--source', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration'],- 'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--code', '--compile', '--days', '--dry-run', '--embed', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],+ 'think': ['--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-usd', '--mcp-only', '--model', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--rounds', '--save', '--since', '--source', '--source-guard', '--surface', '--take', '--timeout', '--token-ttl', '--until', '--with-calibration'],+ 'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--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', '--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', '--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', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],'watch': ['--brain', '--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': ['--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', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],- 'ze-switch': ['--background', '--brain', '--brain-wide-max-cost-usd', '--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'],+ 'whoknows': ['--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', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--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', '--stats', '--stdin', '--surface', '--timeout', '--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/cli-options.ts b/src/core/cli-options.tsindex 0660382c4d..fe84a478d4 100644--- a/src/core/cli-options.ts+++ b/src/core/cli-options.ts@@ -93,6 +93,23 @@ function parseBrainValue(val: string | undefined): string {*/export const TIMEOUT_OWNING_COMMANDS = new Set(['sync', 'remote']);+/**+ * #4541: commands whose result formatter consumes the GLOBAL --explain (the+ * v0.40.4 per-stage search attribution view in cli.ts's query/search+ * formatter; `ask` is the query alias rewritten before dispatch). For every+ * OTHER command the global parser hands the flag back IN PLACE — `extract+ * --explain <kind>`, `whoknows --explain`, and `onboard --check --explain`+ * parse it themselves, and the blanket claim starved them: `extract+ * --explain timeline` fell through to the WRITE-pass extraction instead of+ * the explain view.+ *+ * wave-g: `call` claims it too — `gbrain call <op>` maps leftover argv into+ * op params, so a handed-back --explain would surface as an+ * unknown-parameter error instead of being ignored (the pre-#4541 global+ * behavior for `call query --explain`).+ */+export const EXPLAIN_CLAIMING_COMMANDS = new Set(['query', 'search', 'ask', 'call']);+export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: string[] } {const cliOpts: CliOptions = { ...DEFAULT_CLI_OPTIONS };// #3013: --timeout can't be resolved inline — whether the GLOBAL parser@@ -102,7 +119,8 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s// a second pass below.type Slot =| { plain: string }- | { timeoutValue: string; equalsForm: boolean };+ | { timeoutValue: string; equalsForm: boolean }+ | { explainFlag: true };const slots: Slot[] = [];for (let i = 0; i < argv.length; i++) {@@ -151,8 +169,10 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: scontinue;}// v0.40.4 — --explain for `gbrain search/query` per-stage attribution.+ // #4541: like --timeout, whether the global parser claims it depends on+ // the command, which is only known after the full scan — slot it.if (a === '--explain') {- cliOpts.explain = true;+ slots.push({ explainFlag: true });continue;}// --brain <id> / --brain=<id> — brain (database) axis. Exact-match only:@@ -190,6 +210,10 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: sconst commandSlot = slots.find((s): s is { plain: string } => 'plain' in s);const commandOwnsTimeout =commandSlot !== undefined && TIMEOUT_OWNING_COMMANDS.has(commandSlot.plain);+ // #4541: only the search/query formatter commands claim --explain globally;+ // everyone else gets it back in place (extract/whoknows/onboard own it).+ const commandClaimsExplain =+ commandSlot !== undefined && EXPLAIN_CLAIMING_COMMANDS.has(commandSlot.plain);const rest: string[] = [];const handback: string[] = [];@@ -198,6 +222,11 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: srest.push(s.plain);continue;}+ if ('explainFlag' in s) {+ if (commandClaimsExplain) cliOpts.explain = true;+ else rest.push('--explain');+ continue;+ }if (commandOwnsTimeout) {handback.push('--timeout', s.timeoutValue);continue;diff --git a/src/core/config.ts b/src/core/config.tsindex 64c5ffdec8..76ddbc51b3 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1141,6 +1141,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.image_query.max_bytes','search.reranker.enabled','search.track_retrieval',+ // #4415: per-brain query-intent pattern extensions (JSON bank→regex[]),+ // merged over the shipped banks in src/core/search/query-intent.ts.+ 'search.intent_patterns',// Models tier system (v0.31.12)'models.default','models.tier.utility',@@ -1151,6 +1154,14 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.dream.synthesize','models.dream.extract_atoms','cycle.extract_atoms.budget_usd',+ 'cycle.extract_atoms.max_source_chars',+ 'cycle.extract_atoms.page_discovery_budget',+ // #4540: per-item extractor caps (defaults 50000 chars / 4096 tokens) plus+ // an optional between-item pacing sleep (ms, default 0). Read via+ // engine.getConfig in src/core/cycle/extract-atoms.ts.+ 'cycle.extract_atoms.max_input_chars',+ 'cycle.extract_atoms.max_output_tokens',+ 'cycle.extract_atoms.pacing_ms','models.dream.patterns','models.dream.synthesize_verdict',// #4152: preferred triage-model key (explicit pre-read in loadSynthConfig;@@ -1213,6 +1224,11 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['dream.triage.max_tokens','dream.triage.max_ms','dream.triage.concurrency',+ // #4494: propose_takes extractor output caps (defaults 2048/4096, floor+ // 256, retry clamped >= base). Thinking models spend reasoning tokens+ // inside maxTokens, so the hardcoded defaults truncated every dense page.+ 'dream.propose_takes.max_tokens',+ 'dream.propose_takes.retry_max_tokens','dream.patterns.lookback_days','dream.patterns.min_evidence',// #2782-family: patterns-phase subagent timeouts (mirror of the@@ -1298,6 +1314,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['orphans.exclude_slugs','sync.cost_gate_min_usd','sync.federated_v2',+ 'sync.include_working_tree',// #2179: clamp window for DCR-requested per-client token TTLs. Read by// `gbrain serve --http` at startup; unset min defaults to 300s, unset max// defaults fail-closed to max(--token-ttl, min).diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex 35df66a30b..8215a13e1e 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -533,6 +533,11 @@ async function assembleDelta(? { updatedAfterKeyset: { updatedAt: since, slug: opts.sinceSlug } }: { updated_after: since }),sourceId: opts.sourceId,+ // Match the facts + entity-card arms: delta is world-only unless a+ // trusted local caller explicitly sets includePrivate. Without+ // this engine-level filter, a default/remote delta exposed private+ // page titles and slugs even though its fact payload was filtered.+ excludePrivate: remote,limit: DELTA_PAGE_FETCH_LIMIT + 1,sort: 'updated_asc',});diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex fe4cb87681..5e37ce5180 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1271,15 +1271,24 @@ async function runPhaseSync(// doesn't report a clean run over a wedged source. Timeout-class partials// keep the pre-existing 'ok' mapping (they converge on retry by design).const pullFailedPartial = result.status === 'partial' && result.reason === 'pull_failed';+ // Untracked-gap fix: uncommitted working-tree drift (files invisible to+ // commit-driven sync) surfaces as 'warn', not a clean 'ok +0' — a nightly+ // cycle over a dirty vault otherwise reports convergence it never achieved.+ const uncommittedTotal = result.uncommitted+ ? result.uncommitted.added + result.uncommitted.modified + result.uncommitted.deleted+ : 0;+ const uncommittedNote = uncommittedTotal > 0+ ? `; ${uncommittedTotal} uncommitted file(s) invisible to commit-driven sync — commit them or set sync.include_working_tree=true`+ : '';return {phase: 'sync',- status: result.status === 'blocked_by_failures' || pullFailedPartial ? 'warn' : 'ok',+ status: result.status === 'blocked_by_failures' || pullFailedPartial || uncommittedTotal > 0 ? 'warn' : 'ok',duration_ms: 0,summary: dryRun? `${syncedCount} page(s) would sync, ${result.deleted} would delete`: pullFailedPartial? `git pull failed, nothing imported — source may be behind its remote (sync anchor unchanged)`- : `+${result.added} added, ~${result.modified} modified, -${result.deleted} deleted`,+ : `+${result.added} added, ~${result.modified} modified, -${result.deleted} deleted${uncommittedNote}`,details: {added: result.added,modified: result.modified,@@ -1289,6 +1298,7 @@ async function runPhaseSync(failedFiles: result.failedFiles ?? 0,syncStatus: result.status,...(result.reason ? { syncReason: result.reason } : {}),+ ...(result.uncommitted ? { uncommitted: result.uncommitted } : {}),dryRun,},pagesAffected: result.pagesAffected,@@ -2495,6 +2505,11 @@ export async function runCycle(const { runPhaseSynthesizeConcepts } = await import('./cycle/synthesize-concepts.ts');const { result, duration_ms } = await racedTimePhase(() => runPhaseSynthesizeConcepts(engine, {brainDir: brainDir ?? undefined,+ // #4416: thread the cycle's resolved source into the phase's page/+ // receipt/rollup writes; the engine's `?? 'default'` fallback+ // misfiles (or kills the cycle on the createVersion update path) on+ // any brain without a source literally named 'default'.+ sourceId: cycleSourceId,dryRun,// v0.41.19.0 (T3): closure refreshes cycle lock + fires outer hook.yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex e981333a44..9fcbd4a09c 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -39,8 +39,19 @@ export interface ExtractAtomsDrainDeps {* (zero items succeeded, at least one failure) — i.e. the batch's warning* result was actually a total provider outage, not a partial/no-op batch.* Omit/false for the ordinary partial-success or nothing-to-do cases.+ *+ * #4539: `failureCount` (per-item failures in this batch) and `firstError`+ * (a representative failure message) let the drain surface WHY a run+ * stopped/underperformed — pre-fix the phase's failures[] was collapsed to+ * bare counts and the operator saw only `stopped: no_progress`.*/- runBatch: () => Promise<{ extracted: number; skipped: number; providerFailure?: boolean }>;+ runBatch: () => Promise<{+ extracted: number;+ skipped: number;+ providerFailure?: boolean;+ failureCount?: number;+ firstError?: string;+ }>;/** Count remaining eligible-but-unextracted pages, or null on query error. */countRemaining: () => Promise<number | null>;/** Injectable clock. Production: Date.now. */@@ -74,6 +85,17 @@ export interface ExtractAtomsDrainResult {batches: number;/** Why the loop stopped: drained | window | no_progress | max_batches | provider_failure. */stopped: 'drained' | 'window' | 'no_progress' | 'max_batches' | 'provider_failure';+ /**+ * #4539: total per-item failures across every batch in this run. 0 for a+ * clean run. Included in `--json` verbatim; dream.ts prints a stderr line+ * when non-zero so the operator sees WHY the drain underperformed.+ */+ failure_count: number;+ /**+ * #4539: representative failure message from the most recent batch that+ * reported one (`source: error`), or null for a clean run.+ */+ last_error: string | null;}export async function runExtractAtomsDrain(@@ -91,6 +113,9 @@ export async function runExtractAtomsDrain(// the returned `status`, independent of how `stopped` reads after the// final (possibly overriding) remaining-count check below.let providerFailure = false;+ // #4539: accumulate per-item failure visibility across batches.+ let failureCount = 0;+ let lastError: string | null = null;while (deps.now() < deadline) {if (batches >= maxBatches) { stopped = 'max_batches'; break; }@@ -102,6 +127,8 @@ export async function runExtractAtomsDrain(extracted += r.extracted;skipped += r.skipped;batches++;+ if (typeof r.failureCount === 'number' && r.failureCount > 0) failureCount += r.failureCount;+ if (r.firstError) lastError = r.firstError;deps.onBatch?.({ batch: batches, extracted: r.extracted, remaining: before });// issue #3218: every item this batch attempted failed (0 succeeded, >=1@@ -144,6 +171,8 @@ export async function runExtractAtomsDrain(remaining,batches,stopped,+ failure_count: failureCount,+ last_error: lastError,};});}@@ -218,10 +247,21 @@ export async function runExtractAtomsDrainForSource(const failures = Array.isArray(d.failures) ? d.failures : [];const itemsSucceeded =Number(d.transcripts_processed ?? 0) + Number(d.pages_processed ?? 0);+ // #4539: carry a representative failure up to the drain result instead+ // of collapsing failures[] to bare counts — pre-fix a failing drain+ // reported only `stopped: no_progress` and the operator had no way to+ // see the underlying provider/parse error without re-running the+ // phase by hand.+ const first = failures[0] as { source?: unknown; error?: unknown } | undefined;+ const firstError = first+ ? `${typeof first.source === 'string' ? `${first.source}: ` : ''}${typeof first.error === 'string' ? first.error : JSON.stringify(first.error)}`+ : undefined;return {extracted: Number(d.atoms_extracted ?? 0),skipped: Number(d.duplicates_skipped ?? 0),providerFailure: failures.length > 0 && itemsSucceeded === 0,+ failureCount: failures.length,+ ...(firstError ? { firstError } : {}),};},countRemaining: () => countExtractAtomsBacklog(engine, extractionSourceId),diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex db070f62dd..b236bd498c 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -57,6 +57,7 @@ import { chat as gatewayChat, withBudgetTracker, isAvailable } from '../ai/gatewimport { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';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 { writeReceipt } from '../extract/receipt-writer.ts';import { upsertExtractRollup } from '../extract/rollup-writer.ts';@@ -65,6 +66,12 @@ import { slugifySegment } from '../sync.ts';const DEFAULT_BUDGET_USD = 0.3;const DEFAULT_EXTRACT_ATOMS_MODEL = 'anthropic:claude-haiku-4-5';+// #4529 + #4540: per-item extractor caps, overridable via+// cycle.extract_atoms.* config keys (max_input_chars — with the #4529+// legacy alias max_source_chars — plus max_output_tokens / pacing_ms).+// Exported so tests pin the defaults instead of re-hardcoding the literals.+export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;+export const DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS = 4096;/*** gbrain#4148: consecutive same-content failures of a content-deterministic@@ -261,6 +268,7 @@ export async function discoverExtractablePages(engine: BrainEngine,sourceId: string,affectedSlugs?: string[],+ limit: number = PAGE_DISCOVERY_BUDGET,): Promise<DiscoveredPage[]> {const hasFilter = Array.isArray(affectedSlugs) && affectedSlugs.length > 0;const sql = `@@ -293,7 +301,7 @@ export async function discoverExtractablePages(sourceId,await resolveExtractableTypes(),MIN_PAGE_CHARS_FOR_EXTRACTION,- PAGE_DISCOVERY_BUDGET,+ limit,];if (hasFilter) params.push(affectedSlugs);@@ -385,6 +393,19 @@ export async function countExtractAtomsBacklog(}}+async function resolvePageDiscoveryLimit(engine: BrainEngine): Promise<number> {+ try {+ const configured = await engine.getConfig('cycle.extract_atoms.page_discovery_budget');+ if (configured) {+ const n = Number(configured);+ // Ceiling: discovery selects full compiled_truth bodies per row, so an+ // oversized budget materializes that many pages in one result set.+ if (Number.isFinite(n) && n > 0) return Math.min(Math.floor(n), 10_000);+ }+ } catch { /* keep default */ }+ return PAGE_DISCOVERY_BUDGET;+}+/*** Batch source-hash idempotency check. Returns the set of contentHash16* values that already have an atom row for this source. One SQL@@ -486,7 +507,12 @@ export async function runPhaseExtractAtoms(if (opts._pages !== undefined) {pages = opts._pages;} else {- pages = await discoverExtractablePages(engine, sourceId, opts.affectedSlugs);+ pages = await discoverExtractablePages(+ engine,+ sourceId,+ opts.affectedSlugs,+ await resolvePageDiscoveryLimit(engine),+ );}// 2. Apply transcript-side source-hash idempotency in ONE batch query@@ -592,16 +618,56 @@ export async function runPhaseExtractAtoms(let budgetExhausted = false;let extractModel = DEFAULT_EXTRACT_ATOMS_MODEL;let budgetCap = DEFAULT_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.+ let maxInputChars = DEFAULT_EXTRACT_MAX_INPUT_CHARS;+ let maxOutputTokens = DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS;+ let pacingMs = 0;try {const configuredModel = await engine.getConfig('models.dream.extract_atoms');if (configuredModel) extractModel = configuredModel;+ // `models.dream.extract_atoms` is DB-plane/operator-selected config.+ // The gateway no longer has a model allowlist/extended-model registry:+ // configured per-task chat models resolve like `models.default`, so local+ // user-managed providers (e.g. Ollama tags) need no registration here.const configuredBudget = await engine.getConfig('cycle.extract_atoms.budget_usd');if (configuredBudget) {const n = Number(configuredBudget);if (Number.isFinite(n) && n > 0) budgetCap = n;}+ // #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+ // both are set — they name the same knob.+ const configuredMaxSourceChars = await engine.getConfig('cycle.extract_atoms.max_source_chars');+ if (configuredMaxSourceChars) {+ const n = Number(configuredMaxSourceChars);+ if (Number.isFinite(n) && n >= 500) maxInputChars = Math.floor(n);+ }+ const configuredMaxInput = await engine.getConfig('cycle.extract_atoms.max_input_chars');+ if (configuredMaxInput) {+ const n = Number(configuredMaxInput);+ // Floor of 1000 chars: below that the extractor sees a fragment too+ // small to yield atoms and every page burns budget for nothing.+ if (Number.isFinite(n) && n >= 1_000) maxInputChars = Math.floor(n);+ }+ const configuredMaxOutput = await engine.getConfig('cycle.extract_atoms.max_output_tokens');+ if (configuredMaxOutput) {+ const n = Number(configuredMaxOutput);+ // Floor of 256 tokens mirrors dream.triage.max_tokens: a smaller cap+ // truncates every response into the malformed-output failure path.+ if (Number.isFinite(n) && n >= 256) maxOutputTokens = Math.floor(n);+ }+ // Optional per-item pacing sleep (ms) so a large backlog doesn't hammer+ // a local/self-hosted provider back-to-back. 0 (default) = no pacing.+ const configuredPacing = await engine.getConfig('cycle.extract_atoms.pacing_ms');+ if (configuredPacing) {+ const n = Number(configuredPacing);+ if (Number.isFinite(n) && n > 0) pacingMs = Math.min(60_000, Math.floor(n));+ }} catch {- // Keep safe defaults: Haiku + $0.30.+ // Keep safe defaults on any config-read failure: Haiku model, $0.30 cap,+ // default max_source_chars.}// A cost cap is only meaningful for a model the tracker can price.// BudgetTracker.reserve() hard-fails with BudgetExhausted(reason:'no_pricing')@@ -714,16 +780,21 @@ export async function runPhaseExtractAtoms(messages: [{role: 'user',- content: `Source: ${originLabel}\n\n---\n\n${item.content.slice(0, 50_000)}`,+ // #4529/#4540: configurable input cap, cut UTF-8-safely (a bare+ // .slice() can split a surrogate pair at the boundary).+ content: `Source: ${originLabel}\n\n---\n\n${truncateUtf8(item.content, maxInputChars)}`,},],- maxTokens: 4096,+ maxTokens: maxOutputTokens,});// Post-await yield: closes the "long LLM call past TTL" hazard// codex flagged. The 30s throttle inside maybeYield bounds the// actual refresh rate so this is cheap when calls are fast.await maybeYield();llmHalt.reset();+ // #4540: optional per-item pacing between successful LLM calls.+ // setTimeout (not setImmediate) so the lock-refresh interval fires.+ if (pacingMs > 0) await new Promise<void>((r) => setTimeout(r, pacingMs));estimatedSpendUsd = budgetTracker.totalSpent;diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 78d417a2f3..0f070f7808 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -57,7 +57,7 @@ import type { BrainEngine } from '../engine.ts';import { resolveSupersededByRow, type SupersedeTarget } from '../facts/supersede-resolve.ts';import { writeReceipt } from '../extract/receipt-writer.ts';import { upsertExtractRollup } from '../extract/rollup-writer.ts';-import { parseFactsFence } from '../facts-fence.ts';+import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';import {extractFactsFromFenceText,FENCE_SOURCE_DEFAULT,@@ -186,6 +186,75 @@ export interface ExtractFactsResult {phantomsMorePending: boolean;}+/**+ * #3625 (adversarial review, 2 rounds): whether `timeline` contains a+ * GENUINE Facts fence marker, as opposed to the marker text merely being+ * mentioned inside a fenced code example or quoted prose. A naive+ * `.includes(FACTS_FENCE_BEGIN)` false-positives on both — e.g. a page+ * whose real fence WAS removed, but whose timeline documents the fence+ * syntax in a ```markdown code block or a `> ...` blockquote, would wrongly+ * be treated as "misplaced" and block a genuine deletion, leaving stale+ * facts indexed indefinitely.+ *+ * Round 1 tried reusing fence-scan.ts's scanFencedBlocks() + string removal+ * of its extracted fence bodies. Round-2 adversarial review broke that:+ * scanFencedBlocks normalizes line endings (splits on `\r\n|\r|\n`, joins+ * fence bodies with plain `\n`) and strips opener indentation before+ * returning fence text — so `stripped.split(fenceText).join('')` on the+ * ORIGINAL (un-normalized) string silently fails to match a CRLF or+ * indented code block, leaving the marker inside it undetected and still+ * false-positive. Reconstructed-text removal can't safely undo a lossy+ * normalization.+ *+ * Fix: a self-contained single-pass line scanner (mirroring fence-scan.ts's+ * own CommonMark-subset opener/closer grammar, applied directly against+ * `timeline.split(/\r\n|\r|\n/)` — ONE split, no re-normalization, no+ * text-based removal) that skips lines between a real ``` /~~~ opener and+ * its closer, then checks whether any remaining line, trimmed, exactly+ * equals the marker. A real fence marker is always written as its own line+ * (see FENCE_BODY-shaped output from fence-write.ts / upsertFactRow), so+ * exact-line-match — on lines outside any code fence — rules out both+ * hazards without needing a full markdown AST (mirrors+ * findTimelineSplitIndex's own `trimmed === sentinel` pattern for the same+ * class of problem on the timeline sentinel itself). An unclosed opener+ * runs to EOF (matches fence-scan.ts's documented behavior) — a marker+ * appearing after it is inside an ambiguous, unclosed block and is not+ * trusted as genuine.+ */+function timelineHasGenuineFactsFenceMarker(timeline: string): boolean {+ if (!timeline.includes(FACTS_FENCE_BEGIN)) return false;+ const lines = timeline.split(/\r\n|\r|\n/);+ const OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;+ const CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;+ let i = 0;+ while (i < lines.length) {+ const line = lines[i]!;+ const open = OPEN_RE.exec(line);+ if (open) {+ const marker = open[1]!;+ const fenceChar = marker[0]!;+ const info = open[2]!.trim();+ // Mirrors fence-scan.ts: a backtick opener whose info string contains+ // a backtick is inline code, not a fence opener.+ if (!(fenceChar === '`' && info.includes('`'))) {+ let j = i + 1;+ for (; j < lines.length; j++) {+ const close = CLOSE_RE.exec(lines[j]!);+ if (close && close[1]![0] === fenceChar && close[1]!.length >= marker.length) {+ j++;+ break;+ }+ }+ i = j; // unclosed fence: j reaches lines.length, ending the scan+ continue;+ }+ }+ if (line.trim() === FACTS_FENCE_BEGIN) return true;+ i++;+ }+ return false;+}+/*** Run the extract_facts phase against the current brain state. Returns* an ExtractFactsResult envelope; status mapping (ok / warn / fail)@@ -401,6 +470,36 @@ export async function runExtractFacts(continue;}+ // #3625: splitBody() puts everything below the timeline sentinel into+ // page.timeline, not compiled_truth — a `## Facts` fence written there+ // (agent-composed bodies commonly append it at the bottom) is invisible+ // to the parseFactsFence(body) call above. Without this check,+ // parsed.facts.length === 0 reads as "the user deleted the fence" and+ // the block below prunes every previously-indexed row for the page —+ // when the fence is actually just misplaced, not absent. Distinguish+ // the two by checking whether a fence marker ALSO landed in+ // page.timeline: if so, the page is non-authoritative — malformed+ // placement (loud warning, preserve the existing index), never treated+ // as absence (destructive delete). Checked unconditionally on+ // parsed.facts.length (not just when it's 0): a page can have a valid+ // fence above the sentinel AND a stray/duplicate one below it (e.g. a+ // partial hand-edit), in which case parsed.facts.length > 0 but+ // reconciling from compiled_truth alone would still misread the+ // below-sentinel rows as deleted. Uses timelineHasGenuineFactsFenceMarker+ // rather than a raw .includes() (adversarial review finding: the naive+ // substring check false-positives on the marker text merely being+ // mentioned in a doc code-block or quoted prose, wrongly blocking a+ // genuine deletion and leaving stale facts indexed indefinitely).+ if (timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {+ result.warnings.push(+ `${slug}: FACTS_FENCE_BELOW_SENTINEL: a ## Facts fence was found below ` ++ `the <!-- timeline --> sentinel, where extract_facts cannot see it. ` ++ `Move the fence above the sentinel and re-save — leaving it in place ` ++ `preserves the existing indexed facts but they will not update.`,+ );+ continue;+ }+if (parsed.facts.length > 0) result.pagesWithFacts += 1;// v0.35.4 (D-ENG-1) — thread page.effective_date as the fallbackdiff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 0a1c9fb3b7..93f44aab4d 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -44,7 +44,7 @@ import { chat as gatewayChat, getChatModel, probeChatModel } from '../ai/gatewayimport { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';import { normalizeModelId } from '../model-id.ts';import { writeReceipt } from '../extract/receipt-writer.ts';-import { upsertExtractRollup } from '../extract/rollup-writer.ts';+import { upsertExtractRollup, classifyRunStop } from '../extract/rollup-writer.ts';import { GBrainError } from '../types.ts';import { isConfigTruthy } from '../config.ts';import type { OperationContext } from '../operations.ts';@@ -144,6 +144,17 @@ export type ProposeTakesExtractor = (input: {pageBody: string;existingTakes: Array<{ claim: string; kind: string; holder: string; weight: number }>;modelHint?: string;+ /**+ * #4494: output cap for the extractor call (default+ * PROPOSE_TAKES_MAX_TOKENS). Configurable via dream.propose_takes.max_tokens+ * because thinking models spend reasoning tokens INSIDE maxTokens — at the+ * 2048 default a thinking model can burn the whole budget before emitting+ * any JSON, truncating EVERY page into a permanent per-page retry loop.+ */+ maxTokens?: number;+ /** #4494: escalated cap for the one truncation retry (default+ * PROPOSE_TAKES_RETRY_MAX_TOKENS; clamped to >= maxTokens). */+ retryMaxTokens?: number;}) => Promise<ProposedTake[]>;export interface ProposeTakesOpts extends BasePhaseOpts {@@ -307,6 +318,15 @@ const EXTRACTOR_CALL_TIMEOUT_MS = 90_000;* parity); a still-truncated retry throws an error NAMING the truncation* instead of the old generic 'transient — retry' (which re-billed the page* every cycle forever while hiding the real cause).+ *+ * #4494 — these are now DEFAULTS, overridable via+ * `dream.propose_takes.max_tokens` / `dream.propose_takes.retry_max_tokens`+ * (floor 256; retry clamped >= base), mirroring dream.triage.max_tokens.+ * Thinking models (DeepSeek-R1, MiniMax-M3, Claude with extended thinking)+ * spend reasoning tokens INSIDE the maxTokens budget, so field deployments+ * saw every dense page truncate at 2048 → retry at 4096 → truncate again →+ * throw → re-bill next cycle, forever. Raising the config key breaks that+ * loop without inflating the default for non-thinking models.*/export const PROPOSE_TAKES_MAX_TOKENS = 2048;export const PROPOSE_TAKES_RETRY_MAX_TOKENS = 4096;@@ -339,6 +359,16 @@ export async function defaultExtractor(.replace('{EXISTING_TAKES_JSON}', JSON.stringify(input.existingTakes, null, 2)).replace('{PAGE_BODY}', input.pageBody);+ // #4494: per-run configurable caps (dream.propose_takes.max_tokens /+ // .retry_max_tokens), threaded by the phase; the #3763 constants stay as+ // defaults. Retry is clamped >= base so a partial override can't shrink+ // the escalation below the first attempt.+ const baseMaxTokens = Math.max(256, Math.floor(input.maxTokens ?? PROPOSE_TAKES_MAX_TOKENS));+ const retryMaxTokens = Math.max(+ baseMaxTokens,+ Math.floor(input.retryMaxTokens ?? PROPOSE_TAKES_RETRY_MAX_TOKENS),+ );+// Bound each call so one stalled provider socket can't pin the phase for the// full gateway default (GBRAIN_AI_CHAT_TIMEOUT_MS, 300s) x pageLimit. The// caller already catches per-page errors, logs a warning, and continues.@@ -348,7 +378,7 @@ export async function defaultExtractor(maxTokens,abortSignal: AbortSignal.timeout(EXTRACTOR_CALL_TIMEOUT_MS),});- let result = await call(PROPOSE_TAKES_MAX_TOKENS);+ let result = await call(baseMaxTokens);// #3763: a truncated response (stopReason 'length' — e.g. reasoning tokens// eating the cap, or a dense page extracting many claims) produced@@ -359,15 +389,17 @@ export async function defaultExtractor(// warning tells the operator what actually happened.if (result.stopReason === 'length') {process.stderr.write(- `[propose_takes] WARN: extractor output truncated at maxTokens=${PROPOSE_TAKES_MAX_TOKENS} ` +- `(${input.pagePath}); retrying once at ${PROPOSE_TAKES_RETRY_MAX_TOKENS}\n`,+ `[propose_takes] WARN: extractor output truncated at maxTokens=${baseMaxTokens} ` ++ `(${input.pagePath}); retrying once at ${retryMaxTokens}\n`,);- result = await call(PROPOSE_TAKES_RETRY_MAX_TOKENS);+ result = await call(retryMaxTokens);if (result.stopReason === 'length') {throw new Error(`propose_takes extractor: output truncated (stopReason=length) even at ` +- `maxTokens=${PROPOSE_TAKES_RETRY_MAX_TOKENS} on ${input.pagePath} — ` +- `page prose extracts more than the cap can carry; no tombstone written, page retries next cycle`,+ `maxTokens=${retryMaxTokens} on ${input.pagePath} — ` ++ `page prose extracts more than the cap can carry; raise ` ++ `dream.propose_takes.max_tokens (thinking models spend reasoning tokens ` ++ `inside this budget); no tombstone written, page retries next cycle`,);}}@@ -605,6 +637,27 @@ class ProposeTakesPhase extends BaseCyclePhase {const modelId = opts.model ?? getChatModel();+ // #4494: configurable extractor output caps (dream.triage.max_tokens+ // precedent — floor 256, retry clamped >= base, fail-open to the #3763+ // defaults on any config-plane error). Thinking models spend reasoning+ // tokens inside maxTokens, so the hardcoded 2048/4096 pair put dense+ // pages into a permanent truncate → retry → truncate → re-bill loop.+ let extractorMaxTokens = PROPOSE_TAKES_MAX_TOKENS;+ let extractorRetryMaxTokens = PROPOSE_TAKES_RETRY_MAX_TOKENS;+ try {+ const readCap = async (key: string): Promise<number | null> => {+ const raw = await engine.getConfig?.(key);+ if (raw == null || String(raw).trim() === '') return null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+ };+ const baseCap = await readCap('dream.propose_takes.max_tokens');+ if (baseCap != null) extractorMaxTokens = Math.max(256, Math.floor(baseCap));+ const retryCap = await readCap('dream.propose_takes.retry_max_tokens');+ if (retryCap != null) extractorRetryMaxTokens = Math.floor(retryCap);+ } catch { /* keep defaults */ }+ extractorRetryMaxTokens = Math.max(extractorMaxTokens, extractorRetryMaxTokens);+// With the default (gateway) extractor, skip cheaply when the resolved// model's provider can't run — same probe semantics as patterns.ts /// think/index.ts: unknown provider/model or Anthropic-without-key skips;@@ -768,6 +821,9 @@ class ProposeTakesPhase extends BaseCyclePhase {pageBody: body,existingTakes,modelHint: opts.model,+ // #4494: configurable output caps (see resolution above).+ maxTokens: extractorMaxTokens,+ retryMaxTokens: extractorRetryMaxTokens,});} catch (err) {result.llm_calls_failed += 1;@@ -894,9 +950,14 @@ class ProposeTakesPhase extends BaseCyclePhase {console.error(`[propose_takes] receipt write failed: ${(err as Error).message}`);}}- // A deadline-hit run halted mid-list the same way a budget-exhausted one- // does — record it as a halt, not a completed round. A global-error- // abort (#3044) is the same posture: the round did not complete.+ // #4482: three-way stop classification. A budget/deadline cap is the+ // extractor working as designed (partial progress banked; the rest+ // drains over future runs) — recorded as expected_limit_delta, a+ // capacity signal doctor's failure rate excludes. A global-error abort+ // (#3044) or an all-failures streak (#3763) is a REAL halt, unchanged+ // from today. An error alongside a cap counts as the error.+ // `halted` (any incomplete round, caps included) is kept for the phase+ // result's status/details below — the diagnostic split is rollup-only.const halted =result.budget_exhausted ||result.deadline_hit === true ||@@ -905,8 +966,13 @@ class ProposeTakesPhase extends BaseCyclePhase {await upsertExtractRollup(engine, {kind: 'takes.proposed',source_id: sourceIdForReceipt,- round_completed_delta: halted ? 0 : 1,- halt_delta: halted ? 1 : 0,+ ...classifyRunStop({+ budget_exhausted: result.budget_exhausted === true,+ deadline_hit: result.deadline_hit === true,+ error:+ result.aborted_global_error !== undefined ||+ result.aborted_failure_streak === true,+ }),});// Status folds warnings in (the extract_facts precedent from #1928): adiff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex 1eb40ba554..8e3b25fc05 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -54,6 +54,15 @@ const TIER_T3_MIN = 2;export interface SynthesizeConceptsOpts {brainDir?: string;+ /**+ * #4416: the cycle's resolved source scope (cycleSourceId in cycle.ts).+ * Without it every write below falls through to the engine's `?? 'default'`+ * literal, which misfiles (or, on the createVersion update path, kills the+ * cycle) on any brain whose sole source is not named `default`: getPage's+ * undefined-source path is source-agnostic, so the existence probe passes,+ * then createVersion throws "page ... (source=default) not found".+ */+ sourceId?: string;dryRun?: boolean;yieldDuringPhase?: (() => Promise<void>) | undefined;/**@@ -324,6 +333,8 @@ export async function runPhaseSynthesizeConcepts();await importFromContent(engine, `concepts/${title}`, md, {noEmbed: !isAvailable('embedding'),+ // #4416: target the cycle's resolved source, not the 'default' literal.+ sourceId: opts.sourceId,});}conceptsWritten++;@@ -336,16 +347,17 @@ export async function runPhaseSynthesizeConcepts(await maybeYield();}- // v0.42 Wave B3: receipt + rollup for synthesize_concepts. Brain-global- // phase — uses 'default' source_id because concepts span sources. Receipt- // only fires when concepts were actually written; rollup always fires so- // doctor sees the phase ran.+ // v0.42 Wave B3: receipt + rollup for synthesize_concepts. Receipt/rollup+ // carry the cycle's resolved source (#4416, opts.sourceId); 'default'+ // survives only as the fallback for legacy unscoped callers. Receipt only+ // fires when concepts were actually written; rollup always fires so doctor+ // sees the phase ran.if (!opts.dryRun && conceptsWritten > 0) {const runId = `concepts-${Date.now().toString(36)}`;try {await writeReceipt(engine, {kind: 'concepts',- source_id: 'default',+ source_id: opts.sourceId ?? 'default',run_id: runId,round: 'single',extracted_at: new Date().toISOString(),@@ -365,7 +377,7 @@ export async function runPhaseSynthesizeConcepts(if (!opts.dryRun) {await upsertExtractRollup(engine, {kind: 'concepts',- source_id: 'default',+ source_id: opts.sourceId ?? 'default',cost_delta: estimatedSpendUsd,round_completed_delta: failures.length === 0 ? 1 : 0,halt_delta: failures.length > 0 ? 1 : 0,diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex c0cefff079..23a6d00b2f 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -66,6 +66,7 @@ export { runSubagentsInline, runDrainRenewalTick };import { loadAllowedSlugPrefixes } from './filing-rules.ts';export { loadAllowedSlugPrefixes };import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscript } from './transcript-discovery.ts';+import { loadStorageConfig, isDbOnly } from '../storage-config.ts';import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';import type { Page, PageType } from '../types.ts';import { validateSourceId } from '../utils.ts';@@ -2720,7 +2721,31 @@ async function writeSummaryPage(frontmatter: parsed.frontmatter,}, { sourceId });- // Also write to disk (orchestrator dual-write).+ // Also write to disk (orchestrator dual-write). #4506: the unconditional+ // file write dirtied clean source repos (an untracked+ // dream-cycle-summaries/<date>.md after every nightly run). Two+ // suppressors, both leaving the DB row untouched:+ // - explicit knob `dream.synthesize.summary_file_write=false|0|off`+ // (default ON — back-compat for brains that expect the dual-write);+ // - a gbrain.yml storage tier that declares the summary slug `db_only`+ // (the DB/file-plane split the reporter expected to cover this path).+ const fileWriteRaw = (await engine.getConfig('dream.synthesize.summary_file_write'))?.trim().toLowerCase();+ const fileWriteEnabled = !(fileWriteRaw === 'false' || fileWriteRaw === '0' || fileWriteRaw === 'off');+ let dbOnlyTier = false;+ if (fileWriteEnabled) {+ try {+ const storage = loadStorageConfig(brainDir);+ dbOnlyTier = storage !== null && isDbOnly(summarySlug, storage);+ } catch {+ // Unreadable gbrain.yml — keep the dual-write default (fail-open to+ // pre-#4506 behavior; sync owns loud storage-config validation).+ }+ }+ if (!fileWriteEnabled || dbOnlyTier) {+ const why = !fileWriteEnabled ? 'dream.synthesize.summary_file_write=off' : 'db_only storage tier';+ process.stderr.write(`[dream] summary file-write skipped (${why}): ${summarySlug} lives in the DB only\n`);+ return;+ }try {const filePath = join(brainDir, `${summarySlug}.md`);mkdirSync(dirname(filePath), { recursive: true });@@ -2789,4 +2814,5 @@ export const __testing = {reverseWriteRefs,runSubagentsInline,loadSynthConfig,+ writeSummaryPage,};diff --git a/src/core/db.ts b/src/core/db.tsindex 35cdf0e563..34c87357ad 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1,6 +1,7 @@import postgres from 'postgres';import { GBrainError, type EngineConfig } from './types.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';+import { applyPostgresForwardReferenceBootstrap } from './postgres-engine/forward-reference-bootstrap.ts';import type { BrainEngine } from './engine.ts';import { verifySchema } from './schema-verify.ts';import { isRetryableConnError } from './retry-matcher.ts';@@ -360,6 +361,13 @@ export async function initSchema(): Promise<void> {// Lock-census (PR6 D5): INTENTIONALLY brain-global (session lock, fixed key 42) — schema replay mutates the whole database, not one source.await conn`SELECT pg_advisory_lock(42)`;try {+ // #4477: run the same forward-reference bootstrap as+ // PostgresEngine.initSchema BEFORE replaying the schema blob. Without+ // it, an older brain whose tables predate the blob's forward-referenced+ // columns (e.g. pages.deleted_at ← pages_deleted_at_purge_idx) wedges+ // on the blob's CREATE INDEX. Idempotent single-probe no-op on fresh+ // installs and modern brains.+ await applyPostgresForwardReferenceBootstrap(conn);await conn.unsafe(SCHEMA_SQL);} finally {await conn`SELECT pg_advisory_unlock(42)`;diff --git a/src/core/embed-backfill-submit.ts b/src/core/embed-backfill-submit.tsindex 1b9b265ab7..9c5a2578aa 100644--- a/src/core/embed-backfill-submit.ts+++ b/src/core/embed-backfill-submit.ts@@ -2,13 +2,15 @@* Single submission entry point for the `embed-backfill` minion job* (v0.40 Federated Sync v2 — D19).*- * Every caller routes through `submitEmbedBackfill`:+ * Every automatic caller routes through `submitEmbedBackfill`:* - Parallel sync --all completion (D18)* - Extended `sync` handler (D22, auto_embed_backfill)* - POST /webhooks/github* - `sources federate` / `unfederate` flip hook* - `gbrain sync trigger`* - autopilot per-source dispatch (when source is stale and degraded)+ * Explicit `jobs submit` / MCP submissions route through MinionQueue's public+ * admission gate instead, with explicit CLI follow mode as the inline-worker exception.** Why centralize: D2 added a per-source DB lock at handler entry. That* protects against double-RUN but not double-SUBMIT — a webhook storm could@@ -19,10 +21,12 @@* the same window. Multi-hour push activity racks up unbounded calls.** D19 layered defenses (composed here):- * 1. Per-source cooldown (default 10min). Refuses submission if the most+ * 1. Worker-surface gate. PGLite has no persistent worker, so it refuses+ * instead of accepting a job that cannot drain after submission returns.+ * 2. Per-source cooldown (default 10min). Refuses submission if the most* recent embed-backfill for this source finished or is still active* inside the window.- * 2. Per-source 24h rolling spend cap (default $25). Computed from the+ * 3. Per-source 24h rolling spend cap (default $25). Computed from the* embed-backfill-tagged rows in the budget audit JSONL. Refuses* submission when spend has hit the cap.*@@ -34,6 +38,7 @@* (`gbrain sources status`, webhook response body, sync completion banner).*/import type { BrainEngine } from './engine.ts';+import { embedBackfillWorkerSurface } from './minions/embed-backfill-admission.ts';import { MinionQueue } from './minions/queue.ts';import { parseUsdLimit, resolveSpendPosture, type SpendPosture } from './spend-posture.ts';@@ -43,29 +48,15 @@ export const SPEND_CAP_CONFIG_KEY = 'embed.backfill_max_usd_per_source_24h';const DEFAULT_COOLDOWN_MIN = 10;const DEFAULT_SPEND_CAP_USD = 25;-export type SubmitEmbedBackfillStatus =- | 'submitted'- | 'cooldown'- | 'spend_capped';+export type SubmitEmbedBackfillResult =+ | { status: 'submitted'; jobId: number; spendCapBypassed: false }+ | { status: 'submitted'; jobId: number; spendCapBypassed: true; spend24hUsd: number }+ | { status: 'cooldown'; reason: 'active_or_waiting'; cooldownRemainingSeconds: null }+ | { status: 'cooldown'; reason: 'recently_finished'; cooldownRemainingSeconds: number }+ | { status: 'spend_capped'; spend24hUsd: number; spendCapUsd: number }+ | { status: 'no_worker_surface'; engineKind: 'pglite' | 'unknown' };-export interface SubmitEmbedBackfillResult {- status: SubmitEmbedBackfillStatus;- /** Set when status === 'submitted'. */- jobId?: number;- /** Set when status === 'cooldown'. Seconds remaining until cooldown lifts. */- cooldownRemainingSeconds?: number;- /** Set when status === 'spend_capped'. Dollars spent in the 24h window. */- spend24hUsd?: number;- /** Set when status === 'spend_capped'. Active cap. */- spendCapUsd?: number;- /**- * Set true when `spend.posture=tokenmax` waved the job past the 24h spend- * cap (#2139). The spend is still LEDGERED by the per-job BudgetTracker —- * posture removes the ceiling, not the accounting. Cooldown is NOT bypassed- * (it's queue-churn protection, not a spend gate).- */- spendCapBypassed?: boolean;-}+export type SubmitEmbedBackfillStatus = SubmitEmbedBackfillResult['status'];export interface SubmitEmbedBackfillOpts {/** Logged into the job's data row for audit. */@@ -139,6 +130,12 @@ export async function submitEmbedBackfill(sourceId: string,opts: SubmitEmbedBackfillOpts,): Promise<SubmitEmbedBackfillResult> {+ // PGLite has no persistent worker process: a queued job cannot be drained+ // after this submission call returns. Refuse before reading gates or writing+ // a row so the undrainable job cannot also cooldown-block a later attempt.+ const surface = embedBackfillWorkerSurface(engine);+ if (surface.status === 'no_worker_surface') return surface;+const now = opts.nowMs ?? Date.now();const cooldownMin =opts.cooldownMinOverride ??@@ -168,8 +165,9 @@ export async function submitEmbedBackfill(if (lastJob[0]) {if (lastJob[0].status === 'active' || lastJob[0].status === 'waiting') {- // Active or waiting: no cooldown-remaining number (would be misleading).- return { status: 'cooldown' };+ // Active or waiting has no truthful retry countdown; keep the payload+ // required and explicit instead of omitting a branch-dependent field.+ return { status: 'cooldown', reason: 'active_or_waiting', cooldownRemainingSeconds: null };}if (lastJob[0].finished_at) {const finishedMs = new Date(lastJob[0].finished_at).getTime();@@ -178,6 +176,7 @@ export async function submitEmbedBackfill(if (ageMs < cooldownMs) {return {status: 'cooldown',+ reason: 'recently_finished',cooldownRemainingSeconds: Math.ceil((cooldownMs - ageMs) / 1000),};}@@ -214,7 +213,7 @@ export async function submitEmbedBackfill(return spendCapBypassed? { status: 'submitted', jobId: job.id, spendCapBypassed: true, spend24hUsd: spend24h }- : { status: 'submitted', jobId: job.id };+ : { status: 'submitted', jobId: job.id, spendCapBypassed: false };}/** Round timestamp down to the nearest `bucketMs` boundary. */diff --git a/src/core/embedding-input-limit.ts b/src/core/embedding-input-limit.tsnew file mode 100644index 0000000000..21f77b5b4b--- /dev/null+++ b/src/core/embedding-input-limit.ts@@ -0,0 +1,100 @@+/**+ * #4530 — per-model embedding INPUT token limits.+ *+ * Some hosted encoders enforce a hard cap per single input, far below their+ * batch budget: NVIDIA NIM's `nvidia/nv-embedqa-e5-v5` rejects any input over+ * 512 tokens with a non-transient 400 ("Input length N exceeds maximum+ * allowed token size 512"). The chunker historically calibrated to+ * OpenAI/Voyage-class limits (8K-32K), so on a 512-token model ~35% of chunks+ * in a typical vault could NEVER embed — every sweep re-failed them.+ *+ * This module resolves the effective chunk-token cap for the ACTIVE embedding+ * model so the chunkers split (never truncate) at a size the model accepts:+ *+ * GBRAIN_MAX_CHUNK_TOKENS env (escape hatch for models not in a recipe)+ * → recipe per-model `max_input_tokens` × EMBED_INPUT_SAFETY+ * → DEFAULT_MAX_CHUNK_TOKENS (2000 — unchanged for every other provider)+ *+ * The result is measured in estimateEmbedTokens units (cl100k + CJK-weighted+ * overestimate). EMBED_INPUT_SAFETY covers the mismatch between that estimate+ * and the model's own tokenizer: e5-family models use BERT-style wordpiece,+ * which counts MORE tokens than cl100k on English prose (~1.3-1.5x) and far+ * more on URL/code-dense text. 0.6 × 512 = 307 estimated tokens ≈ 1.2-1.5K+ * chars of prose — consistent with the field-tested 1,100-char safe bound+ * from the issue report. Fail-open: any resolution error returns the default+ * (a resolver bug must never change chunking for unaffected installs).+ */++import { DEFAULT_MAX_CHUNK_TOKENS } from './chunkers/token-estimate.ts';+import { getEmbeddingModel } from './ai/gateway.ts';+import { resolveRecipe } from './ai/model-resolver.ts';+import type { Recipe } from './ai/types.ts';++/** Utilization ceiling applied to a recipe-declared per-input token limit. */+export const EMBED_INPUT_SAFETY = 0.6;++/** Hard floor so a tiny declared limit can't produce confetti chunks. */+const MIN_CHUNK_TOKENS = 64;++/**+ * wave-g: warn once per distinct invalid value, not once per call — the+ * resolver runs per chunkText site, so a typo'd env var would otherwise+ * emit one stderr line per page across a whole backfill. Keyed by value so+ * a CHANGED (still-invalid) value warns again.+ */+let warnedInvalidRaw: string | undefined;++/**+ * Per-model `max_input_tokens` lookup, mirroring model_dims' case-fold rule+ * (#4123): exact match first, then a case-insensitive scan; configured ids+ * arrive cased and recipe tables can carry cased keys.+ */+export function maxInputTokensForModel(recipe: Recipe, modelId: string): number | undefined {+ const table = recipe.touchpoints?.embedding?.max_input_tokens;+ if (!table) return undefined;+ const direct = table[modelId];+ if (typeof direct === 'number' && direct > 0) return direct;+ const folded = modelId.trim().toLowerCase();+ for (const [k, v] of Object.entries(table)) {+ if (k.toLowerCase() === folded && typeof v === 'number' && v > 0) return v;+ }+ return undefined;+}++/**+ * Effective chunk-token cap for the active embedding model. See module doc.+ * Never exceeds DEFAULT_MAX_CHUNK_TOKENS (existing downstream sizing —+ * tsvector limits, context assembly — calibrates to it) and never goes below+ * MIN_CHUNK_TOKENS.+ */+export function resolveMaxChunkTokens(env: Record<string, string | undefined> = process.env): number {+ const raw = env.GBRAIN_MAX_CHUNK_TOKENS;+ if (raw !== undefined && raw.trim() !== '') {+ const n = Number(raw);+ if (Number.isFinite(n) && n > 0) {+ return Math.min(DEFAULT_MAX_CHUNK_TOKENS, Math.max(MIN_CHUNK_TOKENS, Math.floor(n)));+ }+ // Lenient: a typo'd env var must not change chunking silently mid-vault.+ // Once per process per value (wave-g) — not once per chunkText call.+ if (warnedInvalidRaw !== raw) {+ warnedInvalidRaw = raw;+ console.error(+ `[chunker] ignoring invalid GBRAIN_MAX_CHUNK_TOKENS=${JSON.stringify(raw)} — using model/default resolution`,+ );+ }+ }+ try {+ const { parsed, recipe } = resolveRecipe(getEmbeddingModel());+ const declared = maxInputTokensForModel(recipe, parsed.modelId);+ if (declared !== undefined) {+ return Math.min(+ DEFAULT_MAX_CHUNK_TOKENS,+ Math.max(MIN_CHUNK_TOKENS, Math.floor(declared * EMBED_INPUT_SAFETY)),+ );+ }+ } catch {+ // Gateway not configured (tests, engine-free paths) or unknown provider —+ // keep the historical default.+ }+ return DEFAULT_MAX_CHUNK_TOKENS;+}diff --git a/src/core/embedding.ts b/src/core/embedding.tsindex f1b2701d45..658b59372a 100644--- a/src/core/embedding.ts+++ b/src/core/embedding.ts@@ -193,9 +193,9 @@ export function currentEmbeddingSignature(): string | null {export type SyncEmbedMode = 'deferred' | 'inline';/**- * Resolve the embed mode from the same three signals sync.ts uses to- * compute `effectiveNoEmbed`. Single source of truth so the cost gate and- * the actual embed decision can never drift.+ * Resolve the embed mode from the original public v2/serial contract.+ * `./embedding` is a package export, so keep this call shape stable for+ * downstream TypeScript and JavaScript consumers.** effectiveNoEmbed = v2Enabled && !serialFlag && !noEmbed ? true : noEmbed*@@ -216,6 +216,15 @@ export function willEmbedSynchronously(opts: {return effectiveNoEmbed ? 'deferred' : 'inline';}+/** Internal worker-capability-aware mode used by the sync command boundary. */+export function resolveWorkerBackedSyncEmbedMode(opts: {+ deferEligible: boolean;+ noEmbed: boolean;+}): SyncEmbedMode {+ const effectiveNoEmbed = opts.deferEligible || opts.noEmbed;+ return effectiveNoEmbed ? 'deferred' : 'inline';+}+/*** Pure cost-gate decision. The gate BLOCKS (prompt in TTY, auto-defer in* non-TTY) only when embed runs inline AND the estimated spend exceeds thediff --git a/src/core/engine-factory.ts b/src/core/engine-factory.tsindex bd1676dec1..ba5878722c 100644--- a/src/core/engine-factory.ts+++ b/src/core/engine-factory.ts@@ -1,6 +1,6 @@import type { BrainEngine } from './engine.ts';import type { EngineConfig } from './types.ts';-import { setChatUsageSink, makeEngineChatUsageSink } from './ai/chat-usage.ts';+import { registerChatUsageSink, makeEngineChatUsageSink } from './ai/chat-usage.ts';/*** Create an engine instance based on config.@@ -30,10 +30,18 @@ export async function createEngine(config: EngineConfig): Promise<BrainEngine> {// #4218: route gateway.chat() usage accounting into this engine's// chat_usage_log. Every production engine flows through this factory, so// registering here covers CLI, MCP serve, and the minion worker without- // per-caller wiring. Last engine created wins (multi-brain processes log- // against the most recent — documented best-effort); the sink is fail-open,- // so a not-yet-migrated or already-closed engine never breaks a chat call.- setChatUsageSink(makeEngineChatUsageSink(engine));+ // per-caller wiring. #4480: registration is a STACK entry, deregistered on+ // engine.disconnect — a short-lived secondary engine (migrate target,+ // doctor probe) no longer permanently steals the ledger, and records never+ // route to a closed engine. Concurrent multi-engine attribution remains+ // top-of-stack best-effort; the sink is fail-open, so a not-yet-migrated+ // engine never breaks a chat call.+ const deregisterUsageSink = registerChatUsageSink(makeEngineChatUsageSink(engine));+ const origDisconnect = engine.disconnect.bind(engine);+ engine.disconnect = async (): Promise<void> => {+ deregisterUsageSink();+ await origDisconnect();+ };return engine;}diff --git a/src/core/engine.ts b/src/core/engine.tsindex 19109c0021..2052dd7b1f 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1319,6 +1319,11 @@ export interface BrainEngine {* constrains the delete to a specific provenance ('frontmatter', 'markdown',* 'manual') — used by runAutoLink reconciliation to avoid deleting edges from* other provenances when pruning frontmatter-derived edges.+ *+ * #4527: returns the number of rows actually deleted (via RETURNING) so+ * callers can distinguish a real removal from a no-op (typo'd slug, wrong+ * type/provenance, already-removed edge) instead of both looking like+ * success.*/removeLink(from: string,@@ -1326,7 +1331,7 @@ export interface BrainEngine {linkType?: string,linkSource?: string,opts?: { fromSourceId?: string; toSourceId?: string },- ): Promise<void>;+ ): Promise<number>;/*** #3674 — bulk removal of derived links for a set of FROM pages, scoped to* one link_source. The substrate for `extract links --by-mention --rebuild`:@@ -1568,9 +1573,18 @@ export interface BrainEngine {* `opts` for the brain-wide behavior (unchanged). When both are set,* `sourceIds` wins (mirrors `sourceScopeOpts` precedence).*/+ /**+ * #4524: `mode` selects the orphan definition. 'islanded' (the DEFAULT)+ * matches get_health.orphan_pages — no live inbound AND no live outbound+ * link — so every consumer (orphans CLI, find_orphans op, doctor+ * orphan_ratio, health) agrees by construction. 'inbound' is the legacy+ * no-inbound-only view (a page that links out but is never linked TO still+ * counts as an orphan there).+ */findOrphanPages(opts?: {sourceId?: string;sourceIds?: string[];+ mode?: 'inbound' | 'islanded';}): Promise<Array<{ slug: string; title: string; domain: string | null }>>;// Tagsdiff --git a/src/core/extract-takes-from-pages.ts b/src/core/extract-takes-from-pages.tsindex a6c26c9396..5693693952 100644--- a/src/core/extract-takes-from-pages.ts+++ b/src/core/extract-takes-from-pages.ts@@ -13,9 +13,17 @@// 100+-case eval suite. v0.42 ships the classifier + CLI; autopilot stays// blocked until eval coverage catches up.+import { existsSync } from 'node:fs';import type { BrainEngine } from './engine.ts';-import type { TakeBatchInput, TakeKind } from './engine.ts';+import type { TakeKind } from './engine.ts';import { chat, getChatModel, isAvailable } from './ai/gateway.ts';+import {+ appendTakesToPageMdFirst,+ isSafeFenceCellText,+ resolveTakesRepoDir,+ resolveTakesWritePath,+ TakesWriteError,+} from './takes-write.ts';export const ALLOWED_PAGE_TYPES = ['concept', 'atom', 'lore', 'briefing', 'writing', 'originals',@@ -68,6 +76,15 @@ export interface ExtractTakesFromPagesResult {consent_gate_blocked: boolean;/** True if chat gateway is unavailable (no LLM call possible). */llm_unavailable: boolean;+ /**+ * #4473 — pages the md-first writer refused (takes are markdown-canonical;+ * a page with no locatable .md file is skipped BEFORE the LLM call, never+ * written DB-only). Skipped pages hold no takes, so future runs rescan them.+ */+ pages_skipped: number;+ skipped: Array<{ slug: string; reason: string }>;+ /** Count of pages whose md write landed but whose DB mirror warned (reconcile heals). */+ mirror_warnings: number;}interface PageRow {@@ -111,6 +128,7 @@ export async function extractTakesFromPages(engine: BrainEngine,opts: ExtractTakesFromPagesOpts,): Promise<ExtractTakesFromPagesResult> {+ const emptyTail = { pages_skipped: 0, skipped: [], mirror_warnings: 0 };// A12 consent gate: refuse without bootstrap_enabled even on manual call.if (!opts.bootstrapEnabled) {return {@@ -118,6 +136,7 @@ export async function extractTakesFromPages(claims_extracted: 0,consent_gate_blocked: true,llm_unavailable: false,+ ...emptyTail,};}@@ -127,6 +146,7 @@ export async function extractTakesFromPages(claims_extracted: 0,consent_gate_blocked: false,llm_unavailable: true,+ ...emptyTail,};}@@ -162,21 +182,18 @@ export async function extractTakesFromPages(let pagesScanned = 0;let claimsExtracted = 0;- const batch: TakeBatchInput[] = [];+ let pagesSkipped = 0;+ let mirrorWarnings = 0;+ const skipped: Array<{ slug: string; reason: string }> = [];+ // #4473: takes are markdown-canonical (takes-write.ts contract), so the+ // bootstrap routes every write through the fence writer instead of minting+ // DB-only rows the next reconcile/extract would clobber.+ const repoDir = await resolveTakesRepoDir(engine);- async function flush() {- if (batch.length === 0) return;- if (!dryRun) {- try {- claimsExtracted += await engine.addTakesBatch(batch);- } catch {- // batch error — drop and continue with subsequent pages- }- } else {- claimsExtracted += batch.length;- }- batch.length = 0;- }+ const skipPage = (slug: string, reason: string) => {+ pagesSkipped++;+ skipped.push({ slug, reason });+ };for (const page of pages) {pagesScanned++;@@ -184,6 +201,23 @@ export async function extractTakesFromPages(if (!page.compiled_truth || page.compiled_truth.length < 200) continue;+ // #4473: locate the page's markdown home BEFORE the LLM call — a page the+ // fence writer would refuse must not burn classifier budget (skipped pages+ // hold no takes, so every future run would re-classify them).+ if (!dryRun) {+ let locatable = false;+ try {+ const { path } = await resolveTakesWritePath(engine, repoDir, page.slug, page.source_id);+ locatable = existsSync(path);+ } catch {+ locatable = false; // mirror_unavailable (no repo dir + no source local_path)+ }+ if (!locatable) {+ skipPage(page.slug, 'mirror_unavailable');+ continue;+ }+ }+// Truncate to keep per-page cost bounded (~20K chars → ~5K input tokens).const text = page.compiled_truth.slice(0, 20_000);@@ -213,31 +247,49 @@ export async function extractTakesFromPages(const claims = parseClaimsJson(response.text);if (claims.length === 0) continue;- // Assign row_num starting from 1 per page. We don't query existing- // takes for the page — collisions on (page_id, row_num) are an existing- // bug class addresses by extract-conversation-facts; takes-bootstrap- // inherits the same posture: writes start at row_num=1 and the engine's- // unique constraint surfaces duplicates as failures (caller re-runs).- for (let i = 0; i < claims.length; i++) {- const c = claims[i];- batch.push({- page_id: page.id,- row_num: i + 1,- claim: c.claim,- kind: c.kind,- holder,- weight: c.weight,- source: 'cli:takes-bootstrap-from-pages',- });+ if (dryRun) {+ claimsExtracted += claims.length;+ continue;+ }++ // #4473: md-first write through the fence pipeline (row numbers derive+ // from the fence — max existing + 1 — so the historical row_num=1+ // collision posture is gone). LLM output is pre-filtered against the+ // fence-cell guards so one garbled claim drops alone instead of sinking+ // the page's other claims.+ const safeClaims = claims.filter((c) => isSafeFenceCellText(c.claim));+ if (safeClaims.length === 0) continue;+ try {+ const { rowNums, mirror } = await appendTakesToPageMdFirst(+ { engine, slug: page.slug, brainDir: repoDir, sourceId: page.source_id },+ safeClaims.map((c) => ({+ claim: c.claim,+ kind: c.kind,+ holder,+ weight: c.weight,+ source: 'cli:takes-bootstrap-from-pages',+ })),+ );+ claimsExtracted += rowNums.length;+ if (mirror.mirror_warning) mirrorWarnings++;+ } catch (err) {+ if (err instanceof TakesWriteError) {+ // Skip + count (mirror_unavailable race, fence_unparsed, page_locked,+ // invalid_input) — never fall back to a DB-only write.+ skipPage(page.slug, err.code);+ continue;+ }+ throw err;}- if (batch.length >= 200) await flush();}- await flush();return {pages_scanned: pagesScanned,claims_extracted: claimsExtracted,consent_gate_blocked: false,llm_unavailable: false,+ pages_skipped: pagesSkipped,+ skipped,+ mirror_warnings: mirrorWarnings,};}diff --git a/src/core/extract/rollup-writer.ts b/src/core/extract/rollup-writer.tsindex ca339a6244..791eb13151 100644--- a/src/core/extract/rollup-writer.ts+++ b/src/core/extract/rollup-writer.ts@@ -46,11 +46,42 @@ export interface RollupUpsertInput {eval_fail_delta?: number;eval_pass_delta?: number;round_completed_delta?: number;+ /** #4482: EXPECTED-limit stop (per-source budget / walltime cap working as+ * designed — partial progress banked, more on the next run). Orthogonal to+ * halt_delta so doctor's failure rate can exclude self-imposed capacity+ * limits. Column added by migration v141. */+ expected_limit_delta?: number;/** Increment rollup_write_failures inside the table (used by the* self-healing path that records its own write failures forensically). */failure_delta?: number;}+/**+ * #4482: shared classification of how an extract run stopped, so every+ * extractor records the same three-way split instead of hand-folding its+ * flags into one `halted` boolean:+ * - error (provider/auth/global abort, per-page failures) → halt_delta=1 —+ * the failure-oriented signal doctor warns on, unchanged from today;+ * - expected cap only (budget/deadline, no error) → expected_limit_delta=1+ * — a capacity signal, observable but NOT a failure;+ * - clean completion → round_completed_delta=1.+ * An error present alongside a cap counts as an error (the cap didn't cause+ * the failed work).+ */+export function classifyRunStop(stop: {+ budget_exhausted?: boolean;+ deadline_hit?: boolean;+ error?: boolean;+}): { round_completed_delta: number; halt_delta: number; expected_limit_delta: number } {+ if (stop.error === true) {+ return { round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0 };+ }+ if (stop.budget_exhausted === true || stop.deadline_hit === true) {+ return { round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1 };+ }+ return { round_completed_delta: 1, halt_delta: 0, expected_limit_delta: 0 };+}+function today(): string {// ISO YYYY-MM-DD in UTC. Matches Postgres CURRENT_DATE behavior for// UTC servers; for local-time servers there's a slight drift at midnight@@ -77,6 +108,7 @@ export async function upsertExtractRollup(const evalFails = input.eval_fail_delta ?? 0;const evalPasses = input.eval_pass_delta ?? 0;const completed = input.round_completed_delta ?? 0;+ const expectedLimits = input.expected_limit_delta ?? 0;const failures = input.failure_delta ?? 0;try {@@ -84,22 +116,50 @@ export async function upsertExtractRollup(`INSERT INTO extract_rollup_7d (kind, source_id, day,cost_usd, halt_count, eval_fail_count, eval_pass_count,- round_completed_count, rollup_write_failures, updated_at+ round_completed_count, expected_limit_count, rollup_write_failures, updated_at)- VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, now())+ VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, $10, now())ON CONFLICT (kind, source_id, day) DO UPDATE SETcost_usd = extract_rollup_7d.cost_usd + EXCLUDED.cost_usd,halt_count = extract_rollup_7d.halt_count + EXCLUDED.halt_count,eval_fail_count = extract_rollup_7d.eval_fail_count + EXCLUDED.eval_fail_count,eval_pass_count = extract_rollup_7d.eval_pass_count + EXCLUDED.eval_pass_count,round_completed_count = extract_rollup_7d.round_completed_count + EXCLUDED.round_completed_count,+ expected_limit_count = extract_rollup_7d.expected_limit_count + EXCLUDED.expected_limit_count,rollup_write_failures = extract_rollup_7d.rollup_write_failures + EXCLUDED.rollup_write_failures,updated_at = now()`,- [input.kind, input.source_id, day, cost, halts, evalFails, evalPasses, completed, failures],+ [input.kind, input.source_id, day, cost, halts, evalFails, evalPasses, completed, expectedLimits, failures],);return { ok: true };} catch (err) {const msg = (err as Error).message || String(err);+ // #4482 back-compat: a brain that hasn't applied migration v141 yet has+ // no expected_limit_count column. Rather than losing the WHOLE rollup+ // write (best-effort would swallow it), retry the pre-v141 statement —+ // the cap stop degrades to the old conflated halt accounting until the+ // migration runs.+ if (/expected_limit_count/i.test(msg)) {+ try {+ await engine.executeRaw(+ `INSERT INTO extract_rollup_7d (+ kind, source_id, day,+ cost_usd, halt_count, eval_fail_count, eval_pass_count,+ round_completed_count, rollup_write_failures, updated_at+ )+ VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, now())+ ON CONFLICT (kind, source_id, day) DO UPDATE SET+ cost_usd = extract_rollup_7d.cost_usd + EXCLUDED.cost_usd,+ halt_count = extract_rollup_7d.halt_count + EXCLUDED.halt_count,+ eval_fail_count = extract_rollup_7d.eval_fail_count + EXCLUDED.eval_fail_count,+ eval_pass_count = extract_rollup_7d.eval_pass_count + EXCLUDED.eval_pass_count,+ round_completed_count = extract_rollup_7d.round_completed_count + EXCLUDED.round_completed_count,+ rollup_write_failures = extract_rollup_7d.rollup_write_failures + EXCLUDED.rollup_write_failures,+ updated_at = now()`,+ [input.kind, input.source_id, day, cost, halts + expectedLimits, evalFails, evalPasses, completed, failures],+ );+ return { ok: true };+ } catch { /* fall through to the normal failure record */ }+ }// Don't spam: log once per process per (kind, day) error class.rollupErrorLogOnce(input.kind, day, msg);return { ok: false, error: msg };diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex 16392586c1..ee7aa3bb08 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -344,6 +344,118 @@ export function renderFactsTable(facts: ParsedFact[]): string {return `${FACTS_FENCE_BEGIN}${inner}${FACTS_FENCE_END}`;}+/**+ * #2044 / #4548 row-level, visibility-aware restoration merge for the+ * remote write-back boundary (import-file.ts), replacing the original+ * whole-block swap (which only fired when the incoming fence went to+ * exactly zero facts).+ *+ * `get_page`/`fetch` strip non-'world' rows before an untrusted+ * (`ctx.remote !== false`) caller ever sees them, so a documented+ * get_page -> edit -> put_page round-trip arrives MISSING rows the caller+ * structurally could not have seen — their absence is not an intentional+ * delete. Conversely, 'world'-visible rows WERE fully visible, so an+ * edit/deletion of one is the caller's and must be honored (#4554).+ *+ * Rules:+ * - Only non-'world' rows of the existing fence are restoration+ * candidates. World rows are NEVER restored — a legitimate deletion+ * stays deleted.+ * - A hidden row whose rowNum is absent from the incoming fence is+ * restored at its stable rowNum (cross-page `#F<N>` refs survive).+ * - A hidden row whose rowNum APPEARS in the incoming fence with a+ * DIFFERENT claim is a rowNum collision: the caller never saw that+ * number, so the incoming row is a caller-authored addition that+ * landed on a hidden number. The hidden row keeps its stable number;+ * the caller's row is renumbered onto fresh appended numbers+ * (max rowNum across both sets + 1), matching upsertFactRow's+ * append-only contract.+ * - Same rowNum + same claim: the caller already carries the row (e.g.+ * a full-content write-through) — the incoming version wins, nothing+ * restored, so the merge is idempotent.+ * - Either side parsing with warnings returns null: re-rendering a+ * fence we could not fully parse would drop the caller's unparsed+ * rows. The residual data loss is surfaced by factsGapWarning below.+ *+ * Returns null when there is nothing to restore (pure-world fence, no+ * hidden rows missing, or a non-authoritative parse) — the caller writes+ * the incoming fence as-is. Pure and side-effect-free.+ */+export function restoreHiddenFactRows(+ incoming: { facts: ParsedFact[]; warnings: string[] },+ existing: { facts: ParsedFact[]; warnings: string[] },+): { merged: ParsedFact[]; restored: ParsedFact[]; renumbered: Array<{ from: number; to: number }> } | null {+ if (incoming.warnings.length > 0 || existing.warnings.length > 0) return null;+ const hidden = existing.facts.filter((f) => f.visibility !== 'world');+ if (hidden.length === 0) return null;++ const incomingByRowNum = new Map(incoming.facts.map((f) => [f.rowNum, f]));+ const restored: ParsedFact[] = [];+ const collidingRowNums = new Set<number>();+ for (const h of hidden) {+ const inc = incomingByRowNum.get(h.rowNum);+ if (!inc) {+ restored.push(h);+ } else if (inc.claim !== h.claim) {+ collidingRowNums.add(h.rowNum);+ restored.push(h);+ }+ // claim-equal: incoming already carries the row; keep the incoming version.+ }+ if (restored.length === 0) return null;++ let next = Math.max(+ 0,+ ...incoming.facts.map((f) => f.rowNum),+ ...existing.facts.map((f) => f.rowNum),+ ) + 1;+ const renumbered: Array<{ from: number; to: number }> = [];+ const kept = incoming.facts.map((f) => {+ if (!collidingRowNums.has(f.rowNum)) return f;+ const to = next++;+ renumbered.push({ from: f.rowNum, to });+ return { ...f, rowNum: to };+ });+ const merged = [...kept, ...restored].sort((a, b) => a.rowNum - b.rowNum);+ return { merged, restored, renumbered };+}++/**+ * Surfacing-only diagnostic for the residual data-loss case the #4548+ * row-level merge (restoreHiddenFactRows above) deliberately does not+ * cover: when either fence parses with warnings, the merge refuses to+ * re-render it (that would drop the caller's unparsed rows), so non-'world'+ * rows present before the remote write and missing from the incoming write+ * are still dropped. This warning surfaces exactly that.+ *+ * With clean parses the merge always restores hidden rows, so `restored`+ * is true and this returns null — the pre-#4548 gap (a mixed fence's+ * hidden row silently dropped) no longer occurs.+ *+ * Returns a warning string, or null if nothing to flag. Pure and+ * side-effect-free — the caller decides how to surface it (console.warn+ * today).+ */+export function factsGapWarning(+ slug: string,+ incoming: { facts: ParsedFact[]; warnings: string[] },+ existing: { facts: ParsedFact[]; warnings: string[] },+ restored: boolean,+): string | null {+ if (restored) return null;+ if (existing.facts.length === 0) return null;++ const incomingRowNums = new Set(incoming.facts.map((f) => f.rowNum));+ const dropped = existing.facts.filter(+ (f) => f.visibility !== 'world' && !incomingRowNums.has(f.rowNum),+ ).length;+ if (dropped === 0) return null;+ return `[gbrain] #2044 gap on ${slug}: ${dropped} non-'world' fact row(s) present before this ` ++ `remote write are missing from the incoming write and were NOT restored (the fence parsed ` ++ `with warnings, so the row-level merge could not rewrite it safely). If these rows were ` ++ `dropped by a caller who never saw them, they are now lost.`;+}+/*** Append a new fact row to the body. If a fenced facts table exists, the* row is added to the end of it. If not, a new `## Facts` section + fencediff --git a/src/core/facts/absorb-log.ts b/src/core/facts/absorb-log.tsindex d7baedc486..c03efb39c4 100644--- a/src/core/facts/absorb-log.ts+++ b/src/core/facts/absorb-log.ts@@ -18,6 +18,9 @@* - 'queue_shutdown' — queue rejected the enqueue because shutdown is in progress.* - 'embed_failure' — gateway down on embedOne; row inserts with NULL embedding.* - 'pipeline_error' — anything else absorbed inside runFactsBackstop's catch.+ * - 'gateway_auth' — provider authentication/authorization failed.+ * - 'gateway_billing' — provider credit, quota, or billing hard limit failed.+ * - 'gateway_rate_limit' — provider rate limit; retry policy remains with the caller.* - eligibility_skip is intentionally NOT logged (high cardinality, low signal).** The writer is best-effort — a failure to log SHOULDN'T blow up the@@ -26,6 +29,7 @@*/import type { BrainEngine } from '../engine.ts';+import { classifyGlobalLlmError } from '../ai/errors.ts';import { GBrainError } from '../types.ts';export const FACTS_ABSORB_REASONS = [@@ -45,6 +49,9 @@ export const FACTS_ABSORB_REASONS = ['malformed_output','non_terminal_stop','truncated_output',+ 'gateway_auth',+ 'gateway_billing',+ 'gateway_rate_limit',] as const;// v0.39.3.0 WARN-4 + CV13 — module-scoped flag so the first-occurrence@@ -126,6 +133,29 @@ export async function writeFactsAbsorbLog(}}+/**+ * Persist a provider failure without copying provider response bodies, keys,+ * or request payloads into ingest_log. Global failures get stable typed+ * reason codes; all other failures retain the existing classifier.+ */+export async function writeFactsAbsorbFailure(+ engine: BrainEngine,+ ref: string,+ err: unknown,+ sourceId: string = 'default',+): Promise<void> {+ const globalClass = classifyGlobalLlmError(err);+ const reason: FactsAbsorbReason = globalClass === 'auth'+ ? 'gateway_auth'+ : globalClass === 'billing'+ ? 'gateway_billing'+ : globalClass === 'rate_limit'+ ? 'gateway_rate_limit'+ : classifyFactsAbsorbError(err);+ const errorType = err instanceof Error && err.name ? err.name : 'Error';+ await writeFactsAbsorbLog(engine, ref, reason, `provider request failed (${errorType})`, sourceId);+}+/*** Classify an arbitrary error into one of the stable reason codes. Heuristic* pattern match on error name + message; falls back to 'pipeline_error' whendiff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 56b2ef50dc..44ebde5f0e 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -358,10 +358,8 @@ export async function runFactsBackstop(try {await runPipeline(parsedPage, ctx, signal);} catch (err) {- const { classifyFactsAbsorbError, writeFactsAbsorbLog } = await import('./absorb-log.ts');- const reason = classifyFactsAbsorbError(err);- const msg = err instanceof Error ? err.message : String(err);- await writeFactsAbsorbLog(ctx.engine, parsedPage.slug, reason, msg, ctx.sourceId);+ const { writeFactsAbsorbFailure } = await import('./absorb-log.ts');+ await writeFactsAbsorbFailure(ctx.engine, parsedPage.slug, err, ctx.sourceId);}}, ctx.sessionId ?? parsedPage.slug);@@ -641,10 +639,16 @@ async function runPipelineWithBody(const legacyBucket: SurvivedFact[] = [];if (localPath === null) {if (!writeThroughDisabled) {+ // #4489: name the REAL remedy. The sources dispatcher has no+ // "update" verb — attaching a working tree to a path-less source goes+ // through `gbrain sources add <id> --path <dir>` (the #3903+ // non-destructive attach path in sources-ops.ts). Pinned by+ // test/facts-backstop-remedy-verb.test.ts.warnOnce('facts:thin-client-fallback','[facts] sources.local_path unset for source_id=' + ctx.sourceId +- ' — falling through to DB-only inserts. Configure local_path via `gbrain sources update` to enable system-of-record fence writes.',+ ' — falling through to DB-only inserts. Attach a working tree via `gbrain sources add ' + ctx.sourceId ++ ' --path <dir>` to enable system-of-record fence writes.',);}for (const s of survived) legacyBucket.push(s);diff --git a/src/core/github-source.ts b/src/core/github-source.tsindex 96aa37bca3..e5e0c7853e 100644--- a/src/core/github-source.ts+++ b/src/core/github-source.ts@@ -1514,9 +1514,9 @@ async function runExtractAndEmbed(const sub = await submitEmbedBackfill(deps.engine, deps.sourceId, { reason: 'github_sync_defer' });if (sub.status === 'submitted') {process.stderr.write(`[github] large sync (${totalChanges} pages); embeds deferred to embed-backfill job ${sub.jobId} — or ${drainHint}\n`);- } else {+ } else if (sub.status === 'cooldown' || sub.status === 'spend_capped' || sub.status === 'no_worker_surface') {process.stderr.write(`[github] large sync (${totalChanges} pages); embed-backfill not queued (${sub.status}) — ${drainHint}\n`);- }+ } else { sub satisfies never; }} catch (err) {process.stderr.write(`[github] embed-backfill submission failed: ${err instanceof Error ? err.message : String(err)} — ${drainHint}\n`);}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 83310b07d9..1fd541447b 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -5,6 +5,7 @@ import type { BrainEngine, FileSpec } from './engine.ts';import { parseMarkdown } from './markdown.ts';import { classifyStoredType } from './schema-pack/type-usage.ts';import { chunkText } from './chunkers/recursive.ts';+import { resolveMaxChunkTokens } from './embedding-input-limit.ts';import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';import { planEmbeddingReuse } from './embed-reuse.ts';@@ -47,7 +48,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 } from './facts-fence.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning } from './facts-fence.ts';import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';/**@@ -109,14 +110,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 extractFactsFenceBlock(body: string): string | null {- const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);- if (beginIdx === -1) return null;- const endIdx = body.indexOf(FACTS_FENCE_END, beginIdx + FACTS_FENCE_BEGIN.length);- if (endIdx === -1) return null;- return body.slice(beginIdx, endIdx + FACTS_FENCE_END.length);-}-function replaceOrAppendFactsFence(body: string, fenceBlock: string): string {const beginIdx = body.indexOf(FACTS_FENCE_BEGIN);if (beginIdx !== -1) {@@ -130,6 +123,46 @@ function replaceOrAppendFactsFence(body: string, fenceBlock: string): string {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+ * rows that are missing from the incoming body (a remote get_page/fetch+ * stripped them before the caller ever saw them, so their absence is not+ * an intentional delete). World-visible rows are never restored — the+ * caller saw those in full, so an edit/deletion is honored as written.+ * See restoreHiddenFactRows() in facts-fence.ts for the merge rules+ * (stable rowNums, collision renumbering, idempotence, warnings gate).+ *+ * Returns the (possibly merged) body. Emits console.warn for the two+ * surfaced conditions: a caller-authored row renumbered off a hidden+ * rowNum, and the residual malformed-fence case where the merge could not+ * run and hidden rows are genuinely dropped (factsGapWarning).+ */+function mergeHiddenFactRowsIntoBody(+ slug: string,+ incomingBody: string,+ existingBody: string | null | undefined,+): string {+ if (!existingBody) return incomingBody;+ const incomingFacts = parseFactsFence(incomingBody);+ const existingFacts = parseFactsFence(existingBody);+ const merge = restoreHiddenFactRows(incomingFacts, existingFacts);+ if (merge) {+ if (merge.renumbered.length > 0) {+ console.warn(+ `[gbrain] #2044 merge on ${slug}: ${merge.renumbered.length} incoming fact row(s) reused ` ++ `row number(s) belonging to privacy-hidden row(s) and were renumbered ` ++ `(${merge.renumbered.map((r) => `#${r.from}->#${r.to}`).join(', ')}); ` ++ `the hidden row(s) keep their original numbers.`,+ );+ }+ return replaceOrAppendFactsFence(incomingBody, renderFactsTable(merge.merged));+ }+ const gapWarning = factsGapWarning(slug, incomingFacts, existingFacts, false);+ if (gapWarning) console.warn(gapWarning);+ return incomingBody;+}+/*** Extract recognizable code fences via the linear scanner in fence-scan.ts* (#2862 — formerly a `marked.lexer` walk, which was quadratic on@@ -602,24 +635,25 @@ export async function importFromContent(// unscoped-check/scoped-write bug class).const existing = await engine.getPage(slug, { sourceId: sourceId ?? 'default' });- // #2044: remote get_page intentionally strips private facts rows. A- // documented get_page -> edit -> put_page round-trip can therefore arrive- // with an empty/missing Facts fence even though the existing page still has- // canonical fence rows. Preserve the old fence in that narrow case so the- // system-of-record markdown is not truncated by the privacy boundary.- if (opts.remote === true && existing?.compiled_truth) {- const incomingFacts = parseFactsFence(parsed.compiled_truth);- const existingFacts = parseFactsFence(existing.compiled_truth);- const existingFenceBlock = extractFactsFenceBlock(existing.compiled_truth);- if (- incomingFacts.facts.length === 0 &&- incomingFacts.warnings.length === 0 &&- existingFacts.warnings.length === 0 &&- existingFacts.facts.length > 0 &&- existingFenceBlock- ) {- parsed.compiled_truth = replaceOrAppendFactsFence(parsed.compiled_truth, existingFenceBlock);- }+ // #2044 / #4548: remote get_page/fetch intentionally strip non-'world'+ // facts rows before an untrusted caller ever sees them. A documented+ // get_page -> edit -> put_page round-trip therefore arrives MISSING rows+ // the caller structurally could never have seen — their absence is not an+ // intentional delete. Restore exactly those rows via the row-level,+ // visibility-aware merge (restoreHiddenFactRows): world-visible rows the+ // caller saw in full are never restored, so a legitimate edit/deletion of+ // a visible row — including deleting a pure-world fence outright — is+ // honored as written (#4554). Trusted local writers see everything, so+ // the merge never fires for them.+ // The same hazard covers the `timeline` column (#4546): a Facts fence+ // below the `<!-- timeline -->` sentinel is a normal placement, and #4547+ // strips its non-'world' rows for remote readers too — so a round-trip+ // write-back arrives missing those rows as well. Each column merges+ // against its own existing counterpart (fences don't migrate between+ // columns here; splitBody keeps them where the caller wrote them).+ if (opts.remote === true && existing) {+ parsed.compiled_truth = mergeHiddenFactRowsIntoBody(slug, parsed.compiled_truth, existing.compiled_truth);+ parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, existing.timeline);}// #1035: absence of an explicit frontmatter `type:` on an EXISTING page@@ -780,13 +814,18 @@ export async function importFromContent(// warning marker.)const embedSkipped = isEmbedSkipped(parsed.frontmatter) || isQuarantined(parsed.frontmatter);if (!embedSkipped) {+ // #4530: cap chunk tokens at the ACTIVE embedding model's per-input+ // limit (recipe max_input_tokens x safety; default unchanged) so strict+ // encoders like nvidia/nv-embedqa-e5-v5 (512) never see an unembeddable+ // chunk. Split, not truncated.+ const chunkOpts = { maxTokens: resolveMaxChunkTokens() };if (parsed.compiled_truth.trim()) {- for (const c of chunkText(parsed.compiled_truth)) {+ for (const c of chunkText(parsed.compiled_truth, chunkOpts)) {chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'compiled_truth' });}}if (parsed.timeline?.trim()) {- for (const c of chunkText(parsed.timeline)) {+ for (const c of chunkText(parsed.timeline, chunkOpts)) {chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'timeline' });}}diff --git a/src/core/markdown.ts b/src/core/markdown.tsindex 22b05c4801..aedda5ba24 100644--- a/src/core/markdown.ts+++ b/src/core/markdown.ts@@ -187,6 +187,52 @@ function quoteAmbiguousFrontmatterScalars(content: string): string {return `---\n${fixedBody}\n---${closer}${rest}`;}+/**+ * #4526: gray-matter only recognizes a frontmatter fence at byte 0, but the+ * rest of the pipeline (frontmatterBodyOffset above, collectValidationErrors'+ * MISSING_OPEN check below) tolerates leading blank lines before the opener.+ * A content blob with a single leading newline therefore silently lost its+ * whole frontmatter block: empty data, the block left embedded in the body,+ * and the title humanized from the slug — a raw UUID for `fact/<uuid>`+ * pages. Strip leading blank lines when (and only when) the first non-empty+ * line is a fence, so the parse matches what the validators already accept.+ */+function stripLeadingBlanksBeforeFence(content: string): string {+ if (!/^[ \t\r]*\n/.test(content)) return content; // fast path: first line non-blank+ const lines = content.split('\n');+ let i = 0;+ while (i < lines.length && lines[i].trim().length === 0) i++;+ if (i === 0 || i >= lines.length || lines[i].trim() !== '---') return content;+ return lines.slice(i).join('\n');+}++/**+ * #4526 (second arm): pages already corrupted by the pre-fix parse carry+ * their real frontmatter EMBEDDED at the top of the body (double-frontmatter+ * after a get→put round-trip). When the normal precedence found no title+ * (no frontmatter `title:`, no body H1) and the alternative is humanizing+ * the slug/filename, promote a `title:` from the embedded leading fence+ * block instead. Deliberately last-before-fallback: it never overrides a+ * real title, it only rescues the junk-title case.+ */+function inferTitleFromEmbeddedFrontmatter(body: string): string {+ const m = body.match(/^\s*---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/);+ if (!m) return '';+ for (const line of m[1]!.split('\n')) {+ const kv = line.match(/^title:[ \t]+(.+?)[ \t\r]*$/);+ if (!kv) continue;+ let value = kv[1]!;+ if (+ (value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)+ ) {+ value = value.slice(1, -1);+ }+ return value.trim();+ }+ return '';+}+export function parseMarkdown(content: string,filePath?: string,@@ -206,7 +252,9 @@ export function parseMarkdown(// so there's no failure signal to react to after the fact. Pre-quoting// ambiguous values keeps that input from ever reaching gray-matter in// its broken shape.- const safeContent = quoteAmbiguousFrontmatterScalars(content);+ // #4526: lift the fence to byte 0 first (leading blank lines are legal per+ // the validators), THEN quote ambiguous scalars (whose regex anchors ^---).+ const safeContent = quoteAmbiguousFrontmatterScalars(stripLeadingBlanksBeforeFence(content));let parsed: ReturnType<typeof matter> | null = null;let yamlParseError: Error | null = null;try {@@ -248,9 +296,13 @@ export function parseMarkdown(// the H1 fallback they get junk titles humanized from the slug// (`Contact 20170928 5 John Defalco`), which also breaks anything keyed on// the title (e.g. the by-mention gazetteer's first-token bucketing).+ // #4526: an embedded leading fence block's `title:` outranks only the+ // humanized-filename fallback — it rescues pages the pre-fix parse left+ // with their frontmatter stuck in the body, without overriding real titles.const title =coerceFrontmatterString(frontmatter.title).trim() ||inferTitleFromBody(body) ||+ inferTitleFromEmbeddedFrontmatter(body) ||inferTitle(filePath);const tags = extractTags(frontmatter);const slug = coerceFrontmatterString(frontmatter.slug) || inferSlug(filePath);@@ -550,7 +602,7 @@ export function findTimelineSplitIndex(lines: string[]): number {for (let j = i + 1; j < lines.length; j++) {const next = lines[j].trim();if (next.length === 0) continue;- if (/^##\s+(timeline|history)\b/i.test(next)) return i;+ if (/^##\s+(timeline|history)\s*$/i.test(next)) return i;break;}}@@ -882,7 +934,7 @@ function extractTags(frontmatter: Record<string, unknown>): string[] {// ---------------------------------------------------------------------------import { existsSync } from 'node:fs';-import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { dirname, isAbsolute, join, relative, resolve, sep as pathSep } from 'node:path';/** Options for serializePageToMarkdown. */export interface SerializePageOpts {@@ -964,7 +1016,19 @@ export function resolvePageFilePath(** Returns null for an unsafe or non-markdown source path. Callers must still* enforce their normal realpath containment check before a write.+ *+ * Segment splitting is platform-aware (`pathSep`), not a blanket+ * `[\\/]+` split: on POSIX, `\` is a legal filename character (real+ * gbrain data has Apple Notes titles containing one), not a directory+ * separator, so splitting on it there reconstructs a path that doesn't+ * exist on disk even though the file does (issue: undeclared_db_only_pages+ * false positive + silent restore/export failure for any such file). On+ * Windows, `\` is the real separator, so it still needs to split there.*/+function splitLocalPathSegments(value: string): string[] {+ return (pathSep === '\\' ? value.split(/[\\/]+/) : value.split(/\/+/)).filter(Boolean);+}+export function resolveSourceLocalFilePath(localPath: string,rawSourcePath: string | null | undefined,@@ -973,14 +1037,14 @@ export function resolveSourceLocalFilePath(const value = rawSourcePath.trim();if (!value || value.includes('\0') || !/\.mdx?$/i.test(value)) return null;if (isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value)) return null;- const sourceSegments = value.split(/[\\/]+/).filter(Boolean);+ const sourceSegments = splitLocalPathSegments(value);if (sourceSegments.length === 0 || sourceSegments.some(segment => segment === '..')) return null;const absoluteLocalPath = resolve(localPath);let cursor = absoluteLocalPath;while (true) {if (existsSync(join(cursor, '.git'))) {- const scope = relative(cursor, absoluteLocalPath).split(/[\\/]+/).filter(Boolean);+ const scope = splitLocalPathSegments(relative(cursor, absoluteLocalPath));if (scope.length > 0 && scope.every((segment, index) => segment === sourceSegments[index])) {return join(absoluteLocalPath, ...sourceSegments.slice(scope.length));}diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex e5043db66e..da429f5db4 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -6184,6 +6184,22 @@ export const MIGRATIONS: Migration[] = [ON chat_usage_log (model, created_at);`,},+ {+ version: 141,+ name: 'extract_rollup_expected_limit',+ // #4482: orthogonal counter for EXPECTED-limit stops (per-source budget /+ // walltime caps working as designed). halt_count keeps its historical+ // meaning — rows written before this migration conflate error halts and+ // cap stops and are deliberately NOT reclassified (they read as 0 caps,+ // i.e. "unknown"). New writers record error halts in halt_count and cap+ // stops here, so doctor's extract_health failure rate can exclude+ // self-imposed capacity limits while keeping them observable.+ idempotent: true,+ sql: `+ ALTER TABLE extract_rollup_7d+ ADD COLUMN IF NOT EXISTS expected_limit_count INTEGER NOT NULL DEFAULT 0;+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/detached-stderr.ts b/src/core/minions/detached-stderr.tsnew file mode 100644index 0000000000..64181a5790--- /dev/null+++ b/src/core/minions/detached-stderr.ts@@ -0,0 +1,85 @@+/**+ * #4418 — durable stderr sink + spawn helper for `gbrain jobs supervisor+ * start --detach`.+ *+ * The detach path used to re-exec the supervisor with+ * `stdio: ['ignore','ignore','inherit']`: the detached supervisor inherited+ * the INVOKER's stderr, and its worker (ChildWorkerSupervisor spawns with+ * `stdio: 'inherit'`) inherited that same descriptor. When a short-lived+ * automation runner closed its capture pipe after the start payload+ * returned, the worker exited 141 (SIGPIPE) on its next stderr write, and+ * the supervisor — writing its crash/backoff event to the same closed+ * stream — could die too, leaving active jobs and DB locks stale while+ * producers kept enqueueing.+ *+ * Fix: give the detached supervisor a durable sink — an append-mode log in+ * the audit dir (`${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-stderr.log`,+ * next to the JSONL lifecycle audit), falling back to the null device, then+ * to 'ignore'. The worker inherits the supervisor's fd, so ONE durable+ * descriptor covers both processes — not a per-call EPIPE swallow.+ */++import { spawn } from 'node:child_process';+import { closeSync, mkdirSync, openSync } from 'node:fs';+import { join } from 'node:path';+import { resolveAuditDir } from '../audit/audit-writer.ts';++export interface DetachedStderrSink {+ /** fd to pass as the child's stdio[2]; 'ignore' when nothing could be opened. */+ fd: number | 'ignore';+ /** Human-readable location for the start payload; null when 'ignore'. */+ path: string | null;+}++const NULL_DEVICE = process.platform === 'win32' ? '\\\\.\\NUL' : '/dev/null';++/**+ * Open the durable sink: audit-dir log (append) → null device → 'ignore'.+ * Never throws — a sink failure must not block the supervisor start.+ */+export function openDetachedStderrSink(logName = 'supervisor-stderr.log'): DetachedStderrSink {+ try {+ const dir = resolveAuditDir();+ mkdirSync(dir, { recursive: true });+ const path = join(dir, logName);+ return { fd: openSync(path, 'a'), path };+ } catch {+ /* fall through to the null device */+ }+ try {+ return { fd: openSync(NULL_DEVICE, 'w'), path: NULL_DEVICE };+ } catch {+ return { fd: 'ignore', path: null };+ }+}++/** Close the parent's copy of the sink fd after spawn (the child holds its own dup). */+export function closeDetachedStderrSink(sink: DetachedStderrSink): void {+ if (typeof sink.fd === 'number') {+ try {+ closeSync(sink.fd);+ } catch {+ /* already closed */+ }+ }+}++/**+ * Re-exec the CLI as a fully detached supervisor: stdin/stdout ignored,+ * stderr on the durable sink (NEVER 'inherit' — the #4418 regression).+ */+export function spawnDetachedSupervisor(+ execPath: string,+ cliScript: string,+ childArgs: string[],+): { pid: number | undefined; stderrPath: string | null } {+ const sink = openDetachedStderrSink();+ const child = spawn(execPath, [cliScript, ...childArgs], {+ detached: true,+ stdio: ['ignore', 'ignore', sink.fd],+ env: process.env,+ });+ child.unref();+ closeDetachedStderrSink(sink);+ return { pid: child.pid, stderrPath: sink.path };+}diff --git a/src/core/minions/embed-backfill-admission.ts b/src/core/minions/embed-backfill-admission.tsnew file mode 100644index 0000000000..ca9e379ec3--- /dev/null+++ b/src/core/minions/embed-backfill-admission.ts@@ -0,0 +1,94 @@+/**+ * Engine-aware admission for the embed-backfill queue job.+ *+ * PGLite has no persistent worker process, so a background row cannot drain.+ * Keep this module dependency-light: MinionQueue calls it before schema,+ * config, policy, SQL, or transaction access.+ */+import type { BrainEngine } from '../engine.ts';+import { assertValidSourceId } from '../source-id.ts';++export const EMBED_BACKFILL_JOB_NAME = 'embed-backfill';++export type EmbedBackfillWorkerSurface =+ | { status: 'worker_backed'; engineKind: 'postgres' }+ | { status: 'no_worker_surface'; engineKind: 'pglite' | 'unknown' };++export interface EmbedBackfillAdmissionTrust {+ /** The caller starts and awaits an inline worker in this same process. */+ allowPgliteInlineWorker?: boolean;+}++export function embedBackfillWorkerSurface(+ engine: Pick<BrainEngine, 'kind'>,+): EmbedBackfillWorkerSurface {+ const kind = engine.kind;+ if (kind === 'postgres') return { status: 'worker_backed', engineKind: 'postgres' };+ if (kind === 'pglite') return { status: 'no_worker_surface', engineKind: 'pglite' };+ kind satisfies never;+ // Runtime defense for untyped plugins/casts whose value is outside the+ // declared union; the compile-time check above forces policy for new kinds.+ return { status: 'no_worker_surface', engineKind: 'unknown' };+}++export function embedBackfillManualDrainCommand(sourceId: string): string {+ const source = sourceId === '' ? '<source-id>' : sourceId;+ if (source !== '<source-id>') assertValidSourceId(source);+ return `gbrain embed --stale --source ${source}`;+}++export class InvalidEmbedBackfillSourceIdError extends Error {+ readonly code = 'invalid_params' as const;+ readonly sourceId: unknown;++ constructor(sourceId: unknown, cause: unknown) {+ super(cause instanceof Error ? cause.message : String(cause));+ this.name = 'InvalidEmbedBackfillSourceIdError';+ this.sourceId = sourceId;+ }+}++function assertEmbedBackfillSourceId(sourceId: unknown): asserts sourceId is string {+ try {+ assertValidSourceId(sourceId);+ } catch (e) {+ throw new InvalidEmbedBackfillSourceIdError(sourceId, e);+ }+}++export class NoEmbedBackfillWorkerSurfaceError extends Error {+ readonly code = 'no_worker_surface' as const;+ readonly engineKind: 'pglite' | 'unknown';+ readonly sourceId: string;++ constructor(sourceId: string, engineKind: 'pglite' | 'unknown' = 'pglite') {+ const source = sourceId || '<source-id>';+ const direct = embedBackfillManualDrainCommand(source);+ const surface = engineKind === 'pglite'+ ? 'PGLite has no persistent worker surface'+ : 'the runtime engine kind has no recognized persistent worker surface';+ super(+ `embed-backfill job rejected: ${surface}, so a queued row cannot drain. ` ++ `Run \`${direct}\` instead.`,+ );+ this.name = 'NoEmbedBackfillWorkerSurfaceError';+ this.engineKind = engineKind;+ this.sourceId = source;+ }+}++export function assertEmbedBackfillQueueAdmission(+ engine: Pick<BrainEngine, 'kind'>,+ jobName: string,+ data?: Record<string, unknown>,+ trusted?: EmbedBackfillAdmissionTrust,+): void {+ if (jobName.trim() !== EMBED_BACKFILL_JOB_NAME) return;+ const rawSourceId = data?.sourceId;+ if (rawSourceId !== undefined) assertEmbedBackfillSourceId(rawSourceId);+ const surface = embedBackfillWorkerSurface(engine);+ if (surface.status === 'worker_backed') return;+ if (surface.engineKind === 'pglite' && trusted?.allowPgliteInlineWorker) return;+ const sourceId = rawSourceId ?? '<source-id>';+ throw new NoEmbedBackfillWorkerSurfaceError(sourceId, surface.engineKind);+}diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex 9f75a2a129..8c1414ccec 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -48,7 +48,7 @@ import {logSubagentSubmission,logSubagentHeartbeat,} from './subagent-audit.ts';-import { resolveModel, isAnthropicProvider, TIER_DEFAULTS } from '../../model-config.ts';+import { resolveModel, isAnthropicProvider, isOpenRouterAnthropic, TIER_DEFAULTS } from '../../model-config.ts';import { splitProviderModelId, normalizeModelId } from '../../model-id.ts';import { resolveAnthropicKey } from '../../ai/anthropic-key.ts';import { buildSystemPrompt, DEFAULT_SUBAGENT_SYSTEM } from '../system-prompt.ts';@@ -417,7 +417,10 @@ export function makeSubagentHandler(deps: SubagentDeps) {// #2753: share the doctor's truthiness set. Before this, the doctor accepted// yes/on but the worker did not, so `config set ... yes` reported healthy// here and still refused the job below.- const useGatewayLoop = isConfigTruthy(useGatewayLoopRaw);+ // OpenRouter Anthropic is not `isAnthropicProvider` (the Messages SDK+ // cannot speak OR). Auto-enable the gateway loop so the legacy pin+ // does not refuse `openrouter:anthropic/…` when the flag is off.+ const useGatewayLoop = isConfigTruthy(useGatewayLoopRaw) || isOpenRouterAnthropic(model);if (!useGatewayLoop && !isAnthropicProvider(model)) {throw new Error(`subagent job: resolved model "${model}" is non-Anthropic but agent.use_gateway_loop is not enabled. ` +@@ -1690,6 +1693,12 @@ function adaptContentBlocksToChatBlocks(blocks: unknown): ChatBlock[] | string {: {};if (t === 'text' && typeof block.text === 'string') {out.push({ type: 'text', text: block.text, ...meta });+ } else if (t === 'reasoning' && typeof block.text === 'string') {+ // OpenAI Responses API reasoning-item id (providerMetadata.openai.itemId)+ // — see the ChatBlock doc comment. Must survive crash-replay the same+ // way tool-call providerMetadata does, or a resumed reasoning-model+ // tool loop dead-letters on its next turn.+ out.push({ type: 'reasoning', text: block.text, ...meta });} else if (t === 'tool_use' && typeof block.id === 'string' && typeof block.name === 'string') {// v1 Anthropic shapeout.push({diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex a7974d5c91..e9953635c2 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -16,6 +16,7 @@ import type {import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';import { validateAttachment } from './attachments.ts';import { isProtectedJobName } from './protected-names.ts';+import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';import {computeParamHash,resolveAdmissionPolicy,@@ -36,14 +37,12 @@ import {logBatchRetry as auditLogBatchRetry,logBatchExhausted as auditLogBatchExhausted,} from '../audit/batch-retry-audit.ts';--/** Options for opting into protected-job-name submission. Passed as a separate- * 4th arg to `MinionQueue.add()` (NOT folded into `opts`) so user-spread- * `{...userOpts}` payloads can't accidentally carry the trust flag. */+/** Trusted 4th argument, kept outside user-spread job options. */export interface TrustedSubmitOpts {- /** When true, allow submission of names in PROTECTED_JOB_NAMES (currently 'shell').- * Set only by the CLI path and by `submit_job` when `ctx.remote === false`. */+ /** Allow PROTECTED_JOB_NAMES; CLI or operation-local callers only. */allowProtectedSubmit?: boolean;+ /** Allow PGLite embed-backfill only for an explicit inline-worker caller. */+ allowPgliteInlineWorker?: boolean;}const MIGRATION_VERSION = 7;@@ -214,6 +213,7 @@ export class MinionQueue {if (jobName.length === 0) {throw new Error('Job name cannot be empty');}+ assertEmbedBackfillQueueAdmission(this.engine, jobName, data, trusted);if (isProtectedJobName(jobName) && !trusted?.allowProtectedSubmit) {throw new Error(`protected job name '${jobName}' requires CLI or operation-local submitter ` +diff --git a/src/core/model-config.ts b/src/core/model-config.tsindex 922e21a76e..73457e09e7 100644--- a/src/core/model-config.ts+++ b/src/core/model-config.ts@@ -305,6 +305,19 @@ export function isAnthropicProvider(modelString: string): boolean {return model.toLowerCase().startsWith('claude-');}+/**+ * OpenRouter Anthropic routes (`openrouter:anthropic/…`). These are NOT+ * native Anthropic (`isAnthropicProvider` stays false — the Messages SDK+ * cannot speak OR). The legacy `!useGatewayLoop && !isAnthropicProvider`+ * pin treats them as an exception and auto-routes through gateway.toolLoop().+ */+export function isOpenRouterAnthropic(modelString: string): boolean {+ if (!modelString) return false;+ const { provider, model } = splitProviderModelId(modelString);+ return provider?.trim().toLowerCase() === 'openrouter'+ && model.toLowerCase().startsWith('anthropic/');+}+const _subagentTierWarningsEmitted = new Set<string>();// Module-level set of deprecated config keys we've already warned about.diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex b28d798ee1..bf5cbd19c0 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -23,7 +23,7 @@ import type {import type { OAuthServerProvider, AuthorizationParams } from '@modelcontextprotocol/sdk/server/auth/provider.js';import type { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients.js';import type { AuthInfo as SdkAuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';-import { InvalidTokenError, InvalidClientMetadataError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { InvalidTokenError, InvalidClientMetadataError, InvalidGrantError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import { hashToken, generateToken, isUndefinedColumnError } from './utils.ts';import { assertValidSourceId } from './source-id.ts';import { hasScope, assertAllowedScopes, parseScopeString, InvalidScopeError } from './scope.ts';@@ -682,14 +682,20 @@ export class GBrainOAuthProvider implements OAuthServerProvider {AND client_id = ${client.client_id}RETURNING client_id, scopes, expires_at`;- if (rows.length === 0) throw new Error('Refresh token not found');+ // #4532: InvalidGrantError (not bare Error) — the SDK's token handler maps+ // OAuthError subclasses to their RFC 6749 wire shape (400 invalid_grant)+ // and everything else to a 500 Internal Server Error. A refresh with a+ // rotated/expired token is a routine client condition (RFC 6749 §5.2+ // invalid_grant), and the 500 made well-behaved MCP clients treat it as a+ // server outage instead of re-running the authorization flow.+ if (rows.length === 0) throw new InvalidGrantError('Refresh token not found');const row = rows[0];// NULL expires_at is treated as expired (fail-closed). Schema permits NULL// even though issueTokens always sets it, so a corrupt or hand-modified row// can't ride past validation.const expiresAt = coerceTimestamp(row.expires_at);- if (expiresAt === undefined || expiresAt < now) throw new Error('Refresh token expired');+ if (expiresAt === undefined || expiresAt < now) throw new InvalidGrantError('Refresh token expired');// F3 hardening: requested scopes on refresh MUST be a subset of the// original grant on this refresh token's row. RFC 6749 §6: "the scope ofdiff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex 403477c92b..c476e1754a 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -68,9 +68,12 @@ export const QUERY_DESCRIPTION ="Hybrid search with vector + keyword + multi-query expansion. " +"Prefer `query` for concept / synonym / landscape questions ('all the X that " +"do Y', 'the landscape of Z') — expansion recovers synonym- and " +- "outcome-phrased matches a single embedding misses. Still top-K: for " +- "exhaustive enumeration use list_pages; for exact known tokens `search` is " +- "cheaper (no expansion LLM call). " ++ "outcome-phrased matches a single embedding misses. Still top-K, and the " ++ "default count when `limit` is omitted depends on the configured search " ++ "mode (10 conservative / 25 balanced / 50 tokenmax — see the `limit` param " ++ "description); pass `limit` explicitly for a stable count regardless of " ++ "mode. For exhaustive enumeration use list_pages; for exact known tokens " ++ "`search` is cheaper (no expansion LLM call). " +"For personal/emotional questions ('what's going on with me', 'anything notable', " +"'how am I feeling'), prefer get_recent_salience, find_anomalies, or " +"get_recent_transcripts. Semantic search returns polished pages and misses " +diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.tsindex a9c5a43cb7..f54943b4d5 100644--- a/src/core/ops/jobs.ts+++ b/src/core/ops/jobs.ts@@ -11,6 +11,12 @@ import type { Operation, OperationContext } from './contract.ts';import { OperationError } from './contract.ts';import { normalizeSlugPrefix } from './context.ts';import { hasScope } from '../scope.ts';+import {+ assertEmbedBackfillQueueAdmission,+ embedBackfillManualDrainCommand,+ InvalidEmbedBackfillSourceIdError,+ NoEmbedBackfillWorkerSurfaceError,+} from '../minions/embed-backfill-admission.ts';// --- Jobs (Minions) ---@@ -81,6 +87,28 @@ const submit_job: Operation = {scope: 'admin',handler: async (ctx, p) => {const name = typeof p.name === 'string' ? p.name.trim() : '';+ const jobData = (p.data as Record<string, unknown>) || {};+ const translateAdmissionError = (e: unknown): never => {+ if (e instanceof InvalidEmbedBackfillSourceIdError) {+ throw new OperationError('invalid_params', e.message);+ }+ if (e instanceof NoEmbedBackfillWorkerSurfaceError) {+ throw new OperationError(+ 'no_worker_surface',+ e.message,+ `Run \`${embedBackfillManualDrainCommand(e.sourceId)}\` to drain embeddings inline.`,+ );+ }+ throw e;+ };++ // Dry-run is a feasibility preview, not an admission bypass. Evaluate the+ // read-only worker-surface gate before returning so MCP and CLI agree.+ try {+ assertEmbedBackfillQueueAdmission(ctx.engine, name, jobData);+ } catch (e) {+ translateAdmissionError(e);+ }if (ctx.dryRun) return { dry_run: true, action: 'submit_job', name };// Submit-side MCP guard: reject protected job names from untrusted callers@@ -103,8 +131,6 @@ const submit_job: Operation = {// name. Strict `=== false` so an untyped/cast context can't escalate.const trusted = ctx.remote === false && isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;- const jobData = (p.data as Record<string, unknown>) || {};-// v0.35.8.0: pre-enqueue shell-job validation, parity with the CLI submit// path. Closes the bug class where shell.ts handler-time validation ran// AFTER queue.add() persisted the row (codex F-CDX-1). Note: this branch@@ -117,17 +143,23 @@ const submit_job: Operation = {validateShellJobParams(jobData);}- const job = await queue.add(name, jobData, {- queue: (p.queue as string) || 'default',- priority: (p.priority as number) || 0,- max_attempts: (p.max_attempts as number) || 3,- delay: (p.delay as number) || undefined,- timeout_ms: (p.timeout_ms as number) || undefined,- // #4145 [CEO-F7/R2-6]: range enforcement lives in queue.add's- // clampLockDurationMs (ParamDef has no min/max support; wrong TYPE is- // rejected by the shared number validation upstream of this handler).- lock_duration_ms: (p.lock_duration_ms as number) || undefined,- }, trusted);+ const job = await (async () => {+ try {+ return await queue.add(name, jobData, {+ queue: (p.queue as string) || 'default',+ priority: (p.priority as number) || 0,+ max_attempts: (p.max_attempts as number) || 3,+ delay: (p.delay as number) || undefined,+ timeout_ms: (p.timeout_ms as number) || undefined,+ // #4145 [CEO-F7/R2-6]: range enforcement lives in queue.add's+ // clampLockDurationMs (ParamDef has no min/max support; wrong TYPE is+ // rejected by the shared number validation upstream of this handler).+ lock_duration_ms: (p.lock_duration_ms as number) || undefined,+ }, trusted);+ } catch (e) {+ return translateAdmissionError(e);+ }+ })();// v0.35.8.0: submit_job audit-log parity with the CLI path (codex F-CDX-4).// Pre-v0.35.8.0 the op handler bypassed the shell-audit JSONL writerdiff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 29bdaaabcd..8289d4e5ec 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -119,13 +119,16 @@ const remove_link: Operation = {const linkOpts = ctx.sourceId? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }: undefined;- await ctx.engine.removeLink(+ // #4527: report how many edges actually died — an unconditional+ // `{ status: 'ok' }` made a zero-match delete (typo'd slug, wrong+ // link_type, already removed) indistinguishable from a real removal.+ const removed = await ctx.engine.removeLink(p.from as string, p.to as string,(p.link_type as string) || undefined,(p.link_source as string) || undefined,linkOpts,);- return { status: 'ok' };+ return { status: 'ok', removed };},cliHints: { name: 'unlink', aliases: ['link-rm'], positional: ['from', 'to'] },};diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex 5cceb13afa..13e24993b9 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -12,16 +12,26 @@ import { sourceScopeOpts } from './context.ts';const find_orphans: Operation = {name: 'find_orphans',- description: 'Find pages with no inbound wikilinks. Essential for content enrichment cycles.',+ description: 'Find disconnected pages. Default mode "islanded" (no live inbound AND no outbound link) matches get_health.orphan_pages; mode "inbound" is the legacy no-inbound-only view. Essential for content enrichment cycles.',params: {include_pseudo: {type: 'boolean',description: 'Include auto-generated and pseudo pages (default: false)',},+ mode: {+ type: 'string',+ description: "#4524: orphan definition — 'islanded' (default; agrees with get_health.orphan_pages and doctor) or 'inbound' (legacy: no inbound links, even when the page links out).",+ },},scope: 'read',handler: async (ctx, p) => {const { findOrphans } = await import('../../commands/orphans.ts');+ // #4524: validate rather than silently coerce — an unknown mode must not+ // quietly fall back to the default and misreport the orphan set.+ const mode = p.mode === undefined ? undefined : (p.mode as string);+ if (mode !== undefined && mode !== 'inbound' && mode !== 'islanded') {+ throw new Error(`find_orphans: invalid mode "${mode}" — use 'inbound' or 'islanded'`);+ }// v0.41.29.0 (Codex F8): scope by the caller's source (ctx.sourceId /// ctx.auth.allowedSources) via the canonical sourceScopeOpts ladder.// Pre-fix, find_orphans returned brain-wide orphans regardless of a@@ -30,6 +40,7 @@ const find_orphans: Operation = {// orphans --source` instead (ctx.remote === false → empty scope here).return findOrphans(ctx.engine, {includePseudo: (p.include_pseudo as boolean) || false,+ ...(mode ? { mode } : {}),...sourceScopeOpts(ctx),});},diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 6c0ac0c10d..6182cb1792 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -119,6 +119,30 @@ async function dropPrivateSlugs(return candidates.filter(c => !hidden.has(c));}+/**+ * #3625: strip the takes/private-facts fences from BOTH compiled_truth and+ * timeline before a page reaches an untrusted reader. Pre-#3625 this only+ * covered compiled_truth — a `## Facts` fence written below the+ * `<!-- timeline -->` sentinel lands in the `timeline` column (splitBody's+ * split boundary), which get_page/fetch_page returned verbatim, unstripped.+ * A private fact fence misplaced there was fully readable by any remote MCP+ * caller. Same stripping rule as compiled_truth: takes fence dropped+ * entirely, facts fence keeps only `world`-visibility rows.+ */+function stripPrivacyFencesForRemoteReader(page: Page): Page {+ return {+ ...page,+ compiled_truth: stripFactsFence(+ stripTakesFence(page.compiled_truth),+ { keepVisibility: ['world'] },+ ),+ timeline: stripFactsFence(+ stripTakesFence(page.timeline ?? ''),+ { keepVisibility: ['world'] },+ ),+ };+}+const get_page: Operation = {name: 'get_page',description: 'Read a page by slug (supports optional fuzzy matching). To edit a page, pass include_content: true — the returned `content` field is the canonical full markdown (frontmatter + body + timeline sentinel); edit THAT and pass it back to put_page to round-trip losslessly. Reassembling compiled_truth/timeline by hand risks dropping sections. Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (see v0.26.5 recovery window).',@@ -181,7 +205,25 @@ const get_page: Operation = {}if (!page) {- throw new OperationError('page_not_found', `Page not found: ${slug}`, includeDeleted ? 'Check the slug or use fuzzy: true' : 'Page may be soft-deleted; pass include_deleted: true to verify');+ let hint = includeDeleted ? 'Check the slug or use fuzzy: true' : 'Page may be soft-deleted; pass include_deleted: true to verify';+ // #4516: source scoping is by-design isolation, but the miss diagnostic+ // should say WHERE the slug actually lives. Trusted local callers only+ // (`ctx.remote === false`) — for a remote caller the probe would be a+ // cross-source existence oracle outside its grant. Only when the lookup+ // was actually scoped (an unscoped read already spanned every source).+ if (ctx.remote === false && (sourceOpts.sourceId !== undefined || sourceOpts.sourceIds !== undefined)) {+ try {+ // gbrain-allow-unscoped-getpage: read-only diagnostic existence probe —+ // deliberately spans all sources to name where the slug lives.+ const elsewhere = await ctx.engine.getPage(slug, { includeDeleted });+ if (elsewhere && !(excludePrivate && isPrivatePage(elsewhere.frontmatter))) {+ hint = `Page exists in source '${elsewhere.source_id}' — pass --source ${elsewhere.source_id} (source_id: '${elsewhere.source_id}' over MCP). ${hint}`;+ }+ } catch {+ // Diagnostic only — a probe failure must never mask the real error.+ }+ }+ throw new OperationError('page_not_found', `Page not found: ${slug}`, hint);}// v0.37.0 (D11): op-layer write-back for the `last_retrieved_at` stale@@ -222,13 +264,7 @@ const get_page: Operation = {// untrusted readers see them. Private facts never cross the boundary.const isUntrustedReader = ctx.remote === true;const visibleBody = isUntrustedReader- ? {- ...page,- compiled_truth: stripFactsFence(- stripTakesFence(page.compiled_truth),- { keepVisibility: ['world'] },- ),- }+ ? stripPrivacyFencesForRemoteReader(page): page;// v0.42 (#1699) agent-warning channel: surface the page's content_flag// marker as a top-level field (parallel to SearchResult.content_flag) so@@ -300,13 +336,7 @@ const fetch_page: Operation = {// true — every MCP transport) never see takes or private facts fences.const visibleBody = ctx.remote === false? page- : {- ...page,- compiled_truth: stripFactsFence(- stripTakesFence(page.compiled_truth),- { keepVisibility: ['world'] },- ),- };+ : stripPrivacyFencesForRemoteReader(page);return {id: page.slug,title: page.title,@@ -328,7 +358,7 @@ const fetch_page: Operation = {const put_page: Operation = {name: 'put_page',- description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',+ description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. Remote (MCP) callers: body wikilinks are NOT reconciled into the graph — auto_link/auto_timeline are skipped for untrusted writers (response reports auto_links: {skipped: "remote"}); use local capture/put_page for link extraction. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',params: {slug: { type: 'string', required: true, description: 'Page slug' },content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },@@ -571,9 +601,9 @@ const put_page: Operation = {let autoLinks:| { created: number; removed: number; errors: number; unresolved: UnresolvedFrontmatterRef[] }| { error: string }- | { skipped: 'remote' }+ | { skipped: 'remote'; hint?: string }| undefined;- let autoTimeline: { created: number } | { error: string } | { skipped: 'remote' } | undefined;+ let autoTimeline: { created: number } | { error: string } | { skipped: 'remote'; hint?: string } | undefined;// Trusted-workspace path (v0.23 dream cycle) re-enables auto-link/timeline// even though ctx.remote=true, because the allow-list bounds the slug and// the synthesis prompt is itself the trusted dispatcher. Without this,@@ -584,8 +614,14 @@ const put_page: Operation = {&& Array.isArray(ctx.allowedSlugPrefixes)&& ctx.allowedSlugPrefixes.length > 0;if (ctx.remote !== false && !trustedWorkspace) {- autoLinks = { skipped: 'remote' };- autoTimeline = { skipped: 'remote' };+ // #4525: say WHY and what to do about it — pre-fix the bare+ // {skipped: 'remote'} left agents believing their body wikilinks had+ // been reconciled into the graph.+ const hint = 'auto_link/auto_timeline run for trusted local writers only; '+ + 'body wikilinks were saved as text but NOT reconciled into the graph. '+ + 'Use local `gbrain capture`/`gbrain call put_page` for link extraction.';+ autoLinks = { skipped: 'remote', hint };+ autoTimeline = { skipped: 'remote', hint };} else if (result.parsedPage) {try {const enabled = await isAutoLinkEnabled(ctx.engine);diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 9227987596..8cba858f15 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -144,6 +144,32 @@ const search: Operation = {types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },// #3800: subagent token economy — per-call snippet cap.snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },+ // #4398: per-call source scope, mirroring `query` — MCP clients passed it+ // here, got 'unknown parameter ignored', and read UNSCOPED results.+ source_id: {+ type: 'string',+ description:+ "Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",+ },+ // #4415: explicit ranking-axis overrides (the same knobs `query` has had+ // since v0.29.1). The auto-detect banks are English regex, so on a+ // non-English brain the recency/salience stages never fire — these flags+ // (CLI: --salience / --recency) are the per-call override; the+ // search.intent_patterns config is the per-brain fix.+ salience: {+ type: 'string',+ enum: ['off', 'on', 'strong'],+ description:+ "Salience boost (emotional_weight + take_count, no time component): 'off' | 'on' | 'strong'. " ++ 'Omit and gbrain auto-detects from query text. Independent of `recency`.',+ },+ recency: {+ type: 'string',+ enum: ['off', 'on', 'strong'],+ description:+ "Recency boost (per-prefix age decay, no mattering signal): 'off' | 'on' | 'strong'. " ++ 'Omit and gbrain auto-detects. Independent of `salience`. Ignored on the keyword-only opt-out path.',+ },},handler: async (ctx, p) => {const startedAt = Date.now();@@ -154,8 +180,12 @@ const search: Operation = {const types = normalizeTypesParam(p.types);// #3800: snippet cap (param > subagent config default > full text).const snippetCap = await resolveSnippetCap(ctx, p);- // #2561: unqualified trusted-local search spans federated sources.- const scope = federatedSearchScope(ctx);+ // #4398: explicit per-call source_id wins over ctx.sourceId, resolved+ // through the single trust+grant resolver (resolveRequestedScope inside+ // federatedSearchScope) — out-of-grant ids throw permission_denied, and+ // #2561's unqualified trusted-local federated span is unchanged.+ const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;+ const scope = federatedSearchScope(ctx, sourceIdParam);// #4352 — untrusted callers never see `visibility: private` pages// (config-gated; trusted local CLI unchanged).const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);@@ -204,6 +234,9 @@ const search: Operation = {...(types ? { types } : {}),...scope,...(perCallMode ? { mode: perCallMode } : {}),+ // #4415: agent-explicit recency + salience (same posture as `query`).+ salience: p.salience as 'off' | 'on' | 'strong' | undefined,+ recency: p.recency as 'off' | 'on' | 'strong' | undefined,onMeta: (m) => { capturedMeta = m; },});stampDeepResearchIds(results);@@ -233,7 +266,22 @@ const query: Operation = {* CLI loads the file, base64-encodes, and passes through `image`). */image: { type: 'string', description: 'Base64-encoded image bytes for image-similarity search (CLI: --image <path>).' },image_mime: { type: 'string', description: 'MIME type for the image bytes (auto-derived from path on CLI; required when calling op directly).' },- limit: { type: 'number', description: 'Max results (default 20)' },+ // #4356 — the text/hybrid path no longer hard-defaults this to 20; an+ // omitted OR falsy (0) `limit` resolves from the active search mode's+ // searchLimit (10/25/50 for conservative/balanced/tokenmax by default,+ // overridable via the `search.searchLimit` config key — see mode.ts+ // `pick()`). 0 is treated as "unset" rather than "return zero rows",+ // matching the existing convention on every other limit surface with+ // this same shape (`search`'s own limit below, and the image-+ // similarity branch below it) — none of which support a literal+ // empty-result request today; introducing that only here would be a+ // new, undocumented asymmetry rather than a limit-consistency fix.+ // (`search_by_image`, a separate op in src/core/ops/image.ts, has the+ // same convention but isn't "in this file".) The image-similarity path+ // (`image` param) is unaffected by this change and still hard-defaults+ // to 20 regardless of mode — out of scope here, tracked separately+ // (#4356 Problem 2).+ limit: { type: 'number', description: 'Max results. For text queries, omitted or 0 resolves from the active search mode (10 conservative / 25 balanced / 50 tokenmax by default, or the configured `search.searchLimit` override). For image-similarity queries (`image` param), always defaults to 20 regardless of mode.' },offset: { type: 'number', description: 'Skip first N results (for pagination)' },// #3985: multi-type filter (plumbing shipped v0.33; exposed here).types: { type: 'array', items: { type: 'string' }, description: TYPES_PARAM_DESCRIPTION },@@ -399,7 +447,15 @@ const query: Operation = {// Plain hybridSearch remains the bare API for callers that opt out.// (#1663: `let` — the CRAG gate below may swap in an escalated run.)let results = await hybridSearchCached(ctx.engine, queryText, {- limit: (p.limit as number) || 20,+ // #4356 — was a hard `|| 20`, independent of the mode-resolution+ // hybridSearchCached applies when `limit` is falsy (undefined OR 0):+ // `opts?.limit || resolvedMode.searchLimit` (hybrid.ts). Passing+ // `undefined` through instead of hard-defaulting to 20 lets that+ // resolution apply (10/25/50 for conservative/balanced/tokenmax).+ // `(p.limit as number) || undefined` keeps 0 in that same "unset"+ // bucket rather than requesting a literal empty result — see the+ // `limit` param description above for why.+ limit: (p.limit as number) || undefined,offset: (p.offset as number) || 0,excludePrivate,expansion: expand,diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex e65cfaa9a6..15cbbd2015 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -163,9 +163,21 @@ const sources_list: Operation = {scope: 'read',handler: async (ctx, p) => {const { listSources } = await import('../sources-ops.ts');+ // #4433: row-filter the listing to the caller's federated source grant —+ // a client whose grant excludes a source must not learn that source's+ // id, name, or page_count. The filter mirrors EXACTLY the boundary+ // resolveRequestedScope enforces on explicit per-call `source_id` reads+ // (a non-empty ctx.auth.allowedSources array): the listing shows+ // precisely the sources the caller could actually read. Trusted local+ // CLI and remote callers WITHOUT such a grant (the scalar+ // default-source floor, which today may read any source by naming it+ // explicitly) keep the full listing.+ const granted = ctx.remote !== false ? ctx.auth?.allowedSources : undefined;+ const allowedSourceIds = granted && granted.length > 0 ? granted : undefined;return {sources: await listSources(ctx.engine, {includeArchived: (p.include_archived as boolean) === true,+ ...(allowedSourceIds !== undefined ? { allowedSourceIds } : {}),}),};},diff --git a/src/core/pages-upsert-arbiter.ts b/src/core/pages-upsert-arbiter.tsindex 5020fe6679..8a5dd35f67 100644--- a/src/core/pages-upsert-arbiter.ts+++ b/src/core/pages-upsert-arbiter.ts@@ -67,8 +67,25 @@ export async function checkPagesUpsertArbiter(engine: BrainEngine): Promise<Pageif (!tablePresent) {return { tablePresent: false, arbiterPresent: false, needsRepair: false, duplicateGroups: 0 };}+ // Catalog-anchored candidate set (#550 residual): pg_indexes was a bare+ // text scan on tablename, which false-passed on exactly the drift shapes+ // this module exists to catch — an INVALID index (a failed CREATE INDEX+ // CONCURRENTLY remnant renders a normal-looking indexdef but cannot+ // arbitrate), a DEFERRABLE unique (indimmediate = false, unusable for ON+ // CONFLICT), and a same-named table in ANOTHER schema (tablename has no+ // schema qualifier, while the table probe above resolved via search_path).+ // Anchoring on the SAME to_regclass('pages') plus the catalog validity+ // flags closes all three; indpred IS NULL keeps the existing+ // partial-index exclusion at the catalog level too.const rows = await engine.executeRaw<{ indexdef: string }>(- `SELECT indexdef FROM pg_indexes WHERE tablename = 'pages'`,+ `SELECT pg_get_indexdef(x.indexrelid) AS indexdef+ FROM pg_index x+ WHERE x.indrelid = to_regclass('pages')+ AND x.indisunique+ AND x.indisvalid+ AND x.indisready+ AND x.indimmediate+ AND x.indpred IS NULL`,);const arbiterPresent = rows.some(r => isArbiterShape(r.indexdef));let duplicateGroups = 0;diff --git a/src/core/path-confine.ts b/src/core/path-confine.tsindex e0b71cee54..904a5b5f6c 100644--- a/src/core/path-confine.ts+++ b/src/core/path-confine.ts@@ -20,6 +20,7 @@*/import { realpathSync, existsSync, type Stats } from 'fs';+import { realpath as realpathAsync } from 'fs/promises';import { resolve as resolvePath, relative, isAbsolute, dirname, basename, join, sep } from 'path';/**@@ -139,6 +140,35 @@ export function msysToNativePath(return `${drive}:${rest || '\\'}`;}+/**+ * Async twin of `realpathOrResolve` — same fallback contract, but backed by+ * `fs.promises.realpath` instead of `realpathSync`. Exists so a caller+ * resolving N independent paths (e.g. every registered source's local_path)+ * can `Promise.all` them and let a slow/interrupted filesystem stall on ONE+ * path without serializing behind the others: `realpathSync` blocks the+ * event loop for its full duration no matter how many `Promise.all`-wrapped+ * calls surround it (#4091-class root-cause), so parallelizing the SYNC+ * function would still take sum-of-durations, not max-of-durations. Use this+ * version whenever more than one path is being resolved together.+ *+ * The lexical fallback below is the same shape as the sync version above+ * (unflagged there only because semgrep's diff-scoped CI scan doesn't+ * re-flag pre-existing lines): `p` is never raw untrusted input at this+ * call site — a registered source's local_path or the CLI's own cwd — and+ * this is the fallback for a path that already failed to realpath+ * (ENOENT/stale registration). The security boundary is the caller's+ * realpath-both-sides prefix/containment check afterward, not this+ * resolve() call.+ */+export async function realpathOrResolveAsync(p: string): Promise<string> {+ try {+ return await realpathAsync(p);+ } catch {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal+ return resolvePath(p);+ }+}+/*** Containment check for a write TARGET that may not exist yet (a new page file).* `isPathContained` requires the child to already exist; this instead realpathsdiff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 1b079fd708..fc8f30ea09 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -3769,43 +3769,53 @@ export class PGLiteEngine implements BrainEngine {linkType?: string,linkSource?: string,opts?: { fromSourceId?: string; toSourceId?: string },- ): Promise<void> {+ ): Promise<number> {const fromSrc = opts?.fromSourceId ?? 'default';const toSrc = opts?.toSourceId ?? 'default';// Each branch source-qualifies page-id subqueries so a delete only targets// the intended edge between per-source slug rows.+ // #4527: RETURNING 1 so the caller learns how many edges actually died —+ // a zero-match delete must be distinguishable from a real removal.if (linkType !== undefined && linkSource !== undefined) {- await this.db.query(+ const { rows } = await this.db.query(`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4)AND link_type = $5- AND link_source IS NOT DISTINCT FROM $6`,+ AND link_source IS NOT DISTINCT FROM $6+ RETURNING 1`,[from, fromSrc, to, toSrc, linkType, linkSource]);+ return rows.length;} else if (linkType !== undefined) {- await this.db.query(+ const { rows } = await this.db.query(`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4)- AND link_type = $5`,+ AND link_type = $5+ RETURNING 1`,[from, fromSrc, to, toSrc, linkType]);+ return rows.length;} else if (linkSource !== undefined) {- await this.db.query(+ const { rows } = await this.db.query(`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4)- AND link_source IS NOT DISTINCT FROM $5`,+ AND link_source IS NOT DISTINCT FROM $5+ RETURNING 1`,[from, fromSrc, to, toSrc, linkSource]);+ return rows.length;} else {- await this.db.query(+ const { rows } = await this.db.query(`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)- AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4)`,+ AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4)+ RETURNING 1`,[from, fromSrc, to, toSrc]);+ return rows.length;}}@@ -4041,6 +4051,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < $2AND NOT (p2.id = ANY(g.visited))+ AND p2.deleted_at IS NULL${stepScope}ORDER BY p2.slug ASC, p2.id ASCLIMIT $${capIdx})`;@@ -4051,6 +4062,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < $2AND NOT (p2.id = ANY(g.visited))+ AND p2.deleted_at IS NULL${stepScope}`;}@@ -4059,7 +4071,7 @@ export class PGLiteEngine implements BrainEngine {const { rows } = await this.db.query(`WITH RECURSIVE graph AS (SELECT p.id, p.slug, p.title, p.type, 0 as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = $1 ${seedScope}+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${seedScope}UNION ALL@@ -4075,7 +4087,7 @@ export class PGLiteEngine implements BrainEngine {(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))FROM links l2JOIN pages p3 ON p3.id = l2.to_page_id- WHERE l2.from_page_id = g.id ${aggScope}),+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${aggScope}),'[]'::jsonb) as linksFROM graph g@@ -4503,6 +4515,7 @@ export class PGLiteEngine implements BrainEngine {async findOrphanPages(opts?: {sourceId?: string;sourceIds?: string[];+ mode?: 'inbound' | 'islanded';}): Promise<Array<{ slug: string; title: string; domain: string | null }>> {// Soft-delete filter on BOTH sides:// - candidate: p.deleted_at IS NULL — soft-deleted pages aren't orphan candidates@@ -4524,6 +4537,20 @@ export class PGLiteEngine implements BrainEngine {params.push(opts.sourceId);sourceFilter = `AND p.source_id = $${params.length}`;}+ // #4524: default mode 'islanded' — identical predicate to getHealth's+ // orphan_pages (no live inbound AND no live outbound; outbound counts+ // only when its TARGET page is live, per gbrain#4153 endpoint liveness).+ // mode 'inbound' preserves the legacy no-inbound-only view.+ const outboundFilter =+ (opts?.mode ?? 'islanded') === 'islanded'+ ? `AND NOT EXISTS (+ SELECT 1+ FROM links l+ JOIN pages tgt ON tgt.id = l.to_page_id+ WHERE l.from_page_id = p.id+ AND tgt.deleted_at IS NULL+ )`+ : '';const { rows } = await this.db.query(`SELECTp.slug,@@ -4539,6 +4566,7 @@ export class PGLiteEngine implements BrainEngine {WHERE l.to_page_id = p.idAND src.deleted_at IS NULL)+ ${outboundFilter}ORDER BY p.slug`,params);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 316cc8f6ec..affdd70385 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -95,6 +95,7 @@ import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';+import { applyPostgresForwardReferenceBootstrap } from './postgres-engine/forward-reference-bootstrap.ts';import * as factsImpl from './postgres-engine/facts.ts';import type { PgFactsDeps } from './postgres-engine/facts.ts';import * as takesImpl from './postgres-engine/takes.ts';@@ -513,24 +514,10 @@ export class PostgresEngine implements BrainEngine {/*** Bootstrap state that SCHEMA_SQL forward-references but that older brains* don't have yet. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap`- * in shape and intent. Currently covers:- *- * - `sources` table + default seed (FK target of pages.source_id) — v0.18- * - `pages.source_id` column (indexed by `idx_pages_source_id`) — v0.18- * - `links.link_source` column (indexed by `idx_links_source`) — v0.13- * - `links.origin_page_id` column (indexed by `idx_links_origin`) — v0.13- * - `content_chunks.symbol_name` column (indexed by `idx_chunks_symbol_name`) — v0.19- * - `content_chunks.language` column (indexed by `idx_chunks_language`) — v0.19- * - `content_chunks.search_vector` + `parent_symbol_path` + `doc_comment`- * + `symbol_name_qualified` columns (indexed by `idx_chunks_search_vector`- * and `idx_chunks_symbol_qualified`) — v0.20 Cathedral II- * - `pages.deleted_at` column (indexed by `pages_deleted_at_purge_idx`) — v0.26.5- * - `mcp_request_log.agent_name` + `params` + `error_message` columns- * (indexed by `idx_mcp_log_agent_time`) — v0.26.3- * - `subagent_messages.provider_id` column (indexed by- * `idx_subagent_messages_provider`) — v0.27- *- * Keep this in sync with the PGLite version; covered by+ * in shape and intent. The probe set + DDL live in the shared module+ * `src/core/postgres-engine/forward-reference-bootstrap.ts` (#4477) so the+ * standalone `db.initSchema()` SCHEMA_SQL-replay path runs the SAME+ * bootstrap — keep that module in sync with the PGLite version; covered by* `test/schema-bootstrap-coverage.test.ts` (PGLite side) and* `test/e2e/postgres-bootstrap.test.ts` (Postgres side).*/@@ -540,581 +527,7 @@ export class PostgresEngine implements BrainEngine {// compatibility with any unit-test path that still calls bootstrap directly.// Production path always passes the DDL conn so bootstrap probes run inside// the same lock scope as SCHEMA_SQL replay.- const conn = injectedConn ?? this.sql;-- // Single round-trip probe for every forward-reference target.- // current_schema() resolves to whatever search_path the connection uses,- // which matches schema-embedded.ts's `public.` references.- const probeRows = await conn<{- pages_exists: boolean;- source_id_exists: boolean;- deleted_at_exists: boolean;- effective_date_exists: boolean;- links_exists: boolean;- link_source_exists: boolean;- origin_page_id_exists: boolean;- chunks_exists: boolean;- symbol_name_exists: boolean;- language_exists: boolean;- search_vector_exists: boolean;- embedding_image_exists: boolean;- mcp_log_exists: boolean;- agent_name_exists: boolean;- subagent_messages_exists: boolean;- subagent_provider_id_exists: boolean;- ingest_log_exists: boolean;- ingest_log_source_id_exists: boolean;- files_exists: boolean;- files_source_id_exists: boolean;- files_page_id_exists: boolean;- oauth_clients_exists: boolean;- oauth_clients_source_id_exists: boolean;- oauth_clients_federated_read_exists: boolean;- oauth_clients_surface_exists: boolean;- oauth_clients_surface_set_by_exists: boolean;- sources_exists: boolean;- sources_archived_exists: boolean;- sources_archived_at_exists: boolean;- sources_archive_expires_at_exists: boolean;- }[]>`- SELECT- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'pages') AS pages_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_id') AS source_id_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'deleted_at') AS deleted_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'effective_date') AS effective_date_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'links') AS links_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'links' AND column_name = 'link_source') AS link_source_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'links' AND column_name = 'origin_page_id') AS origin_page_id_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'content_chunks') AS chunks_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'symbol_name') AS symbol_name_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'language') AS language_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'search_vector') AS search_vector_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'embedding_image') AS embedding_image_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'mcp_request_log') AS mcp_log_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'mcp_request_log' AND column_name = 'agent_name') AS agent_name_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'subagent_messages') AS subagent_messages_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'subagent_messages' AND column_name = 'provider_id') AS subagent_provider_id_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'ingest_log') AS ingest_log_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'ingest_log' AND column_name = 'source_id') AS ingest_log_source_id_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'files') AS files_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'files' AND column_name = 'source_id') AS files_source_id_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'files' AND column_name = 'page_id') AS files_page_id_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'oauth_clients') AS oauth_clients_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'source_id') AS oauth_clients_source_id_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'federated_read') AS oauth_clients_federated_read_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface') AS oauth_clients_surface_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface_set_by') AS oauth_clients_surface_set_by_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'sources') AS sources_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archived') AS sources_archived_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archived_at') AS sources_archived_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archive_expires_at') AS sources_archive_expires_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'last_retrieved_at') AS pages_last_retrieved_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'ingested_via') AS pages_ingested_via_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'ingested_at') AS pages_ingested_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_uri') AS pages_source_uri_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_kind') AS pages_source_kind_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'contextual_retrieval_mode') AS pages_cr_mode_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'corpus_generation') AS pages_corpus_generation_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'contextual_retrieval_mode') AS sources_cr_mode_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'trust_frontmatter_overrides') AS sources_trust_fm_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'generation') AS pages_generation_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'embedding_signature') AS pages_embedding_signature_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'links_extracted_at') AS pages_links_extracted_at_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'timeline_entries') AS timeline_entries_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'timeline_entries' AND column_name = 'event_page_id') AS timeline_event_page_id_exists,- EXISTS (SELECT 1 FROM information_schema.tables- WHERE table_schema = current_schema() AND table_name = 'minion_jobs') AS minion_jobs_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'timeout_at') AS minion_jobs_timeout_at_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'idempotency_key') AS minion_jobs_idempotency_key_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_job_id') AS minion_jobs_pq_owner_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_token') AS minion_jobs_pq_token_exists,- EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists- `;- const probe = probeRows[0]!;-- const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;- const needsLinksBootstrap = probe.links_exists- && (!probe.link_source_exists || !probe.origin_page_id_exists);- const needsChunksBootstrap = probe.chunks_exists- && (!probe.symbol_name_exists || !probe.language_exists || !probe.search_vector_exists);- // v0.26.5: pages_deleted_at_purge_idx in SCHEMA_SQL crashes if the column- // doesn't exist yet. Migration v34 also adds it, but bootstrap runs first.- const needsPagesDeletedAt = probe.pages_exists && !probe.deleted_at_exists;- // v0.26.3 (v33): idx_mcp_log_agent_time in SCHEMA_SQL needs agent_name col.- const needsMcpLogBootstrap = probe.mcp_log_exists && !probe.agent_name_exists;- // v0.27 (v36): idx_subagent_messages_provider in SCHEMA_SQL needs provider_id- // (the SECOND column in the composite index `(job_id, provider_id)`).- const needsSubagentProviderId = probe.subagent_messages_exists && !probe.subagent_provider_id_exists;- // v0.27.1 (v39): idx_chunks_embedding_image partial HNSW in SCHEMA_SQL- // references embedding_image. Use embedding_image_exists as the proxy for- // both v39 columns; modality is added in the same migration.- const needsChunksEmbeddingImage = probe.chunks_exists && !probe.embedding_image_exists;- // v0.29.1 (v40 + v41): pages_coalesce_date_idx expression index in SCHEMA_SQL- // references effective_date. Use effective_date_exists as the proxy for the- // five v40 + v41 pages columns (emotional_weight, effective_date,- // effective_date_source, import_filename, salience_touched_at).- const needsPagesRecency = probe.pages_exists && !probe.effective_date_exists;- // v0.31.2 (v50): idx_ingest_log_source_type_created in SCHEMA_SQL references- // source_id. Old brains have ingest_log without source_id; bootstrap adds- // the column before SCHEMA_SQL replay creates the index.- const needsIngestLogSourceId = probe.ingest_log_exists && !probe.ingest_log_source_id_exists;- // v0.18 (v18): files.source_id + files.page_id added; idx_files_source_id- // and idx_files_page_id in SCHEMA_SQL crash without them.- const needsFilesBootstrap = probe.files_exists- && (!probe.files_source_id_exists || !probe.files_page_id_exists);- // v0.34.1 (v60+v61+v65): oauth_clients.source_id + federated_read added;- // FK to sources(id) + GIN index idx_oauth_clients_federated_read in- // SCHEMA_SQL crash without them.- const needsOauthClientsBootstrap = probe.oauth_clients_exists- && (!probe.oauth_clients_source_id_exists || !probe.oauth_clients_federated_read_exists);- // WP4 (v127): oauth_clients.surface + surface_set_by. No SCHEMA_SQL index- // references them, but the columns are migration-added AND in the blob's- // CREATE TABLE — the exact v121 mask class — so the bootstrap adds them- // defense-in-depth (and satisfies the MIGRATIONS ADD COLUMN coverage- // gate). They ship in one migration and go missing together.- const probeSurface = probe as {- oauth_clients_surface_exists?: boolean;- oauth_clients_surface_set_by_exists?: boolean;- };- const needsOauthClientsSurface = probe.oauth_clients_exists- && (!probeSurface.oauth_clients_surface_exists || !probeSurface.oauth_clients_surface_set_by_exists);- // v0.26.5 (v34): sources.archived + archived_at + archive_expires_at added- // for soft-delete lifecycle. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS sources`- // is a no-op on pre-existing sources tables (won't add columns), so the- // visibility filters in search/list_pages trip on old brains. Bootstrap- // closes the gap before any visibility-filter SQL runs.- const needsSourcesArchive = probe.sources_exists- && (!probe.sources_archived_exists- || !probe.sources_archived_at_exists- || !probe.sources_archive_expires_at_exists);- // v0.37.0 (v79): pages_last_retrieved_at_idx in SCHEMA_SQL references- // last_retrieved_at. Pre-v79 brains crash without the column; bootstrap- // adds it before SCHEMA_SQL replay creates the index. v79 runs later- // via runMigrations and is idempotent.- const needsPagesLastRetrievedAt = probe.pages_exists && !(probe as { pages_last_retrieved_at_exists?: boolean }).pages_last_retrieved_at_exists;- // v0.38.0 (v80): provenance columns. Not referenced by any SCHEMA_SQL- // index/FK today; bootstrap exists for the column-only forward-- // reference class defense-in-depth.- const probeProv = probe as {- pages_ingested_via_exists?: boolean;- pages_ingested_at_exists?: boolean;- pages_source_uri_exists?: boolean;- pages_source_kind_exists?: boolean;- };- const needsPagesProvenance = probe.pages_exists- && (!probeProv.pages_ingested_via_exists- || !probeProv.pages_ingested_at_exists- || !probeProv.pages_source_uri_exists- || !probeProv.pages_source_kind_exists);- // v0.40.3.0 (v90, renumbered from v0.40.3.0 v81 on master merge):- // contextual retrieval columns on pages + sources. Defense-in-depth.- const probeCr = probe as {- pages_cr_mode_exists?: boolean;- pages_corpus_generation_exists?: boolean;- sources_cr_mode_exists?: boolean;- sources_trust_fm_exists?: boolean;- pages_generation_exists?: boolean;- pages_embedding_signature_exists?: boolean;- pages_links_extracted_at_exists?: boolean;- timeline_entries_exists?: boolean;- timeline_event_page_id_exists?: boolean;- minion_jobs_exists?: boolean;- minion_jobs_timeout_at_exists?: boolean;- minion_jobs_idempotency_key_exists?: boolean;- minion_jobs_pq_owner_exists?: boolean;- minion_jobs_pq_token_exists?: boolean;- minion_jobs_pq_lease_exists?: boolean;- };- const needsContextualRetrievalColumns = (probe.pages_exists- && (!probeCr.pages_cr_mode_exists || !probeCr.pages_corpus_generation_exists))- || (probe.sources_exists- && (!probeCr.sources_cr_mode_exists || !probeCr.sources_trust_fm_exists));- // v0.40.3.0 (v91): pages.generation BIGINT bumped by- // bump_page_generation_trg. pages_generation_idx in SCHEMA_SQL references- // it. Pre-v91 brains crash without the column; bootstrap adds it before- // SCHEMA_SQL replay creates the index.- const needsPagesGeneration = probe.pages_exists && !probeCr.pages_generation_exists;- // v0.41.31 (v108): pages.embedding_signature for real stale semantics.- // No SCHEMA_SQL index references it; bootstrap is defense-in-depth.- const needsPagesEmbeddingSignature = probe.pages_exists && !probeCr.pages_embedding_signature_exists;- // v0.42.7 (v112): pages.links_extracted_at link-extraction freshness- // watermark. pages_links_extracted_at_idx in SCHEMA_SQL references it;- // pre-v112 brains crash without the column, so bootstrap adds it before- // SCHEMA_SQL replay creates the index. v112 runs later via runMigrations- // and is idempotent.- const needsPagesLinksExtractedAt = probe.pages_exists && !probeCr.pages_links_extracted_at_exists;- // v121: schema-blob indexes reference event_page_id before migrations run.- const needsTimelineEventPageId = probeCr.timeline_entries_exists === true- && !probeCr.timeline_event_page_id_exists;- // v7-era (#2626 class sweep): minion_jobs.timeout_at + idempotency_key are- // migration-added AND referenced by blob indexes (idx_minion_jobs_timeout,- // uniq_minion_jobs_idempotency) — a pre-v7 minion_jobs wedges blob replay- // exactly like the v121 incident.- const needsMinionJobsTimeoutAt = probeCr.minion_jobs_exists === true- && !probeCr.minion_jobs_timeout_at_exists;- const needsMinionJobsIdempotencyKey = probeCr.minion_jobs_exists === true- && !probeCr.minion_jobs_idempotency_key_exists;- // Token rides the probe too: a token-only-missing brain (partial upgrade)- // would otherwise be unrepairable — the ALTER block adds all three.- const needsMinionJobsPrivateQueue = probeCr.minion_jobs_exists === true- && (!probeCr.minion_jobs_pq_owner_exists || !probeCr.minion_jobs_pq_token_exists- || !probeCr.minion_jobs_pq_lease_exists);-- if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap- && !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId- && !needsChunksEmbeddingImage && !needsPagesRecency- && !needsIngestLogSourceId && !needsFilesBootstrap- && !needsOauthClientsBootstrap && !needsOauthClientsSurface- && !needsSourcesArchive- && !needsPagesLastRetrievedAt- && !needsPagesProvenance- && !needsContextualRetrievalColumns && !needsPagesGeneration- && !needsPagesEmbeddingSignature- && !needsPagesLinksExtractedAt- && !needsTimelineEventPageId- && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey- && !needsMinionJobsPrivateQueue) return;-- process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');-- if (needsPagesBootstrap) {- // Mirror schema-embedded.ts's `sources` shape so the subsequent- // SCHEMA_SQL CREATE TABLE IF NOT EXISTS is a true no-op.- // Archive columns (v34) are folded in here so a pre-v18 brain doesn't- // need needsSourcesArchive to also fire — bootstrap creates a complete- // v34-shape sources in one go. needsSourcesArchive then only fires on- // the pre-v34 case (sources exists, archive cols don't).- await conn.unsafe(`- CREATE TABLE IF NOT EXISTS sources (- id TEXT PRIMARY KEY,- name TEXT NOT NULL UNIQUE,- local_path TEXT,- last_commit TEXT,- last_sync_at TIMESTAMPTZ,- config JSONB NOT NULL DEFAULT '{}'::jsonb,- archived BOOLEAN NOT NULL DEFAULT FALSE,- archived_at TIMESTAMPTZ,- archive_expires_at TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()- );- INSERT INTO sources (id, name, config)- VALUES ('default', 'default', '{"federated": true}'::jsonb)- ON CONFLICT (id) DO NOTHING;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_id TEXT- NOT NULL DEFAULT 'default' REFERENCES sources(id) ON DELETE CASCADE;- `);- }-- if (needsLinksBootstrap) {- // v11 (links_provenance_columns) handles the CHECK constraint, the- // UNIQUE swap, and the backfill. The bootstrap only adds enough state- // for SCHEMA_SQL's `CREATE INDEX idx_links_source/origin` not to crash.- // v11 runs later via runMigrations and is idempotent.- await conn.unsafe(`- ALTER TABLE links ADD COLUMN IF NOT EXISTS link_source TEXT;- ALTER TABLE links ADD COLUMN IF NOT EXISTS origin_page_id INTEGER- REFERENCES pages(id) ON DELETE SET NULL;- `);- }-- if (needsChunksBootstrap) {- // v26 (content_chunks_code_metadata) adds symbol_name + language; v27- // (Cathedral II) adds parent_symbol_path + doc_comment +- // symbol_name_qualified + search_vector. The schema blob has indexes- // (idx_chunks_search_vector line 141, idx_chunks_symbol_qualified- // line 142) that need the v27 columns to exist before they run.- // v26 + v27 run later via runMigrations and are idempotent.- await conn.unsafe(`- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS language TEXT;- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS symbol_name TEXT;- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS parent_symbol_path TEXT[];- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS doc_comment TEXT;- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS symbol_name_qualified TEXT;- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS search_vector TSVECTOR;- `);- }-- if (needsPagesDeletedAt) {- // v34 (destructive_guard_columns) adds the column + sources columns +- // partial purge index. Bootstrap only adds enough for SCHEMA_SQL's- // `CREATE INDEX pages_deleted_at_purge_idx ... WHERE deleted_at IS NOT NULL`- // not to crash. v34 runs later via runMigrations and is idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;- `);- }-- if (needsMcpLogBootstrap) {- // v33 (admin_dashboard_columns_v0_26_3) adds agent_name + params +- // error_message to mcp_request_log. SCHEMA_SQL's- // `CREATE INDEX idx_mcp_log_agent_time ON mcp_request_log(agent_name,...)`- // crashes without agent_name. v33 runs later via runMigrations and is- // idempotent (and also handles backfill).- await conn.unsafe(`- ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS agent_name TEXT;- ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS params JSONB;- ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS error_message TEXT;- `);- }-- if (needsSubagentProviderId) {- // v36 (subagent_provider_neutral_persistence_v0_27) adds provider_id +- // schema_version on subagent_messages and subagent_tool_executions.- // SCHEMA_SQL's `CREATE INDEX idx_subagent_messages_provider ON- // subagent_messages (job_id, provider_id)` crashes without provider_id- // (composite-index second column). v36 runs later via runMigrations and- // is idempotent.- await conn.unsafe(`- ALTER TABLE subagent_messages ADD COLUMN IF NOT EXISTS provider_id TEXT;- `);- }-- if (needsChunksEmbeddingImage) {- // v39 (multimodal_dual_column_v0_27_1) adds modality + embedding_image- // columns to content_chunks plus a partial HNSW index that references- // embedding_image. Bootstrap mirrors enough state for SCHEMA_SQL's- // `CREATE INDEX idx_chunks_embedding_image ... WHERE embedding_image IS NOT NULL`- // not to crash. v39 runs later via runMigrations and is idempotent.- await conn.unsafe(`- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS modality TEXT NOT NULL DEFAULT 'text';- ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_image vector(1024);- `);- }-- if (needsPagesRecency) {- // v40 (pages_emotional_weight) adds emotional_weight; v41- // (pages_recency_columns) adds effective_date + effective_date_source +- // import_filename + salience_touched_at and the- // `pages_coalesce_date_idx ON pages ((COALESCE(effective_date, updated_at)))`- // expression index. SCHEMA_SQL's CREATE INDEX for that expression crashes- // before v41 runs. Bootstrap adds all five additive columns; v40 + v41- // run later via runMigrations and are idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS emotional_weight REAL NOT NULL DEFAULT 0.0;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS effective_date TIMESTAMPTZ;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS effective_date_source TEXT;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS import_filename TEXT;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS salience_touched_at TIMESTAMPTZ;- `);- }-- if (needsIngestLogSourceId) {- // v50 (ingest_log_source_id) adds source_id +- // idx_ingest_log_source_type_created composite index. SCHEMA_SQL's- // CREATE INDEX (source_id, source_type, created_at) crashes without- // source_id. Bootstrap adds the column with NOT NULL DEFAULT 'default'- // so the index can build cleanly.- await conn.unsafe(`- ALTER TABLE ingest_log ADD COLUMN IF NOT EXISTS source_id TEXT NOT NULL DEFAULT 'default';- `);- }-- if (needsFilesBootstrap) {- // v18 (files_provenance_columns) adds source_id + page_id to files plus- // idx_files_source_id and idx_files_page_id in SCHEMA_SQL. Pre-v18 brains- // crash on the CREATE INDEX. Bootstrap adds both columns; v18 runs later- // via runMigrations and is idempotent.- await conn.unsafe(`- ALTER TABLE files ADD COLUMN IF NOT EXISTS source_id TEXT- NOT NULL DEFAULT 'default' REFERENCES sources(id) ON DELETE CASCADE;- ALTER TABLE files ADD COLUMN IF NOT EXISTS page_id INTEGER- REFERENCES pages(id) ON DELETE SET NULL;- `);- }-- if (needsOauthClientsBootstrap) {- // v60+v61+v65 (oauth_clients_source_id_fk, oauth_clients_federated_read_column,- // oauth_clients_federated_read_gin_index) add source_id + federated_read- // and the GIN index idx_oauth_clients_federated_read. SCHEMA_SQL's- // FK + index references crash on pre-v60 brains. Bootstrap mirrors the- // v60+v61 column shape; v60-v65 run later via runMigrations and are- // idempotent (and handle backfill + the v64 RESTRICT-flip).- await conn.unsafe(`- ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS source_id TEXT- DEFAULT 'default' REFERENCES sources(id) ON DELETE SET NULL;- ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS federated_read TEXT[]- NOT NULL DEFAULT '{}';- `);- }-- if (needsOauthClientsSurface) {- // WP4 (v127): per-client MCP tool surface + operator-lock marker.- // Nullable TEXT, no index — bootstrap mirrors the v127 column shape so- // the blob's CREATE TABLE presence can't mask the forward reference on- // pre-v127 brains (the v121 wedge class). v127 runs later via- // runMigrations and is idempotent. Mirror of the PGLite bootstrap.- await conn.unsafe(`- ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT;- ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT;- `);- }-- if (needsSourcesArchive) {- // v34 (destructive_guard_columns) promotes archive lifecycle from JSONB- // config to real columns on sources. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS- // sources` is a no-op against an existing pre-v34 sources table, so the- // column-add never lands until the v34 migration runs. v34's UPDATE- // statements + downstream visibility filters (search/query/list_pages)- // need the columns to exist on the table schema. Bootstrap adds the- // three columns; v34 runs later via runMigrations and is idempotent- // (and handles JSONB → column backfill).- await conn.unsafe(`- ALTER TABLE sources ADD COLUMN IF NOT EXISTS archived BOOLEAN NOT NULL DEFAULT FALSE;- ALTER TABLE sources ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;- ALTER TABLE sources ADD COLUMN IF NOT EXISTS archive_expires_at TIMESTAMPTZ;- `);- }-- if (needsPagesLastRetrievedAt) {- // v79 (pages_last_retrieved_at): adds the real stale-page signal column- // + full B-tree index. SCHEMA_SQL's CREATE INDEX- // pages_last_retrieved_at_idx crashes without the column. v79 runs- // later via runMigrations and is idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS last_retrieved_at TIMESTAMPTZ;- `);- }-- if (needsPagesProvenance) {- // v81 (pages_provenance_columns): four nullable columns added by the- // v0.38 ingestion cathedral. No SCHEMA_SQL index/FK references them- // today; bootstrap exists defense-in-depth so future schema work that- // does reference them doesn't wedge pre-v81 brains.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS ingested_via TEXT;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS ingested_at TIMESTAMPTZ;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_uri TEXT;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_kind TEXT;- `);- }-- if (needsContextualRetrievalColumns) {- // v0.40.3.0 v90 (contextual_retrieval_columns, renumbered from- // v0.40.3.0 v81 on master merge). Five additive columns wiring the- // three-tier wrapper ladder. Defense-in-depth probes; v90 runs later- // via runMigrations and is idempotent (ADD COLUMN IF NOT EXISTS).- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;- ALTER TABLE pages ADD COLUMN IF NOT EXISTS corpus_generation TEXT;- ALTER TABLE sources ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;- ALTER TABLE sources ADD COLUMN IF NOT EXISTS trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT FALSE;- `);- }-- if (needsPagesGeneration) {- // v0.40.3.0 v91 (pages_generation_trigger_and_bookmark):- // pages.generation BIGINT. SCHEMA_SQL CREATE INDEX- // pages_generation_idx ON pages (generation) crashes on pre-v91 brains- // without this. The trigger and index land via v91 migration run- // later; bootstrap only adds the column. v91 is idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 1;- `);- }-- if (needsPagesEmbeddingSignature) {- // v108 (pages_embedding_signature): embedding provenance for real stale- // semantics. NULL grandfathered. v108 runs later via runMigrations and- // is idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS embedding_signature TEXT;- `);- }-- if (needsPagesLinksExtractedAt) {- // v112 (pages_links_extracted_at): link-extraction freshness watermark.- // pages_links_extracted_at_idx in SCHEMA_SQL references it, so bootstrap- // adds the column before the blob's CREATE INDEX runs. The index itself- // lands via the blob (CREATE INDEX IF NOT EXISTS) and v112 (CONCURRENTLY);- // bootstrap only adds the column. v112 runs later via runMigrations and is- // idempotent.- await conn.unsafe(`- ALTER TABLE pages ADD COLUMN IF NOT EXISTS links_extracted_at TIMESTAMPTZ;- `);- }-- if (needsTimelineEventPageId) {- // Add only the forward-referenced column. Migration v121 remains the- // source of truth for the FK and indexes and runs idempotently afterward.- await conn.unsafe(`- ALTER TABLE timeline_entries ADD COLUMN IF NOT EXISTS event_page_id INTEGER;- `);- }-- if (needsMinionJobsTimeoutAt) {- // v7: blob index idx_minion_jobs_timeout references timeout_at; a- // pre-v7 minion_jobs wedges blob replay without it (same class as v121).- await conn.unsafe(`- ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS timeout_at TIMESTAMPTZ;- `);- }- if (needsMinionJobsIdempotencyKey) {- // v7: blob index uniq_minion_jobs_idempotency references idempotency_key.- await conn.unsafe(`- ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS idempotency_key TEXT;- `);- }- if (needsMinionJobsPrivateQueue) {- // v0.46.26: blob indexes idx_minion_jobs_private_queue_recovery /- // idx_minion_jobs_private_queue_owner reference the private-queue- // owner/lease columns; a pre-upgrade minion_jobs wedges blob replay- // without them (same class as v121). The token column is not indexed- // but rides along so upgraded rows carry the full lifecycle shape.- await conn.unsafe(`- ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;- ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;- ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;- `);- }+ await applyPostgresForwardReferenceBootstrap(injectedConn ?? this.sql);}async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {@@ -3630,7 +3043,7 @@ export class PostgresEngine implements BrainEngine {linkType?: string,linkSource?: string,opts?: { fromSourceId?: string; toSourceId?: string },- ): Promise<void> {+ ): Promise<number> {const sql = this.sql;const fromSrc = opts?.fromSourceId ?? 'default';const toSrc = opts?.toSourceId ?? 'default';@@ -3638,34 +3051,44 @@ export class PostgresEngine implements BrainEngine {// optional constraints; all four combinations are valid. Each branch's// page-id subquery is source-qualified so multi-source brains don't// delete the wrong (from, to) pair.+ // #4527: RETURNING 1 so the caller learns how many edges actually died —+ // a zero-match delete must be distinguishable from a real removal.if (linkType !== undefined && linkSource !== undefined) {- await sql`+ const rows = await sql`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})AND link_type = ${linkType}AND link_source IS NOT DISTINCT FROM ${linkSource}+ RETURNING 1`;+ return rows.length;} else if (linkType !== undefined) {- await sql`+ const rows = await sql`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})AND link_type = ${linkType}+ RETURNING 1`;+ return rows.length;} else if (linkSource !== undefined) {- await sql`+ const rows = await sql`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})AND link_source IS NOT DISTINCT FROM ${linkSource}+ RETURNING 1`;+ return rows.length;} else {- await sql`+ const rows = await sql`DELETE FROM linksWHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})+ RETURNING 1`;+ return rows.length;}}@@ -3917,6 +3340,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < ${depth}AND NOT (p2.id = ANY(g.visited))+ AND p2.deleted_at IS NULL${stepScope}ORDER BY p2.slug ASC, p2.id ASCLIMIT ${cap})`@@ -3926,12 +3350,13 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < ${depth}AND NOT (p2.id = ANY(g.visited))+ AND p2.deleted_at IS NULL${stepScope}`;// Cycle prevention: visited array tracks page IDs already in the path.const rows = await sql`WITH RECURSIVE graph AS (SELECT p.id, p.slug, p.title, p.type, 0 as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} ${seedScope}+ FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${seedScope}UNION ALL@@ -3949,7 +3374,7 @@ export class PostgresEngine implements BrainEngine {(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))FROM links l2JOIN pages p3 ON p3.id = l2.to_page_id- WHERE l2.from_page_id = g.id ${aggScope}),+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${aggScope}),'[]'::jsonb) as linksFROM graph g@@ -4389,6 +3814,7 @@ export class PostgresEngine implements BrainEngine {async findOrphanPages(opts?: {sourceId?: string;sourceIds?: string[];+ mode?: 'inbound' | 'islanded';}): Promise<Array<{ slug: string; title: string; domain: string | null }>> {const sql = this.sql;// Soft-delete filter on BOTH sides:@@ -4408,6 +3834,20 @@ export class PostgresEngine implements BrainEngine {: opts?.sourceId? sql`AND p.source_id = ${opts.sourceId}`: sql``;+ // #4524: default mode 'islanded' — identical predicate to getHealth's+ // orphan_pages (no live inbound AND no live outbound; outbound counts+ // only when its TARGET page is live, per gbrain#4153 endpoint liveness).+ // mode 'inbound' preserves the legacy no-inbound-only view.+ const outboundFilter =+ (opts?.mode ?? 'islanded') === 'islanded'+ ? sql`AND NOT EXISTS (+ SELECT 1+ FROM links l+ JOIN pages tgt ON tgt.id = l.to_page_id+ WHERE l.from_page_id = p.id+ AND tgt.deleted_at IS NULL+ )`+ : sql``;const rows = await sql`SELECTp.slug,@@ -4423,6 +3863,7 @@ export class PostgresEngine implements BrainEngine {WHERE l.to_page_id = p.idAND src.deleted_at IS NULL)+ ${outboundFilter}ORDER BY p.slug`;return rows as unknown as Array<{ slug: string; title: string; domain: string | null }>;diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.tsnew file mode 100644index 0000000000..69cb158c00--- /dev/null+++ b/src/core/postgres-engine/forward-reference-bootstrap.ts@@ -0,0 +1,606 @@+// Forward-reference bootstrap for the RAW Postgres schema-replay path.+//+// Extracted from `PostgresEngine#applyForwardReferenceBootstrap` (#4477) so+// BOTH SCHEMA_SQL replay entrypoints run it before the blob:+// - `PostgresEngine.initSchema()` (src/core/postgres-engine.ts) — delegates+// here from its private method, same call shape as before.+// - `db.initSchema()` (src/core/db.ts) — the standalone module-singleton+// path (used by test/e2e/helpers.ts and legacy callers) previously+// replayed SCHEMA_SQL with NO bootstrap, so an older brain whose tables+// predate the blob's forward-referenced columns wedged on CREATE INDEX.+//+// Bootstrap state that SCHEMA_SQL forward-references but that older brains+// don't have yet. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap`+// in shape and intent. Keep in sync with the PGLite version; covered by+// `test/schema-bootstrap-coverage.test.ts` (PGLite side) and+// `test/e2e/postgres-bootstrap.test.ts` (Postgres side).++import type postgres from 'postgres';++/**+ * Probe + patch every forward-reference target the embedded schema blob+ * needs, on the caller-provided connection. Callers MUST hold the+ * initSchema advisory lock (key 42) on `conn` so concurrent bootstraps+ * can't race on Supabase's transaction pooler.+ *+ * Idempotent on fresh installs and modern brains (single probe round-trip,+ * fast no-op when nothing is missing).+ */+export async function applyPostgresForwardReferenceBootstrap(+ conn: ReturnType<typeof postgres>,+): Promise<void> {++// Single round-trip probe for every forward-reference target.+// current_schema() resolves to whatever search_path the connection uses,+// which matches schema-embedded.ts's `public.` references.+const probeRows = await conn<{+ pages_exists: boolean;+ source_id_exists: boolean;+ deleted_at_exists: boolean;+ effective_date_exists: boolean;+ links_exists: boolean;+ link_source_exists: boolean;+ origin_page_id_exists: boolean;+ chunks_exists: boolean;+ symbol_name_exists: boolean;+ language_exists: boolean;+ search_vector_exists: boolean;+ embedding_image_exists: boolean;+ mcp_log_exists: boolean;+ agent_name_exists: boolean;+ subagent_messages_exists: boolean;+ subagent_provider_id_exists: boolean;+ ingest_log_exists: boolean;+ ingest_log_source_id_exists: boolean;+ files_exists: boolean;+ files_source_id_exists: boolean;+ files_page_id_exists: boolean;+ oauth_clients_exists: boolean;+ oauth_clients_source_id_exists: boolean;+ oauth_clients_federated_read_exists: boolean;+ oauth_clients_surface_exists: boolean;+ oauth_clients_surface_set_by_exists: boolean;+ sources_exists: boolean;+ sources_archived_exists: boolean;+ sources_archived_at_exists: boolean;+ sources_archive_expires_at_exists: boolean;+}[]>`+ SELECT+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'pages') AS pages_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_id') AS source_id_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'deleted_at') AS deleted_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'effective_date') AS effective_date_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'links') AS links_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'links' AND column_name = 'link_source') AS link_source_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'links' AND column_name = 'origin_page_id') AS origin_page_id_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'content_chunks') AS chunks_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'symbol_name') AS symbol_name_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'language') AS language_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'search_vector') AS search_vector_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'content_chunks' AND column_name = 'embedding_image') AS embedding_image_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'mcp_request_log') AS mcp_log_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'mcp_request_log' AND column_name = 'agent_name') AS agent_name_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'subagent_messages') AS subagent_messages_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'subagent_messages' AND column_name = 'provider_id') AS subagent_provider_id_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'ingest_log') AS ingest_log_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'ingest_log' AND column_name = 'source_id') AS ingest_log_source_id_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'files') AS files_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'files' AND column_name = 'source_id') AS files_source_id_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'files' AND column_name = 'page_id') AS files_page_id_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients') AS oauth_clients_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'source_id') AS oauth_clients_source_id_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'federated_read') AS oauth_clients_federated_read_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface') AS oauth_clients_surface_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface_set_by') AS oauth_clients_surface_set_by_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'sources') AS sources_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archived') AS sources_archived_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archived_at') AS sources_archived_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'archive_expires_at') AS sources_archive_expires_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'last_retrieved_at') AS pages_last_retrieved_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'ingested_via') AS pages_ingested_via_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'ingested_at') AS pages_ingested_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_uri') AS pages_source_uri_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'source_kind') AS pages_source_kind_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'contextual_retrieval_mode') AS pages_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'corpus_generation') AS pages_corpus_generation_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'contextual_retrieval_mode') AS sources_cr_mode_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'sources' AND column_name = 'trust_frontmatter_overrides') AS sources_trust_fm_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'generation') AS pages_generation_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'embedding_signature') AS pages_embedding_signature_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'pages' AND column_name = 'links_extracted_at') AS pages_links_extracted_at_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'timeline_entries') AS timeline_entries_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'timeline_entries' AND column_name = 'event_page_id') AS timeline_event_page_id_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs') AS minion_jobs_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'timeout_at') AS minion_jobs_timeout_at_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'idempotency_key') AS minion_jobs_idempotency_key_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_job_id') AS minion_jobs_pq_owner_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_token') AS minion_jobs_pq_token_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists+`;+const probe = probeRows[0]!;++const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;+const needsLinksBootstrap = probe.links_exists+ && (!probe.link_source_exists || !probe.origin_page_id_exists);+const needsChunksBootstrap = probe.chunks_exists+ && (!probe.symbol_name_exists || !probe.language_exists || !probe.search_vector_exists);+// v0.26.5: pages_deleted_at_purge_idx in SCHEMA_SQL crashes if the column+// doesn't exist yet. Migration v34 also adds it, but bootstrap runs first.+const needsPagesDeletedAt = probe.pages_exists && !probe.deleted_at_exists;+// v0.26.3 (v33): idx_mcp_log_agent_time in SCHEMA_SQL needs agent_name col.+const needsMcpLogBootstrap = probe.mcp_log_exists && !probe.agent_name_exists;+// v0.27 (v36): idx_subagent_messages_provider in SCHEMA_SQL needs provider_id+// (the SECOND column in the composite index `(job_id, provider_id)`).+const needsSubagentProviderId = probe.subagent_messages_exists && !probe.subagent_provider_id_exists;+// v0.27.1 (v39): idx_chunks_embedding_image partial HNSW in SCHEMA_SQL+// references embedding_image. Use embedding_image_exists as the proxy for+// both v39 columns; modality is added in the same migration.+const needsChunksEmbeddingImage = probe.chunks_exists && !probe.embedding_image_exists;+// v0.29.1 (v40 + v41): pages_coalesce_date_idx expression index in SCHEMA_SQL+// references effective_date. Use effective_date_exists as the proxy for the+// five v40 + v41 pages columns (emotional_weight, effective_date,+// effective_date_source, import_filename, salience_touched_at).+const needsPagesRecency = probe.pages_exists && !probe.effective_date_exists;+// v0.31.2 (v50): idx_ingest_log_source_type_created in SCHEMA_SQL references+// source_id. Old brains have ingest_log without source_id; bootstrap adds+// the column before SCHEMA_SQL replay creates the index.+const needsIngestLogSourceId = probe.ingest_log_exists && !probe.ingest_log_source_id_exists;+// v0.18 (v18): files.source_id + files.page_id added; idx_files_source_id+// and idx_files_page_id in SCHEMA_SQL crash without them.+const needsFilesBootstrap = probe.files_exists+ && (!probe.files_source_id_exists || !probe.files_page_id_exists);+// v0.34.1 (v60+v61+v65): oauth_clients.source_id + federated_read added;+// FK to sources(id) + GIN index idx_oauth_clients_federated_read in+// SCHEMA_SQL crash without them.+const needsOauthClientsBootstrap = probe.oauth_clients_exists+ && (!probe.oauth_clients_source_id_exists || !probe.oauth_clients_federated_read_exists);+// WP4 (v127): oauth_clients.surface + surface_set_by. No SCHEMA_SQL index+// references them, but the columns are migration-added AND in the blob's+// CREATE TABLE — the exact v121 mask class — so the bootstrap adds them+// defense-in-depth (and satisfies the MIGRATIONS ADD COLUMN coverage+// gate). They ship in one migration and go missing together.+const probeSurface = probe as {+ oauth_clients_surface_exists?: boolean;+ oauth_clients_surface_set_by_exists?: boolean;+};+const needsOauthClientsSurface = probe.oauth_clients_exists+ && (!probeSurface.oauth_clients_surface_exists || !probeSurface.oauth_clients_surface_set_by_exists);+// v0.26.5 (v34): sources.archived + archived_at + archive_expires_at added+// for soft-delete lifecycle. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS sources`+// is a no-op on pre-existing sources tables (won't add columns), so the+// visibility filters in search/list_pages trip on old brains. Bootstrap+// closes the gap before any visibility-filter SQL runs.+const needsSourcesArchive = probe.sources_exists+ && (!probe.sources_archived_exists+ || !probe.sources_archived_at_exists+ || !probe.sources_archive_expires_at_exists);+// v0.37.0 (v79): pages_last_retrieved_at_idx in SCHEMA_SQL references+// last_retrieved_at. Pre-v79 brains crash without the column; bootstrap+// adds it before SCHEMA_SQL replay creates the index. v79 runs later+// via runMigrations and is idempotent.+const needsPagesLastRetrievedAt = probe.pages_exists && !(probe as { pages_last_retrieved_at_exists?: boolean }).pages_last_retrieved_at_exists;+// v0.38.0 (v80): provenance columns. Not referenced by any SCHEMA_SQL+// index/FK today; bootstrap exists for the column-only forward-+// reference class defense-in-depth.+const probeProv = probe as {+ pages_ingested_via_exists?: boolean;+ pages_ingested_at_exists?: boolean;+ pages_source_uri_exists?: boolean;+ pages_source_kind_exists?: boolean;+};+const needsPagesProvenance = probe.pages_exists+ && (!probeProv.pages_ingested_via_exists+ || !probeProv.pages_ingested_at_exists+ || !probeProv.pages_source_uri_exists+ || !probeProv.pages_source_kind_exists);+// v0.40.3.0 (v90, renumbered from v0.40.3.0 v81 on master merge):+// contextual retrieval columns on pages + sources. Defense-in-depth.+const probeCr = probe as {+ pages_cr_mode_exists?: boolean;+ pages_corpus_generation_exists?: boolean;+ sources_cr_mode_exists?: boolean;+ sources_trust_fm_exists?: boolean;+ pages_generation_exists?: boolean;+ pages_embedding_signature_exists?: boolean;+ pages_links_extracted_at_exists?: boolean;+ timeline_entries_exists?: boolean;+ timeline_event_page_id_exists?: boolean;+ minion_jobs_exists?: boolean;+ minion_jobs_timeout_at_exists?: boolean;+ minion_jobs_idempotency_key_exists?: boolean;+ minion_jobs_pq_owner_exists?: boolean;+ minion_jobs_pq_token_exists?: boolean;+ minion_jobs_pq_lease_exists?: boolean;+};+const needsContextualRetrievalColumns = (probe.pages_exists+ && (!probeCr.pages_cr_mode_exists || !probeCr.pages_corpus_generation_exists))+ || (probe.sources_exists+ && (!probeCr.sources_cr_mode_exists || !probeCr.sources_trust_fm_exists));+// v0.40.3.0 (v91): pages.generation BIGINT bumped by+// bump_page_generation_trg. pages_generation_idx in SCHEMA_SQL references+// it. Pre-v91 brains crash without the column; bootstrap adds it before+// SCHEMA_SQL replay creates the index.+const needsPagesGeneration = probe.pages_exists && !probeCr.pages_generation_exists;+// v0.41.31 (v108): pages.embedding_signature for real stale semantics.+// No SCHEMA_SQL index references it; bootstrap is defense-in-depth.+const needsPagesEmbeddingSignature = probe.pages_exists && !probeCr.pages_embedding_signature_exists;+// v0.42.7 (v112): pages.links_extracted_at link-extraction freshness+// watermark. pages_links_extracted_at_idx in SCHEMA_SQL references it;+// pre-v112 brains crash without the column, so bootstrap adds it before+// SCHEMA_SQL replay creates the index. v112 runs later via runMigrations+// and is idempotent.+const needsPagesLinksExtractedAt = probe.pages_exists && !probeCr.pages_links_extracted_at_exists;+// v121: schema-blob indexes reference event_page_id before migrations run.+const needsTimelineEventPageId = probeCr.timeline_entries_exists === true+ && !probeCr.timeline_event_page_id_exists;+// v7-era (#2626 class sweep): minion_jobs.timeout_at + idempotency_key are+// migration-added AND referenced by blob indexes (idx_minion_jobs_timeout,+// uniq_minion_jobs_idempotency) — a pre-v7 minion_jobs wedges blob replay+// exactly like the v121 incident.+const needsMinionJobsTimeoutAt = probeCr.minion_jobs_exists === true+ && !probeCr.minion_jobs_timeout_at_exists;+const needsMinionJobsIdempotencyKey = probeCr.minion_jobs_exists === true+ && !probeCr.minion_jobs_idempotency_key_exists;+// Token rides the probe too: a token-only-missing brain (partial upgrade)+// would otherwise be unrepairable — the ALTER block adds all three.+const needsMinionJobsPrivateQueue = probeCr.minion_jobs_exists === true+ && (!probeCr.minion_jobs_pq_owner_exists || !probeCr.minion_jobs_pq_token_exists+ || !probeCr.minion_jobs_pq_lease_exists);++if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap+ && !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId+ && !needsChunksEmbeddingImage && !needsPagesRecency+ && !needsIngestLogSourceId && !needsFilesBootstrap+ && !needsOauthClientsBootstrap && !needsOauthClientsSurface+ && !needsSourcesArchive+ && !needsPagesLastRetrievedAt+ && !needsPagesProvenance+ && !needsContextualRetrievalColumns && !needsPagesGeneration+ && !needsPagesEmbeddingSignature+ && !needsPagesLinksExtractedAt+ && !needsTimelineEventPageId+ && !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey+ && !needsMinionJobsPrivateQueue) return;++process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');++if (needsPagesBootstrap) {+ // Mirror schema-embedded.ts's `sources` shape so the subsequent+ // SCHEMA_SQL CREATE TABLE IF NOT EXISTS is a true no-op.+ // Archive columns (v34) are folded in here so a pre-v18 brain doesn't+ // need needsSourcesArchive to also fire — bootstrap creates a complete+ // v34-shape sources in one go. needsSourcesArchive then only fires on+ // the pre-v34 case (sources exists, archive cols don't).+ await conn.unsafe(`+ CREATE TABLE IF NOT EXISTS sources (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ local_path TEXT,+ last_commit TEXT,+ last_sync_at TIMESTAMPTZ,+ config JSONB NOT NULL DEFAULT '{}'::jsonb,+ archived BOOLEAN NOT NULL DEFAULT FALSE,+ archived_at TIMESTAMPTZ,+ archive_expires_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ INSERT INTO sources (id, name, config)+ VALUES ('default', 'default', '{"federated": true}'::jsonb)+ ON CONFLICT (id) DO NOTHING;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_id TEXT+ NOT NULL DEFAULT 'default' REFERENCES sources(id) ON DELETE CASCADE;+ `);+}++if (needsLinksBootstrap) {+ // v11 (links_provenance_columns) handles the CHECK constraint, the+ // UNIQUE swap, and the backfill. The bootstrap only adds enough state+ // for SCHEMA_SQL's `CREATE INDEX idx_links_source/origin` not to crash.+ // v11 runs later via runMigrations and is idempotent.+ await conn.unsafe(`+ ALTER TABLE links ADD COLUMN IF NOT EXISTS link_source TEXT;+ ALTER TABLE links ADD COLUMN IF NOT EXISTS origin_page_id INTEGER+ REFERENCES pages(id) ON DELETE SET NULL;+ `);+}++if (needsChunksBootstrap) {+ // v26 (content_chunks_code_metadata) adds symbol_name + language; v27+ // (Cathedral II) adds parent_symbol_path + doc_comment ++ // symbol_name_qualified + search_vector. The schema blob has indexes+ // (idx_chunks_search_vector line 141, idx_chunks_symbol_qualified+ // line 142) that need the v27 columns to exist before they run.+ // v26 + v27 run later via runMigrations and are idempotent.+ await conn.unsafe(`+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS language TEXT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS symbol_name TEXT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS parent_symbol_path TEXT[];+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS doc_comment TEXT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS symbol_name_qualified TEXT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS search_vector TSVECTOR;+ `);+}++if (needsPagesDeletedAt) {+ // v34 (destructive_guard_columns) adds the column + sources columns ++ // partial purge index. Bootstrap only adds enough for SCHEMA_SQL's+ // `CREATE INDEX pages_deleted_at_purge_idx ... WHERE deleted_at IS NOT NULL`+ // not to crash. v34 runs later via runMigrations and is idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;+ `);+}++if (needsMcpLogBootstrap) {+ // v33 (admin_dashboard_columns_v0_26_3) adds agent_name + params ++ // error_message to mcp_request_log. SCHEMA_SQL's+ // `CREATE INDEX idx_mcp_log_agent_time ON mcp_request_log(agent_name,...)`+ // crashes without agent_name. v33 runs later via runMigrations and is+ // idempotent (and also handles backfill).+ await conn.unsafe(`+ ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS agent_name TEXT;+ ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS params JSONB;+ ALTER TABLE mcp_request_log ADD COLUMN IF NOT EXISTS error_message TEXT;+ `);+}++if (needsSubagentProviderId) {+ // v36 (subagent_provider_neutral_persistence_v0_27) adds provider_id ++ // schema_version on subagent_messages and subagent_tool_executions.+ // SCHEMA_SQL's `CREATE INDEX idx_subagent_messages_provider ON+ // subagent_messages (job_id, provider_id)` crashes without provider_id+ // (composite-index second column). v36 runs later via runMigrations and+ // is idempotent.+ await conn.unsafe(`+ ALTER TABLE subagent_messages ADD COLUMN IF NOT EXISTS provider_id TEXT;+ `);+}++if (needsChunksEmbeddingImage) {+ // v39 (multimodal_dual_column_v0_27_1) adds modality + embedding_image+ // columns to content_chunks plus a partial HNSW index that references+ // embedding_image. Bootstrap mirrors enough state for SCHEMA_SQL's+ // `CREATE INDEX idx_chunks_embedding_image ... WHERE embedding_image IS NOT NULL`+ // not to crash. v39 runs later via runMigrations and is idempotent.+ await conn.unsafe(`+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS modality TEXT NOT NULL DEFAULT 'text';+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_image vector(1024);+ `);+}++if (needsPagesRecency) {+ // v40 (pages_emotional_weight) adds emotional_weight; v41+ // (pages_recency_columns) adds effective_date + effective_date_source ++ // import_filename + salience_touched_at and the+ // `pages_coalesce_date_idx ON pages ((COALESCE(effective_date, updated_at)))`+ // expression index. SCHEMA_SQL's CREATE INDEX for that expression crashes+ // before v41 runs. Bootstrap adds all five additive columns; v40 + v41+ // run later via runMigrations and are idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS emotional_weight REAL NOT NULL DEFAULT 0.0;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS effective_date TIMESTAMPTZ;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS effective_date_source TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS import_filename TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS salience_touched_at TIMESTAMPTZ;+ `);+}++if (needsIngestLogSourceId) {+ // v50 (ingest_log_source_id) adds source_id ++ // idx_ingest_log_source_type_created composite index. SCHEMA_SQL's+ // CREATE INDEX (source_id, source_type, created_at) crashes without+ // source_id. Bootstrap adds the column with NOT NULL DEFAULT 'default'+ // so the index can build cleanly.+ await conn.unsafe(`+ ALTER TABLE ingest_log ADD COLUMN IF NOT EXISTS source_id TEXT NOT NULL DEFAULT 'default';+ `);+}++if (needsFilesBootstrap) {+ // v18 (files_provenance_columns) adds source_id + page_id to files plus+ // idx_files_source_id and idx_files_page_id in SCHEMA_SQL. Pre-v18 brains+ // crash on the CREATE INDEX. Bootstrap adds both columns; v18 runs later+ // via runMigrations and is idempotent.+ await conn.unsafe(`+ ALTER TABLE files ADD COLUMN IF NOT EXISTS source_id TEXT+ NOT NULL DEFAULT 'default' REFERENCES sources(id) ON DELETE CASCADE;+ ALTER TABLE files ADD COLUMN IF NOT EXISTS page_id INTEGER+ REFERENCES pages(id) ON DELETE SET NULL;+ `);+}++if (needsOauthClientsBootstrap) {+ // v60+v61+v65 (oauth_clients_source_id_fk, oauth_clients_federated_read_column,+ // oauth_clients_federated_read_gin_index) add source_id + federated_read+ // and the GIN index idx_oauth_clients_federated_read. SCHEMA_SQL's+ // FK + index references crash on pre-v60 brains. Bootstrap mirrors the+ // v60+v61 column shape; v60-v65 run later via runMigrations and are+ // idempotent (and handle backfill + the v64 RESTRICT-flip).+ await conn.unsafe(`+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS source_id TEXT+ DEFAULT 'default' REFERENCES sources(id) ON DELETE SET NULL;+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS federated_read TEXT[]+ NOT NULL DEFAULT '{}';+ `);+}++if (needsOauthClientsSurface) {+ // WP4 (v127): per-client MCP tool surface + operator-lock marker.+ // Nullable TEXT, no index — bootstrap mirrors the v127 column shape so+ // the blob's CREATE TABLE presence can't mask the forward reference on+ // pre-v127 brains (the v121 wedge class). v127 runs later via+ // runMigrations and is idempotent. Mirror of the PGLite bootstrap.+ await conn.unsafe(`+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT;+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT;+ `);+}++if (needsSourcesArchive) {+ // v34 (destructive_guard_columns) promotes archive lifecycle from JSONB+ // config to real columns on sources. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS+ // sources` is a no-op against an existing pre-v34 sources table, so the+ // column-add never lands until the v34 migration runs. v34's UPDATE+ // statements + downstream visibility filters (search/query/list_pages)+ // need the columns to exist on the table schema. Bootstrap adds the+ // three columns; v34 runs later via runMigrations and is idempotent+ // (and handles JSONB → column backfill).+ await conn.unsafe(`+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS archived BOOLEAN NOT NULL DEFAULT FALSE;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS archive_expires_at TIMESTAMPTZ;+ `);+}++if (needsPagesLastRetrievedAt) {+ // v79 (pages_last_retrieved_at): adds the real stale-page signal column+ // + full B-tree index. SCHEMA_SQL's CREATE INDEX+ // pages_last_retrieved_at_idx crashes without the column. v79 runs+ // later via runMigrations and is idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS last_retrieved_at TIMESTAMPTZ;+ `);+}++if (needsPagesProvenance) {+ // v81 (pages_provenance_columns): four nullable columns added by the+ // v0.38 ingestion cathedral. No SCHEMA_SQL index/FK references them+ // today; bootstrap exists defense-in-depth so future schema work that+ // does reference them doesn't wedge pre-v81 brains.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS ingested_via TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS ingested_at TIMESTAMPTZ;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_uri TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS source_kind TEXT;+ `);+}++if (needsContextualRetrievalColumns) {+ // v0.40.3.0 v90 (contextual_retrieval_columns, renumbered from+ // v0.40.3.0 v81 on master merge). Five additive columns wiring the+ // three-tier wrapper ladder. Defense-in-depth probes; v90 runs later+ // via runMigrations and is idempotent (ADD COLUMN IF NOT EXISTS).+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS corpus_generation TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS contextual_retrieval_mode TEXT;+ ALTER TABLE sources ADD COLUMN IF NOT EXISTS trust_frontmatter_overrides BOOLEAN NOT NULL DEFAULT FALSE;+ `);+}++if (needsPagesGeneration) {+ // v0.40.3.0 v91 (pages_generation_trigger_and_bookmark):+ // pages.generation BIGINT. SCHEMA_SQL CREATE INDEX+ // pages_generation_idx ON pages (generation) crashes on pre-v91 brains+ // without this. The trigger and index land via v91 migration run+ // later; bootstrap only adds the column. v91 is idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 1;+ `);+}++if (needsPagesEmbeddingSignature) {+ // v108 (pages_embedding_signature): embedding provenance for real stale+ // semantics. NULL grandfathered. v108 runs later via runMigrations and+ // is idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS embedding_signature TEXT;+ `);+}++if (needsPagesLinksExtractedAt) {+ // v112 (pages_links_extracted_at): link-extraction freshness watermark.+ // pages_links_extracted_at_idx in SCHEMA_SQL references it, so bootstrap+ // adds the column before the blob's CREATE INDEX runs. The index itself+ // lands via the blob (CREATE INDEX IF NOT EXISTS) and v112 (CONCURRENTLY);+ // bootstrap only adds the column. v112 runs later via runMigrations and is+ // idempotent.+ await conn.unsafe(`+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS links_extracted_at TIMESTAMPTZ;+ `);+}++if (needsTimelineEventPageId) {+ // Add only the forward-referenced column. Migration v121 remains the+ // source of truth for the FK and indexes and runs idempotently afterward.+ await conn.unsafe(`+ ALTER TABLE timeline_entries ADD COLUMN IF NOT EXISTS event_page_id INTEGER;+ `);+}++if (needsMinionJobsTimeoutAt) {+ // v7: blob index idx_minion_jobs_timeout references timeout_at; a+ // pre-v7 minion_jobs wedges blob replay without it (same class as v121).+ await conn.unsafe(`+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS timeout_at TIMESTAMPTZ;+ `);+}+if (needsMinionJobsIdempotencyKey) {+ // v7: blob index uniq_minion_jobs_idempotency references idempotency_key.+ await conn.unsafe(`+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS idempotency_key TEXT;+ `);+}+if (needsMinionJobsPrivateQueue) {+ // v0.46.26: blob indexes idx_minion_jobs_private_queue_recovery /+ // idx_minion_jobs_private_queue_owner reference the private-queue+ // owner/lease columns; a pre-upgrade minion_jobs wedges blob replay+ // without them (same class as v121). The token column is not indexed+ // but rides along so upgraded rows carry the full lifecycle shape.+ await conn.unsafe(`+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_job_id INTEGER REFERENCES minion_jobs(id) ON DELETE SET NULL;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_owner_token TEXT;+ ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS private_queue_lease_until TIMESTAMPTZ;+ `);+}+}diff --git a/src/core/schema-pack/index.ts b/src/core/schema-pack/index.tsindex 02c4ca3358..dc405508f1 100644--- a/src/core/schema-pack/index.ts+++ b/src/core/schema-pack/index.ts@@ -98,6 +98,7 @@ export {export {loadActivePack,+ loadResolvedPackByName,resolveActivePackNameOnly,__setPackLocatorForTests,_resetPackLocatorForTests,diff --git a/src/core/schema-pack/load-active.ts b/src/core/schema-pack/load-active.tsindex d6a03428a3..d8809c6641 100644--- a/src/core/schema-pack/load-active.ts+++ b/src/core/schema-pack/load-active.ts@@ -160,6 +160,23 @@ export async function loadActivePack(input: LoadActivePackInput): Promise<Resolv});}+/**+ * Load + resolve a pack BY NAME — extends chain walked, borrow_from+ * resolved, child-wins merge applied — without touching the active-pack+ * resolution chain. `gbrain schema lint <name>` uses this (#4501) so a+ * named pack is linted against the same merged manifest it would serve+ * when active; a child that references inherited parent types must not+ * fail raw-manifest lint. Throws the same errors as `loadActivePack`+ * (UnknownPackError, ExtendsChainTooDeepError, AliasCycleError,+ * SchemaPackManifestError).+ */+export async function loadResolvedPackByName(name: string): Promise<ResolvedPack> {+ const manifest = await loadPackManifestByName(name);+ return await resolvePack(manifest, loadPackManifestByName, {+ loadByPath: (n) => _packLocator(n),+ });+}+/*** Return the resolved pack NAME and source tier WITHOUT loading the* manifest from disk. Used by `gbrain schema active` to surfacediff --git a/src/core/schema-verify.ts b/src/core/schema-verify.tsindex 98cd1ddde0..1b3408a1ca 100644--- a/src/core/schema-verify.ts+++ b/src/core/schema-verify.ts@@ -187,28 +187,30 @@ export interface VerifyResult {failed: Array<{ table: string; column: string; error: string }>;}+export interface DetectResult {+ /** Total columns checked */+ checked: number;+ /** Columns that were missing */+ missing: Array<{ table: string; column: string }>;+}+/**- * Verify that every column defined in schema-embedded.ts actually exists- * in the database. Self-heals missing columns via ALTER TABLE ADD COLUMN.- *- * Should be called after initSchema() + runMigrations() complete.+ * Read-only pass: diff schema-embedded.ts's expected columns against+ * information_schema.columns. Does NOT attempt any ALTER TABLE — callers+ * that only need to detect drift (e.g. a doctor health check) should use+ * this instead of verifySchema(), which mutates the database.*- * @returns VerifyResult with details of what was checked and fixed.- * @throws Error if any columns could not be healed (after attempting all).+ * Extracted from verifySchema() (gbrain#4421) so `gbrain doctor` can report+ * this same ledger-vs-live-schema drift without a plain diagnostic run+ * silently issuing DDL.*/-export async function verifySchema(engine: BrainEngine): Promise<VerifyResult> {+export async function detectMissingColumns(engine: BrainEngine): Promise<DetectResult> {const expected = parseExpectedColumns();const actualColumns = await getActualColumns(engine);const actualTables = await getActualTables(engine);- const result: VerifyResult = {- checked: 0,- missing: [],- healed: [],- failed: [],- };+ const result: DetectResult = { checked: 0, missing: [] };- // Group expected columns by table for cleaner loggingfor (const col of expected) {// Skip tables that don't exist yet — they'll be created by schema.sql// on the next initSchema() call. We only verify columns on tables that@@ -226,6 +228,29 @@ export async function verifySchema(engine: BrainEngine): Promise<VerifyResult> {}}+ return result;+}++/**+ * Verify that every column defined in schema-embedded.ts actually exists+ * in the database. Self-heals missing columns via ALTER TABLE ADD COLUMN.+ *+ * Should be called after initSchema() + runMigrations() complete.+ *+ * @returns VerifyResult with details of what was checked and fixed.+ * @throws Error if any columns could not be healed (after attempting all).+ */+export async function verifySchema(engine: BrainEngine): Promise<VerifyResult> {+ const expected = parseExpectedColumns();+ const detected = await detectMissingColumns(engine);++ const result: VerifyResult = {+ checked: detected.checked,+ missing: detected.missing,+ healed: [],+ failed: [],+ };+if (result.missing.length === 0) {return result;}diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.tsindex 584c5c554c..c057b3d8b2 100644--- a/src/core/search/cjk-keyword-sql.ts+++ b/src/core/search/cjk-keyword-sql.ts@@ -91,6 +91,23 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor}let extraFilter = '';+ // #4480: the CJK arm must honor the SAME shape filters as the main+ // keyword arm. type/types/exclude_slugs were silently dropped here, so a+ // typed query (`gbrain whoknows` → types:['person','company']) or an+ // exclude-scoped query returned out-of-contract rows for CJK text while+ // ASCII text filtered correctly.+ if (opts?.type) {+ params.push(opts.type);+ extraFilter += ` AND p.type = $${params.length}`;+ }+ if (opts?.types && opts.types.length > 0) {+ params.push(opts.types);+ extraFilter += ` AND p.type = ANY($${params.length}::text[])`;+ }+ if (opts?.exclude_slugs?.length) {+ params.push(opts.exclude_slugs);+ extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;+ }if (opts?.language) {params.push(opts.language);extraFilter += ` AND cc.language = $${params.length}`;diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex d9a59c8305..cdad1fd6f9 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -58,6 +58,16 @@ export interface ExactLookupOpts {* only the slug probe runs.*/titleCandidates?: SearchResult[];+ /**+ * #4480 — shape-filter gating. The scored arms apply type/types/+ * exclude_slugs at SQL level; without the same gate here the tier could+ * top-inject a page the caller's filters explicitly excluded. Same+ * semantics as SearchOpts: `type` and `types` are AND-applied, both empty+ * = no type gate.+ */+ type?: string;+ types?: string[];+ excludeSlugs?: string[];}/** Max distinct sources probed for a slug-shaped query on a federated call. */@@ -78,7 +88,17 @@ export async function structuralExactLookup(const hits: SearchResult[] = [];const seen = new Set<string>();+ // #4480 — mirror the scored arms' shape filters so the tier can never+ // inject a page the caller explicitly filtered out.+ const excluded = new Set(opts.excludeSlugs ?? []);+ const typeGate = (t: string | undefined | null): boolean => {+ if (opts.type && t !== opts.type) return false;+ if (opts.types && opts.types.length > 0 && (t == null || !opts.types.includes(t))) return false;+ return true;+ };const push = (r: SearchResult) => {+ if (excluded.has(r.slug)) return;+ if (!typeGate(r.type)) return;const key = `${r.source_id ?? 'default'}::${r.slug}`;if (seen.has(key)) return;seen.add(key);diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex 1c79819dfa..bfd672e0d8 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -39,7 +39,13 @@ import {import { loadConfigWithEngine } from '../config.ts';import { dedupResults } from './dedup.ts';import { applyReranker } from './rerank.ts';-import { autoDetectDetail, classifyQuery, isAmbiguousModalityQuery } from './query-intent.ts';+import {+ classifyQuery,+ classifyQueryWithBrainPatterns,+ isAmbiguousModalityQuery,+ loadEngineIntentPatterns,+ type QuerySuggestions,+} from './query-intent.ts';import { isTitlePhraseMatch } from './title-match.ts';import { normalizeAlias } from './alias-normalize.ts';import { stampEvidence, markKeywordHits } from './evidence.ts';@@ -1199,17 +1205,20 @@ export async function hybridSearch(// v0.32.x search-lite: classify intent once up front. Drives BOTH the// legacy auto-detail / salience / recency suggestions AND the new- // weight-adjustment path. Intent weighting is on by default and can- // be disabled via `opts.intentWeighting = false`. The mode bundle- // supplies the default when neither per-call nor per-key sets it.- const suggestions = classifyQuery(query);+ // weight-adjustment path. Intent weighting is on by default (off via+ // `opts.intentWeighting = false`; mode bundle supplies the default).+ // #4415: merges the brain's `search.intent_patterns` config over the banks.+ const suggestions = await classifyQueryWithBrainPatterns(engine, query);const intentWeightingOn = resolvedMode.intentWeighting;const intentWeights = intentWeightingOn? weightsForIntent(suggestions.intent): weightsForIntent('general');- // Auto-detect detail level from query intent when caller doesn't specify- const detail = opts?.detail ?? autoDetectDetail(query);+ // Auto-detect detail level from query intent when caller doesn't specify.+ // wave-g: read the pattern-aware suggestion computed above (per-engine+ // banks) rather than the pattern-less autoDetectDetail — the two drifted+ // on the first query of a fresh process before the config was applied.+ const detail = opts?.detail ?? suggestions.suggestedDetail;const detailResolved: 'low' | 'medium' | 'high' | null = detail ?? null;const searchOpts: SearchOpts = {limit: innerLimit,@@ -1251,8 +1260,8 @@ export async function hybridSearch(// D2 fix (fix/title-retrieval-arm, Reviewer F1): the hybrid keyword arm// is a recall arm — opt in to the engine's AND→OR zero-recall fallback.// Direct searchKeyword consumers (countMentions, link-extraction, eval)- // do NOT set this and keep the strict-AND contract.- orFallback: true,+ // do NOT set this. Knob: search.keywordOrFallback (rationale: ModeBundle).+ orFallback: resolvedMode.keywordOrFallback,// v0.46.15: collect searchVector's bounded-escalation exhaustion signal —// engines have no telemetry sink (R2-10); hybrid owns the meta emit.// ACCUMULATES across vector calls (adversarial F8): expansion runs N@@ -1368,32 +1377,13 @@ export async function hybridSearch(// v0.29.1: resolve salience/recency from caller (back-compat aliases for// PR #618's `recencyBoost` numeric scale) or fall back to the heuristic.// The wrapper fires from ALL THREE return paths (codex pass-1 #2 + pass-2 #4).- //- // v0.32.x search-lite: when caller hasn't set recency and the intent- // classifier suggests one, prefer that (suggestedRecency on temporal /- // event intents). The legacy heuristic still wins when intent weighting- // is off.- // Back-compat: recencyBoost: 1|2 → 'on'|'strong'; 0 → 'off'.- const legacyRecency: 'off' | 'on' | 'strong' | undefined =- opts?.recencyBoost === 2 ? 'strong' :- opts?.recencyBoost === 1 ? 'on' :- opts?.recencyBoost === 0 ? 'off' :- undefined;- const salienceMode: 'off' | 'on' | 'strong' = opts?.salience ?? suggestions.suggestedSalience;- // Intent-weighting recency suggestion is a NUDGE — it only fires when- // the caller left recency unspecified AND the legacy heuristic also- // didn't fire. The classifier's own suggestedRecency (from v0.29.1)- // still wins when it's set; the new intent suggestion is a fallback.- const intentRecency =- intentWeightingOn && intentWeights.suggestedRecency != null- ? intentWeights.suggestedRecency- : null;+ // wave-g: extracted to resolveEffectiveSalience/resolveEffectiveRecency so+ // hybridSearchCached's knobs-hash key parts (sal=/rec=, v=24) resolve+ // through the IDENTICAL chain — drift here would key cache rows under a+ // different mode than the stored results used.+ const salienceMode: 'off' | 'on' | 'strong' = resolveEffectiveSalience(opts, suggestions);const recencyMode: 'off' | 'on' | 'strong' =- opts?.recency- ?? legacyRecency- ?? (suggestions.suggestedRecency !== 'off'- ? suggestions.suggestedRecency- : (intentRecency ?? suggestions.suggestedRecency));+ resolveEffectiveRecency(opts, suggestions, intentWeightingOn);const postFusionOpts: PostFusionOpts = {applyBacklinks: true,salience: salienceMode,@@ -1500,6 +1490,10 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ // #4480: gate tier injections on the caller's shape filters.+ type: opts?.type,+ types: opts?.types,+ excludeSlugs: opts?.exclude_slugs,});stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });// #3995 — guaranteed page-1 relational evidence: a fired arm's answer is@@ -1887,6 +1881,10 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ // #4480: gate tier injections on the caller's shape filters.+ type: opts?.type,+ types: opts?.types,+ excludeSlugs: opts?.exclude_slugs,});stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });const kwSliced = kwHopped.slice(offset, offset + limit);@@ -2095,6 +2093,10 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ // #4480: gate tier injections on the caller's shape filters.+ type: opts?.type,+ types: opts?.types,+ excludeSlugs: opts?.exclude_slugs,});// T4 — stamp evidence + create_safety so the agent's don't-duplicate@@ -2215,6 +2217,50 @@ export async function hybridSearch(// v0.32.x (search-lite) — cached + budgeted public wrapper// ----------------------------------------------------------------------+/**+ * wave-g (#4415 knobs-hash fold) — the ONE salience resolution chain, shared+ * by bare hybridSearch (post-fusion boost) and hybridSearchCached (the+ * `sal=` cache-key part). Explicit per-call opt wins; otherwise the+ * classifier's pattern-aware suggestion.+ */+function resolveEffectiveSalience(+ opts: HybridSearchOpts | undefined,+ suggestions: QuerySuggestions,+): 'off' | 'on' | 'strong' {+ return opts?.salience ?? suggestions.suggestedSalience;+}++/**+ * wave-g (#4415 knobs-hash fold) — the ONE recency resolution chain, shared+ * by bare hybridSearch and hybridSearchCached (the `rec=` cache-key part).+ *+ * Back-compat: recencyBoost: 1|2 → 'on'|'strong'; 0 → 'off'.+ * Intent-weighting recency suggestion is a NUDGE — it only fires when the+ * caller left recency unspecified AND the classifier's own suggestedRecency+ * (v0.29.1) didn't fire; it stays null when intent weighting is off.+ */+function resolveEffectiveRecency(+ opts: HybridSearchOpts | undefined,+ suggestions: QuerySuggestions,+ intentWeightingOn: boolean,+): 'off' | 'on' | 'strong' {+ const legacyRecency: 'off' | 'on' | 'strong' | undefined =+ opts?.recencyBoost === 2 ? 'strong' :+ opts?.recencyBoost === 1 ? 'on' :+ opts?.recencyBoost === 0 ? 'off' :+ undefined;+ const intentRecency = intentWeightingOn+ ? (weightsForIntent(suggestions.intent).suggestedRecency ?? null)+ : null;+ return (+ opts?.recency+ ?? legacyRecency+ ?? (suggestions.suggestedRecency !== 'off'+ ? suggestions.suggestedRecency+ : (intentRecency ?? suggestions.suggestedRecency))+ );+}+/*** Public wrapper around hybridSearch that adds the v0.32.x search-lite* features: semantic query cache + token budget enforcement. Both are@@ -2292,6 +2338,15 @@ export async function hybridSearchCached(const resolvedColCached = resolveEmbeddingColumn(opts, cfgCached);const isNonDefaultColumn = !isCacheSafe(resolvedColCached, cfgCached);+ // wave-g (#4415): classify ONCE with the brain's `search.intent_patterns`+ // applied (loadEngineIntentPatterns is per-engine + TTL-cached) so the+ // det=/sal=/rec= key parts reflect the SAME classification bare+ // hybridSearch resolves. Pre-fix, det= was computed via the pattern-less+ // global classifier, so a fresh process keyed its first cache row under a+ // pattern-less detail while the stored results used the pattern-aware one.+ const intentStateForCache = await loadEngineIntentPatterns(engine);+ const cacheSuggestions = classifyQuery(query, intentStateForCache.banks);+// Cache key carries the column + provider so different embedding spaces// never collide on the same `(source_id, query_text)` row.const cacheKnobsHash = knobsHash(resolvedForCache, {@@ -2307,9 +2362,21 @@ export async function hybridSearchCached(// gates dedup, chunk-source filtering, and the compiled_truth boost, so// a `--detail low` write (compiled-truth-only result set) must never be// served to a default `medium` lookup. Resolve auto-detect the same way- // bare hybridSearch does (opts.detail ?? autoDetectDetail(query)) so an+ // bare hybridSearch does (opts.detail ?? pattern-aware suggestion) so an// auto-detected `high` query keys like an explicit `high` one.- detail: opts?.detail ?? autoDetectDetail(query),+ detail: opts?.detail ?? cacheSuggestions.suggestedDetail,+ // #4415 (wave-g, v=24) — fold the EFFECTIVE salience/recency modes.+ // Both reorder the post-fusion result set, and #4415 put the per-call+ // overrides on the default MCP `search` surface, so a salience:'strong'+ // write must never serve a salience:'off' lookup of the same query.+ // Resolved by the SAME chain bare hybridSearch uses (helpers above).+ salience: resolveEffectiveSalience(opts, cacheSuggestions),+ recency: resolveEffectiveRecency(opts, cacheSuggestions, resolvedForCache.intentWeighting),+ // #4415 (wave-g, v=24) — fold the applied intent-pattern config+ // fingerprint: a `search.intent_patterns` edit changes classification+ // (and thus results), so it must change the key immediately instead of+ // serving old-classification rows for the rest of the cache TTL.+ intentPatterns: intentStateForCache.fingerprint,// #4352 follow-up — fold the private-visibility posture into the key// (xp=, v=23) for BOTH the lookup and the write below (they share this// one hash), instead of the original wholesale skipCache bypass. A@@ -2361,8 +2428,18 @@ export async function hybridSearchCached(// floor), making offset a result-affecting input that sits OUTSIDE the// knobs hash. Bypass the cache entirely (lookup AND store — the store is// gated on cacheStatus === 'miss' below, so 'disabled' covers both) for- // offset>0 requests; offset===0 semantics are unchanged.- const pagedRequest = (opts?.offset ?? 0) > 0;+ // any nonzero offset; offset===0 semantics are unchanged. #4358 residual+ // gap (this condition landed via #4368's wave as `> 0`, which absorbed+ // the positive-offset half of the original fix but not this one): a+ // negative offset re-slices the stored page just as badly as a positive+ // one (Array.prototype.slice treats a negative start as counting from+ // the array's end) — e.g. for offset=-21/limit=9 on a 21-row pool, the+ // store-time slice correctly returns the pool's first 9 rows, but+ // re-applying that same negative offset a second time (hit path, now+ // against the already-9-row stored page) clamps both bounds to the+ // array's start and returns nothing — so `> 0` let those requests+ // read/write the cache anyway.+ const pagedRequest = (opts?.offset ?? 0) !== 0;// #4352 follow-up — excludePrivate no longer skips the cache: the posture// is folded into knobsHash (xp=, v=23), so a private-included (trusted)// write can never serve a private-excluding lookup and vice versa. The@@ -2435,7 +2512,28 @@ export async function hybridSearchCached(// displace legitimate ones off the offset/limit window either.const scopedResults = filterResultsByCallerScope(hit.results, opts);- const limit = opts?.limit || 20;+ // #4356 — was a hard `|| 20`, independent of the mode-resolution the+ // miss path uses (`opts?.limit || resolvedMode.searchLimit` above, in+ // bare hybridSearch): a balanced-mode miss could cache 25 results,+ // then the next identical-shape hit sliced that row down to 20.+ // `resolvedForCache` (resolved once, above, at the top of this+ // function) already folds `opts?.limit` through the same per-call+ // resolver bare hybridSearch's own `resolvedMode` uses (including 0 —+ // see mode.ts `resolveSearchMode`'s `pick()`), so mirroring it here+ // keeps hit/miss consistent for the common case without a second+ // config round-trip. Caveat: this is a SEPARATE `resolveSearchMode`+ // call from the one bare hybridSearch performs internally on a miss+ // (hybrid.ts's inner `resolvedMode`, computed when `hybridSearch` is+ // invoked below) — not literally the same object — so a `search.mode`+ // / `search.searchLimit` config change landing between these two+ // resolutions within one request could theoretically desync the+ // stored row's actual size from what its own `knobsHash` (built from+ // `resolvedForCache`) implies. Narrow and pre-existing (the double+ // resolution itself predates this PR); tracked as #4359, not fixed+ // here — closing it would mean threading one resolved snapshot into+ // the inner `hybridSearch` call, a larger change than this PR's+ // `|| 20` → `|| resolvedMode.searchLimit` substitution.+ const limit = opts?.limit || resolvedForCache.searchLimit;const offset = opts?.offset || 0;const sliced = scopedResults.slice(offset, offset + limit);@@ -2785,8 +2883,11 @@ export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true)/*** Cosine re-scoring: blend RRF score with query-chunk cosine similarity.* Runs before dedup so semantically better chunks survive.+ *+ * Exported (only) for direct unit testing of the chunkless-row blend fix+ * (#3695) — not part of the public search API surface.*/-async function cosineReScore(+export async function cosineReScore(engine: BrainEngine,results: SearchResult[],queryEmbedding: Float32Array,@@ -2816,10 +2917,18 @@ async function cosineReScore(const maxRrf = Math.max(...results.map(r => r.score));return results.map(r => {+ // v0.46.28.0 (#3695): a row with no hydratable chunk embedding (the+ // synthetic chunkless row for an embed_skip'd oversized page, or a+ // chunk_id whose embedding didn't hydrate) used to return `r` untouched+ // — keeping its RAW post-RRF score on a [0, ~2.0] scale while every+ // other row got compressed onto the [0, 1.0] blended scale below. That+ // gave chunkless rows a structural 2x head start (#3695's reported+ // symptom: an empty-snippet embed_skip page outranking on-point+ // results). Route it through the SAME blend with cosine=0 instead of+ // excluding it — excluding would make embed_skip pages unsearchable,+ // a different (undesired) behavior change.const chunkEmb = r.chunk_id != null ? embeddingMap.get(r.chunk_id) : undefined;- if (!chunkEmb) return r;-- const cosine = cosineSimilarity(queryEmbedding, chunkEmb);+ const cosine = chunkEmb ? cosineSimilarity(queryEmbedding, chunkEmb) : 0;const normRrf = maxRrf > 0 ? r.score / maxRrf : 0;const blended = 0.7 * normRrf + 0.3 * cosine;diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 6aedd671e6..b7f04b5f1c 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -76,6 +76,17 @@ export interface ModeBundle {cache_ttl_seconds: number;/** Zero-LLM intent classifier weight adjustments (PR #897). On for everyone. */intentWeighting: boolean;+ /**+ * Keyword-arm AND→OR zero-recall fallback (fix/title-retrieval-arm, D2).+ * websearch AND semantics at chunk grain mean one non-co-occurring token+ * zeroes keyword recall; the fallback retries once with OR-of-terms.+ * On corpora the FTS config can't stem (CJK/agglutinative text under+ * 'english') the OR retry can match a large fraction of the corpus, and+ * ts_rank has no IDF to demote common-token hits — the relaxed rows read+ * as noise in the RRF blend. This knob lets those corpora turn the+ * fallback off. Default on (the previous hardcoded behavior).+ */+ keywordOrFallback: boolean;/*** Per-call token budget cap (PR #897). undefined = no-op (tokenmax).* 4000 = tight (conservative, fits Haiku context loop).@@ -326,6 +337,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: 4000,expansion: false,searchLimit: 10,@@ -373,6 +385,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: 12000,expansion: false,searchLimit: 25,@@ -434,6 +447,7 @@ export const MODE_BUNDLES: Readonly<Record<SearchMode, Readonly<ModeBundle>>> =cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: undefined,expansion: true,searchLimit: 50,@@ -501,6 +515,7 @@ export interface SearchKeyOverrides {cache_similarity_threshold?: number;cache_ttl_seconds?: number;intentWeighting?: boolean;+ keywordOrFallback?: boolean;tokenBudget?: number;expansion?: boolean;searchLimit?: number;@@ -554,6 +569,7 @@ export interface SearchPerCallOpts {cache_similarity_threshold?: number;cache_ttl_seconds?: number;intentWeighting?: boolean;+ keywordOrFallback?: boolean;tokenBudget?: number;expansion?: boolean;searchLimit?: number;@@ -658,6 +674,7 @@ export function resolveSearchMode(input: ResolveSearchModeInput): ResolvedSearchcache_similarity_threshold: pick('cache_similarity_threshold'),cache_ttl_seconds: pick('cache_ttl_seconds'),intentWeighting: pick('intentWeighting'),+ keywordOrFallback: pick('keywordOrFallback'),tokenBudget: pick('tokenBudget'),expansion: pick('expansion'),searchLimit: pick('searchLimit'),@@ -896,7 +913,43 @@ export function attributeKnob<K extends keyof ModeBundle>(// ~50% cache savings back. Same contamination class as detail (v=16) and// hardExcludes (v=12); same one-time global cold-miss pattern as the bumps// above, refills within cache.ttl_seconds (3600s default).-export const KNOBS_HASH_VERSION = 23;+//+// bump 23→24 (#4358 residual): hybrid.ts's `pagedRequest` skip-cache gate+// only bypassed the cache for offset>0 (the #4368 wave absorbed the+// positive-offset half of the original #4358 fix, which used `!== 0`, as+// `> 0`). A negative offset re-slices an already-sliced stored page just as+// badly as a positive one, and — since offset isn't part of this hash — a+// negative-offset request could read OR write the same cache row an+// offset=0 (or any other offset) request shares. Any row written while that+// gap was live may hold a wrong page under a knobsHash a clean request can+// still reach. No new key part; the bump alone invalidates (the PR authored+// this as v=22; master had already reached 23, so it sequences here per the+// D8 convention). Same one-time global cold-miss pattern as the bumps+// above; refills within cache.ttl_seconds (3600s).+//+// bump 24→25: `kof=` (keyword AND→OR fallback knob) joins the key. The PR+// authored this as 23→24, but 24 was claimed by the negative-offset bump+// above while it was open, so it takes the next free number per the D8+// convention. Same one-time global cold-miss pattern as the bumps above.+//+// bump 25→26 folds salience/recency + intent_patterns (#4415) — wave-g. Three+// new ctx parts:+// sal=/rec= — the EFFECTIVE per-call salience/recency modes (explicit+// SearchOpts ?? auto-suggested, resolved by the same chain bare+// hybridSearch uses — see hybrid.ts resolveEffectiveSalience/+// resolveEffectiveRecency). #4415 extended the per-call knobs to the+// default MCP `search` surface, so a salience:'strong' write (reordered+// result set) could be served to a salience:'off' lookup of the same+// query for the whole TTL — same contamination class as det= (v=16).+// ipat= — fingerprint of the applied `search.intent_patterns` config.+// The patterns change classification (intent weights + auto salience/+// recency/detail) and therefore results; without the fold, a config+// edit kept serving old-classification rows for up to the TTL.+// Same one-time global cold-miss pattern as the bumps above; refills+// within cache.ttl_seconds (3600s default). (Authored as 23→24 on the+// wave-g branch; 24 and 25 were claimed by the two bumps above while it+// was in flight, so it takes the next free number per the D8 convention.)+export const KNOBS_HASH_VERSION = 26;/*** v0.36 (D8 / CDX-2) — second-arg context for the cache key. The@@ -956,6 +1009,28 @@ export interface KnobsHashContext {* (private included), matching enforcement's strict `=== true` semantics.*/excludePrivate?: boolean;+ /**+ * v=24 (#4415, wave-g): the EFFECTIVE salience/recency boost modes for+ * this call — per-call SearchOpts, or the classifier's auto-suggestion+ * when the caller didn't specify (hybridSearchCached resolves them with+ * the same chain bare hybridSearch uses). Both reorder the post-fusion+ * result set, so a 'strong' write must never serve an 'off' lookup.+ * Undefined falls back to 'off' (the classifier's default for unmatched+ * queries) so legacy callers hash stably.+ */+ salience?: 'off' | 'on' | 'strong';+ recency?: 'off' | 'on' | 'strong';+ /**+ * v=24 (#4415, wave-g): fingerprint of the applied `search.intent_patterns`+ * config (query-intent.ts intentPatternFingerprint — 'none' when unset).+ * The patterns change classification (intent weights + auto salience/+ * recency/detail) and therefore results; folding the fingerprint makes a+ * config edit invalidate immediately instead of after the TTL. Threaded+ * through ctx (not read process-globally like fts=) because the applied+ * config is PER ENGINE (wave-g) — a process-global read would key one+ * brain's rows under another brain's patterns in a multi-engine process.+ */+ intentPatterns?: string;}export function knobsHash(@@ -1083,6 +1158,21 @@ export function knobsHash(// Strict `=== true` mirrors the enforcement predicate so undefined and// false (both private-included) hash identically.`xp=${ctx?.excludePrivate === true ? 1 : 0}`,+ // v=25 addition (append-only): keyword AND→OR fallback knob. A+ // fallback-on write (OR-relaxed rows blended in) must not be served+ // to a fallback-off lookup — the zero-strict-recall result sets are+ // disjoint (relaxed rows vs empty keyword arm). `?? true` mirrors the+ // module's defensive read of other knobs for partial-knobs callers.+ `kof=${(knobs.keywordOrFallback ?? true) ? 1 : 0}`,+ // v=26 additions (#4415, wave-g, append-only): effective salience/+ // recency boost modes + applied intent-pattern config fingerprint. A+ // salience/recency-boosted (reordered) write must never serve a lookup+ // under different modes, and a `search.intent_patterns` edit changes+ // classification → results, so it must change the key. 'off'/'none'+ // fallbacks keep legacy callers stable.+ `sal=${ctx?.salience ?? 'off'}`,+ `rec=${ctx?.recency ?? 'off'}`,+ `ipat=${ctx?.intentPatterns ?? 'none'}`,];const h = createHash('sha256');h.update(parts.join('|'));@@ -1121,6 +1211,10 @@ export function loadOverridesFromConfig(if (iw !== undefined) {out.intentWeighting = iw === '1' || iw.toLowerCase() === 'true';}+ const kof = get('search.keywordOrFallback');+ if (kof !== undefined) {+ out.keywordOrFallback = kof === '1' || kof.toLowerCase() === 'true';+ }const tb = get('search.tokenBudget');if (tb !== undefined) {const n = parseInt(tb, 10);@@ -1293,6 +1387,7 @@ export const SEARCH_MODE_CONFIG_KEYS: ReadonlyArray<string> = Object.freeze(['search.cache.similarity_threshold','search.cache.ttl_seconds','search.intentWeighting',+ 'search.keywordOrFallback','search.tokenBudget','search.expansion','search.searchLimit',diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex ff3488800a..c53db1cde2 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -21,6 +21,7 @@ export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {cache_similarity_threshold: 'Cosine-similarity floor for cache hits (0..1)',cache_ttl_seconds: 'Per-row cache TTL',intentWeighting: 'Zero-LLM intent classifier weight adjustments',+ keywordOrFallback: 'Keyword-arm AND→OR zero-recall fallback',tokenBudget: 'Per-call token-budget cap (undefined = no cap)',expansion: 'LLM multi-query expansion (Haiku call per search)',searchLimit: 'Default `limit` for the operation layer',@@ -77,6 +78,7 @@ export async function buildModesReport(engine: BrainEngine): Promise<SearchModes'cache_similarity_threshold','cache_ttl_seconds','intentWeighting',+ 'keywordOrFallback','tokenBudget','expansion','searchLimit',diff --git a/src/core/search/query-intent.ts b/src/core/search/query-intent.tsindex 4acb2d5469..a5e6a6c68c 100644--- a/src/core/search/query-intent.ts+++ b/src/core/search/query-intent.ts@@ -21,9 +21,29 @@* "who is X right now" → suggestedRecency='on' even though "who is" is a* canonical pattern.*- * Pure module. No DB, no LLM, no async. Tested in test/query-intent.test.ts.+ * Pure module. No DB, no LLM, no async — with ONE seam: the shipped banks+ * are English-only regex, so a brain queried in another language never fired+ * the recency/salience stages at all (#4415). `applyIntentPatternConfig`+ * merges per-brain pattern extensions (the `search.intent_patterns` config+ * key, same operator-extension shape as `emotional_weight.high_tags`) over+ * the shipped banks; `classifyQueryWithBrainPatterns` is the async+ * config-loading wrapper hybridSearch calls. classifyQuery itself stays+ * sync + deterministic for a given applied config.+ *+ * wave-g: the config-backed extensions are cached PER ENGINE (WeakMap ++ * short TTL — no config-write invalidation seam exists), so hybridSearch's+ * hot path pays one engine.getConfig round-trip per TTL window instead of+ * one per call, and a multi-engine process (migrate source+target, tests)+ * can't apply one brain's patterns to another brain's queries. The+ * process-global `applyIntentPatternConfig` seam remains for sync callers+ * and tests. `loadEngineIntentPatterns` also exposes a fingerprint of the+ * applied config for the query-cache knobs hash (a pattern-config change+ * changes classification → results, so it must key cache rows).+ * Tested in test/query-intent.test.ts + test/query-intent-config.test.ts.*/+import { createHash } from 'node:crypto';+export type QueryIntent = 'entity' | 'temporal' | 'event' | 'concept' | 'general';export type SalienceMode = 'off' | 'on' | 'strong';@@ -191,6 +211,38 @@ const SALIENCE_ON_PATTERNS = [// where text might have worked." False negatives cost nothing (the legacy// text path still runs). The LLM-intent escalation in Commit 4 catches// genuinely ambiguous phrasings.+//+// CJK note: the English patterns are unreachable for Chinese and Japanese+// queries, because JavaScript's `\b` is an ASCII word boundary.+// A Han or Kana character is not a `\w` character, so no boundary ever exists+// beside it — /\b照片\b/ cannot match the string "照片". CJK queries therefore+// always fell through to 'text' and never reached the embedding_image column,+// however many image chunks the brain holds.+//+// The CJK bank anchors on structure instead of word boundaries: the possessive+// 的 / の, a picture measure word (张/幅/组), or an action verb next to the+// visual noun. Conservatism matches the English bank on purpose — a bare+// visual noun ("截图", like a bare "screenshot") stays 'text', because 'image'+// modality is exclusive (D9 skips keyword search), so a false positive drops+// text results rather than merely adding an image search.+const CJK_VISUAL_NOUNS =+ '照片|相片|图片|圖片|图像|圖像|截图|截圖|截屏|画面|畫面|影像|图表|圖表|' ++ '写真|画像|イラスト|スクショ|スクリーンショット';++const CJK_VISUAL_VERBS =+ '找|搜|搜索|查找|翻出|给我|給我|看看|显示|顯示|展示';++const CROSS_MODAL_PATTERNS_CJK: RegExp[] = [+ // "蓝色羽绒服的照片" / "小花笑的图片" / "那张截图" / "猫の写真"+ new RegExp(`(的|の|[张張幅组組])\\s*(${CJK_VISUAL_NOUNS})`),+ // verb-initial (zh): "找一下蓝色羽绒服照片"+ new RegExp(`(${CJK_VISUAL_VERBS})[^\\n]{0,20}?(${CJK_VISUAL_NOUNS})`),+ // verb-final (ja): "写真を見せて" / "画像を探して"+ new RegExp(`(${CJK_VISUAL_NOUNS})\\s*(を|が|は)?\\s*(見せ|見たい|探し|見つけ)`),+ // "X 长什么样" — the CJK form of "what does X look like"+ /长(得)?(什么|甚么|啥)样|長(得)?(什麼|甚麼)樣/,+];+const CROSS_MODAL_PATTERNS: RegExp[] = [/\b(show|find|get|pull)\s+(me\s+)?(the\s+)?(photos?|images?|pictures?|pics?|screenshots?)\b/i,/\b(photos?|images?|pictures?|pics?|screenshots?)\s+(of|from|at|with|showing|featuring)\b/i,@@ -198,6 +250,7 @@ const CROSS_MODAL_PATTERNS: RegExp[] = [/\b(whiteboard|diagram|slide|screenshot|infographic|chart)s?\s+(of|from|about|showing)\b/i,/\bdiagram\s+(of|for|showing)\b/i,/\bvisual(s|ly)?\s+(of|from|about|showing|representation)\b/i,+ ...CROSS_MODAL_PATTERNS_CJK,];// v0.36 cross-modal wave (Commit 4 prep): visual nouns that combined with@@ -220,6 +273,207 @@ const AMBIGUOUS_REFERENCE_MARKERS: RegExp[] = [/\bfrom\s+(last|this|the)\s+(week|month|year|offsite|meeting|hackathon|deck)\b/i,];+// ─────────────────────────────────────────────────────────+// #4415 — per-brain pattern extensions (search.intent_patterns)+// ─────────────────────────────────────────────────────────++/**+ * Every shipped bank above is English-only `\b`-anchored regex, so a brain+ * queried in another language classified 'general' with recency AND salience+ * permanently 'off' — the ranking stages never executed at all. The+ * `search.intent_patterns` config key (same operator-extension shape as+ * `emotional_weight.high_tags`) merges per-brain patterns OVER the shipped+ * banks: a JSON object of bank-name → array of regex sources, e.g.+ *+ * {"recency_on": ["לאחרונה", "מה חדש"], "strong_recency": ["היום"]}+ *+ * Sources compile with the 'iu' flags ('i' fallback when 'u' rejects the+ * source). Extensions only ever ADD matches — the shipped banks stay in+ * force, and a bad config (unparseable JSON, unknown bank, invalid regex)+ * fail-opens to the shipped behavior per entry.+ */+export const INTENT_PATTERN_BANKS = [+ 'temporal', 'event', 'entity', 'full_context', 'canonical',+ 'strong_recency', 'recency_on', 'salience_on', 'explicit_temporal_bound',+] as const;+export type IntentPatternBank = (typeof INTENT_PATTERN_BANKS)[number];++/**+ * Typed builder for an empty per-bank pattern record. A plain+ * `Object.fromEntries(...) as Record<...>` is rejected by tsc 5.9 (TS2352:+ * fromEntries returns `{ [k: string]: never[] }`, which doesn't overlap the+ * literal-keyed Record). The loop below assigns EVERY member of+ * INTENT_PATTERN_BANKS, so the narrowing assertion on the empty literal is+ * safe by construction.+ */+function emptyBankSet(): Record<IntentPatternBank, RegExp[]> {+ const out = {} as Record<IntentPatternBank, RegExp[]>;+ for (const b of INTENT_PATTERN_BANKS) out[b] = [];+ return out;+}++const EXTENSIONS: Record<IntentPatternBank, RegExp[]> = emptyBankSet();++// Idempotence cache: recompile only when the raw config value changes+// (applyIntentPatternConfig runs per search on the hot path).+let appliedRaw: string | null | undefined;+let appliedErrors: string[] = [];++/**+ * Compile the raw `search.intent_patterns` config value INTO a bank set+ * (cleared first; null/undefined/'' leaves it empty). Returns per-entry+ * compile errors (empty = fully applied). Never throws. Shared by the+ * process-global seam and the per-engine cache.+ */+function compileIntentPatternConfig(+ raw: string | null | undefined,+ into: Record<IntentPatternBank, RegExp[]>,+): string[] {+ const errors: string[] = [];+ for (const bank of INTENT_PATTERN_BANKS) into[bank].length = 0;+ if (!raw) return errors;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (e) {+ errors.push(`search.intent_patterns is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);+ return errors;+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ errors.push('search.intent_patterns must be a JSON object of bank-name → array of regex sources');+ return errors;+ }+ for (const [bank, sources] of Object.entries(parsed as Record<string, unknown>)) {+ if (!(INTENT_PATTERN_BANKS as readonly string[]).includes(bank)) {+ errors.push(`unknown pattern bank '${bank}' (valid: ${INTENT_PATTERN_BANKS.join(', ')})`);+ continue;+ }+ if (!Array.isArray(sources)) {+ errors.push(`bank '${bank}' must be an array of regex sources`);+ continue;+ }+ for (const src of sources) {+ if (typeof src !== 'string' || src.length === 0) {+ errors.push(`bank '${bank}': entries must be non-empty strings`);+ continue;+ }+ try {+ into[bank as IntentPatternBank].push(new RegExp(src, 'iu'));+ } catch {+ try {+ into[bank as IntentPatternBank].push(new RegExp(src, 'i'));+ } catch (e) {+ errors.push(`bank '${bank}': invalid regex '${src}': ${e instanceof Error ? e.message : String(e)}`);+ }+ }+ }+ }+ return errors;+}++/**+ * Compile + install the `search.intent_patterns` config value (raw string+ * from engine.getConfig; null/undefined/'' clears the extensions). Returns+ * the per-entry compile errors (empty = fully applied). Never throws.+ * Process-wide DEFAULT state — sync classifyQuery callers that don't thread+ * a bank set read it. Engine-bound callers use loadEngineIntentPatterns.+ */+export function applyIntentPatternConfig(raw: string | null | undefined): string[] {+ if (raw === appliedRaw) return appliedErrors;+ appliedRaw = raw;+ appliedErrors = compileIntentPatternConfig(raw, EXTENSIONS);+ return appliedErrors;+}++/** Test seam: reset the process-wide extension state AND the per-engine cache. */+export function clearIntentPatternConfigForTests(): void {+ appliedRaw = undefined;+ appliedErrors = [];+ for (const bank of INTENT_PATTERN_BANKS) EXTENSIONS[bank].length = 0;+ engineIntentStates = new WeakMap();+}++/**+ * Short stable fingerprint of a raw `search.intent_patterns` config value —+ * folded into the query-cache knobs hash (mode.ts `ipat=`) because the+ * patterns change classification (intent weights + auto salience/recency/+ * detail) and therefore results. 'none' for unset/empty config so legacy+ * and pattern-less brains hash identically.+ */+export function intentPatternFingerprint(raw: string | null | undefined): string {+ if (!raw) return 'none';+ return createHash('sha256').update(raw).digest('hex').slice(0, 12);+}++/** Per-engine compiled pattern state (wave-g). */+export interface EngineIntentPatternState {+ banks: Record<IntentPatternBank, RegExp[]>;+ /** intentPatternFingerprint of the applied raw config. */+ fingerprint: string;+ /** Per-entry compile errors from the last (re)compile. */+ errors: string[];+ /** Raw config value the banks were compiled from. */+ raw: string | null | undefined;+ /** Last successful-or-attempted fetch time (ms epoch) — TTL anchor. */+ fetchedAt: number;+}++/**+ * How long a per-engine compiled pattern set is trusted before the next+ * classify re-reads `search.intent_patterns`. There is no config-write+ * invalidation seam (engines have no write hooks), so a short TTL bounds+ * both the hot-path getConfig rate AND the staleness window after a+ * `gbrain config set`.+ */+export const INTENT_PATTERN_TTL_MS = 30_000;++let engineIntentStates = new WeakMap<object, EngineIntentPatternState>();++/**+ * The engine's compiled `search.intent_patterns` state, cached per engine+ * object with a short TTL (see INTENT_PATTERN_TTL_MS). Fail-open: a+ * throwing getConfig keeps the last-compiled banks (shipped-only on first+ * failure) and still advances the TTL anchor so a down config plane isn't+ * hammered per query. Never throws.+ */+export async function loadEngineIntentPatterns(+ engine: { getConfig(key: string): Promise<string | null> },+): Promise<EngineIntentPatternState> {+ const now = Date.now();+ let state = engineIntentStates.get(engine);+ if (state && now - state.fetchedAt < INTENT_PATTERN_TTL_MS) return state;+ if (!state) {+ state = { banks: emptyBankSet(), fingerprint: 'none', errors: [], raw: undefined, fetchedAt: now };+ engineIntentStates.set(engine, state);+ }+ state.fetchedAt = now;+ try {+ const raw = await engine.getConfig('search.intent_patterns');+ if (raw !== state.raw) {+ state.raw = raw;+ state.errors = compileIntentPatternConfig(raw, state.banks);+ state.fingerprint = intentPatternFingerprint(raw);+ }+ } catch { /* fail-open: keep the last-compiled banks */ }+ return state;+}++/**+ * classifyQuery with the brain's `search.intent_patterns` merged over the+ * shipped banks — the wrapper hybridSearch calls (it has the engine; the+ * classifier stays sync). Per-engine banks (wave-g): a multi-engine process+ * never applies one brain's patterns to another brain's queries, and the+ * config read is TTL-cached off the hot path. Fail-open: an unreadable+ * config leaves the shipped banks in force.+ */+export async function classifyQueryWithBrainPatterns(+ engine: { getConfig(key: string): Promise<string | null> },+ query: string,+): Promise<QuerySuggestions> {+ const state = await loadEngineIntentPatterns(engine);+ return classifyQuery(query, state.banks);+}+// ─────────────────────────────────────────────────────────// Classifier// ─────────────────────────────────────────────────────────@@ -229,6 +483,17 @@ function matches(patterns: RegExp[], q: string): boolean {return false;}+/** Shipped bank OR the configured extension bank (#4415). Defaults to the+ * process-global extensions; engine-bound callers thread their own set. */+function matchesBank(+ bank: IntentPatternBank,+ shipped: RegExp[],+ q: string,+ ext: Record<IntentPatternBank, RegExp[]> = EXTENSIONS,+): boolean {+ return matches(shipped, q) || matches(ext[bank], q);+}+/*** Classify a query and return all three axis suggestions.*@@ -245,15 +510,18 @@ function matches(patterns: RegExp[], q: string): boolean {* recency='strong' but salience='off' (the user wants newest, not* emotionally-weighted).*/-export function classifyQuery(query: string): QuerySuggestions {- const intent = classifyQueryIntent(query);+export function classifyQuery(+ query: string,+ ext: Record<IntentPatternBank, RegExp[]> = EXTENSIONS,+): QuerySuggestions {+ const intent = classifyQueryIntent(query, ext);const suggestedDetail = intentToDetail(intent);- const hasCanonical = matches(CANONICAL_PATTERNS, query);- const hasTemporalBound = matches(EXPLICIT_TEMPORAL_BOUND_PATTERNS, query);- const hasStrongRecency = matches(STRONG_RECENCY_PATTERNS, query);- const hasRecencyOn = matches(RECENCY_ON_PATTERNS, query);- const hasSalienceOn = matches(SALIENCE_ON_PATTERNS, query);+ const hasCanonical = matchesBank('canonical', CANONICAL_PATTERNS, query, ext);+ const hasTemporalBound = matchesBank('explicit_temporal_bound', EXPLICIT_TEMPORAL_BOUND_PATTERNS, query, ext);+ const hasStrongRecency = matchesBank('strong_recency', STRONG_RECENCY_PATTERNS, query, ext);+ const hasRecencyOn = matchesBank('recency_on', RECENCY_ON_PATTERNS, query, ext);+ const hasSalienceOn = matchesBank('salience_on', SALIENCE_ON_PATTERNS, query, ext);// Recency axislet suggestedRecency: RecencyMode;@@ -318,17 +586,20 @@ export function isAmbiguousModalityQuery(query: string): boolean {// ─────────────────────────────────────────────────────────/** v0.29.0 intent type. Preserved verbatim for back-compat. */-export function classifyQueryIntent(query: string): QueryIntent {- if (matches(FULL_CONTEXT_PATTERNS, query)) return 'temporal';- if (matches(TEMPORAL_PATTERNS, query)) return 'temporal';- if (matches(EVENT_PATTERNS, query)) return 'event';+export function classifyQueryIntent(+ query: string,+ ext: Record<IntentPatternBank, RegExp[]> = EXTENSIONS,+): QueryIntent {+ if (matchesBank('full_context', FULL_CONTEXT_PATTERNS, query, ext)) return 'temporal';+ if (matchesBank('temporal', TEMPORAL_PATTERNS, query, ext)) return 'temporal';+ if (matchesBank('event', EVENT_PATTERNS, query, ext)) return 'event';// v0.46.15 (Cat 13): concept BEFORE entity — definitional paraphrases// ("What is the ownership economy?") previously classified entity and got// the keyword tilt, making hybrid LOSE to its own vector arm on// paraphrase queries. Full-context/temporal/event keep their queries;// only entity/general-bound queries can re-route here.if (isConceptShapedQuery(query)) return 'concept';- if (matches(ENTITY_PATTERNS, query)) return 'entity';+ if (matchesBank('entity', ENTITY_PATTERNS, query, ext)) return 'entity';return 'general';}diff --git a/src/core/skill-trigger-index.ts b/src/core/skill-trigger-index.tsindex 15d21d878d..6c99614bd1 100644--- a/src/core/skill-trigger-index.ts+++ b/src/core/skill-trigger-index.ts@@ -25,7 +25,7 @@* risk codex flagged in #1451 review was consistency, not throughput.*/-import { existsSync, readFileSync, readdirSync, type Dirent } from 'fs';+import { existsSync, readFileSync, readdirSync, statSync, type Dirent } from 'fs';import { join } from 'path';import { parseResolverEntries, type ResolverEntry } from './check-resolvable.ts';import { findAllResolverFiles } from './resolver-filenames.ts';@@ -84,8 +84,21 @@ function loadFrontmatterEntries(skillsDir: string): SkillTriggerEntry[] {}for (const dirent of dirents) {- if (!dirent.isDirectory()) continue;const name = dirent.name;+ // readdirSync's Dirent.isDirectory() reflects the dirent's own type+ // (DT_LNK for symlinks on macOS/Linux) and does NOT follow symlinks,+ // so skill dirs symlinked in from a shared skills store (e.g.+ // ~/.agents/skills/<name>) are silently skipped without this check.+ const isDir = dirent.isDirectory()+ || (dirent.isSymbolicLink() && (() => {+ try {+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `name` is a readdirSync(skillsDir) dirent name: a single separator-free component of the operator's own skills tree, never remote/user input (same pattern as the sibling SKILL.md join below)+ return statSync(join(skillsDir, name)).isDirectory();+ } catch {+ return false;+ }+ })());+ if (!isDir) continue;if (name.startsWith('_') || name.startsWith('.')) continue;if (FRONTMATTER_SKIP_DIRS.has(name)) continue;diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 5562a6a388..13c1c975e6 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -18,7 +18,7 @@ import { join, dirname, resolve } from 'path';import type { BrainEngine } from './engine.ts';import { isSourceFederated, parseSourceConfig } from './sources-load.ts';import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';-import { isTrustedDotfile, realpathOrResolve } from './path-confine.ts';+import { isTrustedDotfile, realpathOrResolve, realpathOrResolveAsync } from './path-confine.ts';// Re-export so scope-resolution call sites can import the sentinel from// either module (#1712).@@ -90,6 +90,59 @@ function readDotfileWalk(startDir: string): string | null {* (prevents silently writing to a nonexistent source and bloating* pages with a dead FK).*/+/**+ * Tier-4 shared core: "registered source whose local_path contains CWD",+ * longest-prefix-wins. Realpaths BOTH sides (not bare resolve) so a+ * symlinked CWD can't forge a prefix match against a registered local_path+ * it doesn't really live under (codex #9); `realpathOrResolveAsync` falls+ * back to lexical resolve() for a stale registration whose path no longer+ * exists.+ *+ * All N `local_path` realpaths (plus cwd's) resolve via `Promise.all`+ * (#4091-class fix): a synchronous `realpathSync` loop blocks the event+ * loop for the FULL duration of every call in sequence, so wrapping the+ * sync calls in `Promise.all` doesn't parallelize anything — a single slow+ * or interrupted filesystem path (network mount, macOS on-access security+ * scan, degraded disk) still serializes the whole tier behind itself times+ * the registered-source count. The async realpath here truly overlaps I/O+ * across sources, so the tier's cost is bounded by the SLOWEST single+ * source, not their sum.+ *+ * Shared by `resolveSourceId` and `resolveSourceWithTier` so the two+ * resolution-chain entry points can't drift on this tier (mirrors how+ * `pickSoleNonDefaultSource` is already shared for tier 5.5).+ */+async function resolveRegisteredPathMatch(+ engine: BrainEngine,+ cwd: string,+): Promise<{ id: string; path: string; pathLen: number } | null> {+ const registered = await listRegisteredLocalPathSources(engine);+ if (registered.length === 0) return null;+ const [cwdResolved, resolvedPaths] = await Promise.all([+ realpathOrResolveAsync(cwd),+ Promise.all(registered.map(r => realpathOrResolveAsync(r.local_path))),+ ]);+ // #3880: ACTIVE sources win the prefix match — an archived (deeper)+ // registration must not shadow an active parent source. When cwd lands+ // ONLY in archived trees, the caller's assertSourceExists still throws+ // (explicit unavailable target — never silent continuation). The paths+ // are already resolved above, so the tiering is a pure in-memory pass.+ for (const archivedTier of [false, true]) {+ let best: { id: string; path: string; pathLen: number } | null = null;+ for (let i = 0; i < registered.length; i++) {+ if ((registered[i].archived === true) !== archivedTier) continue;+ const p = resolvedPaths[i];+ if (cwdResolved === p || cwdResolved.startsWith(p + '/')) {+ if (!best || p.length > best.pathLen) {+ best = { id: registered[i].id, path: p, pathLen: p.length };+ }+ }+ }+ if (best) return best;+ }+ return null;+}+export async function resolveSourceId(engine: BrainEngine,explicit: string | null | undefined,@@ -128,32 +181,9 @@ export async function resolveSourceId(// 4. Registered source whose local_path contains CWD.// Uses longest-prefix match so nested-path configurations (e.g.// gstack at ~/gstack + plans at ~/gstack/plans) pick the deepest.- // #3880: ACTIVE sources win the prefix match — an archived (deeper)- // registration must not shadow an active parent source. When cwd lands- // ONLY in archived trees, the assertSourceExists below still throws- // (explicit unavailable target — never silent continuation).- const registered = await listRegisteredLocalPathSources(engine);- // realpath BOTH sides (not bare resolve) so a symlinked CWD can't forge a- // prefix match against a registered local_path it doesn't really live under- // (codex #9). realpathOrResolve falls back to lexical resolve() for a stale- // registration whose path no longer exists. Resolving both sides keeps a- // legitimately symlinked vault matching — only one-sided symlinks break.- const cwdResolved = realpathOrResolve(cwd);- let best: { id: string; pathLen: number } | null = null;- for (const tier of [- registered.filter((r) => r.archived !== true),- registered.filter((r) => r.archived === true),- ]) {- for (const r of tier) {- const p = realpathOrResolve(r.local_path);- if (cwdResolved === p || cwdResolved.startsWith(p + '/')) {- if (!best || p.length > best.pathLen) {- best = { id: r.id, pathLen: p.length };- }- }- }- if (best) break;- }+ // #3880 active-over-archived tiering + parallel realpath both live in+ // the shared resolveRegisteredPathMatch helper.+ const best = await resolveRegisteredPathMatch(engine, cwd);if (best) {// A local_path registration can outlive source archival. Treat landing in// that tree as an explicit unavailable target, never as permission to@@ -486,25 +516,9 @@ export async function resolveSourceWithTier(}// 4. Registered source whose local_path contains CWD.- // #3880: active-over-archived tiering — see resolveSourceId's block.- const registered = await listRegisteredLocalPathSources(engine);- // realpath both sides — see the matching block in resolveSourceId (codex #9).- const cwdResolved = realpathOrResolve(cwd);- let best: { id: string; path: string; pathLen: number } | null = null;- for (const tier of [- registered.filter((r) => r.archived !== true),- registered.filter((r) => r.archived === true),- ]) {- for (const r of tier) {- const p = realpathOrResolve(r.local_path);- if (cwdResolved === p || cwdResolved.startsWith(p + '/')) {- if (!best || p.length > best.pathLen) {- best = { id: r.id, path: p, pathLen: p.length };- }- }- }- if (best) break;- }+ // #3880 active-over-archived tiering + parallel realpath both live in+ // the shared resolveRegisteredPathMatch helper.+ const best = await resolveRegisteredPathMatch(engine, cwd);if (best) {await assertSourceExists(engine, best.id);return { source_id: best.id, tier: 'local_path', detail: best.path };diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.tsindex 6b16d71795..29424ac31a 100644--- a/src/core/sources-ops.ts+++ b/src/core/sources-ops.ts@@ -385,6 +385,25 @@ export async function addSource(// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- localPath only flows here from the trusted local CLI: the sources_add op hard-rejects `path` unless ctx.remote === false (remote callers get null), so this is the operator registering their own directory; absolutizing it is the #3696 fixopts = { ...opts, localPath: resolvePath(msysToNativePath(opts.localPath)) };}+ if (opts.cloneDir) {+ // #3696 residual: same phantom-path class as localPath above — a relative+ // `--clone-dir clones/x` was stored verbatim as local_path, so every+ // consumer running from a different cwd (launchd daemon at cwd=/,+ // autopilot dispatch, sync anchors) join-resolved a path that does not+ // exist and silently missed the clone.+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- cloneDir only flows here from the trusted local CLI (sources_add hard-rejects it unless ctx.remote === false); absolutizing the operator's own directory is the #3696 fix+ opts = { ...opts, cloneDir: resolvePath(msysToNativePath(opts.cloneDir)) };+ }+ if (opts.github) {+ // #3696 residual (sibling of the cloneDir case above): `--kind github+ // --dir clones/x` stores opts.github.dir verbatim as local_path (Path C+ // below never resolves it), so the same phantom-path class survives+ // through the github-kind registration path — a launchd daemon at+ // cwd=/, autopilot dispatch, or a sync anchor running from a different+ // cwd than the CLI join-resolves a path that does not exist.+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- opts.github.dir only flows here from the trusted local CLI (sources_add hard-rejects opts.github unless ctx.remote === false); absolutizing the operator's own directory is the #3696 fix+ opts = { ...opts, github: { ...opts.github, dir: resolvePath(msysToNativePath(opts.github.dir)) } };+ }// Q4: pre-flight collision check before any clone work.const existing = await engine.executeRaw<{ id: string; local_path: string | null }>(@@ -729,16 +748,28 @@ export async function resolveScopedSourceOrThrow(export async function listSources(engine: BrainEngine,- opts: { includeArchived?: boolean } = {},+ opts: { includeArchived?: boolean; allowedSourceIds?: readonly string[] } = {},): Promise<SourceListEntry[]> {// v0.28.1 codex finding (MEDIUM): the prior version ignored the// includeArchived flag and returned every row. That leaked archived// sources' ids, local_paths, and remote_urls to read-scoped MCP callers// who shouldn't see soft-deleted state. Filter at the SQL level so the// archived rows never reach the wire by default.- const archivedFilter = opts.includeArchived- ? ''- : 'WHERE archived IS NOT TRUE';+ //+ // #4433: `allowedSourceIds` row-filters to the caller's source grant —+ // a scoped remote MCP caller must not enumerate other sources' ids,+ // local_paths, or remote_urls. Row-filter (not field redaction) so+ // out-of-grant rows never reach the wire; undefined = unscoped (trusted+ // local CLI, or a remote caller with no source grant — matching the+ // fail-open posture of every other unscoped read).+ const conds: string[] = [];+ const params: unknown[] = [];+ if (!opts.includeArchived) conds.push('archived IS NOT TRUE');+ if (opts.allowedSourceIds !== undefined) {+ params.push([...opts.allowedSourceIds]);+ conds.push(`id = ANY($${params.length})`);+ }+ const where = conds.length > 0 ? `WHERE ${conds.join(' AND ')}` : '';const rows = await engine.executeRaw<{id: string;name: string;@@ -747,7 +778,8 @@ export async function listSources(config: unknown;}>(`SELECT id, name, local_path, last_sync_at, config- FROM sources ${archivedFilter} ORDER BY (id = 'default') DESC, id`,+ FROM sources ${where} ORDER BY (id = 'default') DESC, id`,+ params,);const out: SourceListEntry[] = [];for (const r of rows) {diff --git a/src/core/storage-config.ts b/src/core/storage-config.tsindex 164dfc8b24..c6003b7310 100644--- a/src/core/storage-config.ts+++ b/src/core/storage-config.ts@@ -372,9 +372,24 @@ export const DERIVE_PHASE_DB_ONLY_DEFAULTS: readonly string[] = ['dream-cycle-summaries/',];-/** Declared db_only dirs plus the derive-phase defaults, deduped. */+/**+ * Declared db_only dirs plus the derive-phase defaults, deduped.+ *+ * `declared` is lowercased before the union (issue #3766): its only consumer+ * (`checkUndeclaredDbOnlyPages`) matches these prefixes against page `slug`+ * values via a plain `.startsWith()`, and slugs are ALWAYS lowercased at+ * creation time (`pathToSlug`/`slugifyCodePath` in sync.ts) regardless of the+ * host filesystem's case sensitivity. Without this, a `storage.db_only`+ * entry typed with any uppercase (e.g. `Notes/` in gbrain.yml) silently never+ * matches a single slug and every page under it gets falsely flagged as+ * undeclared. This is deliberately NOT done in `normalizeAndValidateStorageConfig`+ * / `loadStorageConfig` — `manageGitignore` (sync.ts) reads that raw,+ * case-preserved config to write `.gitignore` entries that must match the+ * REAL on-disk directory name (case-sensitive on Linux); lowercasing there+ * would break gitignore management instead of fixing this doctor check.+ */export function effectiveDbOnlyDirs(declared: string[]): string[] {- return [...new Set([...declared, ...DERIVE_PHASE_DB_ONLY_DEFAULTS])];+ return [...new Set([...declared.map((d) => d.toLowerCase()), ...DERIVE_PHASE_DB_ONLY_DEFAULTS])];}/**diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 79a585227c..6f641b1c45 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -396,7 +396,7 @@ async function runLinksTimelinePass(for (const { slug, candidates } of pageCandidates) {for (const c of candidates) {const resolved = resolveCandidateSources(c, slug, sourceId, allSlugs, slugToSources);- if (!resolved) continue;+ if (!resolved.ok) continue;linkBatch.push({from_slug: resolved.fromSlug,to_slug: c.targetSlug,diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.tsindex 7092a5d9e2..46ced6f60e 100644--- a/src/core/sync-anchor.ts+++ b/src/core/sync-anchor.ts@@ -10,6 +10,7 @@ import type { SyncOpts } from '../commands/sync.ts';import { ownsGlobalSyncAnchor, sameRepoDir } from './sync.ts';import { isWithinRoot } from './sync-git.ts';import { serr } from './console-prefix.ts';+import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';// v0.18.0 Step 5: source-scoped sync state helpers. When opts.sourceId// is set, read/write the per-source row instead of the global config@@ -391,12 +392,30 @@ export async function writeSlugRootMode(): Promise<void> {if (sourceId) {// jsonb_set on a bound ::text — never JSON.stringify into ::jsonb.- await engine.executeRaw(- `UPDATE sources- SET config = jsonb_set(COALESCE(config, '{}'::jsonb), '{slug_root_mode}', to_jsonb($2::text))- WHERE id = $1`,- [sourceId, mode],- );+ //+ // #4521: a historical string-scalar (or array-shaped) sources.config made+ // the plain `jsonb_set(COALESCE(config, '{}'::jsonb), …)` throw+ // `cannot set path in scalar` and abort every subdir-scoped sync right+ // after sync.discover_git_root. Heal-on-write instead: coerce the column+ // through the canonical SOURCE_CONFIG_OBJECT_SQL recovery expression+ // (unwraps double-encoded object strings so their keys SURVIVE; anything+ // unrecoverable collapses to '{}') before setting the key.+ try {+ await engine.executeRaw(+ `UPDATE sources+ SET config = jsonb_set(${SOURCE_CONFIG_OBJECT_SQL}, '{slug_root_mode}', to_jsonb($2::text))+ WHERE id = $1`,+ [sourceId, mode],+ );+ } catch (e) {+ // Name the source — "cannot set path in scalar" alone gives the+ // operator nothing to act on.+ throw new Error(+ `failed to pin slug_root_mode on sources.config for source '${sourceId}': ` ++ `${e instanceof Error ? e.message : String(e)}`,+ e instanceof Error ? { cause: e } : undefined,+ );+ }return;}await engine.setConfig('sync.slug_root_mode', mode);diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.tsindex 330fe8dc5d..6822cd4369 100644--- a/src/core/sync-cost-gate.ts+++ b/src/core/sync-cost-gate.ts@@ -33,6 +33,10 @@ import {} from './embedding.ts';import { estimateCostFromChars } from './embedding-pricing.ts';import { SPEND_CAP_CONFIG_KEY } from './embed-backfill-submit.ts';+import {+ embedBackfillManualDrainCommand,+ type EmbedBackfillWorkerSurface,+} from './minions/embed-backfill-admission.ts';import { git, hasOriginRemote, isDetachedHead, unique } from './sync-git.ts';/**@@ -337,6 +341,7 @@ function labelEstimate(inline: InlineEstimate): string {}type CostGateSource = {+ sourceId?: string;local_path: string | null;config: Record<string, unknown>;last_commit: string | null;@@ -354,12 +359,24 @@ interface CostGateContext {includeGitignored?: boolean;/** Message prefix ('sync --all' | 'sync'). */label: string;+ /** Public queue capability resolved at the command boundary. */+ workerSurface: EmbedBackfillWorkerSurface;+ /** Submission policy; distinct from whether the runtime has a worker. */+ autoSubmitEnabled: boolean;}type CostGateOutcome =| { action: 'proceed'; autoDeferEmbeds: boolean }| { action: 'stop' };+type ManualDrainReason = 'no_worker_surface' | 'auto_submit_disabled';++function manualDrainCommands(sources: CostGateSource[]): string[] {+ return unique(+ sources.map((source) => embedBackfillManualDrainCommand(source.sourceId ?? 'default')),+ );+}+/*** v0.42.42.0 (#2139): the inline-embed cost gate, shared by BOTH `sync --all`* and single-source `sync` so the spend surface is consistent. Runs at the@@ -383,6 +400,10 @@ export async function runInlineCostGate(ctx: CostGateContext,): Promise<CostGateOutcome> {const { sources, mode, dryRun, jsonOut, yesFlag, full, label } = ctx;+ const manualDrainReason: ManualDrainReason | undefined =+ ctx.workerSurface.status === 'no_worker_surface'+ ? 'no_worker_surface'+ : ctx.autoSubmitEnabled ? undefined : 'auto_submit_disabled';// Stale backlog: cheap single SQL; fail-open to 0 so a transient DB hiccup// never blocks the sync. Signature-aware (model/dims swap surfaces here).@@ -421,6 +442,41 @@ export async function runInlineCostGate(`Current backlog ~${staleChars.toLocaleString()} chars (~$${staleCostUsd.toFixed(2)} on ` +`${embeddingModelName}) across ${sources.length} source(s); ` +`${queuedBackfills} backfill job(s) queued.`;+ if (manualDrainReason) {+ const commands = manualDrainCommands(sources);+ const refusal = manualDrainReason === 'no_worker_surface'+ ? 'no persistent worker surface is available'+ : 'automatic backfill submission is disabled by --no-auto-embed';+ const manualMsg =+ `${label}: embedding will not run inline and ${refusal}. ` ++ `Manual drain required: ${commands.map((command) => `\`${command}\``).join(', ')}.`;+ if (dryRun) {+ if (jsonOut) {+ console.log(JSON.stringify({+ status: 'dry_run', mode, gate: 'dry_run', delivery: 'manual',+ reason: manualDrainReason, workerSurface: ctx.workerSurface.status,+ staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd),+ floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName,+ manualCommands: commands,+ }));+ } else {+ console.log(manualMsg);+ console.log('--dry-run: exit without syncing.');+ }+ return { action: 'stop' };+ }+ if (jsonOut) {+ console.log(JSON.stringify({+ status: 'manual_drain_required', mode, gate: 'manual_drain_required',+ reason: manualDrainReason, workerSurface: ctx.workerSurface.status, staleChars, staleCostUsd,+ capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd),+ model: embeddingModelName, manualCommands: commands,+ }));+ } else {+ console.log(manualMsg);+ }+ return { action: 'proceed', autoDeferEmbeds: false };+ }if (dryRun) {if (jsonOut) {console.log(JSON.stringify({ status: 'dry_run', mode, gate: 'dry_run', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));@@ -505,8 +561,34 @@ export async function runInlineCostGate(}return { action: 'proceed', autoDeferEmbeds: false };}- // Non-TTY or --json: AUTO-DEFER embeds to capped backfill jobs. NEVER exit 2- // (the wedged-cron fix). Format splits on the explicit --json flag only.+ // Non-TTY or --json: defer without wedging. Use the background queue only+ // when it has a drainable worker surface; otherwise report the exact+ // manual command and never imply that a job was or will be queued.+ if (manualDrainReason) {+ const commands = manualDrainCommands(sources);+ if (jsonOut) {+ console.log(JSON.stringify({+ status: 'manual_drain_required', mode, gate: 'manual_drain_required',+ reason: manualDrainReason, workerSurface: ctx.workerSurface.status, newTokens: inline.tokens,+ estimateKind: inline.estimateKind, costUsd,+ floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName,+ manualCommands: commands, hint: SPEND_HINT,+ }));+ } else {+ const refusal = manualDrainReason === 'no_worker_surface'+ ? 'no persistent worker surface is available'+ : 'automatic backfill submission is disabled by --no-auto-embed';+ console.log(+ `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` ++ `session — importing now without embeddings because ${refusal}. Manual drain required: ` ++ `${commands.map((command) => `\`${command}\``).join(', ')}. ` ++ `Pass --yes to embed inline.\n${SPEND_HINT}`,+ );+ }+ return { action: 'proceed', autoDeferEmbeds: true };+ }++ // Worker-backed AUTO-DEFER. NEVER exit 2 (the wedged-cron fix).if (jsonOut) {console.log(JSON.stringify({ status: 'auto_deferred', mode, gate: 'auto_deferred_embeds', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));} else {diff --git a/src/core/sync-delta.ts b/src/core/sync-delta.tsindex 9ceb51835e..166eb81dde 100644--- a/src/core/sync-delta.ts+++ b/src/core/sync-delta.ts@@ -64,14 +64,16 @@ function unique<T>(items: T[]): T[] {}/**- * Working-tree manifest for a DETACHED HEAD (relocated from sync.ts:557 so the- * estimator can price detached sources identically to how the executor imports- * them). On a detached HEAD, sync syncs from the live working tree: tracked- * changes (`git diff --name-status -M HEAD`) PLUS untracked files (`ls-files- * --others --exclude-standard`). Attached HEADs never call this — their- * incremental path imports ONLY the commit diff (untracked/dirty files are not- * imported), which is why the estimator must not price dirty files on an- * attached repo (issue #2139 phantom-cost class).+ * Working-tree manifest: tracked changes (`git diff --name-status -M HEAD`)+ * PLUS untracked files (`ls-files --others --exclude-standard`). Built for+ * EVERY sync now, not just detached HEADs (the name predates that): detached+ * HEADs always import it; attached HEADs use it to count uncommitted drift+ * (`SyncResult.uncommitted` + stderr warning) and, under `--working-tree` /+ * `sync.include_working_tree`, to import uncommitted state through the same+ * merge path. The ESTIMATOR still prices working-tree files only for detached+ * sources — attached repos import only the commit diff by default, so pricing+ * dirty files there would re-introduce the #2139 phantom-cost class (the+ * --working-tree opt-in is deliberately not priced; see SyncOpts.workingTree).*/export function buildDetachedWorkingTreeManifest(repoPath: string,diff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.tsnew file mode 100644index 0000000000..97df4ae83e--- /dev/null+++ b/src/core/sync-embed-backfill.ts@@ -0,0 +1,203 @@+/**+ * Sync-facing embed-backfill delivery contract.+ *+ * Keeps queue capability, automatic submission results, human text, and the+ * single-source JSON envelope aligned without growing the sync command facade.+ */+import type { BrainEngine } from './engine.ts';+import { submitEmbedBackfill } from './embed-backfill-submit.ts';+import { resolveWorkerBackedSyncEmbedMode } from './embedding.ts';+import {+ embedBackfillManualDrainCommand,+ embedBackfillWorkerSurface,+ type EmbedBackfillWorkerSurface,+} from './minions/embed-backfill-admission.ts';+import { runInlineCostGate } from './sync-cost-gate.ts';++type SyncCostGateSource = {+ id: string;+ local_path: string | null;+ config: Record<string, unknown>;+ last_commit: string | null;+ chunker_version: string | null;+};++type SyncCostGateFlags = {+ dryRun: boolean;+ jsonOut: boolean;+ yesFlag: boolean;+ full: boolean;+ includeGitignored: boolean;+ noAutoEmbed: boolean;+};++export async function resolveSyncAllEmbedPlan(+ engine: BrainEngine,+ sources: SyncCostGateSource[],+ opts: SyncCostGateFlags & { v2Enabled: boolean; serialFlag: boolean; noEmbed: boolean },+): Promise<{+ stop: boolean;+ workerSurface: EmbedBackfillWorkerSurface;+ deferEligible: boolean;+ fanOutEligible: boolean;+ autoDeferEmbeds: boolean;+ effectiveNoEmbed: boolean;+ shouldBackfill: boolean;+}> {+ const workerSurface = embedBackfillWorkerSurface(engine);+ const deferEligible =+ opts.v2Enabled && !opts.serialFlag && workerSurface.status === 'worker_backed';+ const fanOutEligible = deferEligible && sources.length > 1;+ const buildPlan = (stop: boolean, autoDeferEmbeds: boolean) => ({+ stop,+ workerSurface,+ deferEligible,+ fanOutEligible,+ autoDeferEmbeds,+ effectiveNoEmbed: deferEligible || opts.noEmbed || autoDeferEmbeds,+ shouldBackfill: deferEligible || autoDeferEmbeds || (opts.v2Enabled && opts.noEmbed),+ });+ let autoDeferEmbeds = false;+ if (!opts.noEmbed) {+ const gate = await runInlineCostGate(engine, {+ sources: sources.map((source) => ({ ...source, sourceId: source.id })),+ mode: resolveWorkerBackedSyncEmbedMode({ deferEligible, noEmbed: opts.noEmbed }),+ dryRun: opts.dryRun,+ jsonOut: opts.jsonOut,+ yesFlag: opts.yesFlag,+ full: opts.full,+ includeGitignored: opts.includeGitignored,+ label: 'sync --all',+ workerSurface,+ autoSubmitEnabled: !opts.noAutoEmbed,+ });+ if (gate.action === 'stop') {+ return buildPlan(true, false);+ }+ autoDeferEmbeds = gate.autoDeferEmbeds;+ }+ return buildPlan(false, autoDeferEmbeds);+}++export async function resolveSingleSyncEmbedPlan(+ engine: BrainEngine,+ source: Omit<SyncCostGateSource, 'id'> & { sourceId: string },+ opts: SyncCostGateFlags,+): Promise<{+ stop: boolean;+ workerSurface: EmbedBackfillWorkerSurface;+ autoDeferEmbeds: boolean;+}> {+ const workerSurface = embedBackfillWorkerSurface(engine);+ const gate = await runInlineCostGate(engine, {+ sources: [source],+ mode: 'inline',+ dryRun: opts.dryRun,+ jsonOut: opts.jsonOut,+ yesFlag: opts.yesFlag,+ full: opts.full,+ includeGitignored: opts.includeGitignored,+ label: 'sync',+ workerSurface,+ autoSubmitEnabled: !opts.noAutoEmbed,+ });+ return gate.action === 'stop'+ ? { stop: true, workerSurface, autoDeferEmbeds: false }+ : { stop: false, workerSurface, autoDeferEmbeds: gate.autoDeferEmbeds };+}++export type SyncEmbedBackfillOutcome =+ | { status: 'queued'; job_id: number }+ | {+ status: 'manual_drain_required';+ command: string;+ reason: 'no_worker_surface' | 'auto_submit_disabled';+ }+ | { status: 'skipped'; reason: 'cooldown'; command: string }+ | { status: 'skipped'; reason: 'spend_capped'; command: string; spend_cap_usd: number };++export async function resolveSyncEmbedBackfill(+ engine: BrainEngine,+ sourceId: string,+ opts: {+ reason: string;+ autoSubmitDisabled: boolean;+ },+): Promise<SyncEmbedBackfillOutcome> {+ const command = embedBackfillManualDrainCommand(sourceId);+ if (embedBackfillWorkerSurface(engine).status === 'no_worker_surface') {+ return { status: 'manual_drain_required', command, reason: 'no_worker_surface' };+ }+ if (opts.autoSubmitDisabled) {+ return { status: 'manual_drain_required', command, reason: 'auto_submit_disabled' };+ }++ const submitted = await submitEmbedBackfill(engine, sourceId, { reason: opts.reason });+ switch (submitted.status) {+ case 'submitted':+ return { status: 'queued', job_id: submitted.jobId };+ case 'cooldown':+ return { status: 'skipped', reason: 'cooldown', command };+ case 'spend_capped':+ return {+ status: 'skipped',+ reason: 'spend_capped',+ command,+ spend_cap_usd: submitted.spendCapUsd,+ };+ case 'no_worker_surface':+ return { status: 'manual_drain_required', command, reason: 'no_worker_surface' };+ default:+ submitted satisfies never;+ throw new Error('unreachable embed-backfill submission result');+ }+}++export function formatSyncEmbedBackfillOutcome(+ outcome: SyncEmbedBackfillOutcome,+ sourceName?: string,+): string {+ const source = sourceName ? ` for ${sourceName}` : '';+ switch (outcome.status) {+ case 'queued':+ return `embed-backfill job ${outcome.job_id} queued${source}`;+ case 'manual_drain_required':+ return `embed-backfill not queued; manual drain required: \`${outcome.command}\`${source}`;+ case 'skipped': {+ const detail = outcome.reason === 'cooldown'+ ? 'cooldown'+ : `24h spend cap $${outcome.spend_cap_usd}`;+ return `embed-backfill skipped (${detail})${source}; manual drain: \`${outcome.command}\``;+ }+ default:+ outcome satisfies never;+ throw new Error('unreachable sync embed-backfill outcome');+ }+}++export function buildSingleSyncJsonEnvelope(+ sourceId: string,+ result: {+ status: string;+ reason?: string;+ added: number;+ modified: number;+ deleted: number;+ chunksCreated: number;+ embedded: number;+ },+ embedBackfill?: SyncEmbedBackfillOutcome,+): Record<string, unknown> {+ return {+ schema_version: 1,+ source_id: sourceId,+ sync_status: result.status,+ ...(result.reason ? { reason: result.reason } : {}),+ added: result.added,+ modified: result.modified,+ deleted: result.deleted,+ chunks_created: result.chunksCreated,+ embedded: result.embedded,+ ...(embedBackfill ? { embed_backfill: embedBackfill } : {}),+ };+}diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.tsindex 9cb9000471..f30c1de362 100644--- a/src/core/sync-failure-ledger.ts+++ b/src/core/sync-failure-ledger.ts@@ -215,6 +215,33 @@ export function formatCodeBreakdown(return summary.map(s => ` ${s.code}: ${s.count}`).join('\n');}+/**+ * #4543: name the failing FILES (not just code counts) so a blocked sync is+ * actionable without opening sync-failures.jsonl by hand. Sentinel rows+ * (`<head>`, `<rename:…>`) are excluded — they aren't files. Paths are+ * control-char scrubbed (terminal-escape safety, same policy as+ * sanitizePathForDisplay) and the list is capped so one pathological run+ * can't flood stderr. Callers pair this with the+ * `gbrain frontmatter validate <path>` hint for parse-class failures.+ */+export function formatFailedFileList(+ failures: Array<{ path: string; error: string; code?: string }>,+ limit = 10,+): string {+ const files = failures.filter(f => isSkippablePath(f.path));+ const shown = files.slice(0, Math.max(0, limit));+ const scrub = (p: string): string => {+ // eslint-disable-next-line no-control-regex+ const cleaned = p.replace(/[\x00-\x1f\x7f]/g, '�');+ return cleaned.length > 200 ? `${cleaned.slice(0, 197)}...` : cleaned;+ };+ const lines = shown.map(f => ` ${scrub(f.path)} (${f.code ?? classifyErrorCode(f.error)})`);+ if (files.length > shown.length) {+ lines.push(` … and ${files.length - shown.length} more (see sync-failures.jsonl)`);+ }+ return lines.join('\n');+}+/*** Where `sync-failures.jsonl` lives. Defaults to the gbrain home.*diff --git a/src/core/sync.ts b/src/core/sync.tsindex 98b0c554da..01714de585 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -669,6 +669,7 @@ export {classifyErrorCode,summarizeFailuresByCode,formatCodeBreakdown,+ formatFailedFileList,syncFailuresPath,loadSyncFailures,unacknowledgedSyncFailures,diff --git a/src/core/take-proposals.ts b/src/core/take-proposals.tsindex 79739d5f26..a3226ec72a 100644--- a/src/core/take-proposals.ts+++ b/src/core/take-proposals.ts@@ -112,6 +112,17 @@ async function loadProposal(}const row = rows[0];if (row.status !== 'pending') {+ // wave-g (#4480 follow-up): a crash between the accept CAS and the fence+ // write (or a failed rollback) strands the row as status='accepted' with+ // no promoted take — invisible in the pending list, so surface the+ // repairable shape exactly where a human retry lands.+ if (row.status === 'accepted' && row.promoted_row_num == null) {+ throw new TakeProposalError(+ 'not_pending',+ `Proposal #${id} is stranded: claimed 'accepted' but no take was promoted (crash between claim and fence write, or an accept finishing right now). ` ++ `If no accept is in flight, repair with: UPDATE take_proposals SET status='pending', acted_at=NULL, acted_by=NULL WHERE id=${id} AND status='accepted'; then re-run accept.`,+ );+ }throw new TakeProposalError('not_pending',`Proposal #${id} is already '${row.status}' (acted on) — only pending proposals can be accepted or rejected.`,@@ -131,10 +142,16 @@ export interface ProposalActionTarget {}/**- * Promote a pending proposal into the page's takes fence, then mark the row- * accepted. The fence write happens FIRST (addTakeToPage: lock → resolve page- * → write .md → DB mirror); the status flip is fenced on status='pending' so- * a concurrent accept can't double-stamp.+ * Promote a pending proposal into the page's takes fence.+ *+ * #4480 (TOCTOU): the row is CLAIMED FIRST via a CAS+ * (`status='pending' → 'accepted'` with the rowcount CHECKED), and only the+ * claim winner performs the fence write. The old order (fence write first,+ * status flip after, rowcount ignored) let two concurrent accepts both pass+ * the pending check and both append the take to the .md — the loser's no-op+ * UPDATE reported success anyway. If the fence write fails after a+ * successful claim, the claim is rolled back (best-effort compensation) so+ * a retry can act on the row.*/export async function acceptProposal(target: ProposalActionTarget,@@ -148,43 +165,82 @@ export async function acceptProposal('Accept requires a brain directory (takes are markdown-canonical). Pass --dir or configure sync.repo_path.',);}- const { rowNum } = await addTakeToPage(- {- engine,- slug: proposal.page_slug,- brainDir: target.brainDir,- // The row's OWN source, never the caller's — the scoped load above- // already proved they agree when a caller scope was provided.- sourceId: proposal.source_id,- },- {- claim: proposal.claim_text,- kind: coerceProposalKind(proposal.kind),- holder: proposal.holder,- weight: typeof proposal.weight === 'number' ? proposal.weight : Number(proposal.weight),- },+ // Claim-first CAS: exactly one caller wins the pending row.+ const claimed = await engine.executeRaw<{ id: number }>(+ `UPDATE take_proposals+ SET status = 'accepted', acted_at = now(), acted_by = $2+ WHERE id = $1 AND status = 'pending'+ RETURNING id`,+ [id, target.actedBy ?? 'cli'],);+ if (claimed.length === 0) {+ throw new TakeProposalError(+ 'not_pending',+ `Proposal #${id} was acted on concurrently — only one accept/reject can win a pending row.`,+ );+ }+ let rowNum: number;+ try {+ ({ rowNum } = await addTakeToPage(+ {+ engine,+ slug: proposal.page_slug,+ brainDir: target.brainDir,+ // The row's OWN source, never the caller's — the scoped load above+ // already proved they agree when a caller scope was provided.+ sourceId: proposal.source_id,+ },+ {+ claim: proposal.claim_text,+ kind: coerceProposalKind(proposal.kind),+ holder: proposal.holder,+ weight: typeof proposal.weight === 'number' ? proposal.weight : Number(proposal.weight),+ },+ ));+ } catch (e) {+ // Fence write failed — release the claim so the row stays actionable.+ // Best-effort: a failed rollback (or a crash before this catch) leaves+ // status='accepted' with no promoted_row_num — loadProposal detects that+ // stranded shape on the next accept/reject attempt and prints the exact+ // repair SQL (wave-g).+ try {+ await engine.executeRaw(+ `UPDATE take_proposals+ SET status = 'pending', acted_at = NULL, acted_by = NULL, promoted_row_num = NULL+ WHERE id = $1 AND status = 'accepted'`,+ [id],+ );+ } catch { /* compensation is best-effort */ }+ throw e;+ }await engine.executeRaw(- `UPDATE take_proposals- SET status = 'accepted', acted_at = now(), acted_by = $2, promoted_row_num = $3- WHERE id = $1 AND status = 'pending'`,- [id, target.actedBy ?? 'cli', rowNum],+ `UPDATE take_proposals SET promoted_row_num = $2 WHERE id = $1`,+ [id, rowNum],);return { proposal, rowNum };}-/** Mark a pending proposal rejected. No markdown write. */+/** Mark a pending proposal rejected. No markdown write. #4480: rowcount is+ * CHECKED — a reject that loses a race (row already accepted/rejected) now+ * reports the truth instead of claiming a rejection it never performed. */export async function rejectProposal(target: Pick<ProposalActionTarget, 'engine' | 'sourceId' | 'actedBy'>,id: number,): Promise<TakeProposalRow> {const { engine } = target;const proposal = await loadProposal(engine, id, target.sourceId);- await engine.executeRaw(+ const rejected = await engine.executeRaw<{ id: number }>(`UPDATE take_proposalsSET status = 'rejected', acted_at = now(), acted_by = $2- WHERE id = $1 AND status = 'pending'`,+ WHERE id = $1 AND status = 'pending'+ RETURNING id`,[id, target.actedBy ?? 'cli'],);+ if (rejected.length === 0) {+ throw new TakeProposalError(+ 'not_pending',+ `Proposal #${id} was acted on concurrently — only one accept/reject can win a pending row.`,+ );+ }return proposal;}diff --git a/src/core/takes-write.ts b/src/core/takes-write.tsindex 54b73e1fa7..0c6dc7ceaf 100644--- a/src/core/takes-write.ts+++ b/src/core/takes-write.ts@@ -145,7 +145,7 @@ export async function resolveTakesRepoDir(engine: BrainEngine): Promise<string |*/async function resolveTakesFilePath(engine: BrainEngine,- brainDir: string,+ brainDir: string | null,slug: string,sourceId?: string,): Promise<{ path: string; writeRoot: string }> {@@ -177,6 +177,17 @@ async function resolveTakesFilePath(const path = recordedPath ?? resolvePageFilePath(sourceLocalPath, slug, 'default');return { path, writeRoot: sourceLocalPath };}+ // #4473: a null brainDir (sync.repo_path unset) is only survivable when the+ // source carries its own local_path (handled above). A host-repo page has+ // nowhere to land — refuse with the standard mirror_unavailable shape so+ // batch callers (takes bootstrap) can skip-and-count instead of aborting.+ if (brainDir === null) {+ throw new TakesWriteError(+ 'mirror_unavailable',+ `No markdown repo for source '${src}' — sync.repo_path is unset and the source has no local_path.`,+ 'takes_mirror_unavailable',+ );+ }const pageRoot = src === 'default' ? brainDir : join(brainDir, '.sources', src);const knownPath =sanitizeRecordedSourcePath(recordedSourcePath) ??@@ -190,6 +201,22 @@ async function resolveTakesFilePath(/** Test seam: pins the #2955 msys local_path healing at THIS read site. */export const __takesWriteTesting = { resolveTakesFilePath };+/**+ * #4473 — public read-only probe of the takes write path. The takes-bootstrap+ * sweep (extract-takes-from-pages.ts) checks file existence BEFORE spending an+ * LLM call on a page it could never write (a skipped page is rescanned by+ * every future run, so classifying it first would re-burn budget each time).+ * Throws 'mirror_unavailable' when the page has no resolvable markdown home.+ */+export async function resolveTakesWritePath(+ engine: BrainEngine,+ brainDir: string | null,+ slug: string,+ sourceId?: string,+): Promise<{ path: string; writeRoot: string }> {+ return resolveTakesFilePath(engine, brainDir, slug, sourceId);+}+async function getPageId(engine: BrainEngine, slug: string, sourceId?: string): Promise<number> {const rows = sourceId? await engine.executeRaw<{ id: number }>(@@ -256,6 +283,21 @@ function assertSafeCellText(field: string, value: string | undefined): void {}}+/**+ * #4473 — non-throwing form of the fence-cell guards. The takes-bootstrap+ * sweep pre-filters LLM-authored claims with this so one hostile/garbled+ * claim drops alone instead of sinking the page's other claims (the writer+ * below still asserts — defense in depth).+ */+export function isSafeFenceCellText(value: string): boolean {+ try {+ assertSafeCellText('cell', value);+ return true;+ } catch {+ return false;+ }+}+/*** The param docs promise weight 0..1 and the DB clamps out-of-range values* (normalizeWeightForStorage) — writing the raw value to md would diverge the@@ -367,7 +409,10 @@ function toBatchInput(pageId: number, t: ParsedTake, supersededBy?: number | nul};}-async function withTakesLock<T>(target: TakesWriteTarget, fn: () => Promise<T>): Promise<T> {+async function withTakesLock<T>(+ target: Pick<TakesWriteTarget, 'slug' | 'lockTimeoutMs'>,+ fn: () => Promise<T>,+): Promise<T> {try {return await withPageLock(target.slug, fn, {...(target.lockTimeoutMs !== undefined ? { timeoutMs: target.lockTimeoutMs } : {}),@@ -451,6 +496,79 @@ export async function addTakeToPage(});}+/**+ * #4473 — md-first batch append for the takes-bootstrap lane+ * (extract-takes-from-pages.ts). MARKDOWN IS CANONICAL: the bootstrap+ * classifier used to call engine.addTakesBatch directly, minting DB-only rows+ * that the next md→DB reconcile / extract rebuild silently clobbered. This+ * routes the whole per-page batch through the same fence pipeline as+ * addTakeToPage (lock → page id → fence append → md write → DB mirror), with+ * two bootstrap-specific differences:+ *+ * - `brainDir` may be null (sync.repo_path unset): a page whose source+ * carries its own local_path still resolves; a host-repo page throws+ * 'mirror_unavailable' and the caller skips + counts it.+ * - The page FILE must already exist. Bootstrap sweeps a whole corpus, and+ * minting fence-only twin .md files for DB-born pages would recreate+ * divergence at scale (#3605's stray-twin lesson) — a missing file is a+ * per-page 'mirror_unavailable' skip, never a create.+ *+ * Row numbers derive from the fence (max existing + 1, appended in order),+ * so the historical (page_id, row_num=1) collision posture is gone.+ */+export async function appendTakesToPageMdFirst(+ target: Omit<TakesWriteTarget, 'brainDir'> & { brainDir: string | null },+ rows: ReadonlyArray<AddTakeInput>,+): Promise<{ rowNums: number[]; mirror: TakeMirror }> {+ for (const row of rows) {+ assertHolderAllowed(row.holder, target.allowList);+ assertSafeCellText('claim', row.claim);+ assertSafeCellText('kind', row.kind);+ assertSafeCellText('holder', row.holder);+ assertSafeCellText('source', row.source);+ assertValidWeight(row.weight);+ assertValidSinceDate(row.sinceDate);+ }+ return withTakesLock(target, async () => {+ const pageId = await getPageId(target.engine, target.slug, target.sourceId);+ const { path, writeRoot } = await resolveTakesFilePath(+ target.engine, target.brainDir, target.slug, target.sourceId,+ );+ // Unlike addTakeToPage, a missing file REFUSES (readPageBody's+ // mirror_unavailable) — see the contract note above.+ const body = readPageBody(path);+ // F1: a fence with parser-skipped rows must not be re-rendered.+ assertFenceRoundTrips(parseTakesFence(body));+ let nextBody = body;+ const rowNums: number[] = [];+ for (const row of rows) {+ const r = upsertTakeRow(nextBody, {+ claim: row.claim,+ kind: row.kind,+ holder: row.holder,+ weight: row.weight ?? 0.5,+ source: row.source,+ sinceDate: row.sinceDate,+ active: true,+ });+ nextBody = r.body;+ rowNums.push(r.rowNum);+ }+ writePageBody(path, nextBody, writeRoot);+ // Mirror md→DB with the reconcile primitive, exactly as the fence now+ // states the appended rows.+ const appended = new Set(rowNums);+ const after = parseTakesFence(nextBody).takes.filter(t => appended.has(t.rowNum));+ let mirrorWarning: string | undefined;+ try {+ await target.engine.addTakesBatch(after.map(t => toBatchInput(pageId, t)));+ } catch (err) {+ mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.+ }+ return { rowNums, mirror: { written: true, path, ...(mirrorWarning ? { mirror_warning: mirrorWarning } : {}) } };+ });+}+export interface UpdateTakeFields {weight?: number;source?: string;diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex f209bb7ecd..741cef0c44 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -392,12 +392,49 @@ function surrogateSafeWindowEnd(content: string, requested: number): number {return endsAtHigh && followedByLow ? end - 1 : end;}-function excerptWindow(content: string, requestedStart: number, excerptLen: number): string {+/** #4510 — an excerpt plus what was cut, so callers can mark truncation. */+export interface ExcerptResult {+ text: string;+ /** True when page content BEFORE the excerpt was cut away. */+ truncatedStart: boolean;+ /** True when page content AFTER the excerpt was cut away. */+ truncatedEnd: boolean;+}++/**+ * Maximum share of the window each edge may sacrifice to land on a line+ * boundary (#4510). Tables/checklists cut mid-cell read as complete rows to+ * the model; snapping to line boundaries fixes that. The cap keeps a single+ * very long line (dense prose, minified content) from eating the window —+ * past it, the raw character cut stands and the truncation MARKER carries+ * the honesty instead.+ */+const EXCERPT_LINE_SNAP_MAX_SHARE = 0.25;++function excerptWindow(content: string, requestedStart: number, excerptLen: number): ExcerptResult {const boundedStart = Math.max(0, Math.min(requestedStart, content.length));const requestedEnd = Math.min(content.length, boundedStart + Math.max(0, excerptLen));- const start = surrogateSafeWindowStart(content, boundedStart);- const end = Math.max(start, surrogateSafeWindowEnd(content, requestedEnd));- return ensureWellFormed(content.slice(start, end));+ let start = surrogateSafeWindowStart(content, boundedStart);+ let end = Math.max(start, surrogateSafeWindowEnd(content, requestedEnd));+ // #4510: never sever mid-line when a nearby line boundary exists. Drop the+ // partial FIRST line (advance start to the next newline) and the partial+ // LAST line (retreat end to the last newline) — each bounded by+ // EXCERPT_LINE_SNAP_MAX_SHARE of the window so long-line prose keeps its+ // character cut instead of losing a quarter of the excerpt.+ const snapBudget = Math.max(1, Math.floor(excerptLen * EXCERPT_LINE_SNAP_MAX_SHARE));+ if (start > 0 && content[start - 1] !== '\n') {+ const nl = content.indexOf('\n', start);+ if (nl !== -1 && nl < end && nl + 1 - start <= snapBudget) start = nl + 1;+ }+ if (end < content.length && content[end] !== '\n' && content[end - 1] !== '\n') {+ const nl = content.lastIndexOf('\n', end - 1);+ if (nl > start && end - nl <= snapBudget) end = nl;+ }+ return {+ text: ensureWellFormed(content.slice(start, end)),+ truncatedStart: start > 0,+ truncatedEnd: end < content.length,+ };}/** Select the fixed-budget window containing the strongest unique query-term coverage. */@@ -407,8 +444,26 @@ export function selectRelevantExcerpt(excerptLen: number,pageIdentity = '',): string {- if (excerptLen <= 0) return '';- if (content.length <= excerptLen) return ensureWellFormed(content);+ return selectRelevantExcerptDetailed(content, query, excerptLen, pageIdentity).text;+}++/**+ * #4510 — like selectRelevantExcerpt but reports whether either edge cut page+ * content, so renderers can mark truncation explicitly instead of letting a+ * severed table read as a complete one.+ */+export function selectRelevantExcerptDetailed(+ content: string,+ query: string,+ excerptLen: number,+ pageIdentity = '',+): ExcerptResult {+ if (excerptLen <= 0) {+ return { text: '', truncatedStart: content.length > 0, truncatedEnd: content.length > 0 };+ }+ if (content.length <= excerptLen) {+ return { text: ensureWellFormed(content), truncatedStart: false, truncatedEnd: false };+ }const uniqueTerms = Array.from(new Set(excerptTokens(query)@@ -504,10 +559,37 @@ export function selectRelevantExcerpt(return excerptWindow(content, bestStart, excerptLen);}+/**+ * #4510 — pages-block char budget. The per-page excerpt length is+ * budget-aware: `min(ceiling, totalBudget / pageCount)` with the caller's+ * `floor` as the guaranteed minimum, so a big gather never collapses each+ * page below the floor, and a small gather delivers each page in a much+ * larger (often complete) window instead of wasting the budget.+ */+const PAGES_BLOCK_TOTAL_BUDGET_CHARS = 12_000;+const PAGES_BLOCK_EXCERPT_CEILING_CHARS = 2_400;++/** Budget-aware per-page excerpt length for the pages block (#4510). */+export function pagesBlockExcerptLen(pageCount: number, floor = 600): number {+ if (pageCount <= 0) return floor;+ return Math.max(floor, Math.min(+ PAGES_BLOCK_EXCERPT_CEILING_CHARS,+ Math.floor(PAGES_BLOCK_TOTAL_BUDGET_CHARS / pageCount),+ ));+}++/** Truncation markers (#4510): the model must be able to tell "the table ends+ * here" from "the text was cut here" — an unmarked severed table reads as a+ * complete one. Exported for tests and downstream renderers. */+export const EXCERPT_CUT_START_MARKER = '[… earlier page content omitted …]';+export const EXCERPT_CUT_END_MARKER = '[… page continues beyond this excerpt — read the full page for the rest …]';+/*** Render gather results into the per-block strings the prompt builder uses.* Pages are rendered as `<page slug="..." score="...">excerpt</page>`;* takes are rendered via the renderTakesBlock helper from sanitize.ts.+ * `excerptLen` is exact per page — callers wanting budget-aware sizing pass+ * `pagesBlockExcerptLen(pages.length)` (the think pipeline does).*/export function renderPagesBlock(pages: SearchResult[],@@ -526,13 +608,17 @@ export function renderPagesBlock(const title = String(page.title ?? '');const slugIdentity = slug.split('/').pop()?.replace(/[-_]/g, ' ') ?? '';const content = String(page.chunk_text ?? page.compiled_truth ?? page.snippet ?? '');- const excerpt = selectRelevantExcerpt(+ const excerpt = selectRelevantExcerptDetailed(content,query,excerptLen,`${title} ${slugIdentity}`,);- return `<page slug="${slug}" rank="${idx + 1}">\n${excerpt}\n</page>`;+ const body =+ (excerpt.truncatedStart ? `${EXCERPT_CUT_START_MARKER}\n` : '') ++ excerpt.text ++ (excerpt.truncatedEnd ? `\n${EXCERPT_CUT_END_MARKER}` : '');+ return `<page slug="${slug}" rank="${idx + 1}">\n${body}\n</page>`;}).join('\n\n');}diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 6177d56641..b5a1970af2 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -20,7 +20,7 @@import type Anthropic from '@anthropic-ai/sdk';import type { BrainEngine, SynthesisEvidenceInput } from '../engine.ts';import type { SearchResult } from '../types.ts';-import { runGather, renderPagesBlock, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';+import { runGather, renderPagesBlock, pagesBlockExcerptLen, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';import { renderTakesBlock } from './sanitize.ts';import { buildThinkSystemPrompt, buildThinkUserMessage } from './prompt.ts';import { resolveCitations, type ParsedCitation } from './cite-render.ts';@@ -258,9 +258,14 @@ function inferIntent(question: string, anchor?: string): string {return 'general';}+/** Strip a wrapping code fence, if present (shared by parse + salvage). */+function stripEnvelopeFences(text: string): string {+ return text.trim().replace(/^```(?:json)?\s*\n?/, '').replace(/```\s*$/, '');+}+function tryParseJSON(text: string): unknown {// The model may wrap JSON in code fences. Strip if present.- const stripped = text.trim().replace(/^```(?:json)?\s*\n?/, '').replace(/```\s*$/, '');+ const stripped = stripEnvelopeFences(text);try {return JSON.parse(stripped);} catch {@@ -273,6 +278,104 @@ function tryParseJSON(text: string): unknown {}}+/** #4509 — is this model output SHAPED like a JSON envelope (as opposed to+ * refusal prose / the graceful sentinel, whose raw text is meaningful)? */+export function looksLikeJsonEnvelope(text: string): boolean {+ return stripEnvelopeFences(text).startsWith('{');+}++/**+ * #4509 — best-effort field salvage from a MALFORMED ThinkResponse envelope+ * (the common cause is max-token truncation cutting the JSON mid-string).+ * Pre-fix, the raw envelope text shipped as the user-facing `answer` with+ * `citations: []`. Tolerant by construction: the answer string is recovered+ * up to the cut (dangling escapes trimmed), citations/gaps only when their+ * arrays survived whole. Returns null when no non-empty answer is present —+ * the caller then suppresses the raw JSON entirely.+ */+export function salvageThinkEnvelope(+ text: string,+): Pick<ThinkResponse, 'answer' | 'citations' | 'gaps'> | null {+ const stripped = stripEnvelopeFences(text);+ if (!stripped.startsWith('{')) return null;+ const answer = salvageStringField(stripped, 'answer');+ if (answer === null || answer.trim().length === 0) return null;+ const citations = (salvageArrayField(stripped, 'citations') ?? []).filter(+ (c): c is ThinkResponse['citations'][number] =>+ typeof c === 'object' && c !== null && typeof (c as { page_slug?: unknown }).page_slug === 'string',+ );+ const gaps = (salvageArrayField(stripped, 'gaps') ?? []).filter(+ (g): g is string => typeof g === 'string',+ );+ return { answer, citations, gaps };+}++/** Recover `"key": "…"` even when the closing quote never arrives (truncation). */+function salvageStringField(src: string, key: string): string | null {+ const keyIdx = src.indexOf(`"${key}"`);+ if (keyIdx === -1) return null;+ let i = keyIdx + key.length + 2;+ while (i < src.length && /\s/.test(src[i]!)) i++;+ if (src[i] !== ':') return null;+ i++;+ while (i < src.length && /\s/.test(src[i]!)) i++;+ if (src[i] !== '"') return null;+ i++;+ let raw = '';+ for (; i < src.length; i++) {+ const c = src[i]!;+ if (c === '\\') {+ raw += c + (src[i + 1] ?? '');+ i++;+ continue;+ }+ if (c === '"') break; // properly terminated+ raw += c;+ }+ // Truncation can leave a dangling escape — trim a lone trailing backslash+ // and an incomplete \uXXXX so the re-parse below can't fail on them.+ if (/(?:^|[^\\])(?:\\\\)*\\$/.test(raw)) raw = raw.slice(0, -1);+ raw = raw.replace(/\\u[0-9a-fA-F]{0,3}$/, '');+ try {+ return JSON.parse(`"${raw}"`) as string;+ } catch {+ // Last resort: the escaped text beats the whole raw envelope.+ return raw;+ }+}++/** Parse `"key": [...]` when the array survived whole; null when cut mid-array. */+function salvageArrayField(src: string, key: string): unknown[] | null {+ const keyIdx = src.indexOf(`"${key}"`);+ if (keyIdx === -1) return null;+ const open = src.indexOf('[', keyIdx);+ if (open === -1) return null;+ let depth = 0;+ let inStr = false;+ for (let i = open; i < src.length; i++) {+ const c = src[i]!;+ if (inStr) {+ if (c === '\\') { i++; continue; }+ if (c === '"') inStr = false;+ continue;+ }+ if (c === '"') { inStr = true; continue; }+ if (c === '[') depth++;+ else if (c === ']') {+ depth--;+ if (depth === 0) {+ try {+ const v = JSON.parse(src.slice(open, i + 1));+ return Array.isArray(v) ? v : null;+ } catch {+ return null;+ }+ }+ }+ }+ return null; // truncated mid-array+}+// ─── Extractive fallback [WP2/E2] ────────────────────────────────────────────// When synthesis fails but gather succeeded, a digest of the top gathered// pages (title + best excerpt, page-level citations) beats an empty failure.@@ -431,8 +534,11 @@ export async function runThink(warnings.push(`WINDOW_EXCLUDED_${gather.diagnostics.window.dropped}_PAGES`);}- // Render evidence blocks for the prompt- const pagesBlock = renderPagesBlock(gather.pages, 600, opts.question);+ // Render evidence blocks for the prompt. #4510: the per-page excerpt is+ // budget-aware — 600 chars is the FLOOR (a big gather never collapses each+ // page below it) and a small gather spreads the block budget into much+ // larger, often complete, per-page windows.+ const pagesBlock = renderPagesBlock(gather.pages, pagesBlockExcerptLen(gather.pages.length), opts.question);const takesForPrompt = gather.takes.map(takesHitToTakeForPrompt);const { rendered: takesBlock, sanitizedCount } = renderTakesBlock(takesForPrompt);if (sanitizedCount > 0) {@@ -712,9 +818,24 @@ export async function runThink(warnings.push('LLM_OUTPUT_NOT_JSON');synthesisOk = false; // #1698: malformed output (and the non-JSON graceful sentinel)// Refusals + the graceful sentinel land here too — coarse on purpose- // (no dedicated status; the raw text stays in `answer` for consumers).+ // (no dedicated status; for PROSE the raw text stays in `answer`).synthesisStatus = 'not_json';- response = { answer: text, citations: [], gaps: [] };+ // #4509: a malformed JSON envelope (max-token truncation is the+ // common cause) previously shipped VERBATIM as the user-facing+ // answer. Salvage the answer/citations/gaps fields tolerantly; when+ // the text is JSON-shaped but unsalvageable, emit no answer at all+ // (the extractive fallback below carries the content) — never raw+ // JSON to the user.+ const salvaged = salvageThinkEnvelope(text);+ if (salvaged) {+ warnings.push('SALVAGED_ANSWER_FROM_MALFORMED_JSON');+ response = salvaged;+ } else if (looksLikeJsonEnvelope(text)) {+ warnings.push('MALFORMED_JSON_ANSWER_SUPPRESSED');+ response = { answer: '', citations: [], gaps: [] };+ } else {+ response = { answer: text, citations: [], gaps: [] };+ }} else {const r = parsed as Partial<ThinkResponse>;response = {diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.tsindex 834d9b86cf..b5b88fdbb7 100644--- a/src/core/transcripts/claude-code-jsonl.ts+++ b/src/core/transcripts/claude-code-jsonl.ts@@ -27,6 +27,7 @@import { closeSync, lstatSync, openSync, readFileSync, readSync, statSync } from 'node:fs';import { isPathContained } from '../path-confine.ts';+import { detectWslMountRoot, translateWindowsPath } from '../wsl-paths.ts';import { claudeProjectsDir, type HostSpecTarget } from '../bootstrap/host-specs.ts';import type { WindowTurn } from '../context/entity-salience.ts';@@ -72,17 +73,39 @@ export type ConfineTranscriptResult =* intermediate symlinked directories, so a planted dir-symlink that escapes* the tree also fails). Fail-closed on every error.*- * `opts.root` is a TEST SEAM — production callers use the default.+ * Cross-OS install (#4522, Claude Code on the Windows host + gbrain in WSL):+ * the hook stdin's transcript_path arrives as a Windows drive literal+ * (`C:\Users\…\.claude\projects\…\session.jsonl`). Under WSL that literal is+ * translated to the automount view (`/mnt/c/…`) BEFORE the lstat; on any+ * non-WSL host `detectWslMountRoot()` is null and the path is used verbatim+ * (native Windows lstats drive paths fine; macOS/plain Linux keep failing+ * `unreadable` as before). The containment root translates the same way (a+ * CLAUDE_CONFIG_DIR carrying a Windows literal, the #4324 interaction).+ * When no explicit root is in play, the ONLY accepted fallback root is the+ * session's known config tree on the mounted drive: the Windows+ * user-profile pattern `<mount>/<drive>/Users/<profile>/.claude/projects`+ * (wave-g tightening — the earlier first-`.claude/projects`-marker+ * derivation let an attacker-controlled hook stdin pass under ANY such dir,+ * e.g. `C:\evil\.claude\projects\x.jsonl`). Still transcripts-dir+ * confinement [S3#8], just rooted Windows-side, since the WSL-side+ * `$HOME/.claude/projects` can never contain a Windows-home transcript;+ * anything outside CLAUDE_CONFIG_DIR / that profile tree is rejected.+ *+ * `opts.root` and `opts.wslMountRoot` are TEST SEAMS — production callers use+ * the defaults (`wslMountRoot: null` means "not under WSL").*/export function confineTranscriptPath(p: unknown,- opts: { root?: string; maxBytes?: number } = {},+ opts: { root?: string; maxBytes?: number; wslMountRoot?: string | null } = {},): ConfineTranscriptResult {if (typeof p !== 'string' || p.length === 0) return { ok: false, reason: 'missing_path' };if (!p.endsWith('.jsonl')) return { ok: false, reason: 'not_jsonl' };+ const mountRoot = opts.wslMountRoot !== undefined ? opts.wslMountRoot : detectWslMountRoot();+ const translated = mountRoot !== null ? translateWindowsPath(p, mountRoot) : null;+ const candidate = translated ?? p;let st: ReturnType<typeof lstatSync>;try {- st = lstatSync(p);+ st = lstatSync(candidate);} catch {return { ok: false, reason: 'unreadable' };}@@ -90,9 +113,49 @@ export function confineTranscriptPath(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 ?? claudeProjectsDir();- if (!isPathContained(p, root)) return { ok: false, reason: 'outside_projects_dir' };- return { ok: true, path: p, size: st.size };+ const rootRaw = opts.root ?? claudeProjectsDir();+ const root = (mountRoot !== null ? translateWindowsPath(rootRaw, mountRoot) : null) ?? rootRaw;+ if (!isPathContained(candidate, root)) {+ // Cross-OS fallback (#4522): only for a path we translated ourselves and+ // only when the caller didn't pin an explicit root.+ const derived =+ mountRoot !== null && translated !== null && opts.root === undefined+ ? deriveTranslatedProjectsRoot(translated, mountRoot)+ : null;+ if (derived === null || !isPathContained(candidate, derived)) {+ return { ok: false, reason: 'outside_projects_dir' };+ }+ }+ return { ok: true, path: candidate, size: st.size };+}++/**+ * The Windows user-profile `.claude/projects` root of a TRANSLATED Windows+ * transcript path (posix separators by construction), or null when the path+ * doesn't sit inside one. wave-g tightening: the root is pinned to the+ * session's known config-tree shape —+ * `<mountRoot>/<drive>/Users/<profile>/.claude/projects` — never derived+ * from the path's own first `.claude/projects` marker, which accepted an+ * attacker-controlled tree anywhere on a mounted drive+ * (`C:\evil\.claude\projects\x.jsonl`). The `Users` segment is+ * case-insensitive (Windows filesystems are); the profile segment must be a+ * real component (`.`/`..` refused so `C:\Users\..\.claude\projects` can't+ * widen the root); `.claude/projects` stays exact. `isPathContained` then+ * realpaths both sides, so `..` traversal and planted symlinks past the+ * prefix still fail.+ */+function deriveTranslatedProjectsRoot(translated: string, mountRoot: string): string | null {+ const base = mountRoot.replace(/\/+$/, '');+ if (!translated.startsWith(base + '/')) return null;+ const segments = translated.slice(base.length + 1).split('/');+ // [drive, 'Users', profile, '.claude', 'projects', ...at least one more]+ if (segments.length < 6) return null;+ const [drive, users, profile, dotClaude, projects] = segments;+ if (!/^[a-z]$/i.test(drive)) return null;+ if (users.toLowerCase() !== 'users') return null;+ if (!profile || profile === '.' || profile === '..') return null;+ if (dotClaude !== '.claude' || projects !== 'projects') return null;+ return [base, drive, users, profile, dotClaude, projects].join('/');}// ── Parsing [G3, A6] ────────────────────────────────────────────────────────diff --git a/src/core/transcripts/discover.ts b/src/core/transcripts/discover.tsindex 4372a94ea2..a3e6fe5b36 100644--- a/src/core/transcripts/discover.ts+++ b/src/core/transcripts/discover.ts@@ -21,6 +21,7 @@ import type { BrainEngine } from '../engine.ts';import type { TranscriptFormat } from './types.ts';import { harnessRoots, type HarnessRoot } from './detect.ts';import { isOpenclawCheckpointFile } from './openclaw.ts';+import { isClaudeCliSelfTranscriptPath } from '../ai/providers/claude-cli-scratch.ts';export interface DiscoveredFile {format: TranscriptFormat;@@ -28,6 +29,20 @@ export interface DiscoveredFile {bytes: number;}+export interface DiscoverOpts {+ /**+ * #4472 — include gbrain's OWN claude-cli subprocess sessions. The+ * claude-cli provider spawns `claude --print` from a per-PID tmpdir cwd+ * (gbrain-claude-cli-cwd-<pid>), and Claude Code records each of those+ * calls as a session under ~/.claude/projects/<slugified-cwd>/. Importing+ * them is a self-ingestion feedback loop (gbrain's prompt scaffolding ++ * page content re-entering the brain as "conversations"), so discovery+ * skips them by default. `gbrain transcripts ingest --include-self` is the+ * escape hatch for deliberately auditing the provider's own calls.+ */+ includeSelf?: boolean;+}+/** Recursively list regular files under root (lstat: symlinks are skipped). */function walk(dir: string, out: string[], depth = 0): void {if (depth > 6) return; // harness layouts are shallow; don't wander@@ -51,7 +66,7 @@ function walk(dir: string, out: string[], depth = 0): void {}}-export function discoverTranscriptFiles(roots?: HarnessRoot[]): DiscoveredFile[] {+export function discoverTranscriptFiles(roots?: HarnessRoot[], opts: DiscoverOpts = {}): DiscoveredFile[] {const out: DiscoveredFile[] = [];for (const { format, root, extension } of harnessRoots(roots)) {if (format === 'hermes') {@@ -69,6 +84,10 @@ export function discoverTranscriptFiles(roots?: HarnessRoot[]): DiscoveredFile[]for (const p of files) {if (!p.endsWith(extension)) continue;if (isOpenclawCheckpointFile(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.+ if (!opts.includeSelf && isClaudeCliSelfTranscriptPath(p)) continue;let bytes = 0;try {bytes = lstatSync(p).size;diff --git a/src/core/wsl-paths.ts b/src/core/wsl-paths.tsnew file mode 100644index 0000000000..7812ea03fb--- /dev/null+++ b/src/core/wsl-paths.ts@@ -0,0 +1,72 @@+/**+ * WSL Windows-drive path translation (shared by doctor asset checks and the+ * hook transcript confinement, #1835 / #4522).+ *+ * A Windows-side writer (a Windows gbrain install, or Claude Code running on+ * the Windows host invoking hooks via `wsl.exe`) hands the Linux side Windows+ * drive literals (`C:\Users\x\file`, `D:/foo/img.jpg`). Inside WSL those are+ * reachable through the automount tree (`/mnt/c/Users/x/file` by default; the+ * root is configurable via /etc/wsl.conf `[automount] root`). This module owns+ * the drive-shape detection, the wsl.conf parse, and the mechanical+ * translation; callers decide policy (skip vs stat vs confine).+ */+import { readFileSync } from 'node:fs';++/** `C:\x`, `C:/x` — a Windows drive-letter absolute path. */+export const WINDOWS_DRIVE_PATH_RE = /^([A-Za-z]):[\\/](.*)$/;++/**+ * Translate a Windows drive literal to its WSL automount form+ * (`C:\Users\x` → `<mountRoot>/c/Users/x`). Returns null when `p` is not a+ * drive-letter path — callers use the null to keep the original untouched.+ */+export function translateWindowsPath(p: string, mountRoot: string): string | null {+ const m = WINDOWS_DRIVE_PATH_RE.exec(p);+ if (!m) return null;+ return `${mountRoot.replace(/\/+$/, '')}/${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}`;+}++/**+ * Extract the `[automount] root` value from /etc/wsl.conf content.+ * Defaults to `/mnt` (WSL's own default) when absent/unparseable.+ */+export function parseWslAutomountRoot(conf: string): string {+ let inAutomount = false;+ for (const raw of conf.split(/\r?\n/)) {+ const line = raw.replace(/[#;].*$/, '').trim();+ if (line.startsWith('[')) {+ inAutomount = /^\[automount\]$/i.test(line);+ continue;+ }+ if (!inAutomount) continue;+ const m = /^root\s*=\s*"?([^"]+?)"?\s*$/.exec(line);+ if (m) return m[1];+ }+ return '/mnt';+}++let cachedWslMountRoot: string | null | undefined;++/**+ * Detect the WSL Windows-drive automount root. Returns null when not running+ * under WSL (including macOS and plain Linux). Memoized per process.+ */+export function detectWslMountRoot(): string | null {+ if (cachedWslMountRoot === undefined) cachedWslMountRoot = computeWslMountRoot();+ return cachedWslMountRoot;+}++function computeWslMountRoot(): string | null {+ if (process.platform !== 'linux') return null;+ try {+ // The standard WSL tell: kernel version string names Microsoft.+ if (!/microsoft/i.test(readFileSync('/proc/version', 'utf8'))) return null;+ } catch {+ return null;+ }+ try {+ return parseWslAutomountRoot(readFileSync('/etc/wsl.conf', 'utf8'));+ } catch {+ return '/mnt'; // WSL default when wsl.conf is absent.+ }+}diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsnew file mode 100644index 0000000000..e09bd1fc65--- /dev/null+++ b/src/mcp/resolve-ipc-binding.ts@@ -0,0 +1,205 @@+/**+ * Shared resolve-IPC listener wiring for BOTH serve transports (#4474).+ *+ * Retrieval Reflex (#1981, D9=C): on a PGLite brain, serve owns the single+ * connection, so the context engine (and the per-prompt hook command)+ * resolve salient entities THROUGH the serve over a local unix socket+ * rather than opening a second (impossible) connection. Engine-uniform+ * since #4245: Postgres brains listen too (the hook lane is engine-free by+ * design, so IPC through a serve is its only DB path there) — socket ++ * secret key off hash12(database_url) under ~/.gbrain/run via+ * resolveSocketPathForConfig.+ *+ * Pre-#4474 this block lived inline in the STDIO path (src/mcp/server.ts)+ * only, so `gbrain serve --http` — the exact posture `gbrain bootstrap+ * harness` targets — never bound the socket and every wired lifecycle hook+ * degraded to `no_serve` forever (with serve-delegated sync losing its+ * rung too). Both transports now bind through this helper.+ *+ * Best-effort by contract: failure to bind never blocks the serve.+ */+import type { Server } from 'node:net';+import type { BrainEngine } from '../core/engine.ts';+import { loadConfig } from '../core/config.ts';+import {+ resolveSocketPathForConfig,+ startResolveIpcServer,+ cleanupStaleSocket,+ ensureIpcSecretForConfig,+ type IpcHandlers,+} from '../core/context/resolve-ipc.ts';+import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';+import { lexicalArmsEnabled } from '../core/context/reflex.ts';+import { assembleTurnContext } from '../core/context/turn-context.ts';+import { makeContextPackIpcHandler } from './context-pack-handler.ts';+import { logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';++export interface ResolveIpcBinding {+ /** The bound listener, or null when binding was skipped/failed (best-effort). */+ server: Server | null;+ /** The socket path the listener bound (null when not bound). */+ socketPath: string | null;+ /** Idempotent teardown: close the listener + reap the socket file. */+ close(): void;+}++const NULL_BINDING: ResolveIpcBinding = { server: null, socketPath: null, close: () => {} };++/**+ * Bind the resolve/turn_context/context_pack (+ delegated sync/sweep) IPC+ * listener for a running serve. `defaultSource` is the serve's bound source+ * (resolveMcpStdioSourceScope) — the IPC layer rejects requests naming any+ * other source ([CX2-10]).+ */+export async function bindResolveIpcForServe(+ engine: BrainEngine,+ defaultSource: string,+): Promise<ResolveIpcBinding> {+ try {+ const cfg = loadConfig();+ const resolveSocket = resolveSocketPathForConfig(cfg);+ if (!resolveSocket) return NULL_BINDING;++ // [S3#6] turn_context requires the shared secret from the config-keyed+ // path (created 0600 here if absent). If the secret can't be+ // provisioned, turn_context stays fail-closed ('unauthorized') while+ // the secret-free resolve kind keeps working.+ let ipcSecret: string | undefined;+ try {+ ipcSecret = ensureIpcSecretForConfig(cfg) ?? undefined;+ } catch { /* turn_context disabled; resolve unaffected */ }++ // Serve-delegated sync kinds — built in their OWN try/catch so a+ // runner import/registration failure can never take resolve /+ // turn_context / context_pack down with it (this whole block's shared+ // catch would otherwise swallow the error and start NO listener).+ // Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not+ // registered and clients get 'unsupported_kind' (the polite refusal).+ let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort'> = {};+ if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {+ try {+ const runner = await import('../core/serve-sync-runner.ts');+ syncHandlers = {+ sync_start: (req) =>+ runner.startDelegatedSync(engine, req.options, req.clientToken, {+ boundSourceId: defaultSource,+ }),+ sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId),+ sync_abort: (req) => runner.abortDelegatedSync(req.jobId),+ };+ } catch (e) {+ process.stderr.write(+ `[serve-sync] handlers unavailable: ${e instanceof Error ? e.message : String(e)}\n`,+ );+ }+ }+ // Serve-delegated maintenance sweep (#677) — same posture, own+ // try/catch so a runner failure never takes the other kinds down.+ // Shares the GBRAIN_SERVE_SYNC_IPC kill switch (one delegation family).+ let sweepHandlers: Pick<IpcHandlers, 'sweep_start' | 'sweep_status'> = {};+ if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {+ try {+ const sweepRunner = await import('../core/serve-sweep-runner.ts');+ sweepHandlers = {+ sweep_start: (req) =>+ sweepRunner.startDelegatedSweep(engine, req.options, req.clientToken, {+ boundSourceId: defaultSource,+ }),+ sweep_status: (req) => sweepRunner.getDelegatedSweepStatus(req.jobId),+ };+ } catch (e) {+ process.stderr.write(+ `[serve-sweep] handlers unavailable: ${e instanceof Error ? e.message : String(e)}\n`,+ );+ }+ }++ const server = await startResolveIpcServer(+ resolveSocket,+ {+ // [CX2-10] Bound-source posture for BOTH kinds: the IPC layer+ // rejects any resolve/turn_context request naming a source other+ // than boundSourceId ('source_mismatch'), so the only sourceId that+ // reaches this handler is the bound one or absent — and the handler+ // resolves against the server's OWN registered source regardless.+ resolve: (req) =>+ resolveEntitiesToPointers(+ engine,+ defaultSource,+ req.candidates ?? [],+ {+ priorContextText: req.priorContextText,+ maxPointers: req.maxPointers,+ suppression: req.suppression,+ // v0.46.15 kill switch: either side may disable — a client+ // `false` wins, else the server's own file-config gate.+ // Config is re-read PER REQUEST (adversarial F3): `gbrain+ // serve` is long-running, and the switch's whole value is+ // reverting a false-fire regression on the NEXT TURN with a+ // config edit — a startup snapshot would freeze it until a+ // serve restart. loadConfig is a file read (~1ms) inside the+ // 400ms IPC budget.+ lexicalArms: req.lexicalArms === false ? false : lexicalArmsEnabled(loadConfig()),+ },+ ),+ // IPC v2 [ENG-3]: per-turn context assembly for the hook command.+ // [CX2-10] Always assembles against the server's OWN registered+ // source — cross-source requests are rejected in the IPC layer via+ // boundSourceId below, and the handler never honors a caller source.+ turn_context: (req) =>+ assembleTurnContext(engine, {+ sourceId: defaultSource,+ window: req.window ?? [],+ priorContextText: req.priorContextText,+ sessionId: req.sessionId,+ maxBytes: req.maxBytes,+ // Per-request config read — same next-turn-revert rationale as+ // the resolve handler above (adversarial F3).+ lexicalArms: lexicalArmsEnabled(loadConfig()),+ }),+ // v0.45.7 ambient recall: boundary context pack. Extracted to+ // context-pack-handler.ts (directly testable against a real engine);+ // the runtime owns entity merge, banking, the since-cursor, and the+ // complete-pack-only monotonic cursor advance.+ context_pack: makeContextPackIpcHandler(engine, defaultSource),+ ...syncHandlers,+ ...sweepHandlers,+ },+ {+ // The IPC resolve path IS the ambient reflex channel. Logging happens+ // at DELIVERY (post-write), not inside the resolver — a block the+ // client's 250ms budget abandoned was never injected, and counting it+ // would corrupt the volunteered-vs-used precision stats (red-team).+ onDelivered: (block) => logDeliveredReflexPointers(engine, block.pointers),+ // The hook lane's feedback loop (#2095 closed over turn_context):+ // the delivered block's post-trim volunteered pages + pointers land+ // in context_volunteer_events under the request's channel. Body+ // lives in volunteer-events.ts (logTurnContextDeliveryFireAndForget)+ // so the shipped wiring is unit-testable.+ onTurnContextDelivered: (result, req) =>+ logTurnContextDeliveryFireAndForget(engine, result, req),+ boundSourceId: defaultSource,+ secret: ipcSecret,+ },+ );++ // startResolveIpcServer returns null when the socket is already owned+ // by a live listener (another serve) — that serve is the IPC provider.+ if (!server) return NULL_BINDING;++ let closed = false;+ return {+ server,+ socketPath: resolveSocket,+ close: () => {+ if (closed) return;+ closed = true;+ try { server.close(); } catch { /* noop */ }+ cleanupStaleSocket(resolveSocket);+ },+ };+ } catch {+ /* resolve IPC is best-effort; never block serve */+ return NULL_BINDING;+ }+}diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 602b2ddfdd..97e145e789 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -12,19 +12,8 @@ import { disabledOpsForPublishGates } from './publish-gates.ts';import type { Operation } from '../core/operations.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { loadConfig } from '../core/config.ts';-import {- resolveSocketPathForConfig,- startResolveIpcServer,- cleanupStaleSocket,- ensureIpcSecretForConfig,- type IpcHandlers,-} from '../core/context/resolve-ipc.ts';-import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';-import { lexicalArmsEnabled } from '../core/context/reflex.ts';-import { assembleTurnContext } from '../core/context/turn-context.ts';import { gcSessionContextState } from '../core/context/session-state.ts';-import { makeContextPackIpcHandler } from './context-pack-handler.ts';-import { logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';+import { bindResolveIpcForServe } from './resolve-ipc-binding.ts';export async function resolveMcpStdioSourceScope(engine: BrainEngine,@@ -85,6 +74,31 @@ export async function stdioVisibleTools(return surfacedOps.filter(op => !gateDisabled.has(op.name));}+// ─── #4409: in-flight stdio RPC tracking ────────────────────────────────+// A one-shot MCP client can write a batch of frames and close stdin+// immediately; the SDK parses every frame during the 'data' events (handler+// start is queued as a microtask), so at stdin-'end' time requests can be+// in flight with no response written yet. serve.ts's EOF path consults this+// counter and drains before its graceful exit instead of dropping the+// response on the floor. Module-level because one process runs one stdio+// server (matches the serve-sync-runner singleton posture).+let _stdioRpcsInFlight = 0;++/** Live count of stdio JSON-RPC requests whose handlers have not settled. */+export function stdioRpcsInFlightCount(): number {+ return _stdioRpcsInFlight;+}++/** Wrap one request handler invocation in the in-flight counter. @internal */+export async function trackStdioRpc<T>(work: () => Promise<T>): Promise<T> {+ _stdioRpcsInFlight++;+ try {+ return await work();+ } finally {+ _stdioRpcsInFlight--;+ }+}+export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean } = {}) {const server = new Server({ name: 'gbrain', version: VERSION },@@ -116,16 +130,16 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// subtraction happens per request (stdioVisibleTools) — no caching, so a// `gbrain config set mcp.publish_skills true` takes effect on the next// tools/list without a serve restart (matches the HTTP transports).- server.setRequestHandler(ListToolsRequestSchema, async () => ({+ server.setRequestHandler(ListToolsRequestSchema, async () => trackStdioRpc(async () => ({tools: buildToolDefs(await stdioVisibleTools(engine, surfacedOps), { strictParams }),- }));+ })));// Dispatch tool calls via shared dispatch.ts (parity with HTTP transport).// MCP stdio callers are remote/untrusted; dispatch defaults remote=true.// The MCP SDK's response type widened in 1.29 to allow a managed-task wrapper;// gbrain ops are synchronous, so we return the legacy `{ content, isError? }`// shape and cast through `any` (the SDK accepts it via the ServerResult union).- server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => {+ server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => trackStdioRpc(async () => {const { name, arguments: params } = request.params;// #3242 / #3906: stdio resolves its source through the same ambient chain// as local CLI dispatch: GBRAIN_SOURCE, then .gbrain-source, then the@@ -172,150 +186,19 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// request_tools bounds its catalog by (persist no-ops without auth).surfaceCeiling: surface,});- });+ }));const transport = new StdioServerTransport();await server.connect(transport);- // Retrieval Reflex (#1981, D9=C): on a PGLite brain, serve owns the single- // connection, so the context engine (and the per-prompt hook command)- // resolve salient entities THROUGH us over a local unix socket rather than- // opening a second (impossible) connection. Engine-uniform since #4245:- // Postgres brains listen too (the hook lane is engine-free by design, so- // IPC through a serve is its only DB path there) — socket + secret key off- // hash12(database_url) under ~/.gbrain/run via resolveSocketPathForConfig.- // Best-effort; failure to bind never blocks the MCP server.- let resolveServer: import('node:net').Server | null = null;- let resolveSocket: string | null = null;- try {- const cfg = loadConfig();- resolveSocket = resolveSocketPathForConfig(cfg);- if (resolveSocket) {- const { sourceId: defaultSource } = await resolveMcpStdioSourceScope(engine);- // [S3#6] turn_context requires the shared secret from the config-keyed- // path (created 0600 here if absent). If the secret can't be- // provisioned, turn_context stays fail-closed ('unauthorized') while- // the secret-free resolve kind keeps working.- let ipcSecret: string | undefined;- try {- ipcSecret = ensureIpcSecretForConfig(cfg) ?? undefined;- } catch { /* turn_context disabled; resolve unaffected */ }- // Serve-delegated sync kinds — built in their OWN try/catch so a- // runner import/registration failure can never take resolve /- // turn_context / context_pack down with it (this whole block's shared- // catch would otherwise swallow the error and start NO listener).- // Kill switch: GBRAIN_SERVE_SYNC_IPC=0 → the kinds are simply not- // registered and clients get 'unsupported_kind' (the polite refusal).- let syncHandlers: Pick<IpcHandlers, 'sync_start' | 'sync_status' | 'sync_abort'> = {};- if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {- try {- const runner = await import('../core/serve-sync-runner.ts');- syncHandlers = {- sync_start: (req) =>- runner.startDelegatedSync(engine, req.options, req.clientToken, {- boundSourceId: defaultSource,- }),- sync_status: (req) => runner.getDelegatedSyncStatus(req.jobId),- sync_abort: (req) => runner.abortDelegatedSync(req.jobId),- };- } catch (e) {- process.stderr.write(- `[serve-sync] handlers unavailable: ${e instanceof Error ? e.message : String(e)}\n`,- );- }- }- // Serve-delegated maintenance sweep (#677) — same posture, own- // try/catch so a runner failure never takes the other kinds down.- // Shares the GBRAIN_SERVE_SYNC_IPC kill switch (one delegation family).- let sweepHandlers: Pick<IpcHandlers, 'sweep_start' | 'sweep_status'> = {};- if (process.env.GBRAIN_SERVE_SYNC_IPC !== '0') {- try {- const sweepRunner = await import('../core/serve-sweep-runner.ts');- sweepHandlers = {- sweep_start: (req) =>- sweepRunner.startDelegatedSweep(engine, req.options, req.clientToken, {- boundSourceId: defaultSource,- }),- sweep_status: (req) => sweepRunner.getDelegatedSweepStatus(req.jobId),- };- } catch (e) {- process.stderr.write(- `[serve-sweep] handlers unavailable: ${e instanceof Error ? e.message : String(e)}\n`,- );- }- }- resolveServer = await startResolveIpcServer(- resolveSocket,- {- // [CX2-10] Bound-source posture for BOTH kinds: the IPC layer- // rejects any resolve/turn_context request naming a source other- // than boundSourceId ('source_mismatch'), so the only sourceId that- // reaches this handler is the bound one or absent — and the handler- // resolves against the server's OWN registered source regardless.- resolve: (req) =>- resolveEntitiesToPointers(- engine,- defaultSource,- req.candidates ?? [],- {- priorContextText: req.priorContextText,- maxPointers: req.maxPointers,- suppression: req.suppression,- // v0.46.15 kill switch: either side may disable — a client- // `false` wins, else the server's own file-config gate.- // Config is re-read PER REQUEST (adversarial F3): `gbrain- // serve` is long-running, and the switch's whole value is- // reverting a false-fire regression on the NEXT TURN with a- // config edit — a startup snapshot would freeze it until a- // serve restart. loadConfig is a file read (~1ms) inside the- // 400ms IPC budget.- lexicalArms: req.lexicalArms === false ? false : lexicalArmsEnabled(loadConfig()),- },- ),- // IPC v2 [ENG-3]: per-turn context assembly for the hook command.- // [CX2-10] Always assembles against the server's OWN registered- // source — cross-source requests are rejected in the IPC layer via- // boundSourceId below, and the handler never honors a caller source.- turn_context: (req) =>- assembleTurnContext(engine, {- sourceId: defaultSource,- window: req.window ?? [],- priorContextText: req.priorContextText,- sessionId: req.sessionId,- maxBytes: req.maxBytes,- // Per-request config read — same next-turn-revert rationale as- // the resolve handler above (adversarial F3).- lexicalArms: lexicalArmsEnabled(loadConfig()),- }),- // v0.45.7 ambient recall: boundary context pack. Extracted to- // context-pack-handler.ts (directly testable against a real engine);- // the runtime owns entity merge, banking, the since-cursor, and the- // complete-pack-only monotonic cursor advance.- context_pack: makeContextPackIpcHandler(engine, defaultSource),- ...syncHandlers,- ...sweepHandlers,- },- {- // The IPC resolve path IS the ambient reflex channel. Logging happens- // at DELIVERY (post-write), not inside the resolver — a block the- // client's 250ms budget abandoned was never injected, and counting it- // would corrupt the volunteered-vs-used precision stats (red-team).- onDelivered: (block) => logDeliveredReflexPointers(engine, block.pointers),- // The hook lane's feedback loop (#2095 closed over turn_context):- // the delivered block's post-trim volunteered pages + pointers land- // in context_volunteer_events under the request's channel. Body- // lives in volunteer-events.ts (logTurnContextDeliveryFireAndForget)- // so the shipped wiring is unit-testable.- onTurnContextDelivered: (result, req) =>- logTurnContextDeliveryFireAndForget(engine, result, req),- boundSourceId: defaultSource,- secret: ipcSecret,- },- );- }- } catch {- /* resolve IPC is best-effort; never block serve */- }+ // Retrieval Reflex (#1981, D9=C): the resolve/turn_context/context_pack+ // (+ delegated sync/sweep) IPC listener. Wiring shared with `serve --http`+ // via bindResolveIpcForServe (#4474) — best-effort; failure to bind never+ // blocks the MCP server.+ const ipcBinding = await bindResolveIpcForServe(+ engine,+ (await resolveMcpStdioSourceScope(engine)).sourceId,+ );// v0.45.7 ambient recall: age out stale session cursors once per serve boot// (7-day TTL, indexed DELETE). Best-effort — GC failure never blocks serve.@@ -348,8 +231,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSshuttingDown = true;process.stderr.write(`[gbrain-serve] shutdown: ${reason}\n`);try { startupSweep?.cancel(); } catch { /* noop */ }- try { resolveServer?.close(); } catch { /* noop */ }- if (resolveSocket) cleanupStaleSocket(resolveSocket);+ ipcBinding.close();// Cathedral 5: abort the in-flight checkpoint harvest + drop its queue// BEFORE engine.disconnect — the background-work registry's drain is// CLI-exit-only by contract, and a fire-and-forget DB writer survivingdiff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex b7810574ef..b4b5c45e5c 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.46.28.0 -->+<!-- gbrain-template-stamp: 0.46.29.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/agent-cli.test.ts b/test/agent-cli.test.tsindex 365804d9a6..7c401f77bf 100644--- a/test/agent-cli.test.ts+++ b/test/agent-cli.test.ts@@ -279,16 +279,21 @@ describe('queue.add trusted-submit gate for subagent', () => {});test('subagent with a loop-incapable provider (supports_subagent_loop: false) is rejected at submit time', async () => {- // moonshot supports tools but declares the loop unsupported- // (tool_call_ids not replay-stable); OpenRouter routes carry the same- // declaration because stability can't be guaranteed through the proxy.- // Pre-fix these passed the gate as 'ok' / 'degraded:no_caching'.+ // moonshot supports tools but declares the loop unsupported.+ // Non-Anthropic OpenRouter families stay refused; Anthropic-via-OR is allowed.await expect(queue.add('subagent', { prompt: 'hi', model: 'moonshot:kimi-k2.5' }, {}, { allowProtectedSubmit: true }),).rejects.toThrow(/supports_subagent_loop/);await expect(queue.add('subagent', { prompt: 'hi', model: 'openrouter:openai/gpt-5.2' }, {}, { allowProtectedSubmit: true }),).rejects.toThrow(/supports_subagent_loop/);+ const job = await queue.add(+ 'subagent',+ { prompt: 'hi', model: 'openrouter:anthropic/claude-haiku-4.5' },+ {},+ { allowProtectedSubmit: true },+ );+ expect(job.id).toBeGreaterThan(0);});});diff --git a/test/ai/capabilities.test.ts b/test/ai/capabilities.test.tsindex e7fdbd7d46..e5b261ecf5 100644--- a/test/ai/capabilities.test.ts+++ b/test/ai/capabilities.test.ts@@ -122,12 +122,13 @@ describe('classifyCapabilities (D6 — three-tier capability verdict)', () => {expect(classifyCapabilities('google:gemini-1.5-pro')).toBe('degraded:no_caching');});- it('returns unusable:no_subagent_loop for OpenRouter routes (recipe declares the loop unsupported)', () => {- // Pre-fix these classified 'ok' / 'degraded:no_caching' even though the- // recipe declares supports_subagent_loop: false — the loop-stability gate- // was silently bypassed for every openai-compat aggregator route.+ it('allows OpenRouter Anthropic routes for the subagent loop and refuses other OR families', () => {+ // Anthropic-via-OR shares the Anthropic tool envelope; replay keys off+ // gbrain_tool_use_id. Other proxied families stay refused until they get+ // their own live abort/retry pin.+ expect(classifyCapabilities('openrouter:anthropic/claude-sonnet-4.6')).toBe('ok');+ expect(classifyCapabilities('openrouter:anthropic/claude-haiku-4.5')).toBe('ok');expect(classifyCapabilities('openrouter:openai/gpt-5.2')).toBe('unusable:no_subagent_loop');- expect(classifyCapabilities('openrouter:anthropic/claude-sonnet-4.6')).toBe('unusable:no_subagent_loop');expect(classifyCapabilities('openrouter:deepseek/deepseek-chat')).toBe('unusable:no_subagent_loop');});diff --git a/test/ai/embedQuery.test.ts b/test/ai/embedQuery.test.tsindex c12fa03219..d6ef42d0b8 100644--- a/test/ai/embedQuery.test.ts+++ b/test/ai/embedQuery.test.ts@@ -75,6 +75,28 @@ describe('embedQuery — return shape', () => {});});+describe('embed — input truncation', () => {+ test('never splits a UTF-16 surrogate pair at MAX_CHARS', async () => {+ configureOpenAI();+ const input = `${'a'.repeat(7_999)}💡trailing prose`;+ let captured = '';+ __setEmbedTransportForTests((async (args: any) => {+ captured = args.values[0];+ return fakeEmbeddings(1, 1536);+ }) as any);++ await embed([input]);++ expect(input.slice(0, 8_000).isWellFormed()).toBe(false); // positive control+ expect(captured.isWellFormed()).toBe(true);+ // Truncation must actually occur (not a no-op that trivially passes well-formedness):+ // the straddling pair moves the safe cut back to 7,999, dropping both the emoji and+ // the trailing prose entirely.+ expect(captured.length).toBe(7_999);+ expect(captured).not.toContain('trailing prose');+ });+});+describe('embedQuery — inputType plumbing (ZE asymmetric)', () => {beforeEach(() => configureZE());diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.tsindex c1de4b15f7..ccd1e056a8 100644--- a/test/ai/gateway-chat.test.ts+++ b/test/ai/gateway-chat.test.ts@@ -480,6 +480,66 @@ describe('chat touchpoint — per-part providerMetadata round trip (#4201)', ()});});+// OpenAI's Responses API requires every `function_call` item in a replayed+// transcript to be paired with the `reasoning` item that produced it, or the+// NEXT turn 400s: "Item '<fc_id>' of type 'function_call' was provided+// without its required 'reasoning' item: '<rs_id>'." Reproduced live against+// openai:gpt-5.6-luna in a 2-turn tool-calling conversation: turn 1 captured+// zero reasoning blocks (chat() silently dropped the `reasoning` part) and+// turn 2 failed with exactly that message; after this fix turn 1 captures+// the reasoning block and turn 2 completes. This suite covers the inbound+// capture half with the SAME #4201 providerMetadata channel `text`/`tool-call`+// already use — see gateway-model-messages.test.ts for the outbound echo half.+describe('chat touchpoint — reasoning-item round trip (OpenAI Responses API)', () => {+ beforeEach(() => {+ resetGateway();+ __setGenerateTextTransportForTests(null);+ });++ const REASONING_SIG = { openai: { itemId: 'rs_abc123', reasoningEncryptedContent: 'opaque-blob' } };++ test('chat() captures a reasoning part into a ChatBlock (inbound half)', async () => {+ __setGenerateTextTransportForTests(async () => ({+ content: [+ { type: 'reasoning', text: 'weighing today vs. the forecast...', providerMetadata: REASONING_SIG },+ { type: 'tool-call', toolCallId: 'c1', toolName: 'get_forecast', input: { city: 'Tokyo' } },+ ],+ finishReason: 'tool-calls',+ usage: { inputTokens: 5, outputTokens: 5 },+ }) as any);+ configureGateway({ chat_model: 'openai:gpt-5.6-luna', env: { OPENAI_API_KEY: 'fake' } });+ const result = await chat({+ model: 'openai:gpt-5.6-luna',+ messages: [{ role: 'user', content: 'hello' }],+ });+ const reasoning = result.blocks.find(b => b.type === 'reasoning') as any;+ expect(reasoning).toBeDefined();+ expect(reasoning.text).toBe('weighing today vs. the forecast...');+ expect(reasoning.providerMetadata).toEqual(REASONING_SIG);+ // Never leaks into the final answer text (that's the model's actual reply, not its thinking).+ expect(result.text).toBe('');+ });++ test('a reasoning part with a non-string text field does not poison the call', async () => {+ __setGenerateTextTransportForTests(async () => ({+ content: [+ { type: 'reasoning', text: null },+ { type: 'text', text: 'ok' },+ ],+ finishReason: 'stop',+ usage: { inputTokens: 1, outputTokens: 1 },+ }) as any);+ configureGateway({ chat_model: 'openai:gpt-5.6-luna', env: { OPENAI_API_KEY: 'fake' } });+ const result = await chat({+ model: 'openai:gpt-5.6-luna',+ messages: [{ role: 'user', content: 'hello' }],+ });+ const reasoning = result.blocks.find(b => b.type === 'reasoning') as any;+ expect(reasoning.text).toBe('');+ expect(result.text).toBe('ok');+ });+});+describe('chat — typed provider error status carried to the top level', () => {beforeEach(() => {resetGateway();diff --git a/test/ai/recipe-nan.test.ts b/test/ai/recipe-nan.test.tsnew file mode 100644index 0000000000..c1dd0930cb--- /dev/null+++ b/test/ai/recipe-nan.test.ts@@ -0,0 +1,67 @@+/**+ * nan recipe smoke.+ *+ * Pins the recipe shape so the registry stays byte-stable:+ * - id + tier + implementation + base_url+ * - reranker touchpoint declares the `/v1/rerank` leaf (the whole point —+ * nan.builders 404s on every other path) + `default_timeout_ms`+ * - only live-verified model ids are listed+ */++import { describe, expect, test } from 'bun:test';+import { getRecipe } from '../../src/core/ai/recipes/index.ts';+import { defaultResolveAuth } from '../../src/core/ai/gateway.ts';+import { AIConfigError } from '../../src/core/ai/errors.ts';++describe('recipe: nan', () => {+ test('registered with expected shape', () => {+ const r = getRecipe('nan');+ expect(r).toBeDefined();+ expect(r!.id).toBe('nan');+ expect(r!.tier).toBe('openai-compat');+ expect(r!.implementation).toBe('openai-compatible');+ expect(r!.base_url_default).toBe('https://api.nan.builders/v1');+ expect(r!.auth_env?.required).toEqual(['NAN_API_KEY']);+ });++ test('declares reranker touchpoint with /v1/rerank path + timeout', () => {+ const r = getRecipe('nan')!;+ const tp = r.touchpoints.reranker;+ expect(tp).toBeDefined();+ expect(tp!.path).toBe('/rerank');+ expect(tp!.default_timeout_ms).toBe(30_000);+ expect(tp!.max_payload_bytes).toBe(5_000_000);+ });++ test('base_url + path concatenation produces /v1/rerank, NOT /v1/v1/…', () => {+ const r = getRecipe('nan')!;+ const combined =+ r.base_url_default!.replace(/\/$/, '') + (r.touchpoints.reranker!.path ?? '/models/rerank');+ expect(combined).toBe('https://api.nan.builders/v1/rerank');+ expect(combined).not.toContain('/v1/v1/');+ expect(combined.endsWith('/rerank')).toBe(true);+ });++ test('lists only the live-verified model id', () => {+ const r = getRecipe('nan')!;+ const tp = r.touchpoints.reranker!;+ expect(tp.models).toEqual(['rerank']);+ expect(tp.default_model).toBe('rerank');+ });++ test('default auth: NAN_API_KEY set → Bearer token', () => {+ const r = getRecipe('nan')!;+ const auth = defaultResolveAuth(+ r,+ { NAN_API_KEY: 'nan-fake-key' },+ 'reranker',+ );+ expect(auth.headerName).toBe('Authorization');+ expect(auth.token).toBe('Bearer nan-fake-key');+ });++ test('default auth: missing NAN_API_KEY → AIConfigError', () => {+ const r = getRecipe('nan')!;+ expect(() => defaultResolveAuth(r, {}, 'reranker')).toThrow(AIConfigError);+ });+});diff --git a/test/ai/recipe-openrouter.test.ts b/test/ai/recipe-openrouter.test.tsindex cc64a4e21a..f51d1a5285 100644--- a/test/ai/recipe-openrouter.test.ts+++ b/test/ai/recipe-openrouter.test.ts@@ -69,10 +69,14 @@ describe('recipe: openrouter', () => {const r = getRecipe('openrouter')!;expect(r.touchpoints.chat).toBeDefined();expect(r.touchpoints.chat!.supports_tools).toBe(true);- // supports_subagent_loop: false is enforced — classifyCapabilities()- // refuses the subagent tier on it (unusable:no_subagent_loop). Field- // stays false per the recipe docstring.- expect(r.touchpoints.chat!.supports_subagent_loop).toBe(false);+ const loop = r.touchpoints.chat!.supports_subagent_loop;+ expect(typeof loop).toBe('function');+ if (typeof loop === 'function') {+ expect(loop('anthropic/claude-haiku-4.5')).toBe(true);+ expect(loop('anthropic/claude-sonnet-4.6')).toBe(true);+ expect(loop('openai/gpt-5.2')).toBe(false);+ expect(loop('deepseek/deepseek-chat')).toBe(false);+ }expect(() =>assertTouchpoint(r, 'chat', 'some/provider-model'),).not.toThrow();diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.tsindex 798a942e96..a8bce3113f 100644--- a/test/ambient-recall.test.ts+++ b/test/ambient-recall.test.ts@@ -641,6 +641,52 @@ describe('visibility (eng 1A / D2=A): world-only default, fail-closed widen', ()expect(facts).not.toContain('secret burn rate');expect(r.text as string).not.toContain('secret burn rate');});++ test('delta page arm widens private pages only for trusted local include_private', async () => {+ const since = new Date(Date.now() - 5 * 60_000).toISOString();+ await engine.putPage('notes/delta-world-page', {+ title: 'Delta World Page',+ type: 'note',+ frontmatter: { visibility: 'world' },+ compiled_truth: 'world page body',+ timeline: '',+ });+ await engine.putPage('notes/delta-private-page', {+ title: 'Delta Private Page',+ type: 'note',+ frontmatter: { visibility: 'private' },+ compiled_truth: 'private page body',+ timeline: '',+ });++ const worldOnly = await call(del, ctxFor({ remote: false }), { since });+ const widened = await call(del, ctxFor({ remote: false }), {+ since,+ include_private: true,+ });+ const remote = await call(del, ctxFor({ remote: true, clientId: 'c1' }), {+ since,+ include_private: true,+ });++ for (const result of [worldOnly, widened, remote]) {+ expect(result.pages.map((p: { slug: string }) => p.slug)).toContain(+ 'notes/delta-world-page',+ );+ }+ expect(worldOnly.pages.map((p: { slug: string }) => p.slug)).not.toContain(+ 'notes/delta-private-page',+ );+ expect(worldOnly.text as string).not.toContain('Delta Private Page');+ expect(widened.pages.map((p: { slug: string }) => p.slug)).toContain(+ 'notes/delta-private-page',+ );+ expect(widened.text as string).toContain('Delta Private Page');+ expect(remote.pages.map((p: { slug: string }) => p.slug)).not.toContain(+ 'notes/delta-private-page',+ );+ expect(remote.text as string).not.toContain('Delta Private Page');+ });});describe('budget packing + drop footer', () => {diff --git a/test/archived-source-scoping.test.ts b/test/archived-source-scoping.test.tsindex 174f07abb2..48da03b5d0 100644--- a/test/archived-source-scoping.test.ts+++ b/test/archived-source-scoping.test.ts@@ -118,6 +118,11 @@ describe('#3880 structural pins — all-source local_path selections filter arch// SourceTargetError instead of silently falling through.const src = readFileSync('src/core/source-resolver.ts', 'utf-8');expect(src).toContain('SELECT id, local_path, archived FROM sources WHERE local_path IS NOT NULL');- expect(src.match(/r\.archived !== true/g)?.length ?? 0).toBeGreaterThanOrEqual(2);+ // #4411: tier-4 realpath resolution was parallelized and the two+ // active/archived filter passes were consolidated into one indexed loop+ // over both tiers — same active-over-archived behavior (see the two+ // behavioral tests above), expressed once instead of duplicated twice.+ expect(src).toContain('for (const archivedTier of [false, true])');+ expect(src.match(/\.archived === true\) !== archivedTier/g)?.length ?? 0).toBeGreaterThanOrEqual(1);});});diff --git a/test/bench/correctness-gate.test.ts b/test/bench/correctness-gate.test.tsindex 56b2dc307c..ebf1125491 100644--- a/test/bench/correctness-gate.test.ts+++ b/test/bench/correctness-gate.test.ts@@ -84,6 +84,67 @@ describe('correctness-gate: per-query iteration + aggregate math', () => {expect(result.summary.first_relevant_hit_rate).toBe(1); // top-1 was 'a' which is relevant});+ test('duplicate chunk-level hits from relevant pages cannot inflate recall above 1', async () => {+ const qrels = makeQrels([+ {+ query_id: 'q-duplicate-chunks',+ query: 'x',+ relevant: [+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'b' },+ { source_id: 'default', slug: 'c' },+ { source_id: 'default', slug: 'd' },+ ],+ },+ ]);+ const result = await runCorrectnessGate(fakeEngine, qrels, {+ k: 10,+ // Seven relevant chunk hits used to score 7 / 4 = 1.75 even though+ // they represent only two distinct pages.+ searchFn: async () => [+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'a' },+ { source_id: 'default', slug: 'b' },+ { source_id: 'default', slug: 'b' },+ { source_id: 'default', slug: 'b' },+ ],+ });++ expect(result.per_query[0]?.recall_at_k).toBe(0.5);+ expect(result.per_query[0]?.recall_at_k).toBeLessThanOrEqual(1);+ expect(result.per_query[0]?.retrieved_count).toBe(2);+ expect(result.summary.mean_recall_at_k).toBe(0.5);+ });++ test('distinct relevant pages retain correct recall, including the same slug in different sources', async () => {+ const qrels = makeQrels([+ {+ query_id: 'q-distinct-pages',+ query: 'x',+ relevant: [+ { source_id: 'source-a', slug: 'shared' },+ { source_id: 'source-b', slug: 'shared' },+ { source_id: 'source-a', slug: 'unique-a' },+ { source_id: 'source-b', slug: 'unique-b' },+ ],+ },+ ]);+ const result = await runCorrectnessGate(fakeEngine, qrels, {+ k: 10,+ searchFn: async () => [+ { source_id: 'source-a', slug: 'shared' },+ { source_id: 'source-b', slug: 'shared' },+ { source_id: 'source-a', slug: 'unique-a' },+ ],+ });++ expect(result.per_query[0]?.recall_at_k).toBe(0.75);+ expect(result.per_query[0]?.retrieved_count).toBe(3);+ expect(result.summary.mean_recall_at_k).toBe(0.75);+ });+test('empty retrieved list → recall=0 / first_relevant=0 / expected_top1=0', async () => {const qrels = makeQrels([{diff --git a/test/chat-key-plane.test.ts b/test/chat-key-plane.test.tsindex 1e10ac91d5..eb153e6391 100644--- a/test/chat-key-plane.test.ts+++ b/test/chat-key-plane.test.ts@@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import { withEnv } from './helpers/with-env.ts';import { chatApiKeyConfigured } from '../src/core/brain-score-recommendations.ts';+import { setGatewayAnthropicKeySnapshot } from '../src/core/ai/anthropic-key.ts';describe('#3944 chatApiKeyConfigured', () => {test('no env, no file key → false (a DB-only key is invisible by design)', async () => {@@ -63,3 +64,23 @@ describe('#3944 both planner surfaces share the helper (source guard)', () => {expect(src).not.toContain('process.env.ANTHROPIC_API_KEY ||');});});++describe('#3944 follow-up — gateway env snapshot plane', () => {+ test('a gateway-merged DB-plane key reads as configured, and only while the snapshot is live', async () => {+ await withEnv({ ANTHROPIC_API_KEY: undefined }, () => {+ // A raw DB-only key stays invisible (no engine reaches this helper) —+ // but once loadConfigWithEngine merged it into the RUNNING gateway env+ // (modeled by the snapshot seam), the key is actually serving chat and+ // must not read as missing on either planner surface.+ try {+ setGatewayAnthropicKeySnapshot('sk-test-db-merged');+ expect(chatApiKeyConfigured(null)).toBe(true);+ expect(chatApiKeyConfigured({})).toBe(true);+ } finally {+ setGatewayAnthropicKeySnapshot(undefined);+ }+ // Gateway reset clears the snapshot → back to not-configured.+ expect(chatApiKeyConfigured(null)).toBe(false);+ });+ });+});diff --git a/test/chat-usage.test.ts b/test/chat-usage.test.tsindex 7793e7d5ce..9a43c8d783 100644--- a/test/chat-usage.test.ts+++ b/test/chat-usage.test.ts@@ -21,6 +21,7 @@ import {withChatPhase,currentChatPhase,setChatUsageSink,+ registerChatUsageSink,recordChatUsage,estimateChatCostUsd,makeEngineChatUsageSink,@@ -45,6 +46,63 @@ afterEach(() => {setChatUsageSink(null);});+describe('#4480 — sink registry: multi-engine deregistration restores the prior ledger', () => {+ const usage = { input_tokens: 1, output_tokens: 1 };++ test('records route to the top live sink; deregistering it restores the previous one', () => {+ const primary: ChatUsageRecord[] = [];+ const secondary: ChatUsageRecord[] = [];+ const deregPrimary = registerChatUsageSink((r) => { primary.push(r); });+ const deregSecondary = registerChatUsageSink((r) => { secondary.push(r); });++ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(secondary.length).toBe(1);+ expect(primary.length).toBe(0);++ // The short-lived secondary engine disconnects. Pre-fix (last-wins+ // scalar) the ledger was permanently lost to the closed engine; now the+ // primary sink is restored.+ deregSecondary();+ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(primary.length).toBe(1);+ expect(secondary.length).toBe(1);++ deregPrimary();+ // No live sink: record is a silent no-op (never throws).+ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(primary.length).toBe(1);+ // Deregistration is idempotent.+ deregSecondary();+ deregPrimary();+ });++ test('out-of-order deregistration removes only its own entry', () => {+ const a: ChatUsageRecord[] = [];+ const b: ChatUsageRecord[] = [];+ const c: ChatUsageRecord[] = [];+ const deregA = registerChatUsageSink((r) => { a.push(r); });+ const deregB = registerChatUsageSink((r) => { b.push(r); });+ const deregC = registerChatUsageSink((r) => { c.push(r); });+ // Middle entry disconnects first — top stays the router.+ deregB();+ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(c.length).toBe(1);+ deregC();+ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(a.length).toBe(1);+ expect(b.length).toBe(0);+ deregA();+ });++ test('setChatUsageSink(null) clears every registered entry (legacy scalar API)', () => {+ const a: ChatUsageRecord[] = [];+ registerChatUsageSink((r) => { a.push(r); });+ setChatUsageSink(null);+ recordChatUsage({ model: 'anthropic:claude-haiku-4-5', usage });+ expect(a.length).toBe(0);+ });+});+describe('estimateChatCostUsd — canonical pricing incl. cache tokens', () => {test('anthropic model prices cache reads at 0.1x and writes at 1.25x input', () => {// haiku-4-5: $1/M in, $5/M out, $0.10/M cache-read, $1.25/M cache-writediff --git a/test/chunker-version-gate.test.ts b/test/chunker-version-gate.test.tsindex 91f7efa461..7a0bcef35b 100644--- a/test/chunker-version-gate.test.ts+++ b/test/chunker-version-gate.test.ts@@ -15,21 +15,24 @@ import { describe, test, expect } from 'bun:test';import { CHUNKER_VERSION } from '../src/core/chunkers/code.ts';describe('Layer 12 — CHUNKER_VERSION constant', () => {- test('bumped to 5 for python decorated_definition support (#3821)', () => {+ test('bumped to 6 for the definition-preserving merge guard (#4511)', () => {// v3: v0.19.0 Chonkie parity (tokenizer + small-sibling merge).// v4: v0.20.0 Cathedral II (qualified names + parent scope + doc_comment// + fence extraction + chunk-grain FTS). Folded into content_hash// so any bump forces clean re-chunks on next sync.// v5: #3821 python decorated_definition — decorated fns/classes emitted// ZERO chunks pre-fix; the bump forces recovery re-chunks.- expect(CHUNKER_VERSION).toBe(5);+ // v6: #4511 mergeSmallSiblings stopped erasing symbol_name on short+ // definitions; the bump re-chunks previously-merged files so the+ // lost symbols come back.+ expect(CHUNKER_VERSION).toBe(6);});test('is stable across imports (not recomputed at call time)', async () => {const a = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;const b = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;expect(a).toBe(b);- expect(a).toBe(5);+ expect(a).toBe(6);});});diff --git a/test/chunkers/code-merge-defs.test.ts b/test/chunkers/code-merge-defs.test.tsnew file mode 100644index 0000000000..f9b7fad1e4--- /dev/null+++ b/test/chunkers/code-merge-defs.test.ts@@ -0,0 +1,96 @@+/**+ * #4511 — mergeSmallSiblings must never fold a named definition into an+ * anonymous `symbolType: 'merged'` chunk: merging nulls out symbol_name, and+ * code-def resolves names against chunk rows, so a merged definition was+ * unreachable. A flat file of short top-level defs indexed to ZERO symbols in+ * every language without nested-emit chunks (protection previously happened+ * only as a side effect of hasScopedChunks).+ *+ * Also pins that the fix does NOT disable the merge pass for its stated+ * purpose: runs of imports / small constants still merge.+ */+import { describe, test, expect } from 'bun:test';+import { chunkCodeText, CHUNKER_VERSION } from '../../src/core/chunkers/code.ts';+import { DEF_TYPES, MERGE_PROTECTED_SYMBOL_TYPES } from '../../src/core/chunkers/def-types.ts';+import { DEF_TYPES as DEF_TYPES_VIA_CODE_DEF } from '../../src/commands/code-def.ts';++const symbolMap = (chunks: Awaited<ReturnType<typeof chunkCodeText>>) =>+ chunks.map((c) => `${c.metadata.symbolType}:${c.metadata.symbolName}`);++describe('#4511 — short flat definitions keep their symbol names', () => {+ test('python: two short top-level defs → two named function chunks', async () => {+ const src = 'def a(v):\n return v+1\n\ndef b(v):\n return v-1\n';+ const chunks = await chunkCodeText(src, 't.py');+ expect(chunks).toHaveLength(2);+ expect(symbolMap(chunks)).toEqual(['function:a', 'function:b']);+ });++ test('typescript: two short exported functions → two named chunks', async () => {+ const src = 'export function a(v: number) {\n return v + 1;\n}\n\nexport function b(v: number) {\n return v - 1;\n}\n';+ const chunks = await chunkCodeText(src, 't.ts');+ expect(chunks).toHaveLength(2);+ for (const c of chunks) expect(c.metadata.symbolName).not.toBeNull();+ expect(chunks.map((c) => c.metadata.symbolName)).toEqual(['a', 'b']);+ });++ test('go: two short top-level funcs → two named chunks', async () => {+ const src = 'package t\n\nfunc A(v int) int {\n\treturn v + 1\n}\n\nfunc B(v int) int {\n\treturn v - 1\n}\n';+ const chunks = await chunkCodeText(src, 't.go');+ const named = chunks.filter((c) => c.metadata.symbolName !== null);+ expect(named.map((c) => c.metadata.symbolName)).toEqual(expect.arrayContaining(['A', 'B']));+ expect(chunks.some((c) => c.metadata.symbolType === 'merged' && /func [AB]\(/.test(c.text))).toBe(false);+ });++ test('rust: two short fns → two named chunks', async () => {+ const src = 'fn a(v: i32) -> i32 {\n v + 1\n}\n\nfn b(v: i32) -> i32 {\n v - 1\n}\n';+ const chunks = await chunkCodeText(src, 't.rs');+ expect(chunks.map((c) => c.metadata.symbolName)).toEqual(['a', 'b']);+ });++ test('a definition sitting inside an import/const run is not folded into it', async () => {+ const src = [+ 'import os',+ 'import sys',+ 'import json',+ '',+ 'def keepme(v):',+ ' return v',+ '',+ 'import re',+ 'import io',+ '',+ ].join('\n');+ const chunks = await chunkCodeText(src, 'runs.py');+ const named = chunks.filter((c) => c.metadata.symbolName === 'keepme');+ expect(named).toHaveLength(1);+ expect(named[0]!.metadata.symbolType).toBe('function');+ });++ test('import runs still merge (the pass keeps its stated purpose)', async () => {+ const src = Array.from({ length: 8 }, (_, i) => `import mod_${i}`).join('\n') + '\n';+ const chunks = await chunkCodeText(src, 'imports.py');+ expect(chunks).toHaveLength(1);+ expect(chunks[0]!.metadata.symbolType).toBe('merged');+ });++ test('CHUNKER_VERSION bumped to 6 so existing indexes re-chunk', () => {+ expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(6);+ });++ test('merge guard is a derived view of code-def DEF_TYPES (single shared list)', () => {+ // Same array object via both import paths — not a hand-copied duplicate.+ expect(DEF_TYPES_VIA_CODE_DEF).toBe(DEF_TYPES);+ // Core definition kinds are protected; run forms stay mergeable.+ for (const t of ['function', 'class', 'interface', 'enum', 'struct item', 'type declaration']) {+ expect(MERGE_PROTECTED_SYMBOL_TYPES.has(t)).toBe(true);+ }+ for (const t of ['lexical declaration', 'variable declaration', 'const declaration', 'local declaration']) {+ expect(MERGE_PROTECTED_SYMBOL_TYPES.has(t)).toBe(false);+ }+ // Everything protected (minus the two wrapper forms) is code-def-resolvable.+ for (const t of MERGE_PROTECTED_SYMBOL_TYPES) {+ if (t === 'export statement' || t === 'decorated definition') continue;+ expect(DEF_TYPES).toContain(t);+ }+ });+});diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.tsindex 2b39b22590..34b9433b26 100644--- a/test/chunkers/code.test.ts+++ b/test/chunkers/code.test.ts@@ -10,8 +10,8 @@ import { describe, test, expect } from 'bun:test';import { chunkCodeText, detectCodeLanguage, CHUNKER_VERSION } from '../../src/core/chunkers/code.ts';describe('CHUNKER_VERSION', () => {- test('#3821 python decorated_definition support bumped to 5', () => {- expect(CHUNKER_VERSION).toBe(5);+ test('#4511 definition-preserving merge guard bumped to 6', () => {+ expect(CHUNKER_VERSION).toBe(6);});});diff --git a/test/cjk-keyword-sql.test.ts b/test/cjk-keyword-sql.test.tsindex 0b4307e655..a54a5efd0c 100644--- a/test/cjk-keyword-sql.test.ts+++ b/test/cjk-keyword-sql.test.ts@@ -66,6 +66,28 @@ describe('buildCJKKeywordSql (#3986)', () => {expect(scalar!.params).toContain('c');});+ test('#4480: type/types/exclude_slugs filters bind as params (parity with the main keyword arm)', () => {+ const built = buildCJKKeywordSql('東京', ctx({+ opts: {+ type: 'person' as never,+ types: ['person', 'company'] as never,+ exclude_slugs: ['people/alice-example'],+ },+ }));+ expect(built!.sql).toContain('p.type = $');+ expect(built!.sql).toContain('p.type = ANY($');+ expect(built!.sql).toContain(`p.slug != ALL($`);+ expect(built!.params).toContain('person');+ expect(built!.params).toContainEqual(['person', 'company']);+ expect(built!.params).toContainEqual(['people/alice-example']);+ });++ test('#4480: no type/exclude filters → no p.type / p.slug clauses (unfiltered stays unfiltered)', () => {+ const built = buildCJKKeywordSql('東京', ctx());+ expect(built!.sql).not.toContain('p.type = $');+ expect(built!.sql).not.toContain('p.slug != ALL(');+ });+test('date/lang/symbol filters bind as params', () => {const built = buildCJKKeywordSql('東京', ctx({opts: { afterDate: '2026-01-01', beforeDate: '2026-02-01', language: 'typescript', symbolKind: 'function' },diff --git a/test/claude-code-jsonl.test.ts b/test/claude-code-jsonl.test.tsindex 184d5e999b..51e2c42b10 100644--- a/test/claude-code-jsonl.test.ts+++ b/test/claude-code-jsonl.test.ts@@ -239,3 +239,125 @@ describe('confineTranscriptPath [S3#8]', () => {expect(confineTranscriptPath(dirAsFile, { root })).toEqual({ ok: false, reason: 'not_file' });});});++describe('confineTranscriptPath — cross-OS WSL translation (#4522)', () => {+ /** Simulated automount tree: <tmp>/mnt plays /mnt; c/Users/u/.claude/projects holds the transcript. */+ function wslFixture(): { mountRoot: string; winPath: string; translated: string } {+ const base = tdir();+ const mountRoot = join(base, 'mnt');+ const proj = join(mountRoot, 'c', 'Users', 'u', '.claude', 'projects', 'proj-a');+ mkdirSync(proj, { recursive: true });+ const translated = join(proj, 'sess.jsonl');+ writeFileSync(translated, '{}\n');+ return { mountRoot, winPath: 'C:\\Users\\u\\.claude\\projects\\proj-a\\sess.jsonl', translated };+ }++ test('Windows drive literal translates and confines to its own .claude/projects tree', () => {+ const { mountRoot, winPath, translated } = wslFixture();+ // No explicit root: the default (WSL-side $HOME/.claude/projects) cannot+ // contain the Windows-home transcript — the translated tree must.+ const r = confineTranscriptPath(winPath, { wslMountRoot: mountRoot });+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.path).toBe(translated);+ expect(r.size).toBeGreaterThan(0);+ }+ });++ test('forward-slash drive literal translates too', () => {+ const { mountRoot, translated } = wslFixture();+ const r = confineTranscriptPath('C:/Users/u/.claude/projects/proj-a/sess.jsonl', {+ wslMountRoot: mountRoot,+ });+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.path).toBe(translated);+ });++ test('a Windows-literal containment root (CLAUDE_CONFIG_DIR shape, #4324) translates alongside', () => {+ const { mountRoot, winPath } = wslFixture();+ const r = confineTranscriptPath(winPath, {+ wslMountRoot: mountRoot,+ root: 'C:\\Users\\u\\.claude\\projects',+ });+ expect(r.ok).toBe(true);+ });++ test('rejects: .claude/projects tree OUTSIDE the Windows user-profile pattern (wave-g tightening)', () => {+ // The fallback root must come from the session's known config tree+ // (the Windows user-profile `<drive>:\\Users\\<u>\\.claude\\projects`),+ // never from the supplied path's own `.claude/projects` segment — an+ // attacker-controlled hook stdin under ANY such dir on a mounted drive+ // (C:\\evil\\.claude\\projects\\x.jsonl) must stay fail-closed.+ const { mountRoot } = wslFixture();+ const evilProjects = join(mountRoot, 'c', 'evil', '.claude', 'projects');+ mkdirSync(evilProjects, { recursive: true });+ writeFileSync(join(evilProjects, 'x.jsonl'), '{}\n');+ expect(+ confineTranscriptPath('C:\\evil\\.claude\\projects\\x.jsonl', { wslMountRoot: mountRoot }),+ ).toEqual({ ok: false, reason: 'outside_projects_dir' });+ });++ test('rejects: dot-dot profile segment cannot widen the derived root (wave-g tightening)', () => {+ // C:\\Users\\..\\.claude\\projects\\x.jsonl resolves to the drive root's+ // .claude tree — NOT a user profile. The profile segment must be a real+ // path component, so `..`/`.` are refused before containment ever runs.+ const { mountRoot } = wslFixture();+ const driveRootProjects = join(mountRoot, 'c', '.claude', 'projects');+ mkdirSync(driveRootProjects, { recursive: true });+ writeFileSync(join(driveRootProjects, 'x.jsonl'), '{}\n');+ expect(+ confineTranscriptPath('C:\\Users\\..\\.claude\\projects\\x.jsonl', { wslMountRoot: mountRoot }),+ ).toEqual({ ok: false, reason: 'outside_projects_dir' });+ });++ test('rejects: translated path with no .claude/projects ancestor', () => {+ const { mountRoot } = wslFixture();+ const evil = join(mountRoot, 'c', 'evil');+ mkdirSync(evil, { recursive: true });+ writeFileSync(join(evil, 'secrets.jsonl'), '{}\n');+ expect(confineTranscriptPath('C:\\evil\\secrets.jsonl', { wslMountRoot: mountRoot })).toEqual({+ ok: false,+ reason: 'outside_projects_dir',+ });+ });++ test('rejects: .. traversal escaping the derived projects root', () => {+ const { mountRoot } = wslFixture();+ // Resolves to …/.claude/secret.jsonl — outside the projects tree.+ writeFileSync(join(mountRoot, 'c', 'Users', 'u', '.claude', 'secret.jsonl'), '{}\n');+ const r = confineTranscriptPath('C:\\Users\\u\\.claude\\projects\\..\\secret.jsonl', {+ wslMountRoot: mountRoot,+ });+ expect(r).toEqual({ ok: false, reason: 'outside_projects_dir' });+ });++ test('rejects: explicit root is honored strictly — no derived-tree fallback', () => {+ const { mountRoot, winPath } = wslFixture();+ const pinned = join(tmpdir(), `gb-pinned-${process.pid}`);+ mkdirSync(pinned, { recursive: true });+ try {+ expect(confineTranscriptPath(winPath, { wslMountRoot: mountRoot, root: pinned })).toEqual({+ ok: false,+ reason: 'outside_projects_dir',+ });+ } finally {+ rmSync(pinned, { recursive: true, force: true });+ }+ });++ test('non-WSL host (mountRoot null): drive literal stays unreadable, as before', () => {+ expect(+ confineTranscriptPath('C:\\Users\\u\\.claude\\projects\\p\\s.jsonl', { wslMountRoot: null }),+ ).toEqual({ ok: false, reason: 'unreadable' });+ });++ test('translated symlink is still seen and rejected', () => {+ const { mountRoot, translated } = wslFixture();+ const dir = join(mountRoot, 'c', 'Users', 'u', '.claude', 'projects', 'proj-a');+ symlinkSync(translated, join(dir, 'link.jsonl'));+ const r = confineTranscriptPath('C:\\Users\\u\\.claude\\projects\\proj-a\\link.jsonl', {+ wslMountRoot: mountRoot,+ });+ expect(r).toEqual({ ok: false, reason: 'symlink' });+ });+});diff --git a/test/cli-op-error-status-exit.test.ts b/test/cli-op-error-status-exit.test.tsnew file mode 100644index 0000000000..81b6cb235e--- /dev/null+++ b/test/cli-op-error-status-exit.test.ts@@ -0,0 +1,99 @@+/**+ * #4488 — an op that reports failure IN-BAND (`{status: 'error'}`) must exit+ * non-zero at the CLI.+ *+ * `gbrain put <slug>` with unparseable frontmatter returned the+ * `{status:'error', error:'YAML parse failed…'}` envelope on stdout and+ * exited 0 — the page was never created, but scripts (and agents checking+ * `$?`) read it as success. The op runner only set a non-zero verdict on+ * THROW. It now inspects the normalized result: `status === 'error'` → exit+ * verdict 1 + the error echoed to stderr. No-op statuses ('skipped',+ * 'unchanged', 'created_or_updated') keep exit 0.+ *+ * Subprocess tests against a shared temp PGLite home (schema init paid once+ * in beforeAll; later spawns reuse the persisted brain).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++let home: string;++function run(args: string[], stdin?: string): { stdout: string; stderr: string; status: number } {+ const r = spawnSync('bun', ['run', 'src/cli.ts', ...args], {+ cwd: process.cwd(),+ encoding: 'utf8',+ input: stdin,+ env: {+ ...process.env,+ GBRAIN_HOME: home,+ DATABASE_URL: '',+ GBRAIN_DATABASE_URL: '',+ GBRAIN_SKIP_STARTUP_HOOKS: '1',+ },+ timeout: 240_000,+ });+ return { stdout: r.stdout ?? '', stderr: r.stderr ?? '', status: r.status ?? -1 };+}++const GOOD_PAGE = `---+type: concept+title: Good Page+---++A perfectly fine body.+`;++const BAD_YAML_PAGE = `---+title: [unclosed+type: concept+---++Body under broken frontmatter.+`;++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-4488-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ const dbPath = join(home, '.gbrain', 'brain.pglite');+ writeFileSync(+ join(home, '.gbrain', 'config.json'),+ JSON.stringify({ engine: 'pglite', database_path: dbPath }),+ );+ // Pay schema init in-process (a cold spawn can exceed spawn timeouts on a+ // loaded machine); the CLI spawns below reuse the persisted brain.+ const { createEngine } = await import('../src/core/engine-factory.ts');+ const engineConfig = { engine: 'pglite' as const, database_path: dbPath };+ const engine = await createEngine(engineConfig);+ await engine.connect(engineConfig);+ await engine.initSchema();+ await engine.disconnect();+}, 480_000);++afterAll(() => {+ rmSync(home, { recursive: true, force: true });+});++describe('#4488 in-band {status:error} → CLI exit 1', () => {+ test('put with unparseable frontmatter exits 1 and echoes the error to stderr', () => {+ const r = run(['put', 'notes/bad-yaml'], BAD_YAML_PAGE);+ expect(r.stdout).toContain('"status"');+ expect(r.stdout).toContain('error');+ // Pre-fix: exit 0 with the error envelope on stdout only.+ expect(r.status).toBe(1);+ expect(r.stderr.toLowerCase()).toContain('yaml');+ // The page really was never created.+ const get = run(['get', 'notes/bad-yaml']);+ expect(get.status).not.toBe(0);+ }, 240_000);++ test("a dedup 'skipped' put stays exit 0 (no-op is not a failure)", () => {+ const first = run(['put', 'notes/good-page'], GOOD_PAGE);+ expect(first.status).toBe(0);+ const second = run(['put', 'notes/good-page'], GOOD_PAGE);+ expect(second.status).toBe(0);+ expect(second.stdout).toContain('skipped');+ }, 480_000);+});diff --git a/test/cli-options.test.ts b/test/cli-options.test.tsindex 29cdc6bcc5..b3388bc3ee 100644--- a/test/cli-options.test.ts+++ b/test/cli-options.test.ts@@ -86,6 +86,49 @@ describe('parseGlobalFlags', () => {expect(r.cliOpts.explain).toBe(true);expect(r.rest).toEqual(['search', 'test query']);});++ // #4541 — the global claim is scoped to the search/query formatter commands.+ // Pre-fix, parseGlobalFlags claimed --explain for EVERY command, starving+ // extract (`extract --explain timeline` fell through to the WRITE-pass+ // extraction), whoknows, and onboard, which parse the flag themselves.+ test('#4541: extract keeps its own --explain (handed back in place)', () => {+ const r = parseGlobalFlags(['extract', '--explain', 'timeline']);+ expect(r.cliOpts.explain).toBe(false);+ expect(r.rest).toEqual(['extract', '--explain', 'timeline']);+ });++ test('#4541: whoknows keeps its own --explain', () => {+ const r = parseGlobalFlags(['whoknows', 'fintech compliance', '--explain']);+ expect(r.cliOpts.explain).toBe(false);+ expect(r.rest).toEqual(['whoknows', 'fintech compliance', '--explain']);+ });++ test('#4541: onboard keeps its own --explain', () => {+ const r = parseGlobalFlags(['onboard', '--check', '--explain']);+ expect(r.cliOpts.explain).toBe(false);+ expect(r.rest).toEqual(['onboard', '--check', '--explain']);+ });++ test('#4541: query still claims --explain globally', () => {+ const r = parseGlobalFlags(['query', 'who is alice-example', '--explain']);+ expect(r.cliOpts.explain).toBe(true);+ expect(r.rest).toEqual(['query', 'who is alice-example']);+ });++ test('#4541: ask (query alias) still claims --explain globally', () => {+ const r = parseGlobalFlags(['ask', 'who is alice-example', '--explain']);+ expect(r.cliOpts.explain).toBe(true);+ expect(r.rest).toEqual(['ask', 'who is alice-example']);+ });++ test('wave-g: call claims --explain — never handed into op positional args', () => {+ // `gbrain call <op>` maps leftover argv into op params; a handed-back+ // --explain would surface as an unknown-parameter error instead of+ // being ignored (the pre-#4541 global behavior).+ const r = parseGlobalFlags(['call', 'query', '--explain']);+ expect(r.cliOpts.explain).toBe(true);+ expect(r.rest).toEqual(['call', 'query']);+ });});describe('getCliOptions / setCliOptions singleton', () => {diff --git a/test/config-set.test.ts b/test/config-set.test.tsindex 1a9543fb56..b50a7ba121 100644--- a/test/config-set.test.ts+++ b/test/config-set.test.ts@@ -90,6 +90,18 @@ describe('KNOWN_CONFIG_KEYS', () => {expect(KNOWN_CONFIG_KEYS).toContain('doctor.suppress_provider_sunset');});+ test('contains the working-tree sync toggle (untracked-gap fix)', () => {+ // The drift NOTE + stderr warning both tell users to run+ // `gbrain config set sync.include_working_tree true`; the key must be+ // known or the remedy itself is rejected without --force.+ expect(KNOWN_CONFIG_KEYS).toContain('sync.include_working_tree');+ });++ test('contains the local extract-atoms knobs', () => {+ expect(KNOWN_CONFIG_KEYS).toContain('cycle.extract_atoms.page_discovery_budget');+ expect(KNOWN_CONFIG_KEYS).toContain('cycle.extract_atoms.max_source_chars');+ });+test('registers only the live conversation-parser fallback key', () => {expect(KNOWN_CONFIG_KEYS).toContain('conversation_parser.llm_fallback_enabled');expect(KNOWN_CONFIG_KEY_PREFIXES).not.toContain('conversation_parser.');diff --git a/test/confirm-prompt.test.ts b/test/confirm-prompt.test.tsindex 5172432631..daad1bf849 100644--- a/test/confirm-prompt.test.ts+++ b/test/confirm-prompt.test.ts@@ -59,3 +59,39 @@ describe('promptYesNo (#4318)', () => {expect(await p).toBe(true);});});++/**+ * pglite-repair.ts had its own inline promptYesNo (not this shared helper)+ * with the same close-before-resolve race: `rl.close()` inside the+ * rl.question callback fired the unguarded `rl.on('close', ...)` listener+ * synchronously, so `resolve(false)` won before the typed "y" resolve ran —+ * `gbrain pglite-repair` always treated an affirmative interactive answer as+ * decline. Pins the exact call now wired at that call site (question text ++ * `{ output: process.stderr }`, matching `src/commands/pglite-repair.ts`) so+ * a regression to the old inline shape — or a stdout-leaking `output`+ * default — is caught here rather than only in the generic cases above.+ */+describe('promptYesNo — pglite-repair call-site wiring (#4318 residual)', () => {+ test('"Repair now?" [y/N] question resolves true on "y", written to stderr not stdout', async () => {+ const input = new PassThrough();+ const output = new PassThrough();+ const written: string[] = [];+ output.on('data', (chunk) => written.push(chunk.toString()));++ const p = promptYesNo('Repair now? [y/N] ', { output, input });+ input.write('y\n');++ expect(await p).toBe(true);+ // The prompt text itself must have gone to the injected `output` stream+ // (which stands in for process.stderr at the real call site), not been+ // silently dropped or duplicated with a second "[y/N]" suffix.+ expect(written.join('')).toBe('Repair now? [y/N] ');+ });++ test('"Repair now?" [y/N] question resolves false on decline', async () => {+ const { input, output } = mkStreams();+ const p = promptYesNo('Repair now? [y/N] ', { output, input });+ input.write('n\n');+ expect(await p).toBe(false);+ });+});diff --git a/test/cosine-rescore-chunkless-headstart.test.ts b/test/cosine-rescore-chunkless-headstart.test.tsnew file mode 100644index 0000000000..a00ce2b5d7--- /dev/null+++ b/test/cosine-rescore-chunkless-headstart.test.ts@@ -0,0 +1,119 @@+/**+ * cosineReScore must not give a chunkless row (the synthetic+ * chunk_id=0/COALESCE row for a chunkless page, e.g. an embed_skip'd+ * oversized page — or any chunk_id whose embedding failed to hydrate) a+ * raw-scale head start over rows that got compressed onto the [0, 1.0]+ * blended scale.+ *+ * Pre-fix: `if (!chunkEmb) return r;` returned the row completely+ * untouched, so its RAW post-RRF score (on whatever scale upstream fusion+ * produced, up to ~2.0 with the compiled_truth boost) survived alongside+ * every other row's [0, 1.0]-scale blended score — a structural 2x head+ * start. Reported on #3695: a 602KB embed_skip page with an empty snippet+ * became the #1 result for 15/25 queries in a regression set, displacing+ * on-point pages, purely from this scale mismatch (not from actual+ * relevance).+ *+ * Fix: route the chunkless row through the identical blend formula with+ * cosine=0, so it's compressed onto the same scale as every other row —+ * without excluding it (which would make embed_skip pages unsearchable, a+ * different behavior change).+ */++import { describe, expect, test } from 'bun:test';+import { cosineReScore } from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { SearchResult } from '../src/core/types.ts';++function fakeEngine(embeddings: Map<number, Float32Array>): BrainEngine {+ return {+ getEmbeddingsByChunkIds: async (chunkIds: number[]) => {+ const map = new Map<number, Float32Array>();+ for (const id of chunkIds) {+ const v = embeddings.get(id);+ if (v) map.set(id, v);+ }+ return map;+ },+ } as unknown as BrainEngine;+}++function result(overrides: Partial<SearchResult> & { chunk_id: number; score: number }): SearchResult {+ return {+ slug: 'test/page',+ page_id: 1,+ title: 'Test',+ type: 'note',+ chunk_text: 'text',+ chunk_source: 'compiled_truth',+ chunk_index: 0,+ stale: false,+ ...overrides,+ } as SearchResult;+}++describe('cosineReScore — chunkless-row head start (#3695)', () => {+ test('a chunkless row (chunk_id=0, no hydratable embedding) is compressed onto the same [0,1.0] scale, not left on its raw score', async () => {+ const queryEmbedding = new Float32Array([1, 0, 0]);+ // Chunked row's embedding is orthogonal to the query — cosine=0, so its+ // blend is entirely lexical: 0.7 * normRrf.+ const chunkedEmbedding = new Float32Array([0, 1, 0]);+ const engine = fakeEngine(new Map([[42, chunkedEmbedding]]));++ // Same base (post-fusion, pre-boost) RRF score for both rows — an+ // apples-to-apples comparison of what the rescore step alone does.+ const chunklessRaw = 1.8650; // reproduces the exact #3695 reported score+ const chunkedRaw = 1.8650;++ const results: SearchResult[] = [+ result({ slug: 'chunkless/embed-skip-page', chunk_id: 0, chunk_text: '', score: chunklessRaw }),+ result({ slug: 'chunked/on-point-page', chunk_id: 42, score: chunkedRaw }),+ ];++ const rescored = await cosineReScore(engine, results, queryEmbedding, 'embedding');+ const chunkless = rescored.find(r => r.slug === 'chunkless/embed-skip-page')!;+ const chunked = rescored.find(r => r.slug === 'chunked/on-point-page')!;++ // The chunkless row must NOT retain its raw ~1.86 score — it must be+ // compressed to the blended scale, same as the chunked row.+ expect(chunkless.score).not.toBeCloseTo(chunklessRaw, 2);+ expect(chunkless.score).toBeLessThanOrEqual(1.0);+ expect(chunked.score).toBeLessThanOrEqual(1.0);++ // Both rows had identical base scores and cosine=0 (chunkless has no+ // embedding; the chunked row's embedding is orthogonal to the query) —+ // so both should land on the exact same blended score. Neither+ // structurally outranks the other from the rescore step alone.+ expect(chunkless.score).toBeCloseTo(chunked.score, 6);+ expect(chunkless.cosine).toBe(0);+ });++ test('a chunkless page with genuine lexical relevance still surfaces (not excluded)', async () => {+ const queryEmbedding = new Float32Array([1, 0, 0]);+ const engine = fakeEngine(new Map());++ const results: SearchResult[] = [+ result({ slug: 'chunkless/lexical-hit', chunk_id: 0, chunk_text: '', score: 0.9 }),+ ];++ const rescored = await cosineReScore(engine, results, queryEmbedding, 'embedding');+ expect(rescored).toHaveLength(1);+ expect(rescored[0].slug).toBe('chunkless/lexical-hit');+ expect(Number.isFinite(rescored[0].score)).toBe(true);+ });++ test('an embedded row with a genuinely relevant embedding still outranks an unrelated chunkless row', async () => {+ const queryEmbedding = new Float32Array([1, 0, 0]);+ // Perfectly aligned with the query — cosine=1.+ const relevantEmbedding = new Float32Array([1, 0, 0]);+ const engine = fakeEngine(new Map([[7, relevantEmbedding]]));++ const results: SearchResult[] = [+ result({ slug: 'chunkless/unrelated', chunk_id: 0, chunk_text: '', score: 1.8 }),+ result({ slug: 'chunked/relevant', chunk_id: 7, score: 1.8 }),+ ];++ const rescored = await cosineReScore(engine, results, queryEmbedding, 'embedding');+ expect(rescored[0].slug).toBe('chunked/relevant');+ });+});diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex 6b4fc34662..4ff1608a5b 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -65,6 +65,49 @@ describe('query-intent — suggestedModality regex (D6 + D14)', () => {}});+describe('query-intent — suggestedModality is multilingual (CJK)', () => {+ // Discrimination: `\b` is an ASCII word boundary, so the English bank can+ // never match a Han/Kana query. Every positive below returns 'text' against+ // the English-only patterns.+ const cjkImagePhrasings = [+ '找一下那张蓝色羽绒服的照片', // verb + measure word + 的 + 照片+ '小花笑的图片', // 的 + 图片+ '那张截图', // measure word + 截图+ '搜索去年的相片', // verb + 的 + 相片+ '找一下蓝色羽绒服照片', // verb-initial, no possessive+ '这件衣服长什么样', // "what does X look like"+ '幫我找那張截圖', // traditional Chinese+ '猫の写真を見せて', // Japanese, particle の+ '画像を探して', // Japanese, verb-final+ ];++ for (const query of cjkImagePhrasings) {+ test(`CJK image phrasing: "${query}" → image`, () => {+ expect(classifyQuery(query).suggestedModality).toBe('image');+ });+ }++ const cjkTextPhrasings = [+ '图书馆的开放时间', // 图书馆 is not a visual noun+ '图片压缩算法的原理', // visual noun with no request structure around it+ '截图', // bare visual noun — parity with bare "screenshot"+ '这个项目的进展',+ '影像科的报告在哪', // 影像科 is a department, not a request for images+ '写真集の出版年', // Japanese, no request verb+ ];++ for (const query of cjkTextPhrasings) {+ test(`CJK text phrasing: "${query}" → text`, () => {+ expect(classifyQuery(query).suggestedModality).toBe('text');+ });+ }++ test('English classification is unchanged by the CJK bank', () => {+ expect(classifyQuery('show me photos of acme').suggestedModality).toBe('image');+ expect(classifyQuery('who is acme corp').suggestedModality).toBe('text');+ });+});+describe('isAmbiguousModalityQuery (Commit 4 prep)', () => {// Genuinely ambiguous = visual noun present + reference marker present BUT// CROSS_MODAL_PATTERNS doesn't catch it (otherwise regex already classified@@ -136,7 +179,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 23 (cross-modal still appended; 20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch; 22→23 excludePrivate posture fold #4352)', () => {+ test('KNOBS_HASH_VERSION is 26 (cross-modal still appended; 20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.@@ -161,7 +204,11 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {// status alter stored rows for identical knobs.// 22→23 (#4352 follow-up): private-visibility posture fold (xp=) —// replaces the wholesale cache skip for excludePrivate=true callers.- expect(KNOBS_HASH_VERSION).toBe(23);+ // 23→24 (#4358 residual): negative-offset requests could read/write the+ // same cache row an offset=0 request shares.+ // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).+ expect(KNOBS_HASH_VERSION).toBe(26);});test('flipping unified_multimodal changes the hash', () => {diff --git a/test/cycle-summary-file-write.test.ts b/test/cycle-summary-file-write.test.tsnew file mode 100644index 0000000000..3061b08d91--- /dev/null+++ b/test/cycle-summary-file-write.test.ts@@ -0,0 +1,101 @@+/**+ * #4506 — the dream cycle-summary dual-write into <brainDir> dirtied clean+ * source repos (an untracked dream-cycle-summaries/<date>.md after every+ * nightly run) with no opt-out. Pinned here:+ * - default stays the dual-write (back-compat): DB row + file;+ * - `dream.synthesize.summary_file_write=false` keeps the DB row and+ * skips the file;+ * - a gbrain.yml storage tier declaring the summary path `db_only`+ * suppresses the file write too (the DB/file-plane split covers it).+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { existsSync, 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 { resetPgliteState } from './helpers/reset-pglite.ts';+import { __testing } from '../src/core/cycle/synthesize.ts';++const { writeSummaryPage } = __testing;++let engine: PGLiteEngine;+let brainDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 300_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++beforeEach(async () => {+ await resetPgliteState(engine);+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-4506-'));+});++const SLUG = 'dream-cycle-summaries/2026-08-22';++async function runWrite(): Promise<void> {+ await writeSummaryPage(+ engine, brainDir, SLUG, '2026-08-22',+ ['wiki/some/page'], [{ jobId: 1, status: 'completed' }], 'default',+ );+}++async function dbRowExists(): Promise<boolean> {+ const page = await engine.getPage(SLUG, { sourceId: 'default' });+ return page !== null;+}++describe('#4506 — summary file-write opt-out', () => {+ test('default: dual-write (DB row + file) — back-compat', async () => {+ await runWrite();+ expect(await dbRowExists()).toBe(true);+ expect(existsSync(join(brainDir, `${SLUG}.md`))).toBe(true);+ });++ test('dream.synthesize.summary_file_write=false: DB row only, repo stays clean', async () => {+ await engine.setConfig('dream.synthesize.summary_file_write', 'false');+ await runWrite();+ expect(await dbRowExists()).toBe(true);+ expect(existsSync(join(brainDir, `${SLUG}.md`))).toBe(false);+ expect(existsSync(join(brainDir, 'dream-cycle-summaries'))).toBe(false);+ });++ test("'off' and '0' spellings suppress too", async () => {+ for (const v of ['off', '0']) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-4506-v-'));+ try {+ await engine.setConfig('dream.synthesize.summary_file_write', v);+ await writeSummaryPage(engine, dir, SLUG, '2026-08-22', [], [], 'default');+ expect(existsSync(join(dir, `${SLUG}.md`))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ }+ });++ test('gbrain.yml db_only tier covering the summary path suppresses the file write', async () => {+ writeFileSync(+ join(brainDir, 'gbrain.yml'),+ 'storage:\n db_only:\n - dream-cycle-summaries\n',+ 'utf8',+ );+ await runWrite();+ expect(await dbRowExists()).toBe(true);+ expect(existsSync(join(brainDir, `${SLUG}.md`))).toBe(false);+ });++ test('gbrain.yml with an unrelated db_only tier keeps the dual-write', async () => {+ writeFileSync(+ join(brainDir, 'gbrain.yml'),+ 'storage:\n db_only:\n - atoms\n',+ 'utf8',+ );+ await runWrite();+ expect(existsSync(join(brainDir, `${SLUG}.md`))).toBe(true);+ });+});diff --git a/test/cycle/cycle-sync-uncommitted-warn.serial.test.ts b/test/cycle/cycle-sync-uncommitted-warn.serial.test.tsnew file mode 100644index 0000000000..882e43688a--- /dev/null+++ b/test/cycle/cycle-sync-uncommitted-warn.serial.test.ts@@ -0,0 +1,72 @@+/**+ * Untracked-gap fix — cycle-level mapping of SyncResult.uncommitted.+ *+ * A nightly dream/cycle over a dirty vault used to report a clean 'ok +0'+ * sync phase while uncommitted files sat invisible to commit-driven sync.+ * runPhaseSync must now surface working-tree drift as status 'warn' with the+ * drift note in the summary and `details.uncommitted` populated — and keep+ * the clean-run mapping at 'ok' when no drift is reported.+ *+ * Follows the test/core/cycle.serial.test.ts convention: performSync is+ * mocked module-level; runCycle runs against a real PGLite engine for locks.+ */++import { describe, test, expect, mock, beforeAll, afterAll } from 'bun:test';++let uncommitted: { added: number; modified: number; deleted: number } | undefined;++mock.module('../../src/commands/sync.ts', () => ({+ performSync: async () => ({+ status: 'synced',+ fromCommit: 'abcd',+ toCommit: 'efgh',+ added: 2,+ modified: 1,+ deleted: 0,+ renamed: 0,+ chunksCreated: 4,+ embedded: 0,+ pagesAffected: ['a'],+ ...(uncommitted ? { uncommitted } : {}),+ }),+ runSync: async () => {},+ buildSyncManifest: () => ({ added: [], modified: [], deleted: [], renamed: [] }),+ isSyncable: () => true,+ pathToSlug: (s: string) => s,+}));++const { runCycle } = await import('../../src/core/cycle.ts');+const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');++let engine: InstanceType<typeof PGLiteEngine>;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++describe('runCycle sync phase — uncommitted working-tree drift', () => {+ test("drift maps to 'warn' + summary note + details.uncommitted; clean run stays 'ok'", async () => {+ // Clean run first: no uncommitted field → 'ok', no drift note.+ uncommitted = undefined;+ const clean = await runCycle(engine, { brainDir: '/tmp/brain', phases: ['sync'] });+ const cleanPhase = clean.phases.find(p => p.phase === 'sync');+ expect(cleanPhase?.status).toBe('ok');+ expect(cleanPhase?.summary).not.toContain('uncommitted');+ expect(cleanPhase?.details.uncommitted).toBeUndefined();++ // Dirty vault: uncommitted drift present → 'warn' + note + details.+ uncommitted = { added: 2, modified: 1, deleted: 0 };+ const dirty = await runCycle(engine, { brainDir: '/tmp/brain', phases: ['sync'] });+ const dirtyPhase = dirty.phases.find(p => p.phase === 'sync');+ expect(dirtyPhase?.status).toBe('warn');+ expect(dirtyPhase?.summary).toContain('3 uncommitted file(s)');+ expect(dirtyPhase?.summary).toContain('sync.include_working_tree');+ expect(dirtyPhase?.details.uncommitted).toEqual({ added: 2, modified: 1, deleted: 0 });+ }, 60_000);+});diff --git a/test/cycle/extract-atoms-config-caps.test.ts b/test/cycle/extract-atoms-config-caps.test.tsnew file mode 100644index 0000000000..3ce5fdc2f6--- /dev/null+++ b/test/cycle/extract-atoms-config-caps.test.ts@@ -0,0 +1,135 @@+// #4540 — extract_atoms per-item caps are configurable.+//+// Before the fix the work loop hardcoded `item.content.slice(0, 50_000)` and+// `maxTokens: 4096`. Operators running the phase against small-context or+// thinking models could not shrink/grow either without a code change, and+// the raw .slice() could split a UTF-8 surrogate pair at the boundary.+//+// The fix reads cycle.extract_atoms.max_input_chars /+// cycle.extract_atoms.max_output_tokens at the same engine.getConfig seam as+// cycle.extract_atoms.budget_usd (defaults unchanged), cuts with+// truncateUtf8, and adds an optional cycle.extract_atoms.pacing_ms sleep.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import {+ runPhaseExtractAtoms,+ DEFAULT_EXTRACT_MAX_INPUT_CHARS,+ DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS,+} 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 captureChat(): { calls: ChatOpts[]; chat: (o: ChatOpts) => Promise<ChatResult> } {+ const calls: ChatOpts[] = [];+ return {+ calls,+ chat: async (o: ChatOpts) => {+ calls.push(o);+ return {+ text: '[]',+ blocks: [{ type: 'text', text: '[]' }],+ stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5',+ providerId: 'anthropic',+ };+ },+ };+}++function userContent(o: ChatOpts): string {+ const m = o.messages[o.messages.length - 1];+ return typeof m.content === 'string' ? m.content : JSON.stringify(m.content);+}++describe('extract_atoms configurable caps (#4540)', () => {+ test('defaults unchanged: 50k input chars, 4096 output tokens', async () => {+ const { calls, chat } = captureChat();+ const big = 'x'.repeat(DEFAULT_EXTRACT_MAX_INPUT_CHARS + 5_000);+ await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [{ filePath: '/tmp/t1.txt', content: big, contentHash: 'h1'.repeat(8) }],+ _pages: [],+ _chat: chat,+ });+ expect(calls.length).toBe(1);+ expect(calls[0].maxTokens).toBe(DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS);+ const content = userContent(calls[0]);+ // Body is prefix + truncated content: the 55k payload was cut to 50k.+ expect(content.length).toBeLessThan(DEFAULT_EXTRACT_MAX_INPUT_CHARS + 200);+ expect(content.length).toBeGreaterThanOrEqual(DEFAULT_EXTRACT_MAX_INPUT_CHARS);+ });++ test('cycle.extract_atoms.max_input_chars / .max_output_tokens are honored', async () => {+ await engine.setConfig('cycle.extract_atoms.max_input_chars', '2000');+ await engine.setConfig('cycle.extract_atoms.max_output_tokens', '512');+ const { calls, chat } = captureChat();+ const big = 'y'.repeat(10_000);+ await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [{ filePath: '/tmp/t2.txt', content: big, contentHash: 'h2'.repeat(8) }],+ _pages: [],+ _chat: chat,+ });+ expect(calls.length).toBe(1);+ expect(calls[0].maxTokens).toBe(512);+ const content = userContent(calls[0]);+ // 2000 content chars + the small "Source: ..." preamble.+ expect(content.length).toBeLessThan(2_200);+ expect(content).toContain('y'.repeat(2_000));+ expect(content).not.toContain('y'.repeat(2_001));+ });++ test('garbage/too-small values fall back to defaults (floors)', async () => {+ await engine.setConfig('cycle.extract_atoms.max_input_chars', '10'); // below 1000 floor+ await engine.setConfig('cycle.extract_atoms.max_output_tokens', 'not-a-number');+ const { calls, chat } = captureChat();+ await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [{ filePath: '/tmp/t3.txt', content: 'z'.repeat(3_000), contentHash: 'h3'.repeat(8) }],+ _pages: [],+ _chat: chat,+ });+ expect(calls.length).toBe(1);+ expect(calls[0].maxTokens).toBe(DEFAULT_EXTRACT_MAX_OUTPUT_TOKENS);+ // Content not truncated to 10 chars — the floor rejected the value.+ expect(userContent(calls[0])).toContain('z'.repeat(3_000));+ });++ test('input cap cuts UTF-8 safely (no lone surrogate at the boundary)', async () => {+ await engine.setConfig('cycle.extract_atoms.max_input_chars', '2001');+ const { calls, chat } = captureChat();+ // Astral chars (2 UTF-16 units each): an odd cap on this content would+ // split a pair if the cut were a bare .slice().+ const astral = '😀'.repeat(2_000);+ await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [{ filePath: '/tmp/t4.txt', content: astral, contentHash: 'h4'.repeat(8) }],+ _pages: [],+ _chat: chat,+ });+ expect(calls.length).toBe(1);+ const content = userContent(calls[0]);+ // Round-tripping through UTF-8 replaces lone surrogates with U+FFFD;+ // well-formed content survives unchanged.+ const roundTripped = new TextDecoder().decode(new TextEncoder().encode(content));+ expect(roundTripped).toBe(content);+ });+});diff --git a/test/cycle/synthesize-concepts-source-scope.test.ts b/test/cycle/synthesize-concepts-source-scope.test.tsnew file mode 100644index 0000000000..ddf1ac7bce--- /dev/null+++ b/test/cycle/synthesize-concepts-source-scope.test.ts@@ -0,0 +1,91 @@+// #4416 — synthesize_concepts must thread the cycle's resolved source+// (opts.sourceId) into its page/receipt/rollup writes. (Fix adopted from the+// open PR #4417 by its reporter.)+//+// Before the fix the phase wrote concept pages via importFromContent with no+// sourceId and hardcoded source_id: 'default' into the receipt + rollup.+// Every write in that path substitutes the literal 'default' when sourceId+// is undefined, so on a brain whose content lives in a source not named+// 'default' (the one-brain-one-source layout in+// docs/architecture/brains-and-sources.md) every synthesized concept page+// silently lands under the seeded 'default' source instead of the cycle's+// source — wrong provenance, invisible to source-scoped reads.++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';++let engine: PGLiteEngine;++// Generous hook timeouts: PGLite WASM cold-start + initSchema can exceed the+// 60s default on loaded CI/dev hosts.+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 240000);++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('personal', 'Personal') ON CONFLICT (id) DO NOTHING`,+ [],+ );+}, 120000);++// Two atoms sharing one concept ref → deterministic-tier narrative, no LLM.+const atoms = [+ { slug: 'a1', title: 'A1', body: 'b1', concept_refs: ['theme'] },+ { slug: 'a2', title: 'A2', body: 'b2', concept_refs: ['theme'] },+];++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 () => {+ const first = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'personal' });+ expect(first.status).toBe('ok');++ const pages = await engine.executeRaw<{ source_id: string }>(+ `SELECT source_id FROM pages WHERE slug = 'concepts/theme'`,+ [],+ );+ expect(pages.length).toBe(1);+ expect(pages[0].source_id).toBe('personal');++ // Update path: importFromContent finds the existing page, then the+ // version write must target the page's REAL source. Pre-fix this path+ // targeted (source=default) and failed on a brain without that source.+ const second = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, sourceId: 'personal' });+ expect(second.status).toBe('ok');++ const rollup = await engine.executeRaw<{ source_id: string }>(+ `SELECT source_id FROM extract_rollup_7d WHERE kind = 'concepts'`,+ [],+ );+ expect(rollup.length).toBeGreaterThan(0);+ expect(rollup.every((r) => r.source_id === 'personal')).toBe(true);+ }, 120000);++ test('omitting sourceId keeps the legacy default fallback', async () => {+ const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms });+ expect(result.status).toBe('ok');++ const pages = await engine.executeRaw<{ source_id: string }>(+ `SELECT source_id FROM pages WHERE slug = 'concepts/theme'`,+ [],+ );+ expect(pages.length).toBe(1);+ expect(pages[0].source_id).toBe('default');++ const rollup = await engine.executeRaw<{ source_id: string }>(+ `SELECT source_id FROM extract_rollup_7d WHERE kind = 'concepts'`,+ [],+ );+ expect(rollup.length).toBeGreaterThan(0);+ expect(rollup.every((r) => r.source_id === 'default')).toBe(true);+ }, 120000);+});diff --git a/test/detached-stderr.test.ts b/test/detached-stderr.test.tsnew file mode 100644index 0000000000..d4f10cd0b4--- /dev/null+++ b/test/detached-stderr.test.ts@@ -0,0 +1,90 @@+/**+ * #4418 — `jobs supervisor start --detach` must not inherit the invoker's+ * stderr.+ *+ * The detach path re-exec'd the supervisor with+ * stdio ['ignore','ignore','inherit']; the worker then inherited that same+ * descriptor via ChildWorkerSupervisor's stdio 'inherit'. When a short-lived+ * automation runner closed its capture pipe, the worker exited 141 (SIGPIPE)+ * on its next stderr write and the supervisor's crash/backoff logging could+ * kill it too — stale jobs + locks while producers kept enqueueing. Pins:+ *+ * 1. the sink prefers a durable append-mode log in the audit dir+ * (GBRAIN_AUDIT_DIR honored) and the fd is actually writable;+ * 2. an unusable audit dir falls back to the null device — never 'inherit';+ * 3. the jobs.ts detach branch routes through spawnDetachedSupervisor and+ * no longer passes stderr 'inherit' (source pin — the branch needs a+ * live Postgres supervisor to exercise end-to-end).+ */+import { describe, test, expect } from 'bun:test';+import { mkdtempSync, writeFileSync, readFileSync, rmSync, writeSync, closeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import {+ openDetachedStderrSink,+ closeDetachedStderrSink,+} from '../src/core/minions/detached-stderr.ts';++describe('openDetachedStderrSink (#4418)', () => {+ test('opens a durable append-mode log in the audit dir (GBRAIN_AUDIT_DIR honored)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gb-detached-stderr-'));+ try {+ await withEnv({ GBRAIN_AUDIT_DIR: dir }, async () => {+ const sink = openDetachedStderrSink();+ expect(typeof sink.fd).toBe('number');+ expect(sink.path).toBe(join(dir, 'supervisor-stderr.log'));+ // The fd is genuinely writable — the property that keeps the+ // supervisor + worker alive after the invoker's pipe closes.+ writeSync(sink.fd as number, 'worker lifecycle line\n');+ closeDetachedStderrSink(sink);+ expect(readFileSync(sink.path!, 'utf-8')).toContain('worker lifecycle line');+ // Append mode: a second open must not truncate the first write.+ const sink2 = openDetachedStderrSink();+ closeDetachedStderrSink(sink2);+ expect(readFileSync(sink.path!, 'utf-8')).toContain('worker lifecycle line');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('unusable audit dir falls back to the null device — never inherit', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gb-detached-stderr-bad-'));+ try {+ // Point the audit dir UNDER a regular file so mkdir fails.+ const blocker = join(dir, 'blocker');+ writeFileSync(blocker, 'not a dir', 'utf-8');+ await withEnv({ GBRAIN_AUDIT_DIR: join(blocker, 'nested') }, async () => {+ const sink = openDetachedStderrSink();+ expect(typeof sink.fd).toBe('number');+ expect(sink.path === '/dev/null' || sink.path === '\\\\.\\NUL').toBe(true);+ closeDetachedStderrSink(sink);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('closeDetachedStderrSink is idempotent and ignore-safe', () => {+ closeDetachedStderrSink({ fd: 'ignore', path: null });+ const sink = openDetachedStderrSink();+ closeDetachedStderrSink(sink);+ closeDetachedStderrSink(sink); // double-close swallowed+ });+});++describe('jobs.ts detach branch (source pin, #4418)', () => {+ const jobsSource = readFileSync(+ join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),+ 'utf-8',+ );++ test('the detach spawn routes through spawnDetachedSupervisor', () => {+ expect(jobsSource).toContain('spawnDetachedSupervisor');+ });++ test("no spawn in jobs.ts hands the detached child an 'inherit' stderr", () => {+ expect(jobsSource).not.toContain("stdio: ['ignore', 'ignore', 'inherit']");+ });+});diff --git a/test/doctor-behavioral.test.ts b/test/doctor-behavioral.test.tsindex 896d57e3c5..69752a06c1 100644--- a/test/doctor-behavioral.test.ts+++ b/test/doctor-behavioral.test.ts@@ -28,6 +28,7 @@ import {computeDoctorReport,type Check,} from '../src/commands/doctor.ts';+import { buildEmbedSkipMarker } from '../src/core/embed-skip.ts';let engine: PGLiteEngine;@@ -242,6 +243,63 @@ describe('buildChecks — orchestrator against PGLite', () => {}});+ test('oversized_pages excludes pages that already took the embed_skip remediation (gbrain dogfooding find)', async () => {+ // The warn message for this check says "existing oversized pages can be+ // ... accepted as non-embeddable" (i.e. frontmatter.embed_skip set).+ // Before this fix the underlying query never excluded those pages, so a+ // page an operator had already remediated the documented way kept+ // re-appearing in this check's output on every run with no way to clear+ // it short of deleting the page. Uses the real production marker shape+ // (an object from buildEmbedSkipMarker, not a bare boolean) — the+ // canonical writer (src/core/content-sanity.ts) never writes a boolean,+ // and the exclusion must match what actually lands in frontmatter.+ const big = 'oversized page body prose for the embed_skip exclusion probe. '.repeat(11_000);+ await engine.putPage('wiki/oversized-embed-skip-probe', {+ type: 'note',+ title: 'Oversized Embed-Skip Probe',+ compiled_truth: big,+ timeline: '',+ frontmatter: { embed_skip: buildEmbedSkipMarker(big.length) },+ });++ const checks = await buildChecks(engine, []);+ const oversized = checks.find(c => c.name === 'oversized_pages');+ expect(oversized).toBeDefined();+ // Positive control above (line ~227) proves the same byte count without+ // embed_skip DOES warn and names the page — this proves the ONLY+ // difference (embed_skip set) is what excludes it.+ expect(oversized!.status).toBe('ok');+ expect(oversized!.message).not.toContain('oversized-embed-skip-probe');+ });++ test('oversized_pages still warns when embed_skip is absent (does not exclude every page)', async () => {+ // Sibling positive control to the exclusion test above: a page with no+ // embed_skip key at all must still warn, proving the exclusion is+ // scoped to the marker's presence and isn't a query regression that+ // silently stops counting oversized pages altogether.+ //+ // Note: per the canonical contract in src/core/embed-skip.ts+ // (isEmbedSkipped: "any non-null value" is skip, by design — the+ // predicate is key-EXISTENCE, not a boolean value check), an explicit+ // `embed_skip: false` is ALSO treated as skip, matching every other+ // embed-skip consumer in the codebase (embed.ts, postgres-engine.ts,+ // pglite-engine.ts). This check must stay consistent with that shared+ // contract rather than inventing its own true/false semantics.+ const big = 'oversized page body prose for the embed_skip-absent probe. '.repeat(11_000);+ await engine.putPage('wiki/oversized-embed-skip-absent-probe', {+ type: 'note',+ title: 'Oversized Embed-Skip-Absent Probe',+ compiled_truth: big,+ timeline: '',+ });++ const checks = await buildChecks(engine, []);+ const oversized = checks.find(c => c.name === 'oversized_pages');+ expect(oversized).toBeDefined();+ expect(oversized!.status).toBe('warn');+ expect(oversized!.message).toContain('oversized-embed-skip-absent-probe');+ });+test('mixed-outcome render path: synthesized checks aggregate as expected', () => {// The orchestrator's render path (outputResults in the wrapper) reads// the same DoctorReport.status enum we compute here. Pin thediff --git a/test/doctor-drift-advice.test.ts b/test/doctor-drift-advice.test.tsindex b00397a471..26f8ae3aee 100644--- a/test/doctor-drift-advice.test.ts+++ b/test/doctor-drift-advice.test.ts@@ -30,4 +30,18 @@ describe('#1123 — multiSourceDriftAdvice references only real surfaces', () =>expect(advice).toContain('GBRAIN_SOURCE=default gbrain delete <slug>');expect(advice).not.toContain('delete --source');});++ // #4490: the advice used to name only two causes, then recommend a delete.+ // The third cause — the file behind the slug is not git-tracked, so the+ // recommended re-sync imports NOTHING for it and the operator lands on the+ // delete step against a row nothing will recreate — must be named, along+ // with the sync flag that covers it, BEFORE the delete recommendation.+ test('#4490: names the untracked-file cause and --include-gitignored before the delete step', () => {+ expect(advice).toContain('--include-gitignored');+ expect(advice.toLowerCase()).toContain('not git-tracked');+ const flagIdx = advice.indexOf('--include-gitignored');+ const deleteIdx = advice.indexOf('gbrain delete <slug>');+ expect(flagIdx).toBeGreaterThan(-1);+ expect(deleteIdx).toBeGreaterThan(flagIdx);+ });});diff --git a/test/doctor-federation-health.test.ts b/test/doctor-federation-health.test.tsindex 71a808fd82..13f3d9db74 100644--- a/test/doctor-federation-health.test.ts+++ b/test/doctor-federation-health.test.ts@@ -7,11 +7,13 @@* fail — lag > 24h, OR coverage < 50% with chunks > 1000*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { configureGateway } from '../src/core/ai/gateway.ts';import { checkFederationHealth } from '../src/commands/doctor.ts';let engine: PGLiteEngine;+let workerBackedEngine: BrainEngine;beforeAll(async () => {// Pin the legacy OpenAI/1536 embedding shape BEFORE initSchema builds the@@ -29,6 +31,13 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ workerBackedEngine = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;}, 30000);afterAll(async () => {@@ -102,7 +111,11 @@ describe('checkFederationHealth', () => {expect(check.status).toBe('warn');expect(check.message).toContain('uncovered');expect(check.message).toContain('embed coverage');- expect(check.message).toContain('gbrain jobs submit embed-backfill');+ expect(check.message).toContain('gbrain embed --stale --source uncovered');+ expect(check.message).not.toContain('gbrain jobs submit embed-backfill');++ const workerBackedCheck = await checkFederationHealth(workerBackedEngine);+ expect(workerBackedCheck.message).toContain('gbrain jobs submit embed-backfill');});test('synced + zero pages → ok (vacuous truth, no coverage warn)', async () => {diff --git a/test/doctor-schema-column-diff.test.ts b/test/doctor-schema-column-diff.test.tsnew file mode 100644index 0000000000..f07b9d1025--- /dev/null+++ b/test/doctor-schema-column-diff.test.ts@@ -0,0 +1,66 @@+/**+ * #4421 — doctor's schema_version check compared ONLY the ledger counter+ * (config.version vs LATEST_VERSION). A PgBouncer transaction-mode pooler+ * can swallow an ALTER TABLE while the migration runner still advances the+ * counter, leaving doctor green over a physically narrower table — the+ * exact drift schema-verify.ts exists to catch, except doctor never called+ * it. Doctor now runs a READ-ONLY column diff (`detectMissingColumns`, the+ * detection half of verifySchema with no self-heal) and downgrades+ * schema_version to warn naming the missing columns + the+ * `gbrain init --migrate-only` hint.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { detectMissingColumns } from '../src/core/schema-verify.ts';+import { doctorFileSource } from './helpers/doctor-source.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++describe('detectMissingColumns (#4421)', () => {+ test('freshly-initialized schema has no missing columns', async () => {+ const diff = await detectMissingColumns(engine);+ expect(diff.checked).toBeGreaterThan(50);+ expect(diff.missing).toEqual([]);+ });++ test('a dropped column is detected read-only (no self-heal)', async () => {+ await engine.executeRaw('ALTER TABLE pages DROP COLUMN import_filename');+ try {+ const diff = await detectMissingColumns(engine);+ expect(diff.missing).toContainEqual({ table: 'pages', column: 'import_filename' });+ // READ-ONLY contract: a second diff still sees it missing — nothing+ // was healed behind the caller's back.+ const again = await detectMissingColumns(engine);+ expect(again.missing).toContainEqual({ table: 'pages', column: 'import_filename' });+ } finally {+ await engine.executeRaw('ALTER TABLE pages ADD COLUMN IF NOT EXISTS import_filename TEXT');+ }+ });+});++describe('doctor schema_version wires the column diff (#4421)', () => {+ // Positional source guard (doctor-source helper pattern): the ledger-ok+ // branch must consult detectMissingColumns BEFORE pushing its ok check, and+ // the warn message must carry the migrate-only hint.+ test('ledger-ok branch calls detectMissingColumns and hints init --migrate-only', () => {+ const src = doctorFileSource('doctor.ts');+ const diffIdx = src.indexOf('detectMissingColumns');+ expect(diffIdx).toBeGreaterThan(-1);+ expect(src).toContain('gbrain init --migrate-only');+ // The diff arm lives inside the schema_version ledger-current branch.+ const anchor = src.indexOf('schemaVersion >= LATEST_VERSION');+ expect(anchor).toBeGreaterThan(-1);+ expect(diffIdx).toBeGreaterThan(anchor);+ });+});diff --git a/test/doctor-schema-version-forward-skew.test.ts b/test/doctor-schema-version-forward-skew.test.tsnew file mode 100644index 0000000000..ffd9ae216b--- /dev/null+++ b/test/doctor-schema-version-forward-skew.test.ts@@ -0,0 +1,70 @@+/**+ * `schema_version` must not report `ok` when the DB is AHEAD of this+ * client's LATEST_VERSION (forward skew). On a multi-node brain (hub ++ * spokes sharing one Postgres), a spoke whose checkout is older than the+ * hub sees `schema_version: ok — Version 111 (latest: 80)` — the old+ * client silently reads/writes tables, columns, and indexes it doesn't+ * know about. Forward skew is more dangerous than backward skew (pending+ * migrations at least block on the next `apply-migrations`), so it must+ * not report a friendlier status than the pending-migrations case.+ *+ * Reported on #2036: a 31-version skew hid for weeks on a real mesh, found+ * only by reading the "Version N (latest: M)" message by eye.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { buildChecks } from '../src/commands/doctor.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+});++describe('schema_version — forward skew (#2036)', () => {+ test('warns, not oks, when the DB version is ahead of this client\'s latest known version', async () => {+ await engine.setConfig('version', String(LATEST_VERSION + 31));++ const checks = await buildChecks(engine, [], undefined);+ const schemaCheck = checks.find((c) => c.name === 'schema_version');++ expect(schemaCheck).toBeDefined();+ expect(schemaCheck?.status).toBe('warn');+ expect(schemaCheck?.message).toContain('AHEAD');+ expect(schemaCheck?.message).toContain(String(LATEST_VERSION + 31));+ expect(schemaCheck?.message).toContain(String(LATEST_VERSION));+ });++ test('still oks when the DB version exactly matches latest', async () => {+ await engine.setConfig('version', String(LATEST_VERSION));++ const checks = await buildChecks(engine, [], undefined);+ const schemaCheck = checks.find((c) => c.name === 'schema_version');++ expect(schemaCheck?.status).toBe('ok');+ expect(schemaCheck?.message).toBe(`Version ${LATEST_VERSION} (latest: ${LATEST_VERSION})`);+ });++ test('still warns (unchanged) when the DB version is behind latest (pending migrations)', async () => {+ await engine.setConfig('version', String(LATEST_VERSION - 1));++ const checks = await buildChecks(engine, [], undefined);+ const schemaCheck = checks.find((c) => c.name === 'schema_version');++ expect(schemaCheck?.status).toBe('warn');+ expect(schemaCheck?.message).toContain('apply-migrations');+ });+});diff --git a/test/doctor-silent-death-checks.test.ts b/test/doctor-silent-death-checks.test.tsindex 9de469ae80..850493d86c 100644--- a/test/doctor-silent-death-checks.test.ts+++ b/test/doctor-silent-death-checks.test.ts@@ -243,6 +243,62 @@ describe('undeclared_db_only_pages (#2784)', () => {expect(c.status).toBe('ok');});+ // #3766 — a `storage.db_only` prefix typed with any uppercase (a plausible+ // authoring choice — nothing in gbrain.yml's schema requires lowercase)+ // used to never match, because page slugs are ALWAYS lowercased at write+ // time (pathToSlug/slugifyCodePath) regardless of the host filesystem's+ // case sensitivity, while the declared prefix was compared verbatim. Every+ // page under the declared directory was falsely flagged undeclared.+ test('declared db_only prefix with different case still matches the (always-lowercase) slug', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_only:\n - Notes/\n');+ await addSource('src-a', repo);+ await addPage('notes/db-resident', { sourceId: 'src-a' });+ const c = await checkUndeclaredDbOnlyPages(engine);+ expect(c.status).toBe('ok');+ });++ // False-negative guard for the fix above: a case-insensitive prefix match+ // must not become a blanket "everything is covered" match. A page under an+ // UNRELATED directory in the same source (with the same mixed-case+ // declaration active) must still be flagged exactly as before.+ test('mixed-case declared prefix does not swallow pages under an unrelated directory', async () => {+ const repo = makeRepo();+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_only:\n - Notes/\n');+ await addSource('src-a', repo);+ await addPage('notes/db-resident', { sourceId: 'src-a' });+ await addPage('people/ghost-page', { sourceId: 'src-a' });+ const c = await checkUndeclaredDbOnlyPages(engine);+ expect(c.status).toBe('warn');+ expect(c.message).toContain('people/ghost-page');+ expect(c.message).not.toContain('notes/db-resident');+ expect((c.details as any).total).toBe(1);+ });++ // #3766 literal repro check: the reporter's symptom (a code source+ // indexing a Next.js App Router repo — bracketed dynamic-route+ // directories, camelCase filenames — got 225/254 pages falsely flagged).+ // Code pages (`page_kind: 'code'`) use a different, non-lossy slug scheme+ // (`slugifyCodePath`, which — unlike the markdown slugifier — intentionally+ // keeps framework paths like `app/[id]/page.tsx` indexable) and this check+ // scopes its SQL to `page_kind = 'markdown'` only, so no code page can ever+ // reach this check's matching logic in the first place. Locks in current+ // (already-correct) behavior against regression.+ test('#3766 repro: bracket-route + camelCase code page is never considered (page_kind=code out of scope)', async () => {+ const repo = makeRepo();+ mkdirSync(join(repo, 'app', 'shop', '[id]'), { recursive: true });+ writeFileSync(join(repo, 'app', 'shop', '[id]', 'page.tsx'), 'export default function Page() {}');+ mkdirSync(join(repo, 'components'), { recursive: true });+ writeFileSync(join(repo, 'components', 'ArchiveButton.tsx'), 'export function ArchiveButton() {}');+ await addSource('src-a', repo);+ // Slugs mirror what slugifyCodePath('app/shop/[id]/page.tsx') /+ // slugifyCodePath('components/ArchiveButton.tsx') actually produce.+ await addPage('app-shop-id-page-tsx', { sourceId: 'src-a', pageKind: 'code' });+ await addPage('components-archivebutton-tsx', { sourceId: 'src-a', pageKind: 'code' });+ const c = await checkUndeclaredDbOnlyPages(engine);+ expect(c.status).toBe('ok');+ });+test('page with no backing file outside every db_only path → warn with sample + fix', async () => {const repo = makeRepo();await addSource('src-a', repo);@@ -311,6 +367,20 @@ describe('undeclared_db_only_pages (#2784)', () => {expect(dirs).toContain('notes/');for (const d of DERIVE_PHASE_DB_ONLY_DEFAULTS) expect(dirs).toContain(d);});++ // #3766 — declared prefixes are lowercased before the union, since the+ // only consumer (checkUndeclaredDbOnlyPages) matches them against+ // always-lowercase page slugs. A mixed-case declaration still dedupes+ // against an already-lowercase default/declaration for the same directory.+ test('effectiveDbOnlyDirs lowercases declared dirs (case-insensitive match against always-lowercase slugs)', () => {+ const dirs = effectiveDbOnlyDirs(['Notes/', 'ATOMS/']);+ expect(dirs).toContain('notes/');+ expect(dirs).not.toContain('Notes/');+ // 'ATOMS/' lowercases to 'atoms/', which collides with (dedupes against)+ // the derive-phase default of the same name.+ expect(dirs.filter(d => d === 'atoms/').length).toBe(1);+ expect(dirs).not.toContain('ATOMS/');+ });});describe('db_only_collector_collision (#2788)', () => {diff --git a/test/doctor-upgrade-errors-stale.test.ts b/test/doctor-upgrade-errors-stale.test.tsnew file mode 100644index 0000000000..fe5690b7fd--- /dev/null+++ b/test/doctor-upgrade-errors-stale.test.ts@@ -0,0 +1,45 @@+/**+ * #4517 — ~/.gbrain/upgrade-errors.jsonl is APPEND-ONLY, and doctor+ * unconditionally warned from its LAST line on every run, forever — even+ * years after the failed upgrade was retried and completed. The check now+ * re-verifies: when the running binary is at/past the failed record's+ * to_version AND the schema ledger is current, the warn downgrades to ok.+ *+ * `upgradeErrorResolved` is the pure decision fn (exported for tests).+ */++import { describe, test, expect } from 'bun:test';+import { upgradeErrorResolved } from '../src/commands/doctor.ts';++describe('upgradeErrorResolved (#4517)', () => {+ test('resolved: binary moved past the failed target and schema is current', () => {+ expect(upgradeErrorResolved('0.46.10.0', '0.46.28.0', true)).toBe(true);+ });++ test('resolved: binary is exactly the failed target (retry landed it)', () => {+ expect(upgradeErrorResolved('0.46.28.0', '0.46.28.0', true)).toBe(true);+ });++ test('NOT resolved: binary is still older than the failed target', () => {+ expect(upgradeErrorResolved('0.46.28.0', '0.46.10.0', true)).toBe(false);+ });++ test('NOT resolved: pending migrations keep the warning even on a newer binary', () => {+ expect(upgradeErrorResolved('0.46.10.0', '0.46.28.0', false)).toBe(false);+ });++ test('4th (MICRO) segment is compared — 0.31.4.0 binary does not resolve a 0.31.4.1 failure', () => {+ expect(upgradeErrorResolved('0.31.4.1', '0.31.4.0', true)).toBe(false);+ expect(upgradeErrorResolved('0.31.4.0', '0.31.4.1', true)).toBe(true);+ });++ test('leading v is tolerated', () => {+ expect(upgradeErrorResolved('v0.46.10.0', '0.46.28.0', true)).toBe(true);+ });++ test('fails closed on malformed versions (keeps warning)', () => {+ 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);+ });+});diff --git a/test/doctor-upgrade-errors.test.ts b/test/doctor-upgrade-errors.test.tsnew file mode 100644index 0000000000..382ba74249--- /dev/null+++ b/test/doctor-upgrade-errors.test.ts@@ -0,0 +1,157 @@+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { withEnv } from './helpers/with-env.ts';+import { checkUpgradeErrors } from '../src/commands/doctor.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import { VERSION } from '../src/version.ts';++async function withHome<T>(fn: (home: string) => T | Promise<T>): Promise<T> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-doctor-upgrade-errors-'));+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ try {+ return await withEnv({ GBRAIN_HOME: dir }, () => fn(dir));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++function writeErrorRecord(home: string, rec: {+ ts: string; phase: string; from_version: string; to_version: string; hint: string;+}) {+ writeFileSync(join(home, '.gbrain', 'upgrade-errors.jsonl'), JSON.stringify(rec) + '\n');+}++/** Minimal engine stub: checkUpgradeErrors only calls getConfig('version'). */+const schemaCurrentEngine = {+ getConfig: async () => String(LATEST_VERSION),+};+const schemaBehindEngine = {+ getConfig: async () => String(LATEST_VERSION - 1),+};++describe('checkUpgradeErrors', () => {+ test('no jsonl file → null (fresh install)', async () => {+ await withHome(async () => {+ expect(await checkUpgradeErrors(null)).toBeNull();+ });+ });++ test('empty jsonl file → null', async () => {+ await withHome(async (home) => {+ writeFileSync(join(home, '.gbrain', 'upgrade-errors.jsonl'), '');+ expect(await checkUpgradeErrors(null)).toBeNull();+ });+ });++ test('failure record whose to_version the installed binary has not reached yet → warn', async () => {+ await withHome(async (home) => {+ // A to_version far ahead of the real running VERSION can never be+ // "already reached" — deterministically exercises the still-warn path+ // regardless of what VERSION happens to be when this test runs. Even a+ // schema-current engine cannot suppress it (both proofs are required).+ writeErrorRecord(home, {+ ts: '2026-08-22T10:00:00Z',+ phase: 'post-upgrade',+ from_version: '0.1.0.0',+ to_version: '999.999.999.999',+ hint: 'gbrain apply-migrations --yes',+ });+ const check = await checkUpgradeErrors(schemaCurrentEngine);+ expect(check).not.toBeNull();+ expect(check?.status).toBe('warn');+ expect(check?.name).toBe('upgrade_errors');+ expect(check?.message).toContain('2026-08-22');+ expect(check?.message).toContain('0.1.0.0 → 999.999.999.999');+ expect(check?.message).toContain('post-upgrade');+ expect(check?.message).toContain('gbrain apply-migrations --yes');+ });+ });++ test('#4517: binary at to_version AND schema current → explicit ok (superseded, not silent)', async () => {+ await withHome(async (home) => {+ // The installed binary's own VERSION is >= itself by definition, so a+ // record targeting exactly VERSION is provably reached binary-side;+ // pairing it with a schema-current engine satisfies both proofs.+ writeErrorRecord(home, {+ ts: '2026-08-22T10:00:00Z',+ phase: 'post-upgrade',+ from_version: '0.1.0.0',+ to_version: VERSION,+ hint: 'gbrain apply-migrations --yes',+ });+ const check = await checkUpgradeErrors(schemaCurrentEngine);+ expect(check).not.toBeNull();+ expect(check?.status).toBe('ok');+ expect(check?.name).toBe('upgrade_errors');+ expect(check?.message).toContain('superseded');+ expect(check?.message).toContain(VERSION);+ });+ });++ test('#4517: binary at to_version but schema NOT verifiable (no engine) → warn stays (fail-closed)', async () => {+ await withHome(async (home) => {+ writeErrorRecord(home, {+ ts: '2026-08-22T10:00:00Z',+ phase: 'post-upgrade',+ from_version: '0.1.0.0',+ to_version: VERSION,+ hint: 'gbrain apply-migrations --yes',+ });+ const check = await checkUpgradeErrors(null);+ expect(check?.status).toBe('warn');+ });+ });++ test('#4517: binary at to_version but schema ledger behind → warn stays', async () => {+ await withHome(async (home) => {+ writeErrorRecord(home, {+ ts: '2026-08-22T10:00:00Z',+ phase: 'post-upgrade',+ from_version: '0.1.0.0',+ to_version: VERSION,+ hint: 'gbrain apply-migrations --yes',+ });+ const check = await checkUpgradeErrors(schemaBehindEngine);+ expect(check?.status).toBe('warn');+ });+ });++ test('#4517: getConfig throwing keeps the warning (unverifiable → fail-closed)', async () => {+ await withHome(async (home) => {+ writeErrorRecord(home, {+ ts: '2026-08-22T10:00:00Z',+ phase: 'post-upgrade',+ from_version: '0.1.0.0',+ to_version: VERSION,+ hint: 'gbrain apply-migrations --yes',+ });+ const throwingEngine = {+ getConfig: async (): Promise<string | null> => { throw new Error('connection lost'); },+ };+ const check = await checkUpgradeErrors(throwingEngine);+ expect(check?.status).toBe('warn');+ });+ });++ test('only the LAST line of a multi-entry log is considered', async () => {+ await withHome(async (home) => {+ const lines = [+ { ts: '2026-08-20T10:00:00Z', phase: 'post-upgrade', from_version: '0.1.0.0', to_version: '0.2.0.0', hint: 'old, irrelevant' },+ { ts: '2026-08-22T10:00:00Z', phase: 'post-upgrade', from_version: '0.2.0.0', to_version: '999.999.999.999', hint: 'gbrain apply-migrations --yes' },+ ];+ writeFileSync(join(home, '.gbrain', 'upgrade-errors.jsonl'), lines.map((l) => JSON.stringify(l)).join('\n') + '\n');+ const check = await checkUpgradeErrors(null);+ expect(check?.message).toContain('2026-08-22');+ expect(check?.message).not.toContain('2026-08-20');+ });+ });++ test('malformed JSON on the last line → null (best-effort, does not throw)', async () => {+ await withHome(async (home) => {+ writeFileSync(join(home, '.gbrain', 'upgrade-errors.jsonl'), 'not valid json\n');+ expect(await checkUpgradeErrors(null)).toBeNull();+ });+ });+});diff --git a/test/doctor-volunteer-channels.test.ts b/test/doctor-volunteer-channels.test.tsindex 286f44b25b..af66385ab9 100644--- a/test/doctor-volunteer-channels.test.ts+++ b/test/doctor-volunteer-channels.test.ts@@ -176,9 +176,16 @@ describe('checkVolunteerChannels', () => {// Serve wires the feedback-loop callback — deleting the registration// would silently disconnect the hook-lane feedback loop while every unit// test stays green (the body lives in volunteer-events.ts; the seam is- // tested with stub callbacks).+ // tested with stub callbacks). #4474 moved the registration into the+ // shared bindResolveIpcForServe helper (src/mcp/resolve-ipc-binding.ts)+ // so stdio serve and `serve --http` wire it identically — pin the+ // callback in the helper AND both serve surfaces routing through it.+ const bindingSrc = readFileSync(join(import.meta.dir, '..', 'src', 'mcp', 'resolve-ipc-binding.ts'), 'utf8');+ expect(bindingSrc).toContain('onTurnContextDelivered');+ expect(bindingSrc).toContain('logTurnContextDeliveryFireAndForget(engine, result, req)');const serverSrc = readFileSync(join(import.meta.dir, '..', 'src', 'mcp', 'server.ts'), 'utf8');- expect(serverSrc).toContain('onTurnContextDelivered');- expect(serverSrc).toContain('logTurnContextDeliveryFireAndForget(engine, result, req)');+ expect(serverSrc).toContain('bindResolveIpcForServe');+ const serveHttpSrc = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'serve-http.ts'), 'utf8');+ expect(serveHttpSrc).toContain('bindResolveIpcForServe');});});diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.tsindex 7d0bf3febf..63d83112a3 100644--- a/test/doctor-wedged-queue.test.ts+++ b/test/doctor-wedged-queue.test.ts@@ -94,6 +94,56 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {expect(check.message).toContain("'default'");});+ // #3063: the check must not claim "worker alive" when no worker is+ // registered for the wedged queue, and must keep the original "worker+ // alive but stuck" wording when one genuinely is.+ it('says "No worker subscribed" (not "worker alive") when no live worker is registered for the wedged queue', async () => {+ await seed('default', 'cycle', 'waiting');+ await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });+ const check = await computeWedgedQueueCheck(pgLike, { readWorkers: () => [] });+ expect(check.status).toBe('fail');+ expect(check.message).toContain('No worker subscribed');+ expect(check.message).not.toContain('worker alive but not claiming work');+ });++ it('keeps "worker alive but not claiming work" when a live worker IS registered for the wedged queue', async () => {+ await seed('default', 'cycle', 'waiting');+ await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });+ const check = await computeWedgedQueueCheck(pgLike, { readWorkers: () => [{ queue: 'default' }] });+ expect(check.status).toBe('fail');+ expect(check.message).toContain('worker alive but not claiming work');+ expect(check.message).not.toContain('No worker subscribed');+ });++ it('a throwing registry read → still fail, but liveness-unknown wording (no fabricated verdict)', async () => {+ await seed('default', 'cycle', 'waiting');+ await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });+ const check = await computeWedgedQueueCheck(pgLike, {+ readWorkers: () => { throw new Error('registry dir unreadable'); },+ });+ expect(check.status).toBe('fail');+ expect(check.message).toContain('worker registry unreadable');+ expect(check.message).not.toContain('worker alive but not claiming work');+ expect(check.message).not.toContain('No worker subscribed');+ expect(check.details?.worker_registry_unreadable).toBe(true);+ });++ it('mixed stuck + no-worker queues → both messages, details count each subset', async () => {+ await seed('default', 'cycle', 'waiting');+ await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });+ await seed('q-orphan', 'cycle', 'waiting');+ await seed('q-orphan', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });+ const check = await computeWedgedQueueCheck(pgLike, { readWorkers: () => [{ queue: 'default' }] });+ expect(check.status).toBe('fail');+ expect(check.message).toContain('worker alive but not claiming work');+ expect(check.message).toContain("'default'");+ expect(check.message).toContain('No worker subscribed');+ expect(check.message).toContain("'q-orphan'");+ expect(check.details?.stuck_worker_queues).toBe(1);+ expect(check.details?.no_worker_queues).toBe(1);+ expect(check.details?.wedged_queues).toBe(2);+ });+it('does NOT flag when a job holds a live lock (active_healthy > 0)', async () => {await seed('default', 'cycle', 'waiting');await seed('default', 'cycle', 'active', { lockUntilSql: "now() + interval '5 min'" });@@ -132,9 +182,12 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {it('shell-escapes an embedded single quote in the restart hint (producer-controlled queue names)', async () => {// The hint is copy-pasted by operators AND remediation agents, so a// queue named q-wedge'd must arrive POSIX-escaped, never raw.+ // A live worker must be registered for the queue, or the #3063+ // liveness split routes this to the "no worker" branch instead,+ // which never builds the restart-hint string at all.await seed("q-wedge'd", 'cycle', 'waiting');await seed("q-wedge'd", 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });- const check = await computeWedgedQueueCheck(pgLike);+ const check = await computeWedgedQueueCheck(pgLike, { readWorkers: () => [{ queue: "q-wedge'd" }] });expect(check.status).toBe('fail');expect(check.message).toContain(String.raw`--queue 'q-wedge'\''d'`);});@@ -144,7 +197,12 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });await seed('q-side', 'cycle', 'waiting');await seed('q-side', 'cycle', 'completed', { updatedAtSql: "now() - interval '30 min'" });- const check = await computeWedgedQueueCheck(pgLike);+ // Both queues need a live worker registered so the #3063 liveness+ // split routes them into the "stuck" branch that builds this+ // restart-hint union, not the "no worker" branch.+ const check = await computeWedgedQueueCheck(pgLike, {+ readWorkers: () => [{ queue: 'default' }, { queue: 'q-side' }],+ });expect(check.status).toBe('fail');// The bare pair (for 'default') terminates with a backtick — no --queue —// and the comma-join carries the per-queue variant right behind it.diff --git a/test/dream-cli-flags.test.ts b/test/dream-cli-flags.test.tsindex 8c4fc06c8b..c0e8bb492e 100644--- a/test/dream-cli-flags.test.ts+++ b/test/dream-cli-flags.test.ts@@ -34,7 +34,8 @@ describe('dream CLI flag wiring', () => {});test('--input implies --phase synthesize', () => {- expect(dreamSrc).toContain("phase = 'synthesize'");+ // #4493: phase became the phases[] array (repeated --phase flags all run).+ expect(dreamSrc).toContain("phases = ['synthesize']");});test('--from > --to range validation', () => {@@ -115,7 +116,8 @@ describe('dream CLI flag wiring', () => {});test('--drain defaults to extract_atoms and rejects other phases', () => {- expect(dreamSrc).toContain("phase = 'extract_atoms'");+ // #4493: phase became the phases[] array (repeated --phase flags all run).+ expect(dreamSrc).toContain("phases = ['extract_atoms']");expect(dreamSrc).toContain('--drain currently supports only --phase extract_atoms');});@@ -153,27 +155,30 @@ describe('dream CLI flag wiring', () => {expect(dreamSrc).toContain('if (once && !phaseWasExplicit && !wantsHelp)');});- // Codex P3 finding: the derived `phase` value gets populated by+ // Codex P3 finding: the derived phase value gets populated by// --input/--drain BEFORE this validation used to run, so those two- // silently slipped past an `!phase`-based check. The fix validates- // against `phaseWasExplicit` (captured at `phaseIdx !== -1`, before- // any implicit defaulting) instead. Behavioral pins live in- // test/dream.test.ts.+ // silently slipped past an emptiness-based check. The fix validates+ // against `phaseWasExplicit` (captured from the raw flag occurrences,+ // before any implicit defaulting) instead. Behavioral pins live in+ // test/dream.test.ts. (#4493: the capture source moved from+ // `phaseIdx !== -1` to `phaseValues.length > 0` when --phase became+ // repeatable — same before-defaulting ordering contract.)test('validates against phaseWasExplicit, captured before --input/--drain defaulting', () => {- expect(dreamSrc).toContain('const phaseWasExplicit = phaseIdx !== -1;');+ expect(dreamSrc).toContain('const phaseWasExplicit = phaseValues.length > 0;');// Must be declared before the --input-implies-synthesize and// --drain-implies-extract_atoms defaulting blocks so it captures// presence prior to any implicit phase assignment.- const explicitIdx = dreamSrc.indexOf('const phaseWasExplicit = phaseIdx !== -1;');- const inputImpliesIdx = dreamSrc.indexOf("phase = 'synthesize'");- const drainImpliesIdx = dreamSrc.indexOf("phase = 'extract_atoms'");+ const explicitIdx = dreamSrc.indexOf('const phaseWasExplicit = phaseValues.length > 0;');+ const inputImpliesIdx = dreamSrc.indexOf("phases = ['synthesize']");+ const drainImpliesIdx = dreamSrc.indexOf("phases = ['extract_atoms']");expect(explicitIdx).toBeGreaterThan(-1);expect(explicitIdx).toBeLessThan(inputImpliesIdx);expect(explicitIdx).toBeLessThan(drainImpliesIdx);});test('threads onceForPhase to runCycle, gated on opts.once', () => {- expect(dreamSrc).toMatch(/onceForPhase:\s*opts\.once\s*\?\s*opts\.phase!\s*:\s*undefined/);+ // #4493: opts.phases[0] — parseArgs guarantees exactly one when --once.+ expect(dreamSrc).toMatch(/onceForPhase:\s*opts\.once\s*\?\s*opts\.phases\[0\]!\s*:\s*undefined/);});test('documents --once in --help output', () => {diff --git a/test/dream.test.ts b/test/dream.test.tsindex d6d2f29dd2..d0c96e59d9 100644--- a/test/dream.test.ts+++ b/test/dream.test.ts@@ -55,12 +55,12 @@ describe('runDream — brainDir resolution', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000); // OAuth v25 + git init; needs breathing room under full-suite load+ }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent loadafterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('explicit --dir takes precedence over engine config', async () => {await engine.setConfig('sync.repo_path', '/configured/dir');@@ -112,12 +112,12 @@ describe('runDream — --phase <name> restricts the cycle', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000); // OAuth v25 + git init; needs breathing room under full-suite load+ }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent loadafterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('--phase lint produces a report with exactly one phase = lint', async () => {const report = await runDream(engine, ['--dir', repo, '--phase', 'lint', '--json']);@@ -149,6 +149,70 @@ describe('runDream — --phase <name> restricts the cycle', () => {spy.mockRestore();errSpy.mockRestore();});++ // #4493: repeated --phase flags all run (previously only the FIRST was+ // read; the rest were silently dropped and the run still exited 0).+ // runCycle executes named phases in canonical cycle order.+ test('--phase lint --phase orphans runs BOTH phases', async () => {+ const report = await runDream(engine, [+ '--dir', repo, '--phase', 'lint', '--phase', 'orphans', '--json',+ ]);+ expect(report).toBeTruthy();+ if (report) {+ expect(report.phases.map(p => p.phase)).toEqual(['lint', 'orphans']);+ }+ });++ test('#4493: repeated identical --phase values collapse to one run', async () => {+ const report = await runDream(engine, [+ '--dir', repo, '--phase', 'lint', '--phase', 'lint', '--json',+ ]);+ expect(report).toBeTruthy();+ if (report) {+ expect(report.phases.map(p => p.phase)).toEqual(['lint']);+ }+ });++ test('#4493: an unknown value in ANY repeat position exits with an error', async () => {+ const spy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runDream(null, ['--dir', repo, '--phase', 'lint', '--phase', 'garbage']);+ } catch (e: any) {+ expect(e.message).toBe('EXIT');+ }+ expect(errSpy.mock.calls.flat().join(' ')).toMatch(/Unknown phase "garbage"/);+ spy.mockRestore();+ errSpy.mockRestore();+ });++ test('#4493: --once with multiple phases exits 2 (single-target contract)', async () => {+ const spy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runDream(null, ['--dir', repo, '--phase', 'lint', '--phase', 'orphans', '--once']);+ } catch (e: any) {+ expect(e.message).toBe('EXIT');+ }+ expect(spy).toHaveBeenCalledWith(2);+ expect(errSpy.mock.calls.flat().join(' ')).toMatch(/--once supports a single --phase target/);+ spy.mockRestore();+ errSpy.mockRestore();+ });++ test('#4493: --phase with a missing value exits 2 instead of silently running the full cycle', async () => {+ const spy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});+ try {+ await runDream(null, ['--dir', repo, '--phase']);+ } catch (e: any) {+ expect(e.message).toBe('EXIT');+ }+ expect(spy).toHaveBeenCalledWith(2);+ expect(errSpy.mock.calls.flat().join(' ')).toMatch(/--phase <name>: missing value/);+ spy.mockRestore();+ errSpy.mockRestore();+ });});// ─── --once (issue #2860) ───────────────────────────────────────────@@ -160,12 +224,12 @@ describe('runDream — --once (issue #2860)', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000);+ }, 300_000);afterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('bare --once (no --phase) exits 2 with a usage hint', async () => {const exitSpy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });@@ -273,12 +337,12 @@ describe('runDream — output format', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000); // OAuth v25 + git init; needs breathing room under full-suite load+ }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent loadafterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('--json emits parsable CycleReport JSON with schema_version', async () => {const lines: string[] = [];@@ -338,12 +402,12 @@ describe('runDream — dry-run propagates through to runCycle', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000); // OAuth v25 + git init; needs breathing room under full-suite load+ }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent loadafterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('--dry-run produces a report where no DB-mutating work happened', async () => {// Before: empty pages table.@@ -367,12 +431,12 @@ describe('runDream — exit-code semantics', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000); // OAuth v25 + git init; needs breathing room under full-suite load+ }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent loadafterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('clean/ok/partial statuses do not call process.exit', async () => {const spy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('UNEXPECTED_EXIT'); });@@ -419,12 +483,12 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000);+ }, 300_000);afterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);// ─── parseArgs: --source missing / conflict / repetition ────────────@@ -475,7 +539,7 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {const report = await runDream(engine, ['--dir', repo, '--phase', 'lint', '--source', 'alpha', '--source', 'alpha', '--json']);expect(report).toBeTruthy();if (report) expect(['ok', 'clean']).toContain(report.status);- }, 60_000);+ }, 300_000);test('--source X --source-id Y (conflict) exits 2', async () => {const exitSpy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });@@ -589,7 +653,7 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {const writtenMs = new Date(after!).getTime();expect(writtenMs).toBeGreaterThanOrEqual(t0);expect(writtenMs).toBeLessThanOrEqual(Date.now() + 1000);- }, 60_000);+ }, 300_000);// ─── Back-compat: bare `gbrain dream` does NOT write per-source stamp ─@@ -610,7 +674,7 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {expect(report).toBeTruthy();expect(await readLastFullCycleAt('alpha')).not.toBeNull();expect(await readLastFullCycleAt('beta')).toBeNull();- }, 60_000);+ }, 300_000);// ─── --source-id alias equivalence (D3) ─────────────────────────────@@ -625,7 +689,7 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {const after = await readLastFullCycleAt('beta');expect(after).not.toBeNull();- }, 60_000);+ }, 300_000);// ─── T3: TypeError MUST propagate (not swallowed by predicate-gated catch) ─@@ -674,12 +738,12 @@ describe('runDream → checkCycleFreshness end-to-end (D5)', () => {beforeEach(async () => {repo = makeGitRepo();engine = await makePGLite();- }, 60_000);+ }, 300_000);afterEach(async () => {if (engine) await engine.disconnect();rmSync(repo, { recursive: true, force: true });- }, 60_000);+ }, 300_000);test('stale source becomes fresh after dream --source (column-name drift guard)', async () => {// Seed source with last_full_cycle_at backdated 25h (above warn floor).@@ -703,5 +767,5 @@ describe('runDream → checkCycleFreshness end-to-end (D5)', () => {// Doctor now sees fresh.const afterCheck = await checkCycleFreshness(engine);expect(afterCheck.status).toBe('ok');- }, 60_000);+ }, 300_000);});diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.tsindex dcc0490c97..4218eb24ae 100644--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts@@ -223,6 +223,12 @@ describe.skipIf(!OPENAI && !ANTHROPIC)('keyed auto fact-extraction (LLM takes)',title: 'Keyed Extraction Probe',compiled_truth: PROSE,});+ // #4473: takes are md-first — the probe page needs a real markdown home+ // (a page with no locatable .md is skipped, never written DB-only).+ const repo = join(root, 'brain');+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ writeFileSync(join(repo, `${SLUG}.md`), `# Keyed Extraction Probe\n\n${PROSE}\n`, 'utf-8');+ await engine.setConfig('sync.repo_path', repo);}, 120_000);afterAll(async () => {diff --git a/test/e2e/dream-cycle-phase-order-pglite.test.ts b/test/e2e/dream-cycle-phase-order-pglite.test.tsindex 7588d14e84..ef1aa30621 100644--- a/test/e2e/dream-cycle-phase-order-pglite.test.ts+++ b/test/e2e/dream-cycle-phase-order-pglite.test.ts@@ -56,6 +56,11 @@ mock.module('../../src/core/embedding.ts', () => ({const effectiveNoEmbed = opts.v2Enabled && !opts.serialFlag && !opts.noEmbed ? true : opts.noEmbed;return effectiveNoEmbed ? 'deferred' : 'inline';},+ // wave-G PGLite backfill-admission hardening added this worker-capability-+ // aware sibling of willEmbedSynchronously; sync-embed-backfill.ts imports it+ // statically, so the mock must carry it (mirror of the real pure fn).+ resolveWorkerBackedSyncEmbedMode: (opts: { deferEligible: boolean; noEmbed: boolean }) =>+ opts.deferEligible || opts.noEmbed ? 'deferred' : 'inline',shouldBlockSync: (costUsd: number, floorUsd: number, mode: string, posture: 'gated' | 'tokenmax' = 'gated') =>posture === 'tokenmax' ? false : mode === 'inline' && costUsd > floorUsd,}));diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.tsindex 2121162f62..bb3f523759 100644--- a/test/e2e/engine-parity.test.ts+++ b/test/e2e/engine-parity.test.ts@@ -655,6 +655,32 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {}});+ test('#3754 soft-deleted pages hidden from traverseGraph on both engines', async () => {+ for (const engine of [pgEngine, pgliteEngine]) {+ await engine.putPage('notes/sdg-from', {+ type: 'note', title: 'sdg-from', compiled_truth: 'links out', timeline: '',+ });+ await engine.putPage('notes/sdg-to', {+ type: 'note', title: 'sdg-to', compiled_truth: 'target', timeline: '',+ });+ await engine.addLink('notes/sdg-from', 'notes/sdg-to', 'ctx', 'wikilink');++ const before = await engine.traverseGraph('notes/sdg-from', 1);+ expect(before.map((n) => n.slug).sort()).toEqual(['notes/sdg-from', 'notes/sdg-to']);++ await engine.softDeletePage('notes/sdg-to', { sourceId: 'default' });++ // Node set, displayed links array, capped recursive variant, and the+ // deleted-seed case all filter identically on both engines.+ const after = await engine.traverseGraph('notes/sdg-from', 1);+ expect(after.map((n) => n.slug)).toEqual(['notes/sdg-from']);+ expect(after[0].links.map((l) => l.to_slug)).toEqual([]);+ const capped = await engine.traverseGraph('notes/sdg-from', 1, { frontierCap: 10 });+ expect(capped.map((n) => n.slug)).toEqual(['notes/sdg-from']);+ expect(await engine.traverseGraph('notes/sdg-to', 1)).toEqual([]);+ }+ });+test('v0.41.19.0 deletePages parity: both engines return same confirmed-deleted slugs', async () => {const realSlugs = ['wiki/dpp-1', 'wiki/dpp-2', 'wiki/dpp-3'];for (const slug of realSlugs) {@@ -791,27 +817,46 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {);}- const scoped = async (eng: BrainEngine, opts: { sourceId?: string; sourceIds?: string[] }) =>+ const scoped = async (+ eng: BrainEngine,+ opts: { sourceId?: string; sourceIds?: string[]; mode?: 'inbound' | 'islanded' },+ ) =>(await eng.findOrphanPages(opts)).map(r => r.slug).filter(s => s.startsWith('people/op-')).sort();- // Scalar scope to src-a: op-orphan-a is an orphan; op-target-a is saved- // by the cross-source inbound (A2). Parity on both engines.- const pgA = await scoped(pgEngine, { sourceId: 'orphan-src-a' });- const pgliteA = await scoped(pgliteEngine, { sourceId: 'orphan-src-a' });- expect(pgA).toEqual(['people/op-orphan-a']);- expect(pgliteA).toEqual(pgA);+ // #4524: the default mode is 'islanded' (no live inbound AND no live+ // outbound — health's definition). op-linker-b has a live outbound link,+ // so it is NOT an orphan by default; mode 'inbound' preserves the legacy+ // no-inbound-only view where it IS one. Both modes pinned on both engines.++ // Scalar scope to src-a: op-orphan-a is an orphan in BOTH modes (no links+ // at all); op-target-a is saved by the cross-source inbound (A2).+ for (const mode of ['islanded', 'inbound'] as const) {+ const pgA = await scoped(pgEngine, { sourceId: 'orphan-src-a', mode });+ const pgliteA = await scoped(pgliteEngine, { sourceId: 'orphan-src-a', mode });+ expect(pgA).toEqual(['people/op-orphan-a']);+ expect(pgliteA).toEqual(pgA);+ }- // Scalar scope to src-b.+ // Scalar scope to src-b: islanded default excludes op-linker-b (live+ // outbound); legacy inbound mode includes it.const pgB = await scoped(pgEngine, { sourceId: 'orphan-src-b' });const pgliteB = await scoped(pgliteEngine, { sourceId: 'orphan-src-b' });- expect(pgB).toEqual(['people/op-linker-b']);+ expect(pgB).toEqual([]);expect(pgliteB).toEqual(pgB);+ const pgBIn = await scoped(pgEngine, { sourceId: 'orphan-src-b', mode: 'inbound' });+ const pgliteBIn = await scoped(pgliteEngine, { sourceId: 'orphan-src-b', mode: 'inbound' });+ expect(pgBIn).toEqual(['people/op-linker-b']);+ expect(pgliteBIn).toEqual(pgBIn);- // Federated array scope (= ANY binding) → union.+ // Federated array scope (= ANY binding) → union, in both modes.const pgFed = await scoped(pgEngine, { sourceIds: ['orphan-src-a', 'orphan-src-b'] });const pgliteFed = await scoped(pgliteEngine, { sourceIds: ['orphan-src-a', 'orphan-src-b'] });- expect(pgFed).toEqual(['people/op-linker-b', 'people/op-orphan-a']);+ expect(pgFed).toEqual(['people/op-orphan-a']);expect(pgliteFed).toEqual(pgFed);+ const pgFedIn = await scoped(pgEngine, { sourceIds: ['orphan-src-a', 'orphan-src-b'], mode: 'inbound' });+ const pgliteFedIn = await scoped(pgliteEngine, { sourceIds: ['orphan-src-a', 'orphan-src-b'], mode: 'inbound' });+ expect(pgFedIn).toEqual(['people/op-linker-b', 'people/op-orphan-a']);+ expect(pgliteFedIn).toEqual(pgFedIn);});// v0.42.7 (#1696): stale-page extraction watermark parity. Isolated under adiff --git a/test/e2e/enrich-pglite.test.ts b/test/e2e/enrich-pglite.test.tsindex af107fb918..9b0b2f54a7 100644--- a/test/e2e/enrich-pglite.test.ts+++ b/test/e2e/enrich-pglite.test.ts@@ -548,3 +548,78 @@ describe('checkpoint persistence (#3629)', () => {expect(synthCalls).toBe(2); // --force re-bills deliberately}, 60000);});++describe('checkpoint residuals (#3629 follow-up)', () => {+ test('blank model output stays retryable: NOT banked in the checkpoint', async () => {+ await seedStub('people/blank-example', 'Blank Example', 'person');+ await seedLinkInto('people/blank-example', 'meetings/blank-m', RICH_CONTEXT);++ let synthCalls = 0;+ const blankSynth: SynthesizeFn = async () => { synthCalls++; return ''; };+ const opts = {+ sourceId: 'default',+ types: ['person' as const],+ model: 'test:model',+ synthesizeFn: blankSynth,+ };++ const r1 = await runEnrichCore(engine, opts);+ expect(synthCalls).toBe(1);+ expect(r1.pages_empty_output).toBe(1);++ // A blank response is a synthesis-failure shape (#2085), not a grounding+ // verdict — the next run must re-attempt it instead of suppressing the+ // page for the checkpoint TTL.+ const r2 = await runEnrichCore(engine, opts);+ expect(synthCalls).toBe(2);+ expect(r2.pages_empty_output).toBe(1);+ }, 60000);++ test('relaxing --min-context re-evaluates a page banked under the stricter gate', async () => {+ await seedStub('people/thin-ctx', 'Thin Ctx', 'person');+ await seedLinkInto('people/thin-ctx', 'meetings/thin-m', RICH_CONTEXT);++ let synthCalls = 0;+ const synth: SynthesizeFn = async () => { synthCalls++; return 'SKIP'; };+ const base = {+ sourceId: 'default',+ types: ['person' as const],+ model: 'test:model',+ synthesizeFn: synth,+ };++ // Strict gate: pre-LLM rejection banks the page under THIS fingerprint.+ const strict = await runEnrichCore(engine, { ...base, minContextChars: 100000 });+ expect(synthCalls).toBe(0);+ expect(strict.pages_skipped_pre_llm ?? 0).toBe(1);++ // Relaxed gate is a different run: the banked pre-LLM skip must not+ // suppress the page under the new knob value.+ await runEnrichCore(engine, { ...base, minContextChars: 10 });+ expect(synthCalls).toBe(1);+ }, 60000);++ test('--dry-run --force does not destroy the real checkpoint', async () => {+ await seedStub('people/dryforce', 'Dry Force', 'person');+ await seedLinkInto('people/dryforce', 'meetings/df-m', RICH_CONTEXT);++ let synthCalls = 0;+ const skipSynth: SynthesizeFn = async () => { synthCalls++; return 'SKIP'; };+ const opts = {+ sourceId: 'default',+ types: ['person' as const],+ model: 'test:model',+ synthesizeFn: skipSynth,+ };++ await runEnrichCore(engine, opts);+ expect(synthCalls).toBe(1);++ // A dry-run preview with --force must stay read-only.+ await runEnrichCore(engine, { ...opts, dryRun: true, force: true });++ const r3 = await runEnrichCore(engine, opts);+ expect(synthCalls).toBe(1); // still banked — the dry-run didn't clear it+ expect(r3.pages_enriched).toBe(0);+ }, 60000);+});diff --git a/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts b/test/e2e/openrouter-anthropic-subagent-replay.live.test.tsnew file mode 100644index 0000000000..d4a0a4764e--- /dev/null+++ b/test/e2e/openrouter-anthropic-subagent-replay.live.test.ts@@ -0,0 +1,168 @@+/**+ * LIVE e2e — OpenRouter Anthropic subagent abort/retry (TODOS.md v0.37.6.0).+ *+ * Skip-gated on OPENROUTER_API_KEY. First turn hits real OR Haiku, persists+ * the tool-call, completes the observation, then aborts before the follow-up+ * model turn. Resume must keep those persisted tool-call ids byte-identical+ * and must not re-dispatch the completed tool.+ *+ * The gateway loop swallows tool-execute errors (they become tool-result+ * isError blocks). Abort is therefore the job AbortSignal after the first+ * successful observation — not a throw from execute.+ *+ * Run (keep-keys required — unit preload strips OPENROUTER_API_KEY):+ * GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 OPENROUTER_API_KEY=... \+ * bun test test/e2e/openrouter-anthropic-subagent-replay.live.test.ts+ */++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 { makeSubagentHandler } from '../../src/core/minions/handlers/subagent.ts';+import type { MinionJobContext, ToolDef, ToolCtx } from '../../src/core/minions/types.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';++const MODEL = 'openrouter:anthropic/claude-haiku-4.5';+const API_KEY = process.env.OPENROUTER_API_KEY;+const skipAll = !API_KEY;+const SYSTEM =+ 'You are a tool-using intern. You MUST call ping before you say anything else. Never answer in prose first.';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ resetGateway();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', '85');+ // Flag OFF on purpose: OR Anthropic must auto-route through the gateway.+ await engine.unsetConfig('agent.use_gateway_loop');+ if (skipAll) return;+ configureGateway({+ chat_model: MODEL,+ embedding_model: 'openrouter:openai/text-embedding-3-small',+ embedding_dimensions: 1024,+ expansion_model: MODEL,+ env: { OPENROUTER_API_KEY: API_KEY! },+ });+});++function makeCtx(+ jobId: number,+ prompt: string,+ signal: AbortSignal,+): MinionJobContext {+ return {+ id: jobId,+ name: 'subagent',+ data: { prompt, model: MODEL, max_turns: 4, system: SYSTEM },+ attempts_made: 0,+ signal,+ deadlineAtMs: null,+ shutdownSignal: new AbortController().signal,+ updateProgress: async () => {},+ updateTokens: async () => {},+ log: async () => {},+ isActive: async () => true,+ readInbox: async () => [],+ };+}++async function makeJob(prompt: string): Promise<{ jobId: number }> {+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at)+ VALUES ('subagent', 'active', $1::jsonb, 'default', 0, now())+ RETURNING id`,+ [JSON.stringify({ prompt, model: MODEL, max_turns: 4, system: SYSTEM })],+ );+ return { jobId: rows[0]!.id };+}++describe('OpenRouter Anthropic live — abort mid-loop and resume', () => {+ test('persisted tool-call ids stay byte-identical across resume', async () => {+ if (skipAll) {+ console.warn('[skip] OPENROUTER_API_KEY not set');+ return;+ }++ let pingCalls = 0;+ const firstAbort = new AbortController();+ const tools: ToolDef[] = [+ {+ name: 'ping',+ description: 'Mandatory ping. Call this tool once with {"who":"gbrain"} before answering.',+ input_schema: {+ type: 'object',+ properties: { who: { type: 'string' } },+ required: ['who'],+ },+ idempotent: true,+ async execute(_input: unknown, _ctx: ToolCtx) {+ pingCalls += 1;+ if (pingCalls === 1) {+ // Observation is complete; abort before the follow-up model turn.+ firstAbort.abort();+ }+ return { pong: true };+ },+ },+ ];++ const handler = makeSubagentHandler({+ engine,+ config: {} as never,+ toolRegistry: tools,+ makeAnthropic: () => ({+ messages: {+ create: async () => {+ throw new Error('legacy Anthropic SDK must not run for openrouter:*');+ },+ },+ }) as never,+ });++ const prompt = 'Call the ping tool exactly once with who=gbrain, then say done. Do not skip the tool.';+ const { jobId } = await makeJob(prompt);++ const first = await handler(makeCtx(jobId, prompt, firstAbort.signal));+ expect(pingCalls).toBe(1);+ expect(first.stop_reason).toBe('error');++ const firstRows = await engine.executeRaw<{ content_blocks: unknown }>(+ `SELECT content_blocks FROM subagent_messages+ WHERE job_id = $1 AND role = 'assistant'+ ORDER BY message_idx ASC LIMIT 1`,+ [jobId],+ );+ expect(firstRows.length).toBe(1);+ const firstBlocks = typeof firstRows[0]!.content_blocks === 'string'+ ? firstRows[0]!.content_blocks+ : JSON.stringify(firstRows[0]!.content_blocks);+ expect(firstBlocks).toMatch(/tool-call|tool_use/);++ const resume = await handler(makeCtx(jobId, prompt, new AbortController().signal));+ expect(resume.stop_reason).toBe('end_turn');+ // First observation already completed; resume must not re-execute it.+ expect(pingCalls).toBe(1);++ const secondRows = await engine.executeRaw<{ content_blocks: unknown }>(+ `SELECT content_blocks FROM subagent_messages+ WHERE job_id = $1 AND role = 'assistant'+ ORDER BY message_idx ASC LIMIT 1`,+ [jobId],+ );+ const secondBlocks = typeof secondRows[0]!.content_blocks === 'string'+ ? secondRows[0]!.content_blocks+ : JSON.stringify(secondRows[0]!.content_blocks);+ expect(secondBlocks).toBe(firstBlocks);+ }, 90_000);+});diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.tsindex dbd8ddd7a7..5ae990d7ff 100644--- a/test/e2e/postgres-bootstrap.test.ts+++ b/test/e2e/postgres-bootstrap.test.ts@@ -218,6 +218,41 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>expect(cols).toHaveLength(1);}, 60_000);+ test('standalone db.initSchema straddles an old-shaped brain via the shared bootstrap (#4477)', async () => {+ // src/core/db.ts's module-level initSchema (used by test/e2e/helpers.ts+ // and legacy callers) replays SCHEMA_SQL directly. Pre-fix it ran NO+ // forward-reference bootstrap, so a brain whose pages table predates a+ // blob-indexed column (here: deleted_at ← pages_deleted_at_purge_idx)+ // wedged on the blob's CREATE INDEX. It now shares+ // applyPostgresForwardReferenceBootstrap with PostgresEngine.initSchema.+ await engine.initSchema();+ const conn = (engine as any).sql;+ await conn.unsafe(`+ DROP INDEX IF EXISTS pages_deleted_at_purge_idx;+ ALTER TABLE pages DROP COLUMN IF EXISTS deleted_at CASCADE;+ `);++ // The engine connected in module-singleton style (PostgresEngine.connect+ // delegates to db.connect), so db.initSchema() runs on the SAME pool —+ // exactly how test/e2e/helpers.ts drives it. Do NOT db.disconnect()+ // here: that would tear down the shared singleton under the engine.+ const db = await import('../../src/core/db.ts');+ // The path under test: bootstrap → SCHEMA_SQL, no engine.initSchema.+ await db.initSchema();++ const col = await conn`+ SELECT column_name FROM information_schema.columns+ WHERE table_schema = current_schema()+ AND table_name = 'pages' AND column_name = 'deleted_at'+ `;+ expect(col).toHaveLength(1);+ const idx = await conn`+ SELECT indexname FROM pg_indexes+ WHERE tablename = 'pages' AND indexname = 'pages_deleted_at_purge_idx'+ `;+ expect(idx).toHaveLength(1);+ }, 60_000);+// Migration v120 — schema-lint hardening (#1647 / #171). Postgres-only// assertions (security_invoker has no surface on embedded PGLite).test('v120: page_links view runs with security_invoker=on (#1647b)', async () => {diff --git a/test/e2e/sources-remote-mcp.test.ts b/test/e2e/sources-remote-mcp.test.tsindex ed9d969e21..bce1092814 100644--- a/test/e2e/sources-remote-mcp.test.ts+++ b/test/e2e/sources-remote-mcp.test.ts@@ -143,9 +143,16 @@ describeE2E('sources-remote-mcp E2E (gstack /setup-gbrain Path 4)', () => {};// Register a sources_admin-scoped client (the "gstack token").+ // #4433: sources_list row-filters to the caller's federated read grant,+ // and registration defaults federated_read=[source_id]=['default'] — a+ // default-grant client would no longer see the sources it adds in the+ // listing. Grant the ids this suite creates so the remote_url-surfacing+ // assertions stay about sources_list's projection, not the row filter+ // (the read-only client keeps the default grant and pins the filter).const reg1 = execSync('bun run src/cli.ts auth register-client e2e-sources-admin ' +- '--grant-types client_credentials --scopes "read sources_admin"',+ '--grant-types client_credentials --scopes "read sources_admin" ' ++ '--federated-read default,e2e-yc-artifacts,e2e-removable',{ cwd: process.cwd(), encoding: 'utf8', env: subprocessEnv },);clientId = reg1.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1];@@ -315,6 +322,10 @@ describeE2E('sources-remote-mcp E2E (gstack /setup-gbrain Path 4)', () => {test('read-only token CAN list sources (read-scoped)', async () => {const result = await callMcp(readOnlyToken!, 'sources_list', {});expect(Array.isArray(result.sources)).toBe(true);+ // #4433: the listing is row-filtered to the caller's federated read+ // grant. This client kept the registration default (['default']), so a+ // source outside its grant must not leak into its listing.+ expect(result.sources.find((s: any) => s.id === 'e2e-yc-artifacts')).toBeUndefined();});test('CLI register-client rejects bogus scope (allowlist)', async () => {diff --git a/test/e2e/subagent-crash-replay-multi-provider.test.ts b/test/e2e/subagent-crash-replay-multi-provider.test.tsindex 75935ee05e..ec54cc7d24 100644--- a/test/e2e/subagent-crash-replay-multi-provider.test.ts+++ b/test/e2e/subagent-crash-replay-multi-provider.test.ts@@ -131,18 +131,14 @@ const PROVIDER_MATRIX: ProviderShape[] = [providerId: 'google',},},- {- providerId: 'openrouter',- modelId: 'openrouter:anthropic/claude-sonnet-4-6',- finalResponse: {- text: 'openrouter resumed: proxied claude response',- blocks: [{ type: 'text', text: 'openrouter resumed: proxied claude response' }] as ChatBlock[],- stopReason: 'end',- usage: { input_tokens: 50, output_tokens: 7, cache_read_tokens: 0, cache_creation_tokens: 0 },- model: 'openrouter:anthropic/claude-sonnet-4-6',- providerId: 'openrouter',- },- },+ // #4478: openrouter left the replay matrix when its recipe declared the+ // subagent loop unsupported — the handler's capability gate refuses those+ // jobs BEFORE the replay path, so they can never reach reconciliation.+ // #4514 then carved out Anthropic-via-OR (`openrouter:anthropic/…`), which+ // shares Anthropic's tool-call envelope; its allowed-path replay coverage+ // lives in test/e2e/openrouter-anthropic-subagent-replay.live.test.ts and+ // test/e2e/subagent-gateway-path.test.ts, not here. Non-Anthropic OR+ // families stay refused — pinned by the dedicated describe below.{providerId: 'deepseek',modelId: 'deepseek:deepseek-chat',@@ -347,6 +343,37 @@ describe('SIGKILL crash-replay reconciliation across provider matrix (v0.38 LOAD});});+ describe('openrouter non-Anthropic route: refused by the supports_subagent_loop gate before replay (#4478/#4514)', () => {+ // The enforcement's own regression coverage: a crashed openrouter job on+ // a NON-Anthropic route must NOT resume through the replay path — the+ // capability gate throws the typed no_subagent_loop rejection first, and+ // the prior tool row is never re-executed. (#4514 allows only+ // `openrouter:anthropic/…` on the loop; every other OR family keeps this+ // refusal until it gets its own live abort/retry evidence.) Covers both+ // persisted shapes so a future shape-specific bypass can't sneak past+ // the gate.+ const OPENROUTER_MODEL = 'openrouter:google/gemini-3-flash-preview';++ for (const shape of ['v2', 'v1'] as const) {+ it(`typed no_subagent_loop rejection instead of replay (${shape} shape)`, async () => {+ __setChatTransportForTests(async () => {+ throw new Error('transport must not be reached for a loop-refused provider');+ });++ const executions: Array<{ name: string; input: unknown }> = [];+ const tools = makeStubTools(executions);+ const handler = buildHandler(tools);++ const { jobId } = await seedCrashedState(`find foo (openrouter ${shape})`, shape);+ const ctx = await makeCrashedCtx(jobId, `find foo (openrouter ${shape})`, OPENROUTER_MODEL);++ await expect(handler(ctx)).rejects.toThrow(/supports_subagent_loop: false/);+ // The refusal fires BEFORE reconciliation/dispatch: nothing re-executes.+ expect(executions.length).toBe(0);+ });+ }+ });+describe('non-idempotent tool with pending status (unrecoverable error)', () => {it('throws unrecoverable when a non-idempotent tool is pending on resume', async () => {// Resume stub re-emits the SAME tool call the worker crashed on.diff --git a/test/e2e/subagent-gateway-path.test.ts b/test/e2e/subagent-gateway-path.test.tsindex 27a4cf7beb..d9f7033910 100644--- a/test/e2e/subagent-gateway-path.test.ts+++ b/test/e2e/subagent-gateway-path.test.ts@@ -195,6 +195,27 @@ describe('runSubagentViaGateway (v0.38 Slice 1 — full handler path through gatexpect(messages[1].message_idx).toBe(1);});+ it('openrouter:anthropic/… auto-routes through the gateway when the flag is off', async () => {+ await engine.unsetConfig('agent.use_gateway_loop');+ __setChatTransportForTests(async () => ({+ text: 'or-anthropic done',+ blocks: [{ type: 'text', text: 'or-anthropic done' }] as ChatBlock[],+ stopReason: 'end',+ usage: { input_tokens: 8, output_tokens: 2, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'openrouter:anthropic/claude-haiku-4.5',+ providerId: 'openrouter',+ } satisfies ChatResult));++ const handler = buildHandler(makeStubTools([]));+ const { ctx } = await makeFakeJob({+ prompt: 'hello',+ model: 'openrouter:anthropic/claude-haiku-4.5',+ });+ const result = await handler(ctx);+ expect(result.result).toBe('or-anthropic done');+ expect(result.stop_reason).toBe('end_turn');+ });+it('happy path 2-turn with tool: dispatches, persists v2 stable ID, returns final text', async () => {let turn = 0;__setChatTransportForTests(async () => {diff --git a/test/e2e/sync-delegation-under-serve.serial.test.ts b/test/e2e/sync-delegation-under-serve.serial.test.tsindex 25bcd131fc..05f2b28487 100644--- a/test/e2e/sync-delegation-under-serve.serial.test.ts+++ b/test/e2e/sync-delegation-under-serve.serial.test.ts@@ -256,14 +256,68 @@ describe('serve-delegated sync (real serve + real sync subprocesses)', () => {// the rung-2 regression pin. The gbrain-sync ROW lock is dead-held for// the 60s takeover grace, so break it explicitly first.const br = await runSyncChild(['--force-break-lock', '--yes'], { timeoutMs: 120_000 });- expect(br.code).toBe(0);+ if (br.code !== 0) {+ throw new Error(`--force-break-lock exited ${br.code}\nstderr:\n${br.err}\nstdout:\n${br.out}`);+ }++ // #4492: settle between the break-lock child and the direct run. CI run+ // 32556210838 flaked here — the direct sync exited 1 and the bare+ // `expect(r.code).toBe(0)` dropped the stderr that would have pinned the+ // race (residual PGLite data-dir lock release vs the next spawn, or a+ // not-yet-cleared gbrain-sync row). Open the brain in-process (connect+ // reaps dead data-dir lock holders) and poll the sync row-lock free,+ // then release BEFORE spawning the direct child.+ const engineConfig = { engine: 'pglite' as const, database_path: dbDir };+ {+ const settleDeadline = Date.now() + 60_000;+ let settleEngine = null as Awaited<ReturnType<typeof createEngine>> | null;+ for (;;) {+ try {+ settleEngine = await createEngine(engineConfig);+ await settleEngine.connect(engineConfig);+ break;+ } catch (e) {+ settleEngine = null;+ if (Date.now() > settleDeadline) {+ throw new Error(`settle: brain not openable after force-break: ${(e as Error).message}`);+ }+ await new Promise((res) => setTimeout(res, 500));+ }+ }+ try {+ for (;;) {+ const held = await settleEngine!.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM gbrain_cycle_locks WHERE id LIKE 'gbrain-sync:%'`,+ );+ if (held[0]!.n === 0) break;+ if (Date.now() > settleDeadline) {+ throw new Error(`settle: gbrain-sync lock row still held after force-break (${held[0]!.n} row(s))`);+ }+ await new Promise((res) => setTimeout(res, 500));+ }+ } finally {+ await settleEngine!.disconnect();+ }+ }- const r = await runSyncChild(['--no-pull', '--yes', '--no-embed'], { timeoutMs: 180_000 });+ // Retry-once: a first direct attempt can still lose a residual startup+ // race with the just-released data-dir lock; a second attempt (with the+ // first failure's stderr surfaced) separates a flaky settle from a real+ // regression.+ let r = await runSyncChild(['--no-pull', '--yes', '--no-embed'], { timeoutMs: 180_000 });+ if (r.code !== 0) {+ process.stderr.write(+ `[pin4] first direct sync attempt exited ${r.code}; retrying once.\n` ++ `[pin4] first-attempt stderr:\n${r.err}\n`,+ );+ r = await runSyncChild(['--no-pull', '--yes', '--no-embed'], { timeoutMs: 180_000 });+ }expect(r.err).not.toContain('delegating the sync');- expect(r.code).toBe(0);+ if (r.code !== 0) {+ throw new Error(`direct sync exited ${r.code}\nstderr:\n${r.err}\nstdout:\n${r.out}`);+ }// The pages are really in the brain (direct engine open works now).- const engineConfig = { engine: 'pglite' as const, database_path: dbDir };const engine = await createEngine(engineConfig);await engine.connect(engineConfig);const rows = await engine.executeRaw<{ n: number }>(diff --git a/test/embed-backfill-cli-admission.serial.test.ts b/test/embed-backfill-cli-admission.serial.test.tsnew file mode 100644index 0000000000..4c08121441--- /dev/null+++ b/test/embed-backfill-cli-admission.serial.test.ts@@ -0,0 +1,153 @@+/**+ * Public CLI admission for embed-backfill on PGLite.+ *+ * A background submit has no persistent worker to drain it and must fail+ * without a row. `--follow` is the narrow exception because that process+ * immediately starts an inline worker and waits for the terminal result.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runJobs } from '../src/commands/jobs.ts';++const REPO_ROOT = resolve(import.meta.dir, '..');+const CLI = join(REPO_ROOT, 'src', 'cli.ts');+let isolatedHome = '';++function run(args: string[]) {+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ HOME: isolatedHome,+ GBRAIN_HOME: isolatedHome,+ };+ for (const key of [+ 'DATABASE_URL',+ 'GBRAIN_DATABASE_URL',+ 'OPENAI_API_KEY',+ 'VOYAGE_API_KEY',+ 'ANTHROPIC_API_KEY',+ 'DEEPSEEK_API_KEY',+ 'DEEP_SEEK_API_KEY',+ ]) delete env[key];+ return spawnSync('bun', [CLI, ...args], {+ cwd: REPO_ROOT,+ env,+ encoding: 'utf8',+ timeout: 120_000,+ });+}++beforeEach(() => {+ isolatedHome = mkdtempSync(join(tmpdir(), 'gbrain-embed-admission-'));+ const init = run(['init', '--pglite', '--no-embedding', '--non-interactive']);+ expect(init.status, init.stderr).toBe(0);+});++afterEach(() => {+ rmSync(isolatedHome, { recursive: true, force: true });+});++describe('jobs submit embed-backfill — PGLite worker surface', () => {+ test('background submit refuses with a direct drain remedy and writes no row', () => {+ const submit = run([+ 'jobs',+ 'submit',+ 'embed-backfill',+ '--params',+ '{"sourceId":"default"}',+ ]);++ expect(submit.status).toBe(1);+ expect(submit.stderr).toContain('PGLite has no persistent worker');+ expect(submit.stderr).toContain('gbrain embed --stale --source default');++ const list = run(['jobs', 'list', '--json']);+ expect(list.status, list.stderr).toBe(0);+ expect(JSON.parse(list.stdout)).toEqual([]);+ }, 30_000);++ test('--dry-run evaluates admission and refuses instead of claiming it would submit', () => {+ const submit = run([+ 'jobs',+ 'submit',+ 'embed-backfill',+ '--params',+ '{"sourceId":"default"}',+ '--dry-run',+ ]);++ expect(submit.status).toBe(1);+ expect(submit.stdout).not.toContain('Would submit');+ expect(submit.stderr).toContain('PGLite has no persistent worker');+ expect(submit.stderr).toContain('gbrain embed --stale --source default');++ const list = run(['jobs', 'list', '--json']);+ expect(list.status, list.stderr).toBe(0);+ expect(JSON.parse(list.stdout)).toEqual([]);+ }, 30_000);++ test('metacharacter source id is rejected without a paste-ready injected remedy', () => {+ const submit = run([+ 'jobs',+ 'submit',+ 'embed-backfill',+ '--params',+ '{"sourceId":"default; printf injected"}',+ ]);++ expect(submit.status).toBe(1);+ expect(submit.stderr).toContain('Invalid source_id');+ expect(submit.stderr).not.toContain('gbrain embed --stale --source default;');++ const list = run(['jobs', 'list', '--json']);+ expect(list.status, list.stderr).toBe(0);+ expect(JSON.parse(list.stdout)).toEqual([]);+ }, 30_000);++ test('after admission, stale schema still fails before shell payload validation', async () => {+ const staleEngine = new PGLiteEngine();+ await staleEngine.connect({});+ await staleEngine.initSchema();+ await staleEngine.setConfig('version', '0');+ const origExit = process.exit;+ const origError = console.error;+ const errors: string[] = [];+ process.exit = (() => { throw new Error('__exit__'); }) as typeof process.exit;+ console.error = (...args: unknown[]) => errors.push(args.map(String).join(' '));+ try {+ await expect(runJobs(staleEngine, ['submit', 'shell', '--params', '{}'])).rejects.toThrow('__exit__');+ } finally {+ process.exit = origExit;+ console.error = origError;+ await staleEngine.disconnect();+ }++ const stderr = errors.join('\n');+ expect(stderr).toContain('minion_jobs table not found (schema version 0');+ expect(stderr).not.toContain('shell: specify exactly one of cmd or argv');+ }, 30_000);++ test('--follow normalizes a padded name before admission and drains inline', () => {+ const submit = run([+ 'jobs',+ 'submit',+ ' embed-backfill ',+ '--params',+ '{"sourceId":"default"}',+ '--follow',+ ]);++ expect(submit.status, submit.stderr).toBe(0);+ expect(submit.stdout).toContain('Executing inline');+ expect(submit.stdout).toContain('completed');++ const list = run(['jobs', 'list', '--json']);+ expect(list.status, list.stderr).toBe(0);+ const jobs = JSON.parse(list.stdout) as Array<{ name: string; status: string }>;+ expect(jobs).toHaveLength(1);+ expect(jobs[0]).toMatchObject({ name: 'embed-backfill', status: 'completed' });+ }, 30_000);+});diff --git a/test/embed-backfill-submit.test.ts b/test/embed-backfill-submit.test.tsindex 3903ceb94d..fefa6606f0 100644--- a/test/embed-backfill-submit.test.ts+++ b/test/embed-backfill-submit.test.ts@@ -10,21 +10,35 @@* - Override knobs in opts honored (test seam)*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import {submitEmbedBackfill,COOLDOWN_CONFIG_KEY,SPEND_CAP_CONFIG_KEY,+ type SubmitEmbedBackfillResult,+ type SubmitEmbedBackfillOpts,} from '../src/core/embed-backfill-submit.ts';import { MinionQueue } from '../src/core/minions/queue.ts';+import { embedBackfillWorkerSurface } from '../src/core/minions/embed-backfill-admission.ts';let engine: PGLiteEngine;+let workerBackedEngine: BrainEngine;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ workerBackedEngine = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;}, 30000); // 30s — PGLite WASM cold-start + 89 migrations exceeds 5s defaultafterAll(async () => {@@ -37,13 +51,208 @@ beforeEach(async () => {await engine.executeRaw('DELETE FROM minion_jobs');});+function submitWithWorker(+ sourceId: string,+ opts: SubmitEmbedBackfillOpts,+) {+ return submitEmbedBackfill(workerBackedEngine, sourceId, opts);+}++function expectStatus<S extends SubmitEmbedBackfillResult['status']>(+ result: SubmitEmbedBackfillResult,+ status: S,+): asserts result is Extract<SubmitEmbedBackfillResult, { status: S }> {+ expect(result.status).toBe(status);+}++function failOnAccessPglite(): { engine: BrainEngine; accesses: string[] } {+ const accesses: string[] = [];+ const fail = (name: string) => async () => {+ accesses.push(name);+ throw new Error(`unexpected engine access: ${name}`);+ };+ return {+ engine: {+ kind: 'pglite',+ getConfig: fail('getConfig'),+ executeRaw: fail('executeRaw'),+ transaction: fail('transaction'),+ } as unknown as BrainEngine,+ accesses,+ };+}++describe('submitEmbedBackfill — worker-surface gate', () => {+ test('automatic refusal happens before config, SQL, or transaction access', async () => {+ const fake = failOnAccessPglite();++ const result = await submitEmbedBackfill(fake.engine, 'default', { reason: 'unit' });++ expect(result).toEqual({ status: 'no_worker_surface', engineKind: 'pglite' });+ expect(fake.accesses).toEqual([]);+ });++ test('refuses PGLite without leaving an undrainable waiting job', async () => {+ const result = await submitEmbedBackfill(engine, 'default', { reason: 'unit' });++ expect(result).toEqual({+ status: 'no_worker_surface',+ engineKind: 'pglite',+ });+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n+ FROM minion_jobs+ WHERE name = 'embed-backfill'`,+ );+ expect(Number(rows[0]?.n ?? 0)).toBe(0);+ });++ test('public queue refuses before config, SQL, or transaction access', async () => {+ const fake = failOnAccessPglite();++ await expect(+ new MinionQueue(fake.engine).add('embed-backfill', { sourceId: 'default' }),+ ).rejects.toThrow('PGLite has no persistent worker');+ expect(fake.accesses).toEqual([]);+ });++ test('public queue refusal leaves no PGLite row', async () => {+ await expect(+ new MinionQueue(engine).add('embed-backfill', { sourceId: 'default' }),+ ).rejects.toThrow('gbrain embed --stale --source default');+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,+ );+ expect(Number(rows[0]?.n ?? 0)).toBe(0);+ });++ test('public refusal rejects a metacharacter source id without rendering a paste-ready command', async () => {+ const fake = failOnAccessPglite();+ let error: Error | undefined;+ try {+ await new MinionQueue(fake.engine).add('embed-backfill', {+ sourceId: 'default; printf injected',+ });+ } catch (e) {+ error = e as Error;+ }++ expect(error).toBeDefined();+ expect(error!.message).toContain('Invalid source_id');+ expect(error!.message).not.toContain('Run `gbrain embed --stale --source');+ expect(fake.accesses).toEqual([]);++ const response = await dispatchToolCall(+ engine,+ 'submit_job',+ { name: 'embed-backfill', data: { sourceId: 'default; printf injected' } },+ { remote: true, transport: 'stdio', sourceId: 'default' },+ );+ expect(response.isError).toBe(true);+ const envelope = JSON.parse(response.content[0]?.text ?? '{}') as Record<string, unknown>;+ expect(envelope).toMatchObject({ error: 'invalid_params' });+ expect(envelope.message).not.toContain('gbrain embed --stale --source');+ });++ test('an unknown future engine kind fails closed before any engine access', async () => {+ const fake = failOnAccessPglite();+ const futureEngine = new Proxy(fake.engine, {+ get(target, prop) {+ if (prop === 'kind') return 'future-engine';+ return Reflect.get(target, prop, target);+ },+ }) as unknown as BrainEngine;++ expect(embedBackfillWorkerSurface(futureEngine)).toEqual({+ status: 'no_worker_surface',+ engineKind: 'unknown',+ });+ await expect(+ new MinionQueue(futureEngine).add('embed-backfill', { sourceId: 'default' }),+ ).rejects.toMatchObject({ code: 'no_worker_surface', engineKind: 'unknown' });+ expect(fake.accesses).toEqual([]);+ });++ test('submit_job refuses before engine access and MCP leaves no row', async () => {+ const fake = failOnAccessPglite();+ const submitJob = operationsByName.submit_job;+ await expect(submitJob.handler({+ engine: fake.engine,+ config: {},+ logger: console,+ dryRun: false,+ remote: true,+ } as never, { name: 'embed-backfill', data: { sourceId: 'default' } })).rejects.toThrow(+ 'PGLite has no persistent worker',+ );+ expect(fake.accesses).toEqual([]);++ const response = await dispatchToolCall(+ engine,+ 'submit_job',+ { name: 'embed-backfill', data: { sourceId: 'default' } },+ { remote: true, transport: 'stdio', sourceId: 'default' },+ );+ expect(response.isError).toBe(true);+ const envelope = JSON.parse(response.content[0]?.text ?? '{}') as Record<string, unknown>;+ expect(envelope).toMatchObject({+ error: 'no_worker_surface',+ suggestion: 'Run `gbrain embed --stale --source default` to drain embeddings inline.',+ });+ expect(envelope.message).toContain('PGLite has no persistent worker');+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,+ );+ expect(Number(rows[0]?.n ?? 0)).toBe(0);+ });++ test('submit_job dry-run reports the same no-worker capability refusal without access or a row', async () => {+ const fake = failOnAccessPglite();+ const submitJob = operationsByName.submit_job;+ await expect(submitJob.handler({+ engine: fake.engine,+ config: {},+ logger: console,+ dryRun: true,+ remote: true,+ } as never, { name: 'embed-backfill', data: { sourceId: 'default' } })).rejects.toMatchObject({+ code: 'no_worker_surface',+ });+ expect(fake.accesses).toEqual([]);++ const response = await dispatchToolCall(+ engine,+ 'submit_job',+ { name: 'embed-backfill', data: { sourceId: 'default' }, dry_run: true },+ { remote: true, transport: 'stdio', sourceId: 'default' },+ );+ expect(response.isError).toBe(true);+ expect(JSON.parse(response.content[0]?.text ?? '{}')).toMatchObject({+ error: 'no_worker_surface',+ });+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,+ );+ expect(Number(rows[0]?.n ?? 0)).toBe(0);+ });++ test('worker-backed public queue still accepts embed-backfill', async () => {+ const job = await new MinionQueue(workerBackedEngine).add(+ 'embed-backfill',+ { sourceId: 'default' },+ );+ expect(job.status).toBe('waiting');+ });+});+describe('submitEmbedBackfill — happy path', () => {test('submits with priority 5 + idempotency key on a clean source', async () => {- const result = await submitEmbedBackfill(engine, 'default', { reason: 'unit' });- expect(result.status).toBe('submitted');+ const result = await submitWithWorker('default', { reason: 'unit' });+ expectStatus(result, 'submitted');expect(result.jobId).toBeDefined();+ expect(result.spendCapBypassed).toBe(false);- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.getJob(result.jobId!);expect(job).not.toBeNull();expect(job!.name).toBe('embed-backfill');@@ -52,12 +261,12 @@ describe('submitEmbedBackfill — happy path', () => {});test('respects opts.priority override', async () => {- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',priority: -10,});- expect(result.status).toBe('submitted');- const queue = new MinionQueue(engine);+ expectStatus(result, 'submitted');+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.getJob(result.jobId!);expect(job!.priority).toBe(-10);});@@ -65,20 +274,24 @@ describe('submitEmbedBackfill — happy path', () => {describe('submitEmbedBackfill — cooldown gate', () => {test('blocks re-submission while a same-source job is active', async () => {- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);// Seed an active job manuallyawait queue.add('embed-backfill', { sourceId: 'default' }, {});await engine.executeRaw(`UPDATE minion_jobs SET status='active' WHERE name='embed-backfill'`,);- const result = await submitEmbedBackfill(engine, 'default', { reason: 'unit' });- expect(result.status).toBe('cooldown');- expect(result.cooldownRemainingSeconds).toBeUndefined();+ const result = await submitWithWorker('default', { reason: 'unit' });+ expectStatus(result, 'cooldown');+ expect(result).toEqual({+ status: 'cooldown',+ reason: 'active_or_waiting',+ cooldownRemainingSeconds: null,+ });});test('blocks re-submission inside the cooldown window after recent finish', async () => {- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.add('embed-backfill', { sourceId: 'default' }, {});// Mark completed 1 minute agoawait engine.executeRaw(@@ -86,17 +299,18 @@ describe('submitEmbedBackfill — cooldown gate', () => {[job.id],);- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',cooldownMinOverride: 10, // 10min cooldown; 1min elapsed → blocked});- expect(result.status).toBe('cooldown');+ expectStatus(result, 'cooldown');+ expect(result.reason).toBe('recently_finished');expect(result.cooldownRemainingSeconds).toBeGreaterThan(0);expect(result.cooldownRemainingSeconds).toBeLessThanOrEqual(10 * 60);});test('allows re-submission after cooldown elapses', async () => {- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.add('embed-backfill', { sourceId: 'default' }, {});// Mark completed 11 minutes ago — past the 10-min cooldownawait engine.executeRaw(@@ -104,104 +318,105 @@ describe('submitEmbedBackfill — cooldown gate', () => {[job.id],);- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',cooldownMinOverride: 10,});- expect(result.status).toBe('submitted');+ expectStatus(result, 'submitted');});test('config-overridable cooldown (via embed.backfill_cooldown_min)', async () => {await engine.setConfig(COOLDOWN_CONFIG_KEY, '60'); // 60min cooldown- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.add('embed-backfill', { sourceId: 'default' }, {});await engine.executeRaw(`UPDATE minion_jobs SET status='completed', finished_at=NOW() - INTERVAL '30 minutes' WHERE id=$1`,[job.id],);- const result = await submitEmbedBackfill(engine, 'default', { reason: 'unit' });- expect(result.status).toBe('cooldown');+ const result = await submitWithWorker('default', { reason: 'unit' });+ expectStatus(result, 'cooldown');});});describe('submitEmbedBackfill — 24h spend cap', () => {test('refuses when spend24hFn returns >= cap', async () => {- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',spendCapUsdOverride: 25,spend24hFn: async () => 25,});- expect(result.status).toBe('spend_capped');+ expectStatus(result, 'spend_capped');expect(result.spend24hUsd).toBe(25);expect(result.spendCapUsd).toBe(25);});test('admits when spend24hFn returns < cap', async () => {- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',spendCapUsdOverride: 25,spend24hFn: async () => 24.99,});- expect(result.status).toBe('submitted');+ expectStatus(result, 'submitted');});test('config-overridable spend cap (via embed.backfill_max_usd_per_source_24h)', async () => {await engine.setConfig(SPEND_CAP_CONFIG_KEY, '5');- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',spend24hFn: async () => 5,});- expect(result.status).toBe('spend_capped');+ expectStatus(result, 'spend_capped');expect(result.spendCapUsd).toBe(5);});// v0.42.42.0 (#2139): off-switch + tokenmax bypass.test('cap "off" → submits even at huge spend (Infinity cap never tripped)', async () => {await engine.setConfig(SPEND_CAP_CONFIG_KEY, 'off');- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',spend24hFn: async () => 1e9,});- expect(result.status).toBe('submitted');+ expectStatus(result, 'submitted');});test('0 falls back to the default cap (off semantics ≠ 0)', async () => {await engine.setConfig(SPEND_CAP_CONFIG_KEY, '0');- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',spend24hFn: async () => 25, // == default $25 → capped});- expect(result.status).toBe('spend_capped');+ expectStatus(result, 'spend_capped');expect(result.spendCapUsd).toBe(25);});test('spend.posture=tokenmax bypasses the cap, marks spendCapBypassed', async () => {- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',postureOverride: 'tokenmax',spendCapUsdOverride: 25,spend24hFn: async () => 100, // way over cap});- expect(result.status).toBe('submitted');+ expectStatus(result, 'submitted');expect(result.spendCapBypassed).toBe(true);+ if (!result.spendCapBypassed) throw new Error('expected spend-cap bypass payload');expect(result.spend24hUsd).toBe(100);});test('tokenmax does NOT bypass the cooldown (axis split — churn protection stays)', async () => {- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);const job = await queue.add('embed-backfill', { sourceId: 'default' }, {});await engine.executeRaw(`UPDATE minion_jobs SET status='completed', finished_at=NOW() - INTERVAL '1 minute' WHERE id=$1`,[job.id],);- const result = await submitEmbedBackfill(engine, 'default', {+ const result = await submitWithWorker('default', {reason: 'unit',postureOverride: 'tokenmax',cooldownMinOverride: 10,spend24hFn: async () => 1e9,});- expect(result.status).toBe('cooldown'); // posture lifts the cap, NOT the cooldown+ expectStatus(result, 'cooldown'); // posture lifts the cap, NOT the cooldown});});@@ -210,13 +425,13 @@ describe('submitEmbedBackfill — source isolation', () => {await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('other', 'other', '{"federated":true}') ON CONFLICT (id) DO NOTHING`,);- const queue = new MinionQueue(engine);+ const queue = new MinionQueue(workerBackedEngine);// Active job on 'default'await queue.add('embed-backfill', { sourceId: 'default' }, {});await engine.executeRaw(`UPDATE minion_jobs SET status='active' WHERE name='embed-backfill'`);// Submit for 'other' — should NOT be blocked- const result = await submitEmbedBackfill(engine, 'other', { reason: 'unit' });- expect(result.status).toBe('submitted');+ const result = await submitWithWorker('other', { reason: 'unit' });+ expectStatus(result, 'submitted');});});diff --git a/test/embedding-input-limit.test.ts b/test/embedding-input-limit.test.tsnew file mode 100644index 0000000000..d371669b14--- /dev/null+++ b/test/embedding-input-limit.test.ts@@ -0,0 +1,180 @@+/**+ * #4530 — the chunker respects the embedding model's per-input token limit.+ *+ * nvidia/nv-embedqa-e5-v5 (NVIDIA NIM) rejects any single input over 512+ * tokens with a non-transient 400; the chunker calibrated to OpenAI/Voyage+ * limits emitted chunks up to ~2000 estimated tokens, so ~35% of a typical+ * vault could NEVER embed. The recipe now declares the per-model limit,+ * resolveMaxChunkTokens() maps it to a chunk-token cap (x 0.6 safety for the+ * cl100k-estimate vs wordpiece mismatch, GBRAIN_MAX_CHUNK_TOKENS escape+ * hatch), and chunkText SPLITS (never truncates) to fit.+ */++import { describe, test, expect, beforeEach, afterAll } from 'bun:test';+import {+ resolveMaxChunkTokens,+ maxInputTokensForModel,+ EMBED_INPUT_SAFETY,+} from '../src/core/embedding-input-limit.ts';+import { DEFAULT_MAX_CHUNK_TOKENS } from '../src/core/chunkers/token-estimate.ts';+import { chunkText } from '../src/core/chunkers/recursive.ts';+import { estimateEmbedTokens } from '../src/core/chunkers/token-estimate.ts';+import { nvidia } from '../src/core/ai/recipes/nvidia.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { isEmbedRetriableError, isTransientNetworkEmbedError } from '../src/core/embed-retry.ts';+import { normalizeAIError, AIConfigError } from '../src/core/ai/errors.ts';+import { withEnv } from './helpers/with-env.ts';++/**+ * resolveMaxChunkTokens() defaults to process.env; tests that exercise the+ * no-arg path clear GBRAIN_MAX_CHUNK_TOKENS via withEnv (restores the prior+ * ambient value — never mutates shard-global env permanently).+ */+const withoutChunkTokenEnv = <T>(fn: () => T | Promise<T>) =>+ withEnv({ GBRAIN_MAX_CHUNK_TOKENS: undefined }, fn);++beforeEach(() => {+ resetGateway();+});++afterAll(() => {+ // Shard hygiene: restore the legacy embedding pin (truncation-test precedent).+ resetGateway();+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { ...process.env },+ });+});++const NV_MODEL = 'nvidia:nvidia/nv-embedqa-e5-v5';+const NV_EXPECTED = Math.floor(512 * EMBED_INPUT_SAFETY); // 307++describe('resolveMaxChunkTokens (#4530)', () => {+ test('default stays DEFAULT_MAX_CHUNK_TOKENS when no model limit is declared', async () => {+ await withoutChunkTokenEnv(() => {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test' },+ });+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);+ });+ });++ test('gateway unconfigured falls back to the default (fail-open)', async () => {+ await withoutChunkTokenEnv(() => {+ expect(resolveMaxChunkTokens()).toBe(DEFAULT_MAX_CHUNK_TOKENS);+ });+ });++ test('nv-embedqa-e5-v5 resolves 512 x safety', async () => {+ await withoutChunkTokenEnv(() => {+ configureGateway({+ embedding_model: NV_MODEL,+ embedding_dimensions: 1024,+ env: { NVIDIA_API_KEY: 'nvapi-test' },+ });+ expect(resolveMaxChunkTokens()).toBe(NV_EXPECTED);+ });+ });++ test('the short alias form resolves the same limit', async () => {+ await withoutChunkTokenEnv(() => {+ configureGateway({+ embedding_model: 'nvidia:nv-embedqa-e5-v5',+ embedding_dimensions: 1024,+ env: { NVIDIA_API_KEY: 'nvapi-test' },+ });+ expect(resolveMaxChunkTokens()).toBe(NV_EXPECTED);+ });+ });++ test('GBRAIN_MAX_CHUNK_TOKENS escape hatch wins, clamped to the default ceiling', () => {+ configureGateway({+ embedding_model: NV_MODEL,+ embedding_dimensions: 1024,+ env: { NVIDIA_API_KEY: 'nvapi-test' },+ });+ expect(resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: '400' })).toBe(400);+ expect(resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: '999999' })).toBe(DEFAULT_MAX_CHUNK_TOKENS);+ expect(resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: '1' })).toBe(64); // floor+ // Garbage falls through to the model/default resolution.+ expect(resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'banana' })).toBe(NV_EXPECTED);+ });++ test('wave-g: invalid GBRAIN_MAX_CHUNK_TOKENS warns once per process per value, not per call', () => {+ // The resolver runs per chunkText site — a typo'd env var must not emit+ // one stderr line per page across a whole backfill.+ const seen: string[] = [];+ const orig = console.error;+ console.error = (...args: unknown[]) => { seen.push(args.join(' ')); };+ try {+ resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'warn-once-probe' });+ resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'warn-once-probe' });+ resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'warn-once-probe' });+ expect(seen.filter((l) => l.includes('warn-once-probe')).length).toBe(1);+ // A CHANGED (still-invalid) value warns again — once.+ resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'warn-once-probe-2' });+ resolveMaxChunkTokens({ GBRAIN_MAX_CHUNK_TOKENS: 'warn-once-probe-2' });+ expect(seen.filter((l) => l.includes('warn-once-probe-2')).length).toBe(1);+ } finally {+ console.error = orig;+ }+ });++ test('maxInputTokensForModel is case-insensitive (model_dims #4123 parity)', () => {+ expect(maxInputTokensForModel(nvidia, 'nvidia/nv-embedqa-e5-v5')).toBe(512);+ expect(maxInputTokensForModel(nvidia, 'NVIDIA/NV-EmbedQA-E5-V5')).toBe(512);+ expect(maxInputTokensForModel(nvidia, 'nvidia/nv-embed-v1')).toBeUndefined();+ });+});++describe('chunkText maxTokens cap (#4530)', () => {+ // Realistic prose paragraph, repeated: dense enough that default chunks+ // measure well over the 307-token cap.+ const para = 'The migration plan covers seventy thousand pages of engineering notes, meeting summaries, and design documents that must be re-embedded onto the new provider without loss. ';+ const text = Array.from({ length: 40 }, () => para).join('\n\n');++ test('every emitted chunk fits the model cap — split, not truncated', () => {+ const cap = NV_EXPECTED;+ const chunks = chunkText(text, { maxTokens: cap });+ expect(chunks.length).toBeGreaterThan(0);+ for (const c of chunks) {+ expect(estimateEmbedTokens(c.text)).toBeLessThanOrEqual(cap);+ }+ // Split, not truncated: the emitted chunks must jointly carry more+ // content than any single capped chunk (nothing was thrown away).+ const totalChars = chunks.reduce((n, c) => n + c.text.length, 0);+ expect(totalChars).toBeGreaterThanOrEqual(text.length * 0.9); // overlap adds, strip removes little+ }, 60000);++ test('default behavior is unchanged when maxTokens is not passed', () => {+ const defaultChunks = chunkText(text);+ const explicitDefault = chunkText(text, { maxTokens: DEFAULT_MAX_CHUNK_TOKENS });+ expect(defaultChunks).toEqual(explicitDefault);+ }, 60000);++ test('a maxTokens above the default ceiling is clamped (pipeline sizing)', () => {+ const oversized = chunkText(text, { maxTokens: 999999 });+ expect(oversized).toEqual(chunkText(text));+ }, 60000);+});++describe('the per-input 400 is non-transient (#4530)', () => {+ // The exact wire shape NVIDIA NIM returns for an over-limit input.+ function nvidia400(): Error {+ const e = new Error('Input length 576 exceeds maximum allowed token size 512') as Error & { statusCode: number };+ e.statusCode = 400;+ return e;+ }++ test('never classified retriable — no 60s backoff loop', () => {+ expect(isEmbedRetriableError(nvidia400())).toBe(false);+ expect(isTransientNetworkEmbedError(nvidia400())).toBe(false);+ });++ test('normalizeAIError marks it config-class (non-retryable), not transient', () => {+ expect(normalizeAIError(nvidia400())).toBeInstanceOf(AIConfigError);+ });+});diff --git a/test/extract-atoms-drain-errors.test.ts b/test/extract-atoms-drain-errors.test.tsnew file mode 100644index 0000000000..ff2c1cc90a--- /dev/null+++ b/test/extract-atoms-drain-errors.test.ts@@ -0,0 +1,78 @@+/**+ * #4539 — the drain surfaces WHY it failed.+ *+ * Pre-fix: runPhaseExtractAtoms returned failures[] in its phase details, but+ * the drain adapter (runExtractAtomsDrainForSource) collapsed them to bare+ * counts, ExtractAtomsDrainResult had no error field, and dream.ts printed+ * only `stopped: no_progress` — a run that failed on every item looked+ * identical to "nothing eligible".+ *+ * Post-fix: runBatch carries failureCount + firstError, the pure loop+ * accumulates them into result.failure_count / result.last_error, and both+ * ride the --json payload verbatim.+ */++import { describe, it, expect } from 'bun:test';+import {+ runExtractAtomsDrain,+ type ExtractAtomsDrainDeps,+} from '../src/core/cycle/extract-atoms-drain.ts';++const passThroughLock: ExtractAtomsDrainDeps['withLock'] = (work) => work();++describe('extract_atoms drain error surfacing (#4539)', () => {+ it('accumulates failure_count and keeps the most recent firstError', async () => {+ let batch = 0;+ const result = await runExtractAtomsDrain(+ {+ withLock: passThroughLock,+ countRemaining: async () => 5,+ runBatch: async () => {+ batch++;+ return batch === 1+ ? { extracted: 1, skipped: 0, failureCount: 2, firstError: 'pages/a: malformed model output' }+ : { extracted: 0, skipped: 0, providerFailure: true, failureCount: 3, firstError: 'pages/b: 429 rate limit' };+ },+ now: () => 0,+ },+ { windowMs: 1_000_000 },+ );+ expect(result.failure_count).toBe(5);+ expect(result.last_error).toBe('pages/b: 429 rate limit');+ expect(result.status).toBe('provider_failure');+ });++ it('clean run reports failure_count 0 and last_error null', async () => {+ const counts = [2, 1, 0];+ let i = 0;+ const result = await runExtractAtomsDrain(+ {+ withLock: passThroughLock,+ countRemaining: async () => counts[Math.min(i++, counts.length - 1)],+ runBatch: async () => ({ extracted: 1, skipped: 0 }),+ now: () => 0,+ },+ { windowMs: 1_000_000 },+ );+ expect(result.stopped).toBe('drained');+ expect(result.failure_count).toBe(0);+ expect(result.last_error).toBeNull();+ });++ it('a failing no-progress run carries the error that explains it', async () => {+ const result = await runExtractAtomsDrain(+ {+ withLock: passThroughLock,+ countRemaining: async () => 5,+ // Partial-failure shape: some items skipped-as-failures, no atoms —+ // the loop stops no_progress, and pre-fix the reason was invisible.+ runBatch: async () => ({ extracted: 0, skipped: 0, failureCount: 5, firstError: 'pages/x: provider 400' }),+ now: () => 0,+ },+ { windowMs: 1_000_000 },+ );+ expect(result.stopped).toBe('no_progress');+ expect(result.failure_count).toBe(5);+ expect(result.last_error).toBe('pages/x: provider 400');+ });+});diff --git a/test/extract-atoms-failure-classes.test.ts b/test/extract-atoms-failure-classes.test.tsindex c836612115..1a83715ce8 100644--- a/test/extract-atoms-failure-classes.test.ts+++ b/test/extract-atoms-failure-classes.test.ts@@ -90,6 +90,31 @@ describe('parseAtomsOutcome — typed parse (gbrain#4148)', () => {});describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {+ test('prompt truncation never splits a UTF-16 surrogate pair', async () => {+ await seedPage('note/surrogate-boundary');+ const content = `${'a'.repeat(49_999)}💡trailing prose`;+ let capturedPrompt = '';++ await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [],+ _pages: [{ slug: 'note/surrogate-boundary', content, contentHash: HASH_A }],+ _chat: async (opts: ChatOpts) => {+ capturedPrompt = String(opts.messages[0]?.content);+ return okChatResult('[]');+ },+ });++ expect(content.slice(0, 50_000).isWellFormed()).toBe(false); // positive control+ expect(capturedPrompt.isWellFormed()).toBe(true);+ // Truncation must actually occur (not a no-op that trivially passes well-formedness):+ // the straddling pair moves the safe cut back to 49,999 'a's, dropping both the emoji+ // and the trailing prose from the sent prompt entirely.+ expect(capturedPrompt).not.toContain('trailing prose');+ expect(capturedPrompt).toContain('a'.repeat(49_999));+ expect(capturedPrompt.length).toBe(`Source: note/surrogate-boundary\n\n---\n\n${'a'.repeat(49_999)}`.length);+ });+test('malformed output is a counted failure, NOT a zero-yield tombstone', async () => {await seedPage('note/m1');const result = await runPhaseExtractAtoms(engine, {diff --git a/test/extract-atoms-page-discovery.test.ts b/test/extract-atoms-page-discovery.test.tsindex 6d33c16dc7..d421c18fbd 100644--- a/test/extract-atoms-page-discovery.test.ts+++ b/test/extract-atoms-page-discovery.test.ts@@ -585,3 +585,125 @@ describe('#2144: zero-yield tombstone', () => {expect(discovered.map((d) => d.slug)).toContain('article/transient-failure');});});++// Local extract-atoms config knobs (cherry-picked fix): the two new+// KNOWN_CONFIG_KEYS resolve through runPhaseExtractAtoms —+// cycle.extract_atoms.page_discovery_budget caps discovery LIMIT+// cycle.extract_atoms.max_source_chars truncates the prompt payload+describe('local extract-atoms config knobs', () => {+ test('page_discovery_budget caps discovery; max_source_chars truncates the prompt slice', async () => {+ await engine.setConfig('cycle.extract_atoms.page_discovery_budget', '1');+ await engine.setConfig('cycle.extract_atoms.max_source_chars', '600');+ await seedPage({ slug: 'note/knob-1', type: 'note', compiled_truth: 'z'.repeat(2000) });+ await seedPage({ slug: 'note/knob-2', type: 'note', compiled_truth: 'z'.repeat(2000) });++ const captured: string[] = [];+ const capturingChat = async (o: ChatOpts): Promise<ChatResult> => {+ captured.push(String(o.messages[0]?.content ?? ''));+ const text = '[{"title":"knob-atom","atom_type":"insight","body":"b"}]';+ 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',+ };+ };++ const result = await runPhaseExtractAtoms(engine, {+ sourceId: 'default',+ _transcripts: [],+ _chat: capturingChat as never,+ });++ // Discovery honored the configured budget: 2 eligible pages, 1 processed.+ expect(result.details.pages_processed).toBe(1);+ expect(captured.length).toBe(1);+ // Payload after the "Source: ...\n\n---\n\n" preamble is sliced to the+ // configured max_source_chars (default would have been 50_000 → 2000 z's).+ const body = captured[0].split('\n\n---\n\n')[1] ?? '';+ expect(body).toBe('z'.repeat(600));+ }, 30_000);+});++// Invalid-value fallbacks for the two knobs: garbage config must degrade to+// the compiled-in defaults, never crash or zero out discovery.+describe('local extract-atoms config knobs — invalid-value fallbacks', () => {+ /**+ * Observe the EFFECTIVE discovery limit by spying on executeRaw: the+ * page-discovery SQL binds the resolved budget as `LIMIT $4`. This pins+ * resolvePageDiscoveryLimit's parse/clamp behavior without exporting it.+ */+ async function effectiveDiscoveryLimit(): Promise<number> {+ const realExecute = engine.executeRaw.bind(engine);+ let limitParam: number | undefined;+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = (async (+ sql: string,+ params?: unknown[],+ ) => {+ if (sql.includes('atoms_scan_hash') && sql.includes('LIMIT $4')) {+ limitParam = Number((params ?? [])[3]);+ }+ return realExecute(sql as never, params as never);+ }) as typeof engine.executeRaw;+ try {+ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: stubChat('[]') });+ } finally {+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = realExecute;+ }+ if (limitParam === undefined) throw new Error('page-discovery query was never observed');+ return limitParam;+ }++ test('page_discovery_budget: non-positive/NaN fall back to default; floats floored; oversized clamped to 10000', async () => {+ // Unset → compiled-in PAGE_DISCOVERY_BUDGET (50).+ expect(await effectiveDiscoveryLimit()).toBe(50);+ const cases: Array<[string, number]> = [+ ['0', 50], // not > 0 → default+ ['-5', 50], // negative → default+ ['abc', 50], // NaN → default+ ['2.7', 2], // positive finite float is FLOORED (not rejected)+ ['20000', 10000], // ceiling clamp — discovery materializes full bodies per row+ ];+ for (const [value, expected] of cases) {+ await engine.setConfig('cycle.extract_atoms.page_discovery_budget', value);+ expect(await effectiveDiscoveryLimit()).toBe(expected);+ }+ }, 60_000);++ function capturingChat(captured: string[]): (o: ChatOpts) => Promise<ChatResult> {+ return async (o: ChatOpts) => {+ captured.push(String(o.messages[0]?.content ?? ''));+ const 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: 'anthropic:claude-haiku-4-5',+ providerId: 'anthropic',+ };+ };+ }++ test("max_source_chars: '499' (below the 500 floor) rejected — default leaves a 2000-char payload untruncated", async () => {+ await engine.setConfig('cycle.extract_atoms.max_source_chars', '499');+ await seedPage({ slug: 'note/floor-reject', type: 'note', compiled_truth: 'z'.repeat(2000) });+ const captured: string[] = [];+ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: capturingChat(captured) as never });+ expect(captured.length).toBe(1);+ const body = captured[0].split('\n\n---\n\n')[1] ?? '';+ expect(body).toBe('z'.repeat(2000)); // default 50_000 → no truncation+ }, 30_000);++ test("max_source_chars: '500' (at the floor) accepted — payload sliced to 500", async () => {+ await engine.setConfig('cycle.extract_atoms.max_source_chars', '500');+ await seedPage({ slug: 'note/floor-accept', type: 'note', compiled_truth: 'z'.repeat(2000) });+ const captured: string[] = [];+ await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: capturingChat(captured) as never });+ expect(captured.length).toBe(1);+ const body = captured[0].split('\n\n---\n\n')[1] ?? '';+ expect(body).toBe('z'.repeat(500));+ }, 30_000);+});diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.tsindex d64ff863c7..2c3dc39068 100644--- a/test/extract-conversation-facts.test.ts+++ b/test/extract-conversation-facts.test.ts@@ -835,6 +835,58 @@ describe('runExtractConversationFactsCore', () => {expect(Number(terminalRows[0]?.count ?? 0)).toBe(1);});+ test('canonicalizes a raw LLM entity display name before writing facts.entity_slug', async () => {+ chatTextOverride = JSON.stringify({+ facts: [{+ fact: 'Alice Example signed the offer letter.',+ kind: 'event',+ entity: 'Alice Example',+ confidence: 1.0,+ notability: 'high',+ }],+ });++ await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'conversations/imessage/alice-example',+ sleepMs: 0,+ });++ const rows = await engine.executeRaw<{ entity_slug: string | null }>(+ `SELECT entity_slug FROM facts+ WHERE source = $1 AND source_markdown_slug = $2`,+ [PER_SEGMENT_SOURCE_PREFIX, 'conversations/imessage/alice-example'],+ );+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every((row) => row.entity_slug === 'people/alice-example')).toBe(true);+ });++ test('preserves an already-canonical LLM entity slug', async () => {+ chatTextOverride = JSON.stringify({+ facts: [{+ fact: 'Alice Example started the new role.',+ kind: 'event',+ entity: 'people/alice-example',+ confidence: 1.0,+ notability: 'high',+ }],+ });++ await runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slug: 'conversations/imessage/alice-example',+ sleepMs: 0,+ });++ const rows = await engine.executeRaw<{ entity_slug: string | null }>(+ `SELECT entity_slug FROM facts+ WHERE source = $1 AND source_markdown_slug = $2`,+ [PER_SEGMENT_SOURCE_PREFIX, 'conversations/imessage/alice-example'],+ );+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every((row) => row.entity_slug === 'people/alice-example')).toBe(true);+ });+test('terminal outcome skips a completed page after checkpoint GC', async () => {await runExtractConversationFactsCore(engine, {sourceId: 'default',diff --git a/test/extract-cross-source-resolution-observability.test.ts b/test/extract-cross-source-resolution-observability.test.tsnew file mode 100644index 0000000000..c8a10fb9f0--- /dev/null+++ b/test/extract-cross-source-resolution-observability.test.ts@@ -0,0 +1,94 @@+/**+ * `resolveCandidateSources` must distinguish a cross-source drop (target+ * resolves via global_basename to a page that exists only in a source other+ * than the origin's or 'default') from a genuinely missing target/from-slug.+ * Both used to return a bare `null`, making a real multi-source graph+ * sparsity problem indistinguishable from a plain dead link (#2589).+ *+ * This is default-deny by design (source isolation — see CLAUDE.md's+ * "Source isolation" cross-cutting invariant): a cross-source drop still+ * does NOT create the edge. Only the *reason* callers can attribute to the+ * drop changes.+ */++import { describe, expect, test } from 'bun:test';+import { resolveCandidateSources } from '../src/commands/extract.ts';+import type { LinkCandidate } from '../src/core/link-extraction.ts';++function candidate(targetSlug: string, fromSlug?: string): LinkCandidate {+ return { fromSlug, targetSlug, linkType: 'mentions', context: 'ctx' };+}++describe('resolveCandidateSources — reason attribution (#2589)', () => {+ test('resolves when target exists in the origin source', () => {+ const allSlugs = new Set(['origin-page', 'target-page']);+ const slugToSources = new Map<string, string[]>([+ ['origin-page', ['source-a']],+ ['target-page', ['source-a']],+ ]);+ const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources);+ expect(r.ok).toBe(true);+ if (r.ok) {+ expect(r.fromSourceId).toBe('source-a');+ expect(r.toSourceId).toBe('source-a');+ }+ });++ test('falls back to default when target only exists there', () => {+ const allSlugs = new Set(['origin-page', 'target-page']);+ const slugToSources = new Map<string, string[]>([+ ['origin-page', ['source-a']],+ ['target-page', ['default']],+ ]);+ const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources);+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.toSourceId).toBe('default');+ });++ test('reason=missing_target when the target slug is not in allSlugs at all', () => {+ const allSlugs = new Set(['origin-page']);+ const slugToSources = new Map<string, string[]>([['origin-page', ['source-a']]]);+ const r = resolveCandidateSources(candidate('nonexistent-page'), 'origin-page', 'source-a', allSlugs, slugToSources);+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toBe('missing_target');+ });++ test('reason=missing_from when the origin slug is not in allSlugs', () => {+ const allSlugs = new Set(['target-page']);+ const slugToSources = new Map<string, string[]>([['target-page', ['source-a']]]);+ const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources);+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toBe('missing_from');+ });++ test('reason=cross_source when the target exists only in an unrelated source (#2589 repro)', () => {+ // 6-source federated brain: origin in comms-imessage, target only in+ // people-vault. Neither the origin source nor 'default' — exactly the+ // silently-dropped case reported on #2589.+ const allSlugs = new Set(['comms-imessage/thread-1', 'people-vault/alice-example']);+ const slugToSources = new Map<string, string[]>([+ ['comms-imessage/thread-1', ['comms-imessage']],+ ['people-vault/alice-example', ['people-vault']],+ ]);+ const r = resolveCandidateSources(+ candidate('people-vault/alice-example'),+ 'comms-imessage/thread-1',+ 'comms-imessage',+ allSlugs,+ slugToSources,+ );+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.reason).toBe('cross_source');+ });++ test('cross_source is still a drop, not an edge — never returns fromSlug/toSourceId', () => {+ const allSlugs = new Set(['origin-page', 'target-page']);+ const slugToSources = new Map<string, string[]>([+ ['origin-page', ['source-a']],+ ['target-page', ['source-b']],+ ]);+ const r = resolveCandidateSources(candidate('target-page'), 'origin-page', 'source-a', allSlugs, slugToSources);+ expect(r).not.toHaveProperty('toSourceId');+ expect(r).not.toHaveProperty('fromSourceId');+ });+});diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.tsindex 178f984ece..5815f64a9f 100644--- a/test/extract-facts-phase.test.ts+++ b/test/extract-facts-phase.test.ts@@ -13,6 +13,7 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tesimport { 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';let engine: PGLiteEngine;@@ -52,6 +53,20 @@ async function putPage(slug: string, body: string): Promise<void> {});}+// #3625: writes compiled_truth and timeline as SEPARATE columns, mirroring+// what splitBody() produces when a `## Facts` fence sits below the+// `<!-- timeline -->` sentinel — the fence text lands in `timeline`, not+// `compiled_truth`, exactly as MCP put_page would store it.+async function putPageWithTimeline(slug: string, compiledTruth: string, timeline: string): Promise<void> {+ await engine.putPage(slug, {+ title: slug,+ type: 'person',+ compiled_truth: compiledTruth,+ frontmatter: {},+ timeline,+ });+}+const FACT_FENCE = (rows: string): string => `# PageBody.@@ -299,6 +314,261 @@ describe('runExtractFacts — happy path', () => {expect(Number(rows.rows[0].n)).toBe(0);});+ test('#3625: a Facts fence below the timeline sentinel is preserved, not deleted, and warns loudly', async () => {+ // Seed the page with the fence in its normal place (above the sentinel)+ // and let it index normally.+ await putPage('people/alice', FACT_FENCE(+ `| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+| 2 | Prefers async | preference | 0.85 | private | medium | 2026-04-29 | | OH | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const seeded = await (engine as any).db.query(+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,+ );+ expect(seeded.rows).toHaveLength(2);++ // #3625 repro: rewrite the page so the SAME fence content now lives in+ // `timeline` (below the sentinel) instead of `compiled_truth` — exactly+ // what splitBody() produces for a page whose `## Facts` fence was+ // written below `<!-- timeline -->`. compiled_truth carries none of the+ // fence text, so parseFactsFence(compiled_truth) sees zero facts.+ await putPageWithTimeline(+ 'people/alice',+ '# Page\n\nBody.\n',+ FACT_FENCE(+ `| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+| 2 | Prefers async | preference | 0.85 | private | medium | 2026-04-29 | | OH | |`,+ ),+ );++ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ // The fix: this must NOT read as "fence removed" and must NOT delete+ // the previously-indexed rows.+ expect(r.factsDeleted).toBe(0);+ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);++ // 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(['Founded Acme', 'Prefers async']);+ });++ test('#3625 control: a genuinely fence-less page (no fence anywhere in the body) still wipes as before', async () => {+ // Same shape as the misplaced-fence case above, but this time the fence+ // is truly absent from BOTH compiled_truth and timeline — the existing+ // "user deleted the fence" contract must still hold; the #3625 guard+ // must not swallow genuine deletions.+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ await putPageWithTimeline('people/alice', '# Just a page\n\nNo fence.\n', 'Some unrelated timeline prose.\n');+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(1);+ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(false);++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const rows = await (engine as any).db.query(+ `SELECT COUNT(*) AS n FROM facts WHERE source_markdown_slug = 'people/alice'`,+ );+ expect(Number(rows.rows[0].n)).toBe(0);+ });++ test('#3625 adversarial review finding: the marker merely mentioned inside a ```code block``` does not block a genuine deletion', async () => {+ // A naive `.includes(FACTS_FENCE_BEGIN)` check false-positives here — the+ // marker text is present in timeline, but only as documentation, not as+ // a real fence. The real fence was genuinely removed and must delete.+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ await putPageWithTimeline(+ 'people/alice',+ '# Alice\n\nThe real Facts fence was removed.\n',+ '## Docs\n\n```markdown\n<!--- gbrain:facts:begin -->\nexample only\n```\n',+ );+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(1);+ expect(r.warnings).toEqual([]);+ });++ test('#3625 adversarial review finding: the marker merely quoted in prose does not block a genuine deletion', async () => {+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ await putPageWithTimeline(+ 'people/alice',+ '# Alice\n\nThe real Facts fence was removed.\n',+ '> Historical docs mention the token <!--- gbrain:facts:begin -->, but this is not a fence.\n',+ );+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(1);+ expect(r.warnings).toEqual([]);+ });++ test('#3625 control: a genuine unbalanced marker (own line, not inside a code block) still blocks deletion', async () => {+ // Contrast with the two false-positive tests above — this marker IS a+ // real (if malformed/unbalanced) fence occurrence and must still guard.+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ await putPageWithTimeline(+ 'people/alice',+ '# Alice\n\nNo compiled fence.\n',+ '<!--- gbrain:facts:begin -->\nPRIVATE_UNBALANCED_ROW\n',+ );+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(0);+ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);+ });++ test('#3625 adversarial review round 2: a CRLF-line-ending code block mentioning the marker does not false-positive', async () => {+ // Round-1 fix (scanFencedBlocks + string removal) normalized line+ // endings internally but tried to remove fence text from the+ // UN-normalized original string, silently failing to strip a CRLF code+ // block and leaving the false positive in place. The round-2 fix+ // (single-pass line scanner, one \r\n|\r|\n split applied throughout)+ // must handle this correctly.+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ await putPageWithTimeline(+ 'people/alice',+ '# Alice\n\nThe real Facts fence was removed.\n',+ '## Docs\r\n\r\n```markdown\r\n<!--- gbrain:facts:begin -->\r\nexample only\r\n```\r\n',+ );+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(1);+ expect(r.warnings).toEqual([]);+ });++ test('#3625 adversarial review round 2: two identical code-block mentions of the marker do not false-positive', async () => {+ await putPage('people/alice', FACT_FENCE(+ `| 1 | seeded | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,+ ));+ await runExtractFacts(engine, { slugs: ['people/alice'] });++ const codeBlock = '```markdown\n<!--- gbrain:facts:begin -->\nexample only\n```\n';+ await putPageWithTimeline(+ 'people/alice',+ '# Alice\n\nThe real Facts fence was removed.\n',+ `${codeBlock}\n${codeBlock}`,+ );+ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });++ expect(r.factsDeleted).toBe(1);+ expect(r.warnings).toEqual([]);+ });++ test('#3625 via the real MCP write path: a stray fence below the sentinel is preserved even when import-file.ts is in play', async () => {+ // Codex review finding: the two tests above write compiled_truth/timeline+ // directly via engine.putPage, bypassing importFromContent's own #2044+ // remote-preservation logic (restores an old fence into compiled_truth+ // when an incoming remote write's compiled half has ZERO facts — which+ // would otherwise mask a below-sentinel duplicate by never even letting+ // this test reach the state it wants to prove: confirmed by running the+ // simpler "compiled_truth ends up with zero facts" version of this test+ // first — #2044 fired and restored the OLD fence, so compiled_truth+ // never went empty and this guard was never exercised).+ //+ // Reproduce a case #2044 does NOT swallow: the incoming remote write's+ // compiled_truth keeps ONE valid fact above the sentinel (so+ // incomingFacts.facts.length > 0 — #2044's restore condition requires+ // exactly 0 and does not fire) while ALSO carrying a stray duplicate+ // fence below the sentinel (e.g. an agent re-appending a "## Facts"+ // section near new content it's adding at the bottom of the page).+ // splitBody() (inside putPage, called by importFromContent) does the+ // real fence/sentinel split — no direct column poking.+ const seed = `---+title: alice+type: person+---++Some body content.++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+| 2 | Prefers async | preference | 0.85 | world | medium | 2026-04-29 | | OH | |+<!--- gbrain:facts:end -->++<!-- timeline -->+`;+ await importFromContent(engine, 'people/alice', seed, { noEmbed: true, remote: true });+ await runExtractFacts(engine, { slugs: ['people/alice'] });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const seeded = await (engine as any).db.query(+ `SELECT fact FROM facts WHERE source_markdown_slug = 'people/alice'`,+ );+ expect(seeded.rows).toHaveLength(2);++ // A malformed remote rewrite: row 1 stays correctly placed above the+ // sentinel (so #2044's restore never fires — incomingFacts.facts.length+ // is 1, not 0), but row 2 got duplicated into a second fence below it.+ const misplaced = `---+title: alice+type: person+---++Some body content.++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | Founded Acme | fact | 1.0 | world | high | 2017-01-01 | | linkedin | |+<!--- gbrain:facts:end -->++<!-- timeline -->++## Facts++<!--- gbrain:facts:begin -->+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | Prefers async | preference | 0.85 | world | medium | 2026-04-29 | | OH | |+<!--- gbrain:facts:end -->+`;+ await importFromContent(engine, 'people/alice', misplaced, { noEmbed: true, remote: true });++ const page = await engine.getPage('people/alice');+ // Sanity: confirm the real write path actually reproduces the #3625+ // precondition (#2044 did NOT restore anything away, and a fence marker+ // really did land in timeline) before trusting the assertions below.+ expect(parseFactsFence(page!.compiled_truth ?? '').facts).toHaveLength(1);+ expect((page!.timeline ?? '')).toContain('gbrain:facts:begin');++ const r = await runExtractFacts(engine, { slugs: ['people/alice'] });+ expect(r.factsDeleted).toBe(0);+ expect(r.warnings.some(w => w.includes('FACTS_FENCE_BELOW_SENTINEL'))).toBe(true);++ // 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'`,+ );+ expect(rows.rows).toHaveLength(2);+ });+test('dry-run does not touch DB', async () => {await putPage('people/alice', FACT_FENCE(`| 1 | A | fact | 1.0 | world | medium | 2026-01-01 | | s | |`,diff --git a/test/extract-rollup-expected-limit.test.ts b/test/extract-rollup-expected-limit.test.tsnew file mode 100644index 0000000000..5f8c1e83cc--- /dev/null+++ b/test/extract-rollup-expected-limit.test.ts@@ -0,0 +1,124 @@+/**+ * #4482 — doctor's extract_health treated EXPECTED budget/deadline cap stops+ * as extraction failures: extract-conversation-facts recorded+ * halted=budget_exhausted and propose-takes folded budget/deadline/global-+ * error into one halt_delta, so a brain whose backlog is simply bigger than+ * one run's per-source budget WARN'd "halt rate > 10%" under completely+ * normal, self-resolving operation — indistinguishable from a provider/auth+ * failure.+ *+ * Fix shape (per the issue's acceptance criteria):+ * - migration adds an orthogonal `expected_limit_count` to extract_rollup_7d;+ * - `classifyRunStop` (shared, pure) splits cap-only stops from error halts;+ * - both extractors write cap stops as expected_limit_delta, errors as+ * halt_delta;+ * - doctor's failure rate excludes caps (they join the denominator as+ * successful partial runs) while cap-hits stay observable per-kind;+ * - old rows (expected_limit_count=0 default) keep today's semantics.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { upsertExtractRollup, classifyRunStop } from '../src/core/extract/rollup-writer.ts';+import { computeExtractHealthCheck } from '../src/commands/doctor/checks/extraction-sync.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++describe('classifyRunStop (#4482)', () => {+ test('clean completion', () => {+ expect(classifyRunStop({})).toEqual({+ round_completed_delta: 1, halt_delta: 0, expected_limit_delta: 0,+ });+ });++ test('budget cap only → expected limit, NOT a halt', () => {+ expect(classifyRunStop({ budget_exhausted: true })).toEqual({+ round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1,+ });+ });++ test('deadline cap only → expected limit, NOT a halt', () => {+ expect(classifyRunStop({ deadline_hit: true })).toEqual({+ round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1,+ });+ });++ test('global error → halt, unchanged from today', () => {+ expect(classifyRunStop({ error: true })).toEqual({+ round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0,+ });+ });++ test('cap AND error → halt wins (an error is present)', () => {+ expect(classifyRunStop({ budget_exhausted: true, error: true })).toEqual({+ round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0,+ });+ });+});++describe('extract_rollup_7d.expected_limit_count (#4482)', () => {+ test('migration added the column and the writer records the delta', async () => {+ const res = await upsertExtractRollup(engine, {+ kind: 'facts.conversation',+ source_id: 'default',+ expected_limit_delta: 1,+ });+ expect(res.ok).toBe(true);+ const rows = await engine.executeRaw<{ expected_limit_count: number; halt_count: number }>(+ `SELECT expected_limit_count, halt_count FROM extract_rollup_7d+ WHERE kind = 'facts.conversation' AND source_id = 'default'`);+ expect(rows.length).toBe(1);+ expect(Number(rows[0]!.expected_limit_count)).toBe(1);+ expect(Number(rows[0]!.halt_count)).toBe(0);+ });++ test('doctor: cap-only stops do NOT raise the failure warning; error halts still do', async () => {+ await engine.executeRaw('DELETE FROM extract_rollup_7d');+ // Kind A: 5 runs, ALL stopped at the expected budget cap. Normal+ // backlog-bigger-than-budget operation — must not warn.+ for (let i = 0; i < 5; i++) {+ await upsertExtractRollup(engine, {+ kind: 'facts.conversation', source_id: 'default', expected_limit_delta: 1,+ });+ }+ let check = await computeExtractHealthCheck(engine);+ expect(check.status).toBe('ok');++ // Kind B: real error halts past the 10% threshold — still warns.+ await upsertExtractRollup(engine, {+ kind: 'takes.proposed', source_id: 'default', halt_delta: 1,+ });+ await upsertExtractRollup(engine, {+ kind: 'takes.proposed', source_id: 'default', round_completed_delta: 1,+ });+ check = await computeExtractHealthCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('takes.proposed');+ expect(check.message).not.toContain('facts.conversation');+ });++ test('caps join the failure-rate denominator (errors amid many caps stay proportionate)', async () => {+ await engine.executeRaw('DELETE FROM extract_rollup_7d');+ // 1 error halt + 19 cap stops = 5% failure rate → below the 10% bar.+ await upsertExtractRollup(engine, { kind: 'facts.conversation', source_id: 'default', halt_delta: 1 });+ for (let i = 0; i < 19; i++) {+ await upsertExtractRollup(engine, { kind: 'facts.conversation', source_id: 'default', expected_limit_delta: 1 });+ }+ const check = await computeExtractHealthCheck(engine);+ expect(check.status).toBe('ok');+ const kinds = (check.details as { kinds: Array<Record<string, unknown>> }).kinds;+ const kind = kinds.find(k => k.kind === 'facts.conversation')!;+ // Cap-hits stay observable as a capacity signal.+ expect(Number(kind.expected_limit_count)).toBe(19);+ });+});diff --git a/test/extract-takes-from-pages-progression.test.ts b/test/extract-takes-from-pages-progression.test.tsindex f8bc2dbc29..8454b26366 100644--- a/test/extract-takes-from-pages-progression.test.ts+++ b/test/extract-takes-from-pages-progression.test.ts@@ -13,6 +13,9 @@* includeCovered restores the full rescan (refresh semantics).*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {configureGateway,@@ -22,12 +25,22 @@ import {import { extractTakesFromPages } from '../src/core/extract-takes-from-pages.ts';let engine: PGLiteEngine;+let repo: string;++/** #4473: takes are md-first — each probe page needs a real .md home. */+function seedMd(slug: string, body: string): void {+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\n${body}\n`, 'utf-8');+}beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ repo = mkdtempSync(join(tmpdir(), 'gb-takes-progression-'));+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ await engine.setConfig('sync.repo_path', repo);+configureGateway({chat_model: 'anthropic:claude-haiku-4-5-20251001',env: { ANTHROPIC_API_KEY: 'sk-ant-test-takes-progression' },@@ -48,12 +61,15 @@ beforeAll(async () => {await engine.putPage('concepts/progression-b', {type: 'concept', title: 'B', compiled_truth: body, frontmatter: {},});+ seedMd('concepts/progression-a', body);+ seedMd('concepts/progression-b', body);});afterAll(async () => {__setChatTransportForTests(null);resetGateway();await engine.disconnect();+ rmSync(repo, { recursive: true, force: true });});describe('extractTakesFromPages — bootstrap progression', () => {@@ -74,6 +90,7 @@ describe('extractTakesFromPages — bootstrap progression', () => {await engine.putPage('concepts/progression-c', {type: 'concept', title: 'C', compiled_truth: body, frontmatter: {},});+ seedMd('concepts/progression-c', body);const r3 = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 50 });expect(r3.pages_scanned).toBe(1);});diff --git a/test/extract-takes-md-first.test.ts b/test/extract-takes-md-first.test.tsnew file mode 100644index 0000000000..b58c3a5d66--- /dev/null+++ b/test/extract-takes-md-first.test.ts@@ -0,0 +1,168 @@+/**+ * #4473 — takes bootstrap is md-FIRST.+ *+ * extractTakesFromPages used to call engine.addTakesBatch directly, minting+ * DB-only takes rows. Takes are markdown-canonical (takes-write.ts contract):+ * the md→DB reconcile upserts from the fence and the extract rebuild lane+ * deletes+reinserts from md, so DB-only rows were silently clobbered by the+ * next sync/extract. Pins:+ *+ * 1. a bootstrapped claim lands in the page's ## Takes fence on disk AND+ * mirrors to the takes table (same rows);+ * 2. a page with no locatable .md file is SKIPPED (reason+ * mirror_unavailable) — no DB-only row is minted, and the skip happens+ * BEFORE the LLM call (no classifier budget burned);+ * 3. dry-run counts claims without touching disk or DB;+ * 4. row numbers derive from the fence (existing fence rows are extended,+ * not collided with at row_num=1).+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ configureGateway,+ resetGateway,+ __setChatTransportForTests,+} from '../src/core/ai/gateway.ts';+import { extractTakesFromPages } from '../src/core/extract-takes-from-pages.ts';+import { parseTakesFence } from '../src/core/takes-fence.ts';++let engine: PGLiteEngine;+let repo: string;+let chatCalls: string[] = [];++const BODY = 'An opinion-bearing body long enough to clear the 200-char eligibility floor. '.repeat(5);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ repo = mkdtempSync(join(tmpdir(), 'gb-takes-md-first-'));+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ await engine.setConfig('sync.repo_path', repo);++ configureGateway({+ chat_model: 'anthropic:claude-haiku-4-5-20251001',+ env: { ANTHROPIC_API_KEY: 'sk-ant-test-md-first' },+ });+ __setChatTransportForTests(async (opts) => {+ // Record which page was classified (the <page slug="..."> wrapper).+ const user = opts.messages?.find((m: { role: string }) => m.role === 'user');+ const text = typeof user?.content === 'string' ? user.content : JSON.stringify(user?.content ?? '');+ const m = text.match(/<page slug="([^"]+)"/);+ chatCalls.push(m?.[1] ?? '(unknown)');+ return {+ text: '[{"claim":"a bootstrapped claim","kind":"take","weight":0.7}]',+ blocks: [{ type: 'text' as const, text: '[{"claim":"a bootstrapped claim","kind":"take","weight":0.7}]' }],+ stopReason: 'end' as const,+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5-20251001',+ providerId: 'anthropic',+ };+ });+});++afterAll(async () => {+ __setChatTransportForTests(null);+ resetGateway();+ await engine.disconnect();+ rmSync(repo, { recursive: true, force: true });+});++describe('extractTakesFromPages — md-first (#4473)', () => {+ test('bootstrapped claim lands in the fence on disk AND mirrors to the DB', async () => {+ const slug = 'concepts/md-first-covered';+ await engine.putPage(slug, { type: 'concept', title: 'Covered', compiled_truth: BODY, frontmatter: {} });+ writeFileSync(join(repo, `${slug}.md`), `# Covered\n\n${BODY}\n`, 'utf-8');++ const r = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 50, holder: 'system' });+ expect(r.claims_extracted).toBe(1);+ expect(r.pages_skipped).toBe(0);++ // Markdown is canonical: the fence exists on disk with the claim.+ const fence = parseTakesFence(readFileSync(join(repo, `${slug}.md`), 'utf-8'));+ expect(fence.takes.length).toBe(1);+ expect(fence.takes[0].claim).toBe('a bootstrapped claim');+ expect(fence.takes[0].holder).toBe('system');++ // DB mirror carries the same row (keyed on the fence row number).+ const rows = await engine.executeRaw<{ claim: string; row_num: number }>(+ `SELECT t.claim, t.row_num FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1`,+ [slug],+ );+ expect(rows.length).toBe(1);+ expect(rows[0].claim).toBe('a bootstrapped claim');+ expect(rows[0].row_num).toBe(fence.takes[0].rowNum);+ });++ test('page with no locatable .md file: skipped BEFORE the LLM call, no DB-only row', async () => {+ const slug = 'concepts/md-first-db-born';+ await engine.putPage(slug, { type: 'concept', title: 'DB-born', compiled_truth: BODY, frontmatter: {} });+ // No .md file written — a DB-born page.++ chatCalls = [];+ const r = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 50 });+ expect(r.pages_skipped).toBe(1);+ expect(r.skipped).toEqual([{ slug, reason: 'mirror_unavailable' }]);+ expect(r.claims_extracted).toBe(0);+ // The classifier never ran for the unwritable page (budget honesty).+ expect(chatCalls).not.toContain(slug);++ // No DB-only row was minted (the pre-fix failure mode).+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1`,+ [slug],+ );+ expect(rows[0].n).toBe(0);+ // And no twin .md file was created.+ expect(existsSync(join(repo, `${slug}.md`))).toBe(false);+ });++ test('dry-run counts claims without touching disk or DB', async () => {+ const slug = 'concepts/md-first-dry';+ await engine.putPage(slug, { type: 'concept', title: 'Dry', compiled_truth: BODY, frontmatter: {} });+ writeFileSync(join(repo, `${slug}.md`), `# Dry\n\n${BODY}\n`, 'utf-8');++ const r = await extractTakesFromPages(engine, { bootstrapEnabled: true, maxPages: 50, dryRun: true });+ // Dry-run rescans BOTH uncovered pages (db-born included — no file gate on dry-run).+ expect(r.claims_extracted).toBeGreaterThanOrEqual(1);+ const md = readFileSync(join(repo, `${slug}.md`), 'utf-8');+ expect(md).not.toContain('gbrain:takes');+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1`,+ [slug],+ );+ expect(rows[0].n).toBe(0);+ });++ test('existing fence rows are extended, not collided with at row_num=1', async () => {+ const slug = 'concepts/md-first-extend';+ await engine.putPage(slug, { type: 'concept', title: 'Extend', compiled_truth: BODY, frontmatter: {} });+ // Pre-existing fence with one hand-written row.+ writeFileSync(+ join(repo, `${slug}.md`),+ `# Extend\n\n${BODY}\n\n## Takes\n\n<!--- gbrain:takes:begin -->\n` ++ `| # | claim | kind | who | weight | since | source |\n` ++ `|---|-------|------|-----|--------|-------|--------|\n` ++ `| 1 | Hand-written claim | take | world | 0.5 | | |\n` ++ `<!--- gbrain:takes:end -->\n`,+ 'utf-8',+ );++ const r = await extractTakesFromPages(engine, {+ bootstrapEnabled: true, maxPages: 50, includeCovered: true, sourceIdFilter: 'default',+ });+ expect(r.claims_extracted).toBeGreaterThanOrEqual(1);++ const fence = parseTakesFence(readFileSync(join(repo, `${slug}.md`), 'utf-8'));+ const claims = fence.takes.map((t) => t.claim);+ expect(claims).toContain('Hand-written claim');+ expect(claims).toContain('a bootstrapped claim');+ // The appended row got the NEXT fence row number, not a row_num=1 collision.+ const appended = fence.takes.find((t) => t.claim === 'a bootstrapped claim');+ expect(appended?.rowNum).toBe(2);+ });+});diff --git a/test/extract-takes-model-resolution.test.ts b/test/extract-takes-model-resolution.test.tsindex d0715fa294..39fa1381ad 100644--- a/test/extract-takes-model-resolution.test.ts+++ b/test/extract-takes-model-resolution.test.ts@@ -11,6 +11,9 @@* idiom) — NOT the DB config plane (engine.getConfig('chat_model')).*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {configureGateway,@@ -20,15 +23,19 @@ import {import { extractTakesFromPages } from '../src/core/extract-takes-from-pages.ts';let engine: PGLiteEngine;+let repo: string;const seenModels: string[] = [];let pageN = 0;-/** Each test seeds a fresh uncovered page so the extraction loop fires. */+/** Each test seeds a fresh uncovered page so the extraction loop fires.+ * #4473: takes are md-first — the page needs a real .md home too. */async function seedPage(): Promise<void> {const body = 'An opinion-bearing body long enough to clear the 200-char eligibility floor. '.repeat(5);- await engine.putPage(`concepts/model-resolution-${pageN++}`, {+ const slug = `concepts/model-resolution-${pageN++}`;+ await engine.putPage(slug, {type: 'concept', title: `M${pageN}`, compiled_truth: body, frontmatter: {},});+ writeFileSync(join(repo, `${slug}.md`), `# M${pageN}\n\n${body}\n`, 'utf-8');}beforeAll(async () => {@@ -36,6 +43,10 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();+ repo = mkdtempSync(join(tmpdir(), 'gb-takes-model-res-'));+ mkdirSync(join(repo, 'concepts'), { recursive: true });+ await engine.setConfig('sync.repo_path', repo);+__setChatTransportForTests(async (opts) => {seenModels.push(opts.model ?? '(unset)');return {@@ -53,6 +64,7 @@ afterAll(async () => {__setChatTransportForTests(null);resetGateway();await engine.disconnect();+ rmSync(repo, { recursive: true, force: true });});beforeEach(() => {diff --git a/test/extract-timeline-from-meetings.test.ts b/test/extract-timeline-from-meetings.test.tsindex 0be77f063f..a979ed97ff 100644--- a/test/extract-timeline-from-meetings.test.ts+++ b/test/extract-timeline-from-meetings.test.ts@@ -10,7 +10,7 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();-}, 60_000);+}, 240_000); // cold PGLite init can exceed 60s on a loaded CI/dev machineafterAll(async () => {await engine.disconnect();@@ -98,3 +98,48 @@ describe('extractTimelineFromMeetings', () => {expect(timeline).toHaveLength(0);});});++// ─── #4542 — CLI surface: a zero-meeting run must WARN, not mimic success ──+//+// `gbrain extract timeline --from-meetings --source db` on a brain with no+// meeting-typed pages printed "0 entries on 0 entity pages from 0 meetings"+// and exited 0 — indistinguishable from a healthy no-op. Worse,+// --from-meetings REPLACES the default timeline pass (extract.ts runs it+// solo), so users expecting "meetings AND the usual pass" silently got+// NEITHER. The CLI now warns on stderr, names the meeting predicate, and+// points at omitting the flag.+describe('#4542 zero-meetings warning at the CLI surface', () => {+ async function runExtractCapturingStderr(args: string[]): Promise<string[]> {+ const { runExtract } = await import('../src/commands/extract.ts');+ const lines: string[] = [];+ const savedError = console.error;+ console.error = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };+ try {+ await runExtract(engine, args);+ } finally {+ console.error = savedError;+ }+ return lines;+ }++ it('warns on stderr with the predicate + omit hint when 0 meetings matched', async () => {+ const stderrLines = await runExtractCapturingStderr(['timeline', '--from-meetings', '--source', 'db']);+ const joined = stderrLines.join('\n');+ expect(joined).toContain("type = 'meeting'");+ expect(joined).toContain('omit --from-meetings');+ expect(joined.toLowerCase()).toContain('replaces');+ });++ it('stays quiet when meetings exist', async () => {+ await engine.putPage('meetings/2026-04-20-sync', {+ type: 'meeting',+ title: 'Weekly Sync',+ compiled_truth: 'Discussed roadmap.',+ timeline: '',+ frontmatter: {},+ effective_date: new Date('2026-04-20T00:00:00.000Z'),+ });+ const stderrLines = await runExtractCapturingStderr(['timeline', '--from-meetings', '--source', 'db']);+ expect(stderrLines.join('\n')).not.toContain('omit --from-meetings');+ });+});diff --git a/test/facts-absorb-log.test.ts b/test/facts-absorb-log.test.tsindex fe7c6405fb..543c88d215 100644--- a/test/facts-absorb-log.test.ts+++ b/test/facts-absorb-log.test.ts@@ -10,6 +10,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import {writeFactsAbsorbLog,+ writeFactsAbsorbFailure,classifyFactsAbsorbError,FACTS_ABSORB_REASONS,} from '../src/core/facts/absorb-log.ts';@@ -125,7 +126,22 @@ describe('writeFactsAbsorbLog — ingest_log row shape', () => {expect(FACTS_ABSORB_REASONS).toContain('malformed_output');expect(FACTS_ABSORB_REASONS).toContain('non_terminal_stop');expect(FACTS_ABSORB_REASONS).toContain('truncated_output');- expect(FACTS_ABSORB_REASONS.length).toBe(12);+ expect(FACTS_ABSORB_REASONS).toContain('gateway_auth');+ expect(FACTS_ABSORB_REASONS).toContain('gateway_billing');+ expect(FACTS_ABSORB_REASONS).toContain('gateway_rate_limit');+ expect(FACTS_ABSORB_REASONS.length).toBe(15);+ });++ test.each([+ ['typed-auth', Object.assign(new Error('invalid api key sk-sensitive-auth'), { status: 401 }), 'gateway_auth'],+ ['typed-billing', new Error('credit balance is too low: acct-sensitive'), 'gateway_billing'],+ ['typed-rate', Object.assign(new Error('rate limit: req-sensitive'), { status: 429 }), 'gateway_rate_limit'],+ ])('%s provider failure records only its typed class', async (ref, err, reason) => {+ await writeFactsAbsorbFailure(engine, `meetings/${ref}`, err);+ const log = await engine.getIngestLog({ limit: 30 });+ const ours = log.find(r => r.source_ref === `meetings/${ref}`);+ expect(ours?.summary).toBe(`${reason}: provider request failed (Error)`);+ expect(ours?.summary).not.toContain('sensitive');});});diff --git a/test/facts-backstop-remedy-verb.test.ts b/test/facts-backstop-remedy-verb.test.tsnew file mode 100644index 0000000000..996b3cff80--- /dev/null+++ b/test/facts-backstop-remedy-verb.test.ts@@ -0,0 +1,45 @@+// #4489 — the facts backstop thin-client-fallback warning must name a REAL+// CLI remedy. It used to say "Configure local_path via `gbrain sources+// update`", but the sources dispatcher has no `update` case — the actual+// remedy is the #3903 non-destructive attach: `gbrain sources add <id>+// --path <dir>` (sources-ops.ts UPDATEs local_path when the existing row is+// path-less).+//+// Source-text pin: cheap, hermetic, and cross-checked against the dispatcher+// so the warning can never drift back to a verb that doesn't exist.++import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const REPO_ROOT = join(import.meta.dir, '..');+// test-reads-source-ok: comment-contract pin — the warning's remedy TEXT is+// the product surface; cross-checked against the dispatcher's case labels.+const backstopSrc = readFileSync(join(REPO_ROOT, 'src/core/facts/backstop.ts'), 'utf-8');+// test-reads-source-ok: same pin — dispatcher side of the cross-check above.+const sourcesSrc = readFileSync(join(REPO_ROOT, 'src/commands/sources.ts'), 'utf-8');++describe('facts backstop thin-client-fallback remedy verb (#4489)', () => {+ test('warning does not name the nonexistent `gbrain sources update` verb', () => {+ expect(backstopSrc).not.toContain('gbrain sources update');+ });++ test('warning names the real attach remedy (`gbrain sources add ... --path`)', () => {+ // The fallback warning block should point at sources add with --path.+ const idx = backstopSrc.indexOf('facts:thin-client-fallback');+ expect(idx).toBeGreaterThan(-1);+ const windowText = backstopSrc.slice(idx, idx + 600);+ expect(windowText).toContain('gbrain sources add');+ expect(windowText).toContain('--path');+ });++ test('every `gbrain sources <verb>` the backstop recommends exists in the dispatcher', () => {+ // Extract each "gbrain sources <verb>" mention from the backstop and+ // assert the sources dispatcher has a matching `case '<verb>':`.+ const mentions = [...backstopSrc.matchAll(/gbrain sources ([a-z-]+)/g)].map((m) => m[1]!);+ expect(mentions.length).toBeGreaterThan(0);+ for (const verb of new Set(mentions)) {+ expect(sourcesSrc).toContain(`case '${verb}':`);+ }+ });+});diff --git a/test/fuzz/filesystem-validators.test.ts b/test/fuzz/filesystem-validators.test.tsindex 7e68724e25..0068c986b2 100644--- a/test/fuzz/filesystem-validators.test.ts+++ b/test/fuzz/filesystem-validators.test.ts@@ -23,12 +23,27 @@ import { validateUploadPath } from '../../src/core/operations.ts';const NUM_RUNS = 500;let baseTmpRoot: string;+let savedCwd: string;beforeAll(() => {baseTmpRoot = mkdtempSync(join(tmpdir(), 'gbrain-fuzz-fs-'));+ // #4479: the `..`-probe expectations assume a cwd DEEP enough that+ // resolve('..') stays well below the filesystem root. In the CI container+ // the workdir is the depth-1 /app mount, where '..' resolves to '/' and+ // relative('/', box) no longer starts with '..' — the probe "passes"+ // confinement and the test false-fails as a container-only failure. Run+ // the whole file from a guaranteed-deep working directory instead of+ // depending on where the harness happened to be launched.+ savedCwd = process.cwd();+ const deepCwd = join(baseTmpRoot, 'deep', 'cwd', 'for', 'traversal', 'probes');+ mkdirSync(deepCwd, { recursive: true });+ process.chdir(deepCwd);});afterAll(() => {+ // Restore BEFORE removing baseTmpRoot — rmSync of the cwd's ancestor+ // leaves the process in a deleted directory otherwise.+ process.chdir(savedCwd);rmSync(baseTmpRoot, { recursive: true, force: true });});diff --git a/test/gateway-model-messages.test.ts b/test/gateway-model-messages.test.tsindex 30a8f79795..3e38871a0e 100644--- a/test/gateway-model-messages.test.ts+++ b/test/gateway-model-messages.test.ts@@ -227,5 +227,60 @@ describe('toModelMessages — v6 ModelMessage shape', () => {expect('providerOptions' in out[0].content[0]).toBe(false);expect('providerOptions' in out[0].content[1]).toBe(false);});++ // OpenAI's Responses API rejects a later turn whose history has a+ // `function_call` item with no matching `reasoning` item — "Item+ // '<fc_id>' of type 'function_call' was provided without its required+ // 'reasoning' item: '<rs_id>'." Reproduced against the live API+ // (openai:gpt-5.6-luna, 2-turn tool-calling conversation) before this+ // fix: turn 1 captured zero reasoning blocks despite the server minting+ // one, and turn 2 400'd with exactly that message. This block covers the+ // outbound half of the fix — reasoning blocks must round-trip through+ // toModelMessages() the same way tool-call/text blocks already do.+ const reasoningSig = { openai: { itemId: 'rs_abc123', reasoningEncryptedContent: 'opaque-blob' } };++ test('reasoning block with providerMetadata emits providerOptions', () => {+ const msgs: ChatMessage[] = [+ {+ role: 'assistant',+ content: [+ { type: 'reasoning', text: 'weighing the tradeoff...', providerMetadata: reasoningSig },+ { type: 'tool-call', toolCallId: 'c1', toolName: 'get_forecast', input: { city: 'Tokyo' } },+ ],+ },+ ];+ const out = toModelMessages(msgs) as any[];+ expect(out[0].content[0]).toEqual({+ type: 'reasoning',+ text: 'weighing the tradeoff...',+ providerOptions: reasoningSig,+ });+ });++ test('reasoning block without providerMetadata gains no providerOptions key', () => {+ const msgs: ChatMessage[] = [+ { role: 'assistant', content: [{ type: 'reasoning', text: 'no id captured' }] },+ ];+ const out = toModelMessages(msgs) as any[];+ expect(out[0].content[0]).toEqual({ type: 'reasoning', text: 'no id captured' });+ });++ // Same defensive filter as text blocks (some reasoning models surface+ // text: null/undefined thinking parts that AI SDK v6's Zod schema+ // rejects) — a reasoning block with a non-string `text` must be dropped,+ // not sent through and poison the whole call.+ test('reasoning block with non-string text is dropped, sibling blocks survive', () => {+ const msgs: ChatMessage[] = [+ {+ role: 'assistant',+ content: [+ { type: 'reasoning', text: undefined as unknown as string },+ { type: 'text', text: 'ok' },+ ],+ },+ ];+ const out = toModelMessages(msgs) as any[];+ expect(out[0].content).toEqual([{ type: 'text', text: 'ok' }]);+ });});});diff --git a/test/github-source-materialize.test.ts b/test/github-source-materialize.test.tsindex 760f9ab332..5f64adcdb5 100644--- a/test/github-source-materialize.test.ts+++ b/test/github-source-materialize.test.ts@@ -9,15 +9,11 @@ import { withEnv } from './helpers/with-env.ts';import { runGitHubSync, type GitHubSourceConfig } from '../src/core/github-source.ts';let engine: PGLiteEngine;-// Captured post-initSchema: resetPgliteState wipes the config `version` row-// that MinionQueue.ensureSchema() reads; tests that enqueue jobs restore it.-let migratedVersion: string;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- migratedVersion = (await engine.getConfig('version')) ?? '1';});afterAll(async () => {@@ -782,7 +778,7 @@ describe('github-source materialize', () => {}});- test('large sync defers embeds to an embed-backfill job with a drain hint', async () => {+ test('large PGLite sync refuses an undrainable embed-backfill job', async () => {const dir = mkdtempSync(join(tmpdir(), 'ghsrc-embed-defer-'));const fx = makeFixture();for (let n = 10; n < 111; n++) {@@ -801,17 +797,14 @@ describe('github-source materialize', () => {const fetchImpl = buildFetch(fx);try {await insertSource(engine, dir);- await engine.setConfig('version', migratedVersion); // MinionQueue schema gateawait withEnv({ GH_TOKEN: 'test-token' }, async () => {const res = await runGitHubSync(engine, 'ghsrc', makeCfg(dir), { sourceId: 'ghsrc', full: true, noExtract: true }, fetchImpl);expect(res.added).toBeGreaterThan(100);expect(res.embedded).toBe(0); // inline embed skipped by the size gate- const jobs = await engine.executeRaw<{ data: unknown }>(- `SELECT data FROM minion_jobs WHERE name = 'embed-backfill'`,+ const jobs = await engine.executeRaw<{ id: number }>(+ `SELECT id FROM minion_jobs WHERE name = 'embed-backfill'`,);- expect(jobs.length).toBe(1);- const data = (typeof jobs[0].data === 'string' ? JSON.parse(jobs[0].data) : jobs[0].data) as { sourceId: string };- expect(data.sourceId).toBe('ghsrc');+ expect(jobs).toEqual([]);});} finally {rmSync(dir, { recursive: true, force: true });diff --git a/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts b/test/hybrid-cache-hit-limit-honors-mode.serial.test.tsnew file mode 100644index 0000000000..7152889728--- /dev/null+++ b/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts@@ -0,0 +1,271 @@+/**+ * #4356 Site 2 — the semantic-cache-hit slice used a hard+ * `opts?.limit || 20`, independent of the mode-resolution logic the cache-+ * MISS path uses (`opts?.limit || resolvedMode.searchLimit`, bare+ * hybridSearch). In `balanced` mode (searchLimit: 25) a miss with `limit`+ * omitted could return and cache up to 25 results, but the next identical-+ * shape call served from cache silently sliced that cached row down to 20 —+ * inconsistent between the miss and hit paths for the same call shape.+ * (Scope note: this fix closes that gap for `offset: 0` — the common case,+ * and the shape the first three tests below drive. A SEPARATE bug — offset+ * used to be applied twice on a hit, once already baked into what the miss+ * path stored and once again by the hit branch — used to break hit/miss+ * parity for a nonzero `offset` (filed as #4358); the positive-offset half+ * of that bug is now closed by upstream's #4368 wave (this branch is+ * rebased onto it) by skipping the cache entirely for any positive offset,+ * so there's no cached row left to double-slice for the case the last test+ * near the end of this file drives. A separate PR, #4414 (this account's+ * own, still open as of this commit), widens the same skip condition to+ * also cover negative offsets — not exercised by this file. Both fixes are+ * orthogonal to the `|| 20` vs `|| resolvedMode.searchLimit` substitution+ * this PR makes and neither is part of this PR's diff.)+ *+ * Companion to #4356 Site 1 (see+ * test/query-op-limit-mode-4356.serial.test.ts, the `query` op's own+ * text-path `limit` translation). Fixing both sites in the same PR is the+ * point: shipping only the miss-path fix would make this miss/hit+ * inconsistency newly OBSERVABLE (previously both were wrong at a flat 20,+ * so they agreed) without resolving it — a maintainer-lens review rejected+ * exactly that partial shape when it shipped split across two closed PRs+ * (#4355, #4357).+ *+ * Drives a real store→hit roundtrip (mocked `embed`/`embedQuery` for a+ * deterministic vector, real PGLite SemanticQueryCache — same pattern as+ * test/hybrid-cached-hit-budget-meta.serial.test.ts) with 30 keyword-+ * findable pages spread across 6 page types (dedup's type-diversity layer+ * caps any one type at 60% of the result set, so a single type would+ * silently shrink the pool below 25 regardless of this fix). `autocut` and+ * `relationalRetrieval` are forced off per-call so the result count is+ * driven only by the limit slice under test, not by an unrelated cliff cut+ * or graph arm.+ *+ * Serial: mock.module (isolation guard R2).+ */++import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as realEmbedding from '../src/core/embedding.ts';++/** Deterministic 1536d unit vector — identical for every call, so the+ * second consult matches the first write at cosine 1.0. */+function fixedEmbedding(): Float32Array {+ const arr = new Float32Array(1536);+ for (let i = 0; i < 1536; i++) arr[i] = Math.sin(1 + i * 0.001);+ let norm = 0;+ for (let i = 0; i < 1536; i++) norm += arr[i] * arr[i];+ norm = Math.sqrt(norm);+ if (norm > 0) for (let i = 0; i < 1536; i++) arr[i] /= norm;+ return arr;+}++// Mock BEFORE importing hybrid.ts (spread keeps every other export live).+mock.module('../src/core/embedding.ts', () => ({+ ...realEmbedding,+ embed: async () => fixedEmbedding(),+ embedQuery: async () => fixedEmbedding(),+}));++// Import AFTER mocking.+const { hybridSearchCached, awaitPendingSearchCacheWrites } =+ await import('../src/core/search/hybrid.ts');+const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');++let engine: InstanceType<typeof PGLiteEngine>;+let tmpHome: string;+const savedGbrainHome = process.env.GBRAIN_HOME;++const PAGE_TYPES = ['note', 'company', 'person', 'decision', 'concept', 'idea'];+const PAGE_COUNT = 30; // > balanced searchLimit (25), so the bug (slice to 20) is observable.+const KEYWORD = 'gbrain4356widget';++beforeAll(async () => {+ // Hermetic config home so the developer's real ~/.gbrain/config.json+ // can't leak an embedding_model that flips the cache consult to+ // 'disabled' via isCacheSafe.+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-cache-hit-limit-'));+ process.env.GBRAIN_HOME = tmpHome;++ resetGateway();+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-fake' },+ });++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ for (let i = 0; i < PAGE_COUNT; i++) {+ const type = PAGE_TYPES[i % PAGE_TYPES.length];+ const slug = `widgets/${type}-${i}`;+ const truth = `${KEYWORD} entry number ${i}, a ${type} about widgets.`;+ await engine.putPage(slug, { type, title: `Widget ${i}`, compiled_truth: truth });+ await engine.upsertChunks(slug, [+ { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },+ ]);+ }+});++afterAll(async () => {+ if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = savedGbrainHome;+ try { await engine.disconnect(); } catch { /* ignore */ }+ resetGateway();+ try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }+});++describe('cache HIT — limit honors the resolved mode (#4356)', () => {+ test('balanced mode, limit omitted: hit returns the same count as the miss (searchLimit=25), not clipped to 20', async () => {+ let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const missResults = await hybridSearchCached(engine, KEYWORD, {+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { missMeta = m; },+ });+ expect(missMeta?.cache?.status).toBe('miss');+ // Sanity: the pool is deep enough that the mode's searchLimit (25),+ // not the pool size, is what caps the miss — otherwise this test+ // can't distinguish `|| 20` from `|| resolvedMode.searchLimit`.+ expect(missResults.length).toBe(25);++ await awaitPendingSearchCacheWrites();++ let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const hitResults = await hybridSearchCached(engine, KEYWORD, {+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { hitMeta = m; },+ });+ expect(hitMeta?.cache?.status).toBe('hit');+ // Pre-fix: this was clipped to 20 regardless of the miss's count.+ expect(hitResults.length).toBe(missResults.length);+ expect(hitResults.length).toBe(25);+ });++ test('conservative mode, limit omitted: hit still matches the miss (searchLimit=10, both below the old flat 20)', async () => {+ let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const missResults = await hybridSearchCached(engine, KEYWORD, {+ mode: 'conservative',+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { missMeta = m; },+ });+ expect(missMeta?.cache?.status).toBe('miss');+ expect(missResults.length).toBe(10);++ await awaitPendingSearchCacheWrites();++ let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const hitResults = await hybridSearchCached(engine, KEYWORD, {+ mode: 'conservative',+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { hitMeta = m; },+ });+ expect(hitMeta?.cache?.status).toBe('hit');+ expect(hitResults.length).toBe(missResults.length);+ });++ test('explicit numeric limit round-trips through a hit (limit is folded into knobsHash, so a hit only ever serves a lookup with the SAME resolved limit as the write — this pins that path still behaves, not just the mode-default path above)', async () => {+ await hybridSearchCached(engine, KEYWORD, { limit: 3, autocut: false, relationalRetrieval: false });+ await awaitPendingSearchCacheWrites();++ let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const hitResults = await hybridSearchCached(engine, KEYWORD, {+ limit: 3,+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { hitMeta = m; },+ });+ expect(hitMeta?.cache?.status).toBe('hit');+ expect(hitResults.length).toBe(3);+ });++ // FIXED for POSITIVE offset (was "KNOWN LIMITATION" — the positive-offset+ // half of #4358 landed via upstream's #4368 wave, which this branch is+ // rebased onto; the SEPARATE negative-offset half is #4414, this+ // account's own PR, still open/unmerged as of this commit — see below):+ // a nonzero offset used to break hit/miss count parity, because the miss+ // path stores the ALREADY offset-sliced array (`hybridSearch`'s own+ // `returnPool.slice(offset, offset + limit)`) and the cache-hit branch+ // re-applied `offset` a SECOND time on top of that already-sliced array.+ // For offset=0 this was a no-op (slicing from 0 twice is idempotent),+ // which is why every test above — and the miss/hit consistency this PR+ // actually fixes — held even pre-#4358. For a nonzero offset it was NOT+ // idempotent: e.g. a miss with `limit: 9, offset: 2` stored 9 rows+ // representing pool positions [2, 11); a hit then re-sliced THAT 9-row+ // array at [2, 11) again, yielding rows [2, 9) of a 9-element array — 7+ // rows, not 9.+ //+ // The fix in THIS branch's `hybrid.ts` is `pagedRequest = (opts?.offset+ // ?? 0) > 0` — positive-offset only. It skips the cache entirely (lookup+ // AND store) for any positive offset, so the double-slice path is+ // unreachable for this test's `offset: 2` case: a paginated request+ // returns freshly-computed, correctly-sliced results with+ // `cache.status: 'disabled'`, never a re-sliced cached page. (#4414 later+ // widens this same condition to `!== 0` so negative offsets get the same+ // protection — Array.prototype.slice's negative-index semantics mean a+ // negative offset re-slices a stored page just as badly as a positive+ // one, an independent gap `> 0` alone doesn't cover. That's out of scope+ // for THIS test, which only ever calls with a positive offset.)+ //+ // (`limit: 9` here — rather than the mode default this file's other tests+ // rely on — is deliberate, not incidental: `offset` still isn't part of+ // `knobsHash` (mode.ts's `knobsHash()` has no `offset=` component), so a+ // lookup with a NEW offset but the SAME resolved limit as an earlier test+ // in this file could otherwise collide with an already-written row if the+ // cache were consulted. A limit value unique to this test sidesteps that+ // collision — though it's moot for THIS assertion, since paginated+ // requests bypass the cache outright now; kept for robustness against+ // future changes to the skip condition.)+ test('positive offset never hits the cache — hit/miss count parity holds (was #4358, fixed here by #4368)', async () => {+ let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const missResults = await hybridSearchCached(engine, KEYWORD, {+ limit: 9,+ offset: 2,+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { missMeta = m; },+ });+ expect(missMeta?.cache?.status).toBe('disabled');+ expect(missResults.length).toBe(9);++ await awaitPendingSearchCacheWrites();++ let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const hitResults = await hybridSearchCached(engine, KEYWORD, {+ limit: 9,+ offset: 2,+ autocut: false,+ relationalRetrieval: false,+ onMeta: (m) => { hitMeta = m; },+ });+ // Still 'disabled', not 'hit' — a paginated request skips the cache on+ // EVERY call (lookup AND store), so there's never a stored row for a+ // nonzero offset to serve back. If this assertion ever changes to+ // 'hit', the skip-cache design changed — re-verify the double-slice+ // fix still holds under whatever replaced it, rather than just+ // updating the expected string.+ expect(hitMeta?.cache?.status).toBe('disabled');+ expect(hitResults.length).toBe(9);+ });++ // NOTE on `limit: 0` (not a test — documenting why one isn't here): a+ // `limit: 0` call always returns zero rows (resolveSearchMode's+ // perCall.searchLimit pick treats a forwarded 0 as a set value, so+ // `0 || resolvedMode.searchLimit` resolves to 0 — verified directly+ // against mode.ts), and the miss-path writeback above explicitly skips+ // caching empty result sets ("skip when search returned empty so we+ // don't cache zero-result queries forever"). A `limit: 0` query can+ // therefore never reach a cache HIT via the public API: nothing is ever+ // written for it to hit against, and even if a prior non-zero-limit+ // write existed, `lim=<n>` is folded into `knobsHash` (mode.ts), so a+ // `limit: 0` lookup's hash never matches a `limit: 25` write's row. The+ // line this PR changes (`resolvedForCache.searchLimit` instead of a flat+ // `20`) is exercised by the non-zero cases above; a 0-specific hit+ // scenario is structurally unreachable, not merely untested.+});diff --git a/test/hybrid-degraded-cache-meta.serial.test.ts b/test/hybrid-degraded-cache-meta.serial.test.tsindex e207daa646..9932908533 100644--- a/test/hybrid-degraded-cache-meta.serial.test.ts+++ b/test/hybrid-degraded-cache-meta.serial.test.ts@@ -169,6 +169,16 @@ describe('cache-hit stamping', () => {expect(meta.cache?.status).toBe('disabled');expect(typeof meta.retrieved_count).toBe('number');});++ test('offset<0 also bypasses the cache entirely (#4358 residual — negative offsets re-slice a stored page just as badly as positive ones)', async () => {+ const { results: missResults } = await cachedRun('builder', { limit: 5 });+ expect(missResults.length).toBeGreaterThan(0);+ await awaitPendingSearchCacheWrites();++ const { meta } = await cachedRun('builder', { limit: 5, offset: -50 });+ expect(meta.cache?.status).toBe('disabled');+ expect(typeof meta.retrieved_count).toBe('number');+ });});describe('cache_prestamp — pre-upgrade rows cannot claim clean', () => {diff --git a/test/markdown-leading-blank-frontmatter.test.ts b/test/markdown-leading-blank-frontmatter.test.tsnew file mode 100644index 0000000000..3997688f89--- /dev/null+++ b/test/markdown-leading-blank-frontmatter.test.ts@@ -0,0 +1,77 @@+/**+ * #4526 — a leading blank line before the `---` fence made parseMarkdown+ * miss the entire frontmatter block: gray-matter only recognizes a fence at+ * byte 0, while the rest of the pipeline (frontmatterBodyOffset,+ * collectValidationErrors' MISSING_OPEN check) tolerates leading blanks.+ * Result: empty frontmatter, the block left embedded in the body, and the+ * title humanized from the slug — a raw UUID for `fact/<uuid>` session-digest+ * pages ("2bcdd03c Bffd 4452 A6b8 25294c969c78" in every listing).+ *+ * Second arm: pages already corrupted by the pre-fix parse carry the real+ * frontmatter EMBEDDED at the top of the body (double-frontmatter after a+ * get→put round-trip). When the title would otherwise merely humanize the+ * slug/filename, the embedded block's `title:` is promoted instead.+ */++import { describe, test, expect } from 'bun:test';+import { parseMarkdown } from '../src/core/markdown.ts';++describe('parseMarkdown — leading blank line before frontmatter (#4526)', () => {+ test('a single leading newline no longer hides the frontmatter block', () => {+ const content = '\n---\ntitle: Real Title\ntype: note\n---\nbody text here\n';+ const parsed = parseMarkdown(content, 'fact/2bcdd03c-bffd-4452-a6b8-25294c969c78.md');+ expect(parsed.title).toBe('Real Title');+ expect(parsed.type).toBe('note');+ // The block must be LIFTED out of the body, not left embedded.+ expect(parsed.compiled_truth).toBe('body text here');+ });++ test('multiple blank lines + CRLF endings also parse', () => {+ const content = '\r\n\r\n---\r\ntitle: CRLF Title\r\ntype: note\r\n---\r\nbody\r\n';+ const parsed = parseMarkdown(content, 'fact/uuid-here.md');+ expect(parsed.title).toBe('CRLF Title');+ expect(parsed.compiled_truth).not.toContain('---');+ });++ test('no-frontmatter files are untouched (first non-empty line is not a fence)', () => {+ const content = '\nJust some body text\nwith lines\n';+ const parsed = parseMarkdown(content, 'notes/plain-file.md');+ expect(parsed.title).toBe('Plain File');+ expect(parsed.compiled_truth).toBe('Just some body text\nwith lines');+ });++ test('valid frontmatter at byte 0 still parses exactly as before', () => {+ const content = '---\ntitle: Normal\ntype: note\n---\nbody\n';+ const parsed = parseMarkdown(content, 'notes/normal.md');+ expect(parsed.title).toBe('Normal');+ expect(parsed.compiled_truth).toBe('body');+ });+});++describe('parseMarkdown — embedded-frontmatter title promotion (#4526)', () => {+ test('double-frontmatter round-trip promotes the embedded title over slug humanization', () => {+ // A pre-fix corrupted page round-tripped through get→put: real (titleless)+ // frontmatter, then the original block embedded at the top of the body.+ const content = '---\ntype: note\n---\n---\ntitle: tg-comment-guard dashboard\nkind: session-digest\n---\nreal body\n';+ const parsed = parseMarkdown(content, 'fact/2bcdd03c-bffd-4452-a6b8-25294c969c78.md');+ expect(parsed.title).toBe('tg-comment-guard dashboard');+ });++ test('a frontmatter title still wins over an embedded block', () => {+ const content = '---\ntitle: Outer Title\n---\n---\ntitle: Inner Title\n---\nbody\n';+ const parsed = parseMarkdown(content, 'fact/uuid.md');+ expect(parsed.title).toBe('Outer Title');+ });++ test('a body H1 still wins over an embedded block', () => {+ const content = '---\ntype: note\n---\n---\ntitle: Inner Title\n---\n# Heading Title\nbody\n';+ const parsed = parseMarkdown(content, 'fact/uuid.md');+ expect(parsed.title).toBe('Heading Title');+ });++ test('an embedded block without title: falls back to filename humanization', () => {+ const content = '---\ntype: note\n---\n---\nkind: session-digest\n---\nbody\n';+ const parsed = parseMarkdown(content, 'notes/some-file.md');+ expect(parsed.title).toBe('Some File');+ });+});diff --git a/test/markdown.test.ts b/test/markdown.test.tsindex eae98b3a7f..5dac4fcda5 100644--- a/test/markdown.test.ts+++ b/test/markdown.test.ts@@ -1,5 +1,8 @@-import { describe, test, expect } from 'bun:test';-import { parseMarkdown, serializeMarkdown, splitBody } from '../src/core/markdown.ts';+import { describe, test, expect, afterEach } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { parseMarkdown, serializeMarkdown, splitBody, resolveSourceLocalFilePath } from '../src/core/markdown.ts';describe('Markdown Parser', () => {test('parses frontmatter + compiled_truth + timeline (explicit sentinel)', () => {@@ -139,6 +142,25 @@ describe('splitBody', () => {expect(timeline).toContain('## History');});+ // rule 3's heading match used \b, which matches any heading that+ // merely STARTS with "Timeline"/"History" ("## History & Reach",+ // "## Timeline of Events"). That silently moved the rest of an ordinary+ // article into the timeline half. Rule 3 is a back-compat shim for pages+ // gbrain itself wrote, so it takes the exact heading only.+ test('does NOT split at --- when the heading only STARTS with History', () => {+ const body = 'Article content\n\n---\n\n## History & Reach\n\n- item';+ const { compiled_truth, timeline } = splitBody(body);+ expect(compiled_truth).toBe(body);+ expect(timeline).toBe('');+ });++ test('does NOT split at --- when the heading only STARTS with Timeline', () => {+ const body = 'Article content\n\n---\n\n## Timeline of Events\n\ntext';+ const { compiled_truth, timeline } = splitBody(body);+ expect(compiled_truth).toBe(body);+ expect(timeline).toBe('');+ });+test('does NOT split at plain --- (horizontal rule in article body)', () => {const body = 'Above the line\n\n---\n\nBelow the line';const { compiled_truth, timeline } = splitBody(body);@@ -257,6 +279,42 @@ Second section.expect(parsed.timeline).toContain('Timeline entry');});+ test('keeps the whole body when a section heading merely starts with History', () => {+ // Real shape from an imported chat transcript: HR-separated sections,+ // one of them '## History & Reach'. Pre-fix the page was cut at the HR+ // and everything below it landed in the timeline column.+ const md = `---+type: source+title: Example show+---++Here's a breakdown of how it works.++---++## Format & Premise++- 30 singles date in pods.++---++## History & Reach++- The show premiered in 2020.++---++## Reception++- Critics noted the format.`;+ const parsed = parseMarkdown(md);+ expect(parsed.timeline).toBe('');+ expect(parsed.compiled_truth).toContain('## Format & Premise');+ expect(parsed.compiled_truth).toContain('## History & Reach');+ expect(parsed.compiled_truth).toContain('premiered in 2020');+ expect(parsed.compiled_truth).toContain('## Reception');+ });+test('handles frontmatter without type or title', () => {const md = `---custom_field: hello@@ -614,3 +672,63 @@ ${first.timeline}expect(third.compiled_truth).not.toContain('Series A closed');});});++describe('resolveSourceLocalFilePath — POSIX backslash-in-filename (undeclared_db_only_pages false positive)', () => {+ let repoRoot: string;++ afterEach(() => {+ if (repoRoot) rmSync(repoRoot, { recursive: true, force: true });+ });++ test('a real file whose name contains a literal backslash resolves to its actual on-disk path', () => {+ if (process.platform === 'win32') return; // `\` is the real separator there — no such filename is possible+ // Reproduces production data: an Apple Notes export can legitimately+ // contain a `\` character in a note title, which lands verbatim in the+ // exported filename on a POSIX filesystem (where `\` is a normal+ // filename character, not a path separator).+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-'));+ mkdirSync(join(repoRoot, '.git'));+ mkdirSync(join(repoRoot, 'Archive', 'POL'), { recursive: true });+ const filename = '2019-10-03 \\event title-.md';+ const filePath = join(repoRoot, 'Archive', 'POL', filename);+ writeFileSync(filePath, '# note');++ const sourcePath = `Archive/POL/${filename}`;+ const resolved = resolveSourceLocalFilePath(repoRoot, sourcePath);++ expect(resolved).toBe(filePath);+ });++ test('negative control: a genuinely missing file still resolves to null-equivalent (no such path)', () => {+ if (process.platform === 'win32') return; // relies on `\` staying a filename character (POSIX-only)+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-missing-'));+ mkdirSync(join(repoRoot, '.git'));+ mkdirSync(join(repoRoot, 'Archive', 'POL'), { recursive: true });+ // No file written — the resolved path must point at a location that+ // does not exist, so callers' existsSync() check correctly reports it+ // as unbacked (this stays a real gap, not a resolution bug).+ const sourcePath = 'Archive/POL/2019-10-03 \\never-written-.md';+ const resolved = resolveSourceLocalFilePath(repoRoot, sourcePath);++ expect(resolved).toBe(join(repoRoot, 'Archive', 'POL', '2019-10-03 \\never-written-.md'));+ });++ test('path traversal via a real `/`-separated `..` segment is still rejected', () => {+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-traversal-'));+ mkdirSync(join(repoRoot, '.git'));+ expect(resolveSourceLocalFilePath(repoRoot, '../../etc/passwd.md')).toBeNull();+ });++ test('a Windows drive-letter absolute path is still rejected', () => {+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-drive-'));+ mkdirSync(join(repoRoot, '.git'));+ expect(resolveSourceLocalFilePath(repoRoot, 'C:\\Windows\\evil.md')).toBeNull();+ });++ test('on Windows, `\\` stays a real separator and `..\\` traversal is still rejected', () => {+ if (process.platform !== 'win32') return; // the platform-aware split only changes POSIX behavior+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-backslash-win-'));+ mkdirSync(join(repoRoot, '.git'));+ expect(resolveSourceLocalFilePath(repoRoot, '..\\..\\evil.md')).toBeNull();+ });+});diff --git a/test/migrate-engine-page-copy-failure.serial.test.ts b/test/migrate-engine-page-copy-failure.serial.test.tsindex 4cc6e467e7..d8dbe5d897 100644--- a/test/migrate-engine-page-copy-failure.serial.test.ts+++ b/test/migrate-engine-page-copy-failure.serial.test.ts@@ -53,6 +53,9 @@ describe('copyPageToTarget — undefined-column normalization (#3194)', () => {putPageCalls.push({ slug, page, opts });return fakePage();},+ // #4527: copyPageToTarget restores the source row's timestamps via a+ // raw UPDATE right after putPage.+ executeRaw: async () => [],} as unknown as BrainEngine;const source = {getChunksWithEmbeddings: async () => [],@@ -95,6 +98,9 @@ describe('copyPageToTarget — undefined-column normalization (#3194)', () => {putPageCalls.push({ slug, page, opts });return fakePage();},+ // #4527: copyPageToTarget restores the source row's timestamps via a+ // raw UPDATE right after putPage.+ executeRaw: async () => [],} as unknown as BrainEngine;const source = {getChunksWithEmbeddings: async () => [],diff --git a/test/migrate-timeline-full-copy.test.ts b/test/migrate-timeline-full-copy.test.tsnew file mode 100644index 0000000000..8a6e9dc48d--- /dev/null+++ b/test/migrate-timeline-full-copy.test.ts@@ -0,0 +1,78 @@+/**+ * #4485 — `copyPageToTarget` called `getTimeline` with no limit, and both+ * engines default that read to LIMIT 100 (newest-first). Any page with a+ * longer history silently lost everything past its newest 100 timeline+ * entries on engine migration — no error, no summary line, no retry path+ * (the page was checkpointed as fully copied).+ *+ * The copy now passes an explicit unbounded limit, and the end-of-run+ * verify step compares total source-vs-target timeline counts.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { copyPageToTarget, COPIED_TIMELINE_COUNT_SQL } from '../src/commands/migrate-engine.ts';++let source: PGLiteEngine;+let target: PGLiteEngine;++beforeAll(async () => {+ source = new PGLiteEngine();+ await source.connect({});+ await source.initSchema();+ target = new PGLiteEngine();+ await target.connect({});+ await target.initSchema();+});++afterAll(async () => {+ await source.disconnect();+ await target.disconnect();+});++describe('copyPageToTarget — full timeline copy (#4485)', () => {+ test('a page with more than 100 timeline entries migrates ALL of them', async () => {+ await source.putPage('people/long-history', {+ type: 'person', title: 'Long History', compiled_truth: 'body', timeline: '', frontmatter: {},+ });+ const TOTAL = 130;+ for (let i = 0; i < TOTAL; i++) {+ // Spread across distinct dates so DESC-ordering + LIMIT actually drops+ // the oldest entries under the old behavior.+ const day = String((i % 28) + 1).padStart(2, '0');+ const month = String(Math.floor(i / 28) + 1).padStart(2, '0');+ await source.addTimelineEntry('people/long-history', {+ date: `2024-${month}-${day}`,+ source: 'test',+ summary: `entry ${i}`,+ });+ }++ const page = await source.getPage('people/long-history');+ expect(page).not.toBeNull();+ const counts = await copyPageToTarget(source, target, page!);+ expect(counts.timeline_entries).toBe(TOTAL);++ const copied = await target.getTimeline('people/long-history', { limit: 1000 });+ expect(copied.length).toBe(TOTAL);+ }, 60000);++ test('wave-g: verify parity count is scoped to live pages — soft-deleted timeline rows excluded', async () => {+ // The migration copies listPages() output (soft-deleted excluded), so a+ // soft-deleted source page that still owns timeline rows must NOT count+ // toward the source side of the parity check (false WARN pre-fix).+ await source.putPage('people/gone-example', {+ type: 'person', title: 'Gone', compiled_truth: 'body', timeline: '', frontmatter: {},+ });+ await source.addTimelineEntry('people/gone-example', {+ date: '2024-01-01', source: 'test', summary: 'orphaned-by-soft-delete',+ });+ const before = Number((await source.executeRaw<{ count: string }>(COPIED_TIMELINE_COUNT_SQL))[0].count);+ await source.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'people/gone-example'`);+ const whole = Number((await source.executeRaw<{ count: string }>(+ 'SELECT count(*)::text AS count FROM timeline_entries'))[0].count);+ const scoped = Number((await source.executeRaw<{ count: string }>(COPIED_TIMELINE_COUNT_SQL))[0].count);+ expect(scoped).toBe(before - 1); // the soft-deleted page's row left the copied set+ expect(whole).toBe(before); // whole-table count still includes it (the old false-WARN source)+ }, 60000);+});diff --git a/test/migrate-timestamps-removelink-count.test.ts b/test/migrate-timestamps-removelink-count.test.tsnew file mode 100644index 0000000000..d5560ffa10--- /dev/null+++ b/test/migrate-timestamps-removelink-count.test.ts@@ -0,0 +1,114 @@+/**+ * #4527 — two silent-data defects in the migrate/link plane:+ *+ * 1. `copyPageToTarget` handed `target.putPage` only the 6 PageInput fields,+ * so `created_at` / `updated_at` on every migrated page reset to now() —+ * an engine migration silently destroyed the whole brain's chronology+ * (recency ranking, `--since` filters, timeline ordering all keyed on+ * those columns). The copy must preserve the source row's timestamps.+ *+ * 2. `removeLink` returned `Promise<void>` in both engines and the+ * `remove_link` op answered an unconditional `{ status: 'ok' }`, so a+ * delete that matched ZERO rows (typo'd slug, wrong link_type, already+ * removed) was indistinguishable from a real removal. The engines now+ * return the deleted-row count (RETURNING) and the op reports it.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { copyPageToTarget } from '../src/commands/migrate-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';++let source: PGLiteEngine;+let target: PGLiteEngine;++beforeAll(async () => {+ source = new PGLiteEngine();+ await source.connect({});+ await source.initSchema();+ target = new PGLiteEngine();+ await target.connect({});+ await target.initSchema();+});++afterAll(async () => {+ await source.disconnect();+ await target.disconnect();+});++describe('copyPageToTarget — timestamp preservation (#4527)', () => {+ test('created_at / updated_at survive the copy instead of resetting to now()', async () => {+ await source.putPage('history/old-page', {+ type: 'note', title: 'Old Page', compiled_truth: 'ancient body', timeline: '', frontmatter: {},+ });+ // Backdate the source row the way a years-old brain would look.+ const createdAt = '2021-03-04T05:06:07.000Z';+ const updatedAt = '2023-08-09T10:11:12.000Z';+ await source.executeRaw(+ `UPDATE pages SET created_at = $1, updated_at = $2 WHERE slug = $3 AND source_id = 'default'`,+ [createdAt, updatedAt, 'history/old-page'],+ );++ const page = await source.getPage('history/old-page');+ expect(page).not.toBeNull();+ await copyPageToTarget(source, target, page!);++ const copied = await target.getPage('history/old-page');+ expect(copied).not.toBeNull();+ expect(new Date(copied!.created_at).toISOString()).toBe(createdAt);+ expect(new Date(copied!.updated_at).toISOString()).toBe(updatedAt);+ });+});++describe('removeLink returns the deleted-row count (#4527)', () => {+ test('engine.removeLink reports how many edges actually died', async () => {+ await source.putPage('people/alice-example', {+ type: 'person', title: 'Alice', compiled_truth: 'a person', timeline: '', frontmatter: {},+ });+ await source.putPage('companies/acme-example', {+ type: 'company', title: 'Acme', compiled_truth: 'a company', timeline: '', frontmatter: {},+ });+ await source.addLink('people/alice-example', 'companies/acme-example', 'works there', 'works_at');+ await source.addLink('people/alice-example', 'companies/acme-example', 'founded it', 'founded');++ // A miss (no such type) removes nothing and says so.+ const missed = await source.removeLink('people/alice-example', 'companies/acme-example', 'invested_in');+ expect(missed).toBe(0);++ // A typed hit removes exactly the one row.+ const typed = await source.removeLink('people/alice-example', 'companies/acme-example', 'works_at');+ expect(typed).toBe(1);++ // Untyped removal reports the remaining edge count.+ const rest = await source.removeLink('people/alice-example', 'companies/acme-example');+ expect(rest).toBe(1);++ // Fully-gone pair: zero again.+ const gone = await source.removeLink('people/alice-example', 'companies/acme-example');+ expect(gone).toBe(0);+ });++ test('remove_link op surfaces removed count instead of an unconditional ok', async () => {+ await source.putPage('people/bob-example', {+ type: 'person', title: 'Bob', compiled_truth: 'a person', timeline: '', frontmatter: {},+ });+ await source.putPage('companies/widget-co', {+ type: 'company', title: 'Widget Co', compiled_truth: 'a company', timeline: '', frontmatter: {},+ });+ await source.addLink('people/bob-example', 'companies/widget-co', 'advises', 'advises');++ const op = operationsByName['remove_link'];+ expect(op).toBeDefined();+ const ctx = { engine: source, remote: false } as unknown as OperationContext;++ const hit = await op!.handler(ctx, { from: 'people/bob-example', to: 'companies/widget-co' }) as Record<string, unknown>;+ expect(hit.status).toBe('ok');+ expect(hit.removed).toBe(1);++ // Second identical call matches nothing — the caller can now tell.+ const miss = await op!.handler(ctx, { from: 'people/bob-example', to: 'companies/widget-co' }) as Record<string, unknown>;+ expect(miss.status).toBe('ok');+ expect(miss.removed).toBe(0);+ });+});diff --git a/test/migrations-v128.test.ts b/test/migrations-v128.test.tsindex 53b96cc696..92e8142e9e 100644--- a/test/migrations-v128.test.ts+++ b/test/migrations-v128.test.ts@@ -23,12 +23,14 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';let engine: PGLiteEngine;let queue: MinionQueue;+let workerBackedQueue: MinionQueue;const V128_SQL = MIGRATIONS.find(m => m.version === 128)?.sql ?? '';@@ -48,6 +50,14 @@ beforeAll(async () => {await engine.connect({ database_url: '' }); // in-memoryawait engine.initSchema();queue = new MinionQueue(engine);+ const workerBackedEngine = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;+ workerBackedQueue = new MinionQueue(workerBackedEngine);});afterAll(async () => {@@ -117,7 +127,7 @@ describe('migration v128 — backfill + cleanup semantics (PGLite)', () => {const unmapped = await queue.add('sync', {});expect(unmapped.timeout_ms).toBeNull();// Explicit budget: untouched.- const explicit = await queue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });+ const explicit = await workerBackedQueue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });// --- Cleanup fixtures (statement 2) ---// Three ticker-keyed waiting cycles for ONE source, staggered ages —diff --git a/test/minions.test.ts b/test/minions.test.tsindex a49fbacd35..d354148cd5 100644--- a/test/minions.test.ts+++ b/test/minions.test.ts@@ -1,5 +1,6 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGlite } from '@electric-sql/pglite';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MinionQueue } from '../src/core/minions/queue.ts';import { MinionWorker } from '../src/core/minions/worker.ts';@@ -9,12 +10,21 @@ import type { MinionJob } from '../src/core/minions/types.ts';let engine: PGLiteEngine;let queue: MinionQueue;+let workerBackedQueue: MinionQueue;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({ database_url: '' }); // in-memoryawait engine.initSchema();queue = new MinionQueue(engine);+ const workerBackedEngine = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'kind') return 'postgres';+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as unknown as BrainEngine;+ workerBackedQueue = new MinionQueue(workerBackedEngine);});afterAll(async () => {@@ -342,7 +352,7 @@ describe('MinionQueue: #1737 attempt accounting on dead-letter', () => {describe('MinionQueue: #1737 per-handler default timeout', () => {test('long handler with no explicit timeout_ms gets the 30-min default stamped', async () => {- const job = await queue.add('embed-backfill', { sourceId: 'x' });+ const job = await workerBackedQueue.add('embed-backfill', { sourceId: 'x' });expect(job.timeout_ms).toBe(30 * 60 * 1000);});@@ -371,7 +381,7 @@ describe('MinionQueue: #1737 per-handler default timeout', () => {});test('explicit timeout_ms always wins over the default', async () => {- const job = await queue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });+ const job = await workerBackedQueue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });expect(job.timeout_ms).toBe(5000);});@@ -423,7 +433,7 @@ describe('MinionQueue: claim-time timeout fallback', () => {});test('explicit timeout_ms is never overridden at claim', async () => {- await queue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });+ await workerBackedQueue.add('embed-backfill', { sourceId: 'x' }, { timeout_ms: 5000 });const claimed = await queue.claim('tok-explicit', 30_000, 'default', ['embed-backfill']);expect(claimed).not.toBeNull();expect(claimed!.timeout_ms).toBe(5000);diff --git a/test/model-config.serial.test.ts b/test/model-config.serial.test.tsindex 8f50c4b4fb..8842519972 100644--- a/test/model-config.serial.test.ts+++ b/test/model-config.serial.test.ts@@ -15,6 +15,7 @@ import {TIER_DEFAULTS,PROVIDER_TIER_DEFAULTS,isAnthropicProvider,+ isOpenRouterAnthropic,_resetDeprecationWarningsForTest,} from '../src/core/model-config.ts';import type { GBrainConfig } from '../src/core/config.ts';@@ -302,6 +303,17 @@ describe('resolveModel — v0.31.12 tier system', () => {// widen the guard).expect(isAnthropicProvider('openai/gpt-5')).toBe(false);expect(isAnthropicProvider('google/gemini-3-pro')).toBe(false);+ // OpenRouter Anthropic is a proxy route, not the Messages API.+ expect(isAnthropicProvider('openrouter:anthropic/claude-haiku-4.5')).toBe(false);+ });++ test('isOpenRouterAnthropic matches only openrouter:anthropic/… routes', () => {+ expect(isOpenRouterAnthropic('openrouter:anthropic/claude-haiku-4.5')).toBe(true);+ expect(isOpenRouterAnthropic('openrouter:anthropic/claude-sonnet-4.6')).toBe(true);+ expect(isOpenRouterAnthropic('openrouter:openai/gpt-5.2')).toBe(false);+ expect(isOpenRouterAnthropic('openrouter:deepseek/deepseek-chat')).toBe(false);+ expect(isOpenRouterAnthropic('anthropic:claude-sonnet-4-6')).toBe(false);+ expect(isOpenRouterAnthropic('')).toBe(false);});test('alias-chain conflict: forward + reverse for same id (Codex F6)', async () => {diff --git a/test/oauth-refresh-invalid-grant.test.ts b/test/oauth-refresh-invalid-grant.test.tsnew file mode 100644index 0000000000..0e4e88638b--- /dev/null+++ b/test/oauth-refresh-invalid-grant.test.ts@@ -0,0 +1,89 @@+// #4532 — exchangeRefreshToken failures must be InvalidGrantError, not bare+// Error.+//+// The MCP SDK's token handler maps OAuthError subclasses to their RFC 6749+// wire shape (HTTP 400 + {"error":"invalid_grant"}) and any non-OAuthError to+// a 500 Internal Server Error. Pre-fix, a refresh with a rotated or expired+// token (a routine client condition — RFC 6749 §5.2 invalid_grant) threw bare+// Error and surfaced as a 500, so well-behaved MCP clients treated it as a+// server outage instead of re-running the authorization flow.++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';+import { InvalidGrantError, ServerError, OAuthError } from '@modelcontextprotocol/sdk/server/auth/errors.js';++let db: PGlite;+let sql: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<any>;+let provider: GBrainOAuthProvider;++beforeAll(async () => {+ db = new PGlite({ extensions: { vector, pg_trgm } });+ await db.exec(PGLITE_SCHEMA_SQL);+ sql = async (strings: TemplateStringsArray, ...values: unknown[]) => {+ const query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? `$${i + 1}` : ''), '');+ const result = await db.query(query, values as any[]);+ return result.rows;+ };+ provider = new GBrainOAuthProvider({ sql, tokenTtl: 60, refreshTtl: 300 });+}, 120_000);++afterAll(async () => {+ if (db) await db.close();+}, 15_000);++async function mintTokens() {+ const { clientId } = await provider.registerClientManual(+ 'invalid-grant-test', ['authorization_code'], 'read write',+ ['http://localhost:3000/callback'],+ );+ const client = (await provider.clientsStore.getClient(clientId))!;+ let redirectUrl = '';+ const mockRes = { redirect: (url: string) => { redirectUrl = url; } } as any;+ await provider.authorize(client, {+ codeChallenge: 'challenge',+ redirectUri: 'http://localhost:3000/callback',+ scopes: ['read', 'write'],+ }, mockRes);+ const code = new URL(redirectUrl).searchParams.get('code')!;+ const tokens = await provider.exchangeAuthorizationCode(client, code);+ return { client, tokens };+}++describe('exchangeRefreshToken error typing (#4532)', () => {+ test('unknown/rotated refresh token throws InvalidGrantError (400 invalid_grant on the wire)', async () => {+ const { client } = await mintTokens();+ let caught: unknown;+ try {+ await provider.exchangeRefreshToken(client, 'gbr_definitely-not-a-real-token');+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(InvalidGrantError);+ // The SDK token handler's mapping: OAuthError-but-not-ServerError → 400.+ expect(caught).toBeInstanceOf(OAuthError);+ expect(caught).not.toBeInstanceOf(ServerError);+ expect((caught as InvalidGrantError).toResponseObject().error).toBe('invalid_grant');+ });++ test('expired refresh token throws InvalidGrantError', async () => {+ const { client, tokens } = await mintTokens();+ // Age the refresh row past expiry (fail-closed NULL also counts, but the+ // routine path is a real timestamp in the past).+ await db.query(+ `UPDATE oauth_tokens SET expires_at = 1 WHERE token_type = 'refresh' AND client_id = $1`,+ [client.client_id],+ );+ let caught: unknown;+ try {+ await provider.exchangeRefreshToken(client, tokens.refresh_token!);+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(InvalidGrantError);+ expect((caught as InvalidGrantError).toResponseObject().error).toBe('invalid_grant');+ });+});diff --git a/test/ollama-recipe.test.ts b/test/ollama-recipe.test.tsnew file mode 100644index 0000000000..7dfb12fa7c--- /dev/null+++ b/test/ollama-recipe.test.ts@@ -0,0 +1,40 @@+/**+ * Ollama recipe — chat touchpoint shape.+ *+ * The extract-atoms phase registers config-selected chat models through the+ * gateway's extended-model path so local/user-managed providers (Ollama) can+ * serve the phase without hosted API keys. That wiring presumes the recipe+ * DECLARES a chat touchpoint with a non-empty allowlist — assertTouchpoint+ * rejects a provider whose touchpoint is missing, and an empty models list+ * would leave no default-eligible model at all.+ */++import { describe, test, expect } from 'bun:test';+import { getRecipe } from '../src/core/ai/recipes/index.ts';++describe('Ollama recipe — chat touchpoint', () => {+ test('declares a chat touchpoint', () => {+ const r = getRecipe('ollama');+ expect(r).toBeDefined();+ expect(r!.touchpoints.chat).toBeDefined();+ });++ test('chat models list is non-empty and every entry is a non-empty string', () => {+ const m = getRecipe('ollama')!.touchpoints.chat!.models;+ expect(Array.isArray(m)).toBe(true);+ expect(m.length).toBeGreaterThan(0);+ for (const model of m) {+ expect(typeof model).toBe('string');+ expect(model.length).toBeGreaterThan(0);+ }+ });++ test('local chat models advertise no hosted-only capabilities', () => {+ // Local Ollama chat serves plain completions; the gateway must not route+ // tool-use / subagent / structured-output work here.+ const tp = getRecipe('ollama')!.touchpoints.chat!;+ expect(tp.supports_tools).toBe(false);+ expect(tp.supports_subagent_loop).toBe(false);+ expect(tp.supports_structured_outputs).toBe(false);+ });+});diff --git a/test/orphans-mode-islanded.test.ts b/test/orphans-mode-islanded.test.tsnew file mode 100644index 0000000000..eced1312cd--- /dev/null+++ b/test/orphans-mode-islanded.test.ts@@ -0,0 +1,73 @@+/**+ * #4524 — `find_orphans` / `gbrain orphans` counted pages with NO INBOUND+ * link, while `get_health.orphan_pages` counted ISLANDED pages (no inbound+ * AND no outbound, endpoint-liveness both ways). Mid-curation the two+ * numbers diverged wildly (145 vs 20 on a real brain), so doctor-driven+ * enrichment loops chased a count the orphans tool disagreed with.+ *+ * One canonical policy now: `findOrphanPages` takes `mode:+ * 'inbound' | 'islanded'` and DEFAULTS to 'islanded' — health's definition —+ * so every consumer (orphans CLI, find_orphans op, doctor orphan_ratio,+ * get_health.orphan_pages) agrees by construction. The old no-inbound view+ * stays reachable via mode: 'inbound'.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { findOrphans } from '../src/commands/orphans.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // island: no inbound, no outbound → orphan under BOTH definitions.+ await engine.putPage('people/island', {+ type: 'person', title: 'Island', compiled_truth: 'body', timeline: '', frontmatter: {},+ });+ // hub: no inbound, but LINKS OUT to spoke → orphan only under 'inbound'.+ await engine.putPage('people/hub', {+ type: 'person', title: 'Hub', compiled_truth: 'body', timeline: '', frontmatter: {},+ });+ // spoke: inbound from hub → not an orphan under either definition.+ await engine.putPage('people/spoke', {+ type: 'person', title: 'Spoke', compiled_truth: 'body', timeline: '', frontmatter: {},+ });+ await engine.addLink('people/hub', 'people/spoke', 'knows', 'knows');+});++afterAll(async () => {+ await engine.disconnect();+});++describe('findOrphanPages mode (#4524)', () => {+ test("default = 'islanded' (health's definition): outbound-only pages are NOT orphans", async () => {+ const rows = await engine.findOrphanPages();+ const slugs = rows.map(r => r.slug);+ expect(slugs).toContain('people/island');+ expect(slugs).not.toContain('people/hub');+ expect(slugs).not.toContain('people/spoke');+ });++ test("mode: 'inbound' preserves the old no-inbound view", async () => {+ const rows = await engine.findOrphanPages({ mode: 'inbound' });+ const slugs = rows.map(r => r.slug);+ expect(slugs).toContain('people/island');+ expect(slugs).toContain('people/hub');+ expect(slugs).not.toContain('people/spoke');+ });++ test("mode: 'islanded' explicit matches the default", async () => {+ const def = (await engine.findOrphanPages()).map(r => r.slug).sort();+ const exp = (await engine.findOrphanPages({ mode: 'islanded' })).map(r => r.slug).sort();+ expect(exp).toEqual(def);+ });++ test('findOrphans (policy fn) agrees with get_health.orphan_pages by construction', async () => {+ const health = await engine.getHealth();+ const result = await findOrphans(engine, {});+ expect(result.total_orphans).toBe(health.orphan_pages);+ });+});diff --git a/test/orphans-source-scope.test.ts b/test/orphans-source-scope.test.tsindex 75ef214182..934e753733 100644--- a/test/orphans-source-scope.test.ts+++ b/test/orphans-source-scope.test.ts@@ -33,6 +33,11 @@ const page = (title: string) => ({});// Every test in this file is READ-ONLY (findOrphanPages / getOrphansData /+// #4524 note: every call below pins mode: 'inbound' — this file's subject is+// SOURCE SCOPING (A2/F6/F8), and its fixtures were designed against the+// legacy no-inbound orphan definition (linker pages that link out on+// purpose). The new 'islanded' default is covered by+// test/orphans-mode-islanded.test.ts.// find_orphans op handler). Seed ONCE in beforeAll rather than reset+reseed// per test — the canonical R3/R4 pattern (engine in beforeAll, disconnect in// afterAll) is satisfied, and this cuts the file from ~6min to seconds.@@ -84,7 +89,7 @@ afterAll(async () => {describe('findOrphanPages — source scoping (A2)', () => {test('scoped to default: alice-orphan is an orphan; cross-source-linked page is NOT', async () => {- const rows = await engine.findOrphanPages({ sourceId: 'default' });+ const rows = await engine.findOrphanPages({ sourceId: 'default', mode: 'inbound' });const slugs = rows.map(r => r.slug);expect(slugs).toContain('people/alice-orphan');// A2: cross-target has inbound from src-b → reachable → NOT an orphan.@@ -98,13 +103,13 @@ describe('findOrphanPages — source scoping (A2)', () => {});test('scoped to src-b returns a different orphan set', async () => {- const rows = await engine.findOrphanPages({ sourceId: 'src-b' });+ const rows = await engine.findOrphanPages({ sourceId: 'src-b', mode: 'inbound' });const slugs = rows.map(r => r.slug).sort();expect(slugs).toEqual(['people/src-b-linker', 'people/zara-orphan']);});test('unscoped (brain-wide) returns the union', async () => {- const rows = await engine.findOrphanPages();+ const rows = await engine.findOrphanPages({ mode: 'inbound' });const slugs = rows.map(r => r.slug).sort();expect(slugs).toEqual(['people/alice-orphan',@@ -114,7 +119,7 @@ describe('findOrphanPages — source scoping (A2)', () => {});test('federated sourceIds scopes to the union of the given sources', async () => {- const rows = await engine.findOrphanPages({ sourceIds: ['default', 'src-b'] });+ const rows = await engine.findOrphanPages({ sourceIds: ['default', 'src-b'], mode: 'inbound' });const slugs = rows.map(r => r.slug).sort();expect(slugs).toEqual(['people/alice-orphan',@@ -122,7 +127,7 @@ describe('findOrphanPages — source scoping (A2)', () => {'people/zara-orphan',]);// Single-element federated array behaves like the scalar scope.- const onlyB = await engine.findOrphanPages({ sourceIds: ['src-b'] });+ const onlyB = await engine.findOrphanPages({ sourceIds: ['src-b'], mode: 'inbound' });expect(onlyB.map(r => r.slug).sort()).toEqual(['people/src-b-linker','people/zara-orphan',@@ -132,7 +137,7 @@ describe('findOrphanPages — source scoping (A2)', () => {describe('getOrphansData — scoped totals + F6 denominator', () => {test('default scope: counts differ from brain-wide; excluded non-orphan drops from total_linkable (F6)', async () => {- const data = await findOrphans(engine, { includePseudo: false, sourceId: 'default' });+ const data = await findOrphans(engine, { includePseudo: false, sourceId: 'default', mode: 'inbound' });// 4 live default pages; 1 orphan (alice-orphan).expect(data.total_pages).toBe(4);expect(data.total_orphans).toBe(1);@@ -146,14 +151,14 @@ describe('getOrphansData — scoped totals + F6 denominator', () => {});test('src-b scope: distinct from default', async () => {- const data = await findOrphans(engine, { includePseudo: false, sourceId: 'src-b' });+ const data = await findOrphans(engine, { includePseudo: false, sourceId: 'src-b', mode: 'inbound' });expect(data.total_pages).toBe(2);expect(data.total_orphans).toBe(2);expect(data.total_linkable).toBe(2); // no excluded pages in src-b});test('brain-wide F6: excluded non-orphan drops from total_linkable', async () => {- const data = await findOrphans(engine, { includePseudo: false });+ const data = await findOrphans(engine, { includePseudo: false, mode: 'inbound' });expect(data.total_pages).toBe(6);expect(data.total_orphans).toBe(3);// 6 live pages - 1 excluded (templates/junk-linked) = 5.@@ -161,7 +166,7 @@ describe('getOrphansData — scoped totals + F6 denominator', () => {});test('includePseudo keeps excluded pages in the denominator', async () => {- const data = await findOrphans(engine, { includePseudo: true, sourceId: 'default' });+ const data = await findOrphans(engine, { includePseudo: true, sourceId: 'default', mode: 'inbound' });// No exclusion → denominator is the full live set.expect(data.total_linkable).toBe(4);});@@ -180,7 +185,7 @@ describe('find_orphans MCP op — F8 source-isolation scope', () => {remote: true,sourceId: 'src-b',};- const result = (await op!.handler(ctx as any, {})) as { orphans: { slug: string }[] };+ const result = (await op!.handler(ctx as any, { mode: 'inbound' })) as { orphans: { slug: string }[] };const slugs = result.orphans.map(o => o.slug).sort();expect(slugs).toEqual(['people/src-b-linker', 'people/zara-orphan']);// Leak guard: default's orphan must NOT appear.@@ -205,7 +210,7 @@ describe('find_orphans MCP op — F8 source-isolation scope', () => {allowedSources: ['src-b'], // ...but the federated array wins.},};- const result = (await op!.handler(ctx as any, {})) as { orphans: { slug: string }[] };+ const result = (await op!.handler(ctx as any, { mode: 'inbound' })) as { orphans: { slug: string }[] };const slugs = result.orphans.map(o => o.slug).sort();expect(slugs).toEqual(['people/src-b-linker', 'people/zara-orphan']);expect(slugs).not.toContain('people/alice-orphan');diff --git a/test/orphans.test.ts b/test/orphans.test.tsindex ecbfb74f0e..db9c6a46bc 100644--- a/test/orphans.test.ts+++ b/test/orphans.test.ts@@ -260,10 +260,12 @@ describe('findOrphans (engine-injected)', () => {if (engine) await engine.disconnect();}, 60_000);- test('returns pages with no inbound links, excluding pseudo-pages', async () => {- // Build a tiny brain: alice links to bob. alice is an orphan (nothing- // points to her), bob is not (alice points to him). _atlas is a pseudo- // page that should be excluded by default.+ test('default (islanded, #4524) excludes connected pages and pseudo-pages', async () => {+ // Build a tiny brain: alice links to bob, carol is fully disconnected.+ // Under the #4524 canonical 'islanded' default (= get_health's+ // definition) alice is NOT an orphan (she links out) and bob is not+ // (alice points to him) — only carol is. _atlas is a pseudo page that+ // should be excluded by default.await engine.putPage('people/alice', {type: 'person',title: 'Alice',@@ -276,6 +278,12 @@ describe('findOrphans (engine-injected)', () => {compiled_truth: 'Bob.',timeline: '',});+ await engine.putPage('people/carol', {+ type: 'person',+ title: 'Carol',+ compiled_truth: 'Carol is disconnected.',+ timeline: '',+ });await engine.putPage('_atlas', {type: 'concept',title: 'Atlas',@@ -288,10 +296,15 @@ describe('findOrphans (engine-injected)', () => {const result = await findOrphans(engine);const slugs = result.orphans.map(o => o.slug).sort();- expect(slugs).toEqual(['people/alice']); // _atlas excluded by default; bob has a backlink+ expect(slugs).toEqual(['people/carol']); // alice links out; bob has a backlink; _atlas excludedexpect(result.total_orphans).toBe(1);- expect(result.total_pages).toBe(3);+ expect(result.total_pages).toBe(4);expect(result.excluded).toBeGreaterThanOrEqual(1); // _atlas was filtered++ // The legacy no-inbound-only view stays reachable via mode: 'inbound' —+ // there alice (no backlinks, links out) counts again.+ const inbound = await findOrphans(engine, { mode: 'inbound' });+ expect(inbound.orphans.map(o => o.slug).sort()).toEqual(['people/alice', 'people/carol']);});test('includePseudo: true surfaces pseudo-pages too', async () => {@@ -403,8 +416,14 @@ describe('findOrphans (engine-injected)', () => {const rows = await queryOrphanPages(engine);const slugs = rows.map(r => r.slug);- // alice is orphan (no inbound), bob is NOT (alice links to him).- expect(slugs).toContain('people/alice');+ // #4524 islanded default: bob is NOT an orphan (live inbound from+ // alice), and alice is NOT either — she links out to a live page.+ expect(slugs).not.toContain('people/alice');expect(slugs).not.toContain('people/bob');+ // The legacy inbound-only view still reports alice (no backlinks).+ const inbound = await engine.findOrphanPages({ mode: 'inbound' });+ const inboundSlugs = inbound.map(r => r.slug);+ expect(inboundSlugs).toContain('people/alice');+ expect(inboundSlugs).not.toContain('people/bob');});});diff --git a/test/pages-source-scoping-4329.test.ts b/test/pages-source-scoping-4329.test.tsindex 4154abcb14..0feac044da 100644--- a/test/pages-source-scoping-4329.test.ts+++ b/test/pages-source-scoping-4329.test.ts@@ -265,6 +265,47 @@ describe('#4329 — get_page source_id', () => {});});+describe('#4516 — get_page miss names the source that holds the slug (trusted local only)', () => {+ beforeEach(async () => {+ await engine.putPage('beta-only/doc', {+ type: 'note', title: 'beta only', compiled_truth: 'beta only content', timeline: '', frontmatter: {},+ }, { sourceId: 'beta' });+ });++ test('trusted local scoped miss → hint says which source holds it and how to route there', async () => {+ await expect(get_page.handler(ctxOf({ remote: false }), { slug: 'beta-only/doc' }))+ .rejects.toMatchObject({+ code: 'page_not_found',+ suggestion: expect.stringContaining("--source beta"),+ });+ });++ test('remote caller gets NO cross-source existence hint (no oracle outside the grant)', async () => {+ try {+ await get_page.handler(ctxOf(), { slug: 'beta-only/doc' });+ throw new Error('expected page_not_found');+ } catch (e: any) {+ expect(e.code).toBe('page_not_found');+ expect(String(e.suggestion ?? '')).not.toContain('beta');+ }+ });++ test('slug existing nowhere keeps the plain hint', async () => {+ try {+ await get_page.handler(ctxOf({ remote: false }), { slug: 'nowhere/doc' });+ throw new Error('expected page_not_found');+ } catch (e: any) {+ expect(e.code).toBe('page_not_found');+ expect(String(e.suggestion ?? '')).not.toContain('--source');+ }+ });++ test('explicit --source targeting still finds it (isolation is by design, unchanged)', async () => {+ const res = await get_page.handler(ctxOf({ remote: false }), { slug: 'beta-only/doc', source_id: 'beta' }) as Record<string, unknown>;+ expect(res.title).toBe('beta only');+ });+});+describe('#3070 — sole_non_default emptiness guard (real engine, both ways)', () => {// Neutral cwd (no .gbrain-source ancestor, outside any registered// local_path) + GBRAIN_SOURCE cleared, so tiers 1-4 never fire.diff --git a/test/pages-upsert-arbiter.test.ts b/test/pages-upsert-arbiter.test.tsindex d96afc1a82..b8b16d2a7e 100644--- a/test/pages-upsert-arbiter.test.ts+++ b/test/pages-upsert-arbiter.test.ts@@ -167,3 +167,74 @@ describe('doctor pages_upsert_arbiter check (#550)', () => {expect(check.message).toContain('apply-migrations');});});++describe('#550 residual — catalog validity gates on the arbiter probe', () => {+ test('an INVALID arbiter index does not count (failed CONCURRENTLY remnant shape)', async () => {+ // Healthy first, then flip the catalog validity bit — the exact state a+ // failed CREATE INDEX CONCURRENTLY leaves behind. pg_indexes still+ // renders a normal-looking indexdef for it, but ON CONFLICT cannot use+ // it, so the check must flag needsRepair instead of masking the outage.+ expect((await checkPagesUpsertArbiter(engine)).arbiterPresent).toBe(true);+ await engine.executeRaw(+ `UPDATE pg_index SET indisvalid = false+ WHERE indexrelid = 'pages_source_slug_key'::regclass`,+ );+ try {+ const st = await checkPagesUpsertArbiter(engine);+ expect(st.arbiterPresent).toBe(false);+ expect(st.needsRepair).toBe(true);+ } finally {+ await engine.executeRaw(+ `UPDATE pg_index SET indisvalid = true+ WHERE indexrelid = 'pages_source_slug_key'::regclass`,+ );+ }+ });++ test('repair replaces an INVALID arbiter and putPage works again', async () => {+ await engine.executeRaw(+ `UPDATE pg_index SET indisvalid = false+ WHERE indexrelid = 'pages_source_slug_key'::regclass`,+ );+ const r = await repairPagesUpsertArbiter(engine);+ expect(r.repaired).toBe(true);+ expect((await checkPagesUpsertArbiter(engine)).arbiterPresent).toBe(true);+ await putProbePage('probe/invalid-heal');+ });++ test('a DEFERRABLE unique constraint does not count (indimmediate = false)', async () => {+ await dropArbiter();+ await engine.executeRaw(+ `ALTER TABLE pages ADD CONSTRAINT pages_deferrable_probe+ UNIQUE (source_id, slug) DEFERRABLE INITIALLY IMMEDIATE`,+ );+ try {+ const st = await checkPagesUpsertArbiter(engine);+ expect(st.arbiterPresent).toBe(false);+ expect(st.needsRepair).toBe(true);+ } finally {+ await engine.executeRaw(+ `ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_deferrable_probe`,+ );+ }+ });++ test('an arbiter on a same-named table in ANOTHER schema does not count', async () => {+ await engine.executeRaw(`CREATE SCHEMA IF NOT EXISTS arbiter_decoy`);+ await engine.executeRaw(+ `CREATE TABLE IF NOT EXISTS arbiter_decoy.pages (+ source_id TEXT NOT NULL, slug TEXT NOT NULL,+ CONSTRAINT decoy_source_slug_key UNIQUE (source_id, slug)+ )`,+ );+ await dropArbiter();+ try {+ const st = await checkPagesUpsertArbiter(engine);+ expect(st.arbiterPresent).toBe(false);+ expect(st.needsRepair).toBe(true);+ } finally {+ await engine.executeRaw(`DROP TABLE IF EXISTS arbiter_decoy.pages`);+ await engine.executeRaw(`DROP SCHEMA IF EXISTS arbiter_decoy`);+ }+ });+});diff --git a/test/pglite-repair-command.serial.test.ts b/test/pglite-repair-command.serial.test.tsindex 4ad0e850b6..26bd1dcc20 100644--- a/test/pglite-repair-command.serial.test.ts+++ b/test/pglite-repair-command.serial.test.ts@@ -18,7 +18,7 @@*/import { describe, test, expect } from 'bun:test';import {- existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync,+ existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';@@ -416,3 +416,30 @@ describe('gbrain pglite-repair — argument + quarantine hardening (adversarialexpect(readdirSync(join(dir, '..')).some((f) => f.includes('.wal-repair-backup-'))).toBe(false);});});++describe('gbrain pglite-repair — interactive confirm wiring (#4318 residual)', () => {+ test('uses the shared confirm-prompt helper, not a local reimplementation', () => {+ // This file's own inline `promptYesNo` had the same close-before-resolve+ // race that #4318 fixed in sync-cost-gate.ts/reindex-code.ts: `rl.close()`+ // fired inside the answer callback synchronously triggered an unguarded+ // `rl.on('close', () => resolve(false))`, so a typed "y" was silently+ // read as decline. This pins the fix at the source level — a future+ // change that reintroduces a local `promptYesNo`/`createInterface` here+ // (rather than importing the shared, race-free helper) fails this test,+ // even though `test/confirm-prompt.test.ts` cannot see this file at all.+ // test-reads-source-ok: pins that the local reimplementation stays gone+ // and the shared helper is wired with the exact stderr-preserving args —+ // there's no exported/injectable seam to assert this behaviorally.+ const src = readFileSync(join(import.meta.dir, '../src/commands/pglite-repair.ts'), 'utf8');+ expect(src).toContain("import { promptYesNo } from '../core/confirm-prompt.ts';");+ expect(src).not.toMatch(/\bfunction promptYesNo\b/);+ expect(src).not.toContain("from 'readline'");+ // The call site itself must keep the prompt on stderr — confirm-prompt's+ // default `output` is stdout, and `--json` callers depend on stdout+ // staying machine-readable-only. Checking the import above isn't enough:+ // dropping `{ output: process.stderr }` from this call would still pass+ // that assertion while leaking the prompt into --json output.+ expect(src).toContain("await promptYesNo('Repair now? [y/N] ', { output: process.stderr });");+ expect(src).not.toContain("from 'node:readline'");+ });+});diff --git a/test/privacy-strip-and-forget.test.ts b/test/privacy-strip-and-forget.test.tsindex 968811f51f..6f5a105581 100644--- a/test/privacy-strip-and-forget.test.ts+++ b/test/privacy-strip-and-forget.test.ts@@ -12,7 +12,7 @@* Real PGLite + tempdir filesystem.*/-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -21,6 +21,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { chunkText } from '../src/core/chunkers/recursive.ts';import { forgetFactInFence } from '../src/core/facts/forget.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../src/core/facts-fence.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';let engine: PGLiteEngine;let brainDir: string;@@ -134,6 +136,566 @@ describe('Layer B — get_page strip trigger (Codex R2-#5)', () => {expect(stripped).toContain('WORLD_ROW');expect(stripped).not.toContain('PRIVATE_ROW');});++ // #3625 Codex review Critical finding: get_page/fetch_page only ever+ // stripped compiled_truth. A `## Facts` fence written below the+ // `<!-- timeline -->` sentinel (splitBody's split boundary) lands in the+ // `timeline` column instead — pre-existing, independent of the #3625+ // reconciliation guard — and was returned to remote/untrusted callers+ // completely unstripped, leaking private fact rows through both the+ // `timeline` field and the serialized `content` round-trip field.+ describe('#3625 Critical: get_page/fetch_page must ALSO strip the timeline column', () => {+ function makeCtx(opts: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ // Cross-file gateway-state hermeticity (see put-page-provenance.test.ts's+ // beforeAll comment): put_page's noEmbed = ctx.deferEmbeds === true ||+ // !isAvailable('embedding') — relying on the ambient isAvailable() check+ // means a sibling file sharing this shard's process that configured a+ // live embedding provider makes put_page attempt a real embed call here,+ // which hangs without a stubbed transport. Force it off explicitly.+ deferEmbeds: true,+ ...opts,+ };+ }++ const MISPLACED_FENCE_CONTENT = `---+title: alice+type: person+---++Some body content.++<!-- timeline -->++## Facts++${FACTS_FENCE_BEGIN}+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | PUBLIC_TIMELINE_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | PRIVATE_TIMELINE_FACT | fact | 1.0 | private | high | 2026-01-01 | | s | |+${FACTS_FENCE_END}+`;++ test('get_page: remote caller sees the world row but never the private row, in timeline OR content', async () => {+ const putPageOp = operations.find((o) => o.name === 'put_page')!;+ const getPageOp = operations.find((o) => o.name === 'get_page')!;+ await putPageOp.handler(makeCtx({ remote: false }), {+ slug: 'people/alice-timeline-leak',+ content: MISPLACED_FENCE_CONTENT,+ });++ // Sanity: confirm the fence really landed in timeline, not+ // compiled_truth — otherwise this test would pass for the wrong+ // reason (the pre-existing compiled_truth strip would cover it).+ const raw = await engine.getPage('people/alice-timeline-leak');+ expect(parseFactsFence(raw!.compiled_truth ?? '').facts).toHaveLength(0);+ expect((raw!.timeline ?? '')).toContain('PRIVATE_TIMELINE_FACT');++ const remote = await getPageOp.handler(makeCtx({ remote: true }), {+ slug: 'people/alice-timeline-leak',+ include_content: true,+ }) as { timeline?: string; content?: string };+ expect(remote.timeline).toContain('PUBLIC_TIMELINE_FACT');+ expect(remote.timeline).not.toContain('PRIVATE_TIMELINE_FACT');+ expect(remote.content).not.toContain('PRIVATE_TIMELINE_FACT');++ // Control: a trusted local caller still sees everything, unstripped.+ const local = await getPageOp.handler(makeCtx({ remote: false }), {+ slug: 'people/alice-timeline-leak',+ }) as { timeline?: string };+ expect(local.timeline).toContain('PRIVATE_TIMELINE_FACT');+ });++ test('fetch_page: remote caller\'s serialized text never contains the private timeline row', async () => {+ const putPageOp = operations.find((o) => o.name === 'put_page')!;+ const fetchPageOp = operations.find((o) => o.name === 'fetch')!;+ await putPageOp.handler(makeCtx({ remote: false }), {+ slug: 'people/bob-timeline-leak',+ content: MISPLACED_FENCE_CONTENT.replace('alice', 'bob'),+ });++ const remote = await fetchPageOp.handler(makeCtx({ remote: true }), {+ id: 'people/bob-timeline-leak',+ }) as { text?: string };+ expect(remote.text).toContain('PUBLIC_TIMELINE_FACT');+ expect(remote.text).not.toContain('PRIVATE_TIMELINE_FACT');+ });+ });+});++// ─────────────────────────────────────────────────────────────────+// #2044 / #4548 row-level visibility-aware fence merge on remote+// write-back. A remote get_page strips non-'world' rows before the caller+// ever sees them, so those rows being absent from a put_page write-back is+// NOT an intentional delete — they are restored row-by-row. World-visible+// rows the caller could see are never restored: their edits/deletions are+// the caller's, honored as written (#4554). Trusted local callers see the+// full fence, so the merge never fires for them.+// ─────────────────────────────────────────────────────────────────++describe('#4548 row-level visibility-aware fence merge (remote write-back)', () => {+ function makeCtx(opts: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ deferEmbeds: true,+ ...opts,+ };+ }+ const putPageOp = () => operations.find((o) => o.name === 'put_page')!;+ const getPageOp = () => operations.find((o) => o.name === 'get_page')!;++ async function remoteRoundTrip(slug: string, edit: (content: string) => string): Promise<void> {+ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ await putPageOp().handler(makeCtx({ remote: true }), { slug, content: edit(remote.content ?? '') });+ }++ test('P1 (#4548): mixed world+private fence — the hidden private row is RESTORED on a remote prose-edit round-trip', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/p1-mixed-merge';+ const fence = FENCE_BODY(+ `| 1 | PUBLIC_P1_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | PRIVATE_P1_FACT | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ warnSpy.mockClear();+ await remoteRoundTrip(slug, (c) => c.replace('Some text.', 'Some text edited.'));++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(raw?.compiled_truth ?? '').toContain('Some text edited.');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'PUBLIC_P1_FACT'],+ [2, 'PRIVATE_P1_FACT'],+ ]);+ // The gap is CLOSED — no "#2044 gap" data-loss warning fires anymore.+ const warnedGap = warnSpy.mock.calls.some((c) => String(c[0]).includes('#2044 gap'));+ expect(warnedGap).toBe(false);+ } finally {+ warnSpy.mockRestore();+ }+ });++ test('mixed adds+edits+deletes: world-row edit + world-row delete honored, hidden row restored, caller add kept', async () => {+ const slug = 'people/mixed-adds-edits-deletes';+ const fence = FENCE_BODY(+ `| 1 | PUBLIC_A | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | SECRET_B | fact | 1.0 | private | high | 2026-01-02 | | s | |+| 3 | PUBLIC_C | fact | 1.0 | world | high | 2026-01-03 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ await remoteRoundTrip(slug, (c) => c+ .replace('PUBLIC_A', 'PUBLIC_A_EDITED') // edit visible row 1+ .split('\n').filter((l) => !l.includes('PUBLIC_C')).join('\n') // delete visible row 3+ .replace(FACTS_FENCE_END,+ `| 4 | CALLER_ADDED_FACT | fact | 0.9 | world | medium | 2026-02-01 | | s | |\n${FACTS_FENCE_END}`),+ );++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'PUBLIC_A_EDITED'], // caller's edit of a visible row respected+ [2, 'SECRET_B'], // hidden row restored at its stable rowNum+ [4, 'CALLER_ADDED_FACT'], // caller's addition kept+ ]);+ expect(raw?.compiled_truth ?? '').not.toContain('PUBLIC_C'); // visible deletion honored+ });++ test('caller add colliding with a hidden rowNum: hidden row keeps its stable number, the add is renumbered', async () => {+ const slug = 'people/collision-renumber';+ const fence = FENCE_BODY(+ `| 1 | PUBLIC_COLLIDE | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | SECRET_COLLIDE | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ // The remote caller only sees row 1, so a naive append lands on #2 —+ // the hidden private row's number.+ await remoteRoundTrip(slug, (c) => c.replace(FACTS_FENCE_END,+ `| 2 | CALLER_COLLIDING_ADD | fact | 0.9 | world | medium | 2026-02-01 | | s | |\n${FACTS_FENCE_END}`,+ ));++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'PUBLIC_COLLIDE'],+ [2, 'SECRET_COLLIDE'], // stable rowNum preserved (cross-page #F<N> refs)+ [3, 'CALLER_COLLIDING_ADD'], // caller's add renumbered onto a fresh number+ ]);+ });++ test('pure-private fence round-trip: full restoration still works (the original #2044 path), silently', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/no-warn-allprivate';+ const fence = FENCE_BODY(+ '| 1 | PRIVATE_NOWARN_FACT | fact | 1.0 | private | high | 2026-01-01 | | s | |',+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ warnSpy.mockClear();+ await remoteRoundTrip(slug, (c) => c.replace('Some text.', 'Some text edited.'));++ const anyWarning = warnSpy.mock.calls.some((c) => String(c[0]).includes('#2044'));+ expect(anyWarning).toBe(false);+ const raw = await engine.getPage(slug, { sourceId: 'default' });+ expect((raw?.compiled_truth ?? '')).toContain('PRIVATE_NOWARN_FACT');+ } finally {+ warnSpy.mockRestore();+ }+ });++ test('idempotence: a remote write that already carries the hidden rows (same rowNum + claim) does not duplicate them', async () => {+ const slug = 'people/full-content-writeback';+ const fence = FENCE_BODY(+ `| 1 | PUBLIC_FULL | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | SECRET_FULL | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ // A remote writer that got the full content out-of-band writes it back+ // verbatim (plus a prose edit so the import isn't a hash-match skip).+ await putPageOp().handler(makeCtx({ remote: true }), {+ slug,+ content: fence.replace('Some text.', 'Some text edited.'),+ });++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(parsed.facts).toHaveLength(2);+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'PUBLIC_FULL'],+ [2, 'SECRET_FULL'],+ ]);+ });++ test('residual gap warn: a malformed incoming fence blocks the merge and the #2044 gap warning still fires', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/malformed-residual';+ const fence = FENCE_BODY(+ `| 1 | PUBLIC_MAL | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | SECRET_MAL | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ warnSpy.mockClear();+ // The caller mangles the visible row's kind — the incoming fence now+ // parses with warnings, so the merge refuses to rewrite it (it can't+ // re-render rows it couldn't parse without losing caller content).+ // The hidden row is lost; the gap warning surfaces exactly that.+ await remoteRoundTrip(slug, (c) => c.replace('| fact |', '| banana |'));++ const warnedGap = warnSpy.mock.calls.some(+ (c) => String(c[0]).includes('#2044 gap') && String(c[0]).includes(slug),+ );+ expect(warnedGap).toBe(true);+ const raw = await engine.getPage(slug, { sourceId: 'default' });+ expect((raw?.compiled_truth ?? '')).not.toContain('SECRET_MAL');+ } finally {+ warnSpy.mockRestore();+ }+ });++ test('no merge, no warning: a normal local (non-remote) edit sees the full fence and its deletions are honored', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/no-warn-local';+ const fence = FENCE_BODY(+ `| 1 | LOCAL_WORLD_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | LOCAL_PRIVATE_FACT | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });+ warnSpy.mockClear();+ // Local write that drops both rows -- fully-informed, no merge, no diagnostic.+ await putPageOp().handler(makeCtx({ remote: false }), {+ slug,+ content: '# Page\n\nSome text edited.\n',+ });++ const anyWarning = warnSpy.mock.calls.some((c) => String(c[0]).includes('#2044'));+ expect(anyWarning).toBe(false);+ const raw = await engine.getPage(slug, { sourceId: 'default' });+ expect((raw?.compiled_truth ?? '')).not.toContain('LOCAL_PRIVATE_FACT');+ expect((raw?.compiled_truth ?? '')).not.toContain('LOCAL_WORLD_FACT');+ } finally {+ warnSpy.mockRestore();+ }+ });+});++// ─────────────────────────────────────────────────────────────────+// #4554: a fully-visible world-only fence deletion is a legitimate edit —+// under the row-level merge it stays deleted (no whole-block resurrection),+// and the old "#2044 restoration ... may have genuinely deleted" warn+// (#4555) no longer misfires: nothing world-visible is ever restored.+// ─────────────────────────────────────────────────────────────────++describe('#4554 world-only fence deletion honored (no resurrection, no misfiring warn)', () => {+ function makeCtx(opts: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ deferEmbeds: true,+ ...opts,+ };+ }+ const putPageOp = () => operations.find((o) => o.name === 'put_page')!;+ const getPageOp = () => operations.find((o) => o.name === 'get_page')!;++ test('deleting a world-only fence over remote round-trip: deletion sticks, no restoration warn fires', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/p2-worldonly-honored';+ const fence = FENCE_BODY(+ '| 1 | WORLD_ONLY_P2_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |',+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });++ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ const body = remote.content ?? '';+ const factsHeadingIdx = body.indexOf('## Facts');+ const fenceEndIdx = body.indexOf(FACTS_FENCE_END) + FACTS_FENCE_END.length;+ const edited = body.slice(0, factsHeadingIdx).replace('Some text.', 'Some text, fence removed.')+ + body.slice(fenceEndIdx);+ warnSpy.mockClear();+ await putPageOp().handler(makeCtx({ remote: true }), { slug, content: edited });++ // The caller saw the whole fence and chose to remove it — honored.+ const raw = await engine.getPage(slug, { sourceId: 'default' });+ expect((raw?.compiled_truth ?? '')).not.toContain('WORLD_ONLY_P2_FACT');+ // And no "#2044 restoration"/"#2044" warn misfires about it.+ const anyWarning = warnSpy.mock.calls.some((c) => String(c[0]).includes('#2044'));+ expect(anyWarning).toBe(false);+ } finally {+ warnSpy.mockRestore();+ }+ });++ test('deleting only the WORLD rows of a mixed fence: world deletion sticks while hidden rows are restored', async () => {+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const slug = 'people/p2-mixed-world-delete';+ const fence = FENCE_BODY(+ `| 1 | WORLD_DELETE_ME | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | PRIVATE_KEEP_ME | fact | 1.0 | private | high | 2026-01-02 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });++ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ // Delete the (visible) world row but keep the fence itself.+ const edited = (remote.content ?? '')+ .split('\n').filter((l) => !l.includes('WORLD_DELETE_ME')).join('\n');+ warnSpy.mockClear();+ await putPageOp().handler(makeCtx({ remote: true }), { slug, content: edited });++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [2, 'PRIVATE_KEEP_ME'], // restored — the caller never saw it+ ]);+ expect((raw?.compiled_truth ?? '')).not.toContain('WORLD_DELETE_ME');+ // Restoring hidden rows is correct-by-design now — not at-risk, no warn.+ const anyWarning = warnSpy.mock.calls.some((c) => String(c[0]).includes('#2044'));+ expect(anyWarning).toBe(false);+ } finally {+ warnSpy.mockRestore();+ }+ });++ test('partial deletion of a world-only fence: exactly the kept rows remain, deleted ones stay deleted', async () => {+ const slug = 'people/p2-worldonly-partial';+ const fence = FENCE_BODY(+ `| 1 | WORLD_KEEP_A | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | WORLD_DROP_B | fact | 1.0 | world | high | 2026-01-02 | | s | |+| 3 | WORLD_KEEP_C | fact | 1.0 | world | high | 2026-01-03 | | s | |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });++ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ const edited = (remote.content ?? '')+ .split('\n').filter((l) => !l.includes('WORLD_DROP_B')).join('\n');+ await putPageOp().handler(makeCtx({ remote: true }), { slug, content: edited });++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'WORLD_KEEP_A'],+ [3, 'WORLD_KEEP_C'],+ ]);+ });++ test('restoration preserves forget history: an inactive (struck, forgotten) private row round-trips intact', async () => {+ const slug = 'people/p2-forgotten-roundtrip';+ const fence = FENCE_BODY(+ `| 1 | WORLD_VISIBLE_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | ~~FORGOTTEN_SECRET~~ | fact | 0.9 | private | low | 2026-01-02 | 2026-02-01 | s | forgotten: user asked to remove |`,+ );+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: fence });++ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ expect(remote.content ?? '').not.toContain('FORGOTTEN_SECRET'); // stripped for remote readers+ await putPageOp().handler(makeCtx({ remote: true }), {+ slug,+ content: (remote.content ?? '').replace('Some text.', 'Some text edited.'),+ });++ const raw = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(raw?.compiled_truth ?? '');+ const restoredRow = parsed.facts.find((f) => f.rowNum === 2);+ expect(restoredRow?.claim).toBe('FORGOTTEN_SECRET');+ expect(restoredRow?.active).toBe(false); // strikethrough survives the merge+ expect(restoredRow?.forgotten).toBe(true); // forget-as-fence history survives+ expect(restoredRow?.validUntil).toBe('2026-02-01');+ });+});++// ─────────────────────────────────────────────────────────────────+// #4546 round-trip hazard: #4547 strips takes/facts fences from the+// `timeline` column for remote readers, so a remote get_page -> edit ->+// put_page round-trip arrives with the timeline fence's non-'world' rows+// missing too. The same row-level merge that protects compiled_truth+// (#4548) must cover the timeline-embedded fence, or the write-back+// silently drops the private timeline rows.+// ─────────────────────────────────────────────────────────────────++describe('#4546 timeline-embedded fence survives a remote round-trip', () => {+ function makeCtx(opts: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ deferEmbeds: true,+ ...opts,+ };+ }+ const putPageOp = () => operations.find((o) => o.name === 'put_page')!;+ const getPageOp = () => operations.find((o) => o.name === 'get_page')!;++ const TIMELINE_FENCE_CONTENT = (slug: string) => `---+title: ${slug}+type: person+---++Body content.++<!-- timeline -->++## Facts++${FACTS_FENCE_BEGIN}+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|+| 1 | TL_PUBLIC_FACT | fact | 1.0 | world | high | 2026-01-01 | | s | |+| 2 | TL_SECRET_FACT | fact | 1.0 | private | high | 2026-01-02 | | s | |+${FACTS_FENCE_END}+`;++ test('remote prose-edit round-trip restores the hidden private row into the timeline column', async () => {+ const slug = 'people/tl-roundtrip-restore';+ await putPageOp().handler(makeCtx({ remote: false }), {+ slug,+ content: TIMELINE_FENCE_CONTENT(slug),+ });+ // Sanity: the fence really lives in timeline, and the remote reader+ // never sees the private row (#4547's read-side strip).+ const raw = await engine.getPage(slug, { sourceId: 'default' });+ expect(parseFactsFence(raw!.compiled_truth ?? '').facts).toHaveLength(0);+ expect(raw!.timeline ?? '').toContain('TL_SECRET_FACT');+ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ expect(remote.content ?? '').not.toContain('TL_SECRET_FACT');++ await putPageOp().handler(makeCtx({ remote: true }), {+ slug,+ content: (remote.content ?? '').replace('Body content.', 'Body content, edited remotely.'),+ });++ const after = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(after?.timeline ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [1, 'TL_PUBLIC_FACT'],+ [2, 'TL_SECRET_FACT'], // restored into timeline, not lost, not moved+ ]);+ // The restored row stays in the timeline column; compiled_truth gains no fence.+ expect(parseFactsFence(after?.compiled_truth ?? '').facts).toHaveLength(0);+ expect(after?.compiled_truth ?? '').toContain('Body content, edited remotely.');+ });++ test('deleting the visible world row of the timeline fence sticks; the hidden row is still restored', async () => {+ const slug = 'people/tl-roundtrip-world-delete';+ await putPageOp().handler(makeCtx({ remote: false }), {+ slug,+ content: TIMELINE_FENCE_CONTENT(slug),+ });+ const remote = await getPageOp().handler(makeCtx({ remote: true }), {+ slug,+ include_content: true,+ }) as { content?: string };+ const edited = (remote.content ?? '')+ .split('\n').filter((l) => !l.includes('TL_PUBLIC_FACT')).join('\n');+ await putPageOp().handler(makeCtx({ remote: true }), { slug, content: edited });++ const after = await engine.getPage(slug, { sourceId: 'default' });+ const parsed = parseFactsFence(after?.timeline ?? '');+ expect(parsed.facts.map((f) => [f.rowNum, f.claim])).toEqual([+ [2, 'TL_SECRET_FACT'],+ ]);+ expect(after?.timeline ?? '').not.toContain('TL_PUBLIC_FACT');+ });++ test('local trusted round-trip of a timeline fence is untouched by the merge', async () => {+ const slug = 'people/tl-local-untouched';+ await putPageOp().handler(makeCtx({ remote: false }), {+ slug,+ content: TIMELINE_FENCE_CONTENT(slug),+ });+ // Local caller deletes the ENTIRE timeline fence — fully informed, honored.+ const local = await getPageOp().handler(makeCtx({ remote: false }), {+ slug,+ include_content: true,+ }) as { content?: string };+ const fenceBegin = (local.content ?? '').indexOf('## Facts');+ const fenceEnd = (local.content ?? '').indexOf(FACTS_FENCE_END) + FACTS_FENCE_END.length;+ const edited = (local.content ?? '').slice(0, fenceBegin) + (local.content ?? '').slice(fenceEnd);+ await putPageOp().handler(makeCtx({ remote: false }), { slug, content: edited });++ const after = await engine.getPage(slug, { sourceId: 'default' });+ expect(after?.timeline ?? '').not.toContain('TL_SECRET_FACT');+ expect(after?.timeline ?? '').not.toContain('TL_PUBLIC_FACT');+ });});// ─────────────────────────────────────────────────────────────────diff --git a/test/propose-takes-config-max-tokens.test.ts b/test/propose-takes-config-max-tokens.test.tsnew file mode 100644index 0000000000..7bcce66dec--- /dev/null+++ b/test/propose-takes-config-max-tokens.test.ts@@ -0,0 +1,197 @@+/**+ * #4494 — propose_takes extractor output caps are configurable.+ *+ * Pre-fix, PROPOSE_TAKES_MAX_TOKENS=2048 / PROPOSE_TAKES_RETRY_MAX_TOKENS=4096+ * were hardcoded exports with no config read. Thinking models spend reasoning+ * tokens INSIDE maxTokens, so dense pages truncated at 2048, retried at 4096,+ * truncated again, threw, and were re-billed every cycle forever.+ *+ * Post-fix: dream.propose_takes.max_tokens / dream.propose_takes.retry_max_tokens+ * (floor 256; retry clamped >= base) resolve at the phase's engine.getConfig+ * seam (dream.triage.max_tokens precedent) and thread into defaultExtractor.+ */++import { describe, test, expect, beforeEach, afterAll } from 'bun:test';+import {+ configureGateway,+ resetGateway,+ __setChatTransportForTests,+} from '../src/core/ai/gateway.ts';+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import {+ runPhaseProposeTakes,+ defaultExtractor,+ PROPOSE_TAKES_MAX_TOKENS,+ PROPOSE_TAKES_RETRY_MAX_TOKENS,+ type ProposeTakesExtractor,+} from '../src/core/cycle/propose-takes.ts';+import type { OperationContext } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';++beforeEach(() => {+ resetGateway();+ __setChatTransportForTests(null);+ configureGateway({+ chat_model: 'anthropic:claude-sonnet-4-6',+ env: { ANTHROPIC_API_KEY: 'sk-ant-test' },+ });+});++afterAll(() => {+ __setChatTransportForTests(null);+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { ...process.env },+ });+});++function chatResult(text: string, stopReason: ChatResult['stopReason']): ChatResult {+ return {+ text,+ blocks: [{ type: 'text', text }],+ stopReason,+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6',+ providerId: 'anthropic',+ } as ChatResult;+}++const GOOD_JSON = '[{"claim_text":"Acme doubles ARR by Q4","kind":"bet","holder":"brain","weight":0.7}]';++const baseInput = {+ pagePath: 'companies/acme-example',+ pageBody: 'I bet Acme doubles ARR by Q4.',+ existingTakes: [],+};++describe('defaultExtractor configurable caps (#4494)', () => {+ test('input.maxTokens overrides the base cap', async () => {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => {+ seen.push(opts);+ return chatResult(GOOD_JSON, 'end');+ });+ await defaultExtractor({ ...baseInput, maxTokens: 8192 });+ expect(seen).toHaveLength(1);+ expect(seen[0].maxTokens).toBe(8192);+ });++ test('truncation retry uses retryMaxTokens (clamped >= base)', async () => {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => {+ seen.push(opts);+ return seen.length === 1+ ? chatResult('[{"claim_text":"tru', 'length')+ : chatResult(GOOD_JSON, 'end');+ });+ await defaultExtractor({ ...baseInput, maxTokens: 6000, retryMaxTokens: 3000 });+ expect(seen).toHaveLength(2);+ expect(seen[0].maxTokens).toBe(6000);+ // retry clamp: a retry cap below base escalates to at least base.+ expect(seen[1].maxTokens).toBe(6000);+ });++ test('floor: sub-256 maxTokens is raised to 256', async () => {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => {+ seen.push(opts);+ return chatResult(GOOD_JSON, 'end');+ });+ await defaultExtractor({ ...baseInput, maxTokens: 16 });+ expect(seen[0].maxTokens).toBe(256);+ });++ test('defaults unchanged when no overrides are passed', async () => {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => {+ seen.push(opts);+ return seen.length === 1+ ? chatResult('trunc', 'length')+ : chatResult(GOOD_JSON, 'end');+ });+ await defaultExtractor(baseInput);+ expect(seen[0].maxTokens).toBe(PROPOSE_TAKES_MAX_TOKENS);+ expect(seen[1].maxTokens).toBe(PROPOSE_TAKES_RETRY_MAX_TOKENS);+ });+});++// ─── phase-level config threading ───────────────────────────────────++function buildMockEngine(config: Record<string, string>): BrainEngine {+ return {+ kind: 'pglite',+ async getConfig(key: string): Promise<string | null> {+ return config[key] ?? null;+ },+ async executeRaw<T>(sql: string): Promise<T[]> {+ if (sql.includes('SELECT slug, source_id, compiled_truth')) {+ return [{+ slug: 'wiki/page-0',+ source_id: 'default',+ compiled_truth: 'prose with a bold claim in it',+ }] as T[];+ }+ if (sql.includes('SELECT id FROM take_proposals')) return [];+ if (sql.includes('INSERT INTO take_proposals')) return [{ id: 1 } as unknown as T];+ return [];+ },+ } as unknown as BrainEngine;+}++function buildCtx(engine: BrainEngine): OperationContext {+ return {+ engine,+ config: {} as never,+ logger: { info() {}, warn() {}, error() {} } as never,+ dryRun: false,+ remote: false,+ sourceId: 'default',+ };+}++describe('runPhaseProposeTakes threads dream.propose_takes.* config (#4494)', () => {+ test('configured caps reach the extractor input', async () => {+ const engine = buildMockEngine({+ 'dream.propose_takes.max_tokens': '5000',+ 'dream.propose_takes.retry_max_tokens': '9000',+ });+ const seen: Array<{ maxTokens?: number; retryMaxTokens?: number }> = [];+ const extractor: ProposeTakesExtractor = async (input) => {+ seen.push({ maxTokens: input.maxTokens, retryMaxTokens: input.retryMaxTokens });+ return [];+ };+ await runPhaseProposeTakes(buildCtx(engine), { extractor });+ expect(seen.length).toBeGreaterThanOrEqual(1);+ expect(seen[0].maxTokens).toBe(5000);+ expect(seen[0].retryMaxTokens).toBe(9000);+ });++ test('unset config keeps the #3763 defaults; retry clamps to >= base', async () => {+ const engine = buildMockEngine({ 'dream.propose_takes.max_tokens': '6000' });+ const seen: Array<{ maxTokens?: number; retryMaxTokens?: number }> = [];+ const extractor: ProposeTakesExtractor = async (input) => {+ seen.push({ maxTokens: input.maxTokens, retryMaxTokens: input.retryMaxTokens });+ return [];+ };+ await runPhaseProposeTakes(buildCtx(engine), { extractor });+ expect(seen[0].maxTokens).toBe(6000);+ // Default retry (4096) < configured base (6000) → clamped up to base.+ expect(seen[0].retryMaxTokens).toBe(6000);+ });++ test('garbage values fall back to defaults', async () => {+ const engine = buildMockEngine({+ 'dream.propose_takes.max_tokens': 'banana',+ 'dream.propose_takes.retry_max_tokens': '',+ });+ const seen: Array<{ maxTokens?: number; retryMaxTokens?: number }> = [];+ const extractor: ProposeTakesExtractor = async (input) => {+ seen.push({ maxTokens: input.maxTokens, retryMaxTokens: input.retryMaxTokens });+ return [];+ };+ await runPhaseProposeTakes(buildCtx(engine), { extractor });+ expect(seen[0].maxTokens).toBe(PROPOSE_TAKES_MAX_TOKENS);+ expect(seen[0].retryMaxTokens).toBe(PROPOSE_TAKES_RETRY_MAX_TOKENS);+ });+});diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.tsindex e071ac317f..76c7db8a3b 100644--- a/test/propose-takes.test.ts+++ b/test/propose-takes.test.ts@@ -503,12 +503,15 @@ New prose appended here.`;expect(extractorCalls).toBe(1);expect((details.warnings as string[]).some(w => w.includes('phase deadline hit'))).toBe(true);- // Rollup records the deadline break as a halt, not a completed round- // (same posture as budget exhaustion). Params: $5 = halt, $8 = completed.+ // #4482 three-way stop classification: a deadline cap is the extractor+ // working as designed (partial progress banked) — recorded as an+ // expected_limit, NOT a halt and NOT a completed round (same posture as+ // budget exhaustion). Params: $5 = halt, $8 = completed, $9 = expected_limit.const rollup = captured.find((c) => c.sql.includes('extract_rollup_7d'));expect(rollup).toBeDefined();- expect(rollup!.params[4]).toBe(1); // halt_count delta+ expect(rollup!.params[4]).toBe(0); // halt_count delta (error halts only)expect(rollup!.params[7]).toBe(0); // round_completed delta+ expect(rollup!.params[8]).toBe(1); // expected_limit delta (deadline cap)});test('default deadline does not fire on a fast run', async () => {diff --git a/test/put-page-remote-autolink-hint.test.ts b/test/put-page-remote-autolink-hint.test.tsnew file mode 100644index 0000000000..d34830854c--- /dev/null+++ b/test/put-page-remote-autolink-hint.test.ts@@ -0,0 +1,80 @@+/**+ * #4525 — remote put_page must SAY that auto-link reconciliation was skipped.+ *+ * The security posture (auto_link/auto_timeline run for trusted local writers+ * only) is by design; the failure was silence: the tool description never+ * mentioned it, and the bare {skipped: 'remote'} response left MCP agents+ * believing their body wikilinks had been reconciled into the graph.+ *+ * Pins: (1) the op description names the remote skip; (2) the skipped+ * response carries an actionable hint; (3) local writes are unchanged (no+ * skip marker).+ */++import { afterAll, beforeAll, beforeEach, describe, expect, test } 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 { resetGateway } from '../src/core/ai/gateway.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 240000);++afterAll(async () => {+ await engine.disconnect();+ resetGateway();+}, 120000);++beforeEach(async () => {+ await resetPgliteState(engine);+ resetGateway();+}, 120000);++function makeCtx(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' as const },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ ...overrides,+ };+}++const putPage = operations.find((o) => o.name === 'put_page')!;++const CONTENT = '---\ntitle: Hint Test\n---\n\nSee people/alice-example for context.';++describe('put_page remote auto-link disclosure (#4525)', () => {+ test('tool description names the remote auto-link skip', () => {+ expect(putPage.description).toMatch(/[Rr]emote .*callers/);+ expect(putPage.description).toContain('skipped');+ });++ test('remote write reports skipped: remote WITH an actionable hint', async () => {+ const result = (await putPage.handler(+ makeCtx({ remote: true }),+ { slug: 'notes/remote-hint', content: CONTENT },+ )) as { auto_links?: { skipped?: string; hint?: string }; auto_timeline?: { skipped?: string; hint?: string } };+ expect(result.auto_links?.skipped).toBe('remote');+ expect(result.auto_links?.hint).toBeDefined();+ expect(result.auto_links?.hint).toContain('NOT reconciled');+ expect(result.auto_timeline?.skipped).toBe('remote');+ expect(result.auto_timeline?.hint).toBeDefined();+ }, 120000);++ test('local write does not carry the remote skip marker', async () => {+ const result = (await putPage.handler(+ makeCtx({ remote: false }),+ { slug: 'notes/local-no-skip', content: CONTENT },+ )) as { auto_links?: { skipped?: string } };+ expect(result.auto_links?.skipped).not.toBe('remote');+ }, 120000);+});diff --git a/test/query-intent-config.test.ts b/test/query-intent-config.test.tsnew file mode 100644index 0000000000..c5b18f650e--- /dev/null+++ b/test/query-intent-config.test.ts@@ -0,0 +1,193 @@+/**+ * #4415 — query-intent classifier: per-brain pattern extensions.+ *+ * Every shipped bank is English-only `\b`-anchored regex, so on a+ * non-English brain `classifyQuery` fell to intent 'general' with recency+ * AND salience permanently 'off' — the ranking stages never executed at+ * all. Pins:+ *+ * 1. the unextended banks miss a Hebrew recency query (the bug — kept as+ * a documented baseline);+ * 2. `search.intent_patterns` config merges per-brain patterns OVER the+ * shipped banks (recency_on / strong_recency / salience_on / temporal+ * etc.) and the axes fire;+ * 3. bad config fail-opens per entry (unparseable JSON, unknown bank,+ * invalid regex) — shipped banks stay in force, errors are reported;+ * 4. classifyQueryWithBrainPatterns loads via engine.getConfig and+ * fail-opens on a throwing engine;+ * 5. the `search` op now carries the same explicit salience/recency+ * params `query` has (the per-call override surface — CLI --salience /+ * --recency come from the op contract).+ */+import { describe, test, expect, afterEach } from 'bun:test';+import {+ classifyQuery,+ classifyQueryWithBrainPatterns,+ applyIntentPatternConfig,+ clearIntentPatternConfigForTests,+ intentPatternFingerprint,+ loadEngineIntentPatterns,+ INTENT_PATTERN_BANKS,+} from '../src/core/search/query-intent.ts';+import { operations } from '../src/core/operations.ts';++// The issue's own repro sentence: "what's new recently with the car".+const HEBREW_RECENCY_QUERY = 'מה חדש לאחרונה עם הרכב';++afterEach(() => {+ clearIntentPatternConfigForTests();+});++describe('query-intent — shipped banks are English-only (#4415 baseline)', () => {+ test('Hebrew recency query: recency and salience never fire unextended', () => {+ const s = classifyQuery(HEBREW_RECENCY_QUERY);+ expect(s.intent).toBe('general');+ expect(s.suggestedRecency).toBe('off');+ expect(s.suggestedSalience).toBe('off');+ });+});++describe('applyIntentPatternConfig (#4415)', () => {+ test('recency_on extension fires the recency stage for a Hebrew query', () => {+ const errors = applyIntentPatternConfig(JSON.stringify({+ recency_on: ['לאחרונה', 'מה חדש'],+ }));+ expect(errors).toEqual([]);+ expect(classifyQuery(HEBREW_RECENCY_QUERY).suggestedRecency).toBe('on');+ });++ test('strong_recency + salience_on extensions drive both axes', () => {+ applyIntentPatternConfig(JSON.stringify({+ strong_recency: ['היום'],+ salience_on: ['מה קורה עם'],+ }));+ expect(classifyQuery('מה קורה עם הרכב היום').suggestedRecency).toBe('strong');+ expect(classifyQuery('מה קורה עם הרכב').suggestedSalience).toBe('on');+ });++ test('temporal extension routes intent (and its high-detail mapping)', () => {+ applyIntentPatternConfig(JSON.stringify({ temporal: ['לאחרונה'] }));+ const s = classifyQuery(HEBREW_RECENCY_QUERY);+ expect(s.intent).toBe('temporal');+ expect(s.suggestedDetail).toBe('high');+ });++ test('extensions only ADD: shipped English behavior is unchanged', () => {+ applyIntentPatternConfig(JSON.stringify({ recency_on: ['לאחרונה'] }));+ expect(classifyQuery("what's new recently with the car").suggestedRecency).toBe('on');+ expect(classifyQuery('who is alice-example').suggestedRecency).toBe('off'); // canonical stays off+ });++ test('clearing config restores the shipped-only banks', () => {+ applyIntentPatternConfig(JSON.stringify({ recency_on: ['לאחרונה'] }));+ expect(classifyQuery(HEBREW_RECENCY_QUERY).suggestedRecency).toBe('on');+ applyIntentPatternConfig(null);+ expect(classifyQuery(HEBREW_RECENCY_QUERY).suggestedRecency).toBe('off');+ });++ test('unparseable JSON fail-opens with an error and shipped banks intact', () => {+ const errors = applyIntentPatternConfig('{not json');+ expect(errors.length).toBe(1);+ expect(errors[0]).toContain('not valid JSON');+ expect(classifyQuery('what happened recently').suggestedRecency).toBe('on');+ });++ test('unknown bank and invalid regex are per-entry errors; valid entries still apply', () => {+ const errors = applyIntentPatternConfig(JSON.stringify({+ no_such_bank: ['x'],+ recency_on: ['לאחרונה', '(unclosed'],+ }));+ expect(errors.some((e) => e.includes("unknown pattern bank 'no_such_bank'"))).toBe(true);+ expect(errors.some((e) => e.includes('invalid regex'))).toBe(true);+ // The valid pattern in the same config still landed.+ expect(classifyQuery(HEBREW_RECENCY_QUERY).suggestedRecency).toBe('on');+ });++ test('non-object / non-array-bank shapes are rejected loudly', () => {+ expect(applyIntentPatternConfig(JSON.stringify(['not', 'an', 'object']))[0])+ .toContain('must be a JSON object');+ expect(applyIntentPatternConfig(JSON.stringify({ recency_on: 'not-an-array' }))[0])+ .toContain("must be an array");+ });++ test('every documented bank name is accepted', () => {+ const cfg = Object.fromEntries(INTENT_PATTERN_BANKS.map((b) => [b, ['בדיקה']]));+ expect(applyIntentPatternConfig(JSON.stringify(cfg))).toEqual([]);+ });+});++describe('classifyQueryWithBrainPatterns (#4415)', () => {+ test('loads search.intent_patterns via engine.getConfig', async () => {+ const engine = {+ getConfig: async (key: string) =>+ key === 'search.intent_patterns' ? JSON.stringify({ recency_on: ['לאחרונה'] }) : null,+ };+ const s = await classifyQueryWithBrainPatterns(engine, HEBREW_RECENCY_QUERY);+ expect(s.suggestedRecency).toBe('on');+ });++ test('a throwing engine fail-opens to the shipped banks', async () => {+ const engine = { getConfig: async () => { throw new Error('db down'); } };+ const s = await classifyQueryWithBrainPatterns(engine, HEBREW_RECENCY_QUERY);+ expect(s.suggestedRecency).toBe('off');+ expect((await classifyQueryWithBrainPatterns(engine, 'what happened recently')).suggestedRecency).toBe('on');+ });+});++describe('loadEngineIntentPatterns — per-engine cache (wave-g)', () => {+ const RAW = JSON.stringify({ recency_on: ['לאחרונה'] });++ test('two engines keep their own banks — no cross-brain contamination', async () => {+ const engineA = { getConfig: async () => RAW };+ const engineB = { getConfig: async () => null };+ expect((await classifyQueryWithBrainPatterns(engineA, HEBREW_RECENCY_QUERY)).suggestedRecency).toBe('on');+ expect((await classifyQueryWithBrainPatterns(engineB, HEBREW_RECENCY_QUERY)).suggestedRecency).toBe('off');+ // A's banks survive B's classify (pre-wave-g the process-global state+ // let the LAST engine's config win for every engine in the process).+ expect((await classifyQueryWithBrainPatterns(engineA, HEBREW_RECENCY_QUERY)).suggestedRecency).toBe('on');+ });++ test('engine.getConfig is TTL-cached — one read per window, not one per classify', async () => {+ let reads = 0;+ const engine = { getConfig: async () => { reads++; return RAW; } };+ await classifyQueryWithBrainPatterns(engine, HEBREW_RECENCY_QUERY);+ await classifyQueryWithBrainPatterns(engine, HEBREW_RECENCY_QUERY);+ await classifyQueryWithBrainPatterns(engine, HEBREW_RECENCY_QUERY);+ expect(reads).toBe(1);+ });++ test('fingerprint: none when unset; stable 12-hex when set; exposed on the state', async () => {+ expect(intentPatternFingerprint(null)).toBe('none');+ expect(intentPatternFingerprint(undefined)).toBe('none');+ expect(intentPatternFingerprint('')).toBe('none');+ expect(intentPatternFingerprint(RAW)).toMatch(/^[0-9a-f]{12}$/);+ expect(intentPatternFingerprint(RAW)).toBe(intentPatternFingerprint(RAW));+ const state = await loadEngineIntentPatterns({ getConfig: async () => RAW });+ expect(state.fingerprint).toBe(intentPatternFingerprint(RAW));+ expect(state.errors).toEqual([]);+ });++ test('a throwing engine fail-opens per engine and still stamps the TTL anchor', async () => {+ let reads = 0;+ const engine = { getConfig: async () => { reads++; throw new Error('db down'); } };+ const s1 = await loadEngineIntentPatterns(engine);+ expect(s1.fingerprint).toBe('none');+ // Within the TTL the down config plane is not hammered again.+ await loadEngineIntentPatterns(engine);+ expect(reads).toBe(1);+ });+});++describe('search op — explicit salience/recency params (#4415)', () => {+ const search = operations.find((o) => o.name === 'search')!;+ const query = operations.find((o) => o.name === 'query')!;++ test('search now carries the same salience/recency override params as query', () => {+ for (const op of [search, query]) {+ expect(op.params.salience).toBeDefined();+ expect(op.params.recency).toBeDefined();+ }+ expect(search.params.salience.enum).toEqual(['off', 'on', 'strong']);+ expect(search.params.recency.enum).toEqual(['off', 'on', 'strong']);+ });+});diff --git a/test/query-op-limit-mode-4356.serial.test.ts b/test/query-op-limit-mode-4356.serial.test.tsnew file mode 100644index 0000000000..472ead15ba--- /dev/null+++ b/test/query-op-limit-mode-4356.serial.test.ts@@ -0,0 +1,96 @@+/**+ * #4356 Site 1 — the `query` op's text/hybrid path (src/core/ops/search.ts)+ * was a hard `(p.limit as number) || 20`, independent of the resolved+ * search mode's `searchLimit` (10/25/50 for conservative/balanced/+ * tokenmax). Now `(p.limit as number) || undefined` — an omitted OR falsy+ * (`0`) `limit` lets hybridSearchCached's own mode-resolution apply instead+ * of being silently overridden to a flat 20.+ *+ * `0` is deliberately folded into "unset" here rather than forwarded as a+ * literal "return zero rows" request: `resolveSearchMode` (mode.ts) folds a+ * *forwarded* `opts.limit: 0` into `resolvedMode.searchLimit` itself (the+ * `perCall.searchLimit` pick treats 0 as a set value, not undefined), so a+ * bare hybridSearch/hybridSearchCached caller who passes `limit: 0` today+ * already gets zero rows end-to-end on both the miss and (after this PR's+ * Site 2 fix, see test/hybrid-cache-hit-limit-honors-mode.serial.test.ts)+ * the hit path. This op deliberately does NOT forward that 0 — matching+ * every other limit surface in this file (`search`'s own limit, the image-+ * similarity branch, `search_by_image`), none of which support a literal+ * empty-result request today. Introducing that capability only on this one+ * path would be a new, undocumented asymmetry — out of scope for a limit-+ * CONSISTENCY fix.+ *+ * Companion to #4356 Site 2 (see the sibling cache-hit test file). Fixing+ * both sites in the same PR is the point: shipping only this miss-path fix+ * would make the miss/hit inconsistency newly OBSERVABLE (previously both+ * were wrong at a flat 20, so they agreed) without resolving it — a+ * maintainer-lens review rejected exactly that partial shape when it shipped+ * split across two closed PRs (#4355, #4357).+ *+ * Driven through the REAL dispatch path (dispatchToolCall → query op+ * handler) with hybridSearchCached mocked, same pattern as+ * dispatch-response-meta.serial.test.ts.+ *+ * Serial: mock.module (isolation guard R2).+ */++import { describe, expect, mock, test } from 'bun:test';+import * as realHybrid from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';++let nextResults: unknown[] = [];+let capturedOpts: { limit?: number } | null = null;++// Mock BEFORE importing dispatch (operations.ts binds hybridSearchCached at+// import time; the spread keeps every other export live).+mock.module('../src/core/search/hybrid.ts', () => ({+ ...realHybrid,+ hybridSearchCached: async (+ _engine: unknown,+ _query: string,+ opts: { limit?: number; onMeta?: (m: unknown) => void },+ ) => {+ capturedOpts = opts;+ opts.onMeta?.({ vector_enabled: true, expansion_applied: false, detail_resolved: null });+ return nextResults;+ },+}));++const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');++const engineStub = {+ getConfig: async () => null,+ executeRaw: async () => [],+} as unknown as BrainEngine;++function callQuery(params: Record<string, unknown>) {+ return dispatchToolCall(engineStub, 'query', { query: 'who founded acme-example', ...params }, {+ remote: true,+ transport: 'http',+ sourceId: 'default',+ });+}++describe('query op — text-path limit no longer hard-floors to 20 (#4356 Site 1)', () => {+ test('caller omits `limit` → hybridSearchCached receives limit: undefined (mode bundle decides)', async () => {+ nextResults = [];+ capturedOpts = null;+ await callQuery({});+ expect(capturedOpts).not.toBeNull();+ expect(capturedOpts!.limit).toBeUndefined();+ });++ test('caller passes an explicit positive numeric `limit` → still wins', async () => {+ nextResults = [];+ capturedOpts = null;+ await callQuery({ limit: 7 });+ expect(capturedOpts!.limit).toBe(7);+ });++ test('caller passes `limit: 0` → op forwards undefined (0 is treated as unset, not as "return zero rows")', async () => {+ nextResults = [];+ capturedOpts = null;+ await callQuery({ limit: 0 });+ expect(capturedOpts!.limit).toBeUndefined();+ });+});diff --git a/test/resolve-ipc-binding.test.ts b/test/resolve-ipc-binding.test.tsnew file mode 100644index 0000000000..eb14845ccc--- /dev/null+++ b/test/resolve-ipc-binding.test.ts@@ -0,0 +1,93 @@+/**+ * test/resolve-ipc-binding.test.ts — #4474.+ *+ * `gbrain serve --http` never bound the resolve-IPC unix socket (the+ * listener lived inline in the stdio MCP path only), so on the exact+ * posture `gbrain bootstrap harness` targets, every wired lifecycle hook+ * degraded to `no_serve` forever — with no local recovery on PGLite (the+ * http serve owns the single-writer lock). The wiring now lives in the+ * shared `bindResolveIpcForServe` helper and BOTH transports call it.+ */++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 { bindResolveIpcForServe } from '../src/mcp/resolve-ipc-binding.ts';+import { resolveSocketPath } from '../src/core/context/resolve-ipc.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++const REPO_ROOT = join(import.meta.dir, '..');+const readSrc = (rel: string) => Bun.file(join(REPO_ROOT, rel));++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-ipc-bind-'));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe('bindResolveIpcForServe (#4474)', () => {+ it('binds the socket for a PGLite config and close() reaps it', async () => {+ const dataDir = join(tmp, 'db');+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(+ join(tmp, '.gbrain', 'config.json'),+ JSON.stringify({ engine: 'pglite', database_path: dataDir }),+ );+ await withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, async () => {+ // Bind-time never touches the engine (handlers close over it lazily),+ // so a stub is enough to prove the listener itself comes up.+ const binding = await bindResolveIpcForServe({} as unknown as BrainEngine, 'default');+ try {+ expect(binding.server).not.toBeNull();+ expect(binding.socketPath).toBe(resolveSocketPath(dataDir));+ expect(existsSync(binding.socketPath!)).toBe(true);+ } finally {+ binding.close();+ }+ expect(existsSync(resolveSocketPath(dataDir))).toBe(false);+ // close() is idempotent.+ binding.close();+ });+ });++ it('returns a null binding (not a throw) when the config has no keying material', async () => {+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));+ await withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined }, async () => {+ const binding = await bindResolveIpcForServe({} as unknown as BrainEngine, 'default');+ expect(binding.server).toBeNull();+ expect(binding.socketPath).toBeNull();+ binding.close(); // no-op, must not throw+ });+ });+});++describe('both serve transports bind through the shared helper (#4474)', () => {+ it('serve --http wires bindResolveIpcForServe with teardown', async () => {+ const src = await readSrc('src/commands/serve-http.ts').text();+ expect(src).toContain('bindResolveIpcForServe(');+ expect(src).toContain('ipcBinding.close()');+ });++ it('the stdio MCP path wires bindResolveIpcForServe with teardown', async () => {+ const src = await readSrc('src/mcp/server.ts').text();+ expect(src).toContain('bindResolveIpcForServe(');+ expect(src).toContain('ipcBinding.close()');+ });++ 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.+ const src = await readSrc('src/core/bootstrap/verify.ts').text();+ expect(src).toContain('const liveSocket = existsSync(socketPath)');+ expect(src).toMatch(/if \(!liveSocket\) \{/);+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 6da78d5df5..a739afafb2 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -922,6 +922,14 @@ const COLUMN_EXEMPTIONS = new Set<string>(['dream_verdicts.entities','dream_verdicts.model','dream_verdicts.triage_version',+ // #4482 (migration v141) — expected-limit stop counter. Same precedent as+ // query_cache.knobs_hash et al: extract_rollup_7d is migration-created+ // (v106, absent from PGLITE_SCHEMA_SQL), so no schema-blob forward+ // reference can exist; no index references the column; and both consumers+ // handle absence explicitly (the rollup writer retries the pre-v141+ // statement shape, doctor's extract_health falls back to a 0-column+ // query). Column-only, no bootstrap probe needed.+ 'extract_rollup_7d.expected_limit_count',]);test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {@@ -1050,7 +1058,10 @@ test('extractAlterAddColumnsFromSql handles representative migration SQL shapes'test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (guard symmetry with pglite-engine.ts)', async () => {const { readFileSync } = await import('fs');const { resolve: resolvePath } = await import('path');- const enginePath = resolvePath(process.cwd(), 'src/core/postgres-engine.ts');+ // #4477 peeled the Postgres forward-reference bootstrap out of the+ // postgres-engine.ts façade into its module dir; the guard follows the+ // block to its current home.+ const enginePath = resolvePath(process.cwd(), 'src/core/postgres-engine/forward-reference-bootstrap.ts');const engineSrc = readFileSync(enginePath, 'utf-8');const normalized = engineSrc.replace(/\s+/g, ' ');diff --git a/test/schema-cli-lint-extends.test.ts b/test/schema-cli-lint-extends.test.tsnew file mode 100644index 0000000000..ccf136640c--- /dev/null+++ b/test/schema-cli-lint-extends.test.ts@@ -0,0 +1,105 @@+// #4501 — `gbrain schema lint <name>` must lint the MERGED manifest+// (extends chain resolved), matching the no-name branch's loadActivePack+// path. Pre-fix, the named-pack branch linted the raw loadPackFromFile+// manifest, so a child pack referencing inherited parent types (e.g.+// `enrichable_types: [{type: person}]` with person declared in+// gbrain-base) failed lint with `enrichable_types_undeclared`.+//+// Hermetic subprocess tests, same pattern as test/schema-cli.test.ts.++import { describe, expect, test, beforeAll, afterAll } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const REPO_ROOT = join(import.meta.dir, '..');++let GBRAIN_HOME: string;++beforeAll(() => {+ GBRAIN_HOME = mkdtempSync(join(tmpdir(), 'gbrain-schema-lint-extends-'));+ // gbrainPath appends '.gbrain' to GBRAIN_HOME.+ const packsDir = join(GBRAIN_HOME, '.gbrain', 'schema-packs');++ // Child pack extending gbrain-base; references the INHERITED 'person'+ // page_type. Lint-clean only when the extends chain is resolved.+ mkdirSync(join(packsDir, 'lint-child'), { recursive: true });+ writeFileSync(join(packsDir, 'lint-child', 'pack.yaml'), [+ 'api_version: gbrain-schema-pack-v1',+ 'name: lint-child',+ 'version: 1.0.0',+ 'extends: gbrain-base',+ 'enrichable_types:',+ ' - type: person',+ '',+ ].join('\n'), 'utf-8');++ // Child pack whose parent doesn't exist — lint must fall back to the+ // raw child manifest with a warning instead of hard-failing.+ mkdirSync(join(packsDir, 'lint-orphan'), { recursive: true });+ writeFileSync(join(packsDir, 'lint-orphan', 'pack.yaml'), [+ 'api_version: gbrain-schema-pack-v1',+ 'name: lint-orphan',+ 'version: 1.0.0',+ 'extends: no-such-parent-pack',+ 'page_types:',+ ' - name: widget',+ ' primitive: entity',+ '',+ ].join('\n'), 'utf-8');+});++afterAll(() => {+ rmSync(GBRAIN_HOME, { recursive: true, force: true });+});++function gbrain(args: string[]): { stdout: string; stderr: string; code: number } {+ const result = spawnSync('bun', ['run', 'src/cli.ts', ...args], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ env: {+ ...process.env,+ GBRAIN_DATABASE_URL: '',+ DATABASE_URL: '',+ GBRAIN_HOME,+ },+ });+ return {+ stdout: result.stdout ?? '',+ stderr: result.stderr ?? '',+ code: result.status ?? -1,+ };+}++describe('gbrain schema lint <name> resolves the extends chain (#4501)', () => {+ test('child pack referencing inherited parent type lints clean', () => {+ const r = gbrain(['schema', 'lint', 'lint-child']);+ expect(r.stdout + r.stderr).not.toContain('enrichable_types_undeclared');+ expect(r.code).toBe(0);+ expect(r.stdout).toContain('lint clean');+ }, 30000);++ test('--json reports the child pack name against the merged manifest', () => {+ const r = gbrain(['schema', 'lint', 'lint-child', '--json']);+ expect(r.code).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.pack).toBe('lint-child');+ expect(parsed.ok).toBe(true);+ }, 30000);++ test('missing parent falls back to raw child manifest with a stderr warning', () => {+ const r = gbrain(['schema', 'lint', 'lint-orphan']);+ // The raw child itself is lint-clean, so the command succeeds …+ expect(r.code).toBe(0);+ // … but the unresolvable chain is surfaced on stderr.+ expect(r.stderr).toContain('could not resolve extends chain');+ expect(r.stderr).toContain('lint-orphan');+ }, 30000);++ test('unknown pack name still errors', () => {+ const r = gbrain(['schema', 'lint', 'no-such-pack-anywhere']);+ expect(r.code).toBe(1);+ expect(r.stderr).toContain('Pack not found');+ }, 30000);+});diff --git a/test/schema-lint-extends-resolution.test.ts b/test/schema-lint-extends-resolution.test.tsnew file mode 100644index 0000000000..6f2d2febe2--- /dev/null+++ b/test/schema-lint-extends-resolution.test.ts@@ -0,0 +1,90 @@+// `gbrain schema lint <name>` must lint the RESOLVED manifest.+//+// The named-pack branch of runLintCmd loads the manifest with loadPackFromFile,+// which returns the raw child with its `extends` chain unresolved. Every lint+// rule tests against `manifest.page_types`, so an extending pack that maps+// `frontmatter_links` onto an INHERITED type (e.g. `note` from gbrain-base-v2)+// is reported as referencing an undeclared page type -- a type the resolved+// pack plainly declares.+//+// The no-name branch does not have this bug: it goes through loadActivePack,+// which walks the chain.++import { describe, expect, test, beforeEach, afterEach } from 'bun:test';+import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runSchema } from '../src/commands/schema.ts';+import { withEnv } from './helpers/with-env.ts';++/** Extends gbrain-base-v2 and declares NO page types of its own. */+const CHILD_PACK = `api_version: gbrain-schema-pack-v1+name: extends-child-test+version: 1.0.0+description: extending pack that reuses inherited base-v2 types+extends: gbrain-base-v2+page_types: []+link_types:+ - name: part_of+ inverse: contains+frontmatter_links:+ - page_type: note+ fields: [part_of]+ link_type: part_of+`;++let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-lint-extends-'));+ const dir = join(home, '.gbrain', 'schema-packs', 'extends-child-test');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'pack.yaml'), CHILD_PACK);+});++afterEach(() => {+ rmSync(home, { recursive: true, force: true });+});++describe('schema lint resolves the extends chain for a named pack', () => {+ test('an extending pack that reuses inherited types lints clean', async () => {+ const lines: string[] = [];+ const origLog = console.log;+ const origErr = console.error;+ const origExit = process.exit;+ let exitCode = 0;+ console.log = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };+ console.error = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };+ (process as unknown as { exit: (c?: number) => void }).exit = ((c?: number) => {+ exitCode = c ?? 0;+ throw new Error('__exit__');+ }) as never;++ try {+ await withEnv({ GBRAIN_HOME: home }, () => runSchema(['lint', 'extends-child-test', '--json']));+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ console.log = origLog;+ console.error = origErr;+ (process as unknown as { exit: typeof origExit }).exit = origExit;+ }++ const out = lines.join('\n');+ const start = out.indexOf('{');+ expect(start, `expected JSON lint output, got:\n${out}`).toBeGreaterThanOrEqual(0);+ const report = JSON.parse(out.slice(start));++ const undeclared = (report.errors ?? []).filter(+ (e: { rule: string }) =>+ e.rule === 'frontmatter_links_undeclared_page_type' ||+ e.rule === 'frontmatter_links_undeclared_link_type',+ );++ expect(+ undeclared,+ `inherited base-v2 types must not be reported undeclared: ${JSON.stringify(undeclared)}`,+ ).toEqual([]);+ expect(exitCode).toBe(0);+ });+});diff --git a/test/schema-verify.test.ts b/test/schema-verify.test.tsindex 2934e19ae2..083a984747 100644--- a/test/schema-verify.test.ts+++ b/test/schema-verify.test.ts@@ -1,5 +1,29 @@import { describe, it, expect } from 'bun:test';-import { parseExpectedColumns, simplifyColumnDef } from '../src/core/schema-verify.ts';+import { parseExpectedColumns, simplifyColumnDef, detectMissingColumns } from '../src/core/schema-verify.ts';+import type { BrainEngine } from '../src/core/engine.ts';++/**+ * Minimal executeRaw-only stub: routes on which information_schema view the+ * SQL targets (schema-verify.ts's two queries never touch anything else).+ * Not a shared test helper — narrow enough that a one-off stub here is+ * clearer than adding a new file for a single caller (gbrain#4421).+ */+function stubEngine(opts: {+ tables: string[];+ columns: Array<{ table_name: string; column_name: string }>;+}): BrainEngine {+ return {+ executeRaw: async (sql: string) => {+ if (sql.includes('information_schema.tables')) {+ return opts.tables.map(table_name => ({ table_name })) as unknown[];+ }+ if (sql.includes('information_schema.columns')) {+ return opts.columns as unknown[];+ }+ throw new Error(`stubEngine.executeRaw: unexpected query: ${sql}`);+ },+ } as unknown as BrainEngine;+}describe('parseExpectedColumns', () => {it('extracts columns from all major tables', () => {@@ -54,6 +78,40 @@ describe('parseExpectedColumns', () => {});});+describe('detectMissingColumns', () => {+ it('reports missing when the ledger-expected column is absent from the live table (gbrain#4421 repro)', async () => {+ // Positive control: content_chunks exists (so it's in-scope) but its+ // actual columns don't include embedded_text_hash — the exact drift+ // that made `gbrain doctor` report schema_version=ok while `gbrain+ // import` failed on every file with "column ... does not exist".+ const engine = stubEngine({+ tables: ['content_chunks'],+ columns: [{ table_name: 'content_chunks', column_name: 'chunk_text' }],+ });+ const result = await detectMissingColumns(engine);+ expect(result.missing).toContainEqual({ table: 'content_chunks', column: 'embedded_text_hash' });+ });++ it('reports no missing columns when the live table matches every expected column (negative control)', async () => {+ const expected = parseExpectedColumns();+ const contentChunksCols = expected.filter(c => c.table === 'content_chunks');+ const engine = stubEngine({+ tables: ['content_chunks'],+ columns: contentChunksCols.map(c => ({ table_name: 'content_chunks', column_name: c.column })),+ });+ const result = await detectMissingColumns(engine);+ expect(result.missing).toEqual([]);+ expect(result.checked).toBe(contentChunksCols.length);+ });++ it('skips tables that do not exist yet (fresh-install / not-yet-migrated tables are not false positives)', async () => {+ const engine = stubEngine({ tables: [], columns: [] });+ const result = await detectMissingColumns(engine);+ expect(result.checked).toBe(0);+ expect(result.missing).toEqual([]);+ });+});+describe('simplifyColumnDef', () => {it('strips REFERENCES clauses', () => {const result = simplifyColumnDef(diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex 91b7a53c3b..8235667add 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -89,9 +89,12 @@ describe('alias_resolved boost stage', () => {});describe('KNOBS_HASH_VERSION', () => {- it('is 23 (20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352)', () => {+ it('is 25 (20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {// mw2: 21→22 result-stamp/injection epoch (#1663 #3995 #3783 #4220).// #4352 follow-up: 22→23 private-visibility posture fold (xp=).- expect(KNOBS_HASH_VERSION).toBe(23);+ // #4358 residual: 23→24 negative-offset cache-skip gap.+ // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).+ expect(KNOBS_HASH_VERSION).toBe(26);});});diff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex b37582d43b..2d548a1238 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -60,6 +60,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: 4000,expansion: false,searchLimit: 10,@@ -94,6 +95,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: 12000,expansion: false,searchLimit: 25,@@ -127,6 +129,7 @@ describe('SEARCH_MODES + MODE_BUNDLES canonical shape', () => {cache_similarity_threshold: 0.92,cache_ttl_seconds: 3600,intentWeighting: true,+ keywordOrFallback: true,tokenBudget: undefined,expansion: true,searchLimit: 50,@@ -442,7 +445,12 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// semantic cache for every remote MCP caller (excludePrivate=true is// their default). A private-included write must not serve a// private-excluding lookup and vice versa.- expect(KNOBS_HASH_VERSION).toBe(23);+ // #4358 residual: bumped 23→24 — negative-offset requests could+ // read/write the same cache row an offset=0 request shares+ // (pagedRequest previously skipped only offset>0).+ // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).+ expect(KNOBS_HASH_VERSION).toBe(26);});test('#3515: detail set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -464,7 +472,10 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// 19→20 pool floor (#3002); 20→21 recency fallback re-key (#895).// mw2: 21→22 result-stamp/injection epoch (#1663 #3995 #3783 #4220).// #4352 follow-up: 22→23 private-visibility posture fold (xp=).- expect(KNOBS_HASH_VERSION).toBe(23);+ // #4358 residual: 23→24 negative-offset cache-skip gap.+ // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).+ expect(KNOBS_HASH_VERSION).toBe(26);});test('#4352 follow-up: excludePrivate true vs false produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -484,6 +495,40 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {expect(unset).toBe(including);});+ test('#4415 (wave-g): salience/recency modes produce DIFFERENT hashes (cache contamination prevention)', () => {+ // A salience:'strong' write (post-fusion reordered result set) must+ // never serve a salience:'off' lookup of the same query, and vice+ // versa — same contamination class as det= (v=16). #4415 extended the+ // per-call overrides to the default MCP `search` surface.+ const knobs = resolveSearchMode({ mode: 'balanced' });+ const off = knobsHash(knobs, { salience: 'off', recency: 'off' });+ const on = knobsHash(knobs, { salience: 'on', recency: 'off' });+ const strong = knobsHash(knobs, { salience: 'strong', recency: 'off' });+ const recOn = knobsHash(knobs, { salience: 'off', recency: 'on' });+ const recStrong = knobsHash(knobs, { salience: 'off', recency: 'strong' });+ const unset = knobsHash(knobs);+ expect(new Set([off, on, strong, recOn, recStrong]).size).toBe(5);+ // Undefined falls back to 'off' (the classifier default for unmatched+ // queries) so legacy callers that don't thread the modes hash stably.+ expect(unset).toBe(off);+ });++ test('#4415 (wave-g): intent-pattern config fingerprint produces DIFFERENT hashes (config-edit invalidation)', () => {+ // search.intent_patterns changes classification (intent weights + auto+ // salience/recency/detail) and thus results; folding the fingerprint+ // makes a config edit invalidate immediately instead of serving+ // old-classification rows for the rest of the cache TTL.+ const knobs = resolveSearchMode({ mode: 'balanced' });+ const none = knobsHash(knobs, { intentPatterns: 'none' });+ const cfgA = knobsHash(knobs, { intentPatterns: 'aaaaaaaaaaaa' });+ const cfgB = knobsHash(knobs, { intentPatterns: 'bbbbbbbbbbbb' });+ const unset = knobsHash(knobs);+ expect(none).not.toBe(cfgA);+ expect(cfgA).not.toBe(cfgB);+ // Undefined falls back to 'none' so pattern-less brains hash stably.+ expect(unset).toBe(none);+ });+test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {// Without this, a no-floor write would be served to a floor-enabled read// — direct ranking-correctness leak. Same bug class CDX-4 closed in v0.32.3@@ -646,8 +691,8 @@ describe('v0.40.4 — graph_signals knob', () => {});describe('v0.42.3.0 — autocut knobs', () => {- test('KNOBS_HASH_VERSION is 23 (21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352)', () => {- expect(KNOBS_HASH_VERSION).toBe(23);+ test('KNOBS_HASH_VERSION is 26 (21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 negative-offset cache-skip gap #4358 residual; 24→25 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {+ expect(KNOBS_HASH_VERSION).toBe(26);});test('bundle defaults: conservative off, balanced/tokenmax on @0.20', () => {@@ -835,3 +880,25 @@ describe('v0.46.15 — retrieval-wave knobs (evidence_cosine_floor + autocut_minexpect(relabeled).toBe(base);});});++describe('keywordOrFallback knob (v=25)', () => {+ test('config override turns the fallback off; bundle default stays on', () => {+ expect(resolveSearchMode({ mode: 'balanced' }).keywordOrFallback).toBe(true);+ const off = resolveSearchMode({ mode: 'balanced', overrides: { keywordOrFallback: false } });+ expect(off.keywordOrFallback).toBe(false);+ });++ test('loadOverridesFromConfig parses search.keywordOrFallback', () => {+ expect(loadOverridesFromConfig({ 'search.keywordOrFallback': 'false' }).keywordOrFallback).toBe(false);+ expect(loadOverridesFromConfig({ 'search.keywordOrFallback': '0' }).keywordOrFallback).toBe(false);+ expect(loadOverridesFromConfig({ 'search.keywordOrFallback': '1' }).keywordOrFallback).toBe(true);+ expect(loadOverridesFromConfig({ 'search.keywordOrFallback': 'true' }).keywordOrFallback).toBe(true);+ expect(loadOverridesFromConfig({}).keywordOrFallback).toBeUndefined();+ });++ test('kof participates in knobsHash — a fallback-on row cannot serve a fallback-off lookup', () => {+ const on = knobsHash(resolveSearchMode({ mode: 'balanced' }));+ const off = knobsHash(resolveSearchMode({ mode: 'balanced', overrides: { keywordOrFallback: false } }));+ expect(on).not.toBe(off);+ });+});diff --git a/test/search-op-source-id.test.ts b/test/search-op-source-id.test.tsnew file mode 100644index 0000000000..292762a249--- /dev/null+++ b/test/search-op-source-id.test.ts@@ -0,0 +1,110 @@+/**+ * #4398 — the `search` op must accept `source_id` like `query` does.+ *+ * MCP clients passed `source_id` to `search`, got a "unknown parameter+ * ignored" warning, and silently read UNSCOPED results — while the sibling+ * `query` op honored the same parameter via federatedSearchScope /+ * resolveRequestedScope. Pins:+ *+ * 1. the param exists on the op contract (no more unknown-param warning);+ * 2. an explicit source_id scopes results to that source (both trust+ * classes), on the hybrid path AND the keyword-only opt-out path;+ * 3. a remote caller with a federated grant gets permission_denied for an+ * out-of-grant source_id (the single-resolver posture);+ * 4. '__all__' spans the brain for trusted local callers.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';++let engine: PGLiteEngine;++const search = operations.find((o) => o.name === 'search')!;++function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine as unknown as OperationContext['engine'],+ config: {} as OperationContext['config'],+ logger: console as unknown as OperationContext['logger'],+ dryRun: false,+ remote: false,+ sourceId: 'default',+ ...overrides,+ } as OperationContext;+}++async function slugsFor(ctx: OperationContext, params: Record<string, unknown>): Promise<string[]> {+ const results = (await search.handler(ctx, { query: 'zephyrblatt', ...params })) as Array<{ slug: string }>;+ return results.map((r) => r.slug);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('wiki', 'Wiki') ON CONFLICT (id) DO NOTHING`,+ );+ // The same distinctive token in both sources so scoping is observable.+ // putPage alone leaves content_chunks empty (chunking is the import/embed+ // lane's job), so seed chunks too — the keyword FTS arm reads them.+ for (const [slug, sourceId] of [+ ['notes/zeph-default', 'default'],+ ['notes/zeph-wiki', 'wiki'],+ ] as const) {+ await engine.putPage(slug, {+ type: 'note', title: `Zephyrblatt ${sourceId}`, compiled_truth: `the zephyrblatt lives in ${sourceId}`,+ }, { sourceId });+ await engine.upsertChunks(slug, [+ { chunk_index: 0, chunk_text: `the zephyrblatt lives in ${sourceId}`, chunk_source: 'compiled_truth' },+ ], { sourceId });+ }+});++afterAll(async () => {+ await engine.disconnect();+});++describe('search op — source_id param (#4398)', () => {+ test('the op contract carries source_id (parity with query)', () => {+ expect(search.params.source_id).toBeDefined();+ const query = operations.find((o) => o.name === 'query')!;+ expect(query.params.source_id).toBeDefined();+ });++ test('explicit source_id scopes the hybrid path to that source', async () => {+ const slugs = await slugsFor(ctxOf(), { source_id: 'wiki' });+ expect(slugs).toContain('notes/zeph-wiki');+ expect(slugs).not.toContain('notes/zeph-default');+ });++ test("'__all__' spans every source for trusted local callers", async () => {+ const slugs = await slugsFor(ctxOf(), { source_id: '__all__' });+ expect(slugs).toContain('notes/zeph-wiki');+ expect(slugs).toContain('notes/zeph-default');+ });++ test('remote caller with a federated grant: out-of-grant source_id is permission_denied', async () => {+ const ctx = ctxOf({+ remote: true,+ auth: {+ token: 'gbrain_at_test',+ clientId: 'gbrain_cl_test',+ scopes: ['read'],+ allowedSources: ['default'],+ } as OperationContext['auth'],+ });+ await expect(slugsFor(ctx, { source_id: 'wiki' })).rejects.toThrow(OperationError);+ });++ test('keyword-only opt-out path honors source_id too', async () => {+ await engine.setConfig('search.mcp_keyword_only', 'true');+ try {+ const slugs = await slugsFor(ctxOf(), { source_id: 'wiki' });+ expect(slugs).toContain('notes/zeph-wiki');+ expect(slugs).not.toContain('notes/zeph-default');+ } finally {+ await engine.setConfig('search.mcp_keyword_only', 'false');+ }+ });+});diff --git a/test/search-snippet-cap.test.ts b/test/search-snippet-cap.test.tsindex af1793ec72..e9cf2da3e1 100644--- a/test/search-snippet-cap.test.ts+++ b/test/search-snippet-cap.test.ts@@ -39,11 +39,13 @@ beforeAll(async () => {{ chunk_index: 0, chunk_text: LONG_TEXT, chunk_source: 'compiled_truth' },]);await engine.setConfig('search.mcp_keyword_only', 'true');-}, 60_000);+ // 240s: PGLite cold init (135 migrations) regularly exceeds 60s on a+ // loaded CI box / parallel local agents; the old cap flaked this suite.+}, 240_000);afterAll(async () => {if (engine) await engine.disconnect();-}, 60_000);+}, 240_000);describe('applySnippetCap helper (#3800)', () => {test('truncates chunk_text only and appends the get_page marker', () => {diff --git a/test/search/exact-lookup.test.ts b/test/search/exact-lookup.test.tsindex db6904e3f5..aff0733985 100644--- a/test/search/exact-lookup.test.ts+++ b/test/search/exact-lookup.test.ts@@ -116,6 +116,53 @@ describe('structuralExactLookup (#1663)', () => {});});+describe('#4480 — shape-filter gating (type/types/excludeSlugs)', () => {+ test('excludeSlugs drops a slug-probe hit the caller filtered out', async () => {+ await engine.putPage('people/alice-example', {+ type: 'person', title: 'Alice Example', compiled_truth: 'Founder.',+ });+ const ungated = await structuralExactLookup(engine, 'people/alice-example', { sourceId: 'default' });+ expect(ungated.length).toBe(1);+ const gated = await structuralExactLookup(engine, 'people/alice-example', {+ sourceId: 'default',+ excludeSlugs: ['people/alice-example'],+ });+ expect(gated.length).toBe(0);+ });++ test('types gate drops hits whose type is outside the filter; matching type passes', async () => {+ await engine.putPage('notes/widget-brief', {+ type: 'note', title: 'Widget Brief', compiled_truth: 'A note.',+ });+ const asPerson = await structuralExactLookup(engine, 'notes/widget-brief', {+ sourceId: 'default',+ types: ['person', 'company'],+ });+ expect(asPerson.length).toBe(0);+ const asNote = await structuralExactLookup(engine, 'notes/widget-brief', {+ sourceId: 'default',+ types: ['note'],+ });+ expect(asNote.length).toBe(1);+ });++ test('scalar type gate applies to title-arm hits too', async () => {+ const titleArm = [res('projects/mingtang', 0.4, { title: 'The Mingtang', type: 'note' })];+ const gated = await structuralExactLookup(engine, 'the mingtang', {+ sourceId: 'default',+ titleCandidates: titleArm,+ type: 'person',+ });+ expect(gated.length).toBe(0);+ const passed = await structuralExactLookup(engine, 'the mingtang', {+ sourceId: 'default',+ titleCandidates: titleArm,+ type: 'note',+ });+ expect(passed.length).toBe(1);+ });+});+describe('applyExactLookupTier (#1663)', () => {test('injects an absent identity match at rank-1 above scored organics', async () => {await engine.putPage('people/alice-example', {diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex d474342e95..0694e27281 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -44,7 +44,7 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 23 (…; 20→21 recency fallback re-key #895; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352)', () => {+ test('version is 24 (…; 21→22 result-stamp/injection epoch #1663 #3995 #3783 #4220; 22→23 excludePrivate posture fold #4352; 23→24 keywordOrFallback knob kof=; 25→26 salience/recency + intent_patterns fold #4415)', () => {// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).@@ -83,7 +83,10 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {// #3995 relational page-1 slot, #3783 keyword_hit, #4220 status).// #4352 follow-up: 22→23 excludePrivate posture fold (xp=) — replaces// the wholesale cache skip that disabled caching for remote callers.- expect(KNOBS_HASH_VERSION).toBe(23);+ // #4358 residual: 23→24 negative-offset cache-skip gap.+ // 24→25: kof= (keyword AND→OR fallback knob) joins the key.+ // 25→26: sal=/rec=/ipat= — salience/recency + intent_patterns fold (#4415).+ expect(KNOBS_HASH_VERSION).toBe(26);});test('hash is 16 hex chars regardless of reranker config', () => {diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex 9ec6543025..9afcfc6ab8 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -246,6 +246,39 @@ describe('searchKeyword — D2 AND→OR fallback', () => {});});+describe('hybridSearch — search.keywordOrFallback knob (v=15)', () => {+ // Title deliberately shares no token with the query so the D1 title arm+ // can't rescue the page — isolates the keyword arm's OR retry, which is+ // what the knob gates.+ async function seedLabJournal(): Promise<void> {+ await engine.putPage('notes/lab-journal', {+ type: 'note',+ title: 'Lab Journal',+ compiled_truth: 'quantum lattice harmonics resonance experiments',+ });+ await engine.upsertChunks('notes/lab-journal', [+ {+ chunk_index: 0,+ chunk_text: 'quantum lattice harmonics resonance experiments',+ chunk_source: 'compiled_truth',+ },+ ]);+ }++ test('bundle default (on): the OR retry rescues through the full hybrid path', async () => {+ await seedLabJournal();+ const results = await hybridSearch(engine, 'quantum lattice harmonics zzzmissingtoken', { limit: 10 });+ expect(results.map(r => r.slug)).toContain('notes/lab-journal');+ });++ test('search.keywordOrFallback=false suppresses the OR retry end-to-end', async () => {+ await seedLabJournal();+ await engine.setConfig('search.keywordOrFallback', 'false');+ const results = await hybridSearch(engine, 'quantum lattice harmonics zzzmissingtoken', { limit: 10 });+ expect(results.map(r => r.slug)).not.toContain('notes/lab-journal');+ });+});+describe('buildOrFallbackWebsearchQuery — pure', () => {test('joins tokens with OR', () => {expect(buildOrFallbackWebsearchQuery('alpha beta')).toBe('alpha OR beta');diff --git a/test/serve-stdin-eof-drain.test.ts b/test/serve-stdin-eof-drain.test.tsnew file mode 100644index 0000000000..7449667833--- /dev/null+++ b/test/serve-stdin-eof-drain.test.ts@@ -0,0 +1,192 @@+/**+ * #4409 — stdio serve must not exit on stdin EOF while requests are in flight.+ *+ * A one-shot MCP client writes its frames and closes stdin immediately; the+ * SDK parses every frame during 'data' (handler start is a microtask), so at+ * 'end' time a tools/call can be in flight with no response written. Pre-fix,+ * 'end' → beginShutdown immediately and the response was silently dropped+ * (the codex-plugin door went red on exactly this shape from v0.46.24.0).+ *+ * Also pins the complementary boot-cost fix: serve.ts must not import+ * serve-sync-runner statically (the #4362 static import defeated the+ * GBRAIN_SERVE_SYNC_IPC=0 kill switch and put the runner's module graph on+ * every boot).+ */++import { describe, test, expect, afterEach } from 'bun:test';+import { EventEmitter } from 'events';+import { readFileSync } from 'fs';+import { join } from 'path';+import { runServe, type ServeOptions } from '../src/commands/serve';+import { stdioRpcsInFlightCount, trackStdioRpc } from '../src/mcp/server';+import type { BrainEngine } from '../src/core/engine';+import { _resetStdoutRedirectForTests } from '../src/core/console-prefix';++/* eslint-disable no-console */+const __realConsoleLog = console.log;+const __realConsoleInfo = console.info;+const __realConsoleDebug = console.debug;+afterEach(() => {+ console.log = __realConsoleLog;+ console.info = __realConsoleInfo;+ console.debug = __realConsoleDebug;+ _resetStdoutRedirectForTests();+});+/* eslint-enable no-console */++class StubEngine implements Partial<BrainEngine> {+ disconnectCalls = 0;+ disconnect = async (): Promise<void> => {+ this.disconnectCalls += 1;+ };+}++interface Harness {+ engine: StubEngine;+ stdin: EventEmitter & { isTTY?: boolean };+ logs: string[];+ exited: Promise<number>;+ opts: ServeOptions;+ signals: { emit: (s: string) => void };+}++function makeHarness(extra: Partial<ServeOptions> = {}): Harness {+ const engine = new StubEngine();+ const stdin = new EventEmitter() as EventEmitter & { isTTY?: boolean };+ const logs: string[] = [];+ const handlers = new Map<string, Array<() => void>>();+ const signals = {+ on(signal: string, handler: () => void) {+ const list = handlers.get(signal) ?? [];+ list.push(handler);+ handlers.set(signal, list);+ return signals;+ },+ emit(signal: string) {+ for (const h of handlers.get(signal) ?? []) h();+ },+ };++ let resolveExit!: (code: number) => void;+ const exited = new Promise<number>((r) => { resolveExit = r; });+ let exitCalled = false;++ const opts: ServeOptions = {+ stdin: stdin as any,+ signals: signals as any,+ exit: (code?: number) => {+ if (exitCalled) return;+ exitCalled = true;+ resolveExit(code ?? 0);+ },+ log: (msg: string) => { logs.push(msg); },+ startMcpServer: async () => {},+ getParentPid: () => 1, // skip the parent watchdog+ setInterval: () => 0,+ clearInterval: () => {},+ probeWatchdog: () => false,+ sweepEnabled: false,+ ...extra,+ };++ return { engine, stdin, logs, exited, opts, signals };+}++describe('stdin-EOF drain (#4409)', () => {+ test('EOF with in-flight RPCs waits for them before exiting', async () => {+ let pending = 2;+ const h = makeHarness({ pendingRpcs: () => pending, eofDrainMs: 5_000 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);++ h.stdin.emit('end');+ // Let the drain start and observe the pending requests.+ await new Promise((r) => setTimeout(r, 60));+ expect(h.engine.disconnectCalls).toBe(0); // still draining+ expect(h.logs.some((l) => l.includes('draining before exit'))).toBe(true);++ pending = 0; // responses settled+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.engine.disconnectCalls).toBe(1);+ expect(h.logs.some((l) => l.includes('graceful exit (stdin-end)'))).toBe(true);+ }, 30000);++ test('EOF with no in-flight RPCs exits promptly (idle-server behavior unchanged)', async () => {+ const h = makeHarness({ pendingRpcs: () => 0, eofDrainMs: 5_000 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);+ h.stdin.emit('end');+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.engine.disconnectCalls).toBe(1);+ expect(h.logs.some((l) => l.includes('draining before exit'))).toBe(false);+ }, 30000);++ test('the drain is bounded: a wedged handler cannot pin the process', async () => {+ const h = makeHarness({ pendingRpcs: () => 1, eofDrainMs: 150 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);+ h.stdin.emit('end');+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.engine.disconnectCalls).toBe(1);+ }, 30000);++ test('eofDrainMs=0 restores immediate shutdown', async () => {+ const h = makeHarness({ pendingRpcs: () => 99, eofDrainMs: 0 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);+ h.stdin.emit('end');+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.logs.some((l) => l.includes('draining before exit'))).toBe(false);+ }, 30000);++ test('a signal during the drain still shuts down immediately', async () => {+ const h = makeHarness({ pendingRpcs: () => 1, eofDrainMs: 60_000 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);+ h.stdin.emit('end');+ await new Promise((r) => setTimeout(r, 30));+ h.signals.emit('SIGTERM');+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.logs.some((l) => l.includes('graceful exit (SIGTERM)'))).toBe(true);+ }, 30000);++ test('stdin close takes the same drain path', async () => {+ const h = makeHarness({ pendingRpcs: () => 0, eofDrainMs: 5_000 });+ await runServe(h.engine as unknown as BrainEngine, [], h.opts);+ h.stdin.emit('close');+ const code = await h.exited;+ expect(code).toBe(0);+ expect(h.logs.some((l) => l.includes('graceful exit (stdin-close)'))).toBe(true);+ }, 30000);+});++describe('in-flight RPC counter (#4409)', () => {+ test('trackStdioRpc counts entry/exit including throws', async () => {+ expect(stdioRpcsInFlightCount()).toBe(0);+ let release!: () => void;+ const gate = new Promise<void>((r) => { release = r; });+ const inFlight = trackStdioRpc(async () => { await gate; return 'ok'; });+ await new Promise((r) => setTimeout(r, 0));+ expect(stdioRpcsInFlightCount()).toBe(1);+ release();+ expect(await inFlight).toBe('ok');+ expect(stdioRpcsInFlightCount()).toBe(0);++ await expect(trackStdioRpc(async () => { throw new Error('boom'); })).rejects.toThrow('boom');+ expect(stdioRpcsInFlightCount()).toBe(0);+ });+});++describe('serve-sync-runner stays off the boot path (#4409)', () => {+ test('serve.ts has no static import of serve-sync-runner', () => {+ // test-reads-source-ok: structural module-graph guard — a static import+ // is invisible at runtime once loaded; only the source text can prove+ // the runner stays off the serve boot path (#4409).+ const src = readFileSync(join(import.meta.dir, '../src/commands/serve.ts'), 'utf8');+ // A static `import { x } from '.../serve-sync-runner.ts'` puts the runner+ // module graph on every serve boot and defeats GBRAIN_SERVE_SYNC_IPC=0.+ // Type-only imports are erased at compile time and stay allowed.+ const staticImport = /^import\s+(?!type\b)[^;]*serve-sync-runner/m;+ expect(staticImport.test(src)).toBe(false);+ });+});diff --git a/test/skill-trigger-index.test.ts b/test/skill-trigger-index.test.tsindex af66f3274d..2f23385ccd 100644--- a/test/skill-trigger-index.test.ts+++ b/test/skill-trigger-index.test.ts@@ -9,7 +9,7 @@*/import { afterAll, beforeEach, describe, expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import {@@ -114,6 +114,34 @@ bodyexpect(entries).toEqual([]);});+ test('symlinked skill directory (shared skills store) → frontmatter entries still appear', () => {+ // Regression: readdirSync's Dirent.isDirectory() reflects the dirent's+ // own type (DT_LNK on macOS/Linux for a symlink) and does NOT resolve+ // the link target, so a skill dir symlinked in from a shared store+ // (e.g. `~/.agents/skills/<name>` linked into `skills/<name>`) was+ // silently skipped and its triggers never registered.+ const skillsDir = makeSkillsDir();+ const storeDir = mkdtempSync(join(tmpdir(), 'skill-trigger-index-store-'));+ TEMPDIRS.push(storeDir);+ const realSkillDir = join(storeDir, 'shared-skill');+ mkdirSync(realSkillDir, { recursive: true });+ writeFileSync(+ join(realSkillDir, 'SKILL.md'),+ skillWithTriggers('shared-skill', ['do the shared thing']),+ );+ symlinkSync(realSkillDir, join(skillsDir, 'shared-skill'), 'dir');++ const entries = loadSkillTriggerIndex(skillsDir);+ expect(entries).toHaveLength(1);+ expect(entries[0]).toEqual({+ trigger: 'do the shared thing',+ skillPath: 'skills/shared-skill/SKILL.md',+ isGStack: false,+ section: FRONTMATTER_SECTION,+ source: 'frontmatter',+ });+ });+test('skill with empty triggers: array → not registered', () => {const skillsDir = makeSkillsDir();writeSkill(skillsDir, 'empty', `---diff --git a/test/soft-delete-link-visibility.test.ts b/test/soft-delete-link-visibility.test.tsindex a5c168f41d..643ca2bc92 100644--- a/test/soft-delete-link-visibility.test.ts+++ b/test/soft-delete-link-visibility.test.ts@@ -139,3 +139,50 @@ describe('#3754 traversePaths hides soft-deleted pages', () => {expect(await engine.traversePaths('hop-a', { direction: 'out', depth: 3 })).toEqual([]);});});++describe('#3754 traverseGraph hides soft-deleted pages', () => {+ test('deleted neighbor disappears from nodes AND from the displayed links array', async () => {+ await seedPair();+ const before = await engine.traverseGraph('bl-a', 1);+ expect(before.map((n) => n.slug).sort()).toEqual(['bl-a', 'bl-b']);++ await engine.softDeletePage('bl-b', { sourceId: 'default' });+ const after = await engine.traverseGraph('bl-a', 1);+ expect(after.map((n) => n.slug)).toEqual(['bl-a']);+ // The aggregation subquery must not display an edge to the deleted page.+ expect(after[0].links.map((l) => l.to_slug)).toEqual([]);+ });++ test('a soft-deleted seed anchors nothing', async () => {+ await seedPair();+ await engine.softDeletePage('bl-a', { sourceId: 'default' });+ expect(await engine.traverseGraph('bl-a', 1)).toEqual([]);+ });++ test('a soft-deleted relay breaks multi-hop traversal (recursive step filter)', async () => {+ await engine.putPage('tg-a', { type: 'note', title: 'a', compiled_truth: 'x', timeline: '' });+ await engine.putPage('tg-mid', { type: 'note', title: 'mid', compiled_truth: 'x', timeline: '' });+ await engine.putPage('tg-c', { type: 'note', title: 'c', compiled_truth: 'x', timeline: '' });+ await engine.addLink('tg-a', 'tg-mid', '', 'wikilink');+ await engine.addLink('tg-mid', 'tg-c', '', 'wikilink');+ expect((await engine.traverseGraph('tg-a', 3)).map((n) => n.slug).sort()).toEqual(['tg-a', 'tg-c', 'tg-mid']);++ await engine.softDeletePage('tg-mid', { sourceId: 'default' });+ expect((await engine.traverseGraph('tg-a', 3)).map((n) => n.slug)).toEqual(['tg-a']);+ });++ test('the frontier-capped recursive variant filters too', async () => {+ await seedPair();+ await engine.softDeletePage('bl-b', { sourceId: 'default' });+ const nodes = await engine.traverseGraph('bl-a', 1, { frontierCap: 10 });+ expect(nodes.map((n) => n.slug)).toEqual(['bl-a']);+ });++ test('restore brings the node back', async () => {+ await seedPair();+ await engine.softDeletePage('bl-b', { sourceId: 'default' });+ await engine.restorePage('bl-b', { sourceId: 'default' });+ const nodes = await engine.traverseGraph('bl-a', 1);+ expect(nodes.map((n) => n.slug).sort()).toEqual(['bl-a', 'bl-b']);+ });+});diff --git a/test/source-resolver-tier4-parallel-realpath.test.ts b/test/source-resolver-tier4-parallel-realpath.test.tsnew file mode 100644index 0000000000..8ea437b0d6--- /dev/null+++ b/test/source-resolver-tier4-parallel-realpath.test.ts@@ -0,0 +1,144 @@+/**+ * #4091-class root-cause fix — tier-4 registered-source realpath resolution+ * must overlap I/O across sources, not serialize behind each other.+ *+ * Discovered while investigating why `gbrain takes-list` (and any other+ * CLI command reaching tier 4 of source resolution with no --source/env/+ * dotfile match) took ~40s on a brain with 9 registered sources whose+ * local_path all lived under a directory macOS's on-access security scan+ * makes slow to `realpath()`: each source added its own multi-second delay+ * because the original code called the SYNCHRONOUS `realpathSync` in a+ * plain `for` loop — `Promise.all`-wrapping a sync call does not+ * parallelize it, since a sync call blocks the whole event loop for its+ * full duration regardless of how many promises surround it. The fix+ * switches to `fs.promises.realpath` (`realpathOrResolveAsync`) and+ * resolves every source's path via a single `Promise.all`, so tier 4's+ * cost is bounded by the SLOWEST single source, not their sum.+ *+ * This test can't reproduce the real macOS-scan slowness portably/in CI,+ * so it spies on `realpathOrResolveAsync` to prove concurrency directly:+ * every mocked call increments an in-flight counter and hangs on its own+ * releaser (never auto-resolving), so the test can assert ALL N+1 calls+ * (cwd + every registered source) were issued before ANY of them settled.+ * This is deterministic — no wall-clock/timing assertion, so it can't flake+ * under CI load, timer throttling, or coverage instrumentation (the wall+ * clock version of this test hit exactly that risk in review).+ */++import { describe, test, expect, spyOn } from 'bun:test';+import { resolveSourceId, resolveSourceWithTier } from '../src/core/source-resolver.ts';+import * as pathConfine from '../src/core/path-confine.ts';+import type { BrainEngine } from '../src/core/engine.ts';++function makeStub(paths: Array<{ id: string; local_path: string }>): BrainEngine {+ return {+ kind: 'pglite',+ executeRaw: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {+ // Matches both query shapes of listRegisteredLocalPathSources (#3880):+ // the archived-column query and its pre-v34 column-less fallback. Rows+ // carry no `archived` key here → treated as active.+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) {+ return paths as unknown as T[];+ }+ // #4368-added archival gate: resolveSourceId/resolveSourceWithTier call+ // assertSourceExists on the tier-4 match before returning it. This test+ // only exercises resolution ordering/concurrency, not archival — every+ // id the resolver checks is treated as active.+ if (sql.includes('SELECT id FROM sources WHERE id = $1 AND archived = false')) {+ return [{ id: params?.[0] }] as unknown as T[];+ }+ return [] as unknown as T[];+ },+ getConfig: async () => null,+ } as unknown as BrainEngine;+}++describe('resolveSourceWithTier — tier 4 realpath resolution is parallel, not serial (#4091-class)', () => {+ test('all N+1 realpath calls (cwd + every registered source) are in flight together before any settles', async () => {+ const N = 6;+ const paths = Array.from({ length: N }, (_, i) => ({ id: `src${i}`, local_path: `/slow/path${i}` }));+ const engine = makeStub(paths);++ let inFlight = 0;+ let maxInFlight = 0;+ const releasers: Array<() => void> = [];++ const spy = spyOn(pathConfine, 'realpathOrResolveAsync').mockImplementation((p: string) => {+ inFlight++;+ maxInFlight = Math.max(maxInFlight, inFlight);+ return new Promise<string>((resolvePromise) => {+ releasers.push(() => {+ inFlight--;+ resolvePromise(p);+ });+ });+ });++ try {+ const resultPromise = resolveSourceWithTier(engine, null, '/slow/path3/nested');+ // Let the microtask queue drain so every Promise.all-issued call has+ // started (but none have been released yet — they all hang on their+ // own releaser above). If the tier-4 loop were serial, only the FIRST+ // call would be in flight at this point; the rest would not even have+ // been issued yet, since each `await` blocks starting the next one.+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();++ // cwd's own realpath + one per registered source, all outstanding at once.+ expect(maxInFlight).toBe(N + 1);+ expect(inFlight).toBe(N + 1); // none settled yet either++ // Release everything and let resolution complete.+ for (const release of releasers) release();+ const result = await resultPromise;++ expect(result.source_id).toBe('src3');+ expect(result.tier).toBe('local_path');+ } finally {+ spy.mockRestore();+ }+ });++ test('control: same scenario without the spy still resolves correctly (regression guard)', async () => {+ const paths = [+ { id: 'gstack', local_path: '/work/gstack' },+ { id: 'other', local_path: '/work/other' },+ ];+ const engine = makeStub(paths);+ const result = await resolveSourceWithTier(engine, null, '/work/gstack/src');+ expect(result.source_id).toBe('gstack');+ expect(result.tier).toBe('local_path');+ });++ test('resolveSourceId (the other tier-4 caller) shares the same fix — parity check', async () => {+ // resolveSourceWithTier is covered directly above; resolveSourceId shares+ // resolveRegisteredPathMatch under the hood, so this pins that the+ // refactor didn't let the two entry points drift.+ const paths = [+ { id: 'gstack', local_path: '/work/gstack' },+ { id: 'other', local_path: '/work/other' },+ ];+ const engine = makeStub(paths);+ const id = await resolveSourceId(engine, null, '/work/gstack/src');+ expect(id).toBe('gstack');+ });++ test('a genuine tie (two sources sharing the identical resolved path) keeps the pre-refactor first-row-wins order', async () => {+ // The registered-sources query has no ORDER BY, so a real tie (both+ // candidates resolve to the SAME length AND the same matched prefix) is+ // broken by array/database row order — unchanged by the Promise.all+ // refactor (Promise.all preserves input order). Two DIFFERENT local_path+ // strings of equal length are not a tie unless both are prefixes of cwd;+ // the simplest genuine tie is a duplicate registration (same path twice),+ // which is a real edge case (an operator registering a source twice, or+ // two ids sharing a symlinked vault).+ const paths = [+ { id: 'first', local_path: '/work/same' },+ { id: 'second', local_path: '/work/same' },+ ];+ const engine = makeStub(paths);+ const result = await resolveSourceWithTier(engine, null, '/work/same/nested');+ expect(result.source_id).toBe('first');+ });+});diff --git a/test/sources-abs-path-3696.test.ts b/test/sources-abs-path-3696.test.tsindex 0f3fab1470..fbc60f7c16 100644--- a/test/sources-abs-path-3696.test.ts+++ b/test/sources-abs-path-3696.test.ts@@ -97,3 +97,80 @@ describe('#3696 autopilot dispatch skips relative local_path', () => {expect(relativeLocalPathSkipWarning('ok-src', '/abs/vault')).toBeNull();});});++describe('#3696 residual — a relative --clone-dir is absolutized before use', () => {+ test('relative clone-dir participates in the overlap check as an absolute path', async () => {+ // The overlap check runs BEFORE any clone work and compares finalPath+ // (localPath OR cloneDir) against every registered local_path — all+ // absolute. A verbatim relative clone-dir can never match, so the same+ // phantom-path class #3696 fixed for --path survived through --clone-dir.+ // Observable seam: register a source at the ABSOLUTE parent, then add a+ // URL source whose RELATIVE clone-dir resolves inside it. Fixed code+ // throws overlapping_path before touching git/network; unfixed code+ // sails past the check (and would try to clone).+ const parent = mkdtempSync(join(tmpdir(), 'gbrain-3696-clone-'));+ const origCwd = process.cwd();+ try {+ // chdir FIRST, then derive both paths from the same (realpathed) cwd —+ // macOS chdir realpaths /var → /private/var, so a join(parent, ...)+ // expectation would compare the unrealpathed spelling (same trap the+ // relative --path test above documents).+ process.chdir(parent);+ await addSource(engine, { id: 'abs-parent-3696', localPath: resolve('clones'), force: true });+ const relCloneDir = 'clones/rel-3696';+ expect(isAbsolute(relCloneDir)).toBe(false);++ let err: unknown;+ try {+ await addSource(engine, {+ id: 'rel-clone-3696',+ remoteUrl: 'https://invalid.invalid/repo.git',+ cloneDir: relCloneDir,+ });+ } catch (e) { err = e; }+ expect(String((err as { code?: string } | undefined)?.code ?? err)).toBe('overlapping_path');+ } finally {+ process.chdir(origCwd);+ rmSync(parent, { recursive: true, force: true });+ }+ });+});++describe('#3696 residual — a relative --kind github --dir is absolutized before use', () => {+ test('relative github.dir is resolved against cwd before INSERT', async () => {+ // Path C (--kind github) never went through the cloneDir/localPath+ // absolutization above — `finalPath = opts.github.dir` was used verbatim+ // for both mkdirSync and the local_path INSERT, so the same phantom-path+ // class #3696 fixed for --path/--clone-dir survived through --dir.+ const parent = mkdtempSync(join(tmpdir(), 'gbrain-3696-ghdir-'));+ const origCwd = process.cwd();+ try {+ process.chdir(parent);+ const relDir = 'clones/gh-rel-3696';+ expect(isAbsolute(relDir)).toBe(false);+ const expected = resolve(relDir);++ await addSource(engine, {+ id: 'gh-rel-3696',+ github: {+ tokenEnv: 'GH_TOKEN',+ handle: '',+ scope: 'auto',+ repos: [],+ dir: relDir,+ involvement: true,+ },+ });++ const rows = await engine.executeRaw<{ local_path: string }>(+ `SELECT local_path FROM sources WHERE id = 'gh-rel-3696'`,+ );+ expect(rows.length).toBe(1);+ expect(isAbsolute(rows[0]!.local_path)).toBe(true);+ expect(rows[0]!.local_path).toBe(expected);+ } finally {+ process.chdir(origCwd);+ rmSync(parent, { recursive: true, force: true });+ }+ });+});diff --git a/test/sources-list-scope.test.ts b/test/sources-list-scope.test.tsnew file mode 100644index 0000000000..f651eefa86--- /dev/null+++ b/test/sources-list-scope.test.ts@@ -0,0 +1,121 @@+/**+ * #4433 — sources_list must honor the caller's federated source grant.+ *+ * The handler dropped ctx on the floor and listSources had no scope param,+ * so every OAuth client — including one whose grant deliberately excludes a+ * source — received the full source table (id, name, page_count of the+ * excluded source). Same class as the #3242 wave that scoped+ * get_page/search/list_pages/resolve_slugs, with existence-of-a-source as+ * the leak instead of pages.+ *+ * The filter mirrors EXACTLY the boundary resolveRequestedScope enforces on+ * explicit per-call `source_id` reads — a non-empty ctx.auth.allowedSources+ * array — so the listing shows precisely the sources the caller could read.+ * Pins (row-filter, not field redaction):+ *+ * 1. trusted local CLI stays UNSCOPED (sources management surface);+ * 2. a remote federated grant sees only its granted rows;+ * 3. a remote scalar default-source floor (no allowedSources) keeps the+ * full listing — that caller may read any source by naming it, so+ * hiding rows would break discovery without adding any boundary;+ * 4. an empty allowedSources array behaves like no grant (same as+ * resolveRequestedScope's `allowed.length > 0` gate).+ */+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 = operations.find((o) => o.name === 'sources_list')!;++function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine as unknown as OperationContext['engine'],+ config: {} as OperationContext['config'],+ logger: console as unknown as OperationContext['logger'],+ dryRun: false,+ remote: true,+ ...overrides,+ } as OperationContext;+}++function authOf(allowedSources?: string[]): OperationContext['auth'] {+ return {+ token: 'gbrain_at_test',+ clientId: 'gbrain_cl_test',+ clientName: 'token-b',+ scopes: ['read'],+ ...(allowedSources ? { allowedSources } : {}),+ } as OperationContext['auth'];+}++async function listedIds(ctx: OperationContext): Promise<string[]> {+ const res = (await op.handler(ctx, {})) as { sources: Array<{ id: string }> };+ return res.sources.map((s) => s.id);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw(+ `INSERT INTO sources (id, name) VALUES ('wiki', 'Wiki'), ('restricted', 'Restricted')+ ON CONFLICT (id) DO NOTHING`,+ );+});++afterAll(async () => {+ await engine.disconnect();+});++describe('sources_list — caller source grant (#4433)', () => {+ test('trusted local CLI stays unscoped (sees every source)', async () => {+ const ids = await listedIds(ctxOf({ remote: false, sourceId: 'default' }));+ expect(ids).toContain('default');+ expect(ids).toContain('wiki');+ expect(ids).toContain('restricted');+ });++ test('remote federated grant is row-filtered (excluded source invisible)', async () => {+ const ids = await listedIds(ctxOf({+ remote: true,+ sourceId: 'default',+ auth: authOf(['default', 'wiki']),+ }));+ expect(ids.sort()).toEqual(['default', 'wiki']);+ expect(ids).not.toContain('restricted');+ });++ test('include_archived stays inside the grant too', async () => {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, archived) VALUES ('archived-restricted', 'AR', true)+ ON CONFLICT (id) DO NOTHING`,+ );+ const res = (await op.handler(+ ctxOf({ remote: true, sourceId: 'default', auth: authOf(['default', 'wiki']) }),+ { include_archived: true },+ )) as { sources: Array<{ id: string }> };+ const ids = res.sources.map((s) => s.id);+ expect(ids).not.toContain('archived-restricted');+ expect(ids).not.toContain('restricted');+ });++ test('remote scalar default-source floor (no grant) keeps the full listing', async () => {+ // This caller may read any source by explicit source_id — the listing+ // must match its actual read reach, not invent a boundary reads lack.+ const ids = await listedIds(ctxOf({ remote: true, sourceId: 'default', auth: authOf() }));+ expect(ids).toContain('default');+ expect(ids).toContain('wiki');+ expect(ids).toContain('restricted');+ });++ test('empty allowedSources behaves like no grant (resolveRequestedScope parity)', async () => {+ const ids = await listedIds(ctxOf({+ remote: true,+ sourceId: 'default',+ auth: authOf([]),+ }));+ expect(ids).toContain('restricted');+ });+});diff --git a/test/subagent-v1-v2-shim.test.ts b/test/subagent-v1-v2-shim.test.tsindex 9740cf98ef..370d11fa84 100644--- a/test/subagent-v1-v2-shim.test.ts+++ b/test/subagent-v1-v2-shim.test.ts@@ -169,6 +169,27 @@ describe('adaptContentBlocksToChatBlocks (D5 — v1 Anthropic → v2 ChatBlock sexpect(out.length).toBe(1);expect(out[0].toolCallId).toBe('ok');});++ // A crash-replayed reasoning-model tool loop must keep the OpenAI+ // Responses API reasoning-item id (providerMetadata.openai.itemId) across+ // resume the same way a tool-call's providerMetadata already does —+ // otherwise the resumed job's next turn 400s the same way an un-echoed+ // live turn does (see gateway-chat.test.ts's reasoning-item round trip+ // suite for the live-turn half of this fix).+ it('passes a reasoning block through with providerMetadata intact', () => {+ const sig = { openai: { itemId: 'rs_abc123', reasoningEncryptedContent: 'opaque-blob' } };+ const blocks = [{ type: 'reasoning', text: 'weighing the tradeoff...', providerMetadata: sig }];+ expect(adaptContentBlocksToChatBlocks(blocks)).toEqual(blocks);+ });++ it('drops a reasoning block with a non-string text field (defensive)', () => {+ const blocks = [+ { type: 'reasoning', text: null },+ { type: 'text', text: 'ok' },+ ];+ const out = adaptContentBlocksToChatBlocks(blocks) as any[];+ expect(out).toEqual([{ type: 'text', text: 'ok' }]);+ });});describe('loadPriorToolsV2 (D5 — synthesizes stable keys for v1 rows)', () => {diff --git a/test/sync-break-lock-source-resolution.test.ts b/test/sync-break-lock-source-resolution.test.tsnew file mode 100644index 0000000000..3192d45b42--- /dev/null+++ b/test/sync-break-lock-source-resolution.test.ts@@ -0,0 +1,115 @@+/**+ * #4412 — `sync --break-lock` / `--force-break-lock` must break the lock of+ * the source the sync itself would use.+ *+ * Pre-fix, the break-lock branch hardcoded `sourceArg ?? 'default'` while the+ * sync path resolves through the full ambient chain (--source > GBRAIN_SOURCE+ * > dotfile > cwd > sole-non-default). Under GBRAIN_SOURCE=workspace (the+ * serve-delegation e2e harness, and any real install that scopes via env),+ * `gbrain sync --force-break-lock` inspected `gbrain-sync:default` — absent —+ * printed "nothing to break", exit 0, and left the DEAD holder's row on+ * `gbrain-sync:workspace`. The follow-up sync then refused for the 60s+ * takeover grace: exactly the Pin 4 failure in+ * test/e2e/sync-delegation-under-serve.serial.test.ts:263.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, rmSync } from 'fs';+import { join } from 'path';+import { hostname, tmpdir } from 'os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { runSync } from '../src/commands/sync.ts';+import { addSource } from '../src/core/sources-ops.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;++class ExitSentinel extends Error {+ constructor(public readonly code: number) {+ super(`process.exit(${code})`);+ this.name = 'ExitSentinel';+ }+}++/** Run `runSync` with process.exit trapped; returns the exit code it requested. */+async function runSyncTrapped(args: string[], env: Record<string, string>): Promise<number> {+ const savedExit = process.exit;+ (process as unknown as { exit: (code?: number) => never }).exit = ((code?: number) => {+ throw new ExitSentinel(code ?? 0);+ }) as never;+ try {+ return await withEnv(env, async () => {+ await runSync(engine, args);+ return 0; // returned without exiting+ });+ } catch (e) {+ if (e instanceof ExitSentinel) return e.code;+ throw e;+ } finally {+ (process as unknown as { exit: typeof savedExit }).exit = savedExit;+ }+}++async function insertDeadLock(lockId: string): Promise<void> {+ // pid 999999 is above macOS/Linux default pid ranges — provably dead+ // (kill → ESRCH). Fresh timestamps model a just-SIGKILLed holder.+ await engine.executeRaw(+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)+ VALUES ($1, $2, $3, NOW(), NOW() + interval '30 minutes', NOW())+ ON CONFLICT (id) DO NOTHING`,+ [lockId, 999999, hostname()],+ );+}++async function lockRows(): Promise<string[]> {+ const rows = await engine.executeRaw<{ id: string }>(+ `SELECT id FROM gbrain_cycle_locks ORDER BY id`,+ );+ return rows.map(r => r.id);+}++let srcDir: string;++beforeAll(async () => {+ srcDir = mkdtempSync(join(tmpdir(), 'gb-4412-src-'));+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await resetPgliteState(engine);+ await addSource(engine, { id: 'workspace', localPath: srcDir, force: true });+}, 240_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+ if (srcDir) rmSync(srcDir, { recursive: true, force: true });+}, 60_000);++describe('#4412 break-lock source resolution', () => {+ test('--force-break-lock under GBRAIN_SOURCE breaks THAT source\'s lock, not default', async () => {+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks`);+ await insertDeadLock('gbrain-sync:workspace');++ const code = await runSyncTrapped(+ ['--force-break-lock', '--yes'],+ { GBRAIN_SOURCE: 'workspace' },+ );+ expect(code).toBe(0);+ // Pre-fix: the row survived (the child inspected gbrain-sync:default).+ expect(await lockRows()).not.toContain('gbrain-sync:workspace');+ }, 60_000);++ test('an explicit --source still wins over the ambient chain', async () => {+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks`);+ await insertDeadLock('gbrain-sync:default');+ await insertDeadLock('gbrain-sync:workspace');++ const code = await runSyncTrapped(+ ['--force-break-lock', '--yes', '--source', 'default'],+ { GBRAIN_SOURCE: 'workspace' },+ );+ expect(code).toBe(0);+ const rows = await lockRows();+ expect(rows).not.toContain('gbrain-sync:default');+ expect(rows).toContain('gbrain-sync:workspace');+ }, 60_000);+});diff --git a/test/sync-cost-gate.serial.test.ts b/test/sync-cost-gate.serial.test.tsindex 1371fd01f7..68c16d4fda 100644--- a/test/sync-cost-gate.serial.test.ts+++ b/test/sync-cost-gate.serial.test.ts@@ -5,23 +5,29 @@* in test/sync-cost-preview.test.ts. THIS file pins the end-to-end wiring in* runSync's --all AND single-source paths:*- * R-1 (headline): deferred-embed sync --all, non-TTY, with backlog →- * emits gate:'deferred_notice' and NEVER exit 2.- * R-2 (v0.42.42.0, #2139): inline sync --all (--serial), non-TTY, above floor- * → AUTO-DEFERS (exit 0, gate:'auto_deferred_embeds') and enqueues an- * embed-backfill job. The exit-2 wedge is gone.+ * R-1 (headline): PGLite's serial fallback is inline, never a fictional+ * deferred-to-worker path.+ * R-2 (v0.42.42.0, #2139): PGLite sync --all, non-TTY, above floor+ * → imports without wedging and reports an explicit manual drain;+ * no undrainable embed-backfill row is written.* R-3: chunker drift → full-tree CEILING estimate, auto-defers (not exit 2).* + posture tokenmax, off-switch, format split (#1784/D3A), single-source gate.** Serial-quarantined: stubs process.exit + console.log (process-global).*/import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';+import { existsSync, mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';import { execSync } from 'child_process';import { tmpdir } from 'os';import { join } from 'path';+import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runSources } from '../src/commands/sources.ts';+import { partitionMissingPathSources } from '../src/commands/sync.ts';+import {+ resolveSyncAllEmbedPlan,+ resolveSyncEmbedBackfill,+} from '../src/core/sync-embed-backfill.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { CHUNKER_VERSION } from '../src/core/chunkers/code.ts';@@ -37,12 +43,15 @@ function stubOfflineEmbed(): void {let engine: PGLiteEngine;let repoPath: string;+let repoPathTwo: string;let headSha: string;+let schemaVersion: string;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ schemaVersion = (await engine.getConfig('version')) ?? '140';}, 60_000);afterAll(async () => {@@ -51,6 +60,7 @@ afterAll(async () => {beforeEach(async () => {await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);// Configure the gateway with a dummy key so the pre-gate embedding-creds// preflight passes (diagnoseEmbedding reads gateway configure-time state,// not live env). The gate runs before any real embed call, so no network@@ -71,16 +81,31 @@ beforeEach(async () => {);execSync('git add -A && git commit -m initial', { cwd: repoPath, stdio: 'pipe' });headSha = execSync('git rev-parse HEAD', { cwd: repoPath, stdio: 'pipe' }).toString().trim();++ repoPathTwo = mkdtempSync(join(tmpdir(), 'gbrain-costgate-two-'));+ execSync('git init', { cwd: repoPathTwo, stdio: 'pipe' });+ execSync('git config user.email "[email protected]"', { cwd: repoPathTwo, stdio: 'pipe' });+ execSync('git config user.name "T"', { cwd: repoPathTwo, stdio: 'pipe' });+ mkdirSync(join(repoPathTwo, 'topics'), { recursive: true });+ writeFileSync(+ join(repoPathTwo, 'topics/bar.md'),+ ['---', 'type: concept', 'title: Bar', '---', '', 'second source content to estimate.'].join('\n'),+ );+ execSync('git add -A && git commit -m initial', { cwd: repoPathTwo, stdio: 'pipe' });});afterEach(() => {__setEmbedTransportForTests(null);resetGateway();if (repoPath) rmSync(repoPath, { recursive: true, force: true });+ if (repoPathTwo) rmSync(repoPathTwo, { recursive: true, force: true });});/** Run runSync(args) with process.exit + console.log captured. */-async function runSyncCaptured(args: string[]): Promise<{ exitCode: number | undefined; stdout: string }> {+async function runSyncCaptured(+ args: string[],+ targetEngine: BrainEngine = engine,+): Promise<{ exitCode: number | undefined; stdout: string }> {const { runSync } = await import('../src/commands/sync.ts');const origExit = process.exit;const origLog = console.log.bind(console);@@ -94,7 +119,7 @@ async function runSyncCaptured(args: string[]): Promise<{ exitCode: number | undthrow new Error('__exit__');}) as typeof process.exit;try {- await runSync(engine, args);+ await runSync(targetEngine, args);} catch (e) {if ((e as Error).message !== '__exit__') throw e;} finally {@@ -104,12 +129,289 @@ async function runSyncCaptured(args: string[]): Promise<{ exitCode: number | undreturn { exitCode, stdout: out.join('\n') };}+function jsonLines(stdout: string): Array<Record<string, unknown>> {+ return stdout+ .split('\n')+ .filter((line) => line.trim().startsWith('{'))+ .map((line) => JSON.parse(line) as Record<string, unknown>);+}++async function expectNoEmbedBackfillRow(): Promise<void> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'embed-backfill'`,+ );+ expect(Number(rows[0]?.n ?? 0)).toBe(0);+}++function asWorkerBacked(target: PGLiteEngine): BrainEngine {+ const sql = async (strings: TemplateStringsArray, ...values: unknown[]) => {+ let statement = strings[0] ?? '';+ for (let i = 0; i < values.length; i++) {+ statement += `$${i + 1}${strings[i + 1] ?? ''}`;+ }+ const db = (target as unknown as {+ db: { query: (text: string, params: unknown[]) => Promise<{ rows: unknown[] }> };+ }).db;+ return (await db.query(statement, values)).rows;+ };+ return new Proxy(target, {+ get(inner, prop) {+ if (prop === 'kind') return 'postgres';+ if (prop === 'sql') return sql;+ const value = Reflect.get(inner, prop, inner);+ return typeof value === 'function' ? value.bind(inner) : value;+ },+ }) as unknown as BrainEngine;+}++function commitLargeIncrementalDrop(): void {+ for (let i = 0; i < 101; i++) {+ writeFileSync(+ join(repoPath, `topics/large-${i}.md`),+ ['---', 'type: concept', `title: Large ${i}`, '---', '', `large incremental page ${i}`].join('\n'),+ );+ }+ execSync('git add -A && git commit -m "large incremental drop"', { cwd: repoPath, stdio: 'pipe' });+}+describe('v0.41.31 — sync --all cost gate wiring', () => {- test('R-1: deferred sync --all (non-TTY) emits deferred_notice and never exit 2', async () => {+ test('worker-backed v2 with one runnable source still defers and queues backfill', async () => {+ const workerBackedEngine = asWorkerBacked(engine);+ await runSources(workerBackedEngine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );++ const [source] = await engine.executeRaw<{+ id: string;+ local_path: string | null;+ config: Record<string, unknown>;+ last_commit: string | null;+ chunker_version: string | null;+ }>(+ `SELECT id, local_path, config, last_commit, chunker_version FROM sources WHERE id = 'vault'`,+ );+ const repoTwoHead = execSync('git rev-parse HEAD', { cwd: repoPathTwo, stdio: 'pipe' }).toString().trim();+ const candidates = [+ source,+ {+ id: 'disabled', local_path: repoPathTwo, config: { syncEnabled: false },+ last_commit: repoTwoHead, chunker_version: String(CHUNKER_VERSION),+ },+ {+ id: 'missing', local_path: join(repoPath, 'definitely-missing'), config: {},+ last_commit: null, chunker_version: String(CHUNKER_VERSION),+ },+ ];+ const active = candidates.filter((candidate) => candidate.config.syncEnabled !== false);+ const filtered = partitionMissingPathSources(active, existsSync);+ expect(filtered.runnable.map((candidate) => candidate.id)).toEqual(['vault']);+ expect(filtered.missing.map((candidate) => candidate.id)).toEqual(['missing']);+ const plan = await resolveSyncAllEmbedPlan(workerBackedEngine, filtered.runnable, {+ v2Enabled: true,+ serialFlag: false,+ noEmbed: false,+ noAutoEmbed: false,+ dryRun: false,+ jsonOut: true,+ yesFlag: false,+ full: false,+ includeGitignored: false,+ });++ expect(plan).toMatchObject({+ stop: false,+ deferEligible: true,+ fanOutEligible: false,+ effectiveNoEmbed: true,+ shouldBackfill: true,+ });+ const outcome = await resolveSyncEmbedBackfill(workerBackedEngine, 'vault', {+ reason: 'sync_all',+ autoSubmitDisabled: false,+ });+ expect(outcome.status).toBe('queued');+ const rows = await engine.executeRaw<{ name: string; status: string }>(+ `SELECT name, status FROM minion_jobs WHERE name = 'embed-backfill'`,+ );+ expect(rows).toEqual([{ name: 'embed-backfill', status: 'waiting' }]);+ }, 60_000);++ test('worker-backed v2 serial large incremental deferral still queues backfill', async () => {+ const workerBackedEngine = asWorkerBacked(engine);+ await runSources(workerBackedEngine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.setConfig('sync.federated_v2', 'true');+ await engine.setConfig('sync.cost_gate_min_usd', '1000');+ commitLargeIncrementalDrop();++ const { exitCode, stdout } = await runSyncCaptured(+ ['--all', '--serial', '--json', '--no-pull'],+ workerBackedEngine,+ );++ expect(exitCode).not.toBe(2);+ expect(stdout).toContain('"gate":"below_floor"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));+ expect(final).toBeDefined();+ expect(final!.sources).toEqual([+ expect.objectContaining({+ source_id: 'vault',+ sync_status: 'synced',+ added: 101,+ embedded: 0,+ embed_backfill: expect.objectContaining({ status: 'queued' }),+ }),+ ]);+ const rows = await engine.executeRaw<{ name: string; status: string }>(+ `SELECT name, status FROM minion_jobs WHERE name = 'embed-backfill' ORDER BY id`,+ );+ expect(rows).toEqual([{ name: 'embed-backfill', status: 'waiting' }]);+ }, 120_000);++ test('worker-backed v2 serial large incremental no-auto reports manual drain without a row', async () => {+ const workerBackedEngine = asWorkerBacked(engine);+ await runSources(workerBackedEngine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.setConfig('sync.federated_v2', 'true');+ await engine.setConfig('sync.cost_gate_min_usd', '1000');+ commitLargeIncrementalDrop();++ const { exitCode, stdout } = await runSyncCaptured(+ ['--all', '--serial', '--no-auto-embed', '--json', '--no-pull'],+ workerBackedEngine,+ );++ expect(exitCode).not.toBe(2);+ expect(stdout).toContain('"gate":"below_floor"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));+ expect(final).toBeDefined();+ expect(final!.sources).toEqual([+ expect.objectContaining({+ source_id: 'vault',+ sync_status: 'synced',+ added: 101,+ embedded: 0,+ embed_backfill: {+ status: 'manual_drain_required',+ reason: 'auto_submit_disabled',+ command: 'gbrain embed --stale --source vault',+ },+ }),+ ]);+ await expectNoEmbedBackfillRow();+ }, 120_000);++ test('worker-backed v2-off serial large incremental deferral preserves pre-v2 no-backfill behavior', async () => {+ const workerBackedEngine = asWorkerBacked(engine);+ await runSources(workerBackedEngine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.setConfig('sync.federated_v2', 'false');+ await engine.setConfig('sync.cost_gate_min_usd', '1000');+ commitLargeIncrementalDrop();++ const { exitCode, stdout } = await runSyncCaptured(+ ['--all', '--serial', '--json', '--no-pull'],+ workerBackedEngine,+ );++ expect(exitCode).not.toBe(2);+ expect(stdout).toContain('"gate":"below_floor"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));+ expect(final).toBeDefined();+ const source = (final!.sources as Array<Record<string, unknown>>)[0];+ expect(source).toMatchObject({+ source_id: 'vault',+ sync_status: 'synced',+ added: 101,+ embedded: 0,+ });+ expect(source.embed_backfill).toBeUndefined();+ await expectNoEmbedBackfillRow();+ }, 120_000);++ test('worker-backed --no-auto-embed reports policy refusal without denying queue capability', async () => {+ const workerBackedEngine = asWorkerBacked(engine);+ await runSources(workerBackedEngine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await runSources(workerBackedEngine, ['add', 'vault-two', '--path', repoPathTwo, '--no-federated']);+ const sources = await engine.executeRaw<{+ id: string;+ local_path: string | null;+ config: Record<string, unknown>;+ last_commit: string | null;+ chunker_version: string | null;+ }>(+ `SELECT id, local_path, config, last_commit, chunker_version+ FROM sources WHERE id IN ('vault', 'vault-two') ORDER BY id`,+ );+ const out: string[] = [];+ const origLog = console.log;+ console.log = (...args: unknown[]) => out.push(args.map(String).join(' '));+ let plan: Awaited<ReturnType<typeof resolveSyncAllEmbedPlan>>;+ try {+ plan = await resolveSyncAllEmbedPlan(workerBackedEngine, sources, {+ v2Enabled: true,+ serialFlag: false,+ noEmbed: false,+ noAutoEmbed: true,+ dryRun: false,+ jsonOut: true,+ yesFlag: false,+ full: false,+ includeGitignored: false,+ });+ } finally {+ console.log = origLog;+ }++ const notice = jsonLines(out.join('\n')).find((line) => line.gate === 'manual_drain_required');+ expect(notice).toMatchObject({+ status: 'manual_drain_required',+ workerSurface: 'worker_backed',+ reason: 'auto_submit_disabled',+ });+ expect(plan!).toMatchObject({+ deferEligible: true,+ fanOutEligible: true,+ effectiveNoEmbed: true,+ shouldBackfill: true,+ });+ const outcome = await resolveSyncEmbedBackfill(workerBackedEngine, 'vault', {+ reason: 'sync_all',+ autoSubmitDisabled: true,+ });+ expect(outcome).toEqual({+ status: 'manual_drain_required',+ command: 'gbrain embed --stale --source vault',+ reason: 'auto_submit_disabled',+ });+ await expectNoEmbedBackfillRow();+ }, 60_000);++ test('R-1: PGLite serial fallback stays inline and never claims worker deferral', async () => {await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await runSources(engine, ['add', 'vault-two', '--path', repoPathTwo, '--no-federated']);// Make the fan-out a clean no-op: last_commit == HEAD so performSync// reports up_to_date (no git pull, no backfill submit).- await engine.executeRaw(`UPDATE sources SET last_commit = $1 WHERE id = 'vault'`, [headSha]);+ const headShaTwo = execSync('git rev-parse HEAD', { cwd: repoPathTwo, stdio: 'pipe' }).toString().trim();+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault-two'`,+ [headShaTwo, String(CHUNKER_VERSION)],+ );// Seed a stale backlog so the deferred notice has a non-zero figure.await engine.putPage('vault/note', { type: 'note', title: 'note', compiled_truth: '# note' }, { sourceId: 'vault' });const chunks: ChunkInput[] = [@@ -117,32 +419,43 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {];await engine.upsertChunks('vault/note', chunks, { sourceId: 'vault' });- // v2 default ON → deferred. --json → agent path. NO --yes. --no-pull- // because the synthetic repo has no remote.+ // v2 defaults on, but PGLite has no worker-backed fan-out even with two sources.const { exitCode, stdout } = await runSyncCaptured(['--all', '--json', '--no-pull']);- // The headline assertion: NOT blocked.expect(exitCode).not.toBe(2);- expect(stdout).toContain('"gate":"deferred_notice"');+ expect(stdout).toContain('"gate":"below_floor"');+ expect(stdout).not.toContain('"gate":"deferred_notice"');+ expect(stdout).not.toContain('backfill job(s) queued');+ await expectNoEmbedBackfillRow();}, 60_000);- test('R-2 (#2139): inline sync --all (--serial) above floor AUTO-DEFERS (exit 0, never exit 2) + enqueues backfill', async () => {+ test('R-2 (#2139): PGLite sync --all above floor reports manual drain in gate + final JSON and writes no row', async () => {await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await runSources(engine, ['add', 'vault-two', '--path', repoPathTwo, '--no-federated']);// Floor 0 → any nonzero inline cost trips the gate. Source is unsynced// (last_commit NULL) → first-sync ceiling > 0 > floor.await engine.setConfig('sync.cost_gate_min_usd', '0');- // --serial forces inline even with v2 on. --json → non-TTY path → AUTO-DEFER.- const { exitCode, stdout } = await runSyncCaptured(['--all', '--serial', '--json', '--no-pull']);+ const { exitCode, stdout } = await runSyncCaptured(['--all', '--json', '--no-pull']);expect(exitCode).not.toBe(2);- expect(stdout).toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).toContain('"gate":"manual_drain_required"');+ expect(stdout).toContain('gbrain embed --stale --source vault');+ expect(stdout).toContain('gbrain embed --stale --source vault-two');expect(stdout).not.toContain('"gate":"confirmation_required"');- // The run PROCEEDED to import (the wedge is gone) — embeds were deferred,- // not blocked. (The embed-backfill enqueue wiring + its graceful- // missing-table tolerance is pinned in embed-backfill-submit.test.ts; the- // minion_jobs table isn't provisioned in this gate-wiring harness.)- expect(stdout).toContain('"sync_status":"first_sync"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));+ expect(final).toBeDefined();+ const finalSources = final!.sources as Array<Record<string, unknown>>;+ expect(finalSources).toHaveLength(2);+ expect(finalSources[0]).toMatchObject({+ source_id: 'vault', sync_status: 'first_sync',+ embed_backfill: { status: 'manual_drain_required', command: 'gbrain embed --stale --source vault' },+ });+ expect(finalSources[1]).toMatchObject({+ source_id: 'vault-two', sync_status: 'first_sync',+ embed_backfill: { status: 'manual_drain_required', command: 'gbrain embed --stale --source vault-two' },+ });+ await expectNoEmbedBackfillRow();}, 60_000);test('R-3 (#2139): chunker drift → full-tree CEILING estimate, auto-defers (not exit 2)', async () => {@@ -156,7 +469,7 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {const { exitCode, stdout } = await runSyncCaptured(['--all', '--serial', '--json', '--no-pull']);expect(exitCode).not.toBe(2);- expect(stdout).toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).toContain('"gate":"manual_drain_required"');expect(stdout).toContain('"estimateKind":"ceiling"');}, 60_000);@@ -170,7 +483,7 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {const { exitCode, stdout } = await runSyncCaptured(['--all', '--serial', '--json', '--no-pull']);expect(exitCode).not.toBe(2);- expect(stdout).not.toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).not.toContain('"gate":"manual_drain_required"');expect(stdout).toContain('"estimateKind":"unchanged"');}, 60_000);@@ -189,7 +502,7 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {const { exitCode, stdout } = await runSyncCaptured(['--all', '--serial', '--json', '--no-pull']);expect(exitCode).not.toBe(2);- expect(stdout).not.toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).not.toContain('"gate":"manual_drain_required"');expect(stdout).toContain('"estimateKind":"unchanged"');}, 60_000);@@ -203,7 +516,7 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {expect(exitCode).not.toBe(2);expect(stdout).toContain('"gate":"posture_tokenmax"');- expect(stdout).not.toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).not.toContain('"gate":"manual_drain_required"');}, 60_000);test('sync.cost_gate_min_usd=off → floor renders "unlimited", never blocks', async () => {@@ -215,23 +528,24 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {expect(exitCode).not.toBe(2);expect(stdout).toContain('"floorUsd":"unlimited"');- expect(stdout).not.toContain('"gate":"auto_deferred_embeds"');+ expect(stdout).not.toContain('"gate":"manual_drain_required"');}, 60_000);test('format split (#1784/D3A): non-TTY WITHOUT --json emits human text, no JSON envelope', async () => {await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);await engine.setConfig('sync.cost_gate_min_usd', '0');- // No --json: above floor in a non-TTY session → human auto-defer text.+ // No --json: above floor in a non-TTY PGLite session → manual drain text.const { exitCode, stdout } = await runSyncCaptured(['--all', '--serial', '--no-pull']);expect(exitCode).not.toBe(2);expect(stdout).not.toContain('"gate":'); // no JSON envelope without --json- expect(stdout.toLowerCase()).toContain('deferring embeds');+ expect(stdout.toLowerCase()).toContain('manual drain required');+ expect(stdout).toContain('gbrain embed --stale --source vault');expect(stdout).toContain('spend.posture'); // self-describing hint present}, 60_000);- test('single-source sync gets the same gate (auto-defers above floor, exit 0)', async () => {+ test('single-source PGLite sync reports manual drain in gate + final JSON and writes no row', async () => {await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);await engine.setConfig('sync.cost_gate_min_usd', '0');@@ -239,9 +553,73 @@ describe('v0.41.31 — sync --all cost gate wiring', () => {const { exitCode, stdout } = await runSyncCaptured(['--source', 'vault', '--json', '--no-pull']);expect(exitCode).not.toBe(2);- expect(stdout).toContain('"gate":"auto_deferred_embeds"');- // The gate now exists on the single-source path (was ungated before- // #2139) and proceeds to import rather than blocking.- expect(stdout.toLowerCase()).toContain('imported');+ expect(stdout).toContain('"gate":"manual_drain_required"');+ expect(stdout).toContain('gbrain embed --stale --source vault');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && line.source_id === 'vault');+ expect(final).toMatchObject({+ sync_status: 'first_sync',+ embed_backfill: {+ status: 'manual_drain_required',+ command: 'gbrain embed --stale --source vault',+ },+ });+ await expectNoEmbedBackfillRow();}, 60_000);++ test('single-source PGLite large incremental deferral reports manual drain in final JSON without a row', async () => {+ await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.setConfig('sync.cost_gate_min_usd', '1000');+ commitLargeIncrementalDrop();++ const { exitCode, stdout } = await runSyncCaptured(['--source', 'vault', '--json', '--no-pull']);++ expect(exitCode).not.toBe(2);+ expect(stdout).toContain('"gate":"below_floor"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && line.source_id === 'vault');+ expect(final).toMatchObject({+ sync_status: 'synced',+ added: 101,+ embedded: 0,+ embed_backfill: {+ status: 'manual_drain_required',+ command: 'gbrain embed --stale --source vault',+ },+ });+ await expectNoEmbedBackfillRow();+ }, 120_000);++ test('PGLite sync --all large incremental deferral reports per-source manual drain without a row', async () => {+ await runSources(engine, ['add', 'vault', '--path', repoPath, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET last_commit = $1, chunker_version = $2 WHERE id = 'vault'`,+ [headSha, String(CHUNKER_VERSION)],+ );+ await engine.setConfig('sync.cost_gate_min_usd', '1000');+ commitLargeIncrementalDrop();++ const { exitCode, stdout } = await runSyncCaptured(['--all', '--json', '--no-pull']);++ expect(exitCode).not.toBe(2);+ expect(stdout).toContain('"gate":"below_floor"');+ const final = jsonLines(stdout).find((line) => line.schema_version === 1 && Array.isArray(line.sources));+ expect(final).toBeDefined();+ expect(final!.sources).toEqual([+ expect.objectContaining({+ source_id: 'vault',+ sync_status: 'synced',+ added: 101,+ embedded: 0,+ embed_backfill: {+ status: 'manual_drain_required',+ command: 'gbrain embed --stale --source vault',+ reason: 'no_worker_surface',+ },+ }),+ ]);+ await expectNoEmbedBackfillRow();+ }, 120_000);});diff --git a/test/sync-cost-preview.test.ts b/test/sync-cost-preview.test.tsindex 79ef708dc1..b64e4060d9 100644--- a/test/sync-cost-preview.test.ts+++ b/test/sync-cost-preview.test.ts@@ -18,6 +18,7 @@ import {EMBEDDING_COST_PER_1K_TOKENS,estimateEmbeddingCostUsd,willEmbedSynchronously,+ resolveWorkerBackedSyncEmbedMode,shouldBlockSync,} from '../src/core/embedding.ts';import { lookupEmbeddingPrice } from '../src/core/embedding-pricing.ts';@@ -93,7 +94,8 @@ describe('Layer 8 D1 — embedding cost model', () => {});describe('v0.41.31 — willEmbedSynchronously (embed-mode resolver)', () => {- // Mirrors sync.ts:2346 effectiveNoEmbed = v2 && !serial && !noEmbed ? true : noEmbed.+ // Public compatibility contract: package.json exports ./embedding, so the+ // original v2/serial call shape must remain both type- and runtime-safe.// Embed runs INLINE iff that resolves to false.test('v2 off → inline (legacy synchronous embed)', () => {expect(willEmbedSynchronously({ v2Enabled: false, serialFlag: false, noEmbed: false })).toBe('inline');@@ -110,6 +112,14 @@ describe('v0.41.31 — willEmbedSynchronously (embed-mode resolver)', () => {});});+describe('worker-capability-aware sync embed mode', () => {+ test('defers only when the command boundary found a worker-backed defer path', () => {+ expect(resolveWorkerBackedSyncEmbedMode({ deferEligible: false, noEmbed: false })).toBe('inline');+ expect(resolveWorkerBackedSyncEmbedMode({ deferEligible: true, noEmbed: false })).toBe('deferred');+ expect(resolveWorkerBackedSyncEmbedMode({ deferEligible: false, noEmbed: true })).toBe('deferred');+ });+});+describe('v0.41.31 — shouldBlockSync (cost-gate decision)', () => {// R-1: deferred NEVER blocks, even at absurd cost (the headline fix — a// nightly cron over a synced corpus must not exit 2).diff --git a/test/sync-failures.test.ts b/test/sync-failures.test.tsindex 217e400c8b..7acc834689 100644--- a/test/sync-failures.test.ts+++ b/test/sync-failures.test.ts@@ -614,3 +614,53 @@ describe('v0.41.6.0 D2 — embedding error classification', () => {expect(classifyErrorCode('some random unmatched error message')).toBe('UNKNOWN');});});++// ─── #4543 — blocked_by_failures names the failing files + validate hint ───+//+// The v0.46.28.0 fix (#4496) made a status:'error' import result BLOCK the+// bookmark instead of checkpointing it as done — but the blocked message only+// showed code COUNTS (`YAML_PARSE: 1`), never WHICH file failed, and gave no+// pointer to the tool that pinpoints the YAML issue. Operators had to open+// sync-failures.jsonl by hand.+describe('#4543 blocked output names failing files', () => {+ test('formatFailedFileList names files with codes and skips sentinels', async () => {+ const { formatFailedFileList } = await import('../src/core/sync.ts');+ const out = formatFailedFileList([+ { path: 'notes/bad.md', error: 'YAML parse failed: bad block mapping' },+ { path: '<head>', error: 'history rewrite' },+ ]);+ expect(out).toContain('notes/bad.md');+ expect(out).toContain('YAML_PARSE');+ expect(out).not.toContain('<head>');+ });++ test('formatFailedFileList caps the list and counts the overflow', async () => {+ const { formatFailedFileList } = await import('../src/core/sync.ts');+ const many = Array.from({ length: 15 }, (_, i) => ({+ path: `notes/f${String(i).padStart(2, '0')}.md`,+ error: 'YAML parse failed',+ }));+ const out = formatFailedFileList(many, 10);+ expect(out).toContain('notes/f09.md');+ expect(out).not.toContain('notes/f10.md');+ expect(out).toContain('and 5 more');+ });++ test('formatFailedFileList scrubs control characters from paths', async () => {+ const { formatFailedFileList } = await import('../src/core/sync.ts');+ const out = formatFailedFileList([+ { path: 'notes/evil\x1b[2Jname.md', error: 'YAML parse failed' },+ ]);+ expect(out).not.toContain('\x1b');+ expect(out).toContain('�');+ });++ test('both blocked gates name the files and hint at frontmatter validate', async () => {+ const source = await Bun.file(new URL('../src/commands/sync.ts', import.meta.url)).text();+ // Incremental gate names files from failedFiles; full gate from result.failures.+ expect(source).toContain('formatFailedFileList(failedFiles)');+ expect(source).toContain('formatFailedFileList(result.failures)');+ // The actionable hint rides along in the blocked copy.+ expect(source).toContain("gbrain frontmatter validate <path>");+ });+});diff --git a/test/sync-slug-root-mode-4342.test.ts b/test/sync-slug-root-mode-4342.test.tsindex a1901e4573..f428c0becd 100644--- a/test/sync-slug-root-mode-4342.test.ts+++ b/test/sync-slug-root-mode-4342.test.ts@@ -186,3 +186,53 @@ describe('#4342 slug_root_mode', () => {expect(await readSlugRootMode(engine, 'vault-dry')).toBe('source-root');}, 120_000);});++// ─── #4521 — a string-scalar sources.config must not abort the sync ───────+//+// Historical writers could leave sources.config as a jsonb STRING scalar+// (double-encoded object). v0.46.28.0's writeSlugRootMode ran jsonb_set+// directly on it → 'cannot set path in scalar' → every subdir-scoped sync+// exited 1 right after sync.discover_git_root. The write now heals the+// column through the canonical SOURCE_CONFIG_OBJECT_SQL coercion first.+describe('#4521 scalar sources.config heal-on-write', () => {+ test('writeSlugRootMode heals a string-scalar config and pins the mode', async () => {+ await runSources(engine, ['add', 'vault-scalar', '--path', subdir, '--no-federated']);+ // Simulate the historical corruption: a double-encoded object scalar.+ await engine.executeRaw(+ `UPDATE sources SET config = to_jsonb($2::text) WHERE id = $1`,+ ['vault-scalar', JSON.stringify({ federated: false })],+ );+ await writeSlugRootMode(engine, 'vault-scalar', 'source-root');+ expect(await readSlugRootMode(engine, 'vault-scalar')).toBe('source-root');+ // The heal is a RECOVERY, not a wipe: keys inside the double-encoded+ // object survive, and the column is an object again.+ const rows = await engine.executeRaw<{ federated: string | null; t: string }>(+ `SELECT config->>'federated' AS federated, jsonb_typeof(config) AS t+ FROM sources WHERE id = $1`,+ ['vault-scalar'],+ );+ expect(rows[0]?.t).toBe('object');+ expect(rows[0]?.federated).toBe('false');+ });++ test('a subdir-scoped sync over a scalar config completes instead of aborting', async () => {+ await runSources(engine, ['add', 'vault-scalar-sync', '--path', subdir, '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET config = to_jsonb($2::text) WHERE id = $1`,+ ['vault-scalar-sync', '"not-an-object"'],+ );+ const res = await performSync(engine, {+ repoPath: subdir, sourceId: 'vault-scalar-sync', noEmbed: true, noPull: true,+ });+ expect(['first_sync', 'synced']).toContain(res.status);+ expect(await readSlugRootMode(engine, 'vault-scalar-sync')).toBe('source-root');+ }, 120_000);++ test('a failed pin write names the source in the error', async () => {+ const fake = {+ executeRaw: async () => { throw new Error('cannot set path in scalar'); },+ } as unknown as PGLiteEngine;+ await expect(writeSlugRootMode(fake, 'vault-broken', 'git-root'))+ .rejects.toThrow(/vault-broken/);+ });+});diff --git a/test/sync-working-tree-cli.test.ts b/test/sync-working-tree-cli.test.tsnew file mode 100644index 0000000000..91fa782ff9--- /dev/null+++ b/test/sync-working-tree-cli.test.ts@@ -0,0 +1,172 @@+/**+ * Untracked-gap wiring tests — the CLI layer above performSync.+ *+ * test/sync-working-tree.test.ts pins performSync's behavior; this file pins+ * the three wiring seams the ship coverage audit flagged:+ *+ * 1. printSyncResult renders the drift NOTE on BOTH 'up_to_date' and+ * 'synced' statuses, and stays silent when `uncommitted` is absent.+ * (printSyncResult is module-internal — asserted through runSync's+ * captured stdout, the same seam production output uses.)+ * 2. `--working-tree` parses to SyncOpts.workingTree === true, and an+ * absent flag leaves it undefined so performSync's config fallback+ * (sync.include_working_tree) engages — observable as drift counted+ * but NOT imported when the config is unset.+ * 3. syncOneSource threads shared.workingTree into performSync.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync, runSync, syncOneSource } from '../src/commands/sync.ts';+import { runSources } from '../src/commands/sources.ts';++let engine: PGLiteEngine;+let repoPath: string;+const SOURCE_ID = 'wtree-cli';++function commitAll(msg: string): void {+ execSync('git add -A', { cwd: repoPath, stdio: 'pipe' });+ execSync(`git commit -m "${msg}"`, { cwd: repoPath, stdio: 'pipe' });+}++async function pageExists(slug: string): Promise<boolean> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`,+ [slug, SOURCE_ID],+ );+ return Number(rows[0]?.n ?? 0) > 0;+}++const baseArgs = () => [+ '--no-embed', '--no-extract', '--no-pull',+ '--repo', repoPath, '--source', SOURCE_ID, '--yes',+];++/**+ * Drive runSync with stdout captured (printSyncResult's sink) and+ * process.exit guarded — same harness as sync-sole-non-default-routing.+ */+async function runSyncCaptured(args: string[]): Promise<string> {+ const stdoutOrig = process.stdout.write.bind(process.stdout);+ const chunks: string[] = [];+ process.stdout.write = ((chunk: string | Uint8Array): boolean => {+ chunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));+ return true;+ }) as typeof process.stdout.write;+ const origExit = process.exit;+ let exitCode: number | undefined;+ process.exit = ((code?: number) => {+ exitCode = code;+ throw new Error('__exit__');+ }) as typeof process.exit;+ try {+ await runSync(engine, args);+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ process.exit = origExit;+ process.stdout.write = stdoutOrig;+ }+ expect(exitCode === undefined || exitCode === 0).toBe(true);+ return chunks.join('');+}++describe('sync working-tree CLI wiring (drift NOTE + --working-tree flag)', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-wtree-cli-'));+ 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/base.md'), '# Base\n\ncommitted content\n');+ commitAll('base');++ await runSources(engine, ['add', SOURCE_ID, '--path', repoPath, '--no-federated']);++ // Anchor: first sync establishes last_commit so later runs are incremental.+ const first = await performSync(engine, {+ repoPath, sourceId: SOURCE_ID, noPull: true, noEmbed: true, noExtract: true,+ });+ expect(first.status).toBe('first_sync');+ }, 120_000);++ afterAll(async () => {+ if (engine) await engine.disconnect();+ if (repoPath) rmSync(repoPath, { recursive: true, force: true });+ }, 60_000);++ test('absent flag: up_to_date prints the drift NOTE and drift is NOT imported (config fallback engages)', async () => {+ writeFileSync(join(repoPath, 'topics/untracked.md'), '# Untracked\n\nnever committed\n');+ writeFileSync(join(repoPath, 'topics/base.md'), '# Base\n\nedited but not committed\n');++ const stdout = await runSyncCaptured(baseArgs());+ expect(stdout).toContain('Already up to date.');+ // The NOTE line printSyncResult renders from SyncResult.uncommitted.+ expect(stdout).toContain('NOTE: 2 uncommitted file(s) not synced');+ expect(stdout).toContain('(1 untracked/added, 1 modified, 0 deleted)');+ expect(stdout).toContain("--working-tree");+ // workingTree was passed as undefined (flag absent) and+ // sync.include_working_tree is unset → drift counted, never imported.+ expect(await pageExists('topics/untracked')).toBe(false);+ }, 60_000);++ test('synced status ALSO carries the drift NOTE', async () => {+ // Advance HEAD with a targeted commit while the drift from the previous+ // test stays uncommitted → this run takes the 'synced' path.+ writeFileSync(join(repoPath, 'topics/second.md'), '# Second\n\ncommitted addition\n');+ execSync('git add topics/second.md && git commit -m "second"', { cwd: repoPath, stdio: 'pipe' });++ const stdout = await runSyncCaptured(baseArgs());+ expect(stdout).toContain('Synced ');+ expect(stdout).toContain('NOTE: 2 uncommitted file(s) not synced');+ expect(stdout).toContain('(1 untracked/added, 1 modified, 0 deleted)');+ }, 60_000);++ test('--working-tree flag parses through to import: drift imported, NOTE absent', async () => {+ const stdout = await runSyncCaptured([...baseArgs(), '--working-tree']);+ // The flag reached performSync as workingTree: true — the untracked file+ // imported and the uncommitted field (hence the NOTE) is absent.+ expect(stdout).toContain('Synced ');+ expect(stdout).not.toContain('NOTE:');+ expect(await pageExists('topics/untracked')).toBe(true);+ }, 60_000);++ test('clean tree: up_to_date with no NOTE (uncommitted undefined)', async () => {+ commitAll('settle working tree');+ await runSyncCaptured(baseArgs()); // import the settle commit → anchor at HEAD++ const stdout = await runSyncCaptured(baseArgs());+ expect(stdout).toContain('Already up to date.');+ expect(stdout).not.toContain('NOTE:');+ }, 60_000);++ test('syncOneSource threads shared.workingTree into performSync', async () => {+ writeFileSync(join(repoPath, 'topics/one-source.md'), '# OneSource\n\nuntracked for the pool\n');+ const src = { id: SOURCE_ID, name: SOURCE_ID, local_path: repoPath, config: {} };+ const shared = {+ dryRun: false, full: false, noPull: true, noEmbed: true, noExtract: true,+ skipFailed: false, retryFailed: false, concurrency: undefined,+ };++ // workingTree undefined → drift counted, not imported (fallback path).+ const counted = await syncOneSource(engine, src, shared);+ expect(counted.result.status).toBe('up_to_date');+ expect(counted.result.uncommitted).toEqual({ added: 1, modified: 0, deleted: 0 });+ expect(await pageExists('topics/one-source')).toBe(false);++ // workingTree: true → the same drift imports.+ const imported = await syncOneSource(engine, src, { ...shared, workingTree: true });+ expect(imported.result.status).toBe('synced');+ expect(imported.result.added).toBe(1);+ expect(imported.result.uncommitted).toBeUndefined();+ expect(await pageExists('topics/one-source')).toBe(true);+ }, 60_000);+});diff --git a/test/sync-working-tree.test.ts b/test/sync-working-tree.test.tsnew file mode 100644index 0000000000..0e19faa9d9--- /dev/null+++ b/test/sync-working-tree.test.ts@@ -0,0 +1,189 @@+/**+ * Untracked-gap regression tests — uncommitted working-tree state vs+ * commit-driven incremental sync.+ *+ * Pre-fix bug (observed on a real vault): incremental sync diffs+ * last_commit..HEAD, so files written into the repo but never committed are+ * invisible — sync prints "Already up to date." while the pages sit outside+ * the brain (106 untracked .md files in the wild case). Nothing counted,+ * nothing warned.+ *+ * Fix under test:+ * 1. Attached-HEAD incremental sync COUNTS uncommitted drift through the+ * same scope/exclude/isSyncable filters imports use, reports it as+ * `SyncResult.uncommitted`, and warns on stderr — never silently ignores.+ * 2. `workingTree: true` (CLI --working-tree / config+ * sync.include_working_tree) imports uncommitted state via the same+ * manifest-merge path detached-HEAD syncs always used.+ * 3. Non-syncable untracked files do not count as drift.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';+import { execSync } from 'child_process';+import { tmpdir } from 'os';+import { join } from 'path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync } from '../src/commands/sync.ts';+import { runSources } from '../src/commands/sources.ts';++let engine: PGLiteEngine;+let repoPath: string;+const SOURCE_ID = 'testsrc-wtree';++function commitAll(msg: string): void {+ execSync('git add -A', { cwd: repoPath, stdio: 'pipe' });+ execSync(`git commit -m "${msg}"`, { cwd: repoPath, stdio: 'pipe' });+}++async function pageExists(slug: string): Promise<boolean> {+ const rows = await engine.executeRaw<{ n: number }>(+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`,+ [slug, SOURCE_ID],+ );+ return Number(rows[0]?.n ?? 0) > 0;+}++const baseOpts = () => ({+ repoPath,+ sourceId: SOURCE_ID,+ noPull: true,+ noEmbed: true,+ noExtract: true,+});++describe('sync working-tree drift (untracked gap)', () => {+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await runSources(engine, ['add', SOURCE_ID, '--no-federated']);++ repoPath = mkdtempSync(join(tmpdir(), 'gbrain-wtree-'));+ 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/base.md'), '# Base\n\ncommitted content\n');+ commitAll('base');++ // First sync = full walk; establishes last_commit so later runs are incremental.+ const first = await performSync(engine, baseOpts());+ expect(first.status).toBe('first_sync');+ expect(await pageExists('topics/base')).toBe(true);+ }, 120_000);++ afterAll(async () => {+ if (engine) await engine.disconnect();+ if (repoPath) rmSync(repoPath, { recursive: true, force: true });+ }, 60_000);++ test('default sync counts uncommitted drift and does NOT import it', async () => {+ writeFileSync(join(repoPath, 'topics/untracked.md'), '# Untracked\n\nnever committed\n');+ writeFileSync(join(repoPath, 'topics/base.md'), '# Base\n\nedited but not committed\n');++ const result = await performSync(engine, baseOpts());+ expect(result.status).toBe('up_to_date');+ expect(result.uncommitted).toEqual({ added: 1, modified: 1, deleted: 0 });+ expect(await pageExists('topics/untracked')).toBe(false);+ }, 60_000);++ test('workingTree: true imports uncommitted state (attached HEAD)', async () => {+ const result = await performSync(engine, { ...baseOpts(), workingTree: true });+ expect(result.status).toBe('synced');+ expect(result.added).toBe(1); // topics/untracked.md+ expect(result.modified).toBe(1); // topics/base.md uncommitted edit+ expect(result.uncommitted).toBeUndefined();+ expect(await pageExists('topics/untracked')).toBe(true);+ }, 60_000);++ test('non-syncable untracked files do not count as drift', async () => {+ commitAll('commit the working tree'); // clean slate: prior drift now committed+ writeFileSync(join(repoPath, 'topics/junk.xyz'), 'not syncable\n');++ const result = await performSync(engine, baseOpts());+ // The commit advanced HEAD, so this run imports the committed diff —+ // either way the .xyz file must not surface as uncommitted drift.+ expect(result.uncommitted).toBeUndefined();+ }, 60_000);++ test('synced run imports the committed delta AND reports remaining drift (deletes counted, --exclude honored)', async () => {+ // Committed change: HEAD advances, so this run takes the `synced` path,+ // not the `up_to_date` path — `uncommitted` must ride on BOTH.+ writeFileSync(join(repoPath, 'topics/base.md'), '# Base\n\ncommitted edit two\n');+ commitAll('edit base');+ // Working-tree drift left behind:+ // added → untracked syncable file+ // deleted → tracked file removed from disk, deletion not committed+ // excluded → untracked syncable file matched by --exclude (must NOT count)+ writeFileSync(join(repoPath, 'topics/drift-note.md'), '# Drift\n\nstill uncommitted\n');+ writeFileSync(join(repoPath, 'topics/skipme.md'), '# Skip\n\nexcluded from sync\n');+ rmSync(join(repoPath, 'topics/untracked.md'));++ const result = await performSync(engine, { ...baseOpts(), exclude: ['topics/skipme.md'] });+ expect(result.status).toBe('synced');+ expect(result.modified).toBe(1); // the committed base.md edit imported+ // Drift filtered through the same predicates imports use: skipme.md is+ // excluded, junk.xyz (still on disk from the previous test) is unsyncable.+ expect(result.uncommitted).toEqual({ added: 1, modified: 0, deleted: 1 });+ expect(await pageExists('topics/drift-note')).toBe(false);+ // The uncommitted deletion must NOT have been applied to the brain.+ expect(await pageExists('topics/untracked')).toBe(true);+ }, 60_000);++ test('rename-only dirty tree still reports drift (add + delete decomposition)', async () => {+ // Reviewer-caught gap: a staged `git mv` populates ONLY the manifest's+ // `renamed` bucket — it set hasWorkingTreeChanges but counted zero drift,+ // reproducing the silent "Already up to date." this fix exists to kill.+ commitAll('settle working tree'); // clean slate: prior drift now committed+ await performSync(engine, baseOpts()); // import the settle commit → anchor at HEAD+ execSync('git mv topics/base.md topics/base-renamed.md', { cwd: repoPath, stdio: 'pipe' });++ const result = await performSync(engine, baseOpts());+ expect(result.status).toBe('up_to_date');+ // Rename decomposes as add(new path) + delete(old path).+ expect(result.uncommitted).toEqual({ added: 1, modified: 0, deleted: 1 });+ // Not imported: the renamed page keeps its old slug until committed.+ expect(await pageExists('topics/base')).toBe(true);+ expect(await pageExists('topics/base-renamed')).toBe(false);+ }, 60_000);++ test('sync.include_working_tree config imports without the flag (resolved in performSync, not the CLI)', async () => {+ // Adversarial-review finding: config resolution lived only in the CLI+ // layer, so the dream cycle's own "set sync.include_working_tree=true"+ // remedy was a no-op for every programmatic caller. Now performSync+ // resolves it when opts.workingTree is undefined.+ commitAll('settle rename'); // finalize test 5's staged rename+ await performSync(engine, baseOpts()); // anchor at HEAD+ writeFileSync(join(repoPath, 'topics/config-driven.md'), '# Config\n\nimported via config\n');++ await engine.setConfig('sync.include_working_tree', 'true');+ try {+ const result = await performSync(engine, baseOpts()); // no workingTree flag+ expect(result.status).toBe('synced');+ expect(await pageExists('topics/config-driven')).toBe(true);+ } finally {+ await engine.unsetConfig('sync.include_working_tree');+ }+ }, 60_000);++ test('working-tree mass-delete valve refuses >50% uncommitted deletions', async () => {+ // Adversarial-review finding: merged working-tree deletes bypassed the+ // #2828 reconcile valve — a transient tree state (mid-rebase, accidental+ // rm -rf) on a scheduled working-tree sync could sweep the source.+ mkdirSync(join(repoPath, 'bulk'), { recursive: true });+ for (let i = 0; i < 12; i++) {+ writeFileSync(join(repoPath, `bulk/page-${i}.md`), `# Bulk ${i}\n\ncontent ${i}\n`);+ }+ commitAll('add bulk pages');+ const settled = await performSync(engine, { ...baseOpts(), workingTree: true });+ expect(settled.status).toBe('synced');+ for (let i = 0; i < 12; i++) rmSync(join(repoPath, `bulk/page-${i}.md`));++ const result = await performSync(engine, { ...baseOpts(), workingTree: true });+ // Valve fires: deletes skipped loudly, nothing swept.+ expect(result.deleted).toBe(0);+ expect(await pageExists('bulk/page-0')).toBe(true);+ expect(await pageExists('bulk/page-11')).toBe(true);+ }, 60_000);+});diff --git a/test/take-proposals.test.ts b/test/take-proposals.test.tsindex ff2c24e6d4..dbd56f183f 100644--- a/test/take-proposals.test.ts+++ b/test/take-proposals.test.ts@@ -154,6 +154,37 @@ describe('acceptProposal', () => {expect(row.acted_at).not.toBeNull();});+ test('#4480 TOCTOU: concurrent accepts — exactly one wins, one fence write, loser gets not_pending', async () => {+ const id = await insertProposal({+ slug: 'companies/acme-example', claim: 'Acme signs exactly one concurrent deal', kind: 'take',+ });+ // Pre-fix (fence write first, status flip after, rowcount ignored) BOTH+ // callers passed the pending check, BOTH appended the take to the .md,+ // and BOTH reported success. Post-fix the claim CAS runs first, so only+ // the winner touches the fence.+ const results = await Promise.allSettled([+ acceptProposal({ engine, brainDir: repo, sourceId: 'default', actedBy: 'racer-a' }, id),+ acceptProposal({ engine, brainDir: repo, sourceId: 'default', actedBy: 'racer-b' }, id),+ ]);+ const wins = results.filter((r) => r.status === 'fulfilled');+ const losses = results.filter((r) => r.status === 'rejected');+ expect(wins.length).toBe(1);+ expect(losses.length).toBe(1);+ const lossReason = (losses[0] as PromiseRejectedResult).reason;+ expect(lossReason).toBeInstanceOf(TakeProposalError);+ expect((lossReason as TakeProposalError).code).toBe('not_pending');++ // Exactly ONE copy of the claim in the markdown fence.+ const fence = parseTakesFence(readFileSync(join(repo, 'companies/acme-example.md'), 'utf-8'));+ const copies = fence.takes.filter((t) => t.claim === 'Acme signs exactly one concurrent deal');+ expect(copies.length).toBe(1);++ // Row is stamped once, with the winner's identity + promoted_row_num.+ const row = await proposalRow(id);+ expect(row.status).toBe('accepted');+ expect(row.promoted_row_num).not.toBeNull();+ });+test('double-accept refuses with not_pending', async () => {const id = await insertProposal({ slug: 'companies/widget-co', claim: 'Widget-co raises fund-a next year' });await acceptProposal({ engine, brainDir: repo, sourceId: 'default' }, id);@@ -165,6 +196,23 @@ describe('acceptProposal', () => {}});+ test('wave-g: stranded claim (accepted, no promoted take) surfaces the repair SQL on retry', async () => {+ // The crash-between-CAS-and-fence-write shape (#4480 residual): the row+ // is status='accepted' with promoted_row_num NULL — invisible in the+ // pending list, so the retry path must name it and print the repair.+ const id = await insertProposal({ slug: 'people/strand-example', claim: 'stranded claim', status: 'accepted' });+ try {+ await acceptProposal({ engine, brainDir: repo }, id);+ throw new Error('expected acceptProposal to throw for the stranded row');+ } catch (e) {+ expect(e).toBeInstanceOf(TakeProposalError);+ expect((e as TakeProposalError).code).toBe('not_pending');+ expect((e as Error).message).toContain('stranded');+ expect((e as Error).message).toContain(`SET status='pending'`);+ expect((e as Error).message).toContain(String(id));+ }+ });+test('source scope: accepting an out-of-scope proposal reads as not_found', async () => {const id = await insertProposal({slug: 'companies/acme-example', claim: 'scope: other-source only', sourceId: 'other',@@ -216,6 +264,20 @@ describe('rejectProposal', () => {expect((err as TakeProposalError).code).toBe('not_pending');}});++ test('#4480 TOCTOU: concurrent rejects — exactly one wins the CAS', async () => {+ const id = await insertProposal({ slug: 'companies/widget-co', claim: 'reject: raced claim' });+ const results = await Promise.allSettled([+ rejectProposal({ engine, sourceId: 'default', actedBy: 'racer-a' }, id),+ rejectProposal({ engine, sourceId: 'default', actedBy: 'racer-b' }, id),+ ]);+ // Pre-fix both resolved (the loser's no-op UPDATE went unchecked).+ expect(results.filter((r) => r.status === 'fulfilled').length).toBe(1);+ const loss = results.find((r) => r.status === 'rejected') as PromiseRejectedResult;+ expect((loss.reason as TakeProposalError).code).toBe('not_pending');+ const row = await proposalRow(id);+ expect(row.status).toBe('rejected');+ });});describe('coerceProposalKind', () => {diff --git a/test/takes-extract-json.test.ts b/test/takes-extract-json.test.tsindex 69e37f3a9e..f3f4d6a832 100644--- a/test/takes-extract-json.test.ts+++ b/test/takes-extract-json.test.ts@@ -51,6 +51,10 @@ describe('gbrain takes extract --from-pages --json (#3962)', () => {claims_extracted: 0,consent_gate_blocked: false,llm_unavailable: false,+ // #4473: md-first skip accounting.+ pages_skipped: 0,+ skipped: [],+ mirror_warnings: 0,});});});diff --git a/test/think-cli-source-flag.serial.test.ts b/test/think-cli-source-flag.serial.test.tsnew file mode 100644index 0000000000..b475872645--- /dev/null+++ b/test/think-cli-source-flag.serial.test.ts@@ -0,0 +1,122 @@+/**+ * #4508 — `gbrain think "<q>" --source <id>` used to leak the flag into the+ * question.+ *+ * runThinkCli's flag-strip list lacked `--source` (and `--calibration-holder`),+ * so the flag AND its value joined the positional question: the output echoed+ * `# --source X <question>`, exit 0, and the scope was silently ignored. The+ * CLI now parses --source, validates it (unknown source → exit 1), threads+ * sourceId into runThink, and strips --calibration-holder's value too.+ *+ * runThink is mocked (no LLM, no retrieval) — these tests pin the CLI arg+ * surface only. Source validation runs against a stub engine that knows one+ * source: 'workspace'.+ */+import { describe, test, expect, beforeEach, mock } from 'bun:test';++const captured: { opts: Array<Record<string, unknown>> } = { opts: [] };++const stubResult = {+ answer: 'Stub answer.',+ citations: [],+ gaps: [],+ warnings: [],+ modelUsed: 'none',+ pagesGathered: 0,+ takesGathered: 0,+ graphHits: 0,+};++mock.module('../src/core/think/index.ts', () => ({+ runThink: async (_engine: unknown, opts: Record<string, unknown>) => {+ captured.opts.push(opts);+ return JSON.parse(JSON.stringify(stubResult));+ },+ persistSynthesis: async () => ({ slug: 'synthesis/stub', evidenceInserted: 0, warnings: [] }),+ stripGapsSection: (s: string) => s,+}));++const realConfig = await import('../src/core/config.ts');+mock.module('../src/core/config.ts', () => ({+ ...realConfig,+ isThinClient: () => false,+}));++const { runThinkCli } = await import('../src/commands/think.ts');++/** Stub engine: assertSourceExists's query resolves only 'workspace'. */+const stubEngine = {+ executeRaw: async (_sql: string, params?: unknown[]) =>+ params?.[0] === 'workspace' ? [{ id: 'workspace' }] : [],+} as never;++class ExitSentinel extends Error {+ constructor(public readonly code: number) {+ super(`process.exit(${code})`);+ this.name = 'ExitSentinel';+ }+}++async function runCli(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 {+ await runThinkCli(stubEngine, 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(() => { captured.opts.length = 0; });++describe('#4508 think --source CLI surface', () => {+ test('--source is parsed out of the question and threaded into runThink', async () => {+ const r = await runCli(['what', 'is', 'acme-example', '--source', 'workspace']);+ expect(r.code).toBe(0);+ // The question header is pure — pre-fix it read "# --source workspace what is acme-example".+ expect(r.out[0]).toBe('# what is acme-example\n');+ expect(captured.opts).toHaveLength(1);+ expect(captured.opts[0].question).toBe('what is acme-example');+ expect(captured.opts[0].sourceId).toBe('workspace');+ });++ test('an unknown --source is rejected with exit 1 (never silently ignored)', async () => {+ const r = await runCli(['what', 'is', 'acme-example', '--source', 'nope-source']);+ expect(r.code).toBe(1);+ expect(r.err.join('\n')).toContain('nope-source');+ expect(captured.opts).toHaveLength(0); // never reached runThink+ });++ test('--calibration-holder value no longer leaks into the question', async () => {+ const r = await runCli(['a', 'question', '--with-calibration', '--calibration-holder', 'holder-example']);+ expect(r.code).toBe(0);+ expect(r.out[0]).toBe('# a question\n');+ expect(captured.opts[0].question).toBe('a question');+ expect(captured.opts[0].calibrationHolder).toBe('holder-example');+ });++ test('omitting --source keeps the default scope (no sourceId key)', async () => {+ const r = await runCli(['plain', 'question']);+ expect(r.code).toBe(0);+ expect(captured.opts[0].sourceId).toBeUndefined();+ });++ test('think --help documents --source', async () => {+ const r = await runCli(['--help']);+ expect(r.out.join('\n')).toContain('--source');+ });+});diff --git a/test/think-envelope-salvage.test.ts b/test/think-envelope-salvage.test.tsnew file mode 100644index 0000000000..0d6f44695e--- /dev/null+++ b/test/think-envelope-salvage.test.ts@@ -0,0 +1,127 @@+/**+ * #4509 — think must never ship a raw JSON envelope as the user-facing+ * answer. Valid fenced JSON already parses (tryParseJSON strips fences); the+ * leak needed MALFORMED JSON — typically max-token truncation cutting the+ * envelope mid-string. Pinned here:+ * - salvageThinkEnvelope recovers answer/citations/gaps tolerantly+ * (dangling escapes trimmed, arrays only when whole);+ * - runThink surfaces the salvaged answer (never the raw envelope);+ * - JSON-shaped but unsalvageable output → empty answer, not raw JSON;+ * - prose (refusals / the graceful sentinel) keeps its raw text.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import {+ runThink,+ salvageThinkEnvelope,+ looksLikeJsonEnvelope,+ type ThinkLLMClient,+} from '../src/core/think/index.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++describe('salvageThinkEnvelope (pure)', () => {+ test('recovers the answer from an envelope truncated mid-string', () => {+ const truncated = '{"answer": "The tools you need are a wrench, a bucket and a debur';+ const r = salvageThinkEnvelope(truncated);+ expect(r).not.toBeNull();+ expect(r!.answer).toBe('The tools you need are a wrench, a bucket and a debur');+ expect(r!.citations).toEqual([]);+ expect(r!.gaps).toEqual([]);+ });++ test('trims a dangling escape and an incomplete \\u sequence at the cut', () => {+ expect(salvageThinkEnvelope('{"answer": "line one\\nline two\\')!.answer).toBe('line one\nline two');+ expect(salvageThinkEnvelope('{"answer": "smile \\u26')!.answer).toBe('smile ');+ });++ test('recovers whole citations/gaps arrays when they survived the cut', () => {+ const t = '{"answer": "cited", "citations": [{"page_slug": "a/b", "row_num": 3}], "gaps": ["missing x"], "extra": "cut he';+ const r = salvageThinkEnvelope(t)!;+ expect(r.citations).toEqual([{ page_slug: 'a/b', row_num: 3 }]);+ expect(r.gaps).toEqual(['missing x']);+ });++ test('drops a citations array cut mid-way instead of guessing', () => {+ const t = '{"answer": "ok so far", "citations": [{"page_slug": "a/b", "row_';+ const r = salvageThinkEnvelope(t)!;+ expect(r.answer).toBe('ok so far');+ expect(r.citations).toEqual([]);+ });++ test('fenced malformed JSON salvages the same way', () => {+ const t = '```json\n{"answer": "fenced but cut mid';+ expect(salvageThinkEnvelope(t)!.answer).toBe('fenced but cut mid');+ });++ test('returns null for prose, for envelopes without an answer, and for empty answers', () => {+ expect(salvageThinkEnvelope('I cannot help with that request.')).toBeNull();+ expect(salvageThinkEnvelope('{"citations": [], "gap')).toBeNull();+ expect(salvageThinkEnvelope('{"answer": " ')).toBeNull();+ });++ test('looksLikeJsonEnvelope: fenced/bare objects yes, prose no', () => {+ expect(looksLikeJsonEnvelope('{"answer": "x')).toBe(true);+ expect(looksLikeJsonEnvelope('```json\n{"answer"')).toBe(true);+ expect(looksLikeJsonEnvelope('plain prose, not JSON')).toBe(false);+ });+});++describe('runThink — malformed envelope never reaches the answer (#4509)', () => {+ let engine: PGLiteEngine;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await resetPgliteState(engine);+ }, 300_000);++ afterAll(async () => {+ if (engine) await engine.disconnect();+ }, 60_000);++ function clientReturning(text: string): ThinkLLMClient {+ return {+ create: async () => ({+ content: [{ type: 'text', text }],+ usage: { input_tokens: 10, output_tokens: 10 },+ }) as never,+ };+ }++ test('truncated envelope → salvaged answer, not the raw JSON', async () => {+ const truncated = '{"answer": "Salv買geable answer text that was cut mid-str';+ const r = await runThink(engine, {+ question: 'q?',+ client: clientReturning(truncated),+ withTrajectory: false,+ });+ expect(r.synthesis_status).toBe('not_json');+ expect(r.warnings).toContain('LLM_OUTPUT_NOT_JSON');+ expect(r.warnings).toContain('SALVAGED_ANSWER_FROM_MALFORMED_JSON');+ expect(r.answer).toBe('Salv買geable answer text that was cut mid-str');+ expect(r.answer).not.toContain('{"answer"');+ expect(r.synthesisOk).toBe(false); // salvage never persists as a synthesis page+ }, 60_000);++ test('JSON-shaped but unsalvageable → empty answer, never raw JSON', async () => {+ const r = await runThink(engine, {+ question: 'q?',+ client: clientReturning('{"citations": [], "ga'),+ withTrajectory: false,+ });+ expect(r.synthesis_status).toBe('not_json');+ expect(r.warnings).toContain('MALFORMED_JSON_ANSWER_SUPPRESSED');+ expect(r.answer).toBe('');+ }, 60_000);++ test('refusal prose keeps its raw text (meaningful to consumers)', async () => {+ const r = await runThink(engine, {+ question: 'q?',+ client: clientReturning('I cannot help with that request.'),+ withTrajectory: false,+ });+ expect(r.synthesis_status).toBe('not_json');+ expect(r.answer).toBe('I cannot help with that request.');+ }, 60_000);+});diff --git a/test/think-pages-block.test.ts b/test/think-pages-block.test.tsindex 79dc65e3ac..0410df9a9c 100644--- a/test/think-pages-block.test.ts+++ b/test/think-pages-block.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from 'bun:test';-import { renderPagesBlock } from '../src/core/think/gather.ts';+import {+ renderPagesBlock,+ pagesBlockExcerptLen,+ EXCERPT_CUT_START_MARKER,+ EXCERPT_CUT_END_MARKER,+} from '../src/core/think/gather.ts';import type { SearchResult } from '../src/core/types.ts';function searchResult(@@ -20,6 +25,14 @@ function renderedExcerpt(rendered: string): string {return match[1];}+/** The excerpt minus the #4510 truncation-marker lines. */+function excerptBody(rendered: string): string {+ let body = renderedExcerpt(rendered);+ if (body.startsWith(`${EXCERPT_CUT_START_MARKER}\n`)) body = body.slice(EXCERPT_CUT_START_MARKER.length + 1);+ if (body.endsWith(`\n${EXCERPT_CUT_END_MARKER}`)) body = body.slice(0, -(EXCERPT_CUT_END_MARKER.length + 1));+ return body;+}+describe('renderPagesBlock', () => {test('selects question-relevant facts beyond the leading 600 characters', () => {const prefix = [@@ -63,7 +76,7 @@ describe('renderPagesBlock', () => {test('never splits a surrogate pair at a selected window boundary', () => {const content = `${'a'.repeat(599)}🚀 target evidence ${'z'.repeat(1000)}`;const rendered = renderPagesBlock([searchResult(content)], 600, 'target evidence');- const excerpt = renderedExcerpt(rendered);+ const excerpt = excerptBody(rendered);expect(rendered.isWellFormed()).toBe(true);expect(excerpt).toContain('target evidence');@@ -191,13 +204,13 @@ describe('renderPagesBlock', () => {'unmatched question',);- expect(renderedExcerpt(rendered)).toBe(content.slice(0, 600));+ expect(excerptBody(rendered)).toBe(content.slice(0, 600));});test('keeps a complete surrogate pair ending exactly at the fallback budget', () => {const content = `${'a'.repeat(598)}🚀tail`;const rendered = renderPagesBlock([searchResult(content)], 600);- const excerpt = renderedExcerpt(rendered);+ const excerpt = excerptBody(rendered);expect(excerpt).toBe(content.slice(0, 600));expect(excerpt.isWellFormed()).toBe(true);@@ -207,6 +220,50 @@ describe('renderPagesBlock', () => {const content = 'abcdefghij'.repeat(100);const rendered = renderPagesBlock([searchResult(content)], 600);- expect(renderedExcerpt(rendered)).toBe(content.slice(0, 600));+ expect(excerptBody(rendered)).toBe(content.slice(0, 600));+ });+});++describe('renderPagesBlock — #4510 truncation honesty', () => {+ test('a cut inside a table lands on a row boundary and is explicitly marked', () => {+ const rows = Array.from({ length: 40 }, (_, i) => `| tool-${i} | purpose of tool ${i} goes here |`);+ const content = `# Required Tools\n\n${rows.join('\n')}\n`;+ const rendered = renderPagesBlock([searchResult(content)], 600, 'what tools do I need?');+ const excerpt = renderedExcerpt(rendered);++ // Marked: the model can tell "the table ends here" from "the text was cut".+ expect(excerpt.endsWith(EXCERPT_CUT_END_MARKER)).toBe(true);+ // Every delivered row is complete — no mid-cell severing.+ const body = excerptBody(rendered);+ for (const line of body.split('\n')) {+ if (line.startsWith('|')) expect(line.endsWith('|')).toBe(true);+ }+ });++ test('an excerpt starting mid-page carries the start marker', () => {+ const filler = 'background line\n'.repeat(80);+ const content = `${filler}decisive target evidence here\n${'tail line\n'.repeat(40)}`;+ const rendered = renderPagesBlock([searchResult(content)], 120, 'target evidence');+ const excerpt = renderedExcerpt(rendered);++ expect(excerpt.startsWith(EXCERPT_CUT_START_MARKER)).toBe(true);+ expect(excerpt).toContain('decisive target evidence here');+ });++ test('a page that fits whole carries no markers', () => {+ const content = 'short page\nwith two lines';+ const rendered = renderPagesBlock([searchResult(content)], 600, 'short page');++ expect(rendered).not.toContain(EXCERPT_CUT_START_MARKER);+ expect(rendered).not.toContain(EXCERPT_CUT_END_MARKER);+ expect(renderedExcerpt(rendered)).toBe(content);+ });++ test('pagesBlockExcerptLen: floor holds at high page counts, window grows at low counts', () => {+ expect(pagesBlockExcerptLen(20)).toBe(600); // budget/20 = 600 → floor+ expect(pagesBlockExcerptLen(40)).toBe(600); // never collapses below the floor+ expect(pagesBlockExcerptLen(10)).toBe(1200); // fewer pages → bigger windows+ expect(pagesBlockExcerptLen(1)).toBe(2400); // ceiling+ expect(pagesBlockExcerptLen(0)).toBe(600);});});diff --git a/test/transcripts-self-exclusion.test.ts b/test/transcripts-self-exclusion.test.tsnew file mode 100644index 0000000000..36cddf53ce--- /dev/null+++ b/test/transcripts-self-exclusion.test.ts@@ -0,0 +1,118 @@+/**+ * #4472 — transcript discovery must not re-ingest gbrain's own claude-cli+ * subprocess sessions.+ *+ * The claude-cli provider spawns `claude --print` with+ * cwd = <tmpdir>/gbrain-claude-cli-cwd-<pid>; Claude Code records each call+ * as a session under ~/.claude/projects/<slugified-cwd>/. Discovery picked+ * those up like any other project — a self-ingestion feedback loop (gbrain's+ * prompt scaffolding + page content re-entering the brain as+ * "conversations"). Pins:+ *+ * 1. discovery skips sessions whose path carries the scratch-cwd+ * fingerprint; `includeSelf` restores them (the CLI --include-self+ * escape hatch);+ * 2. the fingerprint predicate + per-PID dir naming agree (the constant is+ * shared, not duplicated);+ * 3. the provider-init sweep removes dead-PID scratch dirs and leaves+ * live-PID, own-PID, and non-matching dirs alone.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, readdirSync } from 'node:fs';+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 type { HarnessRoot } from '../src/core/transcripts/detect.ts';+import {+ CLAUDE_CLI_CWD_PREFIX,+ claudeCliCwdDir,+ claudeCliConfigDir,+ isClaudeCliSelfTranscriptPath,+ sweepDeadClaudeCliScratchDirs,+} from '../src/core/ai/providers/claude-cli-scratch.ts';++let projectsRoot: string;+let roots: HarnessRoot[];++beforeAll(() => {+ projectsRoot = mkdtempSync(join(tmpdir(), 'gb-self-excl-projects-'));+ // A real user project session.+ const userProject = join(projectsRoot, '-Users-alice-code-myapp');+ mkdirSync(userProject, { recursive: true });+ writeFileSync(join(userProject, 'session-user.jsonl'), '{"type":"user"}\n', 'utf-8');+ // gbrain's own claude-cli scratch-cwd session (slugified per Claude Code:+ // /private/tmp/gbrain-claude-cli-cwd-12345 → -private-tmp-gbrain-claude-cli-cwd-12345).+ 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');+ roots = [{ format: 'claude-code', root: projectsRoot, extension: '.jsonl' }];+});++afterAll(() => {+ rmSync(projectsRoot, { recursive: true, force: true });+});++describe('transcript discovery — claude-cli self-session exclusion (#4472)', () => {+ test('default discovery skips gbrain-claude-cli-cwd sessions', () => {+ const found = discoverTranscriptFiles(roots);+ const names = found.map((f) => basename(f.path));+ expect(names).toContain('session-user.jsonl');+ expect(names).not.toContain('session-self.jsonl');+ });++ test('includeSelf restores them (the --include-self escape hatch)', () => {+ const found = discoverTranscriptFiles(roots, { includeSelf: true });+ const names = found.map((f) => basename(f.path));+ expect(names).toContain('session-user.jsonl');+ expect(names).toContain('session-self.jsonl');+ });++ test('fingerprint predicate and per-PID dir naming share one constant', () => {+ expect(basename(claudeCliCwdDir(4242))).toBe(`${CLAUDE_CLI_CWD_PREFIX}4242`);+ expect(isClaudeCliSelfTranscriptPath(claudeCliCwdDir())).toBe(true);+ expect(isClaudeCliSelfTranscriptPath('/Users/alice/.claude/projects/-Users-alice-code-myapp/s.jsonl')).toBe(false);+ // The slugified project-dir form matches too.+ expect(+ isClaudeCliSelfTranscriptPath(`/Users/alice/.claude/projects/-private-tmp-${CLAUDE_CLI_CWD_PREFIX}999/s.jsonl`),+ ).toBe(true);+ });+});++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-'));+ try {+ // A genuinely dead PID: a child that already exited.+ const deadPid = spawnSync('true').pid!;+ expect(typeof deadPid).toBe('number');++ const deadCwd = join(base, `${CLAUDE_CLI_CWD_PREFIX}${deadPid}`);+ const deadCfg = join(base, basename(claudeCliConfigDir(deadPid)));+ const ownCwd = join(base, `${CLAUDE_CLI_CWD_PREFIX}${process.pid}`);+ const liveCwd = join(base, `${CLAUDE_CLI_CWD_PREFIX}1`); // pid 1 is alive (EPERM → alive)+ const nonNumeric = join(base, `${CLAUDE_CLI_CWD_PREFIX}not-a-pid`);+ const unrelated = join(base, 'some-other-dir');+ for (const d of [deadCwd, deadCfg, ownCwd, liveCwd, nonNumeric, unrelated]) {+ mkdirSync(d, { recursive: true });+ writeFileSync(join(d, 'marker.txt'), 'x', 'utf-8');+ }++ const removed = sweepDeadClaudeCliScratchDirs(base);+ expect(removed).toBe(2); // dead cwd + dead config dir+ expect(existsSync(deadCwd)).toBe(false);+ expect(existsSync(deadCfg)).toBe(false);+ expect(existsSync(ownCwd)).toBe(true);+ expect(existsSync(liveCwd)).toBe(true);+ expect(existsSync(nonNumeric)).toBe(true);+ expect(existsSync(unrelated)).toBe(true);+ expect(readdirSync(base).length).toBe(4);+ } finally {+ rmSync(base, { recursive: true, force: true });+ }+ });++ test('unreadable base dir is a no-op, never a throw (fail-open)', () => {+ expect(sweepDeadClaudeCliScratchDirs(join(tmpdir(), 'gb-self-excl-missing-base'))).toBe(0);+ });+});diff --git a/test/upgrade-skill-publish-prompt-race.test.ts b/test/upgrade-skill-publish-prompt-race.test.tsnew file mode 100644index 0000000000..f124b2bd84--- /dev/null+++ b/test/upgrade-skill-publish-prompt-race.test.ts@@ -0,0 +1,62 @@+/**+ * `gbrain upgrade`'s one-time "Enable skill publishing now? (recommended)+ * [Y/n]" prompt (#4318 residual) — same close-before-resolve race the shared+ * `src/core/confirm-prompt.ts` helper was written to fix, but this inline+ * confirm in upgrade.ts predates that helper and was never migrated: it+ * called `rl.close()` inside the answer callback BEFORE resolving, while an+ * unguarded `rl.on('close', () => resolveAns(false))` listener fired+ * synchronously during that close and settled the promise first — so+ * pressing Enter (or typing "y") on this default-YES prompt always resolved+ * `false`, silently leaving skill publishing disabled regardless of what the+ * operator answered.+ *+ * The prompt is inline inside a large, side-effecting `runUpgrade()` flow+ * (DB writes, network) rather than an exported, injectable function, so this+ * pins the fix at the source level: a regression back to the close-before-+ * resolve shape fails here even though `test/confirm-prompt.test.ts` (which+ * only covers the shared helper) cannot see this file at all.+ */+import { describe, test, expect } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++describe('gbrain upgrade — skill-publish prompt wiring (#4318 residual)', () => {+ // test-reads-source-ok: the prompt is inline inside a large, side-effecting,+ // non-exported runUpgrade() with no injectable stdin — resolve/close+ // ordering is only observable in source text, not an executable boundary.+ const src = readFileSync(join(import.meta.dir, '../src/commands/upgrade.ts'), 'utf8');++ test('the close listener is guarded by an `answered` flag, not unconditional', () => {+ // The buggy shape was `rl.on('close', () => resolveAns(false));` with no+ // guard. The fixed shape checks `answered` before declining on close.+ const idx = src.indexOf('[gbrain] Enable skill publishing now?');+ expect(idx).toBeGreaterThan(-1);+ const promptRegion = src.slice(idx - 100, idx + 700);+ expect(promptRegion).toContain('let answered = false;');+ expect(promptRegion).toContain('answered = true;');+ expect(promptRegion).toMatch(/rl\.on\('close',\s*\(\)\s*=>\s*\{\s*if \(!answered\) resolveAns\(false\);/);+ // The regression this guards against: an unconditional decline-on-close.+ expect(promptRegion).not.toMatch(/rl\.on\('close',\s*\(\)\s*=>\s*resolveAns\(false\)\);/);+ });++ test('resolveAns for the answer is called strictly before rl.close() in the question callback', () => {+ const idx = src.indexOf('[gbrain] Enable skill publishing now?');+ const promptRegion = src.slice(idx - 100, idx + 700);+ const resolveIdx = promptRegion.indexOf('resolveAns(a === ');+ const closeIdx = promptRegion.indexOf('rl.close();');+ expect(resolveIdx).toBeGreaterThan(-1);+ expect(closeIdx).toBeGreaterThan(-1);+ expect(resolveIdx).toBeLessThan(closeIdx);+ });++ test('the [Y/n] default-yes contract is preserved: an empty (Enter-only) answer resolves true', () => {+ // The prompt reads "(recommended) [Y/n]" — pressing Enter with no text+ // must accept the recommendation. A fix that only reordered+ // resolve/close without preserving this branch (e.g. narrowing to+ // `a === 'y' || a === 'yes'`) would still pass the two tests above while+ // silently flipping this prompt's default from accept to decline.+ const idx = src.indexOf('[gbrain] Enable skill publishing now?');+ const promptRegion = src.slice(idx - 100, idx + 700);+ expect(promptRegion).toContain("resolveAns(a === '' || a === 'y' || a === 'yes');");+ });+});