Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.28.0 fix: the megawave — 111 backlog issues fixed across retrieval, sync, cycle, jobs, doctor, and visibility (#4475)

Sina Matian67e7e8a9246b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 85021f455b..c7c1059549 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.27.0",
+ "version": "0.46.28.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 17079479b4..f840564f37 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.27.0",
+ "version": "0.46.28.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000000..d18032359f
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,42 @@
+<!-- Title format (IRON RULE): vMAJOR.MINOR.PATCH.MICRO <type>(<scope>): <summary> (#issue) -->
+
+## What
+
+<!-- One paragraph: the user-visible behavior change and the issue it fixes. -->
+
+## Why
+
+<!-- The failure mode this closes. Link the issue. -->
+
+## Discrimination test (required for every fix — #3665)
+
+<!--
+A fix's test is only worth anything if it FAILS without the fix. Fill in the
+one-line result of actually checking that. The helper does it in one command:
+
+ bash scripts/check-test-discriminates.sh <test-file> <source-file> [...]
+
+It reverts the source file(s) to the pre-fix state, runs the test file,
+requires >=1 executed test to FAIL (a crash/missing-file non-zero exit does
+not count — see the script's exit-code contract), restores, and prints the
+line below for you. Tests that pass both ways are worse than no test: they
+inflate reviewer confidence, cost CI time forever, and keep passing after a
+future refactor breaks the behavior.
+
+Delete this section ONLY for pure-docs / pure-refactor PRs with no behavior
+change to pin.
+-->
+
+Discrimination test: reverted `<source file(s)>` to `<ref>`, ran `<test file>` → `N pass / M fail`. Restored → all pass.
+
+## Verification
+
+<!--
+If any message/doc this PR adds tells the user to run a command to verify
+something, paste the output of that verification against a system in the
+BROKEN state (the #3697 class: remediation text that lies). Otherwise delete.
+-->
+
+## Tests
+
+<!-- Test files touched/added, and the local run result (redirect to a file, check the exit code — never pipe through tail). -->
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 64976fae6d..98644ee080 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.27.0 -->
+<!-- gbrain-runbook-stamp: 0.46.28.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d8ac5c39e..313a01da13 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,98 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.28.0] - 2026-08-21
+
+The megawave: 111 verified issues fixed in one release — every remaining
+fixable item from the full-backlog triage, implemented reproduce-first with
+failing-first tests and two-lens adversarial review per area. Fully
+reconciled with v0.46.26.0–27.0 (the daemon env file supersedes interim key
+channels; both rc files now source independently on top of it).
+
+### Security & visibility
+- Private-page visibility (`visibility: private` frontmatter) is now enforced
+ uniformly across every remote read surface — search arms, page reads, link
+ and graph traversal, chunk/version/timeline/raw reads, and slug resolution —
+ with one shared predicate so engines and ops can't drift. Private pages read
+ exactly like missing ones to untrusted callers (no existence oracle). Trusted
+ local CLI use is unchanged; operators keep a config opt-out
+ (`search.remote_private_pages`) and an incident escape hatch
+ (`GBRAIN_REMOTE_PRIVATE_PAGES=1`), documented in the MCP surface runbook.
+- Query caching stays fully effective for remote callers: the visibility
+ posture folds into the cache key (knobs_hash v=23) instead of skipping the
+ cache — one-time cold-miss on upgrade, cross-posture contamination is
+ structurally impossible (pinned at hash, cache-store, and hybrid levels).
+- Untrusted frontmatter can no longer point conversation ingestion at
+ arbitrary host files (absolute-path traversal guard, fail-closed).
+- Trust-gate hardening: tombstone payloads and code-graph readiness rechecks
+ now fail closed on unset trust.
+
+### Retrieval
+- CJK queries recover keyword matches on both engines (bigram fallback parity,
+ #3986); relational-arm results carry evidence stamps and monotone scores.
+- CRAG-style escalation seam (config-gated, default off, experimental) — a
+ degraded search can escalate to a deeper re-run (#1663).
+- Degradation visibility: searches that fall back now say so in `_meta`
+ (#3873 note: model-tier config now takes precedence over `models.default` —
+ set your tier explicitly if you relied on the old order).
+- Multi-type filters, snippet caps, and deep-research ids thread through every
+ search leg uniformly (#3985 #3800).
+
+### Sync, ingestion & timeline
+- Legacy timeline rows are repaired one-time by migration (content-anchored,
+ idempotent) so re-extraction dedups instead of duplicating (#3957); the
+ dedup index re-keys on md5(summary) so long summaries can't abort timeline
+ writes (#3737).
+- `sync --dry-run` is pure again (no config writes, #4342); image files import
+ incrementally (#2683); FS-walk stamps snapshot page state before reading so
+ concurrent edits stay stale-visible (#3875).
+- Entity identity groups (manual cross-source linking, v1) respect source
+ scope in both directions (#4224).
+
+### Jobs, cycle & operations
+- Durable per-call chat usage ledger (`chat_usage_log`, read via `get_usage`,
+ now admin-scoped) with canonical-table cost estimates (#4218).
+- Probe-liveness wedge in the LLM halt/cooldown path unlatched — a deferred
+ probe can no longer freeze a worker queue until restart; strikes escalate
+ per halted probe, not per concurrent failure.
+- Cycle stale-drain is time-budgeted; lock refreshers feature-detect signal
+ shapes; PID-1 zombie reaping under container/daemon use (#2443 #2308).
+- Embed retry/backoff cluster peeled into core (`core/embed-retry.ts`) fixing
+ a core→commands layering hazard; Voyage/OpenAI embedding prices re-verified.
+
+### Release-gate hardening (caught by this release's own gate battery)
+- Schema-pack regex inference no longer uses a `node:vm` watchdog — it could
+ wedge the event loop in embedded-engine processes (silent hangs during
+ large imports); replaced with input caps + a nested-quantifier refusal
+ shared with the lint rule (#3190 follow-up).
+- Autopilot launchd installs survive repo deletion: the job's working
+ directory no longer pins the repo, so the self-disable guard actually runs
+ (previously every respawn died before reaching it).
+
+### Doctor, CLI & DX
+- Doctor: silent-death checks, self-upgrade honesty, dead-check pruning, and
+ quieter output on healthy brains (#3944 #3925 #3958).
+- CLI: silent-failure surfacing on exit paths, confirm-race gate on
+ destructive prompts, Bun.which PATH fix for bootstrap detection (#4325).
+- Decorated Python defs chunk correctly for code-def resolution (#3821).
+- Note for RTL users: pointed-Hebrew (niqqud) slugs re-key under the
+ normalized scheme — existing links self-heal on next sync (#3700).
+
+### Historical CHANGELOG corrections
+- v0.13.1 entry: corrected the budget figure (#3748).
+- v0.46.x entry: `gbrain migrate-engine` → `gbrain migrate --to` (#3697).
+
+### To take advantage of v0.46.26.0
+```bash
+gbrain upgrade # or: bun install -g gbrain@latest
+gbrain migrate # runs migrations v137–v140 (identity groups, timeline
+ # dedup re-key + one-time repair, chat usage ledger)
+gbrain doctor # confirms the new checks pass on your brain
+```
+First queries after upgrade re-warm the semantic cache (knobs v=23). If you
+relied on `models.default` overriding tier config, re-check `gbrain search
+modes` output (#3873 precedence change).
+
## [0.46.27.0] - 2026-08-21
**The autopilot daemon can no longer lose your API keys silently.** The
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 322b6d4988..11cd768f5a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -32,7 +32,7 @@ frontmatter will read as absent. Refresh it once, from the repository root:
git rm --cached -r . -q
git reset --hard
bash -n scripts/run-unit-parallel.sh # silence means bash can read the scripts
-git ls-files --eol -- '*.md' | grep -c w/crlf # 0 means Markdown is clean
+git ls-files --eol -- '*.md' | grep -cE 'w/(crlf|mixed)' # 0 means Markdown is clean
```
Every `check:*` entry in `package.json` invokes its script as `bash scripts/<name>.sh`
@@ -172,6 +172,46 @@ a paired `afterAll(disconnect)`.
listed in `scripts/check-test-isolation.allowlist`; the allow-list MUST shrink
over time — never add new entries.
+### Discrimination test — required for every fix (#3665)
+
+A fix's test is only worth anything if it **fails without the fix**. A test
+that passes both ways is worse than no test: it inflates reviewer confidence,
+gets weighted into the CI shards forever, and keeps passing after a future
+refactor silently breaks the behavior. (An adversarial review pass found PRs
+where 7 of 8 new tests passed on master.)
+
+Every PR that fixes behavior must fill the **Discrimination test** field in
+the PR template with the actual result of checking this:
+
+> Discrimination test: reverted `<source file(s)>` to `<ref>`, ran
+> `<test file>` → `N pass / M fail`. Restored → all pass.
+
+The helper does the whole dance in one command:
+
+```bash
+bash scripts/check-test-discriminates.sh <test-file> <source-file> [<source-file>...]
+```
+
+It reverts the source files to the pre-fix state (plain file copies, no git
+stash), runs the test file, requires at least one EXECUTED test to fail —
+exit ≠ 0 alone does not count, because a missing file or import crash also
+exits non-zero (exit 3, the vacuous-failure class) — restores, and prints the
+paste-ready field line. Exit 1 means the test passed with the fix reverted:
+tighten the assertions before asking for review.
+
+Vacuous-assertion shapes to avoid (they recur):
+- asserting only `exit ≠ 0` (a missing binary also exits non-zero);
+- asserting membership in a set that covers every reachable value
+ (`['warn','fail']` when those are the only outputs);
+- asserting a substring that would also appear in the broken output —
+ assert parsed structure instead.
+
+Relatedly: a test whose only assertion is a regex over `readFileSync`'d
+source text pins spelling, not behavior. New tests that read `src/` text
+need a `test-reads-source-ok: <why>` comment (or a behavioral assertion
+alongside); `test/test-reads-source-smell.test.ts` enforces this for new
+files and ratchets the pre-existing list down.
+
### Local CI gate (recommended before pushing)
```bash
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index d27aca6538..d053c5cf8d 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -238,6 +238,17 @@ diff against gbrain's bundle when you want upstream improvements. (The legacy
`gbrain skillpack install` managed-block model was removed in v0.33 — run
`gbrain skillpack migrate-fence` once if upgrading from an older release.)
+> **PGLite brains are single-process (applies to every MCP registration
+> below).** PGLite is a single-writer embedded Postgres: the first running
+> `gbrain serve` owns the brain's data directory via the data-dir lock. A
+> second `serve` (gbrain registered in two harnesses on the same machine) —
+> or any CLI command that opens the DB — fails on the lock while that serve
+> is live (`gbrain sync` is the one exception: it delegates to the live
+> serve). If multiple processes need the brain at once, run ONE shared
+> `gbrain serve --http` and point every client at it, or migrate to the
+> Postgres/Supabase engine, which tolerates concurrent connections. Details:
+> [docs/architecture/serve-sync-concurrency.md](docs/architecture/serve-sync-concurrency.md).
+
**If you are Hermes:** register gbrain as your MCP server:
```bash
diff --git a/TODOS.md b/TODOS.md
index 4aa5b7d741..efa5b29548 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -2197,10 +2197,16 @@ events at the IPC delivery point and dedupes via the transcript's
plus user reports of "it only noticed on my next message". **Start:**
`src/commands/hook.ts` (the event already has a dispatch slot pattern),
`src/core/bootstrap/hooks.ts` registration writers.
-- [ ] **P3 — engine-uniform IPC listener (Postgres serves).** serve's resolve/turn_context
- socket is PGLite-gated (`src/mcp/server.ts`: `cfg?.engine === 'pglite'`), so on a
- Postgres brain `gbrain hook user-prompt` short-circuits (`no_pglite_path`) and the
- hook lane is PGLite-only. Extending the listener needs (a) a canonical per-connection
+- [x] **P3 — engine-uniform IPC listener (Postgres serves).** DONE (#4245): serve now
+ listens for Postgres brains too — socket + turn_context secret key off
+ `hash12(database_url)` under `~/.gbrain/run` (0700) via
+ `resolveSocketPathForConfig`/`ipcSecretPathForConfig` in
+ `src/core/context/resolve-ipc.ts`; the hook lane's user-prompt/compact/
+ session-start arms route through the same resolver. Original filing:
+ serve's resolve/turn_context
+ socket was PGLite-gated (`src/mcp/server.ts`: `cfg?.engine === 'pglite'`), so on a
+ Postgres brain `gbrain hook user-prompt` short-circuited (`no_pglite_path`) and the
+ hook lane was PGLite-only. Extending the listener needs (a) a canonical per-connection
socket path for brains with no data dir (e.g. `~/.gbrain/run/resolve-<hash12(database_url)>.sock`,
0700 dir) and (b) a secret-file home for `turn_context` auth (same hash-keyed run dir).
The cathedral-3 branch prototyped (a) as `resolveSocketPathForConfig` (see branch
@@ -7560,3 +7566,11 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.
- [ ] P2 (adversarial F3): a chronically-failing transcript (always times out / deterministic all-writes-failed) releases its key on dead AND suppresses the cooldown stamp — re-triaged and re-paid every nightly. Add a bounded per-content-hash failure counter (N strikes → skip + surface in doctor/advisor).
- [ ] P3 (adversarial F6): legacy direct-Anthropic path with the CDX-6 32k thinking default can exceed the SDK's 10-min default request timeout on slow generations (flag-off deployments only; surfaces as a retryable conn error at full token cost). Set an explicit SDK timeout or cap legacy maxTokens.
- [ ] P3: phase-end `embedStalePages` runs outside BudgetTracker (bounded to the phase's own writes + 120s; fold under the tracker if spend telemetry wants it).
+
+### Recipe routing follow-up (#4292)
+- [ ] **P3 — install-time MECE warn for resolver rows.** `gbrain integrations
+ install` appends `resolver_rows_to_append` blindly; when an appended row
+ shares trigger phrases with an existing resolver row in the host repo
+ (e.g. "who is" claimed by both a recipe skill and the query skill), routing
+ goes ambiguous with no signal. Warn at install time when a to-append row's
+ quoted phrases already appear in the target RESOLVER.md/AGENTS.md. Effort: S.
diff --git a/VERSION b/VERSION
index 4a85c1b17a..4b854a3d3b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.27.0
+0.46.28.0
\ No newline at end of file
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index c6d31811f0..e30beee33d 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -345,7 +345,7 @@ canonical.
## Schema state tracking
-`~/.gbrain/update-state.json` tracks which recommended schema directories the user
+`~/.gbrain/upgrade-state.json` tracks which recommended schema directories the user
adopted, declined, or added custom. The auto-update agent
(`docs/guides/upgrades-auto-update.md`) reads this during upgrades to suggest new schema additions without re-suggesting
things the user already declined. The setup skill writes the initial state during
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 42f60913bd..01dd22027f 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **Starter** marks membership in the ~27-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 118 tools across 22 areas. **Starter** marks membership in the ~27-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -13,6 +13,7 @@ Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **S
| `get_health` | Brain health dashboard (embed coverage, stale pages, orphans). | admin | | |
| `get_stats` | Brain statistics (page count, chunk count, etc.) | admin | | |
| `get_status_snapshot` | Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. | admin | | |
+| `get_usage` | Aggregate chat usage + cost from the chat_usage_log ledger (per-model and per-phase token counts, cache reads/writes, USD estimates) with explicit coverage fields. | admin | | |
| `quarantine_list` | List quarantined (hidden) and optionally content-flagged pages by scanning page frontmatter, newest-updated first. | admin | | |
| `run_doctor` | Run brain health checks and return a structured DoctorReport (thin-client doctor surface). | admin | | |
| `run_onboard` | Probe brain health + optionally submit onboard remediations. | admin | | |
@@ -55,6 +56,7 @@ Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
+| `entity_identity_list` | List cross-source entity identity groups and their member pages. | read | | |
| `extract_entities` | Extract entity names (people, companies) from text and create/update their brain stub pages. | write | | |
| `extraction_pending` | List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). | read | | |
@@ -88,12 +90,12 @@ Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
-| `cancel_job` | Cancel a waiting, active, or delayed job | admin | | |
+| `cancel_job` | Cancel a waiting, active, or delayed job. | admin | | |
| `get_agent_job` | Poll an agent job submitted via submit_agent. | agent | yes | |
-| `get_job` | Get job status and details by ID | admin | | |
-| `get_job_progress` | Get structured progress for a running job | admin | | |
+| `get_job` | Get job status and details by ID. | admin | | |
+| `get_job_progress` | Get structured progress for a running job. | admin | | |
| `get_job_stats` | Job queue statistics. | admin | | |
-| `list_jobs` | List jobs with optional filters | admin | | |
+| `list_jobs` | List jobs with optional filters. | admin | | |
| `pause_job` | Pause a waiting, active, or delayed job | admin | | |
| `replay_job` | Replay a completed/failed/dead job, optionally with modified data | admin | | |
| `resume_job` | Resume a paused job back to waiting | admin | | |
@@ -148,6 +150,7 @@ Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **S
|---|---|---|---|---|
| `capture` | Capture a quick note into the brain — the "just remember this" write. | write | yes | |
| `delete_page` | Soft-delete a page. | write | | |
+| `fetch` | Fetch the full text of one search result by its `id` (OpenAI deep-research contract: the search/fetch pair). | read | | |
| `get_chunks` | Get content chunks for a page | read | | |
| `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |
| `get_raw_data` | Retrieve raw data for a page | read | | |
diff --git a/docs/ai-providers/llama-server-reranker.md b/docs/ai-providers/llama-server-reranker.md
index b4b88a2899..1b47543870 100644
--- a/docs/ai-providers/llama-server-reranker.md
+++ b/docs/ai-providers/llama-server-reranker.md
@@ -10,8 +10,10 @@ already drives for ZeroEntropy's hosted reranker. The
Two flavors of "local" this recipe covers:
-- **Qwen3-Reranker** (0.6B / 4B / 8B) — open-weight cross-encoder; pull
- the GGUF from HuggingFace and serve.
+- **Qwen3-Reranker** (0.6B / 4B / 8B) — open-weight cross-encoder. Qwen
+ publishes official GGUFs for its EMBEDDING models but not for the
+ rerankers, so pull a community GGUF conversion from HuggingFace (or
+ convert the official weights yourself) and serve.
- **Self-hosted ZeroEntropy** (`zerank-2`, `zerank-1-small`) — the
weights are on HuggingFace too. GGUF-convert them and serve them the
same way. **Quality is not guaranteed to match ZE-hosted:** GGUF
@@ -48,15 +50,22 @@ across releases. The recipe sends to `/v1/rerank`.
### 2. Pull a reranker GGUF
-For Qwen3-Reranker-4B (quantized Q4_K_M is the sweet spot for CPU):
+For Qwen3-Reranker-4B (quantized Q4_K_M is the sweet spot for CPU),
+pull a community GGUF conversion. Qwen ships no official reranker GGUF
+repos (the official `Qwen/Qwen3-Reranker-4B` repo carries the raw
+weights only), so the conversion below is **community-maintained** —
+verify scores against your own eval before trusting it in production:
```bash
# Pick a quant level — Q4_K_M is the usual CPU sweet spot.
huggingface-cli download \
- Qwen/Qwen3-Reranker-4B-GGUF qwen3-reranker-4b-q4_k_m.gguf \
+ mradermacher/Qwen3-Reranker-4B-GGUF Qwen3-Reranker-4B.Q4_K_M.gguf \
--local-dir ./models
```
+Prefer official provenance? Convert the real `Qwen/Qwen3-Reranker-4B`
+weights yourself with llama.cpp's `convert_hf_to_gguf.py`, then quantize.
+
For self-hosted ZeroEntropy weights, find a community GGUF conversion
or convert from the HuggingFace weights yourself (out of scope of this
doc — see llama.cpp's `convert_hf_to_gguf.py`).
@@ -65,7 +74,7 @@ doc — see llama.cpp's `convert_hf_to_gguf.py`).
```bash
./build/bin/llama-server \
- --model ./models/qwen3-reranker-4b-q4_k_m.gguf \
+ --model ./models/Qwen3-Reranker-4B.Q4_K_M.gguf \
--alias qwen3-reranker-4b \
--reranking \
--port 8081
diff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.md
index 7f6bcbe920..0f7702e9af 100644
--- a/docs/ai-providers/zeroentropy.md
+++ b/docs/ai-providers/zeroentropy.md
@@ -153,7 +153,7 @@ Two probes run for reranker:
|---|---|---|
| `search.reranker.enabled` | `true` for balanced/tokenmax, `false` for conservative | One-flip opt-in/out |
| `search.reranker.model` | `zeroentropyai:zerank-2` (legacy fallback; new installs write `voyage:rerank-2.5`) | The recommended replacement is `voyage:rerank-2.5` |
-| `search.reranker.top_n_in` | `30` | Candidates sent to reranker (caps API spend) |
+| `search.reranker.top_n_in` | per mode: `30` conservative / `25` balanced / `50` tokenmax (tracks each bundle's `searchLimit`) | Candidates sent to reranker (caps API spend) |
| `search.reranker.top_n_out` | `null` (no truncate) | Truncate reranked output to this many; `null` preserves full length |
| `search.reranker.timeout_ms` | `5000` | HTTP timeout; long stalls degrade UX worse than RRF fallback |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 577400bcca..6818137934 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -384,8 +384,8 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind})
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
- `AGENTS.md` — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors `CLAUDE.md` intent via relative links. Claude Code keeps using `CLAUDE.md`.
- `docs/UPGRADING_DOWNSTREAM_AGENTS.md` — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.
-- `src/core/schema-embedded.ts` — AUTO-GENERATED from schema.sql (run `bun run build:schema`)
-- `src/schema.sql` — Full Postgres + pgvector DDL (source of truth, generates schema-embedded.ts)
+- `src/core/schema-embedded.generated.ts` — AUTO-GENERATED from schema.sql (run `bun run build:schema`; the `.generated.ts` suffix exempts it from the module-size ratchet's new-file cap, per the guard's generated-file carve-out)
+- `src/schema.sql` — Full Postgres + pgvector DDL (source of truth, generates schema-embedded.generated.ts)
- `src/core/search/expansion.ts` — Multi-query expansion via Haiku. Exports `sanitizeQueryForPrompt` + `sanitizeExpansionOutput` (prompt-injection defense-in-depth). Sanitized query is only used for the LLM channel; the original query still drives search.
- `recipes/` — Integration recipe files (YAML frontmatter + markdown setup instructions)
- `docs/guides/` — Individual SKILLPACK guides (broken out from monolith)
diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.md
index 50eaa48730..f94a478911 100644
--- a/docs/architecture/brains-and-sources.md
+++ b/docs/architecture/brains-and-sources.md
@@ -241,6 +241,31 @@ is the whole story for them.
source. The flags are for when you want to query across the boundary
deliberately.
+## Entity identity across sources (#4224, v1)
+
+**The identity key for a page is `(source_id, slug)`.** Slugs are only
+unique per source, so `people/alice` in your `wiki` source and
+`people/alice-chen` in a mounted team source are, by default, two unrelated
+pages — even when they describe the same person. Nothing merges them
+automatically.
+
+When they ARE the same entity, say so explicitly with the manual-only
+identity ops (v1 — no auto-matching, no name-similarity heuristics):
+
+```
+gbrain entity-identity-link --entity-id alice-chen --slug people/alice --source-id wiki
+gbrain entity-identity-link --entity-id alice-chen --slug people/alice-chen --source-id team-brain --canonical
+gbrain entity-identity-list --entity-id alice-chen
+gbrain entity-identity-unlink --entity-id alice-chen --slug people/alice --source-id wiki
+```
+
+Members live in the `entity_identities` table (one identity per page;
+re-linking moves the page; at most one canonical member per group). The
+write ops are local-only in v1. Retrieval-side union — `get_links` /
+`get_backlinks` merging edges from a page's identity co-members — is gated
+by the `entity_identity.union` config key (default off) and never widens a
+federated caller's source grant.
+
## Further reading
- [`topologies.md`](./topologies.md) — where the DB lives (operator recipes
diff --git a/docs/designs/VECTOR_BACKENDS.md b/docs/designs/VECTOR_BACKENDS.md
new file mode 100644
index 0000000000..ce14ffdb5b
--- /dev/null
+++ b/docs/designs/VECTOR_BACKENDS.md
@@ -0,0 +1,165 @@
+# Pluggable vector backends: pgvectorscale + VectorChord alongside pgvector (#3673)
+
+Status: **proposal** (maintainer asked for a design before implementation).
+Scope: Postgres engine only — PGLite has no pgvectorscale/VectorChord WASM
+builds and always resolves to `pgvector` (see Degrade path).
+
+## Problem
+
+GBrain's ANN indexing is hardcoded to pgvector HNSW:
+
+1. **Dimension cap.** HNSW indexes at most 2000 dims on `vector` columns and
+ 4000 on `halfvec` (`src/core/vector-index.ts:hnswMaxDimsForType`). Models
+ above that (e.g. a 4096-dim embedding model) lose indexed search entirely
+ and fall back to exact scans — today's degrade path, honest but slow at
+ scale.
+2. **RAM-bound scaling.** HNSW graphs must fit in memory; disk-resident ANN
+ (StreamingDiskANN) scales past that for million-chunk brains.
+3. **No backend choice.** Installed extensions (pgvectorscale, VectorChord)
+ are ignored even when they would serve the brain better.
+
+## Design answers to the three maintainer questions
+
+### 1. Config key shape
+
+ vector.backend = pgvector | pgvectorscale | vchord | auto (default: pgvector)
+
+- Dotted config namespace matches repo convention (`search.mode`, `pace.mode`,
+ `cache.*`); the issue's `embedding_backend` spelling is folded into the
+ `vector.*` namespace where future knobs (`vector.diskann.*` tuning GUCs)
+ will live.
+- Resolution chain mirrors pace-mode (env above config, incident escape
+ hatch; no per-call override — the backend is a property of the INSTALL, not
+ of a query):
+
+ GBRAIN_VECTOR_BACKEND env → config vector.backend → 'pgvector'
+
+- `auto` = probe `pg_extension` once at `initSchema`/connect: pick
+ `pgvectorscale` when installed, else `pgvector`. `vchord` is never
+ auto-selected until phase 2 is proven (explicit opt-in only).
+- The REQUESTED backend (config) and the RESOLVED backend (what the probe
+ actually found usable) are distinct values. The resolved value is what
+ every downstream consumer keys off (index DDL, cache key, doctor). It is
+ re-derived per process from a cheap `pg_extension` lookup — never persisted
+ as truth, so a restored dump onto a host without the extension degrades
+ correctly instead of trusting a stale config row.
+
+### 2. Degrade path when the extension is absent
+
+Fail-open, loud, and recorded — the same posture as the existing
+`chunkEmbeddingIndexSql` dims-too-big skip:
+
+- `initSchema`/migration probes `SELECT extname FROM pg_extension`. If the
+ requested extension is missing, GBrain:
+ 1. warns once per process on stderr
+ (`[vector] vector.backend=pgvectorscale requested but extension not
+ installed — resolved to pgvector`),
+ 2. resolves the backend to `pgvector` and emits pgvector DDL (search keeps
+ working; never a hard failure),
+ 3. surfaces a `gbrain doctor` finding with the exact fix
+ (`CREATE EXTENSION vectorscale CASCADE;` + rebuild command).
+- `CREATE EXTENSION IF NOT EXISTS vectorscale` is attempted (managed hosts
+ like Timescale/self-hosted allow it; Supabase currently does not ship
+ pgvectorscale — the probe result, not the attempt, decides resolution).
+- PGLite: config may carry any value (a brain can be opened by both engines);
+ the PGLite engine always resolves `pgvector` and warns once when the config
+ asks for more. This preserves engine parity of BEHAVIOR (same query
+ results, same SQL operators) while the index access method differs by
+ engine capability.
+- Dimension interplay: each backend gets its own max-dims policy replacing
+ the bare `hnswMaxDimsForType`:
+
+ backendMaxDims('pgvector', 'vector') = 2000
+ backendMaxDims('pgvector', 'halfvec') = 4000
+ backendMaxDims('pgvectorscale', ...) = diskann cap (verify at impl; SBQ
+ lifts it well past 4096)
+ over cap → same "index skipped, exact scan" comment DDL as today
+
+### 3. What the cache key must fold in
+
+`knobsHash` (src/core/search/mode.ts) gains an append-only part:
+
+ vb=<resolved_backend> e.g. vb=pgvectorscale
+
+with a `KNOBS_HASH_VERSION` bump in the same commit (the same discipline as
+the v=10 relationalRetrieval fold). Rationale:
+
+- Two backends are two different ANN approximations over the same vectors —
+ recall sets differ, so a diskann-built result row must never be served to a
+ pgvector-resolved lookup (and vice versa after a backend switch).
+- Folding the RESOLVED backend (not the requested one) means a degraded
+ install (asked for pgvectorscale, got pgvector) shares cache rows with
+ plain pgvector installs — correct, they run identical plans.
+- One-time cold-miss spike on upgrade/backend-switch; refills within
+ `cache.ttl_seconds` (3600s). Same accepted pattern as prior bumps.
+
+## Phase 1 — pgvectorscale (StreamingDiskANN)
+
+Smallest possible diff; everything is DDL-level. pgvectorscale reuses
+pgvector's column types and operators, so **no query SQL changes**:
+
+- `src/core/vector-index.ts`: `chunkEmbeddingIndexSql(dims)` grows a backend
+ parameter → emits `USING diskann (embedding vector_cosine_ops)` when
+ resolved backend is `pgvectorscale` (pure function, unit-testable without a
+ DB). Same treatment for the other emitter sites:
+ `src/schema.sql:336/343` (via `applyChunkEmbeddingIndexPolicy`),
+ `src/core/migrate.ts` takes/facts/query_cache/embedding_image index blocks,
+ and the alt-embedding-column index path.
+- Candidate-pool sizing seam: `hnsw.ef_search` (set transaction-locally in
+ both engines' `searchVector`) has a diskann analogue
+ (`diskann.query_rescore` / search-list sizing). `hnswEfSearchFor` becomes
+ `backendCandidateGucs(backend, candidateLimit)` returning the right
+ `set_config` calls; pgvector path byte-identical to today.
+- Backend switch on an existing brain: reuse the atomic-swap machinery
+ (`vector-index.ts:dropAndRebuild`) — build the diskann index under a temp
+ name, swap, drop HNSW. Exposed as `gbrain embed reindex --backend=<b>`;
+ doctor flags a resolved-backend vs actual-index-method mismatch
+ (`pg_index` joined to `pg_am.amname`) as WARN with that exact command.
+- `gbrain doctor` additions: requested vs resolved backend, extension
+ presence/version, index method per embedding column.
+
+## Phase 2 — VectorChord (vchordrq)
+
+Explicit opt-in only, after phase 1 ships. Modern VectorChord builds its
+`vchordrq` index on pgvector column types (unlike legacy pgvecto.rs, which
+had incompatible column types — the issue's `vchord(N)` column concern; to be
+re-verified at implementation). If column types stay pgvector, phase 2
+collapses to another index-DDL + GUC variant of the phase-1 seam. If a
+target VectorChord version does require its own types, phase 2 must also
+touch `readContentChunksEmbeddingDim`/column-registry parsing and the
+`::vector` casts in both engines — that cost is why it is sequenced second
+and never auto-selected.
+
+## Testing
+
+- Unit (hermetic, always-on): DDL emitter matrix
+ (backend × columnType × dims → exact DDL / skip comment), resolution chain
+ (env > config > default), degrade resolution when the probe reports the
+ extension missing, knobsHash includes `vb=` and the version bump.
+- e2e (DATABASE_URL-gated, extension-gated): against a Postgres with
+ pgvectorscale installed (timescale/timescaledb-ha image in CI or local),
+ assert initSchema builds a diskann index, searchVector returns the same
+ rows as the pgvector baseline on a small fixture (small N → exact-ish
+ recall), and a backend switch rebuild swaps the index without dropping
+ search availability. Skips with a named reason when the extension is
+ absent — the same honest-skip pattern as existing DATABASE_URL gates.
+- Engine parity: `test/e2e/engine-parity.test.ts` continues to compare
+ pglite vs postgres RESULTS; backend choice must not change the parity
+ contract (pgvectorscale returns pgvector-compatible operator semantics).
+
+## Non-goals
+
+- No per-query backend override (cache correctness + index reality make this
+ meaningless).
+- No automatic data migration between column types (phase 2 vchord types, if
+ needed, ship behind an explicit migration command).
+- No benchmark bake-off in-repo — the eval bar is "does an over-4000-dim
+ model get indexed search back", proven by the gated e2e, not a research
+ comparison (per North Star eval discipline).
+
+## Rollout
+
+1. This proposal lands for maintainer review (no behavior change).
+2. Phase 1 PR: config key + resolution + DDL emitters + GUC seam + knobs_hash
+ bump + doctor + gated e2e.
+3. Phase 2 PR: VectorChord, after phase-1 field feedback.
diff --git a/docs/guardrails.md b/docs/guardrails.md
index 7e5b5a6687..3c96443d05 100644
--- a/docs/guardrails.md
+++ b/docs/guardrails.md
@@ -68,8 +68,35 @@ registerGuardrailProvider({
});
```
-Register once at process init (e.g. from a plugin entry or an operator boot
-hook). Registration is idempotent by `id`, so a re-init won't double-fire.
+Registration is idempotent by `id`, so a re-init won't double-fire. There are
+exactly two real wiring paths (#3688):
+
+### Path 1 — embedding gbrain as a library
+
+Import `registerGuardrailProvider` from the public `gbrain/core/guardrails`
+subpath (in the package `exports` map) and register at your process init,
+before any ingest/query runs. This is the path for programs that construct a
+gbrain engine themselves.
+
+### Path 2 — the gbrain CLI: `GBRAIN_GUARDRAILS_MODULE`
+
+Point the env var at a provider module; the CLI imports it at startup, before
+any command dispatch:
+
+```bash
+export GBRAIN_GUARDRAILS_MODULE=/opt/guardrails/my-firewall.ts
+gbrain import notes/ # every seam now consults my-firewall
+```
+
+The module may export any of: a default-exported provider, a default-exported
+provider array, a named `guardrailProviders` array, or a
+`register(registerGuardrailProvider)` function (sync or async).
+
+**Loading is fail-closed.** If `GBRAIN_GUARDRAILS_MODULE` is set but the module
+fails to import or registers zero providers, the CLI exits 1 instead of
+silently running without the firewall you configured. (The *classify* path
+stays fail-open — a registered provider that throws never breaks an ingest.)
+Unset, the variable costs nothing and gbrain stays inert.
### Provider responsibilities
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index 22317413ce..daae46afd6 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -189,7 +189,7 @@ command -v gbrain || { echo "gbrain not on PATH. Install, then retry."; exit 1;
# (Supervisor is Postgres-only. PGLite's exclusive file lock blocks the
# separate worker process. If `config.engine === 'pglite'` the CLI rejects
# with a clear error.)
-gbrain doctor --fast --json | jq '.checks[] | select(.name=="db_connectivity")'
+gbrain doctor --fast --json | jq '.checks[] | select(.name=="connection")'
# 3. Schema is up to date. If version=0 or status=="fail":
# gbrain apply-migrations --yes
@@ -423,8 +423,14 @@ gbrain jobs list --status active --limit 10
# Dead-lettered jobs.
gbrain jobs list --status dead --limit 10
-# Shell handler registered? (check supervisor audit log or worker stderr.)
-gbrain jobs supervisor status --json | jq '.worker_config.allow_shell_jobs'
+# Shell jobs enabled on the worker? There is no supervisor-status JSON field
+# for this — the gate is the GBRAIN_ALLOW_SHELL_JOBS=1 env var on the worker
+# process (the handler is always registered but guarded). Inspect the
+# supervisor's environment directly:
+ps eww -p "$(gbrain jobs supervisor status --json | jq -r '.supervisor_pid')" \
+ | grep -o 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' || echo "flag not set"
+# An unflagged worker that claims a shell job dead-letters it instantly:
+gbrain jobs list --status dead --name shell --limit 3
```
## Uninstall
diff --git a/docs/guides/minions-shell-jobs.md b/docs/guides/minions-shell-jobs.md
index 62875ccf91..9d420afdff 100644
--- a/docs/guides/minions-shell-jobs.md
+++ b/docs/guides/minions-shell-jobs.md
@@ -39,9 +39,12 @@ pass:
`ctx.remote === true` (MCP callers). Independent of the env flag. Remote
agents can never submit shell jobs. `MinionQueue.add('shell', ...)` has its
own guard too, so an in-process handler can't programmatically bypass this.
-2. **Env flag.** The worker only registers the shell handler when
- `GBRAIN_ALLOW_SHELL_JOBS=1` is set on the worker process. Default: off. Your
- agent opts in per-host.
+2. **Env flag.** The shell handler is ALWAYS registered on the worker, but it
+ is guarded: unless `GBRAIN_ALLOW_SHELL_JOBS=1` is set on the worker process,
+ a claimed shell job throws `UnrecoverableError` and goes straight to `dead`
+ (no retries). Default: off. Your agent opts in per-host. (Always-registered
+ guarded mode — not "unregistered", so unflagged workers fail shell jobs
+ loudly instead of leaving them `waiting` forever.)
**What the env allowlist does AND does not do.** Shell jobs run with a minimal
env: `PATH, HOME, USER, LANG, TZ, NODE_ENV`. Your secrets like `OPENAI_API_KEY`
@@ -244,9 +247,13 @@ gbrain jobs get 42
# Submission audit log (operator trail, not forensic)
cat ~/.gbrain/audit/shell-jobs-*.jsonl | jq '.'
-# First-time failure mode: submitted without env flag on the worker
-gbrain jobs list --status waiting --name shell
-# If rows pile up here, no worker with GBRAIN_ALLOW_SHELL_JOBS=1 is running.
+# First-time failure mode: submitted without env flag on the worker.
+# The handler is always registered but guarded: an unflagged worker that claims
+# a shell job dead-letters it immediately (UnrecoverableError, no retries).
+gbrain jobs list --status dead --name shell
+# → error_text: "shell handler disabled on this worker (set GBRAIN_ALLOW_SHELL_JOBS=1 ...)"
+# `waiting` pileups mean NO worker is running at all (flagged or not) — check
+# `gbrain jobs supervisor status` in that case.
```
---
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index 1bf3178c83..e44c4d8256 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -106,3 +106,15 @@ command runs, or Postgres will reject the trigger recreation with
- Keep `GBRAIN_FTS_LANGUAGE` set consistently in every environment that
writes to the brain (CLI shells, MCP server, cron jobs) — a writer without
the env var tokenizes new rows in `english` until the next reindex.
+- **CJK (Chinese / Japanese / Korean):** none of the built-in snowball
+ configurations can tokenize CJK text, so the FTS arm would return nothing
+ for CJK queries. Both engines detect CJK queries and route them to a
+ term-by-term `ILIKE` fallback with term-frequency ranking instead
+ (PGLite since v0.32.7; Postgres since #3986 — shared SQL in
+ `src/core/search/cjk-keyword-sql.ts`). The fallback is correct but not
+ index-accelerated: it scans `content_chunks.chunk_text`, so latency grows
+ with corpus size. Note the routing is query-driven: any query containing
+ CJK characters takes the fallback today, even on a Postgres instance with
+ a CJK-aware extension (`pgroonga` / `zhparser`) installed. Wiring a
+ CJK-capable `GBRAIN_FTS_LANGUAGE` config past the fallback is a filed
+ follow-up.
diff --git a/docs/guides/skillopt.md b/docs/guides/skillopt.md
index 3ac008bbac..119548d6bc 100644
--- a/docs/guides/skillopt.md
+++ b/docs/guides/skillopt.md
@@ -132,6 +132,77 @@ refuses to start when the estimate exceeds `--max-cost-usd`.
| Cost preflight | D3 | Surprise mid-run budget exhaustion |
| Dirty-tree refusal | dry-fix pattern | Overwriting your uncommitted changes |
+## Hardening notes (#4119)
+
+Operational truths that keep a run honest. Read these before trusting a
+score delta.
+
+### Rule judges are gameable — prefer `llm` rubrics for acceptance
+
+`judge: rule` checks (substring / tool-call assertions) are deterministic and
+free, which makes them ideal for smoke coverage — and exactly what a
+skill-text optimizer can overfit. The reflect loop sees failing rollouts and
+can "improve" the skill by teaching the model to emit the literal strings the
+rule checks match, without improving the underlying behavior. Treat rule
+judges as cheap regression pins, not acceptance criteria: any benchmark whose
+score decides a mutation (`D_sel`, `--held-out`) should lean on `llm` rubric
+judges, which grade the trajectory against intent rather than surface tokens.
+A planned n-gram overlap gate (reject candidates whose text copies judge
+strings verbatim) is a tracked follow-up — until it lands, review accepted
+diffs for judge-string echoes before shipping them.
+
+### D13 is a prompt-surface-only limit
+
+Two distinct guarantees get conflated as "the sandbox":
+
+- **D13 (rollout side):** rollouts call a read-only tool allowlist — an
+ optimization run cannot write junk pages into your brain.
+- **D5 + the apply path (mutation side):** the optimizer edits the SKILL BODY
+ MARKDOWN only — the prompt surface. It never touches frontmatter (routing),
+ code, config, or hooks.
+
+The corollary cuts both ways. Nothing outside the prompt surface can be
+damaged by an accepted candidate — but nothing outside the prompt surface can
+be *improved* either. If a benchmark failure is rooted in a missing tool, a
+wrong op contract, or retrieval quality, SkillOpt will at best wordsmith
+around it; fix the code and re-benchmark instead.
+
+### Sizing `--max-cost-usd`
+
+The preflight estimate is a floor, not a ceiling — reflect retries, judge
+re-runs, and the held-out gate add real spend. Rough per-run scaling:
+
+ rollouts ≈ (epochs × steps_per_epoch × batch_size × 1) # forward passes
+ + (accept-gate candidates × |D_sel| × 3) # median-of-3
+ + (|D_test| × 3 × 2) # final + baseline
+ + (--held-out: |held_out| × 3 × 2 per candidate)
+
+Budget ~$0.01 per Sonnet rollout+judge pair and ~$0.03 per Opus reflect call,
+then set `--max-cost-usd` at ~1.5x the estimate so the budget tracker aborts
+runaways without killing honest runs at 95%. A tighter built-in estimator is
+a tracked follow-up. The wall-clock companion knob is `--max-runtime`: the
+deadline is enforced between steps AND inside every gate's rollout loop
+(checked before each individual rollout), so a breach aborts within one
+rollout rather than one batch.
+
+### Hermetic claude-cli rollouts (`CLAUDE_CONFIG_DIR` recipe)
+
+When the target model routes through the `claude-cli:` recipe, each rollout
+child inherits the operator's user-level `~/.claude` state — CLAUDE.md
+memory, `settings.json`, hooks. That contaminates measurements: a skill can
+score well only because YOUR user-level instructions carried it. For hermetic
+runs, set:
+
+ GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1 gbrain skillopt run <skill> ...
+
+`1`/`true` points the child's `CLAUDE_CONFIG_DIR` at an isolated empty
+per-process directory; any other value is used verbatim as the config-dir
+path (pre-seed one if you want a fixed minimal config). **Opt-in on
+purpose:** on non-macOS installs the config dir also holds the OAuth session
+credentials, so the empty-dir form logs the child out there (macOS keeps
+credentials in the keychain and survives). If rollouts start failing auth
+after flipping this on, that is why.
+
## When NOT to use SkillOpt
- **No benchmark.** Optimizing against guesses is worse than not optimizing.
diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.md
index 52d700d5a7..3fa7463c7e 100644
--- a/docs/guides/upgrades-auto-update.md
+++ b/docs/guides/upgrades-auto-update.md
@@ -135,7 +135,7 @@ full_upgrade():
read_and_execute(migration) // in order, don't skip
// Step 5: Schema sync — suggest new, respect declined
- state = read("~/.gbrain/update-state.json")
+ state = read("~/.gbrain/upgrade-state.json")
for recommendation in new_schema_recommendations:
if recommendation not in state.declined:
suggest_to_user(recommendation)
@@ -170,7 +170,9 @@ Prompt: "Run gbrain check-update --json. If update_available is true,
### Frequency Preferences
Default: daily. Store in agent memory as `gbrain_update_frequency: daily|weekly|off`.
-Also persist in `~/.gbrain/update-state.json` so it survives agent context resets.
+Also persist in `~/.gbrain/upgrade-state.json` so it survives agent context resets
+(the runtime's own bookkeeping lives beside it as `~/.gbrain/last-update-check`
+and `~/.gbrain/update-snoozed`).
### Standalone Skillpack Users
diff --git a/docs/mcp/CHATGPT.md b/docs/mcp/CHATGPT.md
index 47b2974e9b..d4ad0ccabd 100644
--- a/docs/mcp/CHATGPT.md
+++ b/docs/mcp/CHATGPT.md
@@ -73,6 +73,32 @@ surface area.
Recommended ChatGPT scope: `read write`. Leave `admin` for your local CLI
and the admin dashboard.
+## Deep research
+
+ChatGPT's **deep research** mode has a stricter MCP contract than normal
+chat: the server must expose a `search`/`fetch` tool PAIR, where every
+`search` result carries an `id` and `fetch(id)` returns
+`{ id, title, text, url, metadata }`. GBrain ships both:
+
+- `search` results carry `id` (the page slug) alongside the native fields.
+- `fetch` takes that `id` and returns the OpenAI shape — `text` is the
+ page's full canonical markdown, `url` is a stable `gbrain://page/...`
+ URI for the citation slot, and `metadata` carries type/source/tags.
+
+`fetch` is a thin read-only adapter over the same page read as `get_page`
+(same source scoping, same privacy fences for remote readers). Normal chat
+keeps using the richer gbrain-native tools; deep research uses the pair.
+
+**DCR zero-scope gotcha.** If the connector registers itself via dynamic
+client registration (`--enable-dcr`) and the registration request omits
+`scope`, the client is registered with an EMPTY scope — and every token it
+mints is zero-scope. The connector then connects fine but every tool call
+(including deep research's `search`/`fetch`) fails with
+`insufficient_scope`. Fix: rescope the client to `read` (or `read write`)
+from the `/admin` dashboard or the CLI, then reconnect. Manual
+registration per step 2 above never hits this — you pick the scopes
+explicitly.
+
## Troubleshooting
**"Invalid redirect_uri" during the ChatGPT connector OAuth handshake**
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index f7cb06a276..04f5ee67c2 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -58,6 +58,18 @@ claude mcp add gbrain -- gbrain serve --surface verbs
That's it. Claude Code spawns `gbrain serve` as a stdio subprocess. No server, no
tunnel, no token needed. Works with both PGLite and Supabase engines.
+> **PGLite brains are single-process.** PGLite is a single-writer embedded
+> Postgres: the first running `gbrain serve` owns the brain's data directory
+> via the data-dir lock, for its whole lifetime. A second `serve` (e.g. a
+> second harness or session registering the same stdio command) — or any CLI
+> command that opens the DB — fails on the lock while that serve is live
+> (`gbrain sync` is the one exception: it delegates to the live serve). If
+> more than one process needs the brain at once, run ONE shared
+> `gbrain serve --http` and point every client at it (Options 2/3 below), or
+> migrate to the Postgres/Supabase engine, which tolerates concurrent
+> connections. Details:
+> [serve ↔ sync concurrency](../architecture/serve-sync-concurrency.md).
+
`--surface verbs` exposes the seven-verb memory protocol (`recall`, `remember`,
`entity`, `synthesize`, `forget`, `context_pack`, `delta` —
[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)),
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index b3843a7b01..fd2be893c4 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -156,6 +156,17 @@ codex mcp remove gbrain
`codex mcp add gbrain -- gbrain serve --surface verbs` — the memory-verb
protocol ([MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)); drop the flag
for the full operation catalog.
+- **PGLite brains are single-process.** PGLite is a single-writer embedded
+ Postgres: the first running `gbrain serve` (the plugin's, or a stdio
+ registration) owns the brain's data directory via the data-dir lock. A
+ second `serve` — say, gbrain registered in a second harness on the same
+ machine — or any CLI command that opens the DB fails on the lock while
+ that serve is live (`gbrain sync` is the one exception: it delegates to
+ the live serve). If multiple processes need the brain at once, run ONE
+ shared `gbrain serve --http` and point every client at it (the remote
+ paths above), or migrate to the Postgres/Supabase engine, which tolerates
+ concurrent connections. Details:
+ [serve ↔ sync concurrency](../architecture/serve-sync-concurrency.md).
- **Ambient recall (Codex has no lifecycle hooks — use the pull path).** At the
start of a topical thread and after a compaction, call
`context_pack(entities, budget_tokens)` to warm the standing entities; on a
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 1a7f98353e..1a3964d578 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -334,6 +334,29 @@ Operator checklist:
Optional defense-in-depth: a dedicated Postgres role (or RLS) limited to the
allowed `source_id`s, so even a leaked connection string can't read everything.
+### Run gbrain under a real init (tini / `--init`)
+
+If `gbrain serve` is your container's entrypoint, it runs as PID 1 and
+inherits every orphaned process in the container. Prefer a real init so
+orphan exits are reaped by something built for the job:
+
+```dockerfile
+# Dockerfile: wrap the entrypoint with tini
+ENTRYPOINT ["/usr/bin/tini", "--", "gbrain", "serve", "--http"]
+```
+
+or at run time:
+
+```bash
+docker run --init ... gbrain serve --http
+```
+
+Without an init, gbrain installs its own PID-1 orphan reaper (Linux only):
+a low-frequency `/proc` scan that `waitpid()`s zombies re-parented to it,
+so long-lived containers don't accumulate defunct entries in the PID table.
+It is fail-open and can be disabled with `GBRAIN_PID1_REAP=0` — but tini /
+`--init` remains the recommended setup.
+
## Troubleshooting
**"missing_auth" error**
diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md
index 249b62040d..e0fe70ab6e 100644
--- a/docs/operations/mcp-surface-runbook.md
+++ b/docs/operations/mcp-surface-runbook.md
@@ -131,8 +131,40 @@ bun run scripts/generate-tool-catalog.ts # refresh the Starter column; freshness
slice. The advisor's drift finding (`mcp_starter_ops_drift`) is the
standing prompt to re-run this move.
+## Move 5 — expose `visibility: private` pages to remote callers (opt-out)
+
+Pages carrying `visibility: private` frontmatter are hidden from every
+remote/untrusted read path by default (fail-closed; trusted local CLI —
+`ctx.remote === false` — always sees everything). The gate covers search +
+recall's query arm, entity cards / context_pack / delta, and the page read
+ops: `get_page` / `fetch` / `list_pages`, `get_chunks` / `get_versions` /
+`get_timeline` / `get_raw_data`, `resolve_slugs`, and
+`get_links` / `get_backlinks` / `traverse_graph`. A gated page reads exactly
+like a missing one (no existence oracle), and link/graph output never
+enumerates private slugs.
+
+Single-user brains where every connected agent is equally trusted can opt
+out:
+
+```bash
+gbrain config set search.remote_private_pages visible # also accepts true / 1
+```
+
+**Expected outcome:** remote reads of private pages resolve again within
+~30s (the trust resolver caches the config per engine for 30s; no restart).
+Clearing the key (`gbrain config set search.remote_private_pages ''`)
+restores enforcement on the same schedule. Resolver:
+`src/core/search/private-visibility.ts`; a failed config read counts as
+"not opted out" (enforce).
+
## Incident levers
+- **`GBRAIN_REMOTE_PRIVATE_PAGES=1`** — operator escape hatch for the
+ private-pages gate (Move 5): the serving process exposes private pages to
+ remote callers regardless of config. Env wins over the config key; unset
+ it to restore the fail-closed default. Use it when the gate itself
+ misbehaves (e.g. a probe error blanking legitimate remote reads) while
+ you diagnose.
- **`GBRAIN_MCP_FORCE_SURFACE=verbs|starter|full`** — narrow-only clamp
(FOV-6a): it `min()`s into every resolved surface and can NEVER widen
past the configured ceiling; widening requires an explicit `--surface`
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 043e970369..bb0b243e05 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -56,6 +56,7 @@ The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to m
| `reindex-code` cost gate | — (preview before re-embed) | — | TTY prompt / non-TTY refuse + exit 2 | `--max-cost off` | informational |
| `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) |
### Sync inline-embed cost gate
@@ -104,6 +105,37 @@ estimate is `delta + stale backlog`, labeled as such.
under-counted may now hit their ceiling; the new number is the honest one, so
raise the cap rather than assuming a regression.
+## Operator price overrides (`pricing.overrides`)
+
+Cost caps are fail-closed: when `--max-cost` (or a phase's default cap) is set
+and a model has no shipped pricing row, the budget tracker aborts with
+`no_pricing` rather than pretend the call is free. Proxy routes hit this by
+design — a LiteLLM endpoint can front a paid provider, so `litellm:*` models
+are deliberately absent from both the pricing tables and the free-local sets.
+
+Declare your real rate in the config plane instead:
+
+```bash
+# Scalar = one USD-per-1M-token rate for input AND output (natural for embeddings):
+gbrain config set pricing.overrides '{"litellm:text-embedding-3-large": 0.13}'
+
+# Object form for chat models with distinct input/output rates:
+gbrain config set pricing.overrides \
+ '{"litellm:gpt-4o": {"input": 2.5, "output": 10}, "litellm:text-embedding-3-large": 0.13}'
+```
+
+Semantics:
+
+- Keys are full `provider:model` strings (case-insensitive, exact match).
+- Overrides win over shipped tables — you own your bill (negotiated rates,
+ markup-charging proxies).
+- Models with neither a table row nor an override stay fail-closed under a cap.
+- Invalid entries (negative, non-numeric) are dropped; those models keep the
+ fail-closed behavior.
+- Consumed by `BudgetTracker` construction (enrich and the cycle's
+ `enrich_thin` phase load it automatically); both chat and embed routes price
+ through it.
+
## Escape hatches at a glance
```bash
diff --git a/docs/schema-author-tutorial.md b/docs/schema-author-tutorial.md
index 62c8ca2ee7..d0ed6a1bec 100644
--- a/docs/schema-author-tutorial.md
+++ b/docs/schema-author-tutorial.md
@@ -17,22 +17,21 @@ That's it. No API keys required for this tutorial — every step works against t
## Step 1: See what pack is active today
```bash
-gbrain schema active --json
+gbrain schema active
```
You'll see something like:
-```json
-{
- "pack_name": "gbrain-base",
- "version": "1.0.0",
- "sha8": "...",
- "page_types_count": 22,
- "source_tier": "default"
-}
+```text
+Active pack: gbrain-base v1.0.0
+Source: default
+Pack identity: ...
+Page types: 22
+Link verbs: 12
+Takes kinds: hot, warm, cold
```
-`source_tier: "default"` means you haven't customized anything — you're on the bundled pack. `page_types_count: 22` is the universal starter (person, company, meeting, note, etc.).
+`Source: default` means you haven't customized anything — you're on the bundled pack. `Page types: 22` is the universal starter (person, company, meeting, note, etc.). (Agents needing this as JSON use the MCP op `get_active_schema_pack` — the CLI subcommand prints human output only.)
**You can't mutate bundled packs directly.** Step 2 forks it so you have something writable.
@@ -54,7 +53,7 @@ gbrain schema use mine
Output: `Pack: mine (json) ... Active.`
-Run `gbrain schema active --json` again to confirm `pack_name` is now `mine` and `source_tier` is `home-config` (read from `~/.gbrain/config.json`).
+Run `gbrain schema active` again to confirm `Active pack:` now says `mine` and `Source:` is `home-config` (read from `~/.gbrain/config.json`).
**You've already accomplished something visible** — the active pack changed, and any future query will route through your fork. The next four steps add a custom type and prove it works.
@@ -214,7 +213,7 @@ gbrain schema lint --with-db
**For agents (MCP):** the same operations are reachable over HTTPS MCP as schema ops. Register an admin-scope OAuth client and `schema_apply_mutations` lets a remote agent compose multi-step refactors as one atomic batch. The batched MCP op + per-pack lock + audit log are the load-bearing primitives that make remote schema authoring safe. See [`skills/schema-author/SKILL.md`](../skills/schema-author/SKILL.md) for the agent dispatcher.
-**Undo a mistake.** Every mutation primitive has an inverse (`remove-type`, `remove-alias`, `remove-prefix`, `remove-link-type`, `set-extractable false`, etc.). If you fork twice and want to revert, `gbrain schema downgrade` restores the previous active pack from `~/.gbrain/schema-pack-history.jsonl`.
+**Undo a mistake.** Every mutation primitive has an inverse (`remove-type`, `remove-alias`, `remove-prefix`, `remove-link-type`, `set-extractable false`, etc.). If you fork twice and want to revert, `gbrain schema downgrade --to <pack>` re-activates the pack you name (e.g. `--to gbrain-base`). The bare history-based form depends on `~/.gbrain/schema-pack-history.jsonl`, which nothing writes today — always pass `--to`.
## Related docs
diff --git a/llms-full.txt b/llms-full.txt
index 8731140596..0485700a4e 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1298,6 +1298,17 @@ diff against gbrain's bundle when you want upstream improvements. (The legacy
`gbrain skillpack install` managed-block model was removed in v0.33 — run
`gbrain skillpack migrate-fence` once if upgrading from an older release.)
+> **PGLite brains are single-process (applies to every MCP registration
+> below).** PGLite is a single-writer embedded Postgres: the first running
+> `gbrain serve` owns the brain's data directory via the data-dir lock. A
+> second `serve` (gbrain registered in two harnesses on the same machine) —
+> or any CLI command that opens the DB — fails on the lock while that serve
+> is live (`gbrain sync` is the one exception: it delegates to the live
+> serve). If multiple processes need the brain at once, run ONE shared
+> `gbrain serve --http` and point every client at it, or migrate to the
+> Postgres/Supabase engine, which tolerates concurrent connections. Details:
+> [docs/architecture/serve-sync-concurrency.md](docs/architecture/serve-sync-concurrency.md).
+
**If you are Hermes:** register gbrain as your MCP server:
```bash
@@ -2777,22 +2788,21 @@ That's it. No API keys required for this tutorial — every step works against t
## Step 1: See what pack is active today
```bash
-gbrain schema active --json
+gbrain schema active
```
You'll see something like:
-```json
-{
- "pack_name": "gbrain-base",
- "version": "1.0.0",
- "sha8": "...",
- "page_types_count": 22,
- "source_tier": "default"
-}
+```text
+Active pack: gbrain-base v1.0.0
+Source: default
+Pack identity: ...
+Page types: 22
+Link verbs: 12
+Takes kinds: hot, warm, cold
```
-`source_tier: "default"` means you haven't customized anything — you're on the bundled pack. `page_types_count: 22` is the universal starter (person, company, meeting, note, etc.).
+`Source: default` means you haven't customized anything — you're on the bundled pack. `Page types: 22` is the universal starter (person, company, meeting, note, etc.). (Agents needing this as JSON use the MCP op `get_active_schema_pack` — the CLI subcommand prints human output only.)
**You can't mutate bundled packs directly.** Step 2 forks it so you have something writable.
@@ -2814,7 +2824,7 @@ gbrain schema use mine
Output: `Pack: mine (json) ... Active.`
-Run `gbrain schema active --json` again to confirm `pack_name` is now `mine` and `source_tier` is `home-config` (read from `~/.gbrain/config.json`).
+Run `gbrain schema active` again to confirm `Active pack:` now says `mine` and `Source:` is `home-config` (read from `~/.gbrain/config.json`).
**You've already accomplished something visible** — the active pack changed, and any future query will route through your fork. The next four steps add a custom type and prove it works.
@@ -2974,7 +2984,7 @@ gbrain schema lint --with-db
**For agents (MCP):** the same operations are reachable over HTTPS MCP as schema ops. Register an admin-scope OAuth client and `schema_apply_mutations` lets a remote agent compose multi-step refactors as one atomic batch. The batched MCP op + per-pack lock + audit log are the load-bearing primitives that make remote schema authoring safe. See [`skills/schema-author/SKILL.md`](../skills/schema-author/SKILL.md) for the agent dispatcher.
-**Undo a mistake.** Every mutation primitive has an inverse (`remove-type`, `remove-alias`, `remove-prefix`, `remove-link-type`, `set-extractable false`, etc.). If you fork twice and want to revert, `gbrain schema downgrade` restores the previous active pack from `~/.gbrain/schema-pack-history.jsonl`.
+**Undo a mistake.** Every mutation primitive has an inverse (`remove-type`, `remove-alias`, `remove-prefix`, `remove-link-type`, `set-extractable false`, etc.). If you fork twice and want to revert, `gbrain schema downgrade --to <pack>` re-activates the pack you name (e.g. `--to gbrain-base`). The bare history-based form depends on `~/.gbrain/schema-pack-history.jsonl`, which nothing writes today — always pass `--to`.
## Related docs
@@ -4696,6 +4706,29 @@ Operator checklist:
Optional defense-in-depth: a dedicated Postgres role (or RLS) limited to the
allowed `source_id`s, so even a leaked connection string can't read everything.
+### Run gbrain under a real init (tini / `--init`)
+
+If `gbrain serve` is your container's entrypoint, it runs as PID 1 and
+inherits every orphaned process in the container. Prefer a real init so
+orphan exits are reaped by something built for the job:
+
+```dockerfile
+# Dockerfile: wrap the entrypoint with tini
+ENTRYPOINT ["/usr/bin/tini", "--", "gbrain", "serve", "--http"]
+```
+
+or at run time:
+
+```bash
+docker run --init ... gbrain serve --http
+```
+
+Without an init, gbrain installs its own PID-1 orphan reaper (Linux only):
+a low-frequency `/proc` scan that `waitpid()`s zombies re-parented to it,
+so long-lived containers don't accumulate defunct entries in the PID table.
+It is fail-open and can be disabled with `GBRAIN_PID1_REAP=0` — but tini /
+`--init` remains the recommended setup.
+
## Troubleshooting
**"missing_auth" error**
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index ba4afdb4ff..49465788c2 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.27.0",
+ "version": "0.46.28.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 9a7ffbc7fb..344a0b1082 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"./ai/gateway": "./src/core/ai/gateway.ts",
"./extract": "./src/commands/extract.ts",
"./ingestion": "./src/core/ingestion/index.ts",
- "./ingestion/test-harness": "./src/core/ingestion/test-harness.ts"
+ "./ingestion/test-harness": "./src/core/ingestion/test-harness.ts",
+ "./core/guardrails": "./src/core/guardrails.ts"
},
"scripts": {
"dev": "bun run src/cli.ts",
@@ -170,7 +171,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.27.0",
+ "version": "0.46.28.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.json
index 1de58ad2da..0af0983d93 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.27.0",
+ "version": "0.46.28.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/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 5e259aeb04..3dabc979d3 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.27.0",
+ "version": "0.46.28.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.md
index b86c708dcd..716fb87d91 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.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
index 8c392ddf81..16c6efdcff 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
@@ -32,8 +32,9 @@ Override priority (highest first):
1. CLI flag (`--model opus`)
2. Per-task config (`gbrain config set models.dream.synthesize opus`)
3. Deprecated per-task config (stderr-warns once, then honored)
-4. **Global default** (`gbrain config set models.default opus`) — single hammer
-5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
+4. **Tier override** (`gbrain config set models.tier.reasoning opus`) —
+ tier-specific beats the generic default (#3873)
+5. **Global default** (`gbrain config set models.default opus`) — single hammer
6. Env var (`GBRAIN_MODEL=opus`)
7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 471db7c74e..ac9af03505 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.27.0",
+ "version": "0.46.28.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/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index a1cce5ddd6..c2e74d54f4 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.27.0",
+ "version": "0.46.28.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.md
index 9bf4407737..e9952cbfdb 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.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
index 8c392ddf81..16c6efdcff 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
@@ -32,8 +32,9 @@ Override priority (highest first):
1. CLI flag (`--model opus`)
2. Per-task config (`gbrain config set models.dream.synthesize opus`)
3. Deprecated per-task config (stderr-warns once, then honored)
-4. **Global default** (`gbrain config set models.default opus`) — single hammer
-5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
+4. **Tier override** (`gbrain config set models.tier.reasoning opus`) —
+ tier-specific beats the generic default (#3873)
+5. **Global default** (`gbrain config set models.default opus`) — single hammer
6. Env var (`GBRAIN_MODEL=opus`)
7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
diff --git a/plugin/README.md b/plugin/README.md
index 6e4edc201c..be13b293f5 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.28.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/conventions/model-routing.md b/plugin/skills/conventions/model-routing.md
index 8c392ddf81..16c6efdcff 100644
--- a/plugin/skills/conventions/model-routing.md
+++ b/plugin/skills/conventions/model-routing.md
@@ -32,8 +32,9 @@ Override priority (highest first):
1. CLI flag (`--model opus`)
2. Per-task config (`gbrain config set models.dream.synthesize opus`)
3. Deprecated per-task config (stderr-warns once, then honored)
-4. **Global default** (`gbrain config set models.default opus`) — single hammer
-5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
+4. **Tier override** (`gbrain config set models.tier.reasoning opus`) —
+ tier-specific beats the generic default (#3873)
+5. **Global default** (`gbrain config set models.default opus`) — single hammer
6. Env var (`GBRAIN_MODEL=opus`)
7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
diff --git a/recipes/retrieval-reflex/install/manifest.json b/recipes/retrieval-reflex/install/manifest.json
index ec89d64161..5182bc2853 100644
--- a/recipes/retrieval-reflex/install/manifest.json
+++ b/recipes/retrieval-reflex/install/manifest.json
@@ -11,6 +11,6 @@
{ "src": "skills/retrieval-reflex/SKILL.md", "target": "skills/retrieval-reflex/SKILL.md", "mode": "0644" }
],
"resolver_rows_to_append": [
- "retrieval-reflex | a named person/company/project/place becomes the subject; a brain-page pointer appears in context; \"who is\", \"what do we know about\", \"tell me about\"; about to assert a non-trivial detail about a named entity"
+ "retrieval-reflex | a named person/company/project/place becomes the subject mid-conversation; a brain-page pointer appears in context; about to assert a non-trivial detail about a named entity from memory (explicit lookup questions route to the query skill)"
]
}
diff --git a/recipes/retrieval-reflex/install/post-install-hint.md b/recipes/retrieval-reflex/install/post-install-hint.md
new file mode 100644
index 0000000000..4972a55a94
--- /dev/null
+++ b/recipes/retrieval-reflex/install/post-install-hint.md
@@ -0,0 +1,45 @@
+# Post-install hint
+
+When `gbrain integrations install retrieval-reflex --target <repo>` completes,
+print this to stdout (or to the install agent's conversation surface) so the
+operator knows what to do next.
+
+---
+
+✓ Retrieval-reflex policy skill installed to `<target-repo>/skills/retrieval-reflex/`.
+
+**Three follow-up steps:**
+
+### 1. Confirm the deterministic pointer layer is healthy
+
+```bash
+gbrain doctor --json | jq '.checks[] | select(.name=="retrieval_reflex_health")'
+```
+
+The pointer layer lives in the gbrain context engine (zero-LLM, on by
+default) — nothing to install. If the check reports it disabled, the policy
+skill alone still carries the behavior; the check output says which.
+
+### 2. Review the appended resolver row
+
+This install appended one row to your `<target>/RESOLVER.md` (or `AGENTS.md`):
+
+```
+retrieval-reflex | a named person/company/project/place becomes the subject mid-conversation; ...
+```
+
+The row is deliberately REFLEX-ONLY. Explicit lookup questions ("who is X",
+"tell me about Y", "what do we know about Z") belong to your query/search
+skill — do not add those phrases to this row, or the two skills will contend
+for the same requests and routing becomes ambiguous.
+
+### 3. Update later
+
+When gbrain ships a new retrieval-reflex policy, refresh your local copy:
+
+```bash
+gbrain integrations install retrieval-reflex --target <target-repo> --refresh
+```
+
+Local edits are preserved by default; pass `--auto take-theirs` to take
+upstream everywhere, or `--dry-run` to preview.
diff --git a/recipes/retrieval-reflex/skills/retrieval-reflex/SKILL.md b/recipes/retrieval-reflex/skills/retrieval-reflex/SKILL.md
index a2bdc804ae..cb0032dd0e 100644
--- a/recipes/retrieval-reflex/skills/retrieval-reflex/SKILL.md
+++ b/recipes/retrieval-reflex/skills/retrieval-reflex/SKILL.md
@@ -2,10 +2,13 @@
name: retrieval-reflex
version: 0.1.0
description: When/what to retrieve — open the brain page for a salient entity before answering from memory.
+# Reflex-only triggers (#4292): direct lookup questions ("who is", "tell
+# me about", ...) route to skills/query — this skill fires on the ambient
+# retrieve-before-answering reflex, not on explicit search requests.
triggers:
- - "who is"
- - "what do we know about"
- - "tell me about"
+ - "a named entity becomes the subject of the exchange"
+ - "a brain-page pointer appeared in context"
+ - "about to assert a detail about an entity from memory"
mutating: false
writes_pages: false
writes_to: []
diff --git a/scripts/build-schema.sh b/scripts/build-schema.sh
index 7440fba267..5876eba8d2 100755
--- a/scripts/build-schema.sh
+++ b/scripts/build-schema.sh
@@ -1,10 +1,12 @@
#!/bin/bash
-# Generate src/core/schema-embedded.ts from src/schema.sql
+# Generate src/core/schema-embedded.generated.ts from src/schema.sql
+# (.generated.ts suffix: module-size ratchet + other source-file guards exempt
+# generated files by that naming convention)
# One source of truth: schema.sql is the canonical file.
# This script produces a TypeScript constant for use in compiled binaries.
set -e
SCHEMA_FILE="src/schema.sql"
-OUT_FILE="src/core/schema-embedded.ts"
+OUT_FILE="src/core/schema-embedded.generated.ts"
echo "// AUTO-GENERATED — do not edit. Run: bun run build:schema" > "$OUT_FILE"
echo "// Source: $SCHEMA_FILE" >> "$OUT_FILE"
echo "" >> "$OUT_FILE"
diff --git a/scripts/check-exports-count.sh b/scripts/check-exports-count.sh
index 45cc056ac8..490a9b2675 100755
--- a/scripts/check-exports-count.sh
+++ b/scripts/check-exports-count.sh
@@ -19,7 +19,7 @@
set -euo pipefail
-EXPECTED_COUNT=21
+EXPECTED_COUNT=22
# Count top-level keys in the exports object. `node -e` parses JSON
# reliably without needing jq (which isn't in every CI environment).
diff --git a/scripts/check-jsonb-pattern.sh b/scripts/check-jsonb-pattern.sh
index 5365379d92..eef06614c6 100755
--- a/scripts/check-jsonb-pattern.sh
+++ b/scripts/check-jsonb-pattern.sh
@@ -50,7 +50,7 @@ MAX_STALLED_PATTERN='max_stalled\s+INTEGER\s+NOT\s+NULL\s+DEFAULT\s+1\b'
# Schema files are fixed paths; under a fixture root (self-test) they don't
# exist — skip rather than fail on the missing-file grep.
SCHEMA_FILES=()
-for f in src/schema.sql src/core/migrate.ts src/core/pglite-schema.ts src/core/schema-embedded.ts; do
+for f in src/schema.sql src/core/migrate.ts src/core/pglite-schema.ts src/core/schema-embedded.generated.ts; do
[ -f "$f" ] && SCHEMA_FILES+=("$f")
done
if [ "${#SCHEMA_FILES[@]}" -gt 0 ] && grep -rEn "$MAX_STALLED_PATTERN" "${SCHEMA_FILES[@]}" 2>/dev/null; then
diff --git a/scripts/check-search-path.sh b/scripts/check-search-path.sh
index 8158d94893..8015f4844d 100755
--- a/scripts/check-search-path.sh
+++ b/scripts/check-search-path.sh
@@ -21,7 +21,7 @@ set -euo pipefail
ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT"
-FILES="src/schema.sql src/core/pglite-schema.ts src/core/schema-embedded.ts"
+FILES="src/schema.sql src/core/pglite-schema.ts src/core/schema-embedded.generated.ts"
# A hardened header reads `... RETURNS trigger SET search_path = ... AS $tag$`.
# An UNHARDENED one reads `... RETURNS trigger AS $tag$` — match that form and
diff --git a/scripts/check-test-discriminates.sh b/scripts/check-test-discriminates.sh
new file mode 100755
index 0000000000..233f44c3f4
--- /dev/null
+++ b/scripts/check-test-discriminates.sh
@@ -0,0 +1,123 @@
+#!/usr/bin/env bash
+# scripts/check-test-discriminates.sh — does this test actually pin the fix? (#3665)
+#
+# A fix's test is only worth anything if it FAILS without the fix. This helper
+# makes that a one-command local check so the PR template's required
+# "Discrimination test" field is trivial to fill honestly:
+#
+# bash scripts/check-test-discriminates.sh <test-file> <source-file> [<source-file>...]
+#
+# What it does:
+# 1. Saves the named source files aside (plain file copies — no git stash, so
+# concurrent worktree users are never disturbed).
+# 2. Reverts each source file to its pre-fix state:
+# - dirty file (uncommitted fix) → content from HEAD
+# - clean file (committed fix) → content from $DISCRIMINATE_BASE
+# (default: merge-base with origin/master, falling back to HEAD~1)
+# A file that does not exist in the base ref is removed (its pre-fix
+# state is nonexistence).
+# 3. Runs `bun test <test-file>` and parses the pass/fail counts.
+# 4. Restores the source files (also on ^C / error — trap'd).
+#
+# Exit codes:
+# 0 DISCRIMINATES — the test fails against the pre-fix source (>=1 test ran
+# and failed).
+# 1 DOES NOT DISCRIMINATE — the test passes with the fix reverted. The test
+# is green both ways and pins nothing (the #3665 class).
+# 3 VACUOUS FAILURE — non-zero exit but zero executed-test failures (import
+# crash, missing file, bash 127). A missing binary also exits non-zero;
+# that is not discrimination (the #3573 class).
+# 2 usage / setup error.
+#
+# NOT wired into CI: the script cannot know which hunk is "the fix" on an
+# arbitrary diff. It exists so the author can, in two minutes, produce the
+# reviewable claim the PR template asks for.
+
+set -uo pipefail
+
+usage() {
+ echo "usage: bash scripts/check-test-discriminates.sh <test-file> <source-file> [<source-file>...]" >&2
+ echo "env: DISCRIMINATE_BASE=<ref> pre-fix ref for committed fixes (default: merge-base with origin/master)" >&2
+ exit 2
+}
+
+[ $# -ge 2 ] || usage
+TEST_FILE="$1"; shift
+SOURCES=("$@")
+
+cd "$(dirname "$0")/.."
+
+[ -f "$TEST_FILE" ] || { echo "[discriminate] test file not found: $TEST_FILE" >&2; exit 2; }
+for f in "${SOURCES[@]}"; do
+ [ -f "$f" ] || { echo "[discriminate] source file not found: $f" >&2; exit 2; }
+ case "$f" in
+ test/*) echo "[discriminate] $f is a test file — pass source files after the test file" >&2; exit 2 ;;
+ esac
+done
+
+BASE_REF="${DISCRIMINATE_BASE:-}"
+if [ -z "$BASE_REF" ]; then
+ BASE_REF="$(git merge-base HEAD origin/master 2>/dev/null || true)"
+ [ -n "$BASE_REF" ] || BASE_REF="HEAD~1"
+fi
+
+SAVE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/discriminate.XXXXXX")"
+restore() {
+ local i=0
+ for f in "${SOURCES[@]}"; do
+ if [ -f "$SAVE_DIR/$i" ]; then
+ cp "$SAVE_DIR/$i" "$f"
+ fi
+ i=$((i + 1))
+ done
+ rm -rf "$SAVE_DIR"
+}
+trap restore EXIT INT TERM
+
+i=0
+for f in "${SOURCES[@]}"; do
+ cp "$f" "$SAVE_DIR/$i"
+ if git diff --quiet -- "$f" 2>/dev/null; then
+ # Clean file: the fix is committed — revert to the pre-fix base ref.
+ if git cat-file -e "$BASE_REF:$f" 2>/dev/null; then
+ git show "$BASE_REF:$f" > "$f"
+ echo "[discriminate] reverted $f to $BASE_REF" >&2
+ else
+ rm -f "$f"
+ echo "[discriminate] $f does not exist at $BASE_REF — removed (pre-fix state is nonexistence)" >&2
+ fi
+ else
+ # Dirty file: the fix is uncommitted — revert to HEAD.
+ git show "HEAD:$f" > "$f" 2>/dev/null || { rm -f "$f"; echo "[discriminate] $f is new+uncommitted — removed" >&2; }
+ echo "[discriminate] reverted $f to HEAD (uncommitted fix)" >&2
+ fi
+ i=$((i + 1))
+done
+
+OUT="$(mktemp "${TMPDIR:-/tmp}/discriminate-out.XXXXXX")"
+bun test --timeout=60000 "$TEST_FILE" > "$OUT" 2>&1
+TEST_EXIT=$?
+restore
+trap - EXIT INT TERM
+
+FAILS="$(grep -Eo '^[[:space:]]*[0-9]+ fail' "$OUT" | grep -Eo '[0-9]+' | tail -1)"
+PASSES="$(grep -Eo '^[[:space:]]*[0-9]+ pass' "$OUT" | grep -Eo '[0-9]+' | tail -1)"
+FAILS="${FAILS:-0}"
+PASSES="${PASSES:-0}"
+
+echo "[discriminate] pre-fix run: exit=$TEST_EXIT pass=$PASSES fail=$FAILS (full output: $OUT)" >&2
+
+if [ "$TEST_EXIT" -eq 0 ]; then
+ echo "[discriminate] DOES NOT DISCRIMINATE: $TEST_FILE passes with the fix reverted." >&2
+ echo "[discriminate] The test is green both ways and pins nothing — tighten its assertions." >&2
+ exit 1
+fi
+if [ "$FAILS" -eq 0 ]; then
+ echo "[discriminate] VACUOUS FAILURE: non-zero exit but no executed test failed (crash/127?)." >&2
+ echo "[discriminate] A missing file also exits non-zero — that is not discrimination." >&2
+ exit 3
+fi
+
+echo "[discriminate] OK: test fails against the pre-fix source ($FAILS failing). Paste into the PR:" >&2
+echo "Discrimination test: reverted ${SOURCES[*]} to ${DISCRIMINATE_BASE:-merge-base}, ran $TEST_FILE → $PASSES pass / $FAILS fail. Restored → all pass."
+exit 0
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 178a8b82ca..c4cd4dc310 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -67,3 +67,4 @@ check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-sui
check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
check-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.ts
check-getpage-scoped-write.mjs scanner yes unscoped-getPage + write co-occurrence scanner (source-isolation bug class); argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
+check-test-discriminates.sh buildfresh exempt manual per-PR discrimination helper (#3665): reverts named source files to their pre-fix state and runs the named test file to prove it fails without the fix — the test run IS the check; not in verify CHECKS or CI
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 568b910bb6..56b4bc8309 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,37 +3,38 @@
# 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 4366 ratchet grown v0.46.25.0 fix waves: sunset-aware search-mode check, dead-check pruning (#3626 #1871 #4382)
-src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
-src/core/postgres-engine.ts 6016 ratchet grown v0.46.25.0 fix waves (#1262 #3827 #4389) + v0.46.26.0: private-queue token bootstrap probe
-src/core/pglite-engine.ts 5971 ratchet grown v0.46.24.0 overnight wave: registry-aware writes + stale/invalidate plane unification (#1262); peeled cjk-search (#4299)
-src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
-src/commands/sync.ts 4334 ratchet grown v0.46.25.0 fix waves: delete-slug resolver + msys healing (#3942 #2955)
-src/core/ai/gateway.ts 4441 ratchet grown v0.46.25.0 D2: env-key snapshot stash (#2119)
-src/cli.ts 3628 ratchet grown v0.46.25.0 D2: stdout interposer install (#4383)
-src/core/cycle.ts 3123 ratchet grown v0.46.25.0 fix waves (#4309 #2821) + v0.46.26.0: cycle-start orphan recovery
+src/commands/doctor.ts 4422 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958)
+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/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 4512 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)
+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 3093 ratchet grown v0.46.25.0 (--json #3685) + v0.46.26.0: maybeRunWorkerStartupRecovery extraction + stats gating + help text
-src/core/search/hybrid.ts 2703 ratchet grown v0.46.25.0 fix waves: cache scope isolation + pool floor + offset bypass (#3871 #3002)
-src/core/engine.ts 2415 ratchet grown v0.46.25.0 fix waves: timeline dedup contract + registry write contract (#3827 #1262)
-src/commands/autopilot.ts 2487 ratchet grown: daemon env-file lane + boot warning + reload-safe install (#2608 #4443)
-src/commands/extract.ts 2066 ratchet lowered: timeline extractor hoisted to core/timeline-extract.ts (module-cycle fix)
+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/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 2016 ratchet grown v0.46.24.0 overnight wave: embedding_plane_split named error (#4287)
-src/core/cycle/synthesize.ts 2725 ratchet merged waves + v0.46.26.0: rolling lease via shared throttled renewer
-src/commands/embed.ts 2046 ratchet grown v0.46.25.0 delegated wave (#3971)
-src/core/types.ts 1882 ratchet grown v0.46.22.0 phone wave: supersession rerank result fields + effective-date page filters (#4056 #4389)
+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/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 ratchet
-src/core/minions/queue.ts 2423 ratchet grown v0.46.26.0 private-queue lifecycle: recovery classifier + monotonic lease + makeThrottledLeaseRenewer
+src/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease
src/commands/init.ts 1950 ratchet grown v0.46.x keyless capability notices
-src/commands/integrations.ts 1733 ratchet grown v0.46.24.0 overnight wave (#3588)
+src/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/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 wave
src/commands/sources.ts 1790 ratchet grown v0.46.22.0 phone wave: github source kind (#4104)
-src/core/link-extraction.ts 1467 ratchet grown v0.46.25.0 delegated wave (#3939 #3723); lowered: stripCodeBlocks + citation loop peeled to markdown-code.ts/timeline-citations.ts (#3892 adoption)
+src/core/link-extraction.ts 1681 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737)
src/core/embedding-migration.ts 1545 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers)
src/core/github-source.ts 1560 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment)
src/core/bootstrap/harness.ts 1947 ratchet
-src/commands/hook.ts 1550 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth
-src/core/schema-embedded.ts 1504 ratchet grown v0.46.26.0: private-queue columns + recovery indexes in the embedded blob
+src/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)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index c05bd5a224..228b05a887 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -8,7 +8,9 @@ test/agent-register.test.ts structural guards 2 readFileSync
test/apply-migrations.test.ts failed migration prints phase detail (#921) 1 readFileSync
test/apply-migrations.test.ts resolveSchemaBehind (#1530) 5 readFileSync
test/apply-migrations.test.ts runApplyMigrations exit codes (v0.36.1.x #1062) 1 readFileSync
+test/archived-source-scoping.test.ts #3880 structural pins — all-source local_path selections filter archived 2 readFileSync
test/asymmetric-encoding-contract.test.ts Source-text contract (cheap belt + suspenders) 3 readFileSync
+test/auto-link-targeted-probe-2544.test.ts #2544 — auto-link behavior through put_page (targeted probe) 6 readFileSync
test/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileSync
test/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSync
test/autopilot-cycle-failure-classification.test.ts runPhaseOrphans ratio threshold — no more absolute count > 20 3 readFileSync
@@ -19,6 +21,7 @@ test/autopilot-install.test.ts autopilot wiring: chat-unavailable boot warning (
test/autopilot-install.test.ts autopilot wrapper script — bun PATH export (v0.42.x regression) 1 readFileSync
test/autopilot-install.test.ts autopilot wrapper script — env source order (v0.36.1.x #966) 1 readFileSync
test/autopilot-install.test.ts autopilot wrapper script — gbrain-owned env file (#2608) 5 readFileSync
+test/autopilot-install.test.ts autopilot wrapper script — key sourcing (#2608) 1 readFileSync
test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readFileSync
test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 readFileSync
test/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 6 readFileSync
@@ -36,10 +39,12 @@ test/brainstorm-timeout.test.ts orchestrator entry-point wrap (CV11 single-point
test/build-llms.test.ts CLAUDE.md restructure content contracts 5 readFileSync
test/build-llms.test.ts build-llms generator 7 readFileSync
test/canonical-migration-command.test.ts canonical migration command (single home: ai/defaults.ts) 5 doctor-source-helper
+test/chat-key-plane.test.ts #3944 both planner surfaces share the helper (source guard) 2 readFileSync
test/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync
test/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSync
test/check-update.test.ts check-update CLI 3 bun-file
test/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSync
+test/chronicle-extract.test.ts runChronicleExtract 9 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — abort + error envelopes 13 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — context isolation 2 readFileSync
test/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip 4 readFileSync
@@ -118,6 +123,8 @@ test/eval-brainbench-e2e.test.ts privacy guard violation branches (negative path
test/eval-brainbench-e2e.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
test/eval-brainbench-e2e.test.ts run-all once-per-sweep semantics (decision 16) 1 exec-scan
test/eval-capture-db-plane.serial.test.ts eval.capture set on the DB plane reaches the runtime gate (#1475) 9 bun-file
+test/eval-synthesize-concepts-routing.test.ts dispatch-layer source pins (routing can’t regress silently) 2 readFileSync
+test/eval-synthesize-concepts-routing.test.ts subprocess smoke — end-to-end routing 1 readFileSync
test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync
test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 2 readFileSync
test/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSync
@@ -141,6 +148,7 @@ test/hook-command.serial.test.ts user-prompt 14 readFileSync
test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
test/integrations.test.ts CLI integration 3 readFileSync
test/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSync
+test/jobs-gateway-refresh-set.test.ts #3387 — GATEWAY_REFRESH_JOB_NAMES ⇔ registerBuiltinJob call sites 5 readFileSync
test/jobs-list-get-json.serial.test.ts help advertises --json on list/get/stats (#3685) 2 readFileSync
test/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 readFileSync
test/jobs-worker-startup-recovery.test.ts work-handler recovery placement (structural) 1 readFileSync
@@ -173,6 +181,7 @@ test/migrations-v0_14_0.test.ts Bug 8 — max_stalled default bumped in schema f
test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 9 readFileSync
test/model-pricing.test.ts no heavy import (cycle guard) 1 readFileSync
test/models-doctor-embed.test.ts models doctor — embedding reachability probe (v0.40.x) 3 readFileSync
+test/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (#3973) 1 doctor-source-helper
test/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing bundled points at a non-bundled skill) 1 readFileSync
test/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSync
test/openclaw-plugin-manifest.test.ts root OpenClaw plugin manifest 2 readFileSync
@@ -182,15 +191,20 @@ test/phantom-redirect-per-source-lock.test.ts phantom-redirect lock contract 3 r
test/postgres-engine-singleton-ownership.test.ts postgres-engine / module-singleton ownership (#1471) 7 readFileSync
test/postgres-engine.test.ts postgres-engine / search date filtering 1 readFileSync
test/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 readFileSync
+test/private-visibility.test.ts shared private predicate lives once (#4352 remediation) 1 readFileSync
test/readme-hero-anchors.test.ts README hero anchors (D9 regression guard) 5 readFileSync
test/redos-hardening.test.ts #1569 --no-schema-pack + heartbeat wiring (structural) 2 readFileSync
+test/redos-hardening.test.ts megawave vm-watchdog removal (bootstrap-verify freeze) 5 readFileSync
test/register-client-source-normalize.test.ts register-client route wiring (structural) 1 readFileSync
test/regression-strict-source-id.test.ts cycle reverse-write call sites use the consolidated path 4 readFileSync
test/regression-strict-source-id.test.ts utils.ts no longer carries an inline permissive regex 2 readFileSync
+test/reindex-code-recovery.test.ts CLI help line (#3970 surface 1) 1 readFileSync
test/release-workflow.test.ts release.yml ↔ binary-self-update asset contract 10 readFileSync
+test/remediation-command-resolution.test.ts #3697 — remediation text resolves against the live CLI surface 3 readFileSync
test/reranker-default-seam.test.ts LEGACY_DEFAULT_RERANKER_MODEL seam (#3657) 4 readFileSync
test/resolver.test.ts RESOLVER.md trigger round-trip (D5/C) 2 readFileSync
test/resolver.test.ts Skill example-name validator (D13) 4 readFileSync
+test/retrieval-reflex-recipe-routing.test.ts retrieval-reflex recipe routing is MECE with the query skill (#4292) 5 readFileSync
test/schema-cli-contract.test.ts v0.39 T6 — schema CLI contract 7 readFileSync
test/schema-pack-unify-types-handler.test.ts #1575 unify-types worker dry-run default 1 readFileSync
test/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSync
diff --git a/skills/conventions/model-routing.md b/skills/conventions/model-routing.md
index 8c392ddf81..16c6efdcff 100644
--- a/skills/conventions/model-routing.md
+++ b/skills/conventions/model-routing.md
@@ -32,8 +32,9 @@ Override priority (highest first):
1. CLI flag (`--model opus`)
2. Per-task config (`gbrain config set models.dream.synthesize opus`)
3. Deprecated per-task config (stderr-warns once, then honored)
-4. **Global default** (`gbrain config set models.default opus`) — single hammer
-5. **Tier override** (`gbrain config set models.tier.reasoning opus`)
+4. **Tier override** (`gbrain config set models.tier.reasoning opus`) —
+ tier-specific beats the generic default (#3873)
+5. **Global default** (`gbrain config set models.default opus`) — single hammer
6. Env var (`GBRAIN_MODEL=opus`)
7. Key-aware tier default (the table above; provider chosen by which keys exist)
8. Hardcoded caller fallback
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index b4e95627f9..e92ba43952 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -48,7 +48,7 @@
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
"conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",
- "conventions/model-routing.md": "a8d2010b3cf59d45812e9e744470cfc4426b8928ddae1ce312443e352b976685",
+ "conventions/model-routing.md": "c1aba7a5c34454d6913edadb52ec7b53a3741f318c47fab6a26d5214479a8532",
"conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954",
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",
diff --git a/src/cli.ts b/src/cli.ts
index 3f905d5c51..f980b66109 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -193,6 +193,12 @@ const CLI_ONLY_SELF_HELP = new Set([
// ZE interim cleanup: the retired ze-switch shim ships truthful help
// (sunset refusal + canonical migration command); the generic stub hid it.
'ze-switch',
+ // #3686 (the #578 residue): eval / storage / reindex each ship real usage —
+ // eval's printHelp (15 subcommands), storage's status usage, reindex's
+ // target-flag usage — that the generic one-line stub was hiding. Their
+ // engine-free --help is answered by pre-engine branches in handleCliOnly
+ // (the sync/capture pattern).
+ 'eval', 'storage', 'reindex',
]);
/**
@@ -388,6 +394,20 @@ async function main() {
const { cliOpts, rest: args } = parseGlobalFlags(rawArgs);
setCliOptions(cliOpts);
+ // #3688: operator-configured guardrail providers load before ANY command
+ // dispatch. Fail-closed by design: when GBRAIN_GUARDRAILS_MODULE is set but
+ // broken, abort rather than silently run without the operator's firewall.
+ // (Unset → zero cost, the OSS distribution stays inert.)
+ if (process.env.GBRAIN_GUARDRAILS_MODULE) {
+ try {
+ const { loadGuardrailProvidersFromEnv } = await import('./core/guardrails.ts');
+ await loadGuardrailProvidersFromEnv();
+ } catch (err) {
+ console.error(`guardrails: ${(err as Error)?.message ?? String(err)}`);
+ process.exit(1);
+ }
+ }
+
let command = args[0];
if (!command || command === '--help' || command === '-h') {
@@ -1066,8 +1086,25 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
// rehearsal request (the resurrected #2185 class the red team caught).
params[key] = true;
} else if (i + 1 < args.length) {
+ // #2822: a flag silently overwriting an already-set positional is
+ // almost always an argument-plumbing mistake (e.g. `gbrain put
+ // notes.md --content "..."` — the file path landed in `content`
+ // positionally, then --content clobbered it). Warn to stderr; when
+ // the discarded value names an existing file, point at capture --file.
+ const prevValue = params[key];
params[key] = args[++i];
if (paramDef?.type === 'number') params[key] = Number(params[key]);
+ if (prevValue !== undefined && prevValue !== params[key]) {
+ let fileHint = '';
+ try {
+ if (typeof prevValue === 'string' && prevValue && existsSync(prevValue)) {
+ fileHint = ` If '${prevValue}' is a file you meant to ingest, use: gbrain capture --file ${prevValue} --slug <slug>`;
+ }
+ } catch { /* best-effort hint */ }
+ process.stderr.write(
+ `Warning: --${key.replace(/_/g, '-')} overwrites the positional value '${String(prevValue)}'.${fileHint}\n`,
+ );
+ }
}
} else if (posIdx < positional.length) {
const key = positional[posIdx++];
@@ -1110,6 +1147,12 @@ export async function applyStdinParam(
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
const content = await readStdinBounded();
if (content === null) return; // no input arrived — let the required-param check fail fast
+ // #2822: empty/whitespace-only stdin is NO input, not a real value. A CI
+ // step's `< /dev/null`, an agent harness's empty pipe, or a botched
+ // redirect used to land '' in the param and flow into a destructive
+ // empty write; leaving the param unset makes the required-param usage
+ // error fire instead (same fail-fast as the #3513 timeout path).
+ if (content.trim() === '') return;
const MAX_STDIN = 5_000_000; // 5MB
if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
@@ -2408,6 +2451,18 @@ async function handleCliOnly(command: string, args: string[]) {
return;
}
+ // #4198: `gbrain eval synthesize-concepts` gets a dedicated branch (mirror
+ // of the chronicle branch above) so the generic qrels eval can't recapture
+ // it — pre-fix it fell through to "Error: --qrels <path|json> is required".
+ // The scaffold needs no DB and exits nonzero with an honest
+ // {ok:false, status:'not_implemented'} envelope until the real evaluator
+ // lands.
+ if (command === 'eval' && args[0] === 'synthesize-concepts') {
+ const { runEvalSynthesizeConceptsCli } = await import('./commands/eval-synthesize-concepts.ts');
+ setCliExitVerdict(await runEvalSynthesizeConceptsCli(args.slice(1)));
+ return;
+ }
+
// v0.41.13.0: `gbrain eval conversation-parser` is pure-function
// (parses fixture JSONL, runs parseConversation, scores results).
// No DB access; bypass connectEngine entirely so the CI fixture
@@ -2504,6 +2559,34 @@ async function handleCliOnly(command: string, args: string[]) {
return;
}
+ // #3686 (the #578 residue): `eval --help` reaches eval.ts's printHelp
+ // engine-free. Placed AFTER the sub-owned no-DB routes above (brainbench /
+ // longmemeval / run-all / cross-modal / chronicle / conversation-parser /
+ // takes-quality replay / whoknows) so each sub's own usage keeps winning;
+ // every remaining `eval … --help` form prints the full subcommand usage
+ // instead of the old one-line stub (or a "No brain configured" error).
+ if (command === 'eval' && (args.includes('--help') || args.includes('-h'))) {
+ const { runEvalCommand } = await import('./commands/eval.ts');
+ await runEvalCommand(null as never, ['--help']);
+ return;
+ }
+
+ // #3686: `storage --help` — runStorage's help guard returns before the
+ // engine argument is touched.
+ if (command === 'storage' && (args.includes('--help') || args.includes('-h'))) {
+ const { runStorage } = await import('./commands/storage.ts');
+ await runStorage(null as never, args);
+ return;
+ }
+
+ // #3686: `reindex --help` — the usage block (incl. the --multimodal flags
+ // the dispatcher parses) lives in reindex.ts; printing it needs no engine.
+ if (command === 'reindex' && (args.includes('--help') || args.includes('-h'))) {
+ const { printReindexHelp } = await import('./commands/reindex.ts');
+ printReindexHelp();
+ return;
+ }
+
// v0.41.6.0 D3 (per outside-voice F1): connect-time + dispatch-time wallclock
// timeouts for read-only commands whose hang would otherwise spin at 100% CPU
// (the production "10-day zombie gbrain search ping" bug class). The wrap
@@ -2595,6 +2678,18 @@ async function handleCliOnly(command: string, args: string[]) {
}
}
+ // Serve-delegated sweep preflight (#677) — same shape as sync above: a live
+ // `gbrain serve` owns the PGLite single-writer lock, so `sweep --once` used
+ // to exit 1 with LiveServeLockError. The lock owner runs the sweep over its
+ // IPC socket instead (commands/sweep-delegate.ts).
+ if (command === 'sweep') {
+ const cfgSweep = loadConfig();
+ if (cfgSweep?.engine === 'pglite' && cfgSweep.database_path && !cfgSweep.database_url) {
+ const { maybeDelegateSweepToServe } = await import('./commands/sweep-delegate.ts');
+ if (await maybeDelegateSweepToServe(cfgSweep.database_path, args)) return;
+ }
+ }
+
// Thin-client `jobs` dispatch: `list` and `get` route over MCP (v0.32
// routing branches in commands/jobs.ts) and never touch a local engine —
// but falling through to connectEngine() below fabricates an empty
@@ -3538,7 +3633,7 @@ CODE INDEXING (v0.19.0 / v0.20.0 Cathedral II)
query <q> --lang <l> Filter hybrid search to one language (v0.20.0)
query <q> --symbol-kind <k> Filter to symbol type (function|class|method|...) (v0.20.0)
reconcile-links [--dry-run] Batch-recompute doc↔impl edges (v0.20.0)
- reindex-code [--source id] [--yes] Explicit code-page reindex (v0.20.0)
+ reindex-code [--source id] [--yes] [--force] Explicit code-page reindex (v0.20.0; --force re-chunks unchanged pages)
reindex-search-vector [--dry-run] [--yes] [--json]
Recreate FTS triggers + backfill under
$GBRAIN_FTS_LANGUAGE (default 'english')
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index fe40e08ff4..655b733315 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -20,7 +20,7 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, utimesSync, unlinkSync, chmodSync, statSync } from 'fs';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { detectExecutionEnvironment } from '../core/execution-env.ts';
-import { join, dirname, isAbsolute } from 'path';
+import { join, dirname, isAbsolute, resolve as resolvePath } from 'path';
import { execSync } from 'child_process';
import type { BrainEngine } from '../core/engine.ts';
import { loadPreferences } from '../core/preferences.ts';
@@ -270,7 +270,10 @@ export function decideLockAcquisition(
lockPath: string,
currentPid: number,
deps: AutopilotLockProbeDeps = {},
-): { action: 'acquire' } | { action: 'exit'; holderPid: number } | { action: 'takeover'; reason: string } {
+):
+ | { action: 'acquire' }
+ | { action: 'exit'; holderPid: number; holderState: 'alive-autopilot' | 'alive-foreign' | 'alive-unknown' }
+ | { action: 'takeover'; reason: string } {
if (!existsSync(lockPath)) return { action: 'acquire' };
let raw = '';
@@ -283,15 +286,21 @@ export function decideLockAcquisition(
const holderPid = Number.parseInt(raw, 10);
const holder = classifyAutopilotLockHolder(holderPid, currentPid, deps);
- if (holder.state === 'alive-autopilot' || holder.state === 'alive-unknown') {
- return { action: 'exit', holderPid };
+ if (holder.state === 'alive-autopilot') {
+ return { action: 'exit', holderPid, holderState: holder.state };
}
- if (holder.state === 'alive-foreign') {
+ if (holder.state === 'alive-foreign' || holder.state === 'alive-unknown') {
+ // #4300: an alive PID whose command we can't identify as gbrain autopilot
+ // (recycled PID after reboot, or a /proc-less + ps-restricted host) gets
+ // the same age-gated takeover as a known-foreign holder. A fresh lock is
+ // still respected; only a stale one (past the grace window) is stolen —
+ // otherwise a single recycled PID bricks the daemon forever.
const lockAgeMs = autopilotLockAgeMs(lockPath);
if (lockAgeMs !== null && lockAgeMs >= AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS) {
- return { action: 'takeover', reason: `foreign pid ${raw || '<empty>'} with stale lock` };
+ const kind = holder.state === 'alive-foreign' ? 'foreign' : 'unidentifiable';
+ return { action: 'takeover', reason: `${kind} pid ${raw || '<empty>'} with stale lock` };
}
- return { action: 'exit', holderPid };
+ return { action: 'exit', holderPid, holderState: holder.state };
}
if (holder.state === 'self') {
return { action: 'takeover', reason: `own pid ${raw || '<empty>'}` };
@@ -603,7 +612,17 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
mkdirSync(gbrainHomePath(), { recursive: true });
const decision = decideLockAcquisition(lockPath, process.pid);
if (decision.action === 'exit') {
- console.error(`Another autopilot instance is running (pid ${decision.holderPid}). Exiting.`);
+ // #4300: say WHY we refused, loudly, so a bricked daemon is diagnosable
+ // from launchd/systemd logs without strace-ing the lock probe.
+ const detail =
+ decision.holderState === 'alive-autopilot'
+ ? 'a live gbrain autopilot process'
+ : decision.holderState === 'alive-unknown'
+ ? 'a live process whose command line could not be inspected (fresh lock — will become stealable once stale)'
+ : 'a live non-gbrain process holding a fresh lock (will become stealable once stale)';
+ console.error(
+ `[autopilot] refusing to start: lock ${lockPath} is held by pid ${decision.holderPid} — ${detail}. Exiting.`,
+ );
process.exit(0);
}
if (decision.action === 'takeover') {
@@ -798,6 +817,11 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// Parser-probe fixture warning is once-per-process, not once-per-cycle
// (compiled-binary installs have no source tree; don't spam the log).
let parserProbeFixtureWarned = false;
+ // #2608: once-per-process no-chat-provider warning. A keyless daemon used
+ // to run every cycle "green" while all LLM phases silently no-op'd
+ // (chronicle reported no_events, propose_takes skipped, …) — the operator
+ // had no signal that shell-profile keys never reached launchd/systemd.
+ let noChatProviderWarned = false;
// v0.37.7.0 #1162 — counter for consecutive reconnect failures.
// Reset on every successful health probe or reconnect. Threshold
// controlled by GBRAIN_AUTOPILOT_MAX_RECONNECT_FAILS env (default 30).
@@ -834,6 +858,25 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// declare the instance stale after 10 minutes (Codex C).
try { utimesSync(lockPath, new Date(), new Date()); } catch { /* best-effort */ }
+ // #2608: loud once-per-process signal when no chat provider is servable.
+ // Without this a keyless daemon looks healthy forever while every LLM
+ // phase quietly skips.
+ if (!noChatProviderWarned) {
+ noChatProviderWarned = true;
+ try {
+ const { isAvailable } = await import('../core/ai/gateway.ts');
+ if (!isAvailable('chat')) {
+ console.error(
+ `[autopilot] WARN: no chat provider is available to this daemon — LLM-dependent ` +
+ `phases (chronicle event extraction, propose_takes, synthesize, …) will skip. ` +
+ `Shell-profile exports often do not reach launchd/systemd: put KEY=value lines in ` +
+ `${join(gbrainHomePath(), 'env')} (sourced by the wrapper), then re-run ` +
+ '`gbrain autopilot --install` to reload the daemon.',
+ );
+ }
+ } catch { /* gateway unconfigured — the cycle surfaces its own errors */ }
+ }
+
// Post-migration convergence: if the file-plane engine identity changed
// since boot, this process is connected to the wrong engine. Exit through
// the clean shutdown path (engine close matters for PGLite WAL) so the
@@ -1022,7 +1065,7 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// poll-only deployments.
try {
const { MinionQueue } = await import('../core/minions/queue.ts');
- const { computeRecommendations, embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG } = await import('../core/brain-score-recommendations.ts');
+ const { computeRecommendations, embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG, chatApiKeyConfigured } = await import('../core/brain-score-recommendations.ts');
const queue = new MinionQueue(engine);
const slotMs = Math.floor(Date.now() / (baseInterval * 1000)) * baseInterval * 1000;
const slot = new Date(slotMs).toISOString();
@@ -1042,6 +1085,16 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
const now = Date.now();
for (const src of sources) {
if (!src.local_path) continue;
+ // #3696: a RELATIVE local_path is meaningless in the daemon
+ // (cwd is launchd's, not the registering shell's) — dispatching
+ // it would sync a phantom path. Skip loudly; the fix is
+ // re-registering with an absolute path (sources add now
+ // resolves) or one successful `gbrain sync` (anchor self-heal).
+ const relWarn = relativeLocalPathSkipWarning(src.id, src.local_path);
+ if (relWarn) {
+ process.stderr.write(relWarn + '\n');
+ continue;
+ }
const lastSyncMs = src.last_sync_at ? new Date(src.last_sync_at).getTime() : 0;
const ageMs = now - lastSyncMs;
if (ageMs < intervalMs) continue; // fresh enough
@@ -1135,6 +1188,12 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
for (const src of sources) {
if (submittedToday >= maxJobsToday) break; // brain-wide daily cap (fairness)
if (!src.local_path) continue;
+ // #3696: same relative-path skip as the freshness loop.
+ const relWarn = relativeLocalPathSkipWarning(src.id, src.local_path);
+ if (relWarn) {
+ process.stderr.write(relWarn + '\n');
+ continue;
+ }
const backlog = await countExtractAtomsBacklog(engine, src.id);
if (backlog === null || backlog <= threshold) continue;
// Time-sloted key (CODEX #2): a static key would block the
@@ -1227,7 +1286,12 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
const cfgField = HOSTED_EMBED_KEY_CONFIG[envVar];
return !!(process.env[envVar] || (cfgField ? embedKeyCfg[cfgField] : undefined));
}),
- hasChatApiKey: !!(process.env.ANTHROPIC_API_KEY || await engine.getConfig('anthropic_api_key')),
+ // #3944: env + FILE plane via the shared helper — the same probe
+ // doctor's loadRecommendationContext uses. Reading the DB plane
+ // here (engine.getConfig) reported a chat key "configured" that
+ // doctor's planner (file plane, per the #2662 rule above) said was
+ // missing, so autopilot dispatched chat jobs doctor called blocked.
+ hasChatApiKey: chatApiKeyConfigured(fileCfg),
};
// v0.41.18.0 (A5 + A19 + A22, T15): consult onboard recommendations
// ALONGSIDE doctor's brain-score recommendations. Onboard's 4 new
@@ -1691,6 +1755,9 @@ rm -f '${q(strikes)}' 2>/dev/null || true
`;
}
+// Exported for tests (#2608): the emitted wrapper text is the contract —
+// key-channel regressions (rc-file || chains, missing env-file sourcing)
+// must be pinnable without installing a daemon.
/**
* #2608: contents of the install-time `<gbrainDir>/env` template. All lines
* commented — the install must never ship a live secret. GBRAIN_HOME is
@@ -1773,7 +1840,12 @@ export function writeWrapperScript(repoPath: string, target: InstallTarget): str
# subprocess). Source it first so secrets like GBRAIN_DATABASE_URL or any
# OPENAI/ANTHROPIC keys exported in zshenv reach autopilot.
[ -f ~/.zshenv ] && source ~/.zshenv 2>/dev/null
-source ~/.zshrc 2>/dev/null || source ~/.bashrc 2>/dev/null || true
+# #2608: source zshrc AND bashrc independently. The old \`zshrc || bashrc\`
+# chain only reached bashrc when sourcing zshrc FAILED — on a machine with
+# both files (default macOS + a bash-managed key setup) the bashrc keys
+# never loaded and every LLM phase silently no-op'd.
+[ -f ~/.zshrc ] && source ~/.zshrc 2>/dev/null
+[ -f ~/.bashrc ] && source ~/.bashrc 2>/dev/null
# gbrain-owned env file (#2608), additive to the profiles above: daemon
# shells are non-interactive, so exports that live only in an interactive
# rc file never reach them — and the ~/.bashrc guard below means even
@@ -1797,18 +1869,41 @@ source ~/.zshrc 2>/dev/null || source ~/.bashrc 2>/dev/null || true
# or which init file the OS loaded.
export PATH=${runtimePathPrefix}"$HOME/.bun/bin:$PATH"
${process.env.GBRAIN_HOME ? `# Baked at install: the supervisor does not pass the installer's env, and\n# without this the daemon would read/write a different home than the\n# install that configured it.\nexport GBRAIN_HOME='${(process.env.GBRAIN_HOME).replace(/'/g, "'\\''")}'\n` : ''}
-${generateSelfDisableGuard(repoPath, target)}exec '${safeGbrainPath}' autopilot --repo '${safeRepoPath}'
+${generateSelfDisableGuard(repoPath, target)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /
+# sync.repo_path row resolves against it instead of a phantom path under the
+# supervisor's cwd. Done HERE — after the guard has proven the repo exists —
+# and NOT via launchd's plist WorkingDirectory: launchd chdir()s before exec,
+# so a deleted repo would fail every respawn and the self-disable guard above
+# could never run. Fail-open (|| true): a repo deleted between the guard and
+# this line still starts the daemon, and the dispatch loops skip relative
+# paths loudly.
+cd '${safeRepoPath}' 2>/dev/null || true
+exec '${safeGbrainPath}' autopilot --repo '${safeRepoPath}'
`;
writeFileSync(wrapperPath, wrapper, { mode: 0o755 });
return wrapperPath;
}
async function installDaemon(engine: BrainEngine, args: string[]) {
- const repoPath = parseArg(args, '--repo') || await engine.getConfig('sync.repo_path');
- if (!repoPath) {
+ // #677: on a PGLite brain the autopilot daemon would hold the single-writer
+ // DB lock for its lifetime — every other gbrain process (serve, search,
+ // sweep, embed) then fails to connect. Refuse with guidance; --force for
+ // operators who genuinely want a daemon-owned brain.
+ const guardMsg = pgliteDaemonGuardMessage(engine.kind, args.includes('--force'));
+ if (guardMsg) {
+ console.error(guardMsg);
+ process.exit(1);
+ }
+ const rawRepoPath = parseArg(args, '--repo') || await engine.getConfig('sync.repo_path');
+ if (!rawRepoPath) {
console.error('No repo path. Use --repo or run gbrain sync --repo first.');
process.exit(1);
}
+ // #3696: the daemon runs with an arbitrary cwd (launchd: `/`), so a
+ // relative `--repo .` baked into the wrapper script resolves to a phantom
+ // path at daemon runtime. Resolve NOW, against the installer's cwd.
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rawRepoPath is the local operator's own --repo CLI arg or the operator-written sync.repo_path config row; installDaemon is reachable only via `gbrain autopilot --install` on the trusted local CLI (never MCP/remote), and absolutizing it here IS the #3696 fix
+ const repoPath = resolvePath(rawRepoPath);
const forcedTarget = parseArg(args, '--target') as InstallTarget | undefined;
const target: InstallTarget = forcedTarget ?? detectInstallTarget();
@@ -1817,6 +1912,15 @@ async function installDaemon(engine: BrainEngine, args: string[]) {
const noInject = args.includes('--no-inject');
const wrapperPath = writeWrapperScript(repoPath, target);
+ // #2608: tell the operator about the deterministic key channel — launchd/
+ // systemd don't inherit the login shell env, and rc-file interactive guards
+ // routinely swallow exports, so "it works in my terminal" keys often never
+ // reach the daemon.
+ console.log(
+ `API keys: the daemon sources ${join(gbrainHomePath(), 'env')} (plain KEY=value lines, ` +
+ `auto-exported) in addition to your shell profile. If LLM phases report no provider, put ` +
+ 'ANTHROPIC_API_KEY=... (or your provider\'s key) there and re-run `gbrain autopilot --install`.',
+ );
// A fresh install clears any prior self-disable AND any leaked pause, so a
// reinstall does not report "disabled" forever or park itself from day one
// on a marker some dead migration left behind.
@@ -1844,8 +1948,57 @@ async function installDaemon(engine: BrainEngine, args: string[]) {
}
}
+/**
+ * #677 — PGLite install guard, pure (the unit-test surface). A PGLite brain
+ * is single-writer: a daemonized autopilot holds the exclusive DB lock 24/7,
+ * so every OTHER gbrain process (`serve`, `search`, `sweep --once`,
+ * `embed --stale`) fails to connect for as long as the daemon lives. The
+ * supported PGLite background story is `gbrain serve` (resident sweep +
+ * serve-delegated sync/sweep over IPC). Returns the refusal message, or null
+ * when the install may proceed (postgres engine, or explicit --force).
+ */
+export function pgliteDaemonGuardMessage(engineKind: string, force: boolean): string | null {
+ if (engineKind !== 'pglite' || force) return null;
+ return (
+ `gbrain autopilot --install: this brain runs on PGLite (single-writer). A daemonized ` +
+ `autopilot would hold the exclusive DB lock 24/7 and block every other gbrain ` +
+ `process (serve, search, sweep, embed) for as long as it runs.\n` +
+ ` Recommended: run \`gbrain serve\` instead — it owns the lock, runs the resident ` +
+ `maintenance sweep, and delegates \`gbrain sync\`/\`gbrain sweep --once\` through its ` +
+ `IPC socket.\n` +
+ ` To install the daemon anyway (dedicated-brain setups), re-run with --force.`
+ );
+}
+
+/**
+ * #3696 — the autopilot dispatch loops refuse to enqueue work for a source
+ * whose local_path is RELATIVE: the daemon's cwd is launchd's (typically `/`),
+ * not the shell that registered the source, so the path would resolve to a
+ * phantom directory and the sync/extract job would fail (or worse, walk the
+ * wrong tree). Returns the stderr warning line when the path must be skipped,
+ * or null when it is dispatchable. Pure — the unit-test surface.
+ */
+export function relativeLocalPathSkipWarning(sourceId: string, localPath: string): string | null {
+ if (isAbsolute(localPath)) return null;
+ return (
+ `[autopilot] skipping source '${sourceId}': relative local_path ` +
+ `'${localPath}' cannot be resolved from a daemon. Re-register with an ` +
+ `absolute --path or run 'gbrain sync --source ${sourceId}' once to self-heal.`
+ );
+}
+
// v0.37.7.0 #1162 — pure function for plist generation so tests can
// assert ThrottleInterval/KeepAlive shape without an installed daemon.
+// #3696: WorkingDirectory pins the daemon's cwd away from launchd's `/`
+// default — but it MUST be a spawn-safe path, NEVER the repo. launchd
+// chdir()s before exec, so a WorkingDirectory that stops existing makes
+// every (re)spawn fail: after a repo deletion the wrapper — and its
+// self-disable guard — would never run again, leaving a zombie KeepAlive
+// job that can never take itself out of rotation. $HOME exists for the
+// job's whole lifetime; the WRAPPER cd's into the repo AFTER the guard has
+// proven it exists (writeWrapperScript), which is what makes legacy
+// RELATIVE sources.local_path / sync.repo_path rows resolve against the
+// repo instead of a phantom path.
export function generateLaunchdPlist(wrapperPath: string, home: string): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -1855,6 +2008,7 @@ export function generateLaunchdPlist(wrapperPath: string, home: string): string
<key>ProgramArguments</key><array>
<string>${escapeXml(wrapperPath)}</string>
</array>
+ <key>WorkingDirectory</key><string>${escapeXml(home)}</string>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<!--
diff --git a/src/commands/call.ts b/src/commands/call.ts
index 284b5e9cef..b4900d9c80 100644
--- a/src/commands/call.ts
+++ b/src/commands/call.ts
@@ -1,6 +1,6 @@
import type { BrainEngine } from '../core/engine.ts';
import { handleToolCall } from '../mcp/server.ts';
-import { resolveSourceId } from '../core/source-resolver.ts';
+import { resolveSourceWithTier, localFederatedSourceIds } from '../core/source-resolver.ts';
import { bigintToStringReplacer } from '../cli.ts';
import { writeStdoutFinal } from '../core/cli-force-exit.ts';
@@ -52,10 +52,20 @@ export async function runCall(
}
const params = jsonStr ? JSON.parse(jsonStr) : {};
- // Resolve through the canonical 6-tier chain. resolveSourceId() throws if
- // an explicit/env/dotfile id refers to a non-registered source.
- const sourceId = await resolveSourceId(engine, explicitSource);
- const result = await handleToolCall(engine, tool, params, { sourceId });
+ // Resolve through the canonical 6-tier chain. resolveSourceWithTier()
+ // throws if an explicit/env/dotfile id refers to a non-registered source.
+ // #3874: mirror cli.ts's makeContext — when the source resolved via a
+ // NON-explicit tier, unqualified search-shaped reads span every
+ // `config.federated = true` source (#2561 parity). Without this,
+ // `gbrain call query ...` silently saw a narrower brain than
+ // `gbrain query ...`.
+ const resolved = await resolveSourceWithTier(engine, explicitSource);
+ const sourceId = resolved.source_id;
+ const localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ const result = await handleToolCall(engine, tool, params, {
+ sourceId,
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
+ });
// `gbrain call` bypasses cli.ts's op-output normalizer entirely, so this
// exit needs its own bigint-safe replacer — any op returning an int8 column
// (BIGSERIAL id) would otherwise crash plain JSON.stringify (#2450).
diff --git a/src/commands/code-callees.ts b/src/commands/code-callees.ts
index 66ebb9bb1d..e4b6484151 100644
--- a/src/commands/code-callees.ts
+++ b/src/commands/code-callees.ts
@@ -122,8 +122,10 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
// Call-graph readiness ('edge' grain): distinguishes "graph not built / still
// indexing" from "genuinely no callees" when count === 0.
+ // remote: false — direct CLI invocation is the trusted local caller, so
+ // the #3707 out_of_scope brain-wide rerun stays available (#4352 gate).
const readiness = await resolveCodeReadiness(engine, {
- kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources,
+ kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources, remote: false,
});
if (shouldEmitJson(args)) {
@@ -131,8 +133,12 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
symbol: sym, source_id: envelopeSourceId, scope, count: edges.length,
status: readiness.status, ready: readiness.ready, callees: edges,
};
+ // #3707: see code-callers.ts — scope problem vs never-built.
+ if (readiness.scoped_source_id) out.scoped_source_id = readiness.scoped_source_id;
if (edges.length === 0 && !allSources && sourceId) {
- out.hint = `No callees in source '${sourceId}'. Try --all-sources to search every source.`;
+ out.hint = readiness.status === 'out_of_scope'
+ ? (readinessHint(readiness) ?? `No callees in source '${sourceId}'.`)
+ : `No callees in source '${sourceId}'. Try --all-sources to search every source.`;
}
console.log(JSON.stringify(out, null, 2));
} else if (edges.length === 0) {
diff --git a/src/commands/code-callers.ts b/src/commands/code-callers.ts
index 87dde20fbc..7d2c424a8e 100644
--- a/src/commands/code-callers.ts
+++ b/src/commands/code-callers.ts
@@ -141,8 +141,10 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promi
// Call-graph readiness ('edge' grain): distinguishes "graph not built / still
// indexing" from "genuinely no callers" when count === 0.
+ // remote: false — direct CLI invocation is the trusted local caller, so
+ // the #3707 out_of_scope brain-wide rerun stays available (#4352 gate).
const readiness = await resolveCodeReadiness(engine, {
- kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources,
+ kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources, remote: false,
});
if (shouldEmitJson(args)) {
@@ -150,8 +152,13 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promi
symbol: sym, source_id: envelopeSourceId, scope, count: edges.length,
status: readiness.status, ready: readiness.ready, callers: edges,
};
+ // #3707: out_of_scope names the empty scope so "grant/scope problem" is
+ // distinguishable from "graph never built" in machine output.
+ if (readiness.scoped_source_id) out.scoped_source_id = readiness.scoped_source_id;
if (edges.length === 0 && !allSources && sourceId) {
- out.hint = `No callers in source '${sourceId}'. Try --all-sources to search every source.`;
+ out.hint = readiness.status === 'out_of_scope'
+ ? (readinessHint(readiness) ?? `No callers in source '${sourceId}'.`)
+ : `No callers in source '${sourceId}'. Try --all-sources to search every source.`;
}
console.log(JSON.stringify(out, null, 2));
} else if (edges.length === 0) {
diff --git a/src/commands/code-def.ts b/src/commands/code-def.ts
index 47fd6055d9..191c952dff 100644
--- a/src/commands/code-def.ts
+++ b/src/commands/code-def.ts
@@ -49,6 +49,24 @@ export const DEF_TYPES = [
// 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
];
export async function findCodeDef(
@@ -100,6 +118,42 @@ export async function findCodeDef(
}));
}
+/**
+ * #3789 aside — when findCodeDef returns 0 rows, distinguish "symbol does not
+ * exist" from "symbol exists but every row's symbol_type is outside the
+ * DEF_TYPES allowlist" (a normalizeSymbolType fallthrough gap, or data chunked
+ * by an older chunker). Returns the distinct filtered-out symbol types for the
+ * name; empty when the symbol genuinely has no named chunks. Runs ONLY on
+ * count:0, rides the symbol_name lookup path the result query already uses.
+ */
+export async function probeFilteredSymbolTypes(
+ engine: BrainEngine,
+ symbol: string,
+ opts: { language?: string } = {},
+): Promise<string[]> {
+ const params: unknown[] = [symbol];
+ let whereLang = '';
+ if (opts.language) {
+ params.push(opts.language);
+ whereLang = `AND cc.language = $${params.length}`;
+ }
+ const rows = await engine.executeRaw<{ symbol_type: string | null }>(
+ `SELECT DISTINCT cc.symbol_type
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ WHERE cc.symbol_name = $1
+ ${whereLang}
+ AND p.page_kind = 'code'
+ ORDER BY cc.symbol_type
+ LIMIT 20`,
+ params,
+ );
+ const allow = new Set([...DEF_TYPES, 'export statement']);
+ return rows
+ .map((r) => r.symbol_type)
+ .filter((t): t is string => t != null && !allow.has(t));
+}
+
function parseFlag(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
return i >= 0 && i + 1 < args.length ? args[i + 1] : undefined;
@@ -137,17 +191,37 @@ export async function runCodeDef(engine: BrainEngine, args: string[]): Promise<v
const results = await findCodeDef(engine, sym, { limit, language });
// code-def is brain-wide (not source-scoped); readiness is 'symbol' grain.
const readiness = await resolveCodeReadiness(engine, { kind: 'symbol', count: results.length });
+ // #3789: a count:0 that was filtered by the DEF_TYPES allowlist must not
+ // read as a bare ready:true / "symbol does not exist". Probe the distinct
+ // symbol types the name DOES have and surface the filtered ones.
+ let filteredTypes: string[] = [];
+ if (results.length === 0) {
+ try {
+ filteredTypes = await probeFilteredSymbolTypes(engine, sym, { language });
+ } catch {
+ // Supplementary signal — never fail the command on the probe.
+ }
+ }
+ const filteredHint = filteredTypes.length > 0
+ ? `Symbol "${sym}" IS indexed, but only with symbol type(s) outside the definition allowlist: ` +
+ `${filteredTypes.join(', ')}. Likely a DEF_TYPES gap or pre-upgrade chunk data — ` +
+ 'try `gbrain code-refs` for these sites, and consider re-syncing the source.'
+ : null;
if (shouldEmitJson(args)) {
console.log(JSON.stringify({
symbol: sym,
count: results.length,
status: readiness.status,
ready: readiness.ready,
+ ...(filteredTypes.length > 0
+ ? { filtered_symbol_types: filteredTypes, hint: filteredHint }
+ : {}),
results,
}, null, 2));
} else {
if (results.length === 0) {
console.log(`No definitions found for "${sym}"`);
+ if (filteredHint) console.log(filteredHint);
const hint = readinessHint(readiness);
if (hint) console.log(hint);
} else {
diff --git a/src/commands/config.ts b/src/commands/config.ts
index e96021fbef..07934cf0bf 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -309,13 +309,23 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
const isKnown = KNOWN_CONFIG_KEYS.includes(key);
const matchesPrefix = KNOWN_CONFIG_KEY_PREFIXES.some(p => key.startsWith(p));
if (!isKnown && !matchesPrefix) {
- const { suggestNearest } = await import('../core/levenshtein.ts');
- const suggestion = suggestNearest(key, KNOWN_CONFIG_KEYS, 3);
console.error(`[config] Unknown config key "${key}".`);
- if (suggestion) {
- console.error(`[config] Did you mean "${suggestion}"?`);
+ // #3748: `budget.*` (e.g. budget.daily_cap_usd) appeared once in old
+ // release notes but was never registered and has NO readers — a
+ // --force write would set a "cap" that caps nothing, which for a
+ // spend control is worse than a rejection. Route the operator to the
+ // controls that actually exist.
+ if (key === 'budget' || key.startsWith('budget.')) {
+ console.error(`[config] budget.* keys are not live controls — nothing in gbrain reads them, so a cap written here caps nothing.`);
+ console.error(`[config] The live spend controls are \`gbrain config set spend.posture <gated|tokenmax>\` and the per-command gates in docs/operations/spend-controls.md.`);
} else {
- console.error(`[config] No similar known key. Run \`gbrain config show\` to see currently-set keys.`);
+ const { suggestNearest } = await import('../core/levenshtein.ts');
+ const suggestion = suggestNearest(key, KNOWN_CONFIG_KEYS, 3);
+ if (suggestion) {
+ console.error(`[config] Did you mean "${suggestion}"?`);
+ } else {
+ console.error(`[config] No similar known key. Run \`gbrain config show\` to see currently-set keys.`);
+ }
}
console.error(`[config] If this is intentional (downstream tooling, forward-compat), re-run with --force.`);
process.exit(1);
@@ -327,6 +337,10 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
const matchesPrefix = KNOWN_CONFIG_KEY_PREFIXES.some(p => key.startsWith(p));
if (!isKnown && !matchesPrefix) {
console.error(`[config] WARN: writing unknown key "${key}" with --force. Nothing in gbrain reads this.`);
+ if (key === 'budget' || key.startsWith('budget.')) {
+ // #3748: an operator who believes this caps spend has NO cap at all.
+ console.error(`[config] WARN: budget.* is NOT a spend cap — the live controls are spend.posture + docs/operations/spend-controls.md.`);
+ }
}
}
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index a9a5fa102b..efbc0e29c6 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -23,6 +23,7 @@ import { computeEffectiveDate } from '../core/effective-date.ts';
import { parseFrontmatter } from '../core/backfill-effective-date.ts';
import { hnswIndexExpected, hnswMaxDimsForType } from '../core/vector-index.ts';
import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';
+import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-health.ts';
// Peeled doctor modules (containment sprint): each is a verbatim move out of
// this file. doctor.ts re-exports every moved public symbol under its
// original name so existing importers (tests, scripts/live-brain-first-check.ts,
@@ -57,6 +58,7 @@ export {
resolveWhoknowsFixturePath,
whoknowsHealthCheck,
pgvectorCheck,
+ pagesUpsertArbiterCheck,
jsonbIntegrityCheck,
checkVolunteerChannels,
takesWeightGridCheck,
@@ -90,6 +92,9 @@ export {
checkProviderSunset,
checkEmbeddingWidthConsistency,
checkFactsEmbeddingWidthConsistency,
+ checkJunkEntityHubs,
+ JUNK_HUB_EDGE_THRESHOLD,
+ JUNK_HUB_MAX_CHUNKS,
} from './doctor/checks/graph-embedding.ts';
export {
checkSourceRoutingHealth,
@@ -117,6 +122,7 @@ export {
checkLinksExtractionLag,
checkUnverifiedExtractions,
checkContentHashDuplicates,
+ checkCodeChunkMetadata,
checkUndeclaredDbOnlyPages,
checkDbOnlyCollectorCollision,
computeExtractAtomsBacklogCheck,
@@ -144,6 +150,7 @@ export {
import {
whoknowsHealthCheck,
pgvectorCheck,
+ pagesUpsertArbiterCheck,
jsonbIntegrityCheck,
checkVolunteerChannels,
takesWeightGridCheck,
@@ -171,6 +178,7 @@ import {
checkProviderSunset,
checkEmbeddingWidthConsistency,
checkFactsEmbeddingWidthConsistency,
+ checkJunkEntityHubs,
} from './doctor/checks/graph-embedding.ts';
import {
checkSourceRoutingHealth,
@@ -195,6 +203,7 @@ import {
checkLinksExtractionLag,
checkUnverifiedExtractions,
checkContentHashDuplicates,
+ checkCodeChunkMetadata,
checkUndeclaredDbOnlyPages,
checkDbOnlyCollectorCollision,
computeExtractAtomsBacklogCheck,
@@ -769,6 +778,14 @@ export async function buildChecks(
// Read/parse failure is itself best-effort; skip silently.
}
+ // 3b-ter. Self-upgrade health (#3747). Pure local-file check (config +
+ // upgrade cache + audit trail; no DB) that was only ever pushed by the
+ // REMOTE report (doctor/report-remote.ts) — the local `gbrain doctor`,
+ // the surface an operator actually runs on the host, never emitted it,
+ // so a wedged auto-upgrade loop was invisible exactly where it would be
+ // diagnosed. Sits beside the upgrade_errors trail it complements.
+ checks.push(checkSelfUpgradeHealth());
+
// 3b-bis. Supervisor health (filesystem-only: PID liveness + audit log).
// Reads the default PID file (`~/.gbrain/supervisor.pid` unless the user
// overrode with GBRAIN_SUPERVISOR_PID_FILE) and the latest audit file
@@ -1742,6 +1759,11 @@ export async function buildChecks(
progress.heartbeat('pgvector');
checks.push(await pgvectorCheck(engine));
+ // 4a-bis. #550: pages(source_id, slug) upsert arbiter — when missing, every
+ // page write fails brain-wide and the version counter can't see the drift.
+ progress.heartbeat('pages_upsert_arbiter');
+ checks.push(await pagesUpsertArbiterCheck(engine));
+
// 4b. PgBouncer / prepared-statement compatibility.
// URL-only inspection — no DB roundtrip — so this is cheap and works
// regardless of whether the caller is the module singleton or a
@@ -2362,7 +2384,12 @@ export async function buildChecks(
// that brains seeded only with code sources don't get spurious warnings
// about missing link/timeline coverage on pages that are test fixtures, not
// real knowledge entities.
- const eligibleStats = (await engine.executeRaw<{ entities: number; linked_from: number; timeline: number }>(
+ // #4191: an entity counts as CONNECTED with an inbound OR outbound link.
+ // Counting outbound only (from_page_id) contradicted onboard's
+ // entity_link_coverage (inbound EXISTS, target 70%): a brain of
+ // inbound-only entities (meetings link TO people) read ok there and
+ // warn here. Same in/out predicate + 70% target both places now.
+ const eligibleStats = (await engine.executeRaw<{ entities: number; connected: number; timeline: number }>(
`WITH eligible AS (
SELECT id FROM pages
WHERE deleted_at IS NULL
@@ -2372,12 +2399,14 @@ export async function buildChecks(
)
SELECT
(SELECT count(*)::int FROM eligible) AS entities,
- (SELECT count(DISTINCT from_page_id)::int FROM links WHERE from_page_id IN (SELECT id FROM eligible)) AS linked_from,
+ (SELECT count(*)::int FROM eligible e
+ WHERE EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = e.id)
+ OR EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id)) AS connected,
(SELECT count(DISTINCT page_id)::int FROM timeline_entries WHERE page_id IN (SELECT id FROM eligible)) AS timeline`,
- ))[0] ?? { entities: entityCount, linked_from: 0, timeline: 0 };
+ ))[0] ?? { entities: entityCount, connected: 0, timeline: 0 };
const eligibleEntityCount = Number(eligibleStats.entities ?? entityCount);
- const linkCoverage = eligibleEntityCount > 0 ? Number(eligibleStats.linked_from ?? 0) / eligibleEntityCount : 0;
+ const linkCoverage = eligibleEntityCount > 0 ? Number(eligibleStats.connected ?? 0) / eligibleEntityCount : 0;
const timelineCoverage = eligibleEntityCount > 0 ? Number(eligibleStats.timeline ?? 0) / eligibleEntityCount : 0;
const linkPct = (linkCoverage * 100).toFixed(0);
const timelinePct = (timelineCoverage * 100).toFixed(0);
@@ -2395,13 +2424,13 @@ export async function buildChecks(
status: 'ok',
message: `Only code/test fixture entity pages found (${entityCount}); graph_coverage not applicable`,
});
- } else if (linkCoverage >= 0.5 && timelineCoverage >= 0.5) {
- checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}%` });
+ } else if (linkCoverage >= 0.7 && timelineCoverage >= 0.5) {
+ checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity connected coverage (in/out) ${linkPct}%, entity timeline coverage ${timelinePct}%` });
} else {
checks.push({
name: 'graph_coverage',
status: 'warn',
- message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
+ message: `Entity connected coverage (in/out) ${linkPct}% (target 70%), entity timeline coverage ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
});
}
@@ -2499,6 +2528,18 @@ export async function buildChecks(
checks.push({ name: 'orphan_ratio', status: 'warn', message: 'Could not check orphan ratio' });
}
+ // 9c. stale_mentions (#3674, lands PR #3711) — read-only drift surface for
+ // by-mention links the current gazetteer no longer produces. Logic lives in
+ // doctor/checks/stale-mentions.ts (module-dir rule); it never throws.
+ progress.heartbeat('stale_mentions');
+ const staleMentionsHb = startHeartbeat(progress, 're-deriving by-mention links…');
+ try {
+ const { staleMentionsCheck } = await import('./doctor/checks/stale-mentions.ts');
+ checks.push(await staleMentionsCheck(engine));
+ } finally {
+ staleMentionsHb();
+ }
+
// 10. Integrity sample scan (v0.13 knowledge runtime).
// Read-only — no network, no writes, no resolver calls. Samples the first
// 500 pages by slug order and surfaces bare-tweet + dead-link counts as a
@@ -3225,11 +3266,9 @@ export async function buildChecks(
}
const total = high + medium + low;
if (total === 0) {
- checks.push({
- name: 'contradictions',
- status: 'ok',
- message: `Latest probe run (${latest.ran_at.slice(0, 10)}) found no suspected contradictions across ${latest.queries_evaluated} queries.`,
- });
+ // #3889: warn (not ok) when the latest run judged zero pairs but
+ // errored — "0 contradictions" from an all-error run is a lie.
+ checks.push({ name: 'contradictions', ...zeroTotalContradictionsCheck(latest) });
} else {
const ciLow = (latest.wilson_ci_lower * 100).toFixed(0);
const ciHigh = (latest.wilson_ci_upper * 100).toFixed(0);
@@ -3719,7 +3758,9 @@ export async function buildChecks(
const succeeded = parseInt((await engine.getConfig('ocr_succeeded')) ?? '0', 10);
const failedNoKey = parseInt((await engine.getConfig('ocr_failed_no_key')) ?? '0', 10);
const failedOther = parseInt((await engine.getConfig('ocr_failed_other')) ?? '0', 10);
- if (attempted === 0) {
+ // #3973: images skipped by the per-run OCR budget cap (maybeOcr).
+ const skippedBudget = parseInt((await engine.getConfig('ocr_skipped_budget')) ?? '0', 10);
+ if (attempted === 0 && skippedBudget === 0) {
checks.push({ name: 'ocr_health', status: 'ok', message: 'OCR not in use (or no images ingested with OCR opt-in)' });
} else if (succeeded === 0 && (failedNoKey > 0 || failedOther > 0)) {
const reasons: string[] = [];
@@ -3731,6 +3772,13 @@ export async function buildChecks(
message: `OCR is opted-in but no calls succeeded (${attempted} attempted, ${reasons.join(', ')}). ` +
`Fix: verify OPENAI_API_KEY is set, or set embedding_image_ocr=false to disable.`,
});
+ } else if (skippedBudget > 0) {
+ checks.push({
+ name: 'ocr_health',
+ status: 'warn',
+ message: `OCR budget cap skipped ${skippedBudget} image(s) (${succeeded}/${attempted} attempted calls succeeded). ` +
+ `Fix: raise embedding_image_ocr_max_images / embedding_image_ocr_max_usd and re-import, or ignore if the cap is intentional.`,
+ });
} else {
checks.push({
name: 'ocr_health',
@@ -3767,6 +3815,10 @@ export async function buildChecks(
// duplicates, undeclared DB-only pages, collector-output-in-db_only.
progress.heartbeat('content_hash_duplicates');
checks.push(await checkContentHashDuplicates(engine));
+ // #3970: code-page chunks missing symbol metadata (unhealable without
+ // reindex-code --force — the content_hash short-circuit skips them).
+ progress.heartbeat('code_chunk_metadata');
+ checks.push(await checkCodeChunkMetadata(engine));
progress.heartbeat('undeclared_db_only_pages');
checks.push(await checkUndeclaredDbOnlyPages(engine));
progress.heartbeat('db_only_collector_collision');
@@ -3807,6 +3859,10 @@ export async function buildChecks(
// graph_signals is enabled in the active mode bundle.
progress.heartbeat('graph_signals_coverage');
checks.push(await checkGraphSignalsCoverage(engine));
+ // #4222 junk_entity_hubs — near-empty entity pages that accreted huge
+ // edge counts (generic-token names like "Will"). Warn + list only.
+ progress.heartbeat('junk_entity_hubs');
+ checks.push(await checkJunkEntityHubs(engine));
// v0.37.0 brainstorm_health — migration v79, track_retrieval, calibration cold-start.
progress.heartbeat('brainstorm_health');
checks.push(await checkBrainstormHealth(engine));
diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts
index 4700b3152f..3b20d5c5dd 100644
--- a/src/commands/doctor/checks/calibration.ts
+++ b/src/commands/doctor/checks/calibration.ts
@@ -55,7 +55,10 @@ export async function checkContextualRetrievalCoverage(engine: BrainEngine): Pro
const rows = await engine.executeRaw<{ chunker_drift: number; mode_null: number }>(
`SELECT
COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,
- COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL)::int AS mode_null
+ -- #4009 belt+braces: extract receipts are audit artifacts stamped
+ -- mode 'none' at write time, but a reindex DB fallback can clear
+ -- the stamp — never count them as "never evaluated".
+ COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL AND type <> 'extract_receipt')::int AS mode_null
FROM pages
WHERE page_kind = 'markdown'
AND deleted_at IS NULL`,
diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.ts
index b7812a5d04..96b1794690 100644
--- a/src/commands/doctor/checks/core-health.ts
+++ b/src/commands/doctor/checks/core-health.ts
@@ -151,6 +151,44 @@ export async function pgvectorCheck(engine: BrainEngine): Promise<Check> {
}
}
+/**
+ * Doctor check: pages(source_id, slug) unique arbiter (#550).
+ *
+ * Every putPage upsert infers ON CONFLICT (source_id, slug). When the
+ * arbiter index/constraint is missing, EVERY page write fails brain-wide
+ * with "no unique or exclusion constraint matching the ON CONFLICT
+ * specification" — and the migration version counter can't see it. Keyed
+ * off the actual index shape via checkPagesUpsertArbiter.
+ */
+export async function pagesUpsertArbiterCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const { checkPagesUpsertArbiter } = await import('../../../core/pages-upsert-arbiter.ts');
+ const status = await checkPagesUpsertArbiter(engine);
+ if (!status.tablePresent || !status.needsRepair) {
+ return {
+ name: 'pages_upsert_arbiter',
+ status: 'ok',
+ message: status.tablePresent
+ ? 'pages has the UNIQUE(source_id, slug) upsert arbiter'
+ : 'no pages table yet',
+ };
+ }
+ const dupNote = status.duplicateGroups > 0
+ ? ` ${status.duplicateGroups} duplicate (source_id, slug) group(s) block the automatic repair — resolve the duplicate pages first, then`
+ : '';
+ return {
+ name: 'pages_upsert_arbiter',
+ status: 'fail',
+ message:
+ `pages is missing the UNIQUE(source_id, slug) arbiter — every page write fails with ` +
+ `"no unique or exclusion constraint" (#550).${dupNote} ` +
+ `Run \`gbrain apply-migrations --yes\` to heal it.`,
+ };
+ } catch {
+ return { name: 'pages_upsert_arbiter', status: 'warn', message: 'Could not check the pages upsert arbiter' };
+ }
+}
+
/**
* Doctor check: JSONB columns are not double-encoded as strings.
*
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 8f1698aba5..96ddbdaf11 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -21,7 +21,7 @@ import {
DERIVE_PHASE_DB_ONLY_DEFAULTS,
findDbOnlyCollisions,
} from '../../../core/storage-config.ts';
-import { slugifyPath } from '../../../core/sync.ts';
+import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/sync.ts';
import { resolveSourceLocalFilePath } from '../../../core/markdown.ts';
import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';
import type { Check } from '../../doctor.ts';
@@ -215,6 +215,13 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<C
const name = 'content_hash_duplicates';
const fix = 'Fix: gbrain pages delete <bare-slug> for each pair, then gbrain pages purge-deleted --older-than 0';
try {
+ // #3946: no shape predicates — EVERY same-source duplicate-content group
+ // surfaces (HAVING count(*) > 1 alone). Classification happens at render:
+ // a group holding BOTH a bare and a path-prefixed slug is the wrong-root
+ // import pattern (the bare slug is the accident, so the delete hint is
+ // safe); a group WITHOUT that shape (all-nested, or distinct bare slugs)
+ // is listed with NO delete hint (#3942 — either copy may be the canonical
+ // one that links point at, so deleting one automatically is a guess).
const rows = await engine.executeRaw<{ source_id: string; content_hash: string; slugs: string }>(
`SELECT source_id, content_hash,
string_agg(slug, '|' ORDER BY length(slug), slug) AS slugs
@@ -222,35 +229,104 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<C
WHERE deleted_at IS NULL AND content_hash IS NOT NULL AND content_hash <> ''
GROUP BY source_id, content_hash
HAVING count(*) > 1
- AND count(*) FILTER (WHERE strpos(slug, '/') = 0) > 0
- AND count(*) FILTER (WHERE strpos(slug, '/') > 0) > 0
LIMIT 50`,
);
if (rows.length === 0) {
- return { name, status: 'ok', message: 'No content-hash duplicate pairs (bare vs path-prefixed slugs)' };
+ return { name, status: 'ok', message: 'No same-source content-hash duplicate groups' };
}
let pairCount = 0;
const samples: string[] = [];
+ let otherGroupCount = 0;
+ const otherSamples: string[] = [];
for (const r of rows) {
const slugs = String(r.slugs).split('|');
+ const bare = slugs.filter(s => !s.includes('/'));
const prefixed = slugs.filter(s => s.includes('/'));
- for (const bare of slugs.filter(s => !s.includes('/'))) {
- const twin = prefixed.find(p => p.endsWith('/' + bare)) ?? prefixed[0];
- pairCount++;
- if (samples.length < 5) samples.push(`${bare} <-> ${twin}`);
+ if (bare.length > 0 && prefixed.length > 0) {
+ for (const b of bare) {
+ const twin = prefixed.find(p => p.endsWith('/' + b)) ?? prefixed[0];
+ pairCount++;
+ if (samples.length < 5) samples.push(`${b} <-> ${twin}`);
+ }
+ } else {
+ otherGroupCount++;
+ if (otherSamples.length < 5) otherSamples.push(slugs.join(' == '));
}
}
+ const parts: string[] = [];
+ if (pairCount > 0) {
+ parts.push(
+ `${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — ` +
+ `usually an import run from the wrong root, which drops the path prefix). ` +
+ `Sample: ${samples.join('; ')}. ${fix}`,
+ );
+ }
+ if (otherGroupCount > 0) {
+ parts.push(
+ `${otherGroupCount} duplicate-content group(s) with distinct slugs (no bare/nested wrong-root shape). ` +
+ `Sample: ${otherSamples.join('; ')}. Review which slug is canonical and consolidate manually — ` +
+ `no automatic delete hint (either copy may be the one links point at).`,
+ );
+ }
return {
name,
status: 'warn',
- message: `${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — usually an import run from the wrong root, which drops the path prefix). Sample: ${samples.join('; ')}. ${fix}`,
- details: { pair_count: pairCount, hash_groups: rows.length, sample_pairs: samples },
+ message: parts.join(' '),
+ details: {
+ pair_count: pairCount,
+ hash_groups: rows.length,
+ sample_pairs: samples,
+ distinct_slug_group_count: otherGroupCount,
+ sample_distinct_slug_groups: otherSamples,
+ },
};
} catch (e) {
return { name, status: 'warn', message: `Could not check content-hash duplicates: ${(e as Error).message}` };
}
}
+/**
+ * issue #3970 — code_chunk_metadata.
+ *
+ * Code pages whose chunks carry NO symbol metadata (symbol_name IS NULL AND
+ * language IS NULL) were chunked before the v0.19/v0.21 code chunker or
+ * re-imported through the markdown path — `code-def`, `code-refs`, and
+ * `query --lang/--symbol-kind` silently miss them. A plain sync or
+ * `reindex-code` never heals them (importCodeFile's content_hash
+ * short-circuit skips unchanged pages), so the cure is
+ * `gbrain reindex-code --force`. Raw SQL only (works on both engines).
+ */
+export async function checkCodeChunkMetadata(engine: BrainEngine): Promise<Check> {
+ const name = 'code_chunk_metadata';
+ try {
+ const rows = await engine.executeRaw<{ chunks: string | number; pages: string | number }>(
+ `SELECT COUNT(*)::text AS chunks, COUNT(DISTINCT c.page_id)::text AS pages
+ FROM content_chunks c
+ JOIN pages p ON p.id = c.page_id
+ WHERE p.type = 'code' AND p.deleted_at IS NULL
+ AND c.symbol_name IS NULL AND c.language IS NULL`,
+ );
+ const chunks = Number(rows[0]?.chunks ?? 0);
+ const pages = Number(rows[0]?.pages ?? 0);
+ if (chunks === 0) {
+ return { name, status: 'ok', message: 'All code-page chunks carry symbol metadata' };
+ }
+ return {
+ name,
+ status: 'warn',
+ message:
+ `${chunks} chunk(s) on ${pages} code page(s) have no symbol metadata ` +
+ `(symbol_name and language both NULL) — code-def/code-refs and ` +
+ `--lang/--symbol-kind filters miss them. A plain sync/reindex skips ` +
+ `unchanged pages via the content_hash short-circuit. ` +
+ `Fix: gbrain reindex-code --force`,
+ details: { chunks_missing_metadata: chunks, pages_affected: pages },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `Could not check code chunk metadata: ${(e as Error).message}` };
+ }
+}
+
/** Walk a repo for markdown files and return their slugified (lowercased) slugs. */
function collectMarkdownSlugs(root: string): Set<string> {
const out = new Set<string>();
@@ -270,6 +346,11 @@ function collectMarkdownSlugs(root: string): Set<string> {
const childRel = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) stack.push(childRel);
else if (/\.mdx?$/i.test(e.name)) out.add(slugifyPath(childRel).toLowerCase());
+ // #3766: code files are pages too (code-slug shape). Legacy code rows
+ // backfilled by migration 25 carry page_kind='markdown' without a
+ // type='code' re-stamp, so their slugs must count as file-backed or
+ // every one of them false-positives as "DB-only".
+ else if (isCodeFilePath(e.name)) out.add(slugifyCodePath(childRel).toLowerCase());
}
}
return out;
@@ -289,9 +370,18 @@ function collectMarkdownSlugs(root: string): Set<string> {
export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<Check> {
const name = 'undeclared_db_only_pages';
try {
- const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
+ // #3880: archived sources are out of scope for filesystem audits (v34
+ // legacy fallback, house style per pickSoleNonDefaultSource).
+ let sources: Array<{ id: string; local_path: string | null }>;
+ try {
+ sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ );
+ } catch {
+ sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ }
const checkable = sources.filter(s => s.local_path && existsSync(s.local_path));
if (checkable.length === 0) {
return { name, status: 'ok', message: 'Not applicable (no sources with a local repo path on this host)' };
@@ -308,8 +398,13 @@ export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<C
// already surfaces the config error itself.
}
const dbOnlyDirs = effectiveDbOnlyDirs(declared);
+ // #3766: skip properly-stamped code pages (type='code') — they live on
+ // the code lane, not the markdown backup story. Legacy code rows from
+ // the migration-25 backfill (page_kind='markdown', type never
+ // re-stamped) still flow through and match via the code-slug backed
+ // set collected below.
const rows = await engine.executeRaw<{ slug: string; source_path: string | null }>(
- `SELECT slug, source_path FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND page_kind = 'markdown'`,
+ `SELECT slug, source_path FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND page_kind = 'markdown' AND type IS DISTINCT FROM 'code'`,
[src.id],
);
if (rows.length === 0) continue;
@@ -370,9 +465,17 @@ export async function checkDbOnlyCollectorCollision(
if (collectors.length === 0) {
return { name, status: 'ok', message: 'No configured collectors declare output paths' };
}
- const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
+ // #3880: skip archived sources (v34 legacy fallback).
+ let sources: Array<{ id: string; local_path: string | null }>;
+ try {
+ sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ );
+ } catch {
+ sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ }
const hits: string[] = [];
for (const src of sources) {
if (!src.local_path || !existsSync(src.local_path)) continue;
@@ -639,7 +742,11 @@ export async function computeExtractHealthCheck(
return {
name,
status: 'warn',
- message: `${totalRollupFailures} rollup write failure(s) in last 7d (audit JSONL is source of truth; rebuild via gbrain extract status --rebuild-rollup)`,
+ // #3697: this hint used to name `gbrain extract status --rebuild-rollup`,
+ // which does not exist (the JSONL→rollup rebuild is a planned self-heal,
+ // not a shipped command). Say what is true instead of sending the
+ // operator to a usage error.
+ message: `${totalRollupFailures} rollup write failure(s) in last 7d. The rollup table is a best-effort cache — the audit JSONL under ~/.gbrain/audit/ is the source of truth, and counts here may undercount until the 7-day window rolls past the failures. No action needed unless failures keep accumulating (then check DB connectivity/permissions).`,
details: {
schema_version: 1,
kinds,
@@ -688,7 +795,7 @@ export async function checkSyncFreshness(
// `gbrain sync`'s up-to-date predicate at sync.ts:1057+1075 checks.
// Columns existed pre-v0.41 (writeSyncAnchor / writeChunkerVersion);
// no schema migration needed.
- const sources = await engine.executeRaw<{
+ type FreshnessSourceRow = {
id: string;
name: string;
local_path: string | null;
@@ -696,11 +803,21 @@ export async function checkSyncFreshness(
last_commit: string | null;
chunker_version: string | null;
newest_content_at: Date | null;
- }>(
- // v0.41.32.0: newest_content_at feeds the REMOTE (non-localOnly) lag so
- // doctorReportRemote never shells out to git on a DB-supplied local_path.
- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL`,
- );
+ };
+ // v0.41.32.0: newest_content_at feeds the REMOTE (non-localOnly) lag so
+ // doctorReportRemote never shells out to git on a DB-supplied local_path.
+ // #3880: archived sources don't participate in freshness health (v34
+ // legacy fallback).
+ let sources: FreshnessSourceRow[];
+ try {
+ sources = await engine.executeRaw<FreshnessSourceRow>(
+ `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ );
+ } catch {
+ sources = await engine.executeRaw<FreshnessSourceRow>(
+ `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL`,
+ );
+ }
if (sources.length === 0) {
return {
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 8832500455..d5663e04b0 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -636,3 +636,107 @@ export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine):
}
}
+
+// ---------------------------------------------------------------------------
+// #4222 junk_entity_hubs — near-empty entity pages with huge edge counts
+// ---------------------------------------------------------------------------
+
+/**
+ * Default thresholds for the junk-hub heuristic: a page with almost no
+ * content of its own (<= JUNK_HUB_MAX_CHUNKS chunks) but a very large edge
+ * count (> JUNK_HUB_EDGE_THRESHOLD links in either direction) is almost
+ * always an extractor-minted generic-token entity ("Will", "Info") that the
+ * by-mention auto-linker turned into a mega-hub. Exported so tests and
+ * out-of-tree tooling reference the shipped numbers instead of copying them.
+ */
+export const JUNK_HUB_EDGE_THRESHOLD = 1000;
+export const JUNK_HUB_MAX_CHUNKS = 2;
+
+/**
+ * #4222 junk_entity_hubs doctor check.
+ *
+ * Surfaces (warn + list — NEVER auto-delete) pages whose edge count dwarfs
+ * their content: chunks <= maxChunks AND total edges (from + to) >
+ * edgeThreshold. These poison graph signals and relational recall. The
+ * mint gate (enrichEntity) and gazetteer drop (buildGazetteer) stop NEW
+ * accretion; this check finds hubs that predate those gates so the owner
+ * can review/merge/delete them deliberately.
+ *
+ * `opts` exists for tests (small corpora can't reach 1000 edges); the
+ * production call site uses the exported defaults.
+ */
+export async function checkJunkEntityHubs(
+ engine: BrainEngine,
+ opts?: { edgeThreshold?: number; maxChunks?: number },
+): Promise<Check> {
+ const edgeThreshold = opts?.edgeThreshold ?? JUNK_HUB_EDGE_THRESHOLD;
+ const maxChunks = opts?.maxChunks ?? JUNK_HUB_MAX_CHUNKS;
+ try {
+ const rows = await engine.executeRaw<{
+ slug: string;
+ source_id: string | null;
+ edges: number;
+ chunks: number;
+ }>(
+ `WITH edge_counts AS (
+ SELECT page_id, COUNT(*)::int AS edges FROM (
+ SELECT from_page_id AS page_id FROM links
+ UNION ALL
+ SELECT to_page_id AS page_id FROM links
+ ) e
+ GROUP BY page_id
+ HAVING COUNT(*) > $1
+ ),
+ chunk_counts AS (
+ SELECT page_id, COUNT(*)::int AS chunks
+ FROM content_chunks
+ GROUP BY page_id
+ )
+ SELECT p.slug, p.source_id, ec.edges, COALESCE(cc.chunks, 0)::int AS chunks
+ FROM edge_counts ec
+ JOIN pages p ON p.id = ec.page_id AND p.deleted_at IS NULL
+ LEFT JOIN chunk_counts cc ON cc.page_id = ec.page_id
+ WHERE COALESCE(cc.chunks, 0) <= $2
+ ORDER BY ec.edges DESC
+ LIMIT 20`,
+ [edgeThreshold, maxChunks],
+ );
+
+ if (rows.length === 0) {
+ return {
+ name: 'junk_entity_hubs',
+ status: 'ok',
+ message: `No junk entity hubs (pages with <=${maxChunks} chunks and >${edgeThreshold} edges)`,
+ };
+ }
+
+ const list = rows
+ .map(r => ` ${r.slug}${(r.source_id ?? 'default') !== 'default' ? ` [${r.source_id}]` : ''} — ${r.edges} edges, ${r.chunks} chunk(s)`)
+ .join('\n');
+ return {
+ name: 'junk_entity_hubs',
+ status: 'warn',
+ message:
+ `${rows.length} near-empty page(s) with >${edgeThreshold} edges — likely generic-token entities ` +
+ `("Will", "Info") minted by an extractor and inflated by mention auto-links:\n${list}\n` +
+ `Review each page and merge/delete deliberately (nothing is auto-deleted). ` +
+ `New accretion is already gated: enrichEntity refuses generic single-token mints and ` +
+ `buildGazetteer drops single-generic-token person titles.`,
+ details: {
+ hubs: rows.map(r => ({
+ slug: r.slug,
+ source_id: r.source_id ?? 'default',
+ edges: r.edges,
+ chunks: r.chunks,
+ })),
+ },
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'junk_entity_hubs',
+ status: 'warn',
+ message: `Could not check for junk entity hubs: ${msg}`,
+ };
+ }
+}
diff --git a/src/commands/doctor/checks/stale-mentions.ts b/src/commands/doctor/checks/stale-mentions.ts
new file mode 100644
index 0000000000..f915affc0d
--- /dev/null
+++ b/src/commands/doctor/checks/stale-mentions.ts
@@ -0,0 +1,77 @@
+/**
+ * stale_mentions doctor check (#3674, lands PR #3711) — auto-linked mentions
+ * the current gazetteer no longer produces.
+ *
+ * `extract links --by-mention` writes through addLinksBatch, which is purely
+ * additive, and put_page reconciliation deliberately excludes 'mentions'. So
+ * a link survives its own justification: rewrite a body so it stops naming
+ * the entity, delete or retype the entity page, or change the tokenizer, and
+ * the row stays. Re-running the scan does not help — it adds today's correct
+ * links ALONGSIDE the old ones.
+ *
+ * READ-ONLY by design; the write-side repair is the opt-in
+ * `gbrain extract links --by-mention --rebuild` sweep (same issue). No
+ * RemediationStep here — a destructive write doesn't belong on a doctor
+ * check's back.
+ *
+ * Never 'fail': the data is wrong but a per-pair `gbrain unlink` workaround
+ * (or the --rebuild sweep) exists, which is the p2 bar.
+ *
+ * Lives in the doctor module dir per the peeled-façade rule — new code goes
+ * here, not back into doctor.ts.
+ */
+
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { scanStaleMentions } from '../../../core/by-mention.ts';
+
+export async function staleMentionsCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const res = await scanStaleMentions(engine);
+ // Say what was NOT covered rather than implying the whole brain was.
+ const coverage = res.pagesScanned < res.totalPagesWithMentions
+ ? ` (sampled ${res.pagesScanned} of ${res.totalPagesWithMentions} pages carrying mentions links)`
+ : '';
+
+ if (res.totalPagesWithMentions === 0) {
+ return {
+ name: 'stale_mentions',
+ status: 'ok',
+ message: 'No by-mention links in this brain.',
+ };
+ }
+ if (res.staleLinks === 0) {
+ return {
+ name: 'stale_mentions',
+ status: 'ok',
+ message: `Re-derived ${res.linksScanned} by-mention link(s) across ${res.pagesScanned} page(s)${coverage}; all still follow from the current gazetteer.`,
+ };
+ }
+ const kinds = Object.entries(res.staleByKind)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([k, n]) => `${n} ${k}`)
+ .join(', ');
+ const eg = res.examples.map(e => `${e.from} -> ${e.to}`).join(', ');
+ // An empty gazetteer makes EVERY mentions row unreproducible, which is
+ // a different diagnosis from ordinary drift — name it, or the operator
+ // reads "everything is stale" and starts deleting real links.
+ const why = res.emptyGazetteer
+ ? 'This brain currently has NO linkable entity pages, so every mentions row is unreproducible — check whether entity pages were deleted or retyped before treating these as garbage. '
+ : '';
+ return {
+ name: 'stale_mentions',
+ status: 'warn',
+ message:
+ `${res.staleLinks} of ${res.linksScanned} by-mention link(s) no longer follow from the current gazetteer${coverage} (${kinds}). ` +
+ `${why}Re-running the scan will NOT remove them — the write path is additive. ` +
+ `Remove individually with: gbrain unlink <from> <to> --link-type mentions --link-source mentions. ` +
+ `e.g. ${eg}`,
+ };
+ } catch (e) {
+ return {
+ name: 'stale_mentions',
+ status: 'warn',
+ message: `stale-mentions scan skipped: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 4403427115..4b8d958690 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -139,7 +139,9 @@ export async function doctorReportRemote(
checks.push({
name: 'timeline_dedup_index',
status: 'ok',
- message: idx.tablePresent ? 'idx_timeline_dedup has the 4-column shape' : 'no timeline_entries table yet',
+ // #3737: canonical shape keys md5(summary) so long summaries can't
+ // overflow the btree row cap.
+ message: idx.tablePresent ? 'idx_timeline_dedup has the md5-keyed 4-column shape' : 'no timeline_entries table yet',
});
} else {
checks.push({
@@ -147,7 +149,7 @@ export async function doctorReportRemote(
status: 'fail',
message:
`idx_timeline_dedup is ${idx.indexPresent ? `(${idx.columns.join(', ')})` : 'absent'}, ` +
- `expected (page_id, date, summary, source) — timeline writes are failing (#2038). ` +
+ `expected (page_id, date, md5(summary), source) — timeline writes are failing (#2038/#3737). ` +
`Run \`gbrain apply-migrations --force-schema\` to heal it.`,
});
}
@@ -155,6 +157,14 @@ export async function doctorReportRemote(
checks.push({ name: 'timeline_dedup_index', status: 'warn', message: 'Could not check idx_timeline_dedup shape' });
}
+ // 2c. #550: pages(source_id, slug) upsert arbiter — same drift class as 2b.
+ // When the arbiter is missing, EVERY putPage fails with "no unique or
+ // exclusion constraint" and the version counter can't see it.
+ {
+ const { pagesUpsertArbiterCheck } = await import('./checks/core-health.ts');
+ checks.push(await pagesUpsertArbiterCheck(engine));
+ }
+
// v0.42.x — Life Chronicle (#2390): orphaned event projections. Reads already
// hide projections whose event page is soft-deleted (read-time correctness);
// this always-run probe surfaces the cleanup backlog. Keyed off the real
diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.ts
index 56fc169444..c3724403b5 100644
--- a/src/commands/doctor/schema-pack-checks.ts
+++ b/src/commands/doctor/schema-pack-checks.ts
@@ -18,8 +18,18 @@ import type { Check } from '../doctor.ts';
export async function checkSchemaPackActive(engine: BrainEngine): Promise<Check> {
try {
const { loadActivePack } = await import('../../core/schema-pack/load-active.ts');
- const { loadConfig } = await import('../../core/config.ts');
- const pack = await loadActivePack({ cfg: loadConfig(), remote: false });
+ const { loadConfigFileOnly } = await import('../../core/config.ts');
+ // #3792: thread the DB-plane schema_pack (tier 4) so doctor resolves the
+ // SAME pack as the engine/onboard checks on brains whose active pack was
+ // flipped via `gbrain config set schema_pack` / unify-types — without it,
+ // doctor reported the home-config pack while every query ran the DB one.
+ // File-only config preserves tier-6 without merging transient env/db
+ // state (matches onboard/checks.ts's checkPackUpgradeAvailable).
+ let dbConfig: string | undefined;
+ try {
+ dbConfig = (await engine.getConfig('schema_pack')) ?? undefined;
+ } catch { /* engine.config may not exist on very old brains */ }
+ const pack = await loadActivePack({ cfg: loadConfigFileOnly(), remote: false, dbConfig });
return {
name: 'schema_pack_active',
status: 'ok',
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 8e385f2da1..15db5d092a 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../core/engine.ts';
-import { embedBatch, currentEmbeddingSignature } from '../core/embedding.ts';
+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';
@@ -23,8 +23,39 @@ import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';
import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';
import { AITransientError } from '../core/ai/errors.ts';
import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';
-import { titleTierCorpusGeneration } from '../core/contextual-retrieval-service.ts';
-import type { Page } from '../core/types.ts';
+import {
+ restampIfDemotedToTitleTier,
+ embedBatchWithBackoff,
+ isEmbedRetriableError,
+ isTransientNetworkEmbedError,
+ type EmbedBatchWithBackoffOpts,
+} from '../core/embed-retry.ts';
+
+// Peeled to src/core/embed-retry.ts (core→commands layering fix: core modules
+// import-file.ts / embed-stale.ts consume these, and a commands module in
+// their value closure risks a real ESM cycle). Façade rule: embed.ts keeps
+// re-exporting its historical surface so import sites and tests never chase
+// the peel.
+export {
+ restampIfDemotedToTitleTier,
+ MAX_RATE_LIMIT_RETRIES,
+ RATE_LIMIT_FALLBACK_MS,
+ RATE_LIMIT_PAD_MS,
+ RATE_LIMIT_JITTER,
+ detect429FromCause,
+ detectGatewayErrorFromCause,
+ parseRetryDelayMs,
+ RATE_LIMIT_ATTEMPT_FLOOR_MS,
+ _setRateLimitFloorsForTests,
+ rateLimitDelayMs,
+ abortableSleep,
+ embedBatchWithBackoff,
+ TRANSIENT_NET_BASE_MS,
+ TRANSIENT_NET_MAX_MS,
+ transientBackoffMs,
+ isTransientNetworkEmbedError,
+} from '../core/embed-retry.ts';
+export type { EmbedBatchWithBackoffOpts } from '../core/embed-retry.ts';
/** #3037: cap failure samples so a corpus-wide outage doesn't bloat --json. */
const FAILURE_SAMPLE_CAP = 10;
@@ -41,23 +72,6 @@ function recordFailure(result: EmbedResult, chunkCount: number, slug: string, e:
}
}
-/**
- * #3507 — after a plain re-embed fully re-embedded a `per_chunk_synopsis`
- * page at the title-only tier (see wrapChunkTextsForStoredMode), restamp the
- * page's CR state to 'title' so `contextual_retrieval_mode` keeps describing
- * the vectors actually in the column. The reindex sweep restores the synopsis
- * tier later. No-op for every other mode.
- */
-export async function restampIfDemotedToTitleTier(
- engine: BrainEngine,
- page: Pick<Page, 'contextual_retrieval_mode'> | null | undefined,
- slug: string,
- sourceId: string,
-): Promise<void> {
- if (page?.contextual_retrieval_mode !== 'per_chunk_synopsis') return;
- await engine.updatePageContextualRetrievalState(slug, sourceId, 'title', titleTierCorpusGeneration());
-}
-
export interface EmbedOpts {
/** Embed ALL pages (every chunk). */
all?: boolean;
@@ -1807,172 +1821,6 @@ async function embedAllStale(
}
}
-/**
- * v0.33.3: rate-limit-aware embedBatch wrapper.
- * #3966: also retries transient gateway errors (502/503/504) that NIM and
- * similar providers emit under sustained bulk load.
- *
- * The OpenAI SDK has built-in retry with exponential backoff, but its
- * backoff window (max ~4s) is too short for TPM (tokens-per-minute)
- * rate limits on large pages (~90K tokens). This wrapper catches
- * 429-shaped and gateway-overload errors, parses the retry delay from
- * the error message (e.g. "Please try again in 248ms"), and sleeps before retrying.
- *
- * v0.33.4 hardening (codex + re-review findings):
- * - D4: detect 429 via the wrapped error's `cause.status` (the gateway's
- * normalizeAIError stores the original error there). Bare `e.status`
- * never fires against an `AITransientError` wrap. Message-match stays
- * as a fallback.
- * - D4a: pass `maxRetries: 0` through `embedBatch` so the AI SDK's
- * default 2-retry stack doesn't multiply this wrapper's 5 attempts.
- * - D2: jitter the parsed delay ±30% so 20 concurrent workers don't
- * resynchronize on the next 429 wave.
- * - D3a/D8: when an external AbortSignal fires (wall-clock budget), the
- * sleep wakes up early AND the abortSignal is threaded into the gateway
- * embed call so an in-flight HTTP request cancels too.
- *
- * Up to MAX_RATE_LIMIT_RETRIES attempts with the parsed (jittered) delay
- * (or a 60s fallback when the message can't be parsed).
- *
- * @internal Exported for unit tests; not part of the public surface.
- */
-export const MAX_RATE_LIMIT_RETRIES = 5;
-export const RATE_LIMIT_FALLBACK_MS = 60_000;
-export const RATE_LIMIT_PAD_MS = 500;
-export const RATE_LIMIT_JITTER = 0.3;
-
-export interface EmbedBatchWithBackoffOpts {
- abortSignal?: AbortSignal;
-}
-
-/**
- * Walk the cause chain looking for a 429 status. The current
- * `normalizeAIError` wraps once into `AITransientError` with `cause = original`,
- * so one level is sufficient — but iterate to handle future wrap layers
- * defensively (max 5 levels to bound a malformed cyclic chain).
- *
- * @internal exported for unit tests.
- */
-export function detect429FromCause(e: unknown): boolean {
- let cur: unknown = e;
- for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
- const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
- if (obj.status === 429 || obj.statusCode === 429) return true;
- cur = obj.cause;
- }
- return false;
-}
-
-/** Gateway overload statuses retried with the same backoff as 429 (#3966). */
-const RETRIABLE_GATEWAY_STATUSES = new Set([502, 503, 504]);
-
-/**
- * Walk the cause chain looking for 502/503/504. Same depth bound as
- * detect429FromCause — one normalizeAIError wrap is typical.
- *
- * @internal exported for unit tests.
- */
-export function detectGatewayErrorFromCause(e: unknown): boolean {
- let cur: unknown = e;
- for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
- const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
- const status = obj.status ?? obj.statusCode;
- if (typeof status === 'number' && RETRIABLE_GATEWAY_STATUSES.has(status)) return true;
- cur = obj.cause;
- }
- return false;
-}
-
-/**
- * Parse a Retry-After hint out of an OpenAI-style 429 message. Falls back
- * to `RATE_LIMIT_FALLBACK_MS` when the message can't be parsed. Adds
- * `RATE_LIMIT_PAD_MS` padding and `RATE_LIMIT_JITTER` randomization so
- * concurrent workers don't resynchronize.
- *
- * @internal exported for unit tests.
- */
-export function parseRetryDelayMs(msg: string, rng: () => number = Math.random): number {
- let delayMs = RATE_LIMIT_FALLBACK_MS;
- const msMatch = msg.match(/try again in (\d+)ms/i);
- const secMatch = msg.match(/try again in ([\d.]+)s/i);
- if (msMatch) delayMs = parseInt(msMatch[1], 10) + RATE_LIMIT_PAD_MS;
- else if (secMatch) delayMs = Math.ceil(parseFloat(secMatch[1]) * 1000) + RATE_LIMIT_PAD_MS;
- // D2: ±30% jitter to decorrelate the herd of 20 workers.
- const jitterFactor = 1 + (rng() * 2 - 1) * RATE_LIMIT_JITTER;
- return Math.max(1, Math.floor(delayMs * jitterFactor));
-}
-
-/**
- * Sleep for `ms` milliseconds. Resolves early (not rejects) when `signal`
- * fires, so the retry loop's caller can re-check `signal.aborted` and
- * exit cleanly without an unhandled rejection.
- *
- * @internal exported for unit tests.
- */
-export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
- return new Promise((resolve) => {
- if (signal?.aborted) {
- resolve();
- return;
- }
- const timer = setTimeout(() => {
- signal?.removeEventListener('abort', onAbort);
- resolve();
- }, ms);
- const onAbort = () => {
- clearTimeout(timer);
- signal?.removeEventListener('abort', onAbort);
- resolve();
- };
- signal?.addEventListener('abort', onAbort, { once: true });
- });
-}
-
-export async function embedBatchWithBackoff(
- texts: string[],
- opts: EmbedBatchWithBackoffOpts = {},
-): Promise<Float32Array[]> {
- const signal = opts.abortSignal;
- for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
- if (signal?.aborted) throw new Error('embed budget aborted');
- try {
- // D4a + D8: maxRetries:0 disables the SDK's stacked retries (so this
- // wrapper is the single source of truth) and abortSignal threads
- // through to the gateway so an in-flight HTTP request cancels mid-fetch.
- return await embedBatch(texts, { maxRetries: 0, ...(signal && { abortSignal: signal }) });
- } catch (e: unknown) {
- // If the budget fired we may have been aborted mid-fetch; bubble out.
- if (signal?.aborted) throw e;
- const msg = e instanceof Error ? e.message : String(e);
- if (!isEmbedRetriableError(e) || attempt === MAX_RATE_LIMIT_RETRIES) throw e;
-
- const delayMs = parseRetryDelayMs(msg);
- // One label for every retriable class — 429 and gateway blips share the loop.
- serr(` [embed-retry] attempt ${attempt + 1}/${MAX_RATE_LIMIT_RETRIES}, waiting ${delayMs}ms...`);
- await abortableSleep(delayMs, signal);
- }
- }
- // Unreachable, but TypeScript needs it.
- return embedBatch(texts);
-}
-
-/**
- * Retriable embed errors: 429 rate limits plus transient gateway overload
- * (502/503/504). Shared by embedBatchWithBackoff (retry decision) and
- * embedPageTexts (fan-out decision). D4: structured detection first
- * (gateway-wrapped errors via cause chain); message-match as fallback for
- * providers whose wrappers strip `cause.status`.
- */
-function isEmbedRetriableError(e: unknown): boolean {
- const msg = e instanceof Error ? e.message : String(e);
- return (
- detect429FromCause(e) ||
- detectGatewayErrorFromCause(e) ||
- /rate.?limit|429/i.test(msg) ||
- /bad gateway|502|503|504|service unavailable|gateway timeout/i.test(msg)
- );
-}
-
/** Walk the cause chain (like detect429FromCause) for the first HTTP status. */
function statusFromCause(e: unknown): number | undefined {
let cur: unknown = e;
@@ -2021,7 +1869,9 @@ async function embedPageTexts(
} catch (e: unknown) {
if (opts.abortSignal?.aborted) throw e; // shutdown, not a chunk problem
if (texts.length <= 1) throw e; // nothing to isolate
- if (isEmbedRetriableError(e) || e instanceof AITransientError) throw e;
+ // #3374 — network-transient exhaustion isn't chunk-specific either:
+ // fanning out during an outage multiplies failing calls per page.
+ if (isEmbedRetriableError(e) || isTransientNetworkEmbedError(e) || e instanceof AITransientError) throw e;
const status = statusFromCause(e);
if (status === 401 || status === 403) throw e;
diff --git a/src/commands/enrich.ts b/src/commands/enrich.ts
index 34913e95e6..3e3788b5fc 100644
--- a/src/commands/enrich.ts
+++ b/src/commands/enrich.ts
@@ -34,7 +34,7 @@ import type { EnrichCandidate, PageType } from '../core/types.ts';
import { operations } from '../core/operations.ts';
import type { OperationContext } from '../core/operations.ts';
import { configureGatewayIfUninitialized, isAvailable, chat, getChatModel, withBudgetTracker } from '../core/ai/gateway.ts';
-import { BudgetTracker, BudgetExhausted, type BudgetReason } from '../core/budget/budget-tracker.ts';
+import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason } from '../core/budget/budget-tracker.ts';
import { hybridSearch } from '../core/search/hybrid.ts';
import { serializeMarkdown } from '../core/markdown.ts';
import { listSources } from '../core/sources-ops.ts';
@@ -164,6 +164,9 @@ export interface EnrichResult {
budget_exhausted_reason?: BudgetReason;
/** Model that triggered a no_pricing abort, when the tracker knew it (#4032). */
budget_exhausted_model?: string;
+ /** #2504 — first pool failure ('slug: message'), so pages_failed > 0 always
+ * carries a WHY (pool.failures was previously write-only). */
+ first_failure?: string;
}
// ---------------------------------------------------------------------------
@@ -479,28 +482,44 @@ 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 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);
+ const done = new Set<string>(opts.force ? [] : await loadOpCheckpoint(engine, cpKey));
+
// Candidate enumeration — ONE source-aware, memory-bounded SQL query.
+ // #3629: over-fetch by the number of checkpointed keys so already-done
+ // pages sitting at the top of the ranking can't wedge the limit window
+ // (limit=N with N done candidates used to yield pending=[] forever while
+ // lower-ranked candidates never got a turn), then slice back to `limit`.
const candidates = await engine.listEnrichCandidates({
types,
sourceId,
thinThreshold,
order,
- limit,
+ limit: limit + done.size,
reenrichAfterMs,
});
result.candidates_considered = candidates.length;
if (candidates.length === 0) return result;
- const fp = enrichFingerprint({ sourceId, types, order, thinThreshold, model });
- const cpKey = checkpointKey(fp);
+ // Filter out already-completed candidates (resume), bounded to this run's
+ // requested window.
+ const pending = candidates
+ .filter((c) => !done.has(completedKey(sourceId, c.slug)))
+ .slice(0, limit);
+ // #3629: nothing to do → return WITHOUT recordCompleted. Re-recording the
+ // same done set on every no-op run would refresh the checkpoint's activity
+ // clock and the 7-day purge TTL would never expire, making SKIP keys
+ // permanent instead of decaying (the intended retry channel; --force is
+ // the immediate one).
+ if (pending.length === 0) return result;
const body = async () => {
- if (opts.force) await clearOpCheckpoint(engine, cpKey);
- const done = new Set<string>(opts.force ? [] : await loadOpCheckpoint(engine, cpKey));
-
- // Filter out already-completed candidates (resume).
- const pending = candidates.filter((c) => !done.has(completedKey(sourceId, c.slug)));
-
const oneCtx: EnrichOneCtx = {
engine,
sourceId,
@@ -544,13 +563,28 @@ export async function runEnrichCore(
result.pages_failed = pool.errored;
+ // #2504 — pool.failures used to be write-only: an operator saw
+ // pages_failed:N with zero reason anywhere (the pricing hard-fail looked
+ // like a model/route problem). Log the first failure loud and carry it on
+ // the result so cycle/JSON consumers see WHY.
+ if (pool.failures.length > 0) {
+ const f = pool.failures[0];
+ const fMsg = f.error instanceof Error ? f.error.message : String(f.error);
+ result.first_failure = `${f.label}: ${fMsg}`;
+ process.stderr.write(
+ `[enrich:${sourceId}] ${pool.errored} page(s) failed; first: ${f.label}: ${fMsg}\n`,
+ );
+ }
+
if (!dryRun) {
+ // #3629: the checkpoint is NOT cleared on a clean run any more. The old
+ // clear made SKIP keys vanish the moment a run completed, so a page
+ // whose synthesis said SKIP (still thin, still a candidate) was
+ // re-billed on every subsequent run — the "unchanged page never
+ // re-spends" contract only held mid-run. Enriched pages drop out of the
+ // thin set anyway; SKIP keys decay via the cycle purge's 7-day TTL
+ // (purgeStaleCheckpoints) and `--force` clears immediately.
await recordCompleted(engine, cpKey, [...done]);
- // Clear the checkpoint only on a clean, complete run so an immediate
- // re-run starts fresh (enriched pages drop out of the thin set anyway).
- if (!pool.aborted && !signal?.aborted) {
- await clearOpCheckpoint(engine, cpKey);
- }
}
};
@@ -562,9 +596,15 @@ export async function runEnrichCore(
// would serialize to null in audit rows). undefined-when-unset still → DEFAULT.
const resolvedCap =
opts.maxCostUsd === Infinity ? undefined : (opts.maxCostUsd ?? DEFAULT_MAX_COST_USD);
+ // #4312: operator price overrides (config `pricing.overrides`) reach the
+ // tracker at construction, so proxy-routed models (litellm chat AND embed)
+ // with a declared rate price normally instead of TX2 no_pricing-aborting.
+ // Loaded only on the internal-tracker path (`??` short-circuits); an
+ // externally-supplied tracker (cycle phase) carries its own overrides.
const tracker = opts.budgetTracker ?? new BudgetTracker({
maxCostUsd: resolvedCap,
label: `enrich:${sourceId}`,
+ pricingOverrides: await loadPricingOverrides(engine),
});
try {
if (opts.budgetTracker) {
@@ -823,6 +863,10 @@ function addInto(agg: EnrichResult, r: EnrichResult): void {
agg.budget_exhausted_reason = r.budget_exhausted_reason;
agg.budget_exhausted_model = r.budget_exhausted_model;
}
+ // #2504 — first failure seen across sources sticks (a sample, not a log).
+ if (r.first_failure && agg.first_failure === undefined) {
+ agg.first_failure = r.first_failure;
+ }
}
/**
diff --git a/src/commands/eval-suspected-contradictions.ts b/src/commands/eval-suspected-contradictions.ts
index 553e08565f..02bdf78464 100644
--- a/src/commands/eval-suspected-contradictions.ts
+++ b/src/commands/eval-suspected-contradictions.ts
@@ -43,6 +43,7 @@ import {
import { maybePromptForCostBeforeProbe } from '../core/eval-contradictions/cost-prompt.ts';
import type {
ContradictionFinding,
+ ProbeReport,
Severity,
} from '../core/eval-contradictions/types.ts';
@@ -237,6 +238,68 @@ function exclusiveOneOf(...flags: Array<unknown>): boolean {
return count === 1;
}
+/**
+ * Build the human summary (stderr) for one probe run. Exported for tests.
+ *
+ * #3889 honesty rules:
+ * - A `run_status === 'judge_failed'` run (every judge call errored, zero
+ * verdicts) must NOT render the "0 / N contradictions" headline or the
+ * Wilson CI — both would present an all-error run as a clean pass.
+ * A loud banner replaces them.
+ * - The judge-errors line prints ALL FIVE error buckets (unknown included)
+ * so the printed buckets always sum to the printed total.
+ */
+export function buildRunSummaryLines(r: ProbeReport, capHitMidRun: boolean): string[] {
+ const pct = (n: number) => (n * 100).toFixed(0);
+ const judgeFailed = r.run_status === 'judge_failed';
+ const lines: string[] = [];
+ lines.push(``);
+ lines.push(`Results: ${r.queries_evaluated} queries, top-${r.top_k} each, judge=${r.judge_model}`);
+ if (judgeFailed) {
+ lines.push(` *** JUDGE FAILED: every judge call errored (${r.judge_errors.total} errors, 0 verdicts). ***`);
+ lines.push(` *** No pair was scored — do NOT read this run as "0 contradictions". ***`);
+ lines.push(` Queries with >=1 contradiction: unknown (judge produced no verdicts)`);
+ } else {
+ lines.push(` Queries with >=1 contradiction: ${r.queries_with_contradiction} / ${r.queries_evaluated} (${pct(r.queries_with_contradiction / Math.max(1, r.queries_evaluated))}%)`);
+ // v0.34 / Lane A2: broader finding count alongside the strict contradiction count.
+ lines.push(` Queries with >=1 finding (any verdict): ${r.queries_with_any_finding} / ${r.queries_evaluated}`);
+ lines.push(` Wilson CI 95%: ${pct(r.calibration.wilson_ci_95.lower)}–${pct(r.calibration.wilson_ci_95.upper)}%`);
+ if (r.calibration.small_sample_note) {
+ lines.push(` Note: ${r.calibration.small_sample_note}`);
+ }
+ }
+ lines.push(` Total findings flagged: ${r.total_contradictions_flagged}`);
+ // v0.34 / Lane A2: per-verdict breakdown surfaces what kinds of finding
+ // dominated the run — distinguishes temporal noise from genuine conflicts.
+ const vb = r.verdict_breakdown;
+ lines.push(` Verdict breakdown:`);
+ lines.push(` contradiction: ${vb.contradiction}`);
+ lines.push(` temporal_supersession: ${vb.temporal_supersession}`);
+ lines.push(` temporal_regression: ${vb.temporal_regression}`);
+ lines.push(` temporal_evolution: ${vb.temporal_evolution}`);
+ lines.push(` negation_artifact: ${vb.negation_artifact}`);
+ lines.push(` no_contradiction: ${vb.no_contradiction}`);
+ lines.push(` Judge errors: ${r.judge_errors.total} (parse_fail=${r.judge_errors.parse_fail} timeout=${r.judge_errors.timeout} http_5xx=${r.judge_errors.http_5xx} refusal=${r.judge_errors.refusal} unknown=${r.judge_errors.unknown})`);
+ lines.push(` Cache: ${r.cache.hits} hits / ${r.cache.misses} misses (${pct(r.cache.hit_rate)}% hit-rate)`);
+ lines.push(` Source-tier breakdown:`);
+ lines.push(` curated_vs_curated: ${r.source_tier_breakdown.curated_vs_curated}`);
+ lines.push(` curated_vs_bulk: ${r.source_tier_breakdown.curated_vs_bulk}`);
+ lines.push(` bulk_vs_bulk: ${r.source_tier_breakdown.bulk_vs_bulk}`);
+ lines.push(` other: ${r.source_tier_breakdown.other}`);
+ lines.push(` Cost: $${r.cost_usd.total.toFixed(4)} (judge $${r.cost_usd.judge.toFixed(4)} + embedding $${r.cost_usd.embedding.toFixed(6)})`);
+ lines.push(` Duration: ${r.duration_ms}ms`);
+ if (r.hot_pages.length > 0) {
+ lines.push(` Hot pages:`);
+ for (const p of r.hot_pages.slice(0, 5)) {
+ lines.push(` ${p.slug} (${p.appearances}, max ${p.max_severity})`);
+ }
+ }
+ if (capHitMidRun) {
+ lines.push(` *** budget cap hit mid-run; report is partial ***`);
+ }
+ return lines;
+}
+
async function runRun(engine: BrainEngine, f: ParsedFlags): Promise<void> {
if (!exclusiveOneOf(f.queriesFile, f.query, f.fromCapture)) {
console.error(
@@ -318,47 +381,7 @@ async function runRun(engine: BrainEngine, f: ParsedFlags): Promise<void> {
// Human summary.
const r = out.report;
- const pct = (n: number) => (n * 100).toFixed(0);
- const lines: string[] = [];
- lines.push(``);
- lines.push(`Results: ${r.queries_evaluated} queries, top-${r.top_k} each, judge=${r.judge_model}`);
- lines.push(` Queries with >=1 contradiction: ${r.queries_with_contradiction} / ${r.queries_evaluated} (${pct(r.queries_with_contradiction / Math.max(1, r.queries_evaluated))}%)`);
- // v0.34 / Lane A2: broader finding count alongside the strict contradiction count.
- lines.push(` Queries with >=1 finding (any verdict): ${r.queries_with_any_finding} / ${r.queries_evaluated}`);
- lines.push(` Wilson CI 95%: ${pct(r.calibration.wilson_ci_95.lower)}–${pct(r.calibration.wilson_ci_95.upper)}%`);
- if (r.calibration.small_sample_note) {
- lines.push(` Note: ${r.calibration.small_sample_note}`);
- }
- lines.push(` Total findings flagged: ${r.total_contradictions_flagged}`);
- // v0.34 / Lane A2: per-verdict breakdown surfaces what kinds of finding
- // dominated the run — distinguishes temporal noise from genuine conflicts.
- const vb = r.verdict_breakdown;
- lines.push(` Verdict breakdown:`);
- lines.push(` contradiction: ${vb.contradiction}`);
- lines.push(` temporal_supersession: ${vb.temporal_supersession}`);
- lines.push(` temporal_regression: ${vb.temporal_regression}`);
- lines.push(` temporal_evolution: ${vb.temporal_evolution}`);
- lines.push(` negation_artifact: ${vb.negation_artifact}`);
- lines.push(` no_contradiction: ${vb.no_contradiction}`);
- lines.push(` Judge errors: ${r.judge_errors.total} (parse_fail=${r.judge_errors.parse_fail} timeout=${r.judge_errors.timeout} http_5xx=${r.judge_errors.http_5xx} refusal=${r.judge_errors.refusal})`);
- lines.push(` Cache: ${r.cache.hits} hits / ${r.cache.misses} misses (${pct(r.cache.hit_rate)}% hit-rate)`);
- lines.push(` Source-tier breakdown:`);
- lines.push(` curated_vs_curated: ${r.source_tier_breakdown.curated_vs_curated}`);
- lines.push(` curated_vs_bulk: ${r.source_tier_breakdown.curated_vs_bulk}`);
- lines.push(` bulk_vs_bulk: ${r.source_tier_breakdown.bulk_vs_bulk}`);
- lines.push(` other: ${r.source_tier_breakdown.other}`);
- lines.push(` Cost: $${r.cost_usd.total.toFixed(4)} (judge $${r.cost_usd.judge.toFixed(4)} + embedding $${r.cost_usd.embedding.toFixed(6)})`);
- lines.push(` Duration: ${r.duration_ms}ms`);
- if (r.hot_pages.length > 0) {
- lines.push(` Hot pages:`);
- for (const p of r.hot_pages.slice(0, 5)) {
- lines.push(` ${p.slug} (${p.appearances}, max ${p.max_severity})`);
- }
- }
- if (out.capHitMidRun) {
- lines.push(` *** budget cap hit mid-run; report is partial ***`);
- }
- console.error(lines.join('\n'));
+ console.error(buildRunSummaryLines(r, out.capHitMidRun).join('\n'));
if (f.output) {
const { writeFileSync } = await import('node:fs');
@@ -370,6 +393,13 @@ async function runRun(engine: BrainEngine, f: ParsedFlags): Promise<void> {
console.log(JSON.stringify(r, null, 2));
}
+ // #3889: an all-errors run produced no verdicts; the row is persisted for
+ // the audit trail but the run itself failed. Exit 1 so cron/CI callers
+ // don't treat "judge never ran" as "no contradictions found".
+ if (r.run_status === 'judge_failed') {
+ process.exit(1);
+ }
+
if (out.capHitMidRun && !f.yes) {
// Cap was hit; we already wrote a partial. Exit non-zero to signal.
process.exit(1);
diff --git a/src/commands/eval-synthesize-concepts.ts b/src/commands/eval-synthesize-concepts.ts
index fb4dec828a..1996d36b3b 100644
--- a/src/commands/eval-synthesize-concepts.ts
+++ b/src/commands/eval-synthesize-concepts.ts
@@ -1,7 +1,13 @@
-// v0.41 T11 — `gbrain eval synthesize-concepts` command (minimal scaffold).
+// `gbrain eval synthesize-concepts` — honest not-implemented scaffold (#4198).
//
-// v0.41 ships the command surface. Parity baseline against your OpenClaw's
-// ~11K concepts (tier agreement + cluster stability) lands in v0.41.1.
+// v0.41 T11 shipped the command surface but never wired a dispatch branch:
+// the subcommand fell through to the generic qrels eval ("Error: --qrels
+// <path|json> is required") and the scaffold envelope claimed ok:true, so a
+// scripted caller read "pass" from a command that evaluated nothing. The
+// dedicated cli.ts branch + this module now return an UNAMBIGUOUS
+// not-implemented verdict: ok:false, status:'not_implemented', nonzero exit.
+// The full parity-baseline evaluator (tier agreement + cluster stability
+// against a downstream agent's concepts/ tree) remains a tracked follow-up.
export interface EvalSynthesizeConceptsOpts {
parityBaseline?: string;
@@ -13,7 +19,7 @@ export interface EvalSynthesizeConceptsResult {
schema_version: 1;
ok: boolean;
reason: string;
- status: 'not_yet_implemented' | 'pass' | 'fail';
+ status: 'not_implemented' | 'pass' | 'fail';
details: Record<string, unknown>;
}
@@ -22,15 +28,66 @@ export async function runEvalSynthesizeConcepts(
): Promise<EvalSynthesizeConceptsResult> {
return {
schema_version: 1,
- ok: true,
- reason: 'v0.41 ships the command surface; full parity-baseline eval lands v0.41.1',
- status: 'not_yet_implemented',
+ // Honest verdict (#4198): an eval that ran nothing must not read as a
+ // pass. ok flips to true only when the real evaluator lands.
+ ok: false,
+ reason:
+ 'eval synthesize-concepts is not implemented yet — no concepts were evaluated. ' +
+ 'The parity-baseline evaluator (tier agreement + cluster stability) is a tracked follow-up.',
+ status: 'not_implemented',
details: {
parity_baseline_path: opts.parityBaseline ?? null,
sample_size: opts.sample ?? null,
- v0_41_1_followup:
- 'Compare synthesize_concepts output against your OpenClaw concepts/ on a sample ' +
- 'subset; compute tier agreement (T1/T2/T3) + cluster stability via set Jaccard.',
+ planned:
+ 'Compare synthesize_concepts output against a downstream agent concepts/ tree on a ' +
+ 'sample subset; compute tier agreement (T1/T2/T3) + cluster stability via set Jaccard.',
},
};
}
+
+const HELP = `gbrain eval synthesize-concepts — concept-synthesis parity eval (NOT IMPLEMENTED)
+
+Status: scaffold. Running it evaluates nothing and exits 1 with an
+{ok:false, status:'not_implemented'} envelope so scripts cannot mistake
+the scaffold for a passing eval.
+
+Usage:
+ gbrain eval synthesize-concepts [--parity-baseline <dir>] [--sample <n>] [--json]
+
+Options:
+ --parity-baseline <dir> Concepts tree to compare against (recorded, unused yet)
+ --sample <n> Sample size (recorded, unused yet)
+ --json Emit the machine envelope on stdout
+ --help Show this help (exit 0)
+
+Planned evaluator: tier agreement (T1/T2/T3) + cluster stability (set
+Jaccard) between synthesize_concepts output and the baseline tree.
+`;
+
+/**
+ * CLI entry — parses flags, prints the envelope, returns the exit code
+ * (0 only for --help; the not-implemented scaffold exits 1).
+ */
+export async function runEvalSynthesizeConceptsCli(args: string[]): Promise<number> {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(HELP);
+ return 0;
+ }
+ const opts: EvalSynthesizeConceptsOpts = { json: args.includes('--json') };
+ const pbIdx = args.indexOf('--parity-baseline');
+ if (pbIdx !== -1 && args[pbIdx + 1]) opts.parityBaseline = args[pbIdx + 1];
+ const sampleIdx = args.indexOf('--sample');
+ if (sampleIdx !== -1 && args[sampleIdx + 1]) {
+ const n = Number(args[sampleIdx + 1]);
+ if (Number.isFinite(n) && n > 0) opts.sample = Math.floor(n);
+ }
+
+ const result = await runEvalSynthesizeConcepts(opts);
+ if (opts.json) {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.error(`eval synthesize-concepts: ${result.status.toUpperCase()}`);
+ console.error(result.reason);
+ }
+ return result.ok ? 0 : 1;
+}
diff --git a/src/commands/eval.ts b/src/commands/eval.ts
index 577d3fa0e7..4da4b7a94b 100644
--- a/src/commands/eval.ts
+++ b/src/commands/eval.ts
@@ -120,6 +120,17 @@ export async function runEvalCommand(engine: BrainEngine, args: string[]): Promi
const { runEvalCompare } = await import('./eval-compare.ts');
return runEvalCompare(args.slice(1));
}
+ if (sub === 'synthesize-concepts') {
+ // #4198: honest not-implemented scaffold. The user-facing path routes
+ // through the cli.ts pre-engine branch; this re-entry branch exists so
+ // the generic qrels flow below can never recapture the subcommand.
+ const { runEvalSynthesizeConceptsCli } = await import('./eval-synthesize-concepts.ts');
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ // Exit-verdict ownership: never assign process.exitCode raw — PGLite
+ // teardown can scribble over it; the owned verdict survives (cli-force-exit).
+ setCliExitVerdict(await runEvalSynthesizeConceptsCli(args.slice(1)));
+ return;
+ }
const opts = parseArgs(args);
@@ -404,6 +415,26 @@ gbrain eval — measure and compare retrieval quality
USAGE
gbrain eval --qrels <path>
gbrain eval --qrels <path> --config-a <path> --config-b <path>
+ gbrain eval <subcommand> [flags] (run \`gbrain eval <subcommand> --help\` where available)
+
+SUBCOMMANDS (#3686 — each has its own flag surface)
+ replay Re-run captured production queries against the current config
+ retrieval-quality Retrieval-quality suite over the calibration corpus
+ gate CI pass/fail gate over a saved baseline
+ compare Compare two saved eval runs
+ run-all Orchestrate every suite (works with no brain configured)
+ brainbench Cross-harness memory conformance suite (hermetic)
+ longmemeval LongMemEval benchmark (brings its own in-memory brain)
+ cross-modal Cross-modal quality gate (pure API calls, no DB)
+ code-retrieval Code-retrieval benchmark
+ brainstorm Brainstorm-quality eval
+ whoknows whoknows ranking eval
+ suspected-contradictions Contradiction-probe eval
+ trajectory Chronological claim trajectory for an entity
+ conversation-parser Fixture-corpus CI gate for the parser registry
+ chronicle Chronicle suite
+ takes-quality {run,trend,regress,replay} takes-quality harness
+ export / prune Export or prune recorded eval results
OPTIONS
--qrels <path|json> Path to qrels JSON file (required)
diff --git a/src/commands/export.ts b/src/commands/export.ts
index 1dbfb8d7ee..da292c0183 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -5,6 +5,7 @@ import { serializeMarkdown } from '../core/markdown.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';
+import { slugifyPath } from '../core/sync.ts';
import { getDefaultSourcePath } from '../core/source-resolver.ts';
import type { PageType } from '../core/types.ts';
@@ -113,8 +114,21 @@ export async function runExport(engine: BrainEngine, args: string[]) {
// `source_id = 'default'` and stamps the default source's tags onto a
// same-slug page from another source (dropping its real ones).
const tags = await engine.getTags(page.slug, { sourceId: page.source_id });
+ // #3772: the file is written at <slug>.md and import re-derives the slug
+ // from that path. When the stored slug is NOT a slugifyPath fixed point
+ // (legacy/hand-keyed slugs with case, apostrophes, accents…), a re-import
+ // would silently re-key the page — stamp the true identity into the
+ // frontmatter so import can restore it (import accepts a frontmatter slug
+ // whose slugified spelling equals the path-derived one). Fixed-point
+ // slugs stay unstamped: no diff noise on the common path. A stale
+ // frontmatter slug that contradicts the DB identity is corrected either way.
+ const fmSlug = (page.frontmatter as Record<string, unknown> | null | undefined)?.['slug'];
+ const needsSlugStamp = slugifyPath(page.slug + '.md') !== page.slug;
+ const frontmatter = (needsSlugStamp || fmSlug !== undefined) && fmSlug !== page.slug
+ ? { ...(page.frontmatter ?? {}), slug: page.slug }
+ : page.frontmatter;
const md = serializeMarkdown(
- page.frontmatter,
+ frontmatter,
page.compiled_truth,
page.timeline,
{ type: page.type, title: page.title, tags },
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 67e073106f..7dddd300b6 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -26,6 +26,16 @@
* The DB-source path uses the v0.10.3 graph extractor (typed link inference,
* within-page dedup, snapshot iteration so concurrent writes don't corrupt
* pagination). FS-source preserves the original v0.10.1 walker behavior.
+ *
+ * `--since DATE` semantics (#4304): the filter compares against the page's
+ * `updated_at` — the row's last DB-write time ("touched since"). Import,
+ * sync, enrichment, and extraction stamps all advance `updated_at`, so
+ * `--since` means "pages touched after DATE", NOT "pages whose content is
+ * dated after DATE" (that would be `effective_date`; a `--since-created`
+ * flag keyed on `created_at` is a filed follow-up). On the DB-source path
+ * the filter is applied to the (slug, source_id, updated_at) refs BEFORE
+ * any full-page fetch, so a narrow --since window doesn't round-trip the
+ * whole corpus through getPage.
*/
import { readFileSync, readdirSync, lstatSync, existsSync } from 'fs';
@@ -40,8 +50,11 @@ import {
WIKILINK_BASENAME_LINK_TYPE,
buildBasenameIndex, queryBasenameIndex, stripCodeBlocks, normalizeBasename,
parseInlineCitationTimelineEntries,
- type UnresolvedFrontmatterRef, type LinkCandidate,
+ type UnresolvedFrontmatterRef, type LinkCandidate, type LinkExtractionPack,
} from '../core/link-extraction.ts';
+// #3190: pack-aware link typing on every extract surface (db/stale/fs).
+import { loadActivePackForLocalEngine } from '../core/schema-pack/best-effort.ts';
+import { inferLinkTypeFromPack } from '../core/schema-pack/link-inference.ts';
export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';
import { createProgress } from '../core/progress.ts';
@@ -104,10 +117,81 @@ export async function stampExtracted(
): Promise<void> {
if (refs.length === 0) return;
try {
- await engine.markPagesExtractedBatch(refs, at);
+ const stamped = await engine.markPagesExtractedBatch(refs, at);
+ // #3957: a shortfall means some refs matched no pages row — the classic
+ // cause is a wrong/defaulted source_id ('default' stamped while the pages
+ // live in a named source), which used to fail silently and leave the
+ // "stale" backlog growing forever while every sweep claimed success.
+ // Still best-effort (unstamped pages just stay visible to extract --stale),
+ // but now observable. stderr, never stdout (bulk-path output discipline).
+ if (stamped < refs.length) {
+ process.stderr.write(
+ `[extract] watermark stamped ${stamped}/${refs.length} page(s) — ` +
+ `${refs.length - stamped} ref(s) matched no page (wrong source_id or not yet synced); ` +
+ `they remain visible to 'gbrain extract --stale'\n`,
+ );
+ }
} catch { /* best-effort: page stays stale, extract --stale re-sweeps it */ }
}
+/**
+ * #3957 review (D4 rule): snapshot each ref's CURRENT `pages.updated_at`
+ * BEFORE extraction reads content, so the eventual watermark stamp carries
+ * the row's read updated_at instead of now(). A now() stamp is a FUTURE
+ * watermark relative to the row — a concurrent edit landing between the
+ * content read and the stamp would be masked (page reads fresh with stale
+ * extraction). Stamping the pre-read value keeps the race honest: the edit
+ * advances updated_at past the stamp and the page re-extracts next run.
+ *
+ * Values are the full-µs `to_char` projection (#1768 — a ms-truncated JS
+ * Date stays strictly below the DB value on Postgres and the page never
+ * clears) and are lifted to LINK_EXTRACTOR_VERSION_TS when older
+ * (GREATEST(updated_at, versionTs) — same rule as extractStaleFromDB, so an
+ * old page can't be stamped below the version clause and loop forever).
+ *
+ * Returns a map keyed `${source_id}\u0000${slug}`. Refs with no live pages
+ * row at snapshot time are ABSENT — callers must skip stamping them (a row
+ * created mid-run was never read; it stays stale and is swept later).
+ */
+async function snapshotStampTimes(
+ engine: BrainEngine,
+ refs: Array<{ slug: string; source_id: string }>,
+): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ const versionTs = LINK_EXTRACTOR_VERSION_TS;
+ const versionMs = Date.parse(versionTs);
+ for (let i = 0; i < refs.length; i += BATCH_SIZE) {
+ const batch = refs.slice(i, i + BATCH_SIZE);
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; updated_at_iso: string }>(
+ `SELECT p.slug, p.source_id,
+ to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso
+ FROM pages p
+ JOIN unnest($1::text[], $2::text[]) AS v(slug, source_id)
+ ON p.slug = v.slug AND p.source_id = v.source_id
+ WHERE p.deleted_at IS NULL`,
+ [batch.map(r => r.slug), batch.map(r => r.source_id)],
+ );
+ for (const r of rows) {
+ const iso = Date.parse(r.updated_at_iso) >= versionMs ? r.updated_at_iso : versionTs;
+ out.set(`${r.source_id}\u0000${r.slug}`, iso);
+ }
+ }
+ return out;
+}
+
+/** Attach snapshot stamps to refs, dropping refs the snapshot never saw. */
+function refsWithSnapshotStamps(
+ refs: Array<{ slug: string; source_id: string }>,
+ stamps: Map<string, string>,
+): Array<{ slug: string; source_id: string; extractedAt: string }> {
+ const out: Array<{ slug: string; source_id: string; extractedAt: string }> = [];
+ for (const r of refs) {
+ const at = stamps.get(`${r.source_id}\u0000${r.slug}`);
+ if (at) out.push({ slug: r.slug, source_id: r.source_id, extractedAt: at });
+ }
+ return out;
+}
+
/**
* v0.42.7 (#1696): pure cross-source resolution for one extracted link
* candidate. Validates both endpoints exist (else the batch JOIN drops the row),
@@ -398,7 +482,7 @@ function parseFrontmatterFromContent(content: string, relPath: string): Record<s
*/
export async function extractLinksFromFile(
content: string, relPath: string, allSlugs: Set<string>,
- opts?: { includeFrontmatter?: boolean; globalBasename?: boolean },
+ opts?: { includeFrontmatter?: boolean; globalBasename?: boolean; pack?: LinkExtractionPack | null },
): Promise<ExtractedLink[]> {
const links: ExtractedLink[] = [];
const slug = pathToSlug(relPath);
@@ -408,6 +492,17 @@ export async function extractLinksFromFile(
// basename lookup against allSlugs when the ancestor walk fails. Off
// by default for back-compat with the v0.10.1 ancestor-only behavior.
const globalBasename = opts?.globalBasename ?? false;
+ // #3190: pack-aware typing on the FS path too. FS has no pages row, so the
+ // page type is dir-guessed (same table the frontmatter section uses); the
+ // context is name-only, so in practice pack page_type bindings (meeting →
+ // attended etc.) are what fire here. Falls through to inferTypeByDir.
+ const pack = opts?.pack ?? null;
+ const topDirForType = slug.split('/')[0];
+ const guessedPageType = topDirForType === 'people' ? 'person'
+ : topDirForType === 'companies' ? 'company'
+ : topDirForType === 'deals' || topDirForType === 'deal' ? 'deal'
+ : topDirForType === 'meetings' ? 'meeting'
+ : 'concept';
// Issue #972 (codex [P2]): strip code fences before scanning so a
// `[[name]]` inside a code block doesn't create an FS edge. Mirrors the
@@ -429,15 +524,17 @@ export async function extractLinksFromFile(
// Issue #972 (codex [P2]): drop a basename self-loop ([[own-tail]] on
// its own page resolving back to itself).
if (isBasename && target === slug) continue;
+ const context = isBasename
+ ? `wikilink (basename match): [${name}]`
+ : `markdown link: [${name}]`;
links.push({
from_slug: slug,
to_slug: target,
link_type: isBasename
? WIKILINK_BASENAME_LINK_TYPE
- : inferTypeByDir(fileDir, dirname(target), fm),
- context: isBasename
- ? `wikilink (basename match): [${name}]`
- : `markdown link: [${name}]`,
+ : (pack ? inferLinkTypeFromPack(pack, guessedPageType, context) : null)
+ ?? inferTypeByDir(fileDir, dirname(target), fm),
+ context,
// Issue #972: tag basename edges so the FS path matches DB/put_page
// provenance and migration v112's widened CHECK is exercised here too.
link_source: isBasename ? 'wikilink-resolved' : undefined,
@@ -468,15 +565,13 @@ export async function extractLinksFromFile(
return null;
},
};
- // Guess the page type from its directory for field-map filtering.
- const topDir = slug.split('/')[0];
- const pageType = topDir === 'people' ? 'person'
- : topDir === 'companies' ? 'company'
- : topDir === 'deals' || topDir === 'deal' ? 'deal'
- : topDir === 'meetings' ? 'meeting'
- : 'concept';
+ // Guess the page type from its directory for field-map filtering
+ // (shared with the pack typing above).
const fm = parseFrontmatterFromContent(content, relPath);
- const fmLinks = await extractFrontmatterLinks(slug, pageType as never, fm, fsResolver);
+ // #3190: thread the pack so pack-declared frontmatter_links fire on the
+ // FS path too (globalBasename false here — the synthetic resolver has no
+ // basename index).
+ const fmLinks = await extractFrontmatterLinks(slug, guessedPageType as never, fm, fsResolver, false, pack);
for (const c of fmLinks.candidates) {
links.push({
from_slug: c.fromSlug ?? slug,
@@ -603,6 +698,17 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
}
// Full walk path: CLI `gbrain extract` or first-run.
+ //
+ // #3957 review (D4): snapshot the walked pages' updated_at BEFORE the walk
+ // reads any content, so the post-walk stamp carries the pre-read value —
+ // never now(), which is a future watermark that masks concurrent edits.
+ let stampRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];
+ if (!dryRun && opts.mode === 'all') {
+ const stampSourceId = opts.sourceId ?? 'default';
+ const walkRefs = walkMarkdownFiles(opts.dir)
+ .map(f => ({ slug: pathToSlug(f.relPath), source_id: stampSourceId }));
+ stampRefs = refsWithSnapshotStamps(walkRefs, await snapshotStampTimes(engine, walkRefs));
+ }
if (opts.mode === 'links' || opts.mode === 'all') {
const r = await extractLinksFromDir(engine, opts.dir, dryRun, jsonMode, workers, opts.signal, opts.sourceId);
result.links_created = r.created;
@@ -614,6 +720,21 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Pr
result.pages_processed = Math.max(result.pages_processed, r.pages);
}
+ // #3957: stamp the links_extracted_at watermark for the walked pages —
+ // mode 'all' only (a links- or timeline-only run hasn't done the full
+ // extraction the watermark asserts; extractForSlugs applies the same C3/D6
+ // rule). Pre-fix the full FS walk never stamped, so every walked page
+ // stayed permanently "stale" to `extract --stale` / doctor and the sweep
+ // re-extracted the whole brain on every run. Refs carry the resolved
+ // source id + the row's pre-read updated_at (D4); files with no pages row
+ // at snapshot time are skipped (nothing to stamp — they stay visible to
+ // `extract --stale` once synced).
+ if (!dryRun && opts.mode === 'all' && !isAborted(opts.signal)) {
+ for (let i = 0; i < stampRefs.length; i += BATCH_SIZE) {
+ await stampExtracted(engine, stampRefs.slice(i, i + BATCH_SIZE));
+ }
+ }
+
return result;
}
@@ -632,9 +753,18 @@ Extraction:
[--infer-dates] [--workers N|--concurrency N]
[--dry-run] [--json]
gbrain extract <links|timeline> --by-mention --source db
+ gbrain extract links --by-mention --rebuild --source db
+ Reconcile instead of accrete: per page, delete the stale
+ link_source='mentions' rows and re-insert the current mention set in
+ one transaction (typed_ner rows whose target is still derivable
+ survive). Fixes drift the stale_mentions doctor check reports (#3674).
gbrain extract <links|timeline|all> --ner --source db
gbrain extract <timeline|all> --from-meetings --source db
+ --since DATE filters on updated_at — the page row's last DB-write time
+ ("touched since"): import, sync, enrich, and extraction stamps all advance
+ it. It is NOT the content's authored/effective date.
+
Incremental sweep:
gbrain extract --stale [--source-id <id>] [--include-frontmatter]
[--catch-up] [--dry-run] [--json]
@@ -739,6 +869,13 @@ export async function runExtract(engine: BrainEngine, args: string[]) {
// mention pass (skip default link extract). DB-source only per D7;
// FS-source is rejected with a paste-ready fix-hint below.
const byMention = args.includes('--by-mention');
+ // #3674: --rebuild switches the by-mention pass from additive to
+ // reconciling. Per page, ONE transaction deletes the page's
+ // link_source='mentions' rows (typed_ner rows whose target is still
+ // derivable survive — extract-ner owns their verbs and the scan can't
+ // regenerate them) and re-inserts the current mention set. Opt-in: the
+ // default pass stays additive-only.
+ const rebuildMentions = args.includes('--rebuild');
// v0.41.18.0 (A10, T7): --ner is a NER-extraction mode dispatch. Same
// DB-source-only posture as --by-mention. Can combine with --by-mention
// in a single command for a shared-gazetteer walk (saves one pass).
@@ -812,6 +949,16 @@ export async function runExtract(engine: BrainEngine, args: string[]) {
);
process.exit(2);
}
+ // #3674: --rebuild is a by-mention reconcile mode; without --by-mention
+ // there is nothing for it to rebuild. Fail loud rather than silently
+ // running an additive pass the operator believed was a cleanup.
+ if (rebuildMentions && !byMention) {
+ console.error(
+ `--rebuild only applies to the by-mention pass. Re-run as:\n\n` +
+ ` gbrain extract links --by-mention --rebuild --source db\n`,
+ );
+ process.exit(2);
+ }
// v0.41.18.0 (T7): same gates for --ner.
if (ner && source === 'fs') {
console.error(
@@ -912,7 +1059,10 @@ export async function runExtract(engine: BrainEngine, args: string[]) {
const { buildGazetteer: buildGz } = await import('../core/by-mention.ts');
const sharedGazetteer = (byMention || ner) ? await buildGz(engine) : undefined;
if (byMention) {
- const r = await extractMentionsFromDb(engine, dryRun, jsonMode, typeFilter, since, { sourceIdFilter });
+ const r = await extractMentionsFromDb(engine, dryRun, jsonMode, typeFilter, since, {
+ sourceIdFilter,
+ rebuild: rebuildMentions,
+ });
result.links_created += r.created;
result.pages_processed += r.pages;
}
@@ -1026,9 +1176,21 @@ async function extractForSlugs(
// stamped after the final flush (mode 'all' only — a partial-mode run
// hasn't done the full extraction the watermark asserts).
const processedRefs: Array<{ slug: string; source_id: string }> = [];
+ // #3957 review (D4): snapshot updated_at BEFORE the pool reads any file so
+ // the stamp carries the pre-read value, not now() (a future watermark that
+ // would mask an edit landing mid-run).
+ const stampSnapshot = (!dryRun && mode === 'all')
+ ? await snapshotStampTimes(
+ engine,
+ slugs.map(slug => ({ slug, source_id: sourceId ?? 'default' })),
+ )
+ : new Map<string, string>();
// Issue #972: read the basename flag once per extract run.
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: active pack loaded once per run for pack-aware link typing +
+ // pack frontmatter_links. Null keeps legacy inference.
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
const linkBatch: LinkBatchInput[] = [];
const timelineBatch: TimelineBatchInput[] = [];
@@ -1086,7 +1248,7 @@ async function extractForSlugs(
const content = readFileSync(fullPath, 'utf-8');
if (doLinks) {
- const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter });
+ const links = await extractLinksFromFile(content, relPath, allSlugs, { globalBasename, includeFrontmatter, pack });
for (const link of links) {
if (dryRun) {
if (!jsonMode) console.log(` ${link.from_slug} → ${link.to_slug} (${link.link_type})`);
@@ -1125,9 +1287,11 @@ async function extractForSlugs(
// #2636: the Dream cycle disables sync's inline extraction and routes
// changed slugs through this incremental path — without a stamp here,
// those pages never get links_extracted_at and stay permanently visible
- // to `extract --stale` / doctor. Stamp only after BOTH batches flushed.
+ // to `extract --stale` / doctor. Stamp only after BOTH batches flushed,
+ // with the pre-read updated_at snapshot (D4) — refs the snapshot never
+ // saw (row created mid-run) are skipped and stay stale.
if (!dryRun && mode === 'all') {
- await stampExtracted(engine, processedRefs);
+ await stampExtracted(engine, refsWithSnapshotStamps(processedRefs, stampSnapshot));
}
progress.finish();
@@ -1155,6 +1319,8 @@ async function extractLinksFromDir(
// re-query the DB. globalBasename = true emits one edge per basename
// match for bare wikilinks like `[[struktura]]`.
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: pack-aware typing + pack frontmatter_links (loaded once per walk).
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
// Progress stream on stderr (separate from the action-events --json writes
// to stdout, which tests grep for). Rate-gated; respects global --quiet /
@@ -1194,7 +1360,7 @@ async function extractLinksFromDir(
if (isAborted(signal)) return;
try {
const content = readFileSync(file.path, 'utf-8');
- const links = await extractLinksFromFile(content, file.relPath, allSlugs, { globalBasename });
+ const links = await extractLinksFromFile(content, file.relPath, allSlugs, { globalBasename, pack });
for (const link of links) {
if (dryRunSeen) {
const key = `${link.from_slug}::${link.to_slug}::${link.link_type}`;
@@ -1314,13 +1480,15 @@ export async function extractLinksForSlugs(
: undefined;
// Issue #972: same flag as the standalone extract path.
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: pack-aware typing on the sync inline hook too.
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
let created = 0;
for (const slug of slugs) {
const filePath = join(repoPath, slug + '.md');
if (!existsSync(filePath)) continue;
try {
const content = readFileSync(filePath, 'utf-8');
- for (const link of await extractLinksFromFile(content, slug + '.md', allSlugs, { globalBasename })) {
+ for (const link of await extractLinksFromFile(content, slug + '.md', allSlugs, { globalBasename, pack })) {
try { await engine.addLink(link.from_slug, link.to_slug, link.context, link.link_type, link.link_source, undefined, undefined, linkOpts); created++; } catch { /* skip */ } // gbrain-allow-direct-insert: gbrain extract single-row fallback when batch path declines a row
}
} catch { /* skip */ }
@@ -1359,6 +1527,24 @@ export async function extractTimelineForSlugs(
// no local checkout (e.g. live MCP servers). Uses the typed link inference and
// timeline parser from src/core/link-extraction.ts.
+/**
+ * #4304: apply the --since filter to (slug, source_id, updated_at) refs
+ * BEFORE any getPage round-trip. `--since` is a "touched since" filter on
+ * `updated_at` (last DB write), not the content's authored date — see the
+ * module header. Semantics match the old in-loop check: keep strictly-newer
+ * rows (updated_at > since); an unparseable `since` is rejected upstream in
+ * runExtract, so the pass-through here is belt-and-braces only.
+ */
+function filterRefsSince<T extends { updated_at: Date }>(
+ refs: T[],
+ since: string | undefined,
+): T[] {
+ if (!since) return refs;
+ const sinceMs = new Date(since).getTime();
+ if (!Number.isFinite(sinceMs)) return refs;
+ return refs.filter(r => r.updated_at.getTime() > sinceMs);
+}
+
async function extractLinksFromDB(
engine: BrainEngine,
dryRun: boolean,
@@ -1390,6 +1576,10 @@ async function extractLinksFromDB(
// Issue #972: opt-in global-basename wikilink resolution. Read once
// per extract run; threaded into each extractPageLinks call.
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: active schema pack, loaded ONCE per run — pack-declared link
+ // verbs (link_types[].inference) + frontmatter_links apply during
+ // extraction instead of being silently ignored. Null = legacy inference.
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
// v0.32.8: listAllPageRefs enumerates (slug, source_id) so we can thread
// sourceId to getPage AND build a cross-source resolution map for link
// disambiguation. Pre-fix used getAllSlugs() which collapsed
@@ -1423,6 +1613,11 @@ async function extractLinksFromDB(
list.push(ref.source_id);
slugToSources.set(ref.slug, list);
}
+ // #4304: --since prunes the walk at the ref level (updated_at comes back
+ // from listAllPageRefs) instead of a getPage round-trip per corpus page.
+ // The resolver maps above are built from the UNFILTERED refs — link
+ // targets outside the window must still resolve.
+ const walkRefs = filterRefsSince(allRefs, since);
let processed = 0, created = 0;
// #2576: skipped-candidate counter — see extractStaleFromDB's twin.
let skippedMissingTarget = 0;
@@ -1432,7 +1627,7 @@ async function extractLinksFromDB(
const processedRefs: Array<{ slug: string; source_id: string }> = [];
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
- progress.start('extract.links_db', allRefs.length);
+ progress.start('extract.links_db', walkRefs.length);
// Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.
const dryRunSeen = dryRun ? new Set<string>() : null;
@@ -1454,15 +1649,10 @@ async function extractLinksFromDB(
}
}
- for (const { slug, source_id } of allRefs) {
+ for (const { slug, source_id } of walkRefs) {
const page = await engine.getPage(slug, { sourceId: source_id });
if (!page) continue;
if (typeFilter && page.type !== typeFilter) continue;
- if (since) {
- const updatedMs = new Date(page.updated_at).getTime();
- const sinceMs = new Date(since).getTime();
- if (Number.isFinite(sinceMs) && updatedMs <= sinceMs) continue;
- }
const fullContent = page.compiled_truth + '\n' + page.timeline;
// --include-frontmatter default OFF in v0.13 (codex tension 5, back-compat).
@@ -1472,7 +1662,7 @@ async function extractLinksFromDB(
// basename lookup; off by default for back-compat.
const extracted = await extractPageLinks(
slug, fullContent, page.frontmatter, page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename },
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack },
);
unresolved.push(...extracted.unresolved);
@@ -1579,10 +1769,13 @@ async function extractTimelineFromDB(
const allRefs = sourceIdFilter
? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter)
: await engine.listAllPageRefs();
+ // #4304: --since prunes at the ref level — no getPage round-trip for
+ // pages outside the window.
+ const walkRefs = filterRefsSince(allRefs, since);
let processed = 0, created = 0;
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
- progress.start('extract.timeline_db', allRefs.length);
+ progress.start('extract.timeline_db', walkRefs.length);
// Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.
const dryRunSeen = dryRun ? new Set<string>() : null;
@@ -1604,15 +1797,10 @@ async function extractTimelineFromDB(
}
}
- for (const { slug, source_id } of allRefs) {
+ for (const { slug, source_id } of walkRefs) {
const page = await engine.getPage(slug, { sourceId: source_id });
if (!page) continue;
if (typeFilter && page.type !== typeFilter) continue;
- if (since) {
- const updatedMs = new Date(page.updated_at).getTime();
- const sinceMs = new Date(since).getTime();
- if (Number.isFinite(sinceMs) && updatedMs <= sinceMs) continue;
- }
const fullContent = page.compiled_truth + '\n' + page.timeline;
let entries = parseTimelineEntries(fullContent);
@@ -1645,8 +1833,9 @@ async function extractTimelineFromDB(
created++;
} else {
// v0.32.8 F4: thread source_id so the JOIN matches the right page
- // when two sources share the same slug.
- batch.push({ slug, date: entry.date, summary: entry.summary, detail: entry.detail || '', source_id });
+ // when two sources share the same slug. #3957: thread the parsed
+ // source label too — see extractStaleFromDB's twin.
+ batch.push({ slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id });
if (batch.length >= BATCH_SIZE) await flush();
}
}
@@ -1686,9 +1875,18 @@ export async function extractStaleFromDB(
includeFrontmatter: boolean;
sourceIdFilter?: string;
catchUp: boolean;
+ /**
+ * Wall-clock cap for the sweep (checked between keyset batches).
+ * Defaults to STALE_TIME_BUDGET_MS (~30 min). Embedded callers (the
+ * cycle's in-line stale drain) pass a much smaller cap so one drain
+ * can't consume the whole cycle — the full budget stays with the
+ * explicit `gbrain extract --stale` command. Ignored when catchUp.
+ */
+ timeBudgetMs?: number;
},
): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number }> {
const { dryRun, jsonMode, includeFrontmatter, sourceIdFilter, catchUp } = opts;
+ const timeBudgetMs = opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS;
const versionTs = LINK_EXTRACTOR_VERSION_TS;
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
@@ -1722,6 +1920,8 @@ export async function extractStaleFromDB(
// extractLinksFromDB (including the codex-[P1] `sourceId` scoping).
const resolver = makeResolver(engine, { mode: 'batch', sourceId: sourceIdFilter });
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: pack-aware verbs + frontmatter_links (see extractLinksFromDB).
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
const allRefs = await engine.listAllPageRefs();
const allSlugs = new Set<string>();
const slugToSources = new Map<string, string[]>();
@@ -1758,7 +1958,7 @@ export async function extractStaleFromDB(
const fullContent = page.compiled_truth + '\n' + page.timeline;
const extracted = await extractPageLinks(
page.slug, fullContent, page.frontmatter, page.type, resolver,
- { skipFrontmatter: !includeFrontmatter, globalBasename },
+ { skipFrontmatter: !includeFrontmatter, globalBasename, pack },
);
for (const c of extracted.candidates) {
const r = resolveCandidateSources(c, page.slug, page.source_id, allSlugs, slugToSources);
@@ -1771,7 +1971,11 @@ export async function extractStaleFromDB(
});
}
for (const entry of parseTimelineEntries(fullContent)) {
- timelineRows.push({ slug: page.slug, date: entry.date, summary: entry.summary, detail: entry.detail || '', source_id: page.source_id });
+ // #3957: carry the parsed source label — omitting it wrote source=''
+ // while the FS path wrote the split label, so the same bullet
+ // extracted via both paths duplicated under the (page_id, date,
+ // summary, source) dedup index.
+ timelineRows.push({ slug: page.slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: page.source_id });
}
// EVERY processed page is stamped (incl. zero-link pages). D4 race fix:
// stamp with the row's READ updated_at, NOT now() — a concurrent edit
@@ -1815,7 +2019,7 @@ export async function extractStaleFromDB(
progress.tick(rows.length);
afterPageId = rows[rows.length - 1]!.id;
- if (!catchUp && Date.now() - startMs > STALE_TIME_BUDGET_MS) { budgetHit = true; break; }
+ if (!catchUp && Date.now() - startMs > timeBudgetMs) { budgetHit = true; break; }
}
progress.finish();
@@ -1861,9 +2065,13 @@ async function extractMentionsFromDb(
jsonMode: boolean,
typeFilter: PageType | undefined,
since: string | undefined,
- opts?: { sourceIdFilter?: string },
-): Promise<{ created: number; pages: number }> {
+ opts?: { sourceIdFilter?: string; rebuild?: boolean },
+): Promise<{ created: number; pages: number; removed: number }> {
const sourceIdFilter = opts?.sourceIdFilter;
+ // #3674: rebuild mode reconciles instead of accreting — per page, one
+ // transaction deletes the stale link_source='mentions' rows and re-inserts
+ // the current mention set. Dry-run stays a pure preview (no deletes).
+ const rebuild = opts?.rebuild === true && !dryRun;
// Build gazetteer once per run. Skip everything if there are no
// linkable entities — vacuous truth, no mentions to find.
@@ -1874,7 +2082,7 @@ async function extractMentionsFromDb(
} else {
console.log('No linkable entity pages found in this brain (need pages with type IN person/company/organization/entity).');
}
- return { created: 0, pages: 0 };
+ return { created: 0, pages: 0, removed: 0 };
}
// v0.41.19.0 (T5): gazetteer hash is part of the checkpoint
@@ -1886,9 +2094,16 @@ async function extractMentionsFromDb(
.digest('hex')
.slice(0, 8);
- const allRefs = sourceIdFilter
- ? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter)
- : await engine.listAllPageRefs();
+ // #4304: --since prunes at the ref level BEFORE the checkpoint diff and
+ // the per-page getPage loop. Refs outside the window never enter the
+ // checkpoint either — the fingerprint below folds `since`, so a resume
+ // with the same window re-filters them just as cheaply.
+ const allRefs = filterRefsSince(
+ sourceIdFilter
+ ? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter)
+ : await engine.listAllPageRefs(),
+ since,
+ );
// v0.41.19.0 (T5): load checkpoint and skip already-completed
// (source_id, slug) pairs. Dry-run does NOT load OR persist the
@@ -1900,7 +2115,11 @@ async function extractMentionsFromDb(
source: sourceIdFilter,
type: typeFilter,
since,
- gazetteerHash,
+ // #3674: rebuild resumes must not reuse an additive run's checkpoint
+ // (pages the additive run "completed" still carry their stale rows).
+ // Folded into the hash input only when set so existing additive
+ // checkpoints keep their fingerprints.
+ gazetteerHash: rebuild ? `${gazetteerHash}:rebuild` : gazetteerHash,
}),
};
const completed = dryRun
@@ -1916,6 +2135,7 @@ async function extractMentionsFromDb(
let processed = 0;
let created = 0;
+ let removed = 0;
const batch: LinkBatchInput[] = [];
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
@@ -1964,28 +2184,19 @@ async function extractMentionsFromDb(
}
}
- const sinceMs = since ? new Date(since).getTime() : null;
-
for (const { slug, source_id } of remaining) {
const page = await engine.getPage(slug, { sourceId: source_id });
// v0.41.19.0 (T5 — codex fix #4): even when we skip a page (filter
// miss, missing row, empty body, no mentions), MARK IT COMPLETED so
// resume doesn't re-fetch it. The decision NOT to create links is
- // itself a completed decision.
+ // itself a completed decision. (#4304: the --since filter moved to the
+ // ref level above — out-of-window pages never reach this loop.)
const key = `${source_id}::${slug}`;
if (!page || (typeFilter && page.type !== typeFilter)) {
pendingForFlush.push(key);
unpersistedCount++;
continue;
}
- if (sinceMs !== null) {
- const updatedMs = new Date(page.updated_at).getTime();
- if (Number.isFinite(updatedMs) && updatedMs <= sinceMs) {
- pendingForFlush.push(key);
- unpersistedCount++;
- continue;
- }
- }
processed++;
progress.tick();
@@ -1993,17 +2204,69 @@ async function extractMentionsFromDb(
// end-of-compiled token doesn't accidentally merge with a
// start-of-timeline token into a false phrase match.
const body = page.compiled_truth + '\n\n' + (page.timeline ?? '');
- if (!body.trim()) {
+ const mentions = body.trim()
+ ? findMentionedEntities(body, gazetteer, {
+ fromSlug: slug,
+ fromSourceId: source_id,
+ })
+ : [];
+
+ // #3674 --rebuild: per-page delete-then-insert in ONE transaction. The
+ // delete sweeps the page's link_source='mentions' rows — INCLUDING pages
+ // whose body now yields zero mentions (those are exactly the stale ones)
+ // — while typed_ner rows whose target is still derivable survive
+ // (extract-ner owns their verbs; the scan can't regenerate them). A
+ // failed page stays UN-checkpointed so resume retries it instead of
+ // marking a half-applied sweep complete.
+ if (rebuild) {
+ const linkRows: LinkBatchInput[] = mentions.map((m) => ({
+ from_slug: slug,
+ to_slug: m.slug,
+ link_type: 'mentions',
+ link_source: 'mentions',
+ context: m.name,
+ from_source_id: source_id,
+ to_source_id: m.source_id,
+ }));
+ try {
+ let pageRemoved = 0;
+ let pageCreated = 0;
+ await engine.transaction(async (tx) => {
+ pageRemoved = await tx.removeLinksByPagesAndSource(
+ [{ slug, source_id }],
+ {
+ linkSource: 'mentions',
+ keepTypedNerPairs: mentions.map((m) => ({
+ from_slug: slug,
+ from_source_id: source_id,
+ to_slug: m.slug,
+ to_source_id: m.source_id,
+ })),
+ },
+ );
+ if (linkRows.length > 0) {
+ pageCreated = await tx.addLinksBatch(linkRows, { auditSite: 'extract.by_mention.rebuild' }); // gbrain-allow-direct-insert: gbrain extract --by-mention --rebuild — reconciling delete-then-insert of the mention scan's own rows
+ }
+ });
+ removed += pageRemoved;
+ created += pageCreated;
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (jsonMode) {
+ process.stderr.write(JSON.stringify({ event: 'rebuild_error', slug, source_id, error: msg }) + '\n');
+ } else {
+ console.error(` rebuild error on ${slug} (page will be retried on resume): ${msg}`);
+ }
+ continue;
+ }
pendingForFlush.push(key);
unpersistedCount++;
+ if (Date.now() - sinceLastPersistMs >= PERSIST_EVERY_MS) {
+ await flushAndCheckpoint();
+ }
continue;
}
- const mentions = findMentionedEntities(body, gazetteer, {
- fromSlug: slug,
- fromSourceId: source_id,
- });
-
if (mentions.length === 0) {
pendingForFlush.push(key);
unpersistedCount++;
@@ -2060,7 +2323,10 @@ async function extractMentionsFromDb(
if (!jsonMode) {
const label = dryRun ? '(dry run) would create' : 'created';
- console.log(`Mentions: ${label} ${created} links from ${processed} pages against gazetteer of ${gazetteer.size} first-token buckets`);
+ const removedNote = rebuild ? `, removed ${removed} stale mention link(s)` : '';
+ console.log(`Mentions: ${label} ${created} links${removedNote} from ${processed} pages against gazetteer of ${gazetteer.size} first-token buckets`);
+ } else if (rebuild) {
+ process.stdout.write(JSON.stringify({ event: 'rebuild_summary', created, removed, pages: processed }) + '\n');
}
- return { created, pages: processed };
+ return { created, pages: processed, removed };
}
diff --git a/src/commands/files.ts b/src/commands/files.ts
index 391644699f..04b8204195 100644
--- a/src/commands/files.ts
+++ b/src/commands/files.ts
@@ -1,5 +1,5 @@
-import { readFileSync, readdirSync, statSync, lstatSync, existsSync, writeFileSync, unlinkSync, mkdirSync } from 'fs';
-import { join, relative, extname, basename, dirname } from 'path';
+import { readFileSync, readdirSync, statSync, lstatSync, existsSync, writeFileSync, unlinkSync, mkdirSync, copyFileSync } from 'fs';
+import { join, relative, extname, basename, dirname, resolve } from 'path';
import { createHash } from 'crypto';
import type { BrainEngine } from '../core/engine.ts';
import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';
@@ -146,24 +146,32 @@ async function uploadFile(engine: BrainEngine, args: string[]) {
const sql = sqlQueryForEngine(engine);
- // Check for existing file by hash
+ // #4302 (fail-closed honesty, mirror of the file_upload op): a files row
+ // must never claim bytes that were stored nowhere. No storage backend →
+ // refuse before any insert instead of recording a phantom upload.
+ const { loadConfig } = await import('../core/config.ts');
+ const config = loadConfig();
+ if (!config?.storage) {
+ console.error('No storage backend configured — `files upload` would record a row with no stored bytes.');
+ console.error('Configure `storage` in your gbrain config (supabase | s3 | local),');
+ console.error('or use `gbrain files upload-raw --page <slug>` for git-tracked small files.');
+ process.exit(1);
+ }
+ const { createStorage } = await import('../core/storage.ts');
+ const storage = await createStorage(config.storage as any);
+
+ // Check for existing file by hash — but only trust the row when the
+ // BACKEND really holds the object (#4302); vanished bytes must re-upload.
const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;
- if (existing.length > 0) {
+ if (existing.length > 0 && (await storage.exists(storagePath).catch(() => false))) {
console.log(`File already uploaded (hash match): ${storagePath}`);
return;
}
- // Upload to storage backend if configured
- const { loadConfig } = await import('../core/config.ts');
- const config = loadConfig();
- if (config?.storage) {
- const { createStorage } = await import('../core/storage.ts');
- const storage = await createStorage(config.storage as any);
- const content = readFileSync(filePath);
- const method = content.length >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';
- console.log(`Uploading ${humanSize(stat.size)} via ${method}...`);
- await storage.upload(storagePath, content, mimeType || undefined);
- }
+ const content = readFileSync(filePath);
+ const method = content.length >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';
+ console.log(`Uploading ${humanSize(stat.size)} via ${method}...`);
+ await storage.upload(storagePath, content, mimeType || undefined);
await sql`
INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
@@ -204,13 +212,62 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {
const needsCloud = stat.size >= SIZE_THRESHOLD || isMedia;
if (!needsCloud) {
- // Small text/PDF files stay in git
+ // #2297: small text/PDF files "stay in git" — which used to mean the
+ // command did NOTHING (no repo copy, no files row) while printing
+ // success:true. Actually bank the file: copy it into the page's .raw/
+ // sidecar dir inside the brain repo and record a files row so
+ // `gbrain files list` / `verify` can see it.
+ if (!pageSlug) {
+ console.error('files upload-raw: --page <slug> is required for git-storage (small text/PDF) files.');
+ process.exit(1);
+ }
+ const { resolveSourceId } = await import('../core/source-resolver.ts');
+ const { resolvePageWriteTarget } = await import('../core/write-through.ts');
+ const sourceArg = args.find((a, i) => args[i - 1] === '--source') || null;
+ const sourceId = await resolveSourceId(engine, sourceArg);
+ const target = await resolvePageWriteTarget(engine, pageSlug, sourceId);
+ if (!target.ok) {
+ console.error(
+ `files upload-raw: cannot resolve a brain-repo destination for page "${pageSlug}" ` +
+ `(${target.skipped}). Configure sync.repo_path (or the source's local_path), ` +
+ `or use \`gbrain files upload\` with a cloud storage backend.`,
+ );
+ process.exit(1);
+ }
+ // <pageDir>/.raw/<page-name>/<basename> — sidecar layout next to the
+ // page's canonical markdown artifact.
+ const pageDir = dirname(target.filePath);
+ const pageName = basename(target.filePath).replace(/\.md$/i, '');
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- pageDir/pageName derive from resolvePageWriteTarget's brain-repo target for the operator's own --page slug; upload-raw is a trusted-local CLI lane (runFiles is wired only from cli.ts, remote:false — the MCP file_upload op is a separate localOnly handler)
+ const destDir = join(pageDir, '.raw', pageName);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- filename is basename() of the operator's own CLI file arg (basename yields a single separator-free segment), joined under the brain-repo sidecar dir above
+ const dest = join(destDir, filename);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- identity comparison only (skip self-copy when source already IS the dest); no fs path is derived from this expression
+ if (resolve(dest) !== resolve(filePath)) {
+ mkdirSync(destDir, { recursive: true });
+ copyFileSync(filePath, dest);
+ }
+ const hash = fileHash(filePath);
+ const storagePath = relative(target.writeRoot, dest);
+ await executeRawJsonb(
+ engine,
+ `INSERT INTO files (source_id, page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb)
+ ON CONFLICT (storage_path) DO UPDATE SET
+ content_hash = EXCLUDED.content_hash,
+ size_bytes = EXCLUDED.size_bytes,
+ mime_type = EXCLUDED.mime_type`,
+ [sourceId, pageSlug, filename, storagePath, mimeType, stat.size, 'sha256:' + hash],
+ [{ storage: 'git', type: fileType }],
+ );
console.log(JSON.stringify({
success: true,
storage: 'git',
- path: filePath,
+ path: dest,
+ storagePath,
size: stat.size,
size_human: humanSize(stat.size),
+ hash: `sha256:${hash}`,
}));
return;
}
@@ -375,16 +432,89 @@ async function verifyFiles(engine: BrainEngine) {
let mismatches = 0;
let missing = 0;
+ // #4302: verify against the actual bytes, not just DB row shape. Cloud rows
+ // are probed via storage.exists (+ hash-checked via download for small
+ // objects); git-storage rows (metadata.storage === 'git', the upload-raw
+ // small-file lane) are checked against the brain repo on disk.
+ const { loadConfig } = await import('../core/config.ts');
+ const config = loadConfig();
+ const storage = config?.storage
+ ? await (await import('../core/storage.ts')).createStorage(config.storage as any).catch(() => null)
+ : null;
+ const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);
+ // Git-lane root resolution mirrors upload-raw's resolvePageWriteTarget:
+ // storage_path was banked relative to the row's OWNING source's local_path
+ // when that source has its own working tree, with sync.repo_path only as
+ // the fallback. Joining every row against sync.repo_path falsely reported
+ // MISSING (or hash-checked the wrong file) for separate-tree sources.
+ const sourceLocalPathCache = new Map<string, string | null>();
+ const gitRootFor = async (sourceId: unknown): Promise<string | null> => {
+ const sid = typeof sourceId === 'string' && sourceId ? sourceId : null;
+ if (!sid) return repoPath ? String(repoPath) : null;
+ if (!sourceLocalPathCache.has(sid)) {
+ let localPath: string | null = null;
+ try {
+ const srcRows = await sql`SELECT local_path FROM sources WHERE id = ${sid}`;
+ localPath = srcRows[0]?.local_path ? String(srcRows[0].local_path) : null;
+ } catch { /* sources table unavailable — fall back to sync.repo_path */ }
+ sourceLocalPathCache.set(sid, localPath);
+ }
+ return sourceLocalPathCache.get(sid) ?? (repoPath ? String(repoPath) : null);
+ };
+ const HASH_CHECK_MAX_BYTES = 10 * 1024 * 1024;
+ const normalizeHash = (h: string) => h.replace(/^sha256:/, '');
+
for (const row of rows) {
- // Note: full verification would check Supabase Storage hash
- // For now, verify the DB record exists and has valid data
if (!row.content_hash || !row.storage_path) {
mismatches++;
console.error(` MISMATCH: ${row.storage_path} (missing hash or path)`);
+ continue;
+ }
+ const storagePath = String(row.storage_path);
+ const meta = (typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata) as Record<string, unknown> | null;
+ if (meta?.storage === 'git') {
+ const gitRoot = await gitRootFor(row.source_id);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- gitRoot is the operator-written sources.local_path / sync.repo_path config; storage_path rows are banked exclusively by trusted-local writers (upload-raw's relative(writeRoot, dest) on the CLI, plus the localOnly file_upload op) — files verify is itself a CLI-only read that hash-compares and reports, never serves content
+ const local = gitRoot ? join(gitRoot, storagePath) : null;
+ if (!local || !existsSync(local)) {
+ missing++;
+ console.error(` MISSING: ${row.storage_path} (git-storage file not in brain repo)`);
+ } else if (normalizeHash(fileHash(local)) !== normalizeHash(String(row.content_hash))) {
+ mismatches++;
+ console.error(` MISMATCH: ${row.storage_path} (repo file hash differs from DB record)`);
+ } else {
+ verified++;
+ }
+ continue;
+ }
+ if (storage) {
+ const present = await storage.exists(storagePath).catch(() => false);
+ if (!present) {
+ missing++;
+ console.error(` MISSING: ${row.storage_path} (not in storage backend)`);
+ continue;
+ }
+ const size = row.size_bytes == null ? null : Number(row.size_bytes);
+ if (size !== null && size <= HASH_CHECK_MAX_BYTES) {
+ try {
+ const bytes = await storage.download(storagePath);
+ const actual = createHash('sha256').update(bytes).digest('hex');
+ if (actual !== normalizeHash(String(row.content_hash))) {
+ mismatches++;
+ console.error(` MISMATCH: ${row.storage_path} (backend hash differs from DB record)`);
+ continue;
+ }
+ } catch { /* download hiccup — exists() already vouched; count verified */ }
+ }
+ verified++;
} else {
+ // No backend configured: DB-shape check only (legacy behavior), but say so.
verified++;
}
}
+ if (!storage) {
+ console.error('Note: no storage backend configured — backend existence/hash checks skipped.');
+ }
if (mismatches === 0 && missing === 0) {
console.log(`${verified} files verified, 0 mismatches, 0 missing`);
diff --git a/src/commands/frontmatter-install-hook.ts b/src/commands/frontmatter-install-hook.ts
index 6224a982f8..0bc1e6b281 100644
--- a/src/commands/frontmatter-install-hook.ts
+++ b/src/commands/frontmatter-install-hook.ts
@@ -158,7 +158,16 @@ async function listSources(engine: BrainEngine, sourceId?: string): Promise<Sour
if (sourceId) {
return engine.executeRaw<SourceRow>(`SELECT id, local_path FROM sources WHERE id = $1`, [sourceId]);
}
- return engine.executeRaw<SourceRow>(`SELECT id, local_path FROM sources WHERE local_path IS NOT NULL ORDER BY id`);
+ // #3880: all-source hook installation skips archived sources (v34 legacy
+ // fallback, house style per pickSoleNonDefaultSource). Explicit --source
+ // targeting above stays deliberate.
+ try {
+ return await engine.executeRaw<SourceRow>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE ORDER BY id`,
+ );
+ } catch {
+ return engine.executeRaw<SourceRow>(`SELECT id, local_path FROM sources WHERE local_path IS NOT NULL ORDER BY id`);
+ }
}
function isGitRepo(dir: string): boolean {
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index c00f1b492a..6cb4d4a193 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -51,10 +51,10 @@ import { ensureGbrainHome, resolveGbrainHome } from '../core/gbrain-home.ts';
import { loadConfig, type GBrainConfig } from '../core/config.ts';
import {
IPC_UNAVAILABLE,
- readIpcSecret,
+ readIpcSecretForConfig,
requestTurnContext,
requestContextPack,
- resolveSocketPath,
+ resolveSocketPathForConfig,
CONTEXT_PACK_CLIENT_TIMEOUT_MS,
type TurnContextResponse,
type ContextPackResponse,
@@ -491,8 +491,12 @@ async function hookSessionStart(io: HookIo): Promise<number> {
// digest above must never be hostage to the brain being down.
try {
const cfg = loadConfig();
- if (cfg?.engine === 'pglite' && cfg.database_path) {
- const secret = readIpcSecret(cfg.database_path);
+ // Engine-uniform (#4245): same config-keyed socket/secret resolution
+ // as the user-prompt and compact arms (PGLite data dir; Postgres
+ // hash12(database_url) run-dir). Null → silent skip, as before.
+ const packSocket = resolveSocketPathForConfig(cfg);
+ if (packSocket) {
+ const secret = readIpcSecretForConfig(cfg);
if (secret) {
// Same sanitizer as the compact banking path — a raw vs sanitized
// id would split the cursor key and the warm pack would miss the
@@ -504,7 +508,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {
// that blows SESSION_START_DEADLINE_MS.
const remaining = SESSION_START_DEADLINE_MS - (Date.now() - t0) - 100;
if (remaining > 100) {
- const res = await requestContextPack(resolveSocketPath(cfg.database_path), {
+ const res = await requestContextPack(packSocket, {
secret,
...(sessionId ? { sessionId } : {}),
...(process.env.GBRAIN_SOURCE ? { sourceId: process.env.GBRAIN_SOURCE } : {}),
@@ -1061,13 +1065,15 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
if (turns.length === 0) return { outcome: 'ok', reason: 'empty_window' };
const cfg = io.configOverride !== undefined ? io.configOverride : loadConfig();
- if (!cfg?.database_path) {
- // No config, or a Postgres brain (no PGLite data dir → no IPC socket).
- // ENGINE-FREE means no direct-engine fallback here; pull-mode covers it.
+ // Engine-uniform (#4245): PGLite keys the socket off the data dir,
+ // Postgres off hash12(database_url) under ~/.gbrain/run. Null = no
+ // keying material at all (no config, thin-client remote) — ENGINE-FREE
+ // means no direct-engine fallback here; pull-mode covers it.
+ const socketPath = resolveSocketPathForConfig(cfg);
+ if (!socketPath) {
return { outcome: 'degraded', reason: 'no_pglite_path' };
}
- const socketPath = resolveSocketPath(cfg.database_path);
- const secret = readIpcSecret(cfg.database_path);
+ const secret = readIpcSecretForConfig(cfg);
if (!secret) return { outcome: 'degraded', reason: 'no_serve' };
const sessionId = typeof j.session_id === 'string' ? j.session_id : undefined;
@@ -1256,15 +1262,18 @@ async function hookCompact(io: HookIo): Promise<number> {
segment = banked.segment;
const flushCorpusFile = banked.flushCorpusFile;
- // Same engine gate as the session-start pack arm (v0.45.7 symmetry): a
- // Postgres config carrying a leftover database_path must not probe the
- // PGLite socket — there is no serve behind it for this brain.
- if (cfg?.engine !== 'pglite' || !cfg.database_path) { outcome = 'degraded'; reason = 'no_pglite_path'; return; }
- const secret = readIpcSecret(cfg.database_path);
+ // Same engine-uniform resolution as the session-start pack arm (v0.45.7
+ // symmetry, engine-uniform since #4245): a Postgres config carrying a
+ // leftover database_path must not probe the PGLite socket (the resolver
+ // checks engine first); a Postgres brain probes its hash12(database_url)
+ // run-dir socket instead. Null = no keying material → degrade.
+ const compactSocket = resolveSocketPathForConfig(cfg);
+ if (!compactSocket) { outcome = 'degraded'; reason = 'no_pglite_path'; return; }
+ const secret = readIpcSecretForConfig(cfg);
if (!secret) { outcome = 'degraded'; reason = 'no_serve'; return; }
if (remaining() < COMPACT_IPC_MIN_BUDGET_MS) { outcome = 'degraded'; reason = 'deadline'; return; }
- const res = await requestContextPack(resolveSocketPath(cfg.database_path), {
+ const res = await requestContextPack(compactSocket, {
secret,
sessionId,
window: turns,
diff --git a/src/commands/import.ts b/src/commands/import.ts
index d3908c7009..80e15dda64 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -131,6 +131,23 @@ export class ImportAbortError extends Error {
}
}
+/**
+ * #3969 — a poll that changed nothing is not an ingest event. Cron-driven
+ * `import`/`sync` against a mostly-static tree was writing an ingest_log row
+ * every run ("Imported 0 pages, N skipped, 0 chunks" — 93% of rows on a
+ * 15-minute cadence), burying real events past get_ingest_log's default
+ * LIMIT 20. Shared by runImport (directory imports) and performSync (git
+ * syncs). `logNoop` (CLI `--log-noop`) opts back into per-poll rows for
+ * deployments using them as a liveness signal.
+ */
+export function shouldLogIngest(
+ counts: { imported: number; errors: number; chunksCreated: number },
+ logNoop: boolean,
+): boolean {
+ if (logNoop) return true;
+ return counts.imported > 0 || counts.errors > 0 || counts.chunksCreated > 0;
+}
+
/** Bug 9 — surface per-file failures so callers (performFullSync) can gate state advances. */
export interface RunImportResult {
imported: number;
@@ -176,6 +193,8 @@ export async function runImport(
const allowNoncanonicalRoot = args.includes('--allow-noncanonical-root');
const fresh = args.includes('--fresh');
const jsonOutput = args.includes('--json');
+ // #3969: opt back into per-poll ingest_log rows (default: no-op runs skip the write).
+ const logNoop = args.includes('--log-noop');
const includeGitignored = args.includes('--include-gitignored') || opts.includeGitignored === true;
// #3637: under --json, stdout belongs to the JSON document alone. The
@@ -719,13 +738,16 @@ export async function runImport(
}
}
- // Log the ingest
- await engine.logIngest({
- source_type: 'directory',
- source_ref: dir,
- pages_updated: importedSlugs,
- summary: `Imported ${imported} pages, ${skipped} skipped, ${chunksCreated} chunks`,
- });
+ // Log the ingest. #3969: skip the row when the run changed nothing
+ // (imported=0, errors=0, chunks=0) unless --log-noop — see shouldLogIngest.
+ if (shouldLogIngest({ imported, errors, chunksCreated }, logNoop)) {
+ await engine.logIngest({
+ source_type: 'directory',
+ source_ref: dir,
+ pages_updated: importedSlugs,
+ summary: `Imported ${imported} pages, ${skipped} skipped, ${chunksCreated} chunks`,
+ });
+ }
// Import → sync continuity: write sync checkpoint if this is a git repo.
// Bug 9 — gate last_commit on "no failures" so import doesn't silently
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 1b1ba354be..b763edd7a8 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1381,7 +1381,9 @@ function printMemoryVerbsQuickstart(opts: { emptyBrain?: boolean; onPglite?: boo
console.log('→ Do this next — give your agent memory (copy these three commands):');
console.log(' claude mcp add gbrain -- gbrain serve --surface verbs');
console.log(' gbrain remember "I prefer dark mode in every editor" --provenance demo --entity people/me');
- console.log(' gbrain recall --entity people/me');
+ // #3697: recall takes the entity as a positional (there is no --entity flag;
+ // the old form only worked because recall skips unknown flags silently).
+ console.log(' gbrain recall people/me');
console.log('Then ask your agent in a NEW session — it remembers.');
console.log('');
console.log('Note: memories agents save are readable by every agent connected to');
diff --git a/src/commands/integrations.ts b/src/commands/integrations.ts
index 3149892ed5..197281b7b6 100644
--- a/src/commands/integrations.ts
+++ b/src/commands/integrations.ts
@@ -1678,7 +1678,10 @@ async function cmdInstall(args: string[]): Promise<void> {
const { written, manifestPath } = await installRecipeIntoHostRepo(recipeId, opts);
console.log(`[install] ${recipeId}: copied ${written} files into ${realpathSync(opts.target)}`);
console.log(`[install] manifest: ${manifestPath}`);
- if (!opts.dryRun) {
+ // Gate the pointer on the hint actually existing (#4292) — a recipe
+ // without a post-install-hint.md must not send the operator to a 404.
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- manifestPath derives from a findRecipe()-validated bundle root (embedded recipes/ tree or the operator-set GBRAIN_RECIPES_DIR) joined with a literal filename; used only as an existsSync gate on printing a hint line, and `gbrain integrations` is wired only from cli.ts (trusted local, never MCP)
+ if (!opts.dryRun && existsSync(join(pathDirname(manifestPath), 'post-install-hint.md'))) {
console.log('[install] next steps: see recipes/' + recipeId + '/install/post-install-hint.md');
}
}
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 0db3abf6ea..8dd9faeb0c 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -15,6 +15,7 @@ import {
JOB_CHILD_EXIT_USAGE,
} from '../core/minions/worker-exit-codes.ts';
import { CHILD_ENV, resolveChildCliInvocation } from '../core/minions/job-isolation.ts';
+import { withFactsAbsorbHaltCooldown } from '../core/minions/llm-halt-cooldown.ts';
import { runChildJobEntry } from '../core/minions/run-child.ts';
import type { MinionHandler, MinionJob, MinionJobStatus } from '../core/minions/types.ts';
import type { PaceKeyOverrides } from '../core/pace-mode.ts';
@@ -90,6 +91,12 @@ export function factsAbsorbShouldRetry(
return classification === 'keyed' && factsAbsorbUnavailable(result);
}
+// Job names whose handlers call the LLM gateway: registerBuiltinJob wraps
+// them with refreshGatewayForJob so file-plane keys + DB-plane model config
+// reach a long-lived worker. Drift guard: test/jobs-gateway-refresh-set.test.ts
+// pins this set against the registerBuiltinJob call sites — a gateway-using
+// handler registered via bare worker.register() runs with a stale gateway
+// (the #3387 chronicle_extract silent-no_events class).
const GATEWAY_REFRESH_JOB_NAMES = new Set([
'embed',
'extract-conversation-facts',
@@ -105,6 +112,10 @@ const GATEWAY_REFRESH_JOB_NAMES = new Set([
'embed-backfill',
'extract-takes-from-pages',
'embed-catch-up',
+ // #3387: chronicle_extract's judge is a gateway chat call — without the
+ // refresh a worker booted before `config set` never saw the DB-plane chat
+ // model and every extraction silently returned no_events.
+ 'chronicle_extract',
]);
function registerBuiltinJob(
@@ -2296,7 +2307,10 @@ export async function registerBuiltinHandlers(
// LLM spend per page; no shell). Enqueued by the put_page chronicle backstop
// and by `gbrain chronicle backfill`. Idempotent (content-addressed event
// slugs + projection upsert), so a retry re-runs to the same state.
- worker.register('chronicle_extract', async (job) => {
+ // #3387: registered via registerBuiltinJob (gateway-refresh wrap) — the
+ // judge is a gateway chat call, so a stale worker gateway meant silent
+ // no_events for every extraction.
+ registerBuiltinJob(worker, engine, 'chronicle_extract', async (job) => {
const slug = typeof job.data.slug === 'string' ? job.data.slug : undefined;
if (!slug) throw new Error('chronicle_extract job requires data.slug');
const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;
@@ -2426,7 +2440,12 @@ export async function registerBuiltinHandlers(
const dir = typeof job.data.dir === 'string'
? job.data.dir
: (await engine.getConfig('sync.repo_path')) ?? '.';
- return await runExtractCore(engine, { mode, dir, dryRun: !!job.data.dryRun });
+ // #3957: thread the job's source id into the fs-walk extractors. Without
+ // it the batch rows default to source_id='default' and the pages JOIN
+ // drops every row on a non-'default' brain (silent "created 0"), and the
+ // full-walk watermark stamp targets the wrong source.
+ const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;
+ return await runExtractCore(engine, { mode, dir, dryRun: !!job.data.dryRun, sourceId });
});
worker.register('backlinks', async (job) => {
@@ -2447,12 +2466,12 @@ export async function registerBuiltinHandlers(
// Local patch 2026-06-11: durable facts:absorb. One-shot CLI processes
// (capture/put/sync) can't finish the extraction chat before their exit
// drain aborts it, so backstop.ts submits this job instead and the
- // long-lived worker does the LLM work here. Inline mode: errors throw,
- // so minion retry/backoff handles transient gateway failures and real
- // failures stay visible in `gbrain jobs list --status failed`. In the
- // gateway-refresh set so the worker re-stamps model config (and re-folds
- // file-plane keys) before every extraction job.
- registerBuiltinJob(worker, engine, 'facts-absorb', async (job) => {
+ // long-lived worker does the LLM work here. Inline mode: errors throw, so
+ // minion retry/backoff handles transient failures and real ones stay visible
+ // in `gbrain jobs list --status failed`. In the gateway-refresh set (model
+ // config re-stamped per job). #4310: wrapped in the provider-halt cooldown
+ // (llm-halt-cooldown.ts) — a globally-broken provider defers the queue.
+ registerBuiltinJob(worker, engine, 'facts-absorb', withFactsAbsorbHaltCooldown(async (job) => {
const slug = typeof job.data.slug === 'string' ? job.data.slug : '';
if (!slug) throw new Error('facts-absorb job requires data.slug');
const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : 'default';
@@ -2484,14 +2503,13 @@ export async function registerBuiltinHandlers(
// 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. A
- // KEYLESS worker completes the job as a calm skip (its execution-time
- // gate already printed the keyless note; a retry loop would turn every
- // page write into failed-job noise). The retry conversion lives HERE, not
- // in the shared pipeline — the same pipeline serves the extract_facts op,
+ // KEYLESS worker completes the job as a calm skip (its execution-time gate
+ // already printed the keyless note; a retry loop would turn every page
+ // write into failed-job noise). The retry conversion lives HERE, not in
+ // the shared pipeline — the same pipeline serves the extract_facts op,
// which must return its keyless envelope instead of throwing. The
- // classification runs in the WORKER process: availability decisions
- // belong to the process that executes (the submitting hook subprocess may
- // have a deliberately neutered env).
+ // classification runs in the WORKER process (the submitting hook
+ // subprocess may have a deliberately neutered env).
if (factsAbsorbUnavailable(result)) {
const { classifyUnavailable } = await import('../core/facts/backstop.ts');
const jobModel = typeof job.data.model === 'string' && job.data.model ? job.data.model : undefined;
@@ -2501,7 +2519,7 @@ export async function registerBuiltinHandlers(
}
}
return result;
- });
+ }));
// Autopilot-cycle handler: delegates to runCycle. Shares the exact same
// phase set and ordering as `gbrain dream` and autopilot's inline path —
diff --git a/src/commands/lint.ts b/src/commands/lint.ts
index db8e5e5981..687bccf47b 100644
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@ -140,8 +140,16 @@ export function lintContent(content: string, filePath: string, opts: LintContent
});
}
- // Rule: Placeholder dates
+ // Rule: Placeholder dates. #3958: skip lines inside fenced code blocks —
+ // a page DOCUMENTING date formats (```\ncreated: YYYY-MM-DD\n```) is not a
+ // page with an unfilled placeholder. Both ``` and ~~~ fences toggle.
+ let inFence = false;
for (let i = 0; i < lines.length; i++) {
+ if (/^\s{0,3}(```|~~~)/.test(lines[i])) {
+ inFence = !inFence;
+ continue;
+ }
+ if (inFence) continue;
if (lines[i].match(/\bYYYY-MM-DD\b/) || lines[i].match(/\bXX-XX\b/) || lines[i].match(/\b\d{4}-XX-XX\b/)) {
issues.push({
file: filePath, line: i + 1, rule: 'placeholder-date',
@@ -171,10 +179,16 @@ export function lintContent(content: string, filePath: string, opts: LintContent
});
}
if (!fm.match(/^created:/m)) {
+ // #3958: when the page's own frontmatter carries a capture timestamp
+ // (captured_at / ingested_at), `--fix` can promote it to `created` —
+ // mark the finding fixable so the operator knows --fix will heal it.
+ const promotable = /^(?:captured_at|ingested_at):/m.test(fm);
issues.push({
file: filePath, line: 1, rule: 'missing-created',
- message: 'Frontmatter missing required field: created',
- fixable: false,
+ message: promotable
+ ? 'Frontmatter missing required field: created (promotable from captured_at/ingested_at)'
+ : 'Frontmatter missing required field: created',
+ fixable: promotable,
});
}
}
@@ -286,6 +300,25 @@ export function lintContent(content: string, filePath: string, opts: LintContent
return issues;
}
+/**
+ * #3958: promote `captured_at:` (preferred) or `ingested_at:` to `created:`
+ * when the frontmatter has no `created:` of its own. The value is copied
+ * verbatim (quoting preserved) and inserted directly below the source line.
+ * No-op when there is no frontmatter, `created:` already exists, or neither
+ * capture field is present. Pure + exported for tests.
+ */
+export function promoteCreatedFromCapture(content: string): string {
+ if (!content.startsWith('---')) return content;
+ const fmEnd = content.indexOf('---', 3);
+ if (fmEnd <= 0) return content;
+ const fm = content.slice(3, fmEnd);
+ if (fm.match(/^created:/m)) return content;
+ const src = fm.match(/^captured_at:[ \t]*(\S.*)$/m) ?? fm.match(/^ingested_at:[ \t]*(\S.*)$/m);
+ if (!src || src.index === undefined) return content;
+ const insertAt = 3 + src.index + src[0].length;
+ return content.slice(0, insertAt) + `\ncreated: ${src[1].trim()}` + content.slice(insertAt);
+}
+
/** Auto-fix fixable issues */
export function fixContent(content: string): string {
let fixed = content;
@@ -300,6 +333,11 @@ export function fixContent(content: string): string {
fixed = fixed.replace(/^```(?:markdown|md)\s*\n/, '');
fixed = fixed.replace(/\n```\s*$/, '');
+ // #3958: missing-created is fixable when the page's own frontmatter
+ // carries a capture timestamp. Runs after the fence unwrap so a wrapped
+ // page's frontmatter is visible to the promotion.
+ fixed = promoteCreatedFromCapture(fixed);
+
// Clean up excessive blank lines left by fixes
fixed = fixed.replace(/\n{3,}/g, '\n\n');
@@ -465,6 +503,10 @@ export interface LintResult {
pages_scanned: number;
pages_with_issues: number;
total_issues: number;
+ /** #3958: how many of total_issues are fixable — the CLI's "Run with
+ * --fix" hint only prints when this is non-zero, so an all-unfixable
+ * report can't send the operator on a no-op --fix run. */
+ total_fixable: number;
total_fixed: number;
dryRun: boolean;
applied_fix: boolean;
@@ -495,6 +537,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
const lintOpts: LintContentOpts = { contentSanity };
let totalIssues = 0;
+ let totalFixable = 0;
let totalFixed = 0;
let pagesWithIssues = 0;
@@ -515,6 +558,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
if (issues.length === 0) continue;
pagesWithIssues++;
totalIssues += issues.length;
+ totalFixable += issues.filter(i => i.fixable).length;
let fixCount = 0;
if (opts.fix && issues.some(i => i.fixable)) {
@@ -534,6 +578,7 @@ export async function runLintCore(opts: LintOpts): Promise<LintResult> {
pages_scanned: pages.length,
pages_with_issues: pagesWithIssues,
total_issues: totalIssues,
+ total_fixable: totalFixable,
total_fixed: totalFixed,
dryRun: !!opts.dryRun,
applied_fix: !!opts.fix,
@@ -608,7 +653,10 @@ export async function runLint(args: string[]) {
console.log(`\n${result.pages_scanned} pages scanned. ${result.total_issues} issue(s) in ${result.pages_with_issues} page(s).`);
if (doFix) {
console.log(`${dryRun ? '(dry run) ' : ''}${result.total_fixed} auto-fixed.`);
- } else if (result.total_issues > 0) {
- console.log(`Run with --fix to auto-fix fixable issues.`);
+ } else if (result.total_fixable > 0) {
+ // #3958: only advertise --fix when at least one finding is actually
+ // fixable — an all-unfixable report used to send operators on a no-op
+ // `--fix` run that changed nothing.
+ console.log(`Run with --fix to auto-fix ${result.total_fixable} fixable issue(s).`);
}
}
diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.ts
index 4924d0bb42..96b7011ff7 100644
--- a/src/commands/reindex-code.ts
+++ b/src/commands/reindex-code.ts
@@ -28,7 +28,7 @@ import { importCodeFile } from '../core/import-file.ts';
import { estimateTokens } from '../core/chunkers/code.ts';
import { getEmbeddingModelName, estimateEmbeddingCostUsd } from '../core/embedding.ts';
import { errorFor, serializeError } from '../core/errors.ts';
-import { createInterface } from 'readline';
+import { promptYesNo } from '../core/confirm-prompt.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { BudgetTracker, BudgetExhausted } from '../core/budget/budget-tracker.ts';
@@ -186,18 +186,6 @@ async function estimateReindexCost(
return { totalTokens, totalPages };
}
-async function promptYesNo(question: string): Promise<boolean> {
- return new Promise((resolve) => {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- rl.question(question, (answer) => {
- rl.close();
- const a = answer.trim().toLowerCase();
- resolve(a === 'y' || a === 'yes');
- });
- rl.on('close', () => resolve(false));
- });
-}
-
export async function runReindexCode(
engine: BrainEngine,
opts: ReindexCodeOpts = {},
@@ -424,6 +412,26 @@ export function buildCostRefusal(opts: {
};
}
+/**
+ * issue #3970 — recovery hint for the "0 reindexed, N skipped" wall. Without
+ * --force, importCodeFile's content_hash short-circuit skips every unchanged
+ * page, so a user trying to backfill symbol metadata (or re-embed) sees an
+ * all-skipped pass with no pointer at the cure. Pure + exported for tests.
+ * Returns null when the hint doesn't apply (something reindexed, nothing
+ * skipped, or --force already passed).
+ */
+export function reindexForceHint(
+ result: Pick<ReindexCodeResult, 'reindexed' | 'skipped'>,
+ force: boolean | undefined,
+): string | null {
+ if (force || result.reindexed > 0 || result.skipped === 0) return null;
+ return (
+ `All ${result.skipped} page(s) were skipped by the content_hash short-circuit ` +
+ `(content unchanged since last index). To force a full re-chunk + re-embed pass ` +
+ `(e.g. to backfill symbol metadata), re-run with --force.`
+ );
+}
+
/**
* CLI entrypoint. Parses argv, wires cost-preview gate + JSON/TTY branching,
* delegates to runReindexCode. Exit codes: 0 on success/dry-run, 2 on
@@ -555,6 +563,10 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Pr
`(${result.codePages} total code pages, ~${result.totalTokens.toLocaleString()} tokens, ` +
`est. $${result.costUsd.toFixed(2)}).`,
);
+ // #3970: an all-skipped pass without --force is usually someone trying to
+ // heal missing chunk metadata — point at the flag that actually does it.
+ const hint = reindexForceHint(result, force);
+ if (hint) console.log(hint);
if (result.failures && result.failures.length > 0) {
console.log(`\n${result.failures.length} failure(s):`);
for (const f of result.failures.slice(0, 10)) {
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index d4088aa8d7..13a0f23b82 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -71,6 +71,48 @@ export interface ReindexResult {
type: string | null;
}
+// #3686: real usage, reachable via `gbrain reindex --help` (the generic
+// one-line CLI_ONLY stub used to shadow every target flag). The --multimodal
+// flags are parsed by the cli.ts dispatcher (reindex-multimodal routing) but
+// documented here so the whole surface lives in one block.
+const REINDEX_HELP = `gbrain reindex — re-chunk / re-embed existing pages after a pipeline upgrade
+
+USAGE
+ gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--no-embed] [--json] [--repo PATH]
+ gbrain reindex --multimodal [--limit N] [--workers N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]
+ gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]
+
+TARGETS (exactly one required)
+ --markdown Re-chunk markdown pages whose chunker_version lags the
+ current chunker (or whose contextual-retrieval state is
+ unset when embedding is on).
+ --multimodal Re-embed image/PDF chunks through the multimodal
+ embedding pipeline (Voyage batches).
+ --aliases Backfill the free-text alias layer (page_aliases) for
+ pages whose frontmatter aliases predate the projection.
+
+OPTIONS
+ --type <t> --markdown only: restrict to one page type
+ --limit N Cap pages/chunks processed this run
+ --workers N --multimodal only: parallel UPDATEs per batch
+ (--concurrency is an alias)
+ --dry-run Report what would change; write nothing
+ --cost-estimate --multimodal only: print the embed cost estimate and stop
+ --no-embed Skip re-embedding (chunk-only reindex)
+ --yes --multimodal only: skip the cost confirm
+ --source <id> --aliases only: restrict to one source
+ --repo PATH --markdown only: brain repo override
+ --json Machine-readable output
+ --help, -h Show this help
+
+Related: \`gbrain reindex-code --help\`, \`gbrain reindex-frontmatter --help\`,
+\`gbrain reindex-search-vector --help\`.
+`;
+
+export function printReindexHelp(): void {
+ console.log(REINDEX_HELP);
+}
+
const REINDEX_VALUE_FLAGS = new Set(['--type', '--limit', '--repo', '--workers', '--concurrency']);
export function normalizeReindexArgs(args: string[]): string[] {
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index d529b58326..34de458849 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -167,8 +167,27 @@ Resolution chain (7-tier, tier 1 trust-gated):
async function runActive(_args: string[]): Promise<void> {
const cfg = loadConfig();
- const resolution = resolveActivePackNameOnly({ cfg, remote: false });
- const pack = await loadActivePack({ cfg, remote: false });
+ // #3792: consult the DB-plane schema_pack (tier 4) so `gbrain schema
+ // active` reports the SAME pack the engine queries with on brains whose
+ // active pack was flipped via `gbrain config set schema_pack` /
+ // unify-types. Best-effort AND gated on an actually-configured brain
+ // (cfg non-null): an unconfigured home has no DB plane to consult, and
+ // connecting would cold-CREATE a PGLite data dir as a side effect of a
+ // read-only inspection command.
+ let dbConfig: string | undefined;
+ if (cfg) {
+ try {
+ dbConfig = await withConnectedEngine(async (engine) => {
+ try {
+ return (await engine.getConfig('schema_pack')) ?? undefined;
+ } catch {
+ return undefined;
+ }
+ });
+ } catch { /* no connectable DB — file/env resolution stands */ }
+ }
+ const resolution = resolveActivePackNameOnly({ cfg, remote: false, dbConfig });
+ const pack = await loadActivePack({ cfg, remote: false, dbConfig });
console.log(`Active pack: ${pack.manifest.name} v${pack.manifest.version}`);
console.log(`Source: ${resolution.source}`);
console.log(`Pack identity: ${pack.identity}`);
diff --git a/src/commands/skillopt.ts b/src/commands/skillopt.ts
index 7cc8492efe..5445df1cdf 100644
--- a/src/commands/skillopt.ts
+++ b/src/commands/skillopt.ts
@@ -314,6 +314,16 @@ export async function runSkillOptCommand(engine: BrainEngine | null, args: strin
}) + '\n');
} else {
process.stderr.write(`[skillopt] Outcome: ${result.outcome}\n`);
+ // #3516: never a silent failure — say WHY the run aborted/errored.
+ if (result.outcome === 'aborted' || result.outcome === 'errored') {
+ const reason = result.receipt.abort_reason ?? 'unknown';
+ const detail = result.receipt.abort_detail ?? '(no detail captured)';
+ process.stderr.write(`[skillopt] Failure reason: ${reason}\n`);
+ process.stderr.write(`[skillopt] Detail: ${detail}\n`);
+ if (detail.includes('no_pricing')) {
+ process.stderr.write(`[skillopt] Hint: model has no pricing entry; pass --no-max-cost (or --max-cost-usd 0) to run uncapped with a warn-once.\n`);
+ }
+ }
process.stderr.write(`[skillopt] Best sel-score: ${(result.receipt.best_sel_score ?? 0).toFixed(3)}\n`);
process.stderr.write(`[skillopt] Final cost: $${(result.receipt.final_cost_usd ?? 0).toFixed(2)}\n`);
if (result.mutatedSkillFile) {
@@ -398,7 +408,11 @@ export function parseFlags(args: string[]): ParsedFlags {
if (a === '--allow-mutate-bundled') { allowMutateBundled = true; i += 1; continue; }
if (a === '--held-out') { heldOutPath = args[++i]; i += 1; continue; }
if (a === '--json') { json = true; i += 1; continue; }
- if (a === '--max-cost-usd') { maxCostUsd = mustFloat(args[++i], '--max-cost-usd'); i += 1; continue; }
+ // #3516: 0 is accepted and means UNCAPPED — pricing misses for unpriced
+ // model ids (openrouter:*, litellm:*) then warn-once instead of aborting
+ // the run with BudgetExhausted(no_pricing).
+ if (a === '--max-cost-usd') { maxCostUsd = mustNonNegFloat(args[++i], '--max-cost-usd'); i += 1; continue; }
+ if (a === '--no-max-cost') { maxCostUsd = 0; i += 1; continue; }
if (a === '--max-runtime-min') { maxRuntimeMin = mustInt(args[++i], '--max-runtime-min'); i += 1; continue; }
if (a === '--force') { force = true; i += 1; continue; }
if (a === '--resume') { resumeRunId = args[++i]; i += 1; continue; }
@@ -503,6 +517,15 @@ function mustFloat(v: string | undefined, flag: string): number {
return n;
}
+/** #3516: like mustFloat but 0 is allowed (0 = uncapped for --max-cost-usd). */
+function mustNonNegFloat(v: string | undefined, flag: string): number {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) {
+ throw new Error(`${flag} requires a non-negative number (got '${v}'; 0 disables the cap)`);
+ }
+ return n;
+}
+
function handleErrorAndExit(err: unknown, json: boolean, exitCode: number): never {
if (json) {
const envelope = err instanceof StructuredAgentError ? err.envelope : serializeError(err);
diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.ts
index fd87c58330..c66dbd2556 100644
--- a/src/commands/sources-harden.ts
+++ b/src/commands/sources-harden.ts
@@ -42,7 +42,16 @@ function configHost(config: unknown): string | null {
async function loadSourceRows(engine: BrainEngine, id: string | undefined, all: boolean): Promise<SourceRow[]> {
if (all) {
- return engine.executeRaw<SourceRow>(`SELECT id, local_path, config FROM sources WHERE local_path IS NOT NULL ORDER BY id`);
+ // #3880: `--all` skips archived sources (v34 legacy fallback, house
+ // style per pickSoleNonDefaultSource). Explicit <id> below stays
+ // deliberate (recovery ops may target archived rows).
+ try {
+ return await engine.executeRaw<SourceRow>(
+ `SELECT id, local_path, config FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE ORDER BY id`,
+ );
+ } catch {
+ return engine.executeRaw<SourceRow>(`SELECT id, local_path, config FROM sources WHERE local_path IS NOT NULL ORDER BY id`);
+ }
}
if (!id) throw new Error('Usage: gbrain sources harden <id|--all> [--pat-file <p>] [--branch <b>] [--no-cron] [--no-verify] [--dry-run] [--json]');
return engine.executeRaw<SourceRow>(`SELECT id, local_path, config FROM sources WHERE id = $1`, [id]);
diff --git a/src/commands/storage.ts b/src/commands/storage.ts
index 4416d7d310..ba3494e905 100644
--- a/src/commands/storage.ts
+++ b/src/commands/storage.ts
@@ -33,7 +33,32 @@ export interface StorageStatusResult {
// ── Dispatcher ────────────────────────────────────────────
+// #3686: real usage, reachable via `gbrain storage --help` (the generic
+// one-line CLI_ONLY stub used to shadow this surface entirely).
+const STORAGE_HELP = `gbrain storage — storage-tier status for the brain repo
+
+USAGE
+ gbrain storage [status] [--repo <path>] [--json]
+
+SUBCOMMANDS
+ status (default) Report page counts and disk usage per storage
+ tier, list DB pages whose repo file is missing, and
+ validate the storage config.
+
+OPTIONS
+ --repo <path> Brain repo to walk (default: resolved from the storage
+ config / default source path)
+ --json Machine-readable output
+ --help, -h Show this help
+`;
+
export async function runStorage(engine: BrainEngine, args: string[]): Promise<void> {
+ // Help first — before the engine argument is touched, so `--help` works
+ // with no brain configured (dispatched engine-free from cli.ts).
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(STORAGE_HELP);
+ return;
+ }
const subcommand = args[0];
if (!subcommand || subcommand === 'status') {
await runStorageStatus(engine, args.slice(1));
diff --git a/src/commands/sweep-delegate.ts b/src/commands/sweep-delegate.ts
new file mode 100644
index 0000000000..63405e5dda
--- /dev/null
+++ b/src/commands/sweep-delegate.ts
@@ -0,0 +1,250 @@
+/**
+ * Serve-delegated maintenance sweep — the CLI half (#677).
+ *
+ * On a PGLite brain a live `gbrain serve` holds the single-writer lock for
+ * its lifetime, so `gbrain sweep --once` used to exit 1 with
+ * LiveServeLockError. The pre-connect hook in cli.ts calls
+ * maybeDelegateSweepToServe: when the holder is a live serve, the sweep runs
+ * INSIDE the serve over the resolve-IPC socket (sweep_start / sweep_status;
+ * wire shapes in core/context/sweep-ipc.ts, execution in
+ * core/serve-sweep-runner.ts) and this module polls to completion and prints
+ * the report — same decision ladder as commands/sync-delegate.ts.
+ *
+ * Returns false = fall through to the normal connect path (no live serve, or
+ * an explicit opt-out); true = handled (delegated or politely refused with an
+ * exit verdict).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { serr } from '../core/console-prefix.ts';
+import { probeLivePgliteHolder } from '../core/bootstrap/uninstall.ts';
+import {
+ IPC_UNAVAILABLE,
+ readIpcSecret,
+ requestSweepStart,
+ requestSweepStatus,
+ resolveSocketPath,
+ type SweepStartIpcResult,
+} from '../core/context/resolve-ipc.ts';
+import type { DelegatedSweepOptions, SweepStatusResponse } from '../core/context/sweep-ipc.ts';
+
+const POLL_MS = 500;
+const MAX_POLL_FAILURES = 60;
+const PID_PROBE_EVERY = 5;
+
+async function setVerdict(code: number): Promise<void> {
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ setCliExitVerdict(code);
+}
+
+function remediation(pid: number, extra = ''): string {
+ const tail = extra ? ` ${extra}` : '';
+ return (
+ `Alternatives: stop that serve (kill ${pid}) and re-run, or pass --no-delegate ` +
+ `to skip delegation (the run will then fail while the serve holds the lock).${tail}`
+ );
+}
+
+/** Flags this delegation understands (same default-deny posture as sync). */
+const KNOWN_FLAGS = new Set(['--once', '--json', '--no-delegate', '--help', '-h']);
+const VALUE_FLAGS = new Set(['--source', '--budget-ms', '--batch-limit']);
+
+export type ParsedDelegatedSweepArgs =
+ | { ok: true; options: DelegatedSweepOptions; jsonMode: boolean }
+ | { ok: false; refused: string };
+
+/** Pure argv classifier (exported for tests). Default-deny on unknown tokens. */
+export function parseDelegatedSweepArgs(args: string[]): ParsedDelegatedSweepArgs {
+ const options: DelegatedSweepOptions = {};
+ let jsonMode = false;
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (VALUE_FLAGS.has(a)) {
+ const v = args[i + 1];
+ if (v === undefined) return { ok: false, refused: `${a} (missing value)` };
+ if (a === '--source') options.sourceId = v;
+ else {
+ const n = Number(v);
+ if (!Number.isInteger(n) || n < 0) return { ok: false, refused: `${a} ${v}` };
+ if (a === '--budget-ms') options.budgetMs = n;
+ else options.batchLimit = n;
+ }
+ i++;
+ continue;
+ }
+ if (KNOWN_FLAGS.has(a)) {
+ if (a === '--json') jsonMode = true;
+ continue;
+ }
+ return { ok: false, refused: a };
+ }
+ return { ok: true, options, jsonMode };
+}
+
+/**
+ * Delegate `gbrain sweep --once` to a live serve when one holds this PGLite
+ * brain's lock. Mirrors maybeDelegateSyncToServe's ladder.
+ */
+export async function maybeDelegateSweepToServe(dataDir: string, args: string[]): Promise<boolean> {
+ // 0. Explicit opt-outs + non-delegatable spellings (help prints locally;
+ // a missing --once is a local usage error).
+ if (args.includes('--no-delegate') || process.env.GBRAIN_SWEEP_NO_DELEGATE === '1') return false;
+ if (args.includes('--help') || args.includes('-h')) return false;
+ if (!args.includes('--once')) return false;
+ // 1. Mounts never delegate — the socket/secret/lock belong to the HOST brain.
+ try {
+ const { resolveBrainId } = await import('../core/brain-resolver.ts');
+ const { getCliOptions } = await import('../core/cli-options.ts');
+ if (resolveBrainId(getCliOptions().brain) !== 'host') return false;
+ } catch { /* resolver trouble → normal path */ }
+ // 2. Holder probe (read-only; never reaps).
+ const holder = probeLivePgliteHolder(dataDir);
+ if (!holder || !holder.serve) return false;
+
+ // 3. Argv gate (default-deny).
+ const parsed = parseDelegatedSweepArgs(args);
+ if (!parsed.ok) {
+ serr(
+ `[sweep] a live \`gbrain serve\` (PID ${holder.pid}) holds this PGLite brain, and ` +
+ `\`${parsed.refused}\` isn't supported through serve-delegated sweep. ` +
+ remediation(holder.pid),
+ );
+ await setVerdict(1);
+ return true;
+ }
+
+ // Engine-free source tier (env/dotfile); absent → the serve's bound/default.
+ let sourceId = parsed.options.sourceId;
+ if (!sourceId) {
+ try {
+ const { resolveSourceIdEngineFree } = await import('../core/source-resolver.ts');
+ const resolved = resolveSourceIdEngineFree(null);
+ if (resolved && resolved !== '__all__') sourceId = resolved;
+ } catch { /* fall through to the serve's default */ }
+ }
+
+ // 4. Socket + secret.
+ const sock = resolveSocketPath(dataDir);
+ const secret = readIpcSecret(dataDir);
+ if (!existsSync(sock) || !secret) {
+ serr(
+ `[sweep] a live \`gbrain serve\` (PID ${holder.pid}) holds this PGLite brain's ` +
+ `single-writer lock but exposes no sweep IPC (older gbrain, or ` +
+ `GBRAIN_SERVE_SYNC_IPC=0). ` + remediation(holder.pid, 'Restart that serve on this gbrain version.'),
+ );
+ await setVerdict(1);
+ return true;
+ }
+
+ const options: DelegatedSweepOptions = { ...parsed.options, ...(sourceId ? { sourceId } : {}) };
+ const clientToken = randomUUID();
+
+ let start = await requestSweepStart(sock, { secret, clientToken, options });
+ if (start === IPC_UNAVAILABLE) {
+ const still = probeLivePgliteHolder(dataDir);
+ if (!still || !still.serve) return false;
+ start = await requestSweepStart(sock, { secret, clientToken, options });
+ if (start === IPC_UNAVAILABLE) {
+ serr(
+ `[sweep] the live \`gbrain serve\` (PID ${holder.pid}) is not answering its IPC socket. ` +
+ remediation(holder.pid, 'It may be wedged.'),
+ );
+ await setVerdict(1);
+ return true;
+ }
+ }
+ if ('degraded' in (start as object)) {
+ serr(
+ `[sweep] the running \`gbrain serve\` (PID ${holder.pid}) predates serve-delegated sweep. ` +
+ remediation(holder.pid, 'Restart it on this gbrain version.'),
+ );
+ await setVerdict(1);
+ return true;
+ }
+ const startResp = start as Exclude<SweepStartIpcResult, typeof IPC_UNAVAILABLE | { degraded: string }>;
+ if (!startResp.ok) {
+ const messages: Record<string, string> = {
+ busy: `another delegated sweep is already running inside the serve — wait a moment and re-run.`,
+ unauthorized: `the serve rejected the IPC secret — restart the serve (it re-provisions \`.gbrain-ipc-secret\`) and re-run.`,
+ source_mismatch: `the serve is bound to a different source — run \`gbrain sweep --once --source <the serve's source>\`, or stop the serve.`,
+ unsupported_kind: `the serve has delegation disabled (GBRAIN_SERVE_SYNC_IPC=0, an older serve, or a startup failure).`,
+ };
+ const detail = messages[startResp.error ?? ''] ??
+ `the serve refused the delegated sweep (${startResp.error}).`;
+ serr(`[sweep] ${detail} ${remediation(holder.pid, '')}`);
+ await setVerdict(1);
+ return true;
+ }
+
+ const jobId = startResp.jobId!;
+ serr(
+ `[sweep] live \`gbrain serve\` (PID ${holder.pid}) holds the PGLite lock — running ` +
+ `the sweep inside it (job ${jobId}).`,
+ );
+
+ // Poll to completion (a sweep is bounded — default 5s budget).
+ let failures = 0;
+ for (;;) {
+ await new Promise((r) => setTimeout(r, POLL_MS));
+ const s = await requestSweepStatus(sock, { secret, jobId });
+ if (s === IPC_UNAVAILABLE || 'degraded' in (s as object)) {
+ failures++;
+ if (failures % PID_PROBE_EVERY === 0) {
+ const still = probeLivePgliteHolder(dataDir);
+ if (!still || !still.serve) {
+ serr(`[sweep] the serve (PID ${holder.pid}) died mid-sweep — re-run \`gbrain sweep --once\`.`);
+ await setVerdict(1);
+ return true;
+ }
+ }
+ if (failures >= MAX_POLL_FAILURES) {
+ serr(`[sweep] the serve (PID ${holder.pid}) stopped answering its IPC socket mid-sweep.`);
+ await setVerdict(1);
+ return true;
+ }
+ continue;
+ }
+ failures = 0;
+ const status = s as SweepStatusResponse;
+ if (!status.ok) {
+ serr(
+ status.error === 'unknown_job'
+ ? `[sweep] the serve restarted mid-sweep (job ${jobId} is gone) — re-run \`gbrain sweep --once\`.`
+ : `[sweep] delegated sweep failed: ${status.error}`,
+ );
+ await setVerdict(1);
+ return true;
+ }
+ if (status.state === 'error') {
+ serr(`[sweep] delegated sweep failed inside the serve: ${status.jobError ?? 'unknown error'}`);
+ await setVerdict(1);
+ return true;
+ }
+ if (status.state === 'done' && status.report) {
+ const report = status.report;
+ if (parsed.jsonMode) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ console.log(`Sweep complete (${report.durationMs}ms, source=${status.sourceId ?? 'default'}, via serve PID ${holder.pid}):`);
+ console.log(` facts reconciled: ${report.factsReconciled}`);
+ console.log(` links extracted: ${report.linksExtracted}`);
+ console.log(` links removed: ${report.linksRemoved}`);
+ console.log(` timeline extracted: ${report.timelineExtracted}`);
+ console.log(` corpus ingested: ${report.corpusIngested}`);
+ if (report.skipped.length > 0) {
+ console.log(' skipped:');
+ for (const sk of report.skipped) console.log(` ${sk.reason}: ${sk.count}`);
+ }
+ }
+ // Mirror runSweep's exit rule: total failure exits nonzero.
+ const { isTotalFailure } = await import('./sweep.ts');
+ if (isTotalFailure(report)) {
+ serr('[sweep] total failure — every pass errored. See skipped reasons above.');
+ await setVerdict(1);
+ }
+ return true;
+ }
+ // running → keep polling.
+ }
+}
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 84b258c4ac..ac0a8a1ff2 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -1,9 +1,9 @@
import { existsSync, readFileSync, writeFileSync, statSync, realpathSync } from 'fs';
-import { join, relative } from 'path';
+import { join, relative, resolve as pathResolve } from 'path';
import type { BrainEngine } from '../core/engine.ts';
import { DELETE_BATCH_SIZE } from '../core/engine-constants.ts';
-import { importFile } from '../core/import-file.ts';
-import { collectSyncableFiles } from './import.ts';
+import { importFile, importImageFile, isImageFilePath as isImageImportPath } from '../core/import-file.ts';
+import { collectSyncableFiles, shouldLogIngest } from './import.ts';
import {
isSyncable,
isPoisonedPath,
@@ -18,6 +18,8 @@ import {
applySyncFailureGate,
isSkippablePath,
resolveAutoSkipThreshold,
+ summarizeFailuresByCode,
+ isEmbeddingInfraCode,
DEFAULT_SOURCE_ID,
} from '../core/sync.ts';
import {
@@ -100,6 +102,8 @@ import {
writeSyncAnchor,
readChunkerVersion,
writeChunkerVersion,
+ resolveSlugRootMode,
+ type SlugRootMode,
} from '../core/sync-anchor.ts';
import {
SyncLockBusyError,
@@ -226,6 +230,14 @@ export interface SyncResult {
embedded: number;
pagesAffected: string[];
failedFiles?: number; // count of parse failures (Bug 9)
+ /**
+ * #3875: code breakdown of the blocking failures (set on
+ * `blocked_by_failures` only). Lets printSyncResult (and --json consumers)
+ * distinguish provider-infra failures (EMBEDDING_TIMEOUT / RATE_LIMIT /
+ * QUOTA — retry after fixing the provider) from genuine file poison
+ * (--skip-failed territory).
+ */
+ failureCodes?: Array<{ code: string; count: number }>;
/**
* Files skipped because their FILENAME contains bracket/control characters
* (SyncableReason 'malformed-path'). Informational — these never gate
@@ -283,6 +295,12 @@ export interface SyncOpts {
noPull?: boolean;
noEmbed?: boolean;
noExtract?: boolean;
+ /**
+ * #3969: opt back into per-poll ingest_log rows. By default a sync that
+ * landed nothing (no pages written, no chunks, no failures acknowledged)
+ * skips the ingest_log write — mirrors runImport's shouldLogIngest gate.
+ */
+ logNoop?: boolean;
/** Bug 9 — acknowledge + skip past current failure set (CLI --skip-failed). */
skipFailed?: boolean;
/** Bug 9 — re-attempt unacknowledged failures explicitly (CLI --retry-failed). */
@@ -577,13 +595,21 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
serr(`[gbrain phase] sync.resolve_repo`);
opts.onProgress?.({ phase: 'resolve_repo' });
// Resolve repo path
- const repoPath = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
- if (!repoPath) {
+ const rawRepoPath = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
+ if (!rawRepoPath) {
const hint = opts.sourceId
? `Source "${opts.sourceId}" has no local_path. Run: gbrain sources add ${opts.sourceId} --path <path>`
: `No repo path specified. Use --repo or run gbrain init with --repo first.`;
throw new Error(hint);
}
+ // #3696: resolve to ABSOLUTE at entry. A relative path (legacy relative
+ // sources.local_path row, or a caller-passed `--repo .`) breaks the moment
+ // any consumer runs from a different cwd (launchd daemon at cwd=/). Since
+ // writeSyncAnchor('repo_path', anchorPath) re-persists this value below,
+ // one successful sync from the right cwd self-heals a legacy relative row
+ // to absolute.
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rawRepoPath is the local operator's --repo CLI arg or the operator-written sync anchor (sync.repo_path / sources.local_path); the sync_brain op is localOnly:true so no remote caller reaches this path, and absolutizing it here IS the #3696 fix
+ const repoPath = pathResolve(rawRepoPath);
serr(`[gbrain phase] sync.load_active_pack`);
// v0.39 T1.5: load active pack ONCE at sync entry; pass to every per-file
@@ -796,7 +822,31 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// the SCOPE path, so a follow-up bare `gbrain sync` auto-discovers the same
// scope. Unchanged (the caller's repoPath spelling) when no --src-subpath.
const anchorPath = opts.srcSubpath ? rawScopeRoot : repoPath;
- const fullSyncRoots = { gitContextRoot, syncScopeRoot, anchorPath };
+ // #4342 — explicit + STICKY slug namespace for scoped syncs. Pre-fix the
+ // namespace was implicit: a local_path that happened to sit inside a bigger
+ // git repo silently produced git-root-PREFIXED slugs (`notes/foo` instead
+ // of `foo`), diverging from what `gbrain import <dir>` of the same tree
+ // creates. The mode is decided once (resolveSlugRootMode: stored pin >
+ // explicit --src-subpath > auto-pin when existing pages already carry the
+ // prefix > local_path-relative) and persisted, so a live install never
+ // re-slugs and every later sync agrees.
+ let slugRootMode: SlugRootMode = 'git-root';
+ if (scoped) {
+ // Probe prefix in SLUG spelling (resolveSlugForPath), not raw path
+ // spelling — the auto-pin LIKE must match how slugs were actually minted.
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- syncScopeRelPath is relative() of the realpath'd scope already proven inside the realpath'd git root by the isWithinRoot guard above (so it carries no ..); the join output only mints an in-memory slug probe string, no fs operation
+ const probeSlug = resolveSlugForPath(join(syncScopeRelPath, 'x.md'));
+ const slugPrefix = probeSlug.slice(0, probeSlug.length - '/x'.length);
+ slugRootMode = await resolveSlugRootMode(engine, {
+ sourceId: opts.sourceId,
+ explicitGitRoot: opts.srcSubpath !== undefined,
+ slugPrefix,
+ // #4342 review fix: a --dry-run must not persist the sticky pin —
+ // resolve in-memory only; the first real sync writes it.
+ dryRun: opts.dryRun === true,
+ });
+ }
+ const fullSyncRoots = { gitContextRoot, syncScopeRoot, anchorPath, slugRootMode };
serr(`[gbrain phase] sync.detect_head`);
// Detect detached HEAD up front so the working-tree fallback fires for both
@@ -1224,6 +1274,24 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
.map(r => r.to),
]);
+ // #4342 'source-root' mode: translate the (git-root-relative) manifest to
+ // SOURCE-relative paths so every downstream consumer — slugs, source_path,
+ // deletes, renames, checkpoints — names pages the way `gbrain import
+ // <local_path>` would. Under 'git-root' (or an unscoped sync) this is a
+ // no-op and the pre-#4342 behavior is byte-for-byte. The file-join base
+ // below (`syncImportRoot`) moves with it so `join(base, path)` still lands
+ // on the same file.
+ const sourceRootMode = scoped && slugRootMode === 'source-root';
+ const syncImportRoot = sourceRootMode ? syncScopeRoot : gitContextRoot;
+ /** Manifest path → the mode's canonical page path (slug/source_path base). */
+ const modePath = (p: string): string => (sourceRootMode ? scopeRel(p) : p);
+ if (sourceRootMode) {
+ filtered.added = filtered.added.map(scopeRel);
+ filtered.modified = filtered.modified.map(scopeRel);
+ filtered.deleted = filtered.deleted.map(scopeRel);
+ filtered.renamed = filtered.renamed.map(r => ({ from: scopeRel(r.from), to: scopeRel(r.to) }));
+ }
+
// 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.
@@ -1310,7 +1378,9 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
if (reason === 'malformed-path' && !isPoisonedPath(path)) continue;
// #3942: guarded resolver — never delete a page whose recorded origin is
// a DIFFERENT file just because this path re-slugifies onto its slug.
- const slug = await resolveRemovedPathSlug(engine, path, opts.sourceId, serr);
+ // #4342: resolve in the mode's namespace (source-relative under
+ // 'source-root'; git-root-relative otherwise).
+ const slug = await resolveRemovedPathSlug(engine, modePath(path), opts.sourceId, serr);
if (slug === undefined) continue;
try {
const existing = await engine.getPage(slug, pageOpts);
@@ -1781,14 +1851,21 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// throw here crashes the whole sync mid-run and freezes the checkpoint,
// defeating --skip-failed. A `skipped` result carrying an error is also
// captured so the failure is recorded rather than silently dropped.
- // Paths from git diff are relative to gitContextRoot; join from there.
+ // Paths from git diff are relative to gitContextRoot — except under
+ // #4342's 'source-root' mode, where the filtered manifest (this loop's
+ // source) was remapped scope-relative; the join base moves with it.
// NAV-1 TOCTOU: refuse a destination that realpath-resolves outside the
// repo (committed symlink pointing out).
- const filePath = join(gitContextRoot, to);
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `to` is a git-diff rename path from the synced repo (repo content can be hostile), but the joined path is used ONLY inside the isPathSafe(filePath, gitContextRoot) realpath containment check on the next line — a path escaping the repo root (dot-dot or committed symlink) is refused before any read
+ const filePath = join(syncImportRoot, to);
let importResult: Awaited<ReturnType<typeof importFile>> | undefined;
if (existsSync(filePath) && isPathSafe(filePath, gitContextRoot)) {
try {
- const result = await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack });
+ // #2683: dispatch renamed images to importImageFile (binary bytes
+ // through importFile threw UTF-8 errors). Same gate as import.ts.
+ const result = isImageImportPath(to) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'
+ ? await importImageFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId })
+ : await importFile(engine, filePath, to, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack });
importResult = result;
noteTypeWarning(result.type_warning);
if (result.status === 'imported') chunksCreated += result.chunks;
@@ -1937,8 +2014,10 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
progress.start('sync.imports', importsToDo.length);
// Core import logic shared by serial and parallel paths.
- // Paths from git diff are relative to gitContextRoot; join from there.
- const syncRepoPath = gitContextRoot;
+ // Paths from git diff are relative to gitContextRoot; under #4342's
+ // 'source-root' mode the filtered manifest was remapped scope-relative,
+ // so the join base moves to syncScopeRoot with it.
+ const syncRepoPath = syncImportRoot;
// paced-backfill (T3 / C9 / CX4): ONE shared pacer across all worker
// engines. This is the multi-pool permit case — each parallel worker owns a
// separate PostgresEngine, so a single worker count can't bound TOTAL
@@ -2059,8 +2138,14 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
// / addLink) target (sourceId, slug). Pre-fix the schema DEFAULT
// 'default' was applied even for non-default sources, fabricating
// duplicate rows that crashed bare-slug subqueries with Postgres 21000.
+ // #2683: incremental adds/modifies dispatch images to importImageFile
+ // when multimodal is on (same gate as import.ts's full-sync walker).
+ // Pre-fix, a committed .png went through importFile's UTF-8 text read
+ // and failed — images only ever landed via `sync --full`.
const result = await observed(pacer, () =>
- importFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack }));
+ isImageImportPath(path) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'
+ ? importImageFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId })
+ : importFile(eng, filePath, path, { noEmbed, sourceId: opts.sourceId, activePack: syncActivePack }));
noteTypeWarning(result.type_warning);
if (result.status === 'imported') {
chunksCreated += result.chunks;
@@ -2349,13 +2434,29 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
);
} else {
const fileFailCount = failedFiles.filter(f => isSkippablePath(f.path)).length;
- 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 ` +
- `acknowledge and move on. A file that keeps failing auto-skips after ` +
- `${resolveAutoSkipThreshold()} consecutive syncs.`,
- );
+ // #3875: code-aware copy. Provider-infra failures (embed timeout /
+ // rate limit / quota) are NOT bad files — suggesting --skip-failed for
+ // them acknowledges away perfectly good content. Point at provider
+ // health + a plain re-run (or --full to rebuild) instead.
+ const infraCodes = summarizeFailuresByCode(failedFiles).filter(c => isEmbeddingInfraCode(c.code));
+ if (infraCodes.length > 0) {
+ serr(
+ `\nSync blocked: ${fileFailCount} file(s) failed — embedding provider errors:\n` +
+ `${codeBreakdown}\n\n` +
+ `These are provider-health failures (timeout / rate limit / quota), not bad ` +
+ `files — do NOT use --skip-failed for them. Check the embedding provider ` +
+ `(is it running? out of quota?), then re-run 'gbrain sync' (only the failed ` +
+ `files are re-attempted), or 'gbrain sync --full' to rebuild.`,
+ );
+ } 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 ` +
+ `acknowledge and move on. A file that keeps failing auto-skips after ` +
+ `${resolveAutoSkipThreshold()} consecutive syncs.`,
+ );
+ }
}
// Update last_run + repo_path (progress on infra) but NOT last_commit. The
// checkpoint is INTENTIONALLY left in place — the banked completed set lets
@@ -2380,6 +2481,7 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
embedded: 0,
pagesAffected,
failedFiles: failedFiles.length,
+ failureCodes: summarizeFailuresByCode(failedFiles),
bankedFiles,
};
}
@@ -2398,16 +2500,28 @@ async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<Sy
);
}
- // Log ingest
- await engine.logIngest({
- // #3242 (attribution sub-bug): credit the sync to the source it wrote
- // to, not the shared 'default' bucket.
- ...(opts.sourceId ? { source_id: opts.sourceId } : {}),
- source_type: 'git_sync',
- source_ref: `${repoPath} @ ${headCommit.slice(0, 8)}`,
- pages_updated: pagesAffected,
- summary: `Sync: +${filtered.added.length} ~${filtered.modified.length} -${filtered.deleted.length} R${filtered.renamed.length}, ${chunksCreated} chunks, ${elapsed}ms`,
- });
+ // Log ingest. #3969: mirror runImport's shouldLogIngest gate — a run that
+ // landed nothing (no pages written, no chunks, no failures acknowledged or
+ // auto-skipped) is a poll, not an ingest event; skip the row unless
+ // opts.logNoop opts back in.
+ if (shouldLogIngest(
+ {
+ imported: pagesAffected.length,
+ errors: gate.acknowledged + gate.autoSkipped.length,
+ chunksCreated,
+ },
+ opts.logNoop === true,
+ )) {
+ await engine.logIngest({
+ // #3242 (attribution sub-bug): credit the sync to the source it wrote
+ // to, not the shared 'default' bucket.
+ ...(opts.sourceId ? { source_id: opts.sourceId } : {}),
+ source_type: 'git_sync',
+ source_ref: `${repoPath} @ ${headCommit.slice(0, 8)}`,
+ pages_updated: pagesAffected,
+ summary: `Sync: +${filtered.added.length} ~${filtered.modified.length} -${filtered.deleted.length} R${filtered.renamed.length}, ${chunksCreated} chunks, ${elapsed}ms`,
+ });
+ }
// Auto-extract links + timeline (cheap CPU, but skip-inline for LARGE syncs).
// Thread opts.sourceId so the extract phase reconciles edges + timeline
@@ -2627,15 +2741,17 @@ async function performFullSync(
// syncScopeRoot — where files are walked/imported (== gitContextRoot
// when no subpath scope is active)
// anchorPath — what gets written back to sync.repo_path/local_path
- roots: { gitContextRoot: string; syncScopeRoot: string; anchorPath: string },
+ // slugRootMode — #4342 sticky namespace anchor (git-root|source-root)
+ roots: { gitContextRoot: string; syncScopeRoot: string; anchorPath: string; slugRootMode: SlugRootMode },
headCommit: string,
opts: SyncOpts,
): Promise<SyncResult> {
- const { gitContextRoot, syncScopeRoot, anchorPath } = roots;
- // Scoped sync → slugs/source_path are git-root-relative (matches the
- // incremental path's git-diff paths). Unscoped → undefined (dir-relative,
- // the pre-#774 behavior, byte-for-byte).
- const slugRoot = syncScopeRoot !== gitContextRoot ? gitContextRoot : undefined;
+ const { gitContextRoot, syncScopeRoot, anchorPath, slugRootMode } = roots;
+ // Scoped 'git-root' sync → slugs/source_path are git-root-relative (matches
+ // the incremental path's git-diff paths). Unscoped OR pinned 'source-root'
+ // (#4342) → undefined (dir-relative — local_path IS the slug base).
+ const slugRoot =
+ syncScopeRoot !== gitContextRoot && slugRootMode === 'git-root' ? gitContextRoot : undefined;
// Dry-run: walk the scope, count syncable files, return without writing.
// Fixes the silent-write-on-dry-run bug where performFullSync called
// runImport unconditionally regardless of opts.dryRun.
@@ -2754,12 +2870,25 @@ async function performFullSync(
serr(`\nFull sync blocked: repository history changed during sync.\n${codeBreakdown}`);
} else {
const fileFailCount = result.failures.filter(f => isSkippablePath(f.path)).length;
- 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 ` +
- `that keeps failing auto-skips after ${resolveAutoSkipThreshold()} consecutive syncs.`,
- );
+ // #3875: code-aware copy — provider-infra failures must not be routed
+ // to --skip-failed (same rationale as the incremental gate above).
+ const infraCodes = summarizeFailuresByCode(result.failures).filter(c => isEmbeddingInfraCode(c.code));
+ if (infraCodes.length > 0) {
+ serr(
+ `\nFull sync blocked: ${fileFailCount} file(s) failed — embedding provider errors:\n` +
+ `${codeBreakdown}\n\n` +
+ `These are provider-health failures (timeout / rate limit / quota), not bad ` +
+ `files — do NOT use --skip-failed for them. Check the embedding provider, ` +
+ `then re-run 'gbrain sync --full'.`,
+ );
+ } 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 ` +
+ `that keeps failing auto-skips after ${resolveAutoSkipThreshold()} consecutive syncs.`,
+ );
+ }
}
await engine.setConfig('sync.last_run', new Date().toISOString());
await writeSyncAnchor(engine, opts.sourceId, 'repo_path', anchorPath);
@@ -2772,6 +2901,7 @@ async function performFullSync(
embedded: 0,
pagesAffected: [],
failedFiles: result.failures.length,
+ failureCodes: summarizeFailuresByCode(result.failures),
};
}
if (fullGate.acknowledged > 0) {
@@ -3327,8 +3457,33 @@ See also:
// surfaces the auto-route to stderr so the user knows what happened
// and can pass --source to override if needed.
const explicitSource = args.find((a, i) => args[i - 1] === '--source') || null;
- const { resolveSourceWithTier, formatSoleNonDefaultNudge } = await import('../core/source-resolver.ts');
- const resolved = await resolveSourceWithTier(engine, explicitSource);
+ const { resolveSourceWithTier, resolveSourceForRepoPath, formatSoleNonDefaultNudge } =
+ await import('../core/source-resolver.ts');
+ // #3765: an explicit --repo anchors source resolution at the REPO dir, not
+ // the caller's cwd. Pre-fix, `gbrain sync --repo ~/other-vault` parsed the
+ // path but resolved the source from cwd — anchors, page writes, and the
+ // per-source lock (`syncLockId(sourceId)`) all followed the WRONG source.
+ // Precedence: --source flag > repo-derived (dotfile/local_path at the repo
+ // dir) > the ambient chain. A conflicting GBRAIN_SOURCE refuses loudly.
+ let resolved: { source_id: string; tier: string; detail?: string } | null = null;
+ if (!explicitSource && repoPath) {
+ const derived = await resolveSourceForRepoPath(engine, repoPath);
+ if (derived) {
+ const envSource = process.env.GBRAIN_SOURCE;
+ if (envSource && envSource !== derived.source_id) {
+ console.error(
+ `--repo resolves to source '${derived.source_id}' (via ${derived.tier}) but ` +
+ `GBRAIN_SOURCE='${envSource}' is set. Pass --source <id> to disambiguate.`,
+ );
+ process.exit(1);
+ }
+ resolved = derived;
+ process.stderr.write(
+ `[gbrain] routing sync to source '${derived.source_id}' (resolved from --repo via ${derived.tier}).\n`,
+ );
+ }
+ }
+ if (!resolved) resolved = await resolveSourceWithTier(engine, explicitSource);
const sourceId: string = resolved.source_id;
if (resolved.tier === 'sole_non_default') {
const nudge = formatSoleNonDefaultNudge(sourceId);
@@ -3367,9 +3522,20 @@ See also:
// own "do work?" gate (sync.ts:1057+1075) + doctor's sync_freshness.
// Both columns predate v0.41 (writeSyncAnchor / writeChunkerVersion); no
// schema migration needed.
- const sources = await engine.executeRaw<{ id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null }>(
- `SELECT id, name, local_path, config, last_commit, chunker_version FROM sources WHERE local_path IS NOT NULL`,
- );
+ // #3880: archived sources must not re-enter `sync --all`. The archived
+ // column is v34+ — fall back to the unfiltered query on older brains
+ // (house style per pickSoleNonDefaultSource).
+ type SyncAllSourceRow = { id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null };
+ let sources: SyncAllSourceRow[];
+ try {
+ sources = await engine.executeRaw<SyncAllSourceRow>(
+ `SELECT id, name, local_path, config, last_commit, chunker_version FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ );
+ } catch {
+ sources = await engine.executeRaw<SyncAllSourceRow>(
+ `SELECT id, name, local_path, config, last_commit, chunker_version FROM sources WHERE local_path IS NOT NULL`,
+ );
+ }
if (!sources || sources.length === 0) {
console.log('No sources with local_path configured. Use `gbrain sources add <id> --path <path>` first.');
return;
@@ -4301,11 +4467,23 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = p
break;
case 'dry_run':
break; // already printed in performSync
- case 'blocked_by_failures':
- write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed to parse.`);
+ case 'blocked_by_failures': {
+ write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed.`);
write(` See ~/.gbrain/sync-failures.jsonl for details, or run 'gbrain doctor'.`);
- write(` Fix the files then re-run 'gbrain sync', or 'gbrain sync --skip-failed' to move on.`);
+ // #3875: code-aware recovery hint — provider-infra failures are not
+ // fixed by --skip-failed (that would silently unindex good files).
+ const infraCodes = (result.failureCodes ?? []).filter(c => isEmbeddingInfraCode(c.code));
+ if (infraCodes.length > 0) {
+ write(
+ ` Embedding provider errors (${infraCodes.map(c => `${c.code} x${c.count}`).join(', ')}): ` +
+ `check provider health, then re-run 'gbrain sync' (or 'gbrain sync --full'). ` +
+ `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.`);
+ }
break;
+ }
case 'partial':
// #3068: a failed (non-timeout) pull with zero imports gets its own
// message — "imported 0 of 0" reads like success, but the local
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index d2b9d759eb..8866886444 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -27,6 +27,12 @@ import {
} from '../core/takes-write.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
+import {
+ listPendingProposals,
+ acceptProposal,
+ rejectProposal,
+ TakeProposalError,
+} from '../core/take-proposals.ts';
// --- Helpers ---
@@ -461,6 +467,93 @@ async function cmdCalibration(engine: BrainEngine, args: string[]): Promise<void
}
}
+/**
+ * #2411 / #4102 — `gbrain takes propose` drains the take_proposals queue the
+ * propose_takes cycle phase fills. Bare invocation lists pending proposals;
+ * --accept promotes one into the page's takes fence via the shared
+ * write-through core (D17: the ONLY queue→canonical path); --reject dismisses.
+ * Before this command existed the dispatcher parsed `propose` as a page slug
+ * and printed "No takes on propose." with exit 0 — a dead-end queue.
+ */
+async function cmdPropose(engine: BrainEngine, args: string[], sourceId: string): Promise<void> {
+ const json = flagPresent(args, '--json');
+ const acceptRaw = flagValue(args, '--accept');
+ const rejectRaw = flagValue(args, '--reject');
+ if (acceptRaw !== undefined && rejectRaw !== undefined) {
+ console.error('Error: --accept and --reject are mutually exclusive (choose one).');
+ process.exit(1);
+ }
+
+ const parseId = (raw: string, flag: string): number => {
+ const id = parseInt(raw, 10);
+ if (!Number.isFinite(id) || id <= 0 || String(id) !== raw.trim()) {
+ console.error(`Invalid ${flag} "${raw}". Expected a proposal id (from \`gbrain takes propose\`).`);
+ process.exit(1);
+ }
+ return id;
+ };
+
+ const actedBy = resolveOwnerHolder({
+ configValue: await engine.getConfig('emotional_weight.user_holder'),
+ });
+
+ if (acceptRaw !== undefined) {
+ const id = parseId(acceptRaw, '--accept');
+ const dirArg = flagValue(args, '--dir');
+ const brainDir = await resolveBrainDir(engine, dirArg ?? null);
+ try {
+ const { proposal, rowNum } = await acceptProposal({ engine, brainDir, sourceId, actedBy }, id);
+ console.log(`Accepted proposal #${id} → take #${rowNum} on ${proposal.page_slug}.`);
+ } catch (err) {
+ if (err instanceof TakeProposalError) {
+ console.error(err.message);
+ process.exit(1);
+ }
+ exitTakesError(err);
+ }
+ return;
+ }
+
+ if (rejectRaw !== undefined) {
+ const id = parseId(rejectRaw, '--reject');
+ try {
+ const proposal = await rejectProposal({ engine, sourceId, actedBy }, id);
+ console.log(`Rejected proposal #${id} (${proposal.page_slug}).`);
+ } catch (err) {
+ if (err instanceof TakeProposalError) {
+ console.error(err.message);
+ process.exit(1);
+ }
+ throw err;
+ }
+ return;
+ }
+
+ // Bare `takes propose` — list the pending queue (source-scoped).
+ const limitRaw = flagValue(args, '--limit');
+ const limit = limitRaw !== undefined ? parseInt(limitRaw, 10) : 20;
+ if (!Number.isFinite(limit) || limit <= 0) {
+ console.error(`Invalid --limit "${limitRaw}". Expected a positive integer.`);
+ process.exit(1);
+ }
+ const pending = await listPendingProposals(engine, { sourceId, limit });
+ if (json) {
+ console.log(JSON.stringify(pending, null, 2));
+ return;
+ }
+ if (pending.length === 0) {
+ console.log('No pending take proposals. The propose_takes cycle phase fills this queue.');
+ return;
+ }
+ console.log(`# Pending take proposals (${pending.length})\n`);
+ for (const p of pending) {
+ const w = Number(p.weight).toFixed(2);
+ const domain = p.domain ? ` • ${p.domain}` : '';
+ console.log(`#${p.id} ${p.page_slug} [${p.kind} • ${p.holder} • w=${w}${domain}]\n ${p.claim_text}\n`);
+ }
+ console.log('Accept with `gbrain takes propose --accept <id>`; reject with `--reject <id>`.');
+}
+
// --- Dispatcher ---
export async function runTakes(engine: BrainEngine, args: string[]): Promise<void> {
@@ -485,6 +578,10 @@ Subcommands:
[--evidence "..."] [--value N --unit usd|pct|count] [--by <slug>]
Record bet resolution (immutable, v0.30.0)
Back-compat: --outcome true|false (deprecated alias)
+ takes propose [--limit N] [--json] List pending LLM-proposed takes (propose_takes queue)
+ takes propose --accept <id> [--dir <path>]
+ Promote a proposal into the page's takes fence
+ takes propose --reject <id> Dismiss a proposal
takes scorecard [<holder>] [--domain <prefix>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
Aggregate calibration scorecard (v0.30.0)
takes calibration [<holder>] [--bucket-size 0.1] [--json]
@@ -509,6 +606,9 @@ Common flags:
case 'update': return cmdUpdate(engine, rest, await resolveTakesSourceId(engine));
case 'supersede': return cmdSupersede(engine, rest, await resolveTakesSourceId(engine));
case 'resolve': return cmdResolve(engine, rest, await resolveTakesSourceId(engine));
+ // #2411: `takes propose` used to fall through to the slug path and print
+ // "No takes on propose." — the LLM proposal queue had no drain surface.
+ case 'propose': return cmdPropose(engine, rest, await resolveTakesSourceId(engine));
case 'scorecard': return cmdScorecard(engine, rest);
case 'calibration': return cmdCalibration(engine, rest);
case 'revisit': return cmdRevisit(engine, rest);
diff --git a/src/commands/think.ts b/src/commands/think.ts
index e4aa6250d3..ad6c7ca233 100644
--- a/src/commands/think.ts
+++ b/src/commands/think.ts
@@ -114,6 +114,9 @@ prints what would have been the input (exit 0).
let result: any;
let savedSlug: string | undefined;
let evidenceInserted = 0;
+ // #2556: --take persistence outputs.
+ let takeRow: number | null = null;
+ let takePath: string | undefined;
const cfg = loadConfig();
if (isThinClient(cfg)) {
if (save || take) {
@@ -160,6 +163,25 @@ prints what would have been the input (exit 0).
process.exit(1);
}
}
+
+ // #2556: --take was documented (and parsed) since v0.28 but never
+ // executed — runThink ignored opts.take entirely. Persist md-first
+ // through the canonical takes write-through; a refusal (no repo, empty
+ // answer, failed synthesis, write error) exits non-zero (same F2
+ // posture as --save: the user explicitly asked for a persist).
+ if (take && anchor) {
+ const { persistTakeFromSynthesis } = await import('../core/think/persist-take.ts');
+ const persisted = await persistTakeFromSynthesis(engine, result, { anchor });
+ takeRow = persisted.take_row;
+ takePath = persisted.path;
+ for (const w of persisted.warnings) result.warnings.push(w);
+ if (persisted.take_row === null) {
+ console.error(
+ `think: --take requested but no take row was appended (${persisted.warnings.join(', ') || 'unknown reason'}).`,
+ );
+ process.exit(1);
+ }
+ }
} catch (e) {
// #1698: an unresolvable explicit --model throws here. Clean non-zero exit
// with the actionable message, not a stack trace.
@@ -179,6 +201,7 @@ prints what would have been the input (exit 0).
cost_usd: costUsd ?? null,
saved_slug: savedSlug ?? null,
evidence_inserted: evidenceInserted,
+ take_row: takeRow,
}, null, 2));
return;
}
@@ -198,6 +221,9 @@ prints what would have been the input (exit 0).
if (savedSlug) {
console.log(`Saved: ${savedSlug} (${evidenceInserted} evidence rows)`);
}
+ if (takeRow !== null) {
+ console.log(`Take: row ${takeRow} appended to ${anchor}${takePath ? ` (${takePath})` : ''}`);
+ }
if (result.warnings.length > 0) {
console.error(`Warnings: ${result.warnings.join(', ')}`);
}
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index 905284448f..e2cd4bcaa1 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -17,9 +17,48 @@
*/
import type { GBrainConfig } from '../config.ts';
+import { loadConfig } from '../config.ts';
import type { AIGatewayConfig } from './types.ts';
import { mergedProviderEnv } from './provider-env.ts';
+/**
+ * #3350: fold FILE-plane `provider_base_urls.{anthropic,openai}` into the
+ * gateway env as `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL`, same shape as the
+ * credential folds (env wins for keys carrying a real value). Native
+ * providers read their base URL exclusively from env via
+ * `resolveNativeBaseUrl` (which also normalizes the `/v1` suffix), so before
+ * this fold a config.json `provider_base_urls.anthropic` was silently ignored
+ * by native chat/embed calls.
+ *
+ * MOUNT SAFETY (gateway.ts `reconfigureGatewayWithEngine` rationale): the
+ * fold takes the FILE config explicitly — never a DB-merged config — so
+ * DB-plane `provider_base_urls.*` (which can be merged from a shared brain)
+ * can never steer this process's native bearer keys to an attacker URL.
+ * `buildGatewayConfig` therefore re-reads `loadConfig()` for this fold even
+ * when its caller passed a DB-merged config.
+ *
+ * @internal exported for tests + gateway's file-plane env refresh.
+ */
+export function foldNativeBaseUrlsFromFilePlane(
+ fileCfg: Pick<GBrainConfig, 'provider_base_urls'> | null,
+ env: Record<string, string | undefined>,
+): Record<string, string | undefined> {
+ const urls = fileCfg?.provider_base_urls;
+ if (!urls) return env;
+ const out = { ...env };
+ for (const [provider, envKey] of [
+ ['anthropic', 'ANTHROPIC_BASE_URL'],
+ ['openai', 'OPENAI_BASE_URL'],
+ ] as const) {
+ const fileUrl = urls[provider];
+ // Env wins: only fold when the env carries no real value.
+ if (fileUrl && fileUrl.trim() && !(out[envKey] && out[envKey]!.trim())) {
+ out[envKey] = fileUrl.trim();
+ }
+ }
+ return out;
+}
+
export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
// The file-plane key fold + env merge live in mergedProviderEnv
// (src/core/ai/provider-env.ts) — the single canonical mapping shared with
@@ -45,6 +84,16 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
if (process.env.LITELLM_BASE_URL) envBaseUrls['litellm'] = process.env.LITELLM_BASE_URL;
if (process.env.OPENROUTER_BASE_URL) envBaseUrls['openrouter'] = process.env.OPENROUTER_BASE_URL;
+ // #3350: native base-URL fold — MUST read the file plane directly, not `c`
+ // (callers can pass a DB-merged config; see foldNativeBaseUrlsFromFilePlane's
+ // mount-safety note). Fail-open: an unreadable config folds nothing.
+ let fileCfg: GBrainConfig | null = null;
+ try {
+ fileCfg = loadConfig();
+ } catch {
+ fileCfg = null;
+ }
+
return {
embedding_model: c.embedding_model,
embedding_dimensions: c.embedding_dimensions,
@@ -55,6 +104,7 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
base_urls: { ...envBaseUrls, ...(c.provider_base_urls ?? {}) }, // config wins over env
provider_chat_options: c.provider_chat_options,
// #1249 empty-string drop + GEMINI alias applied inside mergedProviderEnv.
- env: mergedProviderEnv(c, process.env),
+ // #3350 file-plane native base-URL fold layered on top (env wins).
+ env: foldNativeBaseUrlsFromFilePlane(fileCfg, mergedProviderEnv(c, process.env)),
};
}
diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.ts
new file mode 100644
index 0000000000..d85bba182a
--- /dev/null
+++ b/src/core/ai/chat-usage.ts
@@ -0,0 +1,159 @@
+/**
+ * chat-usage.ts — durable per-call chat usage accounting (#4218, reviving the
+ * #3392 shape).
+ *
+ * gateway.chat() calls `recordChatUsage` at its SUCCESS boundary (both the
+ * production provider path and the test-transport path) with the answering
+ * model + token usage. This module:
+ *
+ * - attributes a best-effort PHASE via AsyncLocalStorage (`withChatPhase`):
+ * the minion worker wraps handler execution in `job:<name>`; direct CLI /
+ * op callers record with phase NULL unless they opt in. Attribution is
+ * advisory — a missing phase never blocks the record.
+ * - prices the call from CANONICAL_PRICING (`estimateChatCostUsd`),
+ * including cache_read/cache_write tokens at the provider's cache rates
+ * when the table carries them (Anthropic), falling back to the input
+ * rate otherwise. Unknown models record cost_usd = NULL (never a fake 0).
+ * - forwards the record to the registered sink FIRE-AND-FORGET. Accounting
+ * is strictly fail-open: a sink error (missing table pre-migration,
+ * closed engine, disk pressure) must never break a chat call.
+ *
+ * Coverage contract (surfaced verbatim by the `get_usage` op): only
+ * gateway.chat() calls are logged. The subagent raw-SDK path, embeddings
+ * (embedding-pricing.ts owns those), and calls made before the sink was
+ * registered or before migration v140 are NOT covered. Failed chat calls are
+ * not logged either — the budget tracker (budget-tracker.ts) remains the
+ * pessimistic in-flight spend gate; this table is the after-the-fact ledger.
+ *
+ * No engine import here (the sink is injected) — this module stays a leaf so
+ * the gateway can import it statically without deepening any cycle.
+ */
+
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { canonicalLookup } from '../model-pricing.ts';
+
+export interface ChatUsageRecord {
+ /** "provider:modelId" of the model that actually answered. */
+ model: string;
+ /** Recipe/provider id when known (e.g. 'anthropic'). */
+ provider: string | null;
+ /** Best-effort attribution, e.g. 'job:embed-backfill'. NULL = direct/unattributed. */
+ phase: string | null;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ cache_write_tokens: number;
+ /** USD, priced from CANONICAL_PRICING. NULL when the model has no pricing. */
+ cost_usd: number | null;
+}
+
+export type ChatUsageSink = (record: ChatUsageRecord) => void | Promise<void>;
+
+const __chatPhaseStore = new AsyncLocalStorage<string>();
+
+/** Run `fn` with every gateway.chat() inside it attributed to `phase`. */
+export function withChatPhase<T>(phase: string, fn: () => T): T {
+ return __chatPhaseStore.run(phase, fn);
+}
+
+export function currentChatPhase(): string | null {
+ return __chatPhaseStore.getStore() ?? null;
+}
+
+let _sink: ChatUsageSink | null = null;
+
+/** Register (or clear, with null) the process-wide usage sink. Last wins. */
+export function setChatUsageSink(sink: ChatUsageSink | null): void {
+ _sink = sink;
+}
+
+/**
+ * Price a chat call in USD from the canonical table. Cache tokens use the
+ * table's cache_read/cache_write rates when present, else the input rate
+ * (documented best-effort — see module doc). Unknown model → null.
+ */
+export function estimateChatCostUsd(
+ model: string,
+ usage: {
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens?: number;
+ cache_write_tokens?: number;
+ },
+): number | null {
+ const p = canonicalLookup(model);
+ if (!p) return null;
+ const cacheRead = usage.cache_read_tokens ?? 0;
+ const cacheWrite = usage.cache_write_tokens ?? 0;
+ return (
+ (usage.input_tokens * p.input +
+ usage.output_tokens * p.output +
+ cacheRead * (p.cache_read ?? p.input) +
+ cacheWrite * (p.cache_write ?? p.input)) /
+ 1_000_000
+ );
+}
+
+/**
+ * Called by gateway.chat() at its success boundary. Never throws; the sink
+ * runs fire-and-forget with errors swallowed.
+ */
+export function recordChatUsage(input: {
+ model: string;
+ provider?: string | null;
+ usage: {
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens?: number;
+ cache_write_tokens?: number;
+ };
+}): void {
+ const sink = _sink;
+ if (!sink) return;
+ try {
+ const record: ChatUsageRecord = {
+ model: input.model,
+ provider: input.provider ?? null,
+ phase: currentChatPhase(),
+ input_tokens: Math.max(0, Math.round(input.usage.input_tokens || 0)),
+ output_tokens: Math.max(0, Math.round(input.usage.output_tokens || 0)),
+ cache_read_tokens: Math.max(0, Math.round(input.usage.cache_read_tokens || 0)),
+ cache_write_tokens: Math.max(0, Math.round(input.usage.cache_write_tokens || 0)),
+ cost_usd: estimateChatCostUsd(input.model, input.usage),
+ };
+ void Promise.resolve(sink(record)).catch(() => {
+ /* fail-open: accounting must never break a chat call */
+ });
+ } catch {
+ /* fail-open */
+ }
+}
+
+/**
+ * Standard sink: INSERT into chat_usage_log via the engine's executeRaw.
+ * Positional parameters only — no JSONB, no string-built SQL. Registered by
+ * the engine factory (last engine created wins; multi-brain processes log
+ * against the most recently created engine — documented best-effort).
+ */
+export function makeEngineChatUsageSink(engine: {
+ executeRaw: (sql: string, params?: unknown[]) => Promise<unknown>;
+}): ChatUsageSink {
+ return async (r: ChatUsageRecord): Promise<void> => {
+ await engine.executeRaw(
+ `INSERT INTO chat_usage_log
+ (model, provider, phase, input_tokens, output_tokens,
+ cache_read_tokens, cache_write_tokens, cost_usd)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ r.model,
+ r.provider,
+ r.phase,
+ r.input_tokens,
+ r.output_tokens,
+ r.cache_read_tokens,
+ r.cache_write_tokens,
+ r.cost_usd,
+ ],
+ );
+ };
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 1ebdd038e3..3f47021dda 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -47,6 +47,7 @@ import type {
TouchpointKind,
} from './types.ts';
import { resolveRecipe, assertTouchpoint, parseModelId, embeddingDimsForModel } from './model-resolver.ts';
+import { recordChatUsage } from './chat-usage.ts';
import {
OPENROUTER_CACHE_HEADER,
openrouterRequiresExplicitPromptCache,
@@ -61,7 +62,7 @@ import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.
import { loadConfig } from '../config.ts';
import type { GBrainConfig } from '../config.ts';
import { mergedProviderEnv } from './provider-env.ts';
-import { buildGatewayConfig } from './build-gateway-config.ts';
+import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';
// ---- Gateway-wide AI-HTTP timeout (v0.42.20.0, #1762/#1775) ----
//
@@ -502,7 +503,12 @@ export function refreshGatewayEnvFromFilePlane(): void {
} catch {
cfg = null;
}
- _config = { ..._config, env: mergedProviderEnv(cfg, process.env) };
+ // #3350: re-apply the file-plane native base-URL fold — without it a worker
+ // refresh would silently drop ANTHROPIC_BASE_URL/OPENAI_BASE_URL that the
+ // boot fold installed from provider_base_urls.{anthropic,openai}. File-plane
+ // only (cfg is loadConfig() here), preserving the mount-safety rule that
+ // DB-plane base_urls never steer native keys.
+ _config = { ..._config, env: foldNativeBaseUrlsFromFilePlane(cfg, mergedProviderEnv(cfg, process.env)) };
_modelCache.clear();
}
@@ -1657,6 +1663,22 @@ function instantiateEmbedding(recipe: Recipe, modelId: string, cfg: AIGatewayCon
/** Minimum sub-batch size before we give up splitting and just throw. */
const MIN_SUB_BATCH = 1;
+/**
+ * #3875: default per-call item cap for `no_batch_cap` recipes (Ollama,
+ * LiteLLM proxy). These recipes declare no static token/item cap because the
+ * backend's capacity is user-launched — but the per-SDK-call
+ * AI_EMBED_TIMEOUT_MS (60s default) then bounded a whole FILE's chunks in one
+ * request. A slow local model (CPU Ollama) embedding a large file timed out
+ * deterministically and every retry re-sent the same oversized batch. Capping
+ * items per sub-batch makes the 60s timeout a per-BATCH budget: 16 chunks per
+ * call finishes comfortably even on CPU-bound local models, and a genuinely
+ * wedged provider still surfaces the timeout loudly on the first sub-batch.
+ * An explicit `max_batch_items` on the recipe always wins over this default.
+ *
+ * @internal exported for tests; not part of the public gateway API.
+ */
+export const NO_BATCH_CAP_SUB_BATCH_ITEMS = 16;
+
/**
* Embed many texts. Truncates to MAX_CHARS, then dispatches based on whether
* the recipe declares a per-batch token budget.
@@ -1803,7 +1825,18 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
// Hard COUNT cap (e.g. llama-server's "maximum allowed batch size 32").
// Token budget can't bound item count, so re-split any oversized batch.
- const maxBatchItems = embedding?.max_batch_items;
+ //
+ // #3875: recipes that declare `no_batch_cap` (Ollama, LiteLLM proxy) have
+ // NO static token cap AND no item cap, so a large file used to ride to the
+ // provider as ONE request — and the 60s AI_EMBED_TIMEOUT_MS (per SDK call)
+ // became a per-FILE budget. A slow local model embedding hundreds of chunks
+ // hit the timeout deterministically, and no amount of retrying could ever
+ // succeed. Default those recipes to a conservative item cap so the per-call
+ // timeout bounds a fixed amount of work; an explicit max_batch_items still
+ // wins.
+ const maxBatchItems =
+ embedding?.max_batch_items ??
+ (embedding?.no_batch_cap === true ? NO_BATCH_CAP_SUB_BATCH_ITEMS : undefined);
const batches = maxBatchItems
? tokenBatches.flatMap(b => capBatchItems(b, maxBatchItems))
: tokenBatches;
@@ -3562,6 +3595,18 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
let threw: unknown = null;
try {
res = await _chatTransport(opts);
+ // #4218 success boundary (test-transport lane): same accounting call as
+ // the production path below so transport-driven tests exercise it.
+ recordChatUsage({
+ model: res.model ?? modelStrEarly,
+ provider: res.providerId ?? null,
+ usage: {
+ input_tokens: res.usage.input_tokens,
+ output_tokens: res.usage.output_tokens,
+ cache_read_tokens: res.usage.cache_read_tokens,
+ cache_write_tokens: res.usage.cache_creation_tokens,
+ },
+ });
return res;
} catch (err) {
threw = err;
@@ -3775,19 +3820,27 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
const { inputTokens: inTok, outputTokens: outTok } = normalizeSdkUsage(usage);
_recordBudget(`${recipe.id}:${modelId}`, inTok, outTok);
+ const usageOut = {
+ input_tokens: inTok,
+ output_tokens: outTok,
+ // `usage.cachedInputTokens` is the AI SDK's provider-neutral cache-read
+ // count — it's how OpenAI-compatible routes (OpenRouter's
+ // prompt_tokens_details.cached_tokens) surface cache hits.
+ cache_read_tokens: Number(anthropicCache.cacheReadInputTokens ?? anthropicCache.cache_read_input_tokens ?? usage.cachedInputTokens ?? 0),
+ cache_creation_tokens: Number(anthropicCache.cacheCreationInputTokens ?? anthropicCache.cache_creation_input_tokens ?? 0),
+ };
+ // #4218 success boundary: durable usage ledger (fire-and-forget, fail-open).
+ recordChatUsage({
+ model: `${recipe.id}:${modelId}`,
+ provider: recipe.id,
+ usage: { ...usageOut, cache_write_tokens: usageOut.cache_creation_tokens },
+ });
+
return {
text: blocks.filter(b => b.type === 'text').map(b => (b as { type: 'text'; text: string }).text).join(''),
blocks,
stopReason: mapStopReason((result as any).finishReason, providerMetadata),
- usage: {
- input_tokens: inTok,
- output_tokens: outTok,
- // `usage.cachedInputTokens` is the AI SDK's provider-neutral cache-read
- // count — it's how OpenAI-compatible routes (OpenRouter's
- // prompt_tokens_details.cached_tokens) surface cache hits.
- cache_read_tokens: Number(anthropicCache.cacheReadInputTokens ?? anthropicCache.cache_read_input_tokens ?? usage.cachedInputTokens ?? 0),
- cache_creation_tokens: Number(anthropicCache.cacheCreationInputTokens ?? anthropicCache.cache_creation_input_tokens ?? 0),
- },
+ usage: usageOut,
model: `${recipe.id}:${modelId}`,
providerId: recipe.id,
providerMetadata,
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index bd5a20d0c0..540b779d9a 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -26,7 +26,9 @@
* the only way to skip it is `--bare`, which forces ANTHROPIC_API_KEY
* auth and defeats the whole point of this provider. The ~42k cached
* tokens from user-level instructions are accepted as a cost-trivial
- * trade-off on the subscription path.
+ * trade-off on the subscription path. #4119: when those user-level
+ * instructions must NOT leak into a measurement (SkillOpt rollouts),
+ * set GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG — see resolveHermeticConfigDir.
*
* doStream is not yet implemented; the model declares no streaming. Callers
* (gateway.toolLoop primarily) use doGenerate.
@@ -59,6 +61,38 @@ function ensureCleanCwd(): string {
return CLAUDE_CWD;
}
+// #4119 — opt-in hermetic config dir for the child. See resolveHermeticConfigDir.
+const CLAUDE_HERMETIC_CONFIG = join(tmpdir(), `gbrain-claude-cli-config-${process.pid}`);
+let hermeticEnsured = false;
+/**
+ * Resolve the CLAUDE_CONFIG_DIR the child should run with when
+ * GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG is set (#4119). Returns null when the
+ * knob is unset/off — the child then inherits the user's real config dir
+ * (today's behavior). `1`/`true` → a per-process empty tmpdir; any other
+ * non-empty value is used verbatim as the config-dir path.
+ *
+ * Opt-in, NOT default: on non-macOS installs the config dir also holds the
+ * OAuth session credentials, so pointing the child at an empty dir logs it
+ * out (macOS keeps credentials in the keychain and survives). SkillOpt runs
+ * that need hermetic measurements (no user-level CLAUDE.md / settings.json /
+ * hooks bleeding into rollouts) flip it deliberately — see
+ * docs/guides/skillopt.md, "Hermetic claude-cli rollouts".
+ */
+export function resolveHermeticConfigDir(
+ raw: string | undefined = process.env.GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG,
+): string | null {
+ const v = raw?.trim();
+ if (!v || v === '0' || v.toLowerCase() === 'false') return null;
+ if (v === '1' || v.toLowerCase() === 'true') {
+ if (!hermeticEnsured) {
+ mkdirSync(CLAUDE_HERMETIC_CONFIG, { recursive: true });
+ hermeticEnsured = true;
+ }
+ return CLAUDE_HERMETIC_CONFIG;
+ }
+ return v;
+}
+
/** Parsed shape of `claude --print --output-format json`. */
interface ClaudeJsonResult {
type: 'result';
@@ -311,6 +345,12 @@ function runClaude(
for (const k of Object.keys(env)) {
if (k.startsWith('CLAUDE_CODE_USE_')) delete env[k];
}
+ // #4119 opt-in hermetic config: point the child's CLAUDE_CONFIG_DIR at an
+ // isolated directory so user-level ~/.claude state (CLAUDE.md memory,
+ // settings.json, hooks) can't leak into measurements. Off by default —
+ // see resolveHermeticConfigDir for the auth caveat that makes it opt-in.
+ const hermeticConfigDir = resolveHermeticConfigDir();
+ if (hermeticConfigDir) env.CLAUDE_CONFIG_DIR = hermeticConfigDir;
const child = spawn(claudeBin(), args, {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: ensureCleanCwd(),
diff --git a/src/core/audit-slug-fallback.ts b/src/core/audit-slug-fallback.ts
index 829c07ffcb..95814e5a93 100644
--- a/src/core/audit-slug-fallback.ts
+++ b/src/core/audit-slug-fallback.ts
@@ -58,11 +58,15 @@ const writer = createAuditWriter<SlugFallbackAuditEvent>({
* logging). Write failure to the JSONL is logged but does NOT throw — the
* import succeeds either way.
*/
-export function logSlugFallback(slug: string, sourcePath: string): void {
+export function logSlugFallback(
+ slug: string,
+ sourcePath: string,
+ reason: 'path slugified empty' | 'normalization-equivalent identity restore' = 'path slugified empty',
+): void {
// D7 dual logging — every fallback gets an operator-visible stderr line
// regardless of audit write success. Lives in this caller, not in the
// shared writer, because only this audit module wants per-call stderr.
- process.stderr.write(`[gbrain] slug fallback: ${sourcePath} → ${slug} (frontmatter slug; path slugified empty)\n`);
+ process.stderr.write(`[gbrain] slug fallback: ${sourcePath} → ${slug} (frontmatter slug; ${reason})\n`);
writer.log({
slug,
source_path: sourcePath,
diff --git a/src/core/autopilot-lock.ts b/src/core/autopilot-lock.ts
index ab5268277e..38474fd6bc 100644
--- a/src/core/autopilot-lock.ts
+++ b/src/core/autopilot-lock.ts
@@ -1,4 +1,5 @@
import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
export type AutopilotLockHolder =
| { state: 'dead' }
@@ -22,8 +23,27 @@ export function isPidAlive(pid: number): boolean {
}
}
-export function readProcessCommand(pid: number): string | null {
+export interface ProcessCommandProbeDeps {
+ /** Injected for tests; defaults to fs.readFileSync of /proc/<pid>/cmdline. */
+ readCmdlineFile?: (path: string) => Buffer | string;
+}
+
+/**
+ * Best-effort process command lookup. On Linux, /proc/<pid>/cmdline is read
+ * first (no subprocess, works even when `ps` is unavailable or restricted —
+ * e.g. minimal containers), falling back to `ps -o args=` elsewhere (#4300).
+ */
+export function readProcessCommand(pid: number, deps: ProcessCommandProbeDeps = {}): string | null {
if (!Number.isFinite(pid) || pid <= 0) return null;
+ const readCmdline = deps.readCmdlineFile ?? readFileSync;
+ try {
+ const raw = readCmdline(`/proc/${pid}/cmdline`);
+ // argv is NUL-separated with a trailing NUL; normalize to a space-joined line.
+ const cmd = raw.toString().split('\0').filter((part) => part.length > 0).join(' ').trim();
+ if (cmd.length > 0) return cmd;
+ } catch {
+ // Not Linux (no /proc) or unreadable — fall through to ps.
+ }
try {
const out = execFileSync('ps', ['-p', String(pid), '-o', 'args='], {
encoding: 'utf8',
diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.ts
index f1bba6b726..55ee85c597 100644
--- a/src/core/bootstrap/harness.ts
+++ b/src/core/bootstrap/harness.ts
@@ -95,6 +95,7 @@ import {
opencodeConfigDir,
opencodeGlobalConfigPath,
type ClaudeHookEvent,
+ claudeConfigDir,
} from './host-specs.ts';
import {
opencodeEntryKind,
@@ -282,7 +283,12 @@ function resolveDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>
mint: deps.mint ?? defaultMint,
revokeById: deps.revokeById ?? defaultRevokeById,
pgliteLiveServe: deps.pgliteLiveServe ?? defaultPgliteLiveServe,
- detectClaude: deps.detectClaude ?? (() => whichSafe('claude') !== null),
+ // #4325: config-dir fallback mirrors detectCodex/detectOpencode below —
+ // CI runners and alias-only shells don't expose a `claude` binary on the
+ // probing process's PATH even when Claude Code is configured.
+ detectClaude:
+ deps.detectClaude ??
+ (() => whichSafe('claude') !== null || existsSync(claudeConfigDir())),
detectCodex:
deps.detectCodex ??
(() => whichSafe('codex') !== null || existsSync(deps.codexConfig ?? codexConfigPath())),
@@ -297,7 +303,10 @@ function resolveDeps(deps: HarnessDeps): Required<Omit<HarnessDeps, 'gbrainBin'>
function whichSafe(bin: string): string | null {
try {
- return Bun.which(bin);
+ // #4325: pass PATH explicitly — Bun.which's default lookup snapshots the
+ // process-start PATH and ignores runtime process.env.PATH mutations, so
+ // env-remapped test lanes (withEnv) could never sandbox detection.
+ return process.env.PATH ? Bun.which(bin, { PATH: process.env.PATH }) : Bun.which(bin);
} catch {
return null;
}
@@ -1331,9 +1340,10 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P
// 11. Degradation + skew honesty.
if (health.engine === 'postgres') {
d.log(
- '\nNote: this brain runs on Postgres — per-turn hook injection is degraded (no_pglite_path: the hook IPC ' +
- 'socket is PGLite-only today). MCP tools are the active seam: sessions search/read/write the brain on ' +
- 'demand; the hooks are pre-wired and light up when the engine-uniform listener lands (tracked in TODOS.md).',
+ '\nNote: this brain runs on Postgres — per-turn hook injection needs a running `gbrain serve` for this ' +
+ 'brain (hooks heartbeat no_pglite_path/no_serve until one is up; the engine-uniform IPC listener keys its ' +
+ 'socket off the connection URL under ~/.gbrain/run). MCP tools are the active seam: sessions ' +
+ 'search/read/write the brain on demand; the pre-wired hooks light up whenever a serve runs.',
);
}
if (health.version && flags.token === undefined && isServeOlderThanScopes(health.version)) {
@@ -1739,7 +1749,7 @@ export async function statusHarness(flags: HarnessFlags, rawDeps: HarnessDeps):
d.log(` pending: ${receipt.token.previous_ids.length} previous token(s) await revocation (re-run to converge): ${receipt.token.previous_ids.join(', ')}`);
}
if (degraded) {
- d.log('per-turn injection: degraded on Postgres (MCP tools are the active seam).');
+ d.log('per-turn injection: needs a running gbrain serve on Postgres (MCP tools are the active seam).');
}
if (skew) d.log(`note: ${skew}`);
}
diff --git a/src/core/bootstrap/host-specs.ts b/src/core/bootstrap/host-specs.ts
index f79b42c052..46520a553a 100644
--- a/src/core/bootstrap/host-specs.ts
+++ b/src/core/bootstrap/host-specs.ts
@@ -260,6 +260,16 @@ export function claudeUserSettingsPath(): string {
return join(claudeConfigBase(), 'settings.json');
}
+/**
+ * #4325: the config-dir base itself, exported for detection — a machine with
+ * a `~/.claude` (or CLAUDE_CONFIG_DIR) directory has Claude Code configured
+ * even when the `claude` binary isn't on the probing process's PATH (CI
+ * runners, alias-only shells). Mirrors detectCodex's config-file fallback.
+ */
+export function claudeConfigDir(): string {
+ return claudeConfigBase();
+}
+
/** permissions.allow entry that pre-approves an MCP server's tools for headless runs. */
export function mcpPermissionEntry(serverName: string): string {
return `mcp__${serverName}`;
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index e9b0ca5a32..002e49fd48 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -949,7 +949,15 @@ function commitScaffolding(repoPath: string, branch: string, redact: (s: string)
stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV },
}).toString().trim();
if (!staged) return { status: 'ok', detail: 'scaffolding already committed' };
- execFileSync('git', ['-C', repoPath, 'commit', '-m', 'chore(gbrain): install brain durability scaffolding'], {
+ // #3925: suppress hooks on THIS commit. Step 3 already installed the
+ // local post-commit hook, so a plain `git commit` here detaches a
+ // background brain_push that races the explicit fail-loud push below on
+ // the same ref (cannot-lock-ref on origin; the loser's `pull --rebase`
+ // retry then takes .git/index.lock — flock is absent on macOS, so the
+ // hook can't serialize against us). core.hooksPath=/dev/null makes the
+ // push below the ONLY push for the scaffolding commit; every later
+ // operator/agent commit still fires the hook normally.
+ execFileSync('git', ['-C', repoPath, '-c', 'core.hooksPath=/dev/null', 'commit', '-m', 'chore(gbrain): install brain durability scaffolding'], {
stdio: 'ignore', timeout: 30_000, env: { ...process.env, ...GIT_ENV },
});
execFileSync('git', ['-C', repoPath, ...['-c', 'http.followRedirects=false'], 'push', 'origin', `HEAD:${branch}`], {
diff --git a/src/core/brain-score-recommendations.ts b/src/core/brain-score-recommendations.ts
index 8240640729..e7b5e15241 100644
--- a/src/core/brain-score-recommendations.ts
+++ b/src/core/brain-score-recommendations.ts
@@ -55,6 +55,23 @@ export const HOSTED_EMBED_KEY_CONFIG: Record<string, string> = {
* Uses the recipe registry (pure data), not the gateway runtime, so this
* module stays free of AI-SDK coupling and works before engine.connect().
*/
+/**
+ * #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.
+ */
+export function chatApiKeyConfigured(
+ fileCfg: { anthropic_api_key?: unknown } | null | undefined,
+): boolean {
+ return !!(process.env.ANTHROPIC_API_KEY || fileCfg?.anthropic_api_key);
+}
+
export function embeddingProviderConfigured(
embeddingModel: string | undefined,
resolveKey: (envVar: string) => boolean,
@@ -303,7 +320,10 @@ export function computeRecommendations(
// and noExtract:true after T5 lands → extract job is the materializer).
// ---------------------------------------------------------------------
if (ctx.repoPath && health.stale_pages > 0) {
- const params = { mode: 'all', dir: ctx.repoPath };
+ // #3957: carry the source id so the extract job's fs-walk rows land in
+ // (and its watermark stamp targets) the brain source that owns repoPath —
+ // not the 'default' fallback that silently no-ops on federated brains.
+ const params = { mode: 'all', dir: ctx.repoPath, ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}) };
out.push({
id: 'extract.all',
job: 'extract',
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index 1d963dbbcc..3819b10396 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -312,7 +312,11 @@ export function autoFixFrontmatter(
// the slug field is present and mismatched.
const re = /^slug:\s*(.+?)\s*$/m;
const m = working.match(re);
- if (m && m[1].replace(/^["']|["']$/g, '') !== expectedSlug) {
+ // #3772: keep a normalization-equivalent slug (its slugified spelling IS
+ // the path-derived slug) — export stamps these to preserve legacy page
+ // identities, and stripping it here would re-key the page on next import.
+ const declaredSlug = m ? m[1].replace(/^["']|["']$/g, '') : '';
+ if (m && declaredSlug !== expectedSlug && slugifyPath(declaredSlug) !== expectedSlug) {
working = working.replace(re, '').replace(/\n{3,}/g, '\n\n');
fixes.push({
code: 'SLUG_MISMATCH',
@@ -756,7 +760,16 @@ async function listSources(engine: BrainEngine, sourceId?: string): Promise<Sour
);
return rows;
}
- return engine.executeRaw<SourceRow>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL ORDER BY id`,
- );
+ // #3880: archived sources are excluded from automatic all-source scanning.
+ // The archived column is v34+ — fall back on older brains (house style per
+ // pickSoleNonDefaultSource).
+ try {
+ return await engine.executeRaw<SourceRow>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE ORDER BY id`,
+ );
+ } catch {
+ return engine.executeRaw<SourceRow>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL ORDER BY id`,
+ );
+ }
}
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 5729eea5fb..b020d36c43 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -78,6 +78,85 @@ export interface BudgetTrackerOpts {
label: string;
/** Override the audit file path (tests + custom installers). */
auditPath?: string;
+ /**
+ * #4312 — operator config-plane price overrides (`pricing.overrides`),
+ * normalized via parsePricingOverrides. Consulted BEFORE the shipped
+ * pricing tables in every cost computation, so an operator routing through
+ * a proxy (LiteLLM fronting a paid provider — chat AND embed) can declare
+ * their real rate instead of TX2 no_pricing hard-failing under --max-cost.
+ * Models with neither a table row nor an override stay fail-closed.
+ */
+ pricingOverrides?: PricingOverrides;
+}
+
+/**
+ * #4312 — normalized operator price overrides: model string (lowercased) →
+ * per-1M-token pricing. Declared in the config plane as JSON, e.g.
+ * gbrain config set pricing.overrides '{"litellm:gpt-4o": {"input": 2.5, "output": 10}, "litellm:text-embedding-3-large": 0.13}'
+ * A bare number means one rate for input AND output tokens (embeddings only
+ * ever bill input, so a scalar is the natural spelling there).
+ */
+export type PricingOverrides = Record<string, ModelPricing>;
+
+/**
+ * Parse the raw `pricing.overrides` config value (JSON string or object) into
+ * a normalized PricingOverrides map. Invalid entries are DROPPED (the model
+ * stays unpriced → the TX2 fail-closed contract still applies to it); a
+ * wholly-unparseable value yields undefined. Never throws.
+ */
+export function parsePricingOverrides(raw: unknown): PricingOverrides | undefined {
+ let value: unknown = raw;
+ if (value == null) return undefined;
+ if (typeof value === 'string') {
+ const s = value.trim();
+ if (!s) return undefined;
+ try {
+ value = JSON.parse(s);
+ } catch {
+ return undefined;
+ }
+ }
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
+ const isRate = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0;
+ const out: PricingOverrides = {};
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ const key = k.trim().toLowerCase();
+ if (!key) continue;
+ if (isRate(v)) {
+ out[key] = { input: v, output: v };
+ continue;
+ }
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
+ const obj = v as { input?: unknown; output?: unknown; pricePerMTok?: unknown };
+ const input = obj.input ?? obj.pricePerMTok;
+ if (isRate(input) && (obj.output === undefined || isRate(obj.output))) {
+ out[key] = { input, output: (obj.output as number | undefined) ?? input };
+ }
+ }
+ }
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+/**
+ * Load + parse operator price overrides from the DB config plane
+ * (`pricing.overrides`). Fail-open to undefined — a config read failure must
+ * never block a run; the affected models simply keep the fail-closed
+ * no-pricing behavior.
+ */
+export async function loadPricingOverrides(
+ engine: { getConfig(key: string): Promise<string | null> },
+): Promise<PricingOverrides | undefined> {
+ try {
+ return parsePricingOverrides(await engine.getConfig('pricing.overrides'));
+ } catch {
+ return undefined;
+ }
+}
+
+/** Exact-key override lookup (keys normalized to lowercase at parse time). */
+function overrideFor(modelId: string, overrides?: PricingOverrides): ModelPricing | null {
+ if (!overrides) return null;
+ return overrides[modelId.trim().toLowerCase()] ?? null;
}
export class BudgetExhausted extends Error {
@@ -259,12 +338,21 @@ function lookupPricing(modelId: string, kind: BudgetKind): ModelPricing | null {
* `reserve()` hard-fails with BudgetExhausted(reason:'no_pricing') and the
* caller silently does no work.
*/
-export function isModelPriceable(modelId: string, kind: BudgetKind): boolean {
- return lookupPricing(modelId, kind) !== null;
+export function isModelPriceable(modelId: string, kind: BudgetKind, overrides?: PricingOverrides): boolean {
+ return overrideFor(modelId, overrides) !== null || lookupPricing(modelId, kind) !== null;
}
-function costForUsage(modelId: string, inputTokens: number, outputTokens: number, kind: BudgetKind): number | null {
- const p = lookupPricing(modelId, kind);
+function costForUsage(
+ modelId: string,
+ inputTokens: number,
+ outputTokens: number,
+ kind: BudgetKind,
+ overrides?: PricingOverrides,
+): number | null {
+ // #4312: operator overrides win — the operator owns their bill (negotiated
+ // rates, proxy routes the shipped tables can't know about). Missing both →
+ // null, and the TX2 fail-closed contract in reserve() still applies.
+ const p = overrideFor(modelId, overrides) ?? lookupPricing(modelId, kind);
if (!p) return null;
return (inputTokens / 1_000_000) * p.input + (outputTokens / 1_000_000) * p.output;
}
@@ -326,6 +414,7 @@ export class BudgetTracker {
estimate.estimatedInputTokens,
estimate.maxOutputTokens,
estimate.kind,
+ this.opts.pricingOverrides,
);
if (projected === null) {
@@ -335,7 +424,9 @@ export class BudgetTracker {
// void the contract.
const pricingFile = estimate.kind === 'chat' ? 'model-pricing.ts' : 'embedding-pricing.ts';
const msg = `${this.opts.label}: no pricing entry for model "${estimate.modelId}" (kind=${estimate.kind}). ` +
- `Add it to src/core/${pricingFile} or drop --max-cost.`;
+ `Add it to src/core/${pricingFile}, declare an operator rate via ` +
+ `\`gbrain config set pricing.overrides '{"${estimate.modelId}": <usd-per-1M-tokens>}'\` (#4312), ` +
+ `or drop --max-cost.`;
appendAuditLine(this.auditPath, {
schema_version: 1,
ts: new Date().toISOString(),
@@ -431,7 +522,13 @@ export class BudgetTracker {
record(actual: BudgetActualUsage & { kind?: BudgetKind }): void {
this.callsRecorded++;
const kind: BudgetKind = actual.kind ?? 'chat';
- const cost = costForUsage(actual.modelId, actual.inputTokens, actual.outputTokens ?? 0, kind);
+ const cost = costForUsage(
+ actual.modelId,
+ actual.inputTokens,
+ actual.outputTokens ?? 0,
+ kind,
+ this.opts.pricingOverrides,
+ );
if (cost === null) {
// Unpriced model: record audit but skip cumulative math. Cap (if set)
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 31eff4462e..2fa428cb21 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -30,6 +30,9 @@ import type { BrainEngine } from './engine.ts';
import { isUndefinedTableError } from './utils.ts';
import { CJK_SLUG_CHARS } from './cjk.ts';
import { stripCodeBlocks } from './link-extraction.ts';
+// #4222: shared generic-token reject list — same list gates enrichEntity
+// minting and drives the junk_entity_hubs doctor check.
+import { isGenericEntityToken } from './entity-name-quality.ts';
/** D2: hardcoded entity types for v1. Pack-aware extension is TODO-1. */
export const LINKABLE_ENTITY_TYPES = ['person', 'company', 'organization', 'entity'] as const;
@@ -372,8 +375,8 @@ export async function buildGazetteer(
opts: BuildGazetteerOpts = {},
): Promise<Gazetteer> {
const typeList = LINKABLE_ENTITY_TYPES.map(t => `'${t}'`).join(', ');
- const rows = await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null }>(
- `SELECT slug, source_id, title
+ const rows = await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null }>(
+ `SELECT slug, source_id, title, type
FROM pages
WHERE type IN (${typeList})
AND deleted_at IS NULL`,
@@ -404,6 +407,15 @@ export async function buildGazetteer(
const tokens = tokenizeTitle(row.title);
if (tokens.length === 0) continue;
if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;
+ // #4222: a single-generic-token PERSON title ("Will", "Chief") is a
+ // junk-hub magnet — every prose occurrence of the word would accrete
+ // another mention edge onto a near-empty page. Dropped from the
+ // gazetteer even though the page exists (unlike the CK12 ignore-list
+ // rule above, which trusts user-created pages: these titles are
+ // overwhelmingly extractor-minted, and the page itself stays intact —
+ // only the auto-link accretion stops). Multi-token titles ("Will
+ // Smith") and non-person types are unaffected.
+ if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) continue;
const entry: GazetteerEntry = {
slug: row.slug,
@@ -600,3 +612,177 @@ export function findMentionedEntities(
return out;
}
+
+// ============================================================
+// Stale-mention detection (read-only)
+// ============================================================
+
+/** One `link_source='mentions'` row the current gazetteer no longer produces. */
+export interface StaleMention {
+ from: string;
+ to: string;
+ /** `link_kind` as stored; NULL rows (legacy / pre-v98) report as 'plain'. */
+ kind: string;
+}
+
+export interface StaleMentionsScan {
+ /** Live pages carrying at least one `link_source='mentions'` row. */
+ totalPagesWithMentions: number;
+ /** Pages actually re-scanned (bounded by `opts.limit`). */
+ pagesScanned: number;
+ /** `mentions` rows on the scanned pages. */
+ linksScanned: number;
+ /** Of those, rows whose target the current gazetteer no longer produces. */
+ staleLinks: number;
+ /** Stale counts split by `link_kind` — `typed_ner` rows come from extract-ner. */
+ staleByKind: Record<string, number>;
+ /** True when the brain has NO linkable entity pages at all. */
+ emptyGazetteer: boolean;
+ /** First few stale rows, for an operator-facing message. */
+ examples: StaleMention[];
+}
+
+const STALE_MENTIONS_DEFAULT_LIMIT = 500;
+const STALE_MENTIONS_MAX_EXAMPLES = 5;
+
+/**
+ * Re-derive what `extract links --by-mention` would produce today and report
+ * `link_source='mentions'` rows that no longer follow from the current
+ * gazetteer + page bodies.
+ *
+ * STRICTLY READ-ONLY. This deletes nothing and writes nothing; it exists so
+ * the drift is visible, because the scan's write path (`addLinksBatch`) is
+ * purely additive. Re-running the scan adds today's correct links ALONGSIDE
+ * rows left by an older gazetteer, an older tokenizer, or a body that has
+ * since stopped mentioning the entity — nothing ever removes those.
+ *
+ * A row is counted stale when the current scan does not produce its
+ * (source_id, slug) target from the page's body. That test is deliberately
+ * target-based rather than kind-based, so it covers `link_kind='typed_ner'`
+ * rows too: extract-ner derives those from the same mention set, so a target
+ * this scan no longer yields cannot have a live verb-typed edge either. The
+ * converse does NOT hold — a still-produced target says nothing about
+ * whether the stored verb is still right — so `typed_ner` counts are
+ * reported separately rather than folded into one number.
+ *
+ * Bounded by `limit` (default 500) in slug order for determinism. The
+ * returned `totalPagesWithMentions` is the unbounded figure so callers can
+ * say what was and was not covered instead of implying full coverage.
+ */
+export async function scanStaleMentions(
+ engine: BrainEngine,
+ opts: { limit?: number } = {},
+): Promise<StaleMentionsScan> {
+ const limit = opts.limit ?? STALE_MENTIONS_DEFAULT_LIMIT;
+
+ const totalRow = await engine.executeRaw<{ count: number }>(
+ `SELECT COUNT(DISTINCT l.from_page_id)::int AS count
+ FROM links l
+ JOIN pages p ON p.id = l.from_page_id
+ WHERE l.link_source = 'mentions'
+ AND p.deleted_at IS NULL`,
+ [],
+ );
+ const totalPagesWithMentions = totalRow[0]?.count ?? 0;
+
+ const empty: StaleMentionsScan = {
+ totalPagesWithMentions,
+ pagesScanned: 0,
+ linksScanned: 0,
+ staleLinks: 0,
+ staleByKind: {},
+ emptyGazetteer: false,
+ examples: [],
+ };
+ if (totalPagesWithMentions === 0) return empty;
+
+ const gazetteer = await buildGazetteer(engine);
+
+ // Same bounded page set for both queries so the link rows and the bodies
+ // can never describe different pages.
+ const scannedCte =
+ `WITH scanned AS (
+ SELECT p.id
+ FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND EXISTS (
+ SELECT 1 FROM links l
+ WHERE l.from_page_id = p.id AND l.link_source = 'mentions'
+ )
+ ORDER BY p.slug
+ LIMIT $1
+ )`;
+
+ const bodies = await engine.executeRaw<{
+ id: number; slug: string; source_id: string | null; body: string;
+ }>(
+ `${scannedCte}
+ SELECT p.id, p.slug, p.source_id,
+ COALESCE(p.compiled_truth, '') || E'\n\n' || COALESCE(p.timeline, '') AS body
+ FROM pages p
+ JOIN scanned s ON s.id = p.id
+ ORDER BY p.slug`,
+ [limit],
+ );
+
+ const rows = await engine.executeRaw<{
+ from_id: number; from_slug: string; to_slug: string;
+ to_source_id: string | null; link_kind: string | null;
+ }>(
+ `${scannedCte}
+ SELECT l.from_page_id AS from_id, f.slug AS from_slug,
+ t.slug AS to_slug, t.source_id AS to_source_id, l.link_kind
+ FROM links l
+ JOIN scanned s ON s.id = l.from_page_id
+ JOIN pages f ON f.id = l.from_page_id
+ JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_source = 'mentions'
+ ORDER BY f.slug, t.slug`,
+ [limit],
+ );
+
+ const byPage = new Map<number, typeof rows>();
+ for (const r of rows) {
+ const bucket = byPage.get(r.from_id);
+ if (bucket) bucket.push(r);
+ else byPage.set(r.from_id, [r]);
+ }
+
+ const staleByKind: Record<string, number> = {};
+ const examples: StaleMention[] = [];
+ let staleLinks = 0;
+
+ for (const page of bodies) {
+ const stored = byPage.get(page.id);
+ if (!stored || stored.length === 0) continue;
+
+ const fromSourceId = page.source_id ?? 'default';
+ const produced = new Set(
+ findMentionedEntities(page.body, gazetteer, {
+ fromSlug: page.slug,
+ fromSourceId,
+ }).map(m => `${m.source_id}::${m.slug}`),
+ );
+
+ for (const row of stored) {
+ const key = `${row.to_source_id ?? 'default'}::${row.to_slug}`;
+ if (produced.has(key)) continue;
+ staleLinks++;
+ const kind = row.link_kind ?? 'plain';
+ staleByKind[kind] = (staleByKind[kind] ?? 0) + 1;
+ if (examples.length < STALE_MENTIONS_MAX_EXAMPLES) {
+ examples.push({ from: page.slug, to: row.to_slug, kind });
+ }
+ }
+ }
+
+ return {
+ totalPagesWithMentions,
+ pagesScanned: bodies.length,
+ linksScanned: rows.length,
+ staleLinks,
+ staleByKind,
+ emptyGazetteer: gazetteer.size === 0,
+ examples,
+ };
+}
diff --git a/src/core/calibration/nudge.ts b/src/core/calibration/nudge.ts
index 6fb0c5bfe9..ae56a3f450 100644
--- a/src/core/calibration/nudge.ts
+++ b/src/core/calibration/nudge.ts
@@ -16,8 +16,10 @@
* - take_nudge_log records every fire keyed on (take_id|proposal_id,
* nudge_pattern). The cooldown probe checks "was this same pattern fired
* on this same take in the last NUDGE_COOLDOWN_DAYS?" If yes, silently skip.
- * - Reset via `gbrain takes nudge --reset <take_id>` clears the cooldown
- * for that take so the next sync re-fires fresh nudges.
+ * - No CLI reset shim exists (#3697: an earlier draft named
+ * `gbrain takes nudge --reset`, which never shipped). Deleting the
+ * take's take_nudge_log rows clears the cooldown so the next sync
+ * re-fires fresh nudges.
*
* Output channel:
* v0.36.1.0 ship state: STDERR only. Multi-channel routing (webhook,
diff --git a/src/core/calibration/templates.ts b/src/core/calibration/templates.ts
index 5a4783aa3e..0fe0545e63 100644
--- a/src/core/calibration/templates.ts
+++ b/src/core/calibration/templates.ts
@@ -78,10 +78,15 @@ export function patternStatementTemplate(s: PatternStatementSlots): string {
/** E7 nudge template — stderr line on sync after a take is committed. */
export function nudgeTemplate(s: NudgeSlots): string {
+ // #3697: this used to advertise `gbrain takes nudge --hush <pattern>`, a
+ // subcommand that does not exist. The 14-day quiet period is automatic —
+ // fireNudge logs to take_nudge_log and the cooldown probe suppresses
+ // repeats per (take_id, pattern) — so say that instead of naming a
+ // command that exits "Unknown subcommand".
return (
`[gbrain] You just committed a ${s.domain} take at conviction ${s.conviction.toFixed(2)}. ` +
`Recent record on similar calls: ${s.nRecentMisses} of ${s.nRecentTotal} missed. ` +
- `Hush this pattern for 14 days: gbrain takes nudge --hush ${s.hushPattern}`
+ `This nudge auto-quiets for pattern '${s.hushPattern}' for 14 days.`
);
}
diff --git a/src/core/calibration/think-ab.ts b/src/core/calibration/think-ab.ts
index d5efdb07c0..efff353ac9 100644
--- a/src/core/calibration/think-ab.ts
+++ b/src/core/calibration/think-ab.ts
@@ -149,7 +149,10 @@ export function formatAbReport(report: AbReportResult, days: number): string {
lines.push(`A/B report (last ${days} days):`);
lines.push(` Total trials: ${report.total_trials}`);
if (report.total_trials === 0) {
- lines.push(' No data yet. Try: gbrain think --ab "<question>"');
+ // #3697: this used to suggest `gbrain think --ab`, a flag `think` never
+ // parses (the CLI trial-runner wiring never shipped; runAbTrial is
+ // API-only). Don't send the user to a silently-misparsed command.
+ lines.push(' No data yet. (A/B trials are recorded via the runAbTrial harness; a CLI trial-runner has not shipped.)');
return lines.join('\n');
}
lines.push(` Baseline wins: ${report.baseline_wins}`);
diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.ts
index a1324118d9..e430b0ef17 100644
--- a/src/core/chronicle/extract-events.ts
+++ b/src/core/chronicle/extract-events.ts
@@ -35,7 +35,7 @@ export interface ChronicleJudgeResult {
* the JSON array was cut mid-stream and must not be parsed as complete.
* - 'parse_failed': the model returned text but no valid JSON array.
*/
- failure?: 'truncated' | 'parse_failed';
+ failure?: 'truncated' | 'parse_failed' | 'llm_unavailable';
}
export type ChronicleJudge = (input: ChronicleJudgeInput) => Promise<ChronicleJudgeResult>;
@@ -193,7 +193,11 @@ const DEFAULT_JUDGE_MAX_TOKENS = 4000;
function defaultJudge(engine: BrainEngine): ChronicleJudge {
return async (input) => {
const { isAvailable, chat } = await import('../ai/gateway.ts');
- if (!isAvailable('chat')) return { events: [] };
+ // #2608: a missing chat provider used to return a bare `{events: []}` —
+ // indistinguishable from "the judge read the page and found no events",
+ // so keyless daemons reported clean no_events runs forever. Surface it as
+ // a distinct failure (mapped to status 'skipped' / judge_llm_unavailable).
+ if (!isAvailable('chat')) return { events: [], failure: 'llm_unavailable' };
const body = (input.body || '').slice(0, 12_000);
// #2606: configurable cap so event-dense pages have headroom.
let maxTokens = DEFAULT_JUDGE_MAX_TOKENS;
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index c938f4ae18..71e3c94249 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -22,6 +22,12 @@ import { chunkText as recursiveChunk } from './recursive.ts';
import { buildQualifiedName } from './qualified-names.ts';
import { estimateTokens, estimateEmbedTokens, estimateEmbedTokensCeiling, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
import { safeSplitIndex } from '../text-safe.ts';
+import {
+ isComponentMarkupPath,
+ extractComponentScriptRegions,
+ maskOutsideRegion,
+ maskRegions,
+} from './component-markup.ts';
// Both estimators moved to token-estimate.ts (#3477 follow-up) so
// recursive.ts can share them without an import cycle. Re-exported here:
@@ -119,7 +125,14 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:
// chunks get the new columns populated. Without this, the v28 backfill
// gives every existing chunk a search_vector but subsequent Layer 5 AST
// work would silently no-op.
-export const CHUNKER_VERSION = 4;
+//
+// v5 (#3821): Python `decorated_definition` handling. A decorated top-level
+// function or class (and a decorated method inside a class) parses as a
+// `decorated_definition` wrapper around the def — previously unmatched by
+// 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;
// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)
let Parser: typeof import('web-tree-sitter') | null = null;
@@ -327,6 +340,19 @@ function chunkEndNode(node: any, language: SupportedCodeLanguage): any {
return next && next.type === 'function_body' ? next : node;
}
+/**
+ * #3821: Python wraps a decorated function/class in a `decorated_definition`
+ * node whose actual def hangs off field 'definition'. Symbol NAME/TYPE come
+ * from the inner def; chunk RANGES stay on the outer wrapper so decorator
+ * text survives in the emitted chunk. Identity for non-wrapper nodes.
+ */
+function unwrapDecorated(node: any): any {
+ if (node?.type === 'decorated_definition') {
+ return node.childForFieldName?.('definition') ?? node;
+ }
+ return node;
+}
+
// Per-language top-level AST node types that count as semantic units.
// Languages not in this map fall through to the recursive text chunker
// when the grammar loads but no semantic nodes match — correct behavior.
@@ -356,6 +382,11 @@ const TOP_LEVEL_TYPES: Partial<Record<SupportedCodeLanguage, Set<string>>> = {
]),
python: new Set([
'function_definition', 'class_definition',
+ // #3821: a decorated fn/class parses as decorated_definition wrapping the
+ // def via field 'definition' — without this entry decorated code emitted
+ // zero chunks. Symbol name/type unwrap the wrapper (unwrapDecorated);
+ // the chunk keeps the OUTER range so decorator text survives.
+ 'decorated_definition',
'import_statement', 'import_from_statement', 'assignment',
]),
ruby: new Set(['class', 'module', 'method', 'singleton_method', 'assignment']),
@@ -411,6 +442,14 @@ const BODY_NODE_TYPES = new Set([
'module_body',
'body_statement',
'body',
+ // #3602: C# class/namespace bodies AND Rust impl/trait bodies are
+ // `declaration_list` (no `_body` suffix), so nested-emit's scan could
+ // never descend into them — Rust impl methods were silently dropped
+ // (only the scope-header chunk emitted) and C# could not nest at all.
+ // Shared set: PHP class bodies are also declaration_list, but PHP has
+ // no NESTED_EMIT_CONFIG entry and splitLargeNode prefers the `body`
+ // field, so this is additive there.
+ 'declaration_list',
]);
/**
@@ -445,7 +484,9 @@ const NESTED_EMIT_CONFIG: Partial<Record<SupportedCodeLanguage, NestedEmitConfig
},
python: {
parentTypes: new Set(['class_definition']),
- childTypes: new Set(['function_definition']),
+ // #3821: decorated methods (@property, @staticmethod, ...) parse as
+ // decorated_definition — emit them as leaves too, decorators included.
+ childTypes: new Set(['function_definition', 'decorated_definition']),
},
ruby: {
parentTypes: new Set(['class', 'module']),
@@ -459,6 +500,17 @@ const NESTED_EMIT_CONFIG: Partial<Record<SupportedCodeLanguage, NestedEmitConfig
parentTypes: new Set(['class_declaration', 'interface_declaration', 'record_declaration']),
childTypes: new Set(['method_declaration', 'constructor_declaration']),
},
+ // #3602: C# nesting. Namespaces (block-scoped AND file-scoped, cf. #3601)
+ // are parents so `namespace Demo { class C { ... } }` recurses Demo → C →
+ // methods with the full parent path. Bodies are `declaration_list` (see
+ // BODY_NODE_TYPES above).
+ c_sharp: {
+ parentTypes: new Set([
+ 'namespace_declaration', 'file_scoped_namespace_declaration',
+ 'class_declaration', 'interface_declaration', 'struct_declaration',
+ ]),
+ childTypes: new Set(['method_declaration', 'constructor_declaration', 'property_declaration']),
+ },
};
let initDone = false;
@@ -640,6 +692,51 @@ export async function chunkCodeTextFull(
if (!source.trim()) return { chunks: [], edges: [] };
+ // #3768: .svelte/.astro carry real TS/JS in <script> blocks (and the Astro
+ // `---` fence) but map to 'html'. Parse each script region with the TS/JS
+ // grammar over a geometry-preserving mask (absolute line numbers AND
+ // absolute edge byte offsets for free); the markup keeps its html chunks
+ // with the script interiors blanked so text isn't double-indexed.
+ if (isComponentMarkupPath(filePath)) {
+ const componentResult = await chunkComponentMarkup(source, filePath, opts);
+ if (componentResult) return componentResult;
+ }
+
+ return chunkParsedLanguage(source, filePath, language, opts);
+}
+
+/** #3768 orchestration — returns null when the file has no script regions. */
+async function chunkComponentMarkup(
+ source: string,
+ filePath: string,
+ opts: CodeChunkOptions,
+): Promise<ChunkAndEdgeResult | null> {
+ const regions = extractComponentScriptRegions(source, filePath);
+ if (regions.length === 0) return null;
+ const chunks: CodeChunk[] = [];
+ const edges: import('./edge-extractor.ts').ExtractedEdge[] = [];
+ for (const region of regions) {
+ const masked = maskOutsideRegion(source, region);
+ const r = await chunkParsedLanguage(masked, filePath, region.language, opts);
+ chunks.push(...r.chunks);
+ edges.push(...r.edges);
+ }
+ const markup = maskRegions(source, regions);
+ if (markup.trim()) {
+ const m = await chunkParsedLanguage(markup, filePath, 'html', opts);
+ chunks.push(...m.chunks);
+ edges.push(...m.edges);
+ }
+ // Re-number so downstream chunk_index stays unique + sequential per file.
+ return { chunks: chunks.map((c, i) => ({ ...c, index: i })), edges };
+}
+
+async function chunkParsedLanguage(
+ source: string,
+ filePath: string,
+ language: SupportedCodeLanguage,
+ opts: CodeChunkOptions,
+): Promise<ChunkAndEdgeResult> {
const largeThreshold = opts.largeChunkThresholdTokens ?? 1000;
const chunkTarget = opts.chunkSizeTokens ?? 300;
const timeoutMs = resolveChunkerTimeoutMs();
@@ -709,7 +806,9 @@ export async function chunkCodeTextFull(
// For SQL `statement` wrappers, the meaningful type lives on the inner
// child. extractSymbolName already dives in for the name; mirror that
// here so chunk headers say "table users" not "statement users".
- const typeNode = (nestableNode ?? node);
+ // #3821: same for Python decorated_definition — the header must say
+ // "function cached_fn" / "class Config", not "decorated definition".
+ const typeNode = unwrapDecorated(nestableNode ?? node);
const symbolType = (typeNode.type === 'statement' && typeNode.namedChildCount === 1)
? normalizeSymbolType(typeNode.namedChild(0).type)
: normalizeSymbolType(typeNode.type);
@@ -1103,6 +1202,11 @@ function buildChunk(input: {
function findNestableParent(node: any, config: NestedEmitConfig | undefined): any | null {
if (!config) return null;
if (config.parentTypes.has(node.type)) return node;
+ // #3821: a decorated Python class (`@dataclass class Config`) wraps the
+ // class_definition in decorated_definition. Return the OUTER node so the
+ // scope-header chunk's range keeps the decorator text; emitNestedScoped
+ // unwraps for name/type/children.
+ if (config.parentTypes.has(unwrapDecorated(node).type)) return node;
// One-level unwrap — TS export_statement wraps a class_declaration.
// We don't go deeper because that would accidentally treat a method
// inside a class as a top-level parent.
@@ -1158,8 +1262,12 @@ function emitNestedScoped(
): void {
const name = extractSymbolName(node);
if (!name) return;
- const symbolType = normalizeSymbolType(node.type);
- const { parents, leaves } = collectImmediateNestedChildren(node, config);
+ // #3821: unwrap decorated_definition for type + child collection (the
+ // class body hangs off the inner def); ranges below stay on `node` so a
+ // decorated class's scope header keeps its decorator line.
+ const def = unwrapDecorated(node);
+ const symbolType = normalizeSymbolType(def.type);
+ const { parents, leaves } = collectImmediateNestedChildren(def, config);
// Parent scope-header chunk: declaration + member digest.
const digestNames = [
@@ -1167,7 +1275,7 @@ function emitNestedScoped(
...leaves.map(l => extractSymbolName(l)).filter((n): n is string => Boolean(n)),
];
chunks.push(buildChunk({
- body: buildScopeHeaderBody(node, source, digestNames),
+ body: buildScopeHeaderBody(node, source, digestNames, def),
filePath, language, symbolName: name, symbolType,
startLine: node.startPosition.row + 1,
endLine: node.endPosition.row + 1,
@@ -1182,10 +1290,12 @@ function emitNestedScoped(
emitNestedScoped(p, newParentPath, source, filePath, language, config, chunks);
}
- // Leaf children: methods / functions / fields.
+ // Leaf children: methods / functions / fields. #3821: a decorated method
+ // is a decorated_definition leaf — type from the inner def, range from the
+ // outer node so the decorator line ships in the chunk.
for (const leaf of leaves) {
const leafName = extractSymbolName(leaf);
- const leafType = normalizeSymbolType(leaf.type);
+ const leafType = normalizeSymbolType(unwrapDecorated(leaf).type);
const leafText = source.slice(leaf.startIndex, leaf.endIndex).trim();
if (!leafText) continue;
chunks.push(buildChunk({
@@ -1205,10 +1315,15 @@ function emitNestedScoped(
* declaration line + a digest of member names so class-level queries
* still hit something.
*/
-function buildScopeHeaderBody(node: any, source: string, memberNames: string[]): string {
+function buildScopeHeaderBody(node: any, source: string, memberNames: string[], declNode: any = node): string {
const full = source.slice(node.startIndex, node.endIndex);
- const firstLineBreak = full.indexOf('\n');
- const declaration = firstLineBreak > 0 ? full.slice(0, firstLineBreak) : full.slice(0, 120);
+ // #3821: when `node` is a decorated_definition wrapper, `declNode` is the
+ // inner def — the declaration must run THROUGH the def's first line so a
+ // decorated class header reads "@dataclass\nclass Config:" instead of
+ // stopping at the bare decorator line.
+ const declOffset = Math.max(0, (declNode?.startIndex ?? node.startIndex) - node.startIndex);
+ const firstLineBreak = full.indexOf('\n', declOffset);
+ const declaration = firstLineBreak > 0 ? full.slice(0, firstLineBreak) : full.slice(0, declOffset + 120);
if (memberNames.length === 0) return declaration;
return `${declaration}\n\n// Members: ${memberNames.slice(0, 20).join(', ')}`;
}
@@ -1221,9 +1336,12 @@ interface SplitRange {
}
function splitLargeNode(node: any, source: string, chunkTarget: number): SplitRange[] {
+ // #3821: a large decorated def's body hangs off the INNER definition —
+ // dive through the wrapper or the splitter finds no body and emits whole.
+ const inner = unwrapDecorated(node);
const body =
- node.childForFieldName('body') ||
- node.namedChildren.find((c: any) => BODY_NODE_TYPES.has(c.type)) ||
+ inner.childForFieldName('body') ||
+ inner.namedChildren.find((c: any) => BODY_NODE_TYPES.has(c.type)) ||
null;
if (!body || body.namedChildren.length < 2) return [];
@@ -1280,15 +1398,46 @@ function extractSymbolName(node: any): string | null {
if (nested) return nested;
}
+ // #3821: Python decorated_definition exposes the wrapped def via field
+ // 'definition' (mirrors the TS export_statement 'declaration' dive above).
+ const definition = node.childForFieldName('definition');
+ if (definition) {
+ const nested = extractSymbolName(definition);
+ if (nested) return nested;
+ }
+
for (const child of node.namedChildren) {
if (child.type.endsWith('identifier') || child.type === 'constant') {
const v = sanitize(child.text);
if (v) return v;
}
}
+
+ // #3789: declaration wrappers hold the identifier one level down —
+ // Kotlin `property_declaration > variable_declaration > simple_identifier`,
+ // TS/JS `lexical_declaration > variable_declarator` (field: name),
+ // Go `type_declaration > type_spec` / `const_declaration > const_spec`
+ // / `var_declaration > var_spec` (field: name),
+ // C/C++ `declaration > init_declarator` (identifier child).
+ // Without this dive those chunks carry symbol_name NULL, so code-def can
+ // never surface them even with their symbol_type in DEF_TYPES. Dive is
+ // restricted to these wrapper kinds only — an arbitrary expression child
+ // must never donate a false name.
+ for (const child of node.namedChildren) {
+ if (NAME_WRAPPER_TYPES.has(child.type)) {
+ const nested = extractSymbolName(child);
+ if (nested) return nested;
+ }
+ }
return null;
}
+// See the wrapper dive in extractSymbolName (#3789).
+const NAME_WRAPPER_TYPES = new Set([
+ 'variable_declaration', 'variable_declarator', 'init_declarator',
+ 'type_spec', 'const_spec', 'var_spec',
+]);
+
// SQL-specific symbol extractor. Returns:
// string — DDL statement: extracted target name (table/function/view/index/etc).
// null — DDL statement type, but name extraction failed (edge fixture).
diff --git a/src/core/chunkers/component-markup.ts b/src/core/chunkers/component-markup.ts
new file mode 100644
index 0000000000..9f2767485c
--- /dev/null
+++ b/src/core/chunkers/component-markup.ts
@@ -0,0 +1,120 @@
+/**
+ * #3768 — .svelte/.astro script-region extraction.
+ *
+ * detectCodeLanguage maps .svelte/.astro to 'html' (the markup half really is
+ * html), which used to send the WHOLE file through the recursive fallback
+ * chunker: no symbol names, no code edges — code-def/code-callers blind to
+ * every component. code.ts uses these helpers to parse the script regions
+ * (<script> blocks and the Astro `---` frontmatter fence) with the TS/JS
+ * grammar while the markup keeps its html chunks.
+ *
+ * The load-bearing trick is GEOMETRY-PRESERVING masking: instead of slicing a
+ * script region out (which would shift every line number and byte offset), we
+ * blank every non-newline character OUTSIDE the region to spaces. The masked
+ * string has the same length and the same line structure as the original, so
+ * tree-sitter's row numbers and the edge extractor's callSiteByteOffsets are
+ * absolute in the real file — no post-hoc offset arithmetic to get wrong.
+ */
+
+export interface ComponentScriptRegion {
+ /** Index into the original source where the script CODE starts. */
+ start: number;
+ /** Index one past the end of the script code. */
+ end: number;
+ /** 1-based line the script code starts on. */
+ startLine: number;
+ language: 'typescript' | 'javascript';
+}
+
+export function isComponentMarkupPath(filePath: string): boolean {
+ const lower = filePath.toLowerCase();
+ return lower.endsWith('.svelte') || lower.endsWith('.astro');
+}
+
+const SCRIPT_OPEN_RE = /<script\b[^>]*>/gi;
+const SCRIPT_CLOSE = '</script>';
+const LANG_TS_RE = /\blang\s*=\s*["']?(?:ts|typescript)["']?/i;
+
+function lineOfIndex(source: string, index: number): number {
+ let line = 1;
+ for (let i = 0; i < index; i++) {
+ if (source.charCodeAt(i) === 10 /* \n */) line++;
+ }
+ return line;
+}
+
+/** Astro component script: the `---` fence pair at the very top of the file. */
+function matchAstroFence(source: string): ComponentScriptRegion | null {
+ const open = /^---[ \t]*\r?\n/.exec(source);
+ if (!open) return null;
+ const bodyStart = open[0].length;
+ const close = /\n---[ \t]*(?:\r?\n|$)/.exec(source.slice(bodyStart));
+ if (!close) return null;
+ const end = bodyStart + close.index; // exclusive: stops before the \n preceding the closing ---
+ if (!source.slice(bodyStart, end).trim()) return null;
+ // Astro's component script is TypeScript by default.
+ return { start: bodyStart, end, startLine: lineOfIndex(source, bodyStart), language: 'typescript' };
+}
+
+/**
+ * Find every script region in a .svelte/.astro file, in document order:
+ * the Astro fence (astro only) plus each <script ...>…</script> block
+ * (svelte instance + module scripts, astro client scripts). Empty and
+ * unterminated blocks are skipped.
+ */
+export function extractComponentScriptRegions(source: string, filePath: string): ComponentScriptRegion[] {
+ const regions: ComponentScriptRegion[] = [];
+ const lower = filePath.toLowerCase();
+ const isAstro = lower.endsWith('.astro');
+ if (isAstro) {
+ const fence = matchAstroFence(source);
+ if (fence) regions.push(fence);
+ }
+ SCRIPT_OPEN_RE.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = SCRIPT_OPEN_RE.exec(source)) !== null) {
+ const codeStart = m.index + m[0].length;
+ const close = source.indexOf(SCRIPT_CLOSE, codeStart);
+ if (close < 0) break;
+ // Astro processes client <script> blocks as TypeScript by default;
+ // svelte defaults to javascript unless lang="ts".
+ const language = LANG_TS_RE.test(m[0]) || isAstro ? 'typescript' : 'javascript';
+ if (source.slice(codeStart, close).trim()) {
+ regions.push({ start: codeStart, end: close, startLine: lineOfIndex(source, codeStart), language });
+ }
+ SCRIPT_OPEN_RE.lastIndex = close + SCRIPT_CLOSE.length;
+ }
+ return regions;
+}
+
+/** Replace every non-newline character with a space (keeps length + lines). */
+function blankSpan(text: string): string {
+ return text.replace(/[^\n\r]/g, ' ');
+}
+
+/**
+ * Keep ONE region's text at its original position; blank everything else.
+ * Parsing the result with the region's grammar yields absolute line numbers
+ * and absolute byte offsets for free.
+ */
+export function maskOutsideRegion(source: string, region: { start: number; end: number }): string {
+ return (
+ blankSpan(source.slice(0, region.start)) +
+ source.slice(region.start, region.end) +
+ blankSpan(source.slice(region.end))
+ );
+}
+
+/**
+ * Blank the given regions' interiors (script code) while keeping the markup —
+ * the html half chunks without double-indexing the script text. The <script>
+ * tags themselves stay (they sit outside the regions), so the markup remains
+ * structurally valid html.
+ */
+export function maskRegions(source: string, regions: Array<{ start: number; end: number }>): string {
+ let out = source;
+ for (const r of regions) {
+ out = out.slice(0, r.start) + blankSpan(out.slice(r.start, r.end)) + out.slice(r.end);
+ }
+ return out;
+}
diff --git a/src/core/chunkers/edge-extractor.ts b/src/core/chunkers/edge-extractor.ts
index dce9c41419..e85875183a 100644
--- a/src/core/chunkers/edge-extractor.ts
+++ b/src/core/chunkers/edge-extractor.ts
@@ -119,6 +119,11 @@ const CALL_CONFIG: Partial<Record<SupportedCodeLanguage, CallConfig>> = {
// navigation_expression for `receiver.method(...)` — resolved to the
// method name by the navigation_expression case in extractCalleeName).
kotlin: { callNodeTypes: new Set(['call_expression']), calleeFirstNamedChild: true },
+ // #3602: tree-sitter-c-sharp calls are invocation_expression with a
+ // `function` field. Bare calls hold an identifier; member calls
+ // (`obj.Method(...)`) hold a member_access_expression, which
+ // extractCalleeName resolves via its trailing-identifier fallback.
+ c_sharp: { callNodeTypes: new Set(['invocation_expression']), calleeFieldName: 'function' },
};
/**
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 2300e0e276..d2e9c5d544 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -22,65 +22,65 @@ 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', '--no-confirm', '--no-embedding', '--no-follow', '--offset', '--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', '--url', '--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', '--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'],
'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', '--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', '--undo-wave', '--url', '--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', '--page', '--param', '--params', '--password', '--path', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--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', '--no-embedding', '--no-federated', '--offset', '--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', '--url', '--what', '--where', '--who', '--with-db', '--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'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
'claw-test': ['--ab', '--agent', '--all', '--auto', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--output-format', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--version', '--with-calibration', '--yes'],
'code-callees': ['--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--dir', '--federated', '--force', '--help', '--json', '--kind', '--limit', '--name', '--no-federated', '--no-json', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--url', '--yes'],
'code-callers': ['--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--dir', '--federated', '--force', '--help', '--json', '--kind', '--limit', '--name', '--no-federated', '--no-json', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--url', '--yes'],
- 'code-def': ['--all', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--pretty', '--source', '--yes'],
- 'code-refs': ['--all', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'],
+ 'code-def': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--pretty', '--source', '--yes'],
+ 'code-refs': ['--all', '--all-sources', '--brain', '--chunker-debug', '--help', '--json', '--lang', '--limit', '--no-json', '--source', '--yes'],
'compile-context': ['--brain', '--budget', '--check', '--federated', '--help', '--include', '--json', '--no-federated', '--out', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stdout', '--target'],
'config': ['--all', '--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', '--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-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-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', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--recency', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rubric-version', '--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-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'],
'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', '--markdown', '--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', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--older-than', '--order', '--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', '--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', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--rrf-k', '--rubric-version', '--runs', '--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', '--help', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-federated', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--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', '--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', '--remediate', '--repo', '--restore-only', '--run-id', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--timeout', '--type', '--verbose', '--workers', '--yes'],
+ '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'],
- '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', '--repo', '--run-id', '--since', '--slugs', '--source', '--source-id', '--stale', '--type', '--verbose', '--workers'],
- 'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--retry-failed', '--source', '--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', '--no-embedding', '--no-federated', '--offset', '--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', '--url', '--watch', '--with-db', '--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'],
'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', '--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'],
+ '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', '--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', '--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', '--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', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--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-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', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--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', '--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', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],
+ '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'],
'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', '--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-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resume', '--run-id', '--safe', '--scope', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--target', '--target-score', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--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'],
'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', '--offset', '--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', '--url', '--with-db', '--yes'],
+ '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'],
'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', '--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', '--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', '--no-embedding', '--offset', '--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', '--url', '--with-db', '--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'],
'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', '--no-embedding', '--no-federated', '--offset', '--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', '--url', '--watch', '--with-db', '--yes'],
- 'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],
+ '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'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
@@ -94,24 +94,24 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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'],
'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', '--brain', '--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', '--reset', '--resolve', '--schema-pack', '--since', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--target-type', '--thin', '--to', '--token-ttl', '--with-db'],
+ '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'],
'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
'serve': ['--all', '--bind', '--bound-slug-prefixes', '--brain', '--compile', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--name', '--no-embedding', '--no-hard-deadline', '--once', '--parallel', '--port', '--prefix', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--timeout', '--token-ttl', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--verbose', '--writes-pages', '--writes-to'],
- 'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--model', '--no-mutate', '--optimizer-model', '--patch', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--target-model', '--target-models', '--verbose', '--yes'],
+ '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'],
'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': ['--abbrev-ref', '--abi', '--abort', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--budget-usd-per-day', '--by-mention', '--cached', '--catch-up', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content', '--content-audit', '--count', '--date', '--days', '--deadline-ms', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--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', '--http', '--image', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--json', '--judge-model', '--kind', '--lang', '--limit', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-sources', '--max-usd', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no', '--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', '--offset', '--older-than', '--order', '--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-rollup', '--reenrich-after', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--section', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--trusted-extraction', '--type', '--types', '--url', '--verbose', '--verify', '--version', '--watch', '--what', '--where', '--who', '--window', '--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', '--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'],
'storage': ['--brain', '--federated', '--fix', '--help', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--to'],
- 'sweep': ['--batch-limit', '--brain', '--budget-ms', '--help', '--json', '--once', '--source', '--stale', '--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', '--lock', '--locks', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--rebase', '--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', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--yes'],
- 'takes': ['--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', '--repo', '--restore-only', '--row', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--surface', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
+ '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'],
+ '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'],
- 'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--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', '--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'],
+ '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', '--no-embedding', '--offset', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--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', '--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'],
};
diff --git a/src/core/code-graph-readiness.ts b/src/core/code-graph-readiness.ts
index a8b93a4721..c85567f268 100644
--- a/src/core/code-graph-readiness.ts
+++ b/src/core/code-graph-readiness.ts
@@ -15,9 +15,11 @@
* Two grains, because the four commands read different data:
* - `code-def` / `code-refs` read `content_chunks.symbol_name` /
* `chunk_text`, which are populated at CHUNK time (during sync/import),
- * independent of edge resolution. Their readiness is 2-state: code chunks
- * exist → `ready`, else `not_built`. They never report `indexing` (edge
- * resolution is irrelevant to them).
+ * independent of edge resolution. Their readiness is 3-state: no code
+ * chunks → `not_built`; code chunks but none carry `symbol_name` →
+ * `no_symbols` (#3640 — chunks predate symbol extraction; hint at
+ * `reindex-code`); symbol-bearing chunks exist → `ready`. They never
+ * report `indexing` (edge resolution is irrelevant to them).
* - `code-callers` / `code-callees` read the call graph (`code_edges_*`).
* Their readiness is 3-state: no code chunks → `not_built`; code chunks
* but edges not yet resolved → `indexing`; all resolved → `ready`.
@@ -28,6 +30,17 @@
* EDGE_EXTRACTOR_VERSION_TS`. Counting only `IS NULL` would falsely report
* `ready` after a resolver-version bump (the graph is stale, not done).
*
+ * Both grains share one more state (#3707): when the SCOPED probe finds no
+ * code but an unscoped rerun finds code brain-wide, the status is
+ * `out_of_scope` — the graph is built, the caller's resolved scope (per-call
+ * source_id / source pin / remote federated_read grant) just excludes it.
+ * The hint names the scope instead of misdirecting to `gbrain sync`.
+ * #4352 remediation: that unscoped rerun probes code existence OUTSIDE the
+ * caller's resolved scope, so it runs ONLY for trusted local callers
+ * (`remote === false`, the repo trust convention — anything else is
+ * untrusted, fail-closed). A scoped remote caller sees `not_built`, never
+ * a brain-wide code-existence disclosure.
+ *
* Cost: callers run this ONLY when `count === 0` (see `resolveCodeReadiness`);
* a non-empty result short-circuits to `ready: true` with no query. Probes use
* `EXISTS` (short-circuits on first row) rather than `COUNT(*)` because the
@@ -43,7 +56,7 @@
import type { BrainEngine } from './engine.ts';
import { EDGE_EXTRACTOR_VERSION_TS } from './chunkers/symbol-resolver.ts';
-export type CodeGraphStatus = 'not_built' | 'indexing' | 'ready' | 'unknown';
+export type CodeGraphStatus = 'not_built' | 'no_symbols' | 'indexing' | 'ready' | 'out_of_scope' | 'unknown';
export interface CodeGraphReadiness {
/** Coarse machine-readable state. */
@@ -54,6 +67,12 @@ export interface CodeGraphReadiness {
has_code: boolean;
/** Whether unresolved/stale edge chunks remain in scope (edge kind only). */
pending_edges: boolean;
+ /**
+ * #3707: set ONLY for `out_of_scope` — the resolved source scope that was
+ * probed and found to hold no code (while code exists brain-wide), so
+ * hints/envelopes can name the scope instead of misdirecting to `gbrain sync`.
+ */
+ scoped_source_id?: string;
}
/** Scope for a readiness probe. Omit `sourceId` (or set `allSources`) for brain-wide. */
@@ -85,6 +104,34 @@ async function codeChunksExist(engine: BrainEngine, sourceId: string | undefined
return Boolean(rows[0]?.e);
}
+/**
+ * EXISTS probe: does any SYMBOL-BEARING code chunk exist in scope (#3640)?
+ * Code chunks can exist without symbol metadata (chunks written before
+ * symbol-aware chunking, or a chunker fallback that skipped extraction);
+ * `code-def` / `code-refs` match on `symbol_name`, so bare code-chunk
+ * existence would falsely report `ready` while every lookup returns 0.
+ * Rides the partial `idx_chunks_symbol_name` index.
+ */
+async function symbolChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise<boolean> {
+ const params: unknown[] = [];
+ let scopeClause = '';
+ if (sourceId) {
+ params.push(sourceId);
+ scopeClause = `AND p.source_id = $${params.length}`;
+ }
+ const rows = await engine.executeRaw<{ e: boolean }>(
+ `SELECT EXISTS(
+ SELECT 1 FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ WHERE p.page_kind = 'code'
+ AND cc.symbol_name IS NOT NULL
+ ${scopeClause}
+ ) AS e`,
+ params,
+ );
+ return Boolean(rows[0]?.e);
+}
+
/** EXISTS probe: does any code chunk have unresolved/stale edges (resolver predicate)? */
async function pendingEdgeChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise<boolean> {
const params: unknown[] = [EDGE_EXTRACTOR_VERSION_TS];
@@ -116,7 +163,18 @@ async function pendingEdgeChunksExist(engine: BrainEngine, sourceId: string | un
*/
export async function resolveCodeReadiness(
engine: BrainEngine,
- opts: { kind: 'symbol' | 'edge'; count: number } & ReadinessScope,
+ opts: {
+ kind: 'symbol' | 'edge';
+ count: number;
+ /**
+ * #4352 remediation: trust gate for the #3707 out_of_scope brain-wide
+ * rerun. Pass `ctx.remote` (ops) or `false` (local CLI commands).
+ * Omitted/unset is treated as untrusted — the rerun is skipped and a
+ * scoped miss stays `not_built` (fail-closed, per the repo trust
+ * convention: only strict `false` is trusted).
+ */
+ remote?: boolean;
+ } & ReadinessScope,
): Promise<CodeGraphReadiness> {
if (opts.count > 0) {
return { status: 'ready', ready: true, has_code: true, pending_edges: false };
@@ -125,11 +183,33 @@ export async function resolveCodeReadiness(
try {
const hasCode = await codeChunksExist(engine, sourceId);
if (!hasCode) {
+ // #3707: "no code in scope" conflated two very different situations —
+ // the graph was never built, vs. the graph IS built but the caller's
+ // resolved scope (per-call source_id, .gbrain-source pin, or a remote
+ // client's federated_read grant) excludes every code-bearing source.
+ // The old `not_built` hint then misdirected operators to `gbrain sync`
+ // on a fully-indexed brain. When a scope was applied, rerun the probe
+ // brain-wide: code elsewhere → out_of_scope, a scope/grant problem,
+ // not an indexing one. #4352: trusted local callers only — the rerun
+ // reads outside the resolved scope, so a remote caller never learns
+ // whether code exists beyond its grant.
+ if (sourceId !== undefined && opts.remote === false && (await codeChunksExist(engine, undefined))) {
+ return {
+ status: 'out_of_scope', ready: false, has_code: false,
+ pending_edges: false, scoped_source_id: sourceId,
+ };
+ }
return { status: 'not_built', ready: false, has_code: false, pending_edges: false };
}
if (opts.kind === 'symbol') {
- // Symbol metadata is set at chunk time; code chunks exist ⇒ genuinely none.
- return { status: 'ready', ready: true, has_code: true, pending_edges: false };
+ // Symbol metadata is set at chunk time — but only when the chunker
+ // actually extracted symbols. Probe for symbol-bearing chunks (#3640):
+ // code chunks without any symbol_name mean every def/refs lookup will
+ // return 0 no matter the symbol, which is "not built", not "no match".
+ const hasSymbols = await symbolChunksExist(engine, sourceId);
+ return hasSymbols
+ ? { status: 'ready', ready: true, has_code: true, pending_edges: false }
+ : { status: 'no_symbols', ready: false, has_code: true, pending_edges: false };
}
const pending = await pendingEdgeChunksExist(engine, sourceId);
return pending
@@ -146,6 +226,13 @@ export function readinessHint(r: CodeGraphReadiness): string | null {
switch (r.status) {
case 'not_built':
return 'Symbol graph not built (no code indexed in scope). Run `gbrain sync` to index code.';
+ case 'out_of_scope':
+ return `Code IS indexed in this brain, but none of it is inside your resolved source scope${
+ r.scoped_source_id ? ` (source '${r.scoped_source_id}')` : ''
+ }. This is a scope/grant problem, not an indexing one — do NOT re-run \`gbrain sync\`. ` +
+ `Pass a source_id that holds code (or --all-sources locally); remote clients: check the client's federated_read grant.`;
+ case 'no_symbols':
+ return 'Code is indexed but carries no symbol metadata (chunks predate symbol-aware chunking). Run `gbrain reindex-code` to rebuild the symbol graph.';
case 'indexing':
return 'Symbol graph still building (edges pending resolution). Re-run after the next `gbrain dream` cycle / autopilot tick.';
case 'unknown':
diff --git a/src/core/config.ts b/src/core/config.ts
index 338579a695..64c5ffdec8 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1224,6 +1224,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'emotional_weight.user_holder',
// Cycle phase config
'cycle.grade_takes.write_gstack_learnings',
+ // #4102: off switch for the propose_takes LLM phase (default ON; the
+ // phase ships in the default list). Read by src/core/cycle/propose-takes.ts.
+ 'cycle.propose_takes.enabled',
// Content sanity (v0.41)
'content_sanity.bytes_warn',
'content_sanity.bytes_block',
diff --git a/src/core/confirm-prompt.ts b/src/core/confirm-prompt.ts
new file mode 100644
index 0000000000..5f10940072
--- /dev/null
+++ b/src/core/confirm-prompt.ts
@@ -0,0 +1,42 @@
+/**
+ * #4318 — shared interactive [y/N] confirm.
+ *
+ * The old inline twins (sync-cost-gate.ts, reindex-code.ts) called
+ * `rl.close()` BEFORE resolving the answer, and their unguarded
+ * `rl.on('close', () => resolve(false))` listener fired synchronously during
+ * that close — so the promise settled `false` before the real answer's
+ * resolve ran and a typed "y" was read as a decline (the cost gate refused
+ * every interactive approval).
+ *
+ * Rules pinned here (test/confirm-prompt.test.ts):
+ * - resolve the ANSWER first, then close the interface;
+ * - the 'close' listener resolves(false) ONLY when no answer arrived
+ * (true EOF / Ctrl-D — decline, matching the [y/N] default).
+ */
+
+import { createInterface } from 'node:readline';
+
+export interface ConfirmStreams {
+ input?: NodeJS.ReadableStream;
+ output?: NodeJS.WritableStream;
+}
+
+/** Interactive [y/N] prompt. Resolves true on y/yes; false on anything else or EOF. */
+export async function promptYesNo(question: string, streams: ConfirmStreams = {}): Promise<boolean> {
+ return new Promise((resolve) => {
+ const rl = createInterface({
+ input: streams.input ?? process.stdin,
+ output: streams.output ?? process.stdout,
+ });
+ let answered = false;
+ rl.question(question, (answer) => {
+ answered = true;
+ const a = answer.trim().toLowerCase();
+ resolve(a === 'y' || a === 'yes');
+ rl.close();
+ });
+ rl.on('close', () => {
+ if (!answered) resolve(false);
+ });
+ });
+}
diff --git a/src/core/context/entity-salience.ts b/src/core/context/entity-salience.ts
index a80ad7b025..1408c6e3fc 100644
--- a/src/core/context/entity-salience.ts
+++ b/src/core/context/entity-salience.ts
@@ -22,6 +22,7 @@
*/
import { normalizeAlias } from '../search/alias-normalize.ts';
+import { CJK_SLUG_CHARS, hasCJK } from '../cjk.ts';
export interface EntityCandidate {
/** Surface form for the pointer label, e.g. "Garry Tan" or "@garry". */
@@ -51,6 +52,17 @@ export const MAX_CANDIDATES = 12;
*/
export const MAX_WEAK_CANDIDATES = 32;
+/**
+ * Max CJK weak n-gram candidates per turn (#3746). CJK names have no
+ * capitalization signal and no whitespace tokenization, so the strong pass
+ * (\p{Lu}-anchored) and the lowercase weak pass (\p{Ll}-anchored) are both
+ * blind to them — 田中/김철수/王小明 extracted ZERO candidates pre-fix.
+ * Own budget: n-grams are noisier than lowercase words, and the resolver
+ * restricts them to exact-evidence arms (alias / exact-title / exact-slug),
+ * so the cap only bounds probe size.
+ */
+export const MAX_CJK_WEAK_CANDIDATES = 24;
+
/**
* HARD stopwords — function words that are never an entity, even capitalized
* mid-sentence. Pronouns, articles/determiners, auxiliaries, conjunctions,
@@ -122,6 +134,15 @@ function isPureNumber(s: string): boolean {
// @handles (step 1 owns those) and the lowercase TAIL of a capitalized word.
const WEAK_TOKEN_RE = /(?<![\p{L}\p{N}'’@-])\p{Ll}[\p{L}\p{N}'’-]{2,}(?![\p{L}\p{N}'’-])/gu;
+// #3746 — CJK runs (Han/hiragana/katakana/hangul, the shared cjk.ts ranges).
+// CJK chars are \p{Lo}: invisible to both the \p{Lu}-anchored strong pass and
+// the \p{Ll}-anchored lowercase weak pass above.
+const CJK_RUN_RE = new RegExp(`[${CJK_SLUG_CHARS}]+`, 'gu');
+// Pure-hiragana grams are overwhelmingly particles/function words (の, して,
+// です) — never emitted as candidates. Names in hiragana-only form are a
+// documented v1 miss (same class as the lowercase-Latin limit above).
+const PURE_HIRAGANA_RE = /^[぀-ゟ]+$/u;
+
/**
* Extract candidate entity surface-forms from one turn's text.
* Deterministic, precision-biased, capped at MAX_CANDIDATES. Deduped on the
@@ -241,6 +262,42 @@ export function extractCandidates(text: string): EntityCandidate[] {
weakCount++;
out.push({ display: raw, query: raw, weak: true });
}
+
+ // 4. CJK weak n-gram pass (#3746). CJK scripts carry no capitalization and
+ // (for JA/ZH) no whitespace tokenization, so both passes above are blind to
+ // 田中 / 김철수 / 王小明. Emit 2–4-char n-grams of each CJK run as WEAK
+ // candidates (own budget; position-major, longest-first per position so a
+ // leading name's grams always make the cap). The resolver restricts weak
+ // candidates to exact-evidence arms — alias, plus the pure-CJK
+ // exact-title/exact-slug arm — so junk grams cost only probe size and can
+ // never fabricate a pointer without an exact registered match.
+ if (hasCJK(text)) {
+ let cjkCount = 0;
+ outer: for (const m of text.matchAll(CJK_RUN_RE)) {
+ const run = m[0];
+ if (run.length < 2) continue;
+ const grams: string[] = [];
+ if (run.length <= 4) {
+ grams.push(run); // whole short run (KO/whitespace-tokenized names)
+ } else {
+ for (let i = 0; i < run.length - 1; i++) {
+ for (const n of [4, 3, 2]) {
+ if (i + n <= run.length) grams.push(run.slice(i, i + n));
+ }
+ }
+ }
+ for (const g of grams) {
+ if (cjkCount >= MAX_CJK_WEAK_CANDIDATES) break outer;
+ if (PURE_HIRAGANA_RE.test(g)) continue; // particles/function words
+ const norm = normalizeAlias(g);
+ if (!norm) continue;
+ if (strongNorms.has(norm) || weakSeen.has(norm)) continue;
+ weakSeen.add(norm);
+ cjkCount++;
+ out.push({ display: g, query: g, weak: true });
+ }
+ }
+ }
return out;
}
diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.ts
index e86cd860b1..1170811893 100644
--- a/src/core/context/resolve-ipc.ts
+++ b/src/core/context/resolve-ipc.ts
@@ -37,12 +37,18 @@
* response, and an old serve answers `unknown_kind:sync_start` so the
* client degrades to the documented stop-the-serve refusal.
*
+ * sweep_start / sweep_status (secret-gated, protocol:2) — #677:
+ * serve-delegated maintenance sweep, the same start+poll shape as the
+ * sync kinds (no abort — a sweep is a bounded run). Wire shapes in
+ * sweep-ipc.ts; execution in serve-sweep-runner.ts; CLI half in
+ * commands/sweep-delegate.ts.
+ *
* Local-only (unix socket in a 0700 dir on the brain's data dir, socket mode
* 0600 set before readiness is announced) — no network surface.
*/
import net from 'node:net';
-import { randomBytes, timingSafeEqual } from 'node:crypto';
+import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import {
existsSync,
unlinkSync,
@@ -53,6 +59,7 @@ import {
writeFileSync,
} from 'node:fs';
import { join, dirname } from 'node:path';
+import { configDir } from '../config.ts';
import type { EntityCandidate } from './entity-salience.ts';
import type { WindowTurn } from './entity-salience.ts';
import type { PointerBlock } from './retrieval-reflex.ts';
@@ -65,6 +72,12 @@ import type {
SyncStatusRequest,
SyncStatusResponse,
} from './sync-ipc.ts';
+import type {
+ SweepStartRequest,
+ SweepStartResponse,
+ SweepStatusRequest,
+ SweepStatusResponse,
+} from './sweep-ipc.ts';
const SOCK_NAME = '.gbrain-resolve.sock';
const SECRET_NAME = '.gbrain-ipc-secret';
@@ -95,6 +108,12 @@ export const CONTEXT_PACK_SERVER_BUDGET_MS = 600;
export const SYNC_START_CLIENT_TIMEOUT_MS = 1500;
export const SYNC_STATUS_CLIENT_TIMEOUT_MS = 1000;
export const SYNC_ABORT_CLIENT_TIMEOUT_MS = 1000;
+/**
+ * Delegated-sweep kinds (#677) — same O(1) register/read shape as the sync
+ * kinds, same budgets.
+ */
+export const SWEEP_START_CLIENT_TIMEOUT_MS = 1500;
+export const SWEEP_STATUS_CLIENT_TIMEOUT_MS = 1000;
const MAX_MSG_BYTES = 256 * 1024;
/** Marker the client returns when no server is reachable (vs. a real null result). */
@@ -201,7 +220,9 @@ export type IpcRequest =
| ContextPackRequest
| SyncStartRequest
| SyncStatusRequest
- | SyncAbortRequest;
+ | SyncAbortRequest
+ | SweepStartRequest
+ | SweepStatusRequest;
export interface ResolveResponse {
ok: boolean;
@@ -234,6 +255,8 @@ export type ContextPackHandler = (req: ContextPackRequest) => Promise<TurnContex
export type SyncStartIpcHandler = (req: SyncStartRequest) => SyncStartResponse | Promise<SyncStartResponse>;
export type SyncStatusIpcHandler = (req: SyncStatusRequest) => SyncStatusResponse | Promise<SyncStatusResponse>;
export type SyncAbortIpcHandler = (req: SyncAbortRequest) => SyncAbortResponse | Promise<SyncAbortResponse>;
+export type SweepStartIpcHandler = (req: SweepStartRequest) => SweepStartResponse | Promise<SweepStartResponse>;
+export type SweepStatusIpcHandler = (req: SweepStatusRequest) => SweepStatusResponse | Promise<SweepStatusResponse>;
/** Handler MAP replacing the single closure [ENG-3]. */
export interface IpcHandlers {
@@ -243,6 +266,8 @@ export interface IpcHandlers {
sync_start?: SyncStartIpcHandler;
sync_status?: SyncStatusIpcHandler;
sync_abort?: SyncAbortIpcHandler;
+ sweep_start?: SweepStartIpcHandler;
+ sweep_status?: SweepStatusIpcHandler;
}
export interface IpcServerOpts {
@@ -283,6 +308,94 @@ export function resolveSocketPath(dataDir: string): string {
return join(dataDir, SOCK_NAME);
}
+// -- Engine-uniform paths (#4245, TODOS "engine-uniform IPC listener") --
+
+/**
+ * IPC home for brains with no data dir: `~/.gbrain/run` (GBRAIN_HOME
+ * honored via configDir). Created 0700 by the server bind / secret
+ * provision paths — never world-visible.
+ */
+export function ipcRunDir(): string {
+ return join(configDir(), 'run');
+}
+
+/** First 12 hex chars of sha256(value) — path key that never embeds the URL's credentials. */
+function hash12(value: string): string {
+ return createHash('sha256').update(value).digest('hex').slice(0, 12);
+}
+
+/** Minimal config slice the engine-uniform path resolvers key on (loadConfig's shape). */
+export interface IpcPathConfig {
+ engine?: 'postgres' | 'pglite';
+ database_path?: string;
+ database_url?: string;
+}
+
+/**
+ * Canonical socket path for a brain CONFIG (engine-uniform, #4245).
+ * PGLite keeps the data-dir socket (wire location unchanged — old serves
+ * and hooks keep pairing); Postgres gets
+ * `~/.gbrain/run/resolve-<hash12(database_url)>.sock` so two brains on one
+ * machine never share a socket. Returns null when the config carries no
+ * keying material (no config at all, thin-client remote, or a postgres
+ * config with no URL) — callers degrade, never guess.
+ *
+ * Engine is checked FIRST: a postgres config carrying a LEFTOVER
+ * database_path must not key off the path — there is no PGLite brain (and
+ * no serve) behind it (v0.45.7 gate, preserved).
+ *
+ * Multi-serve note: on Postgres several serves for the SAME database_url
+ * share this path; the newest bind wins (same last-serve-wins posture as
+ * the PGLite socket after a stale-socket cleanup). Bound-source rejection
+ * [CX2-10] still applies per request.
+ */
+export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined): string | null {
+ if (!cfg) return null;
+ if (cfg.engine === 'pglite' && cfg.database_path) return resolveSocketPath(cfg.database_path);
+ if (cfg.engine === 'postgres' && cfg.database_url) {
+ return join(ipcRunDir(), `resolve-${hash12(cfg.database_url)}.sock`);
+ }
+ return null;
+}
+
+/**
+ * Canonical shared-secret path for a brain config — same engine-uniform
+ * keying as resolveSocketPathForConfig (data dir on PGLite, hash12-keyed
+ * run-dir file on Postgres). Null = no keying material.
+ */
+export function ipcSecretPathForConfig(cfg: IpcPathConfig | null | undefined): string | null {
+ if (!cfg) return null;
+ if (cfg.engine === 'pglite' && cfg.database_path) return ipcSecretPath(cfg.database_path);
+ if (cfg.engine === 'postgres' && cfg.database_url) {
+ return join(ipcRunDir(), `secret-${hash12(cfg.database_url)}`);
+ }
+ return null;
+}
+
+/**
+ * Server-side (engine-uniform): ensure the secret at the config-keyed path.
+ * Null = no keying material (caller starts no listener); throws only when
+ * the file can neither be read nor created (turn_context disabled, never
+ * "skip auth" — same contract as ensureIpcSecret).
+ */
+export function ensureIpcSecretForConfig(cfg: IpcPathConfig | null | undefined): string | null {
+ const p = ipcSecretPathForConfig(cfg);
+ if (!p) return null;
+ return ensureIpcSecretAtPath(p);
+}
+
+/** Client-side (engine-uniform): read the config-keyed secret; null when absent. */
+export function readIpcSecretForConfig(cfg: IpcPathConfig | null | undefined): string | null {
+ const p = ipcSecretPathForConfig(cfg);
+ if (!p) return null;
+ try {
+ const s = readFileSync(p, 'utf8').trim();
+ return s || null;
+ } catch {
+ return null;
+ }
+}
+
// ── Shared secret [S3#6] ──────────────────────────────────────────────────
/** Canonical shared-secret file path for a PGLite data dir. */
@@ -297,7 +410,11 @@ export function ipcSecretPath(dataDir: string): string {
* "turn_context disabled", never as "skip auth").
*/
export function ensureIpcSecret(dataDir: string): string {
- const p = ipcSecretPath(dataDir);
+ return ensureIpcSecretAtPath(ipcSecretPath(dataDir));
+}
+
+/** Path-keyed body shared by the data-dir and config-keyed secret provisioners. */
+function ensureIpcSecretAtPath(p: string): string {
try {
const existing = readFileSync(p, 'utf8').trim();
if (existing) {
@@ -506,6 +623,32 @@ export async function requestSyncAbort(
return syncRoundTrip<SyncAbortResponse>(socketPath, line, opts.timeoutMs ?? SYNC_ABORT_CLIENT_TIMEOUT_MS);
}
+// ── Delegated-sweep clients (#677) — same fail-soft ladder as sync ─────────
+
+export type SweepStartClientRequest = Omit<SweepStartRequest, 'kind' | 'protocol'>;
+export type SweepStatusClientRequest = Omit<SweepStatusRequest, 'kind' | 'protocol'>;
+
+export type SweepStartIpcResult = SweepStartResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
+export type SweepStatusIpcResult = SweepStatusResponse | TurnContextStaleServe | typeof IPC_UNAVAILABLE;
+
+export async function requestSweepStart(
+ socketPath: string,
+ req: SweepStartClientRequest,
+ opts: { timeoutMs?: number } = {},
+): Promise<SweepStartIpcResult> {
+ const line = JSON.stringify({ kind: 'sweep_start', protocol: 2, ...req } satisfies SweepStartRequest);
+ return syncRoundTrip<SweepStartResponse>(socketPath, line, opts.timeoutMs ?? SWEEP_START_CLIENT_TIMEOUT_MS);
+}
+
+export async function requestSweepStatus(
+ socketPath: string,
+ req: SweepStatusClientRequest,
+ opts: { timeoutMs?: number } = {},
+): Promise<SweepStatusIpcResult> {
+ const line = JSON.stringify({ kind: 'sweep_status', protocol: 2, ...req } satisfies SweepStatusRequest);
+ return syncRoundTrip<SweepStatusResponse>(socketPath, line, opts.timeoutMs ?? SWEEP_STATUS_CLIENT_TIMEOUT_MS);
+}
+
async function syncRoundTrip<Resp extends { ok: boolean; protocol: 2 }>(
socketPath: string,
line: string,
@@ -683,6 +826,14 @@ export async function startResolveIpcServer(
resp = JSON.stringify(
await handleSyncKind(parsed as SyncAbortRequest, handlers.sync_abort, opts),
);
+ } else if (kind === 'sweep_start') {
+ resp = JSON.stringify(
+ await handleSyncKind(parsed as SweepStartRequest, handlers.sweep_start, opts),
+ );
+ } else if (kind === 'sweep_status') {
+ resp = JSON.stringify(
+ await handleSyncKind(parsed as SweepStatusRequest, handlers.sweep_status, opts),
+ );
} else {
resp = JSON.stringify({ ok: false, error: `unknown_kind:${String(kind)}` });
}
diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.ts
index 9006c4fdb2..fbf20e25d1 100644
--- a/src/core/context/retrieval-reflex.ts
+++ b/src/core/context/retrieval-reflex.ts
@@ -25,6 +25,7 @@
import type { BrainEngine } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
+import { CJK_SLUG_CHARS } from '../cjk.ts';
import { escapeLikePattern } from '../search/sql-ranking.ts';
import { slugify } from '../entities/resolve.ts';
import { stripTakesFence } from '../takes-fence.ts';
@@ -39,8 +40,15 @@ export { reflexPointerRationale } from './reflex-rationale.ts';
export const DEFAULT_MAX_POINTERS = 3;
const SYNOPSIS_MAX = 160;
+// #3746 — pure-CJK norm (every char in the shared Han/kana/hangul ranges).
+// These norms get the extra exact-title/exact-slug arm: CJK candidates are
+// n-grams with no capitalization signal, `slugify()` strips CJK entirely (so
+// the generic slug arm can never fire for them), and the alias table alone
+// covers only explicitly registered aliases.
+const PURE_CJK_RE = new RegExp(`^[${CJK_SLUG_CHARS}]+$`, 'u');
+
/** Which resolution arm produced a pointer (provenance → honest confidence). */
-export type ResolveArm = 'alias' | 'title' | 'slug-suffix' | 'title-surname';
+export type ResolveArm = 'alias' | 'title' | 'slug-suffix' | 'title-surname' | 'cjk-title';
/**
* v0.43 (#2095) — arm → confidence. Lives HERE, next to the arm definitions,
@@ -52,11 +60,17 @@ export type ResolveArm = 'alias' | 'title' | 'slug-suffix' | 'title-surname';
* the volunteer layer's 0.70 default gate (a 0.6x score would be silently
* discarded there) and below 'title' (an exact-title hit is stronger
* evidence than a surname-tail match).
+ *
+ * 'cjk-title' (#3746) also sits at 0.72: a pure-CJK weak n-gram that exactly
+ * matches a unique page title/slug. Exact evidence, but the gram lacks the
+ * capitalization signal a strong 'title' candidate carries — score it with
+ * the surname class, above the volunteer gate.
*/
export const ARM_CONFIDENCE: Record<ResolveArm, number> = {
alias: 0.9,
title: 0.8,
'title-surname': 0.72,
+ 'cjk-title': 0.72,
'slug-suffix': 0.6,
};
@@ -427,6 +441,48 @@ export async function resolveEntitiesToPointers(
}
}
+ // Arm 2.5 — pure-CJK weak exact-title/exact-slug (#3746, 'cjk-title').
+ // CJK weak n-grams may probe EXACT title/slug equality on top of the alias
+ // arm: slugify() strips CJK so the generic slug arm can never fire, and CJK
+ // pages routinely have no registered alias. Never suffix/surname (an n-gram
+ // tail-matching slugs would over-match wildly). Gated by the same
+ // lexicalArms kill switch as the other weak arms; GLOBAL uniqueness across
+ // the considered sources (mirror of the weak-alias fold) — an ambiguous
+ // gram injects nothing.
+ if (lexicalArms && weakNorms.size) {
+ const armResolvedNorms = new Set(resolved.map((r) => r.matchedNorm).filter(Boolean));
+ const cjkNorms = [...weakNorms].filter((n) => PURE_CJK_RE.test(n) && !armResolvedNorms.has(n));
+ if (cjkNorms.length) {
+ try {
+ const cjkRows = await engine.executeRaw<PageRow>(
+ `SELECT slug, source_id, title, type, frontmatter, compiled_truth
+ FROM pages
+ WHERE deleted_at IS NULL
+ AND source_id = ANY($1::text[])
+ AND ( lower(title) = ANY($2::text[]) OR slug = ANY($3::text[]) )`,
+ [sourceIds, cjkNorms, cjkNorms],
+ );
+ const cjkHits = new Map<string, Array<{ slug: string; source_id: string }>>();
+ for (const r of cjkRows) {
+ rowByKey.set(keyOf(r.source_id, r.slug), r); // hydrate for synopsis
+ const titleLc = (r.title ?? '').toLowerCase();
+ for (const n of cjkNorms) {
+ if (titleLc === n || r.slug === n) {
+ const list = cjkHits.get(n) ?? [];
+ list.push({ slug: r.slug, source_id: r.source_id });
+ cjkHits.set(n, list);
+ }
+ }
+ }
+ for (const [n, hits] of cjkHits) {
+ if (hits.length === 1) push(hits[0].slug, hits[0].source_id, 'cjk-title', n);
+ }
+ } catch {
+ /* fail-open — the alias arm already ran */
+ }
+ }
+ }
+
// Build pointers in confidence order, applying suppression + cap.
const suppression = opts.suppression ?? 'slug-and-title';
const pointers: ReflexPointer[] = [];
diff --git a/src/core/context/sweep-ipc.ts b/src/core/context/sweep-ipc.ts
new file mode 100644
index 0000000000..f53c7dfa47
--- /dev/null
+++ b/src/core/context/sweep-ipc.ts
@@ -0,0 +1,144 @@
+/**
+ * Serve-delegated maintenance sweep IPC — wire types + validation (#677).
+ *
+ * A live `gbrain serve` holds a PGLite brain's single-writer connection for
+ * its lifetime, so a concurrent `gbrain sweep --once` process cannot open the
+ * brain (LiveServeLockError). These kinds let the sweep CLI delegate the run
+ * to the serve process over the existing resolve-IPC socket — the lock owner
+ * does the work, the CLI polls. Same trust posture as the sync kinds: narrow
+ * typed requests, secret-gated, raw SQL never crosses the wire.
+ *
+ * sweep_start { options, clientToken } → { ok, jobId } | { ok:false, error }
+ * sweep_status { jobId } → job state + final SweepReport
+ *
+ * No abort kind: a sweep is a bounded run (default 5s budget) — the client
+ * just polls to completion. This module is deliberately a LEAF: pure types +
+ * pure functions, imported by both the resolve-ipc plumbing and the
+ * serve-sweep-runner. It must not import resolve-ipc.ts (cycle) or any
+ * engine module.
+ */
+
+import { isValidSourceId } from '../source-id.ts';
+import type { SweepReport } from '../sweep.ts';
+
+// ── Options allowlist ──────────────────────────────────────────────────────
+
+/**
+ * Field table driving the validator + both wire builders (single source of
+ * truth, same pattern as DELEGATED_SYNC_OPTION_FIELDS). Everything NOT in
+ * this table is rejected fail-closed.
+ */
+export const DELEGATED_SWEEP_OPTION_FIELDS = {
+ sourceId: 'string',
+ budgetMs: 'number',
+ batchLimit: 'number',
+} as const;
+
+/** Hard ceiling on a delegated sweep's wall-clock budget (10 min). */
+export const DELEGATED_SWEEP_BUDGET_MAX_MS = 600_000;
+
+export interface DelegatedSweepOptions {
+ /** Must satisfy the canonical source-id shape; validated at the boundary. */
+ sourceId?: string;
+ budgetMs?: number;
+ batchLimit?: number;
+}
+
+export type DelegatedSweepValidation =
+ | { ok: true; options: DelegatedSweepOptions }
+ | { ok: false; error: string };
+
+/**
+ * Fail-closed wire validation: unknown keys reject, wrong types reject,
+ * sourceId must be shape-valid, numeric knobs must be non-negative integers
+ * (budgetMs clamps to DELEGATED_SWEEP_BUDGET_MAX_MS). Returns a NEW object
+ * built from the field table — never the caller's reference.
+ */
+export function validateDelegatedSweepOptions(raw: unknown): DelegatedSweepValidation {
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
+ return { ok: false, error: 'invalid_options:options' };
+ }
+ const rec = raw as Record<string, unknown>;
+ for (const key of Object.keys(rec)) {
+ if (!(key in DELEGATED_SWEEP_OPTION_FIELDS)) {
+ return { ok: false, error: `invalid_options:${key}` };
+ }
+ }
+ const out: Record<string, unknown> = {};
+ for (const [key, type] of Object.entries(DELEGATED_SWEEP_OPTION_FIELDS)) {
+ const v = rec[key];
+ if (v === undefined) continue;
+ if (typeof v !== type) return { ok: false, error: `invalid_options:${key}` };
+ out[key] = v;
+ }
+ for (const key of ['budgetMs', 'batchLimit'] as const) {
+ const v = out[key];
+ if (v === undefined) continue;
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
+ return { ok: false, error: `invalid_options:${key}` };
+ }
+ }
+ if (typeof out.budgetMs === 'number') {
+ out.budgetMs = Math.min(out.budgetMs, DELEGATED_SWEEP_BUDGET_MAX_MS);
+ }
+ if (out.sourceId !== undefined && !isValidSourceId(out.sourceId as string)) {
+ return { ok: false, error: 'invalid_options:sourceId' };
+ }
+ return { ok: true, options: out as unknown as DelegatedSweepOptions };
+}
+
+// ── Wire request / response types ──────────────────────────────────────────
+
+export type DelegatedSweepState = 'running' | 'done' | 'error';
+
+export interface SweepStartRequest {
+ kind: 'sweep_start';
+ protocol: 2;
+ secret: string;
+ /**
+ * Client-generated idempotency token — a retry after a lost ack attaches to
+ * its own job (running or retained-terminal) instead of duplicate-running.
+ */
+ clientToken: string;
+ options: DelegatedSweepOptions;
+}
+
+export type SweepStartError =
+ | 'busy'
+ | 'unauthorized'
+ | 'unsupported_protocol'
+ | 'unsupported_kind'
+ | 'shutting_down'
+ | 'source_mismatch'
+ | string; // `invalid_options:<field>`
+
+export interface SweepStartResponse {
+ ok: boolean;
+ protocol: 2;
+ jobId?: string;
+ /** True when a token retry matched the retained terminal job. */
+ completed?: boolean;
+ error?: SweepStartError;
+}
+
+export interface SweepStatusRequest {
+ kind: 'sweep_status';
+ protocol: 2;
+ secret: string;
+ jobId: string;
+}
+
+export interface SweepStatusResponse {
+ ok: boolean;
+ protocol: 2;
+ state?: DelegatedSweepState;
+ sourceId?: string;
+ startedAt?: number;
+ elapsedMs?: number;
+ /** Present when state === 'done'. Bounded — counts + skip reasons only. */
+ report?: SweepReport;
+ /** Present when state === 'error' — the job's failure message. */
+ jobError?: string;
+ /** ok:false protocol errors: 'unauthorized' | 'unknown_job' | 'unsupported_kind' | 'unsupported_protocol'. */
+ error?: string;
+}
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 6c0adadb82..35df66a30b 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -74,6 +74,8 @@ export interface TurnContextFact {
valid_from?: string;
/** Recording time (v0.45.7) — delta's "new since" filter prefers this over valid_from. */
created_at?: string;
+ /** #4206: provenance context (e.g. extract_facts' source_slug). */
+ context?: string | null;
confidence: number;
}
@@ -569,6 +571,8 @@ async function assembleDelta(
entity_slug: r.entity_slug,
valid_from: r.valid_from.toISOString(),
created_at: r.created_at.toISOString(),
+ // #4206: provenance context rides delta like the other projections.
+ context: r.context ?? null,
confidence: r.confidence,
}));
} catch {
diff --git a/src/core/context/volunteer.ts b/src/core/context/volunteer.ts
index fee658394d..22d957e01a 100644
--- a/src/core/context/volunteer.ts
+++ b/src/core/context/volunteer.ts
@@ -116,6 +116,7 @@ function rationaleFor(arm: ResolveArm, display: string, c: WindowEntityCandidate
arm === 'alias' ? `alias match "${display}"`
: arm === 'title' ? `exact title match "${display}"`
: arm === 'title-surname' ? `surname match "${display}"`
+ : arm === 'cjk-title' ? `exact CJK title/slug match "${display}"`
: `slug match "${display}"`;
if (!c) return armText;
const parts = [armText];
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index a9c8fb79a1..455d1e95df 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -177,6 +177,23 @@ export function titleTierCorpusGeneration(): string {
return computeCorpusGeneration({ crMode: 'title', synopsisModel: DEFAULT_SYNOPSIS_MODEL });
}
+/**
+ * #3883: resolve the synopsis output-token cap from the
+ * `models.synopsis_max_tokens` config key. Returns undefined when unset or
+ * invalid so generatePerChunkSynopsis falls back to its SYNOPSIS_MAX_TOKENS
+ * default (200). Clamped to a sane range (16..8192); fail-open on config
+ * errors (a config read failure must never block a re-embed).
+ */
+export async function resolveSynopsisMaxTokens(engine: BrainEngine): Promise<number | undefined> {
+ try {
+ const raw = await engine.getConfig('models.synopsis_max_tokens');
+ if (raw == null || raw === '') return undefined;
+ const n = Number(raw);
+ if (Number.isFinite(n) && n >= 16 && n <= 8192) return Math.floor(n);
+ } catch { /* fail-open to the page-summary default */ }
+ return undefined;
+}
+
/**
* Compute source_text_hash for D27 P1-4 cache key composition. The
* synopsis cache invalidates correctly when adjacent text changes (page
@@ -244,6 +261,12 @@ export interface ReembedPageArgs {
killSwitchDisabled?: boolean;
/** Resolved provider-neutral model used for per-chunk synopsis generation. */
synopsisModel?: string;
+ /**
+ * #3883: output-token cap for each synopsis call. When omitted, the
+ * `models.synopsis_max_tokens` config is read once per page; when that is
+ * unset too, page-summary's SYNOPSIS_MAX_TOKENS default (200) applies.
+ */
+ synopsisMaxTokens?: number;
/**
* @deprecated Use `synopsisModel`. Retained for callers compiled against
* the pre-provider-neutral service shape.
@@ -333,6 +356,10 @@ export async function reembedPageWithContextualRetrieval(
// single bad chunk demotes the whole page to title-only so all
// chunks on the page share the same wrapper shape.
const synopsisModel = args.synopsisModel ?? args.haikuModel ?? DEFAULT_SYNOPSIS_MODEL;
+ // #3883: explicit arg wins; else the models.synopsis_max_tokens config;
+ // else undefined → page-summary's SYNOPSIS_MAX_TOKENS default (200).
+ const synopsisMaxTokens =
+ args.synopsisMaxTokens ?? (await resolveSynopsisMaxTokens(args.engine));
let attemptMode: CRMode = resolution.mode;
let fallbackReason: SynopsisFailureKind | null = null;
@@ -344,6 +371,7 @@ export async function reembedPageWithContextualRetrieval(
chunks: chunks as ChunkInput[],
args,
synopsisModel,
+ synopsisMaxTokens,
});
if (phase1.kind === 'success') {
@@ -445,8 +473,10 @@ async function tryBuildPhase1(opts: {
chunks: ChunkInput[];
args: ReembedPageArgs;
synopsisModel: string;
+ /** #3883: resolved output-token cap (undefined → page-summary default). */
+ synopsisMaxTokens?: number;
}): Promise<Phase1Result> {
- const { attemptMode, page, chunks, args, synopsisModel } = opts;
+ const { attemptMode, page, chunks, args, synopsisModel, synopsisMaxTokens } = opts;
// Build the wrapper prefix for THIS page. Title-only tier: one prefix
// reused across all chunks. per_chunk_synopsis tier: prefix is built
@@ -506,6 +536,7 @@ async function tryBuildPhase1(opts: {
page,
args,
synopsisModel,
+ synopsisMaxTokens,
});
},
});
@@ -553,8 +584,10 @@ async function buildWrappedChunkText(opts: {
page: Page;
args: ReembedPageArgs;
synopsisModel: string;
+ /** #3883: resolved output-token cap (undefined → page-summary default). */
+ synopsisMaxTokens?: number;
}): Promise<string> {
- const { chunk: c, sourceText, safeTitle, page, args, synopsisModel } = opts;
+ const { chunk: c, sourceText, safeTitle, page, args, synopsisModel, synopsisMaxTokens } = opts;
// Code chunks always bypass the wrapper (D20-T4) — pass through.
if (c.chunk_source === 'fenced_code') {
@@ -591,6 +624,7 @@ async function buildWrappedChunkText(opts: {
chunkIndex: c.chunk_index,
model: synopsisModel,
abortSignal: args.abortSignal,
+ maxTokens: synopsisMaxTokens,
});
} finally {
if (leaseAcquired && args.releaseSynopsisLease) {
@@ -672,7 +706,14 @@ function readSourceTextWithFallback(page: Page, chunks: ChunkInput[]): string {
.join('\n\n');
}
-async function loadSourceRow(engine: BrainEngine, sourceId: string): Promise<SourceRow> {
+/**
+ * Load one source row with the CR-relevant columns. Exported for reuse by
+ * the import path (#3885: stored `sources set-cr-mode` must apply on
+ * capture/reindex, not just the Minion backfill) and the conversation-parser
+ * body reader (#3911: relative raw_transcript resolves against the OWNING
+ * source's local_path). Throws when the source id is unknown.
+ */
+export async function loadSourceRow(engine: BrainEngine, sourceId: string): Promise<SourceRow> {
const rows = await engine.executeRaw<SourceRow>(
`SELECT id, name, local_path, last_commit, last_sync_at, config, created_at,
contextual_retrieval_mode, trust_frontmatter_overrides
diff --git a/src/core/conversation-parser/body.ts b/src/core/conversation-parser/body.ts
index fd24345d81..bacf5750dd 100644
--- a/src/core/conversation-parser/body.ts
+++ b/src/core/conversation-parser/body.ts
@@ -1,7 +1,8 @@
import { existsSync, readFileSync } from 'node:fs';
-import { isAbsolute, join } from 'node:path';
+import { isAbsolute, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
+import { loadSourceRow } from '../contextual-retrieval-service.ts';
export function readSummaryBody(page: Page): string {
const compiled = page.compiled_truth ?? '';
@@ -18,18 +19,79 @@ function extractRawTranscriptPath(page: Page): string | null {
return trimmed.length > 0 ? trimmed : null;
}
+/**
+ * Resolve `rel` against `root`, rejecting any result that escapes the root
+ * (`../`-style traversal in frontmatter is untrusted data — a page synced
+ * from a mounted repo must not read arbitrary host files). Returns the
+ * resolved absolute path, or null on escape.
+ */
+function resolveWithinRoot(root: string, rel: string): string | null {
+ const rootAbs = resolve(root);
+ const candidate = resolve(rootAbs, rel);
+ if (candidate === rootAbs || candidate.startsWith(rootAbs + sep)) return candidate;
+ return null;
+}
+
+/**
+ * #3911: a RELATIVE `raw_transcript` is repo-relative — but "the repo" is the
+ * page's OWNING source, not the brain-global `sync.repo_path`. Multi-source
+ * brains stored transcripts per source; resolving every page against the
+ * global repo path silently read the wrong file (or nothing) for any page
+ * outside that one repo. Resolution order:
+ *
+ * 1. absolute path — accepted only when it lands INSIDE a registered root
+ * (the owning source's `local_path`, else `sync.repo_path`). Frontmatter
+ * is untrusted data, so an absolute `/etc/passwd`-style path is rejected
+ * the same as `../` traversal (#3911 follow-up);
+ * 2. page.source_id's source row `local_path` — escape-checked;
+ * 3. `sync.repo_path` fallback (source row missing / no local_path) —
+ * also escape-checked.
+ *
+ * A RELATIVE path that ESCAPES its root is rejected outright (returns null →
+ * caller falls back to the summary body); it does not retry lower tiers.
+ * An ABSOLUTE path may sit in either root (containment, not resolution).
+ */
+async function resolveTranscriptPath(
+ engine: BrainEngine,
+ page: Page,
+ rawTranscript: string,
+): Promise<string | null> {
+ let sourceLocalPath: string | null = null;
+ if (page.source_id) {
+ try {
+ sourceLocalPath = (await loadSourceRow(engine, page.source_id)).local_path;
+ } catch {
+ // Unknown source id / sources table unavailable — fall through to the
+ // brain-global repo path, the pre-#3911 behavior.
+ }
+ }
+ if (isAbsolute(rawTranscript)) {
+ // resolveWithinRoot handles absolute candidates: resolve(root, abs) is
+ // abs itself, so this is a pure containment check against each root.
+ if (sourceLocalPath) {
+ const contained = resolveWithinRoot(sourceLocalPath, rawTranscript);
+ if (contained) return contained;
+ }
+ const repoPath = await engine.getConfig('sync.repo_path');
+ if (repoPath) {
+ const contained = resolveWithinRoot(repoPath, rawTranscript);
+ if (contained) return contained;
+ }
+ return null; // outside every registered root — fail closed
+ }
+ if (sourceLocalPath) return resolveWithinRoot(sourceLocalPath, rawTranscript);
+ const repoPath = await engine.getConfig('sync.repo_path');
+ if (repoPath) return resolveWithinRoot(repoPath, rawTranscript);
+ return null;
+}
+
export async function readConversationBodyForParsing(
engine: BrainEngine,
page: Page,
): Promise<string> {
const rawTranscript = extractRawTranscriptPath(page);
if (rawTranscript) {
- const repoPath = await engine.getConfig('sync.repo_path');
- const resolved = isAbsolute(rawTranscript)
- ? rawTranscript
- : repoPath
- ? join(repoPath, rawTranscript)
- : null;
+ const resolved = await resolveTranscriptPath(engine, page, rawTranscript);
if (resolved && existsSync(resolved)) {
const rawBody = readFileSync(resolved, 'utf8').trim();
if (rawBody.length > 0) return rawBody;
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 6126f01675..fe4cb87681 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -572,6 +572,15 @@ export interface CycleOpts {
* existing dispatch + every existing minion job in flight at upgrade
* time use this row in `gbrain_cycle_locks`.
*/
+/**
+ * #4062 review: wall-clock cap for the extract phase's IN-CYCLE stale drain.
+ * Deliberately small — the drain is a backlog nibbler that must not starve
+ * the phases behind it; the full STALE_TIME_BUDGET_MS (~30 min) belongs to
+ * the explicit `gbrain extract --stale` command. A backlog bigger than one
+ * cap's worth drains incrementally across cycles (staleRemaining reports it).
+ */
+export const CYCLE_STALE_DRAIN_BUDGET_MS = 3 * 60 * 1000;
+
const LEGACY_CYCLE_LOCK_ID = 'gbrain-cycle';
// v0.41.19.0 (T2 of ops-fix-wave): dropped from 30 min to 5 min so a
// crashed cycle releases the lock within 5 min instead of holding it for
@@ -1366,6 +1375,40 @@ async function runPhaseExtract(
const linksCreated = result?.links_created ?? 0;
const timelineCreated = result?.timeline_entries_created ?? 0;
const incremental = changedSlugs !== undefined;
+ // #4062: the targeted pass above only covers what sync reported (or the
+ // fs walk found) — pages left stale for any OTHER reason (extractor
+ // version bump, DB-only writes, a prior aborted sweep) never re-extracted
+ // on the cycle, so the links_extracted_at backlog grew unboundedly until
+ // someone hand-ran `gbrain extract --stale`. Drain it here: DB-source,
+ // source-scoped, capped at CYCLE_STALE_DRAIN_BUDGET_MS per cycle (the
+ // full ~30-min STALE_TIME_BUDGET_MS stays with the explicit
+ // `gbrain extract --stale` command — an unbounded in-cycle drain would
+ // starve every later phase behind a big backlog; the remainder drains
+ // across subsequent cycles), no-op when nothing is stale. Failures
+ // degrade to details (the targeted pass already succeeded — a drain
+ // hiccup must not fail the phase).
+ let staleRemaining: number | undefined;
+ let staleDetails: Record<string, unknown> = {};
+ try {
+ const { extractStaleFromDB } = await import('../commands/extract.ts');
+ const drained = await extractStaleFromDB(engine, {
+ dryRun: false,
+ jsonMode: false,
+ includeFrontmatter,
+ sourceIdFilter: sourceId,
+ catchUp: false,
+ timeBudgetMs: CYCLE_STALE_DRAIN_BUDGET_MS,
+ });
+ staleRemaining = drained.staleRemaining;
+ staleDetails = {
+ stale_pages_drained: drained.pagesProcessed,
+ stale_links_created: drained.linksCreated,
+ stale_timeline_created: drained.timelineCreated,
+ staleRemaining: drained.staleRemaining,
+ };
+ } catch (e) {
+ staleDetails = { stale_drain_error: e instanceof Error ? e.message : String(e) };
+ }
return {
phase: 'extract',
status: 'ok',
@@ -1378,6 +1421,8 @@ async function runPhaseExtract(
pages_processed: result?.pages_processed ?? 0,
incremental,
...(incremental ? { slugs_targeted: changedSlugs.length } : {}),
+ ...staleDetails,
+ ...(staleRemaining !== undefined && staleRemaining > 0 ? { stale_backlog: true } : {}),
},
};
} catch (e) {
@@ -2569,7 +2614,10 @@ export async function runCycle(
// clean partial-exit fires before the worker's kill switch (same
// literal shape as the patterns call above so the structural guard
// matches both).
- const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
+ // #4102: `once` bypasses the cycle.propose_takes.enabled off switch
+ // for `gbrain dream --phase propose_takes --once` (same semantics as
+ // conversation_facts_backfill / enrich_thin above).
+ const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null, once: opts.onceForPhase === 'propose_takes' }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 4930cb3b8f..20484b8274 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -186,6 +186,7 @@ export async function runPhaseConversationFactsBackfill(
const startedAt = Date.now();
const maxTotalWalltimeMs = cfg.maxTotalWalltimeMin * 60_000;
+ const maxWalltimeMs = cfg.maxWalltimeMin * 60_000;
const sources = await listSources(engine);
if (sources.length === 0) {
@@ -198,108 +199,155 @@ export async function runPhaseConversationFactsBackfill(
};
}
- // Brain-wide tracker — created ONCE, scoped to brain-wide cap. Passed
- // explicitly into every per-source core invocation via opts.budgetTracker
- // so the core doesn't wrap (which would REPLACE).
- const brainTracker = new BudgetTracker({
- maxCostUsd: cfg.maxTotalCostUsd,
- label: 'conversation_facts_backfill:brain-wide',
- });
-
- const perSourceResults: Record<string, ExtractConversationFactsResult & { error?: string }> = {};
+ type PerSourceRecord = ExtractConversationFactsResult & {
+ error?: string;
+ walltime_exhausted?: boolean;
+ };
+ const perSourceResults: Record<string, PerSourceRecord> = {};
let skippedByBrainWideCap = 0;
let skippedByBrainWideWalltime = 0;
+ let sourcesBudgetExhausted = 0;
+ let sourcesWalltimeExhausted = 0;
let totalSpent = 0;
+ const zeroResult = (): ExtractConversationFactsResult => ({
+ pages_considered: 0,
+ pages_processed: 0,
+ pages_skipped: 0,
+ pages_skipped_too_large: 0,
+ pages_skipped_disappeared: 0,
+ pages_skipped_completed: 0,
+ pages_skipped_non_extractable: 0,
+ pages_marked_non_extractable: 0,
+ pages_skipped_unrecognized_speaker: 0,
+ pages_failed: 0,
+ pages_llm_fallback: 0,
+ // v0.41.15.0 (D6 + D11): new counters from the per-page lock
+ // + delete-orphans-first replay safety.
+ pages_lock_skipped: 0,
+ orphan_facts_cleaned: 0,
+ segments_processed: 0,
+ facts_extracted: 0,
+ facts_inserted: 0,
+ });
+
+ // #3627: the per-source caps (max_cost_usd / max_walltime_min) were parsed
+ // but never enforced — one runaway source could eat the whole brain-wide
+ // budget while every later source starved. Each source now runs under its
+ // OWN tracker capped at min(per-source cap, brain-wide remainder) with the
+ // tracker's runtime cap as the LLM-boundary walltime check, PLUS an
+ // AbortController deadline threaded as the core's signal (the core already
+ // aborts at page/pool boundaries). Per-source exhaustion records and
+ // CONTINUES to the next source; only the brain-wide caps break the loop.
try {
- // Single withBudgetTracker scope wraps the entire loop so the
- // brain-wide tracker counts EVERY gateway call inside any per-source
- // invocation. The core uses opts.budgetTracker as-is (no nested wrap),
- // so the AsyncLocalStorage scope established here remains active.
- await withBudgetTracker(brainTracker, async () => {
- for (const src of sources) {
- if (opts.signal?.aborted) throw new Error('aborted');
+ for (let i = 0; i < sources.length; i++) {
+ const src = sources[i];
+ if (opts.signal?.aborted) throw new Error('aborted');
- // Brain-wide walltime check.
- if (Date.now() - startedAt > maxTotalWalltimeMs) {
- skippedByBrainWideWalltime++;
- continue;
- }
+ // Brain-wide walltime check.
+ const remainingWallMs = maxTotalWalltimeMs - (Date.now() - startedAt);
+ if (remainingWallMs <= 0) {
+ skippedByBrainWideWalltime++;
+ continue;
+ }
+
+ // Brain-wide cost check (sum of per-source tracker spends).
+ const remainingCostUsd = cfg.maxTotalCostUsd - totalSpent;
+ if (remainingCostUsd <= 0) {
+ skippedByBrainWideCap = sources.length - i;
+ break;
+ }
+
+ const perSourceWallMs = Math.min(maxWalltimeMs, remainingWallMs);
+ const perSourceCapUsd = Math.min(cfg.maxCostUsd, remainingCostUsd);
+ const tracker = new BudgetTracker({
+ maxCostUsd: perSourceCapUsd,
+ maxRuntimeMs: perSourceWallMs,
+ label: `conversation_facts_backfill:${src.id}`,
+ });
- try {
- const result = await runExtractConversationFactsCore(engine, {
+ // Per-source deadline signal. The tracker's maxRuntimeMs fires at LLM
+ // call boundaries (core catches BudgetExhausted and returns a partial
+ // result + receipt); the AbortController is the backstop for stretches
+ // with no LLM call. An outer abort forwards so shutdown still works.
+ const controller = new AbortController();
+ let walltimeFired = false;
+ const timer = setTimeout(() => {
+ walltimeFired = true;
+ controller.abort(new Error(
+ `conversation_facts_backfill: per-source walltime cap (${cfg.maxWalltimeMin}min) hit for ${src.id}`,
+ ));
+ }, perSourceWallMs);
+ const onOuterAbort = () => controller.abort();
+ opts.signal?.addEventListener('abort', onOuterAbort, { once: true });
+
+ try {
+ const result = await withBudgetTracker(tracker, () =>
+ runExtractConversationFactsCore(engine, {
sourceId: src.id,
types: cfg.types,
dryRun: opts.dryRun,
- // Pass brain-wide tracker so core skips its own auto-wrap.
- budgetTracker: brainTracker,
+ // Per-source tracker so core skips its own auto-wrap.
+ budgetTracker: tracker,
// v0.41.15.0 (D9 cycle context): cycle config controls
// per-source worker count. Default 1 — opt-in concurrency
// for cycle paths.
workers: cfg.workers,
- }, opts.signal);
- perSourceResults[src.id] = result;
- if (result.budget_exhausted) {
- // Brain-wide cap hit. Remaining sources skipped.
- skippedByBrainWideCap = Math.max(
- 0,
- sources.length - Object.keys(perSourceResults).length,
- );
- break;
- }
- } catch (err) {
- if (err instanceof BudgetExhausted) {
- skippedByBrainWideCap = Math.max(
- 0,
- sources.length - Object.keys(perSourceResults).length,
- );
- break;
- }
+ }, controller.signal),
+ );
+ perSourceResults[src.id] = result;
+ // #3627: per-source exhaustion (cost or the tracker's runtime cap)
+ // is recorded and the loop CONTINUES — the next source gets its own
+ // fresh budget. Only the brain-wide checks at the loop top break.
+ if (result.budget_exhausted) sourcesBudgetExhausted++;
+ } catch (err) {
+ if (opts.signal?.aborted) throw err; // real caller abort propagates
+ if (walltimeFired) {
+ // Our own per-source deadline aborted the core mid-run: record +
+ // continue with the next source.
+ sourcesWalltimeExhausted++;
+ perSourceResults[src.id] = {
+ ...zeroResult(),
+ walltime_exhausted: true,
+ error: 'walltime_exhausted',
+ };
+ } else if (err instanceof BudgetExhausted) {
+ // Escaped the core's own catch — same per-source posture.
+ sourcesBudgetExhausted++;
+ perSourceResults[src.id] = {
+ ...zeroResult(),
+ budget_exhausted: true,
+ error: err.message,
+ };
+ } else {
// Per-source failure: record + continue with next source.
perSourceResults[src.id] = {
- pages_considered: 0,
- pages_processed: 0,
- pages_skipped: 0,
- pages_skipped_too_large: 0,
- pages_skipped_disappeared: 0,
- pages_skipped_completed: 0,
- pages_skipped_non_extractable: 0,
- pages_marked_non_extractable: 0,
- pages_skipped_unrecognized_speaker: 0,
+ ...zeroResult(),
pages_failed: 1,
- pages_llm_fallback: 0,
- // v0.41.15.0 (D6 + D11): new counters from the per-page lock
- // + delete-orphans-first replay safety.
- pages_lock_skipped: 0,
- orphan_facts_cleaned: 0,
- segments_processed: 0,
- facts_extracted: 0,
- facts_inserted: 0,
error: (err as Error).message,
};
}
+ } finally {
+ clearTimeout(timer);
+ opts.signal?.removeEventListener('abort', onOuterAbort);
+ totalSpent += tracker.totalSpent;
}
- });
+ }
} catch (err) {
- if (err instanceof BudgetExhausted) {
- // Brain-wide cap hit during last source.
- } else if ((err as Error).message === 'aborted' || opts.signal?.aborted) {
+ if ((err as Error).message === 'aborted' || opts.signal?.aborted) {
// Propagate abort.
throw err;
- } else {
- // Unexpected error.
- return {
- phase: 'conversation_facts_backfill',
- status: 'fail',
- duration_ms: Date.now() - startedAt,
- summary: `brain-wide loop failed: ${(err as Error).message}`,
- details: { error: (err as Error).message, perSourceResults },
- };
}
+ // Unexpected error.
+ return {
+ phase: 'conversation_facts_backfill',
+ status: 'fail',
+ duration_ms: Date.now() - startedAt,
+ summary: `brain-wide loop failed: ${(err as Error).message}`,
+ details: { error: (err as Error).message, perSourceResults },
+ };
}
- totalSpent = brainTracker.totalSpent;
-
// Aggregate.
const totals = {
pages_processed: 0,
@@ -349,7 +397,12 @@ export async function runPhaseConversationFactsBackfill(
spent_usd: totalSpent,
skipped_by_brain_wide_cap: skippedByBrainWideCap,
skipped_by_brain_wide_walltime: skippedByBrainWideWalltime,
+ // #3627: per-source cap enforcement observability.
+ sources_budget_exhausted: sourcesBudgetExhausted,
+ sources_walltime_exhausted: sourcesWalltimeExhausted,
types: cfg.types,
+ max_cost_usd: cfg.maxCostUsd,
+ max_walltime_min: cfg.maxWalltimeMin,
max_total_cost_usd: cfg.maxTotalCostUsd,
max_total_walltime_min: cfg.maxTotalWalltimeMin,
per_source: perSourceResults,
diff --git a/src/core/cycle/enrich-thin.ts b/src/core/cycle/enrich-thin.ts
index 85c3f9f6ea..df7c2856ca 100644
--- a/src/core/cycle/enrich-thin.ts
+++ b/src/core/cycle/enrich-thin.ts
@@ -101,6 +101,17 @@ async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
const n = parseFloat(raw);
return Number.isFinite(n) && n > 0 ? n : fallback;
};
+ // #2504 — cost knobs accept 'off'/'unlimited'/'none' (the same spellings
+ // `gbrain enrich --max-usd` takes) → Infinity sentinel. Per-source 'off'
+ // leaves the brain-wide total governing; both 'off' reaches runEnrichCore
+ // as Infinity, which it maps to an uncapped tracker. parseFloat('off') used
+ // to silently become the default cap — the operator's opt-out was ignored.
+ const parseCostOrDefault = (raw: string | null, fallback: number): number => {
+ if (raw != null && ['off', 'unlimited', 'none'].includes(raw.trim().toLowerCase())) {
+ return Infinity;
+ }
+ return parseFloatOrDefault(raw, fallback);
+ };
const parseIntOrDefault = (raw: string | null, fallback: number): number => {
if (raw == null) return fallback;
const n = parseInt(raw, 10);
@@ -127,8 +138,8 @@ async function loadCfg(engine: BrainEngine): Promise<ResolvedConfig> {
return {
enabled: enabledFlag,
- maxCostUsd: parseFloatOrDefault(maxCost, 1.0),
- maxTotalCostUsd: parseFloatOrDefault(maxTotalCost, 5.0),
+ maxCostUsd: parseCostOrDefault(maxCost, 1.0),
+ maxTotalCostUsd: parseCostOrDefault(maxTotalCost, 5.0),
maxTotalWalltimeMin: parseFloatOrDefault(maxTotalWall, 30),
maxPagesPerTick: parseIntOrDefault(maxPages, 3),
types,
@@ -266,8 +277,10 @@ export async function runPhaseEnrichThin(
pages_skipped_insufficient: totals.skipped_insufficient,
spent_usd: totalSpent,
skipped_by_brain_wide_walltime: skippedByBrainWideWalltime,
- max_cost_usd: cfg.maxCostUsd,
- max_total_cost_usd: cfg.maxTotalCostUsd,
+ // #2504 — Infinity would JSON-serialize to null; report the 'off'
+ // spelling the operator configured instead.
+ max_cost_usd: Number.isFinite(cfg.maxCostUsd) ? cfg.maxCostUsd : 'off',
+ max_total_cost_usd: Number.isFinite(cfg.maxTotalCostUsd) ? cfg.maxTotalCostUsd : 'off',
max_pages_per_tick: cfg.maxPagesPerTick,
types: cfg.types,
order: cfg.order,
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 517e463e4a..de2e3d6d12 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -49,7 +49,7 @@
// sourceId arg — atoms always wrote to 'default' regardless of source,
// which made the NOT EXISTS guard ineffective on federated brains.
-import type { BrainEngine } from '../engine.ts';
+import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
import type { GBrainConfig } from '../config.ts';
import type { ProgressReporter } from '../progress.ts';
@@ -776,6 +776,12 @@ export async function runPhaseExtractAtoms(
// deterministic slugs upsert instead of duplicating.
const hash16 = item.contentHash.slice(0, 16);
const importedSlugs: string[] = [];
+ // #3961: provenance edges source-page → atom, accumulated during the
+ // atom loop and flushed AFTER the completion-receipt flip so a
+ // partially-failed item never banks edges for atoms whose receipt
+ // never flipped. Page-kind items only — transcripts are files, not
+ // pages, so there is no from-endpoint to link.
+ const provenanceLinks: LinkBatchInput[] = [];
for (const atom of atoms) {
const srcRef = item.kind === 'transcript' ? item.filePath : item.slug;
const slug = atomSlug(atom.title, srcRef);
@@ -817,6 +823,15 @@ export async function runPhaseExtractAtoms(
noEmbed: !isAvailable('embedding'),
});
importedSlugs.push(slug);
+ if (item.kind === 'page') {
+ provenanceLinks.push({
+ from_slug: item.slug,
+ to_slug: slug,
+ link_source: 'atom-provenance',
+ from_source_id: sourceId,
+ to_source_id: sourceId,
+ });
+ }
totalAtomsExtracted++;
}
// Completion receipt: flip provisional → real in one statement, then
@@ -828,6 +843,21 @@ export async function runPhaseExtractAtoms(
WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL`,
[hash16, sourceId, importedSlugs],
);
+ // #3961: bank the provenance edges so `gbrain backlinks <source-page>`
+ // and the graph surface atom lineage. ON CONFLICT-deduped by the
+ // batch write, so the deterministic-slug re-run path upserts instead
+ // of duplicating. Best-effort: a link failure must not fail the item
+ // (the receipt already flipped — atoms are safe) but it logs loudly.
+ if (provenanceLinks.length > 0) {
+ try {
+ await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.extract_atoms.provenance' }); // gbrain-allow-direct-insert: atom-provenance edges derived from the extraction itself (no markdown body to reconcile from)
+ } catch (linkErr) {
+ console.error(
+ `[extract_atoms] atom-provenance link batch failed for ${item.kind === 'page' ? item.slug : 'item'}: ` +
+ `${(linkErr as Error).message}`,
+ );
+ }
+ }
if (item.kind === 'page') {
await stampAtomsScanHash(item);
}
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 18d7308aac..78d417a2f3 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -54,6 +54,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';
@@ -71,9 +72,18 @@ import { embed, isAvailable } from '../ai/gateway.ts';
import { isAborted } from '../abort-check.ts';
interface ExistingPageFact {
+ // v0.46 (#3014) — the row's own fact id. Read so the supersession-drift
+ // check can compare the DB's stored `superseded_by` (a fact id) against
+ // the fence reference re-resolved to the target row's current id.
+ id: number | string;
fact: string;
source: string | null;
row_num: number | string | null;
+ // v0.46 (#3014) — supersession columns, read so a struck row whose
+ // fence says "superseded" but whose DB columns are still NULL counts as
+ // drifted and re-heals through the wipe+reinsert fallback.
+ superseded_by: number | string | null;
+ expired_at: Date | string | null;
}
function factContentKey(fact: string, source: string | null | undefined): string {
@@ -123,7 +133,7 @@ async function listExistingFactsForPage(
sourceId: string,
): Promise<ExistingPageFact[]> {
return engine.executeRaw<ExistingPageFact>(
- `SELECT fact, source, row_num
+ `SELECT id, fact, source, row_num, superseded_by, expired_at
FROM facts
WHERE source_id = $1
AND source_markdown_slug = $2
@@ -282,6 +292,21 @@ export async function runExtractFacts(
`fence backfill: \`gbrain apply-migrations --force-retry 0.32.2\` then ` +
`\`gbrain apply-migrations --yes\`. Or drain individual rows via \`forget_fact\`.`,
);
+ // #3683: book the halt BEFORE the early return. The end-of-run rollup
+ // write below is unreachable from this path, so pre-fix a guard-triggered
+ // run recorded NOTHING in extract_rollup_7d — halt_count was structurally
+ // 0 and doctor extract_health's `halt_rate > 10%` warning could never
+ // fire for facts.fence no matter how long the phase stayed jammed.
+ // upsertExtractRollup is best-effort internally (never throws).
+ if (!opts.dryRun) {
+ await upsertExtractRollup(engine, {
+ kind: 'facts.fence',
+ source_id: sourceId,
+ cost_delta: 0,
+ round_completed_delta: 0,
+ halt_delta: 1,
+ });
+ }
return result;
}
@@ -423,27 +448,83 @@ export async function runExtractFacts(
const desired = desiredByKey.get(factContentKey(f.fact, f.source));
return desired !== undefined && Number(f.row_num) !== desired.row_num;
});
+ // v0.46 (#3014) — a struck row whose fence says "superseded" (or
+ // otherwise inactive) but whose DB columns are still NULL has an
+ // identical content key + row_num, so the checks above miss it. Treat
+ // a mismatch between the fence-desired supersession/expiry state and
+ // the DB columns as drift so the wipe+reinsert fallback re-heals the
+ // row (transports superseded_by + expired_at that a pre-fix cycle
+ // dropped).
+ //
+ // The supersession term keys off the RESOLVED reference, not merely
+ // "the fence carries a reference": we re-resolve the fence's
+ // `superseded by #N` against the current DB rows with the SAME resolver
+ // insertFacts uses, then compare the resolved target id to the id the
+ // DB stored. A permanently-unresolvable reference (self / dangling /
+ // chain) resolves to NULL every cycle and matches the DB's NULL, so it
+ // never churns; a pre-fix NULL, or a CHANGED reference (even between two
+ // resolvable targets), still differs and re-heals. Resolution stays
+ // page-local — `superseded by #N` only ever points within this page —
+ // so a row_num → id lookup over `existing` is a faithful mirror of the
+ // insert-time SELECT.
+ const existingByRowNum = new Map<number, ExistingPageFact>();
+ for (const f of existing) {
+ const rn = f.row_num == null ? NaN : Number(f.row_num);
+ if (Number.isFinite(rn)) existingByRowNum.set(rn, f);
+ }
+ const hasSupersessionDrift = existing.some(f => {
+ const desired = desiredByKey.get(factContentKey(f.fact, f.source));
+ if (desired === undefined) return false;
+
+ // Expiry dimension: a struck row must carry expired_at; a pre-fix row
+ // (both columns NULL) drifts here and re-heals. Compare NULL-ness, NOT
+ // the timestamp value: the mapper stamps `expired_at = valid_until ??
+ // today`, so a value comparison would see the stored timestamp differ
+ // from a freshly-recomputed `today` every day and churn the page each
+ // cycle. NULL-ness is the stable "is this row struck?" signal.
+ const desiredExpired = desired.expired_at != null;
+ const dbExpired = f.expired_at != null;
+ if (desiredExpired !== dbExpired) return true;
+
+ // Supersession dimension: resolve the fence reference against the
+ // current DB rows and compare the resolved target id to what the DB
+ // stored.
+ const desiredRow = desired.superseded_by_row;
+ let resolvedTargetId: number | null = null;
+ if (desiredRow !== undefined) {
+ const targetExisting = existingByRowNum.get(desiredRow);
+ const target: SupersedeTarget | undefined = targetExisting
+ ? { id: Number(targetExisting.id), struck: targetExisting.expired_at != null }
+ : undefined;
+ resolvedTargetId = resolveSupersededByRow(Number(f.row_num), desiredRow, target, slug).superseded_by;
+ }
+ const dbTargetId = f.superseded_by == null ? null : Number(f.superseded_by);
+ return resolvedTargetId !== dbTargetId;
+ });
if (
existing.length === extracted.length &&
!hasStaleExisting &&
!hasDuplicateExisting &&
- !hasRowNumDrift
+ !hasRowNumDrift &&
+ !hasSupersessionDrift
) {
continue;
}
let toInsert = extracted.filter(f => !existingKeys.has(factContentKey(f.fact, f.source)));
- if (hasStaleExisting || hasDuplicateExisting || hasRowNumDrift) {
- // Fall back to the legacy page-level reconcile when old DB rows must
- // be removed. Same delete scoping as above: legacy
- // NULL-source_markdown_slug rows, `cli:`-origin conversation
- // facts (#1928), and soft-expired legacy rows (#2646) survive.
- const deleted = await engine.deleteFactsForPage(slug, sourceId, {
- excludeSourcePrefixes: ['cli:'],
- preserveExpiredLegacy: true,
- });
- result.factsDeleted += deleted.deleted;
+ // v0.46 (#3014) — when old DB rows must be removed, defer the wipe into
+ // insertFacts' own transaction (deleteForPageFirst) rather than calling
+ // deleteFactsForPage here. A standalone delete self-commits, so a
+ // failing insert afterward left the page permanently emptied; running
+ // the delete as the first statement of the insert transaction makes the
+ // reconcile atomic — a failed insert rolls the delete back. Same delete
+ // scoping as before: legacy NULL-source_markdown_slug rows, `cli:`-origin
+ // conversation facts (#1928), and soft-expired legacy rows (#2646)
+ // survive.
+ let deleteForPageFirst: { slug: string; excludeSourcePrefixes: string[]; preserveExpiredLegacy: boolean } | undefined;
+ if (hasStaleExisting || hasDuplicateExisting || hasRowNumDrift || hasSupersessionDrift) {
+ deleteForPageFirst = { slug, excludeSourcePrefixes: ['cli:'], preserveExpiredLegacy: true };
toInsert = extracted;
}
@@ -490,8 +571,21 @@ export async function runExtractFacts(
if (toInsert.length === 0) continue;
- const inserted = await engine.insertFacts(toInsert, { source_id: sourceId }); // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
+ const inserted = await engine.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
+ toInsert,
+ { source_id: sourceId },
+ deleteForPageFirst ? { deleteForPageFirst } : undefined,
+ );
result.factsInserted += inserted.inserted;
+ // v0.46 (#3014) — the wipe (when needed) ran inside insertFacts' txn;
+ // count it here from the atomic result rather than a separate delete.
+ result.factsDeleted += inserted.deleted;
+ // v0.46 (#3014) — surface unresolvable `superseded by #N` references
+ // (self / dangling / struck target) as cycle warnings; the row still
+ // inserts with superseded_by NULL + expired_at set (never a guessed FK).
+ // resolveSupersededByRow already prefixes each message with the slug +
+ // row, so push verbatim — no `${slug}: ` re-prefix.
+ for (const w of inserted.warnings) result.warnings.push(w);
}
// v0.42 Wave B3: receipt + rollup. extract_facts is deterministic
@@ -517,12 +611,15 @@ export async function runExtractFacts(
}
}
if (!opts.dryRun) {
+ // #3683: guard-triggered runs return early above (and book their halt
+ // there), so this path is always a completed round — the old
+ // `result.guardTriggered ? … : …` ternaries were dead in their true arm.
await upsertExtractRollup(engine, {
kind: 'facts.fence',
source_id: sourceId,
cost_delta: 0,
- round_completed_delta: result.guardTriggered ? 0 : 1,
- halt_delta: result.guardTriggered ? 1 : 0,
+ round_completed_delta: 1,
+ halt_delta: 0,
});
}
diff --git a/src/core/cycle/filing-rules.ts b/src/core/cycle/filing-rules.ts
index 1b2ed2169c..a675c2eee0 100644
--- a/src/core/cycle/filing-rules.ts
+++ b/src/core/cycle/filing-rules.ts
@@ -115,6 +115,7 @@ function loadFromCandidates(candidates: string[], outputRoot: string): string[]
export async function loadAllowedSlugPrefixes(
outputRoot = 'wiki',
engine?: BrainEngine,
+ namespaces?: DreamNamespaceGlobs,
): Promise<string[]> {
const candidates = [join(process.cwd(), 'skills', '_brain-filing-rules.json')];
if (engine) {
@@ -122,8 +123,39 @@ export async function loadAllowedSlugPrefixes(
if (repo) candidates.push(join(repo, 'skills', '_brain-filing-rules.json'));
}
candidates.push(join(__dirname, '..', '..', '..', 'skills', '_brain-filing-rules.json'));
- return loadFromCandidates(candidates, outputRoot);
+ return appendNamespaceGlobs(loadFromCandidates(candidates, outputRoot), namespaces);
}
-/** Test seam for the candidate-ladder semantics (both fail arms). */
-export const __filingRulesTesting = { loadFromCandidates };
+/**
+ * #4117: per-lane namespace prefixes (already SUMMARY_SLUG_RE-validated by
+ * loadDreamNamespaces in synthesize.ts — this module never sees raw config).
+ */
+export interface DreamNamespaceGlobs {
+ reflectionsPrefix?: string;
+ originalsPrefix?: string;
+}
+
+/**
+ * #4117: derive allow-list globs from the configured per-lane namespaces so
+ * a custom `dream.synthesize.{reflections,originals}_slug_prefix` is
+ * actually writable (the prompt tells the subagent to write there; put_page
+ * enforces this list server-side). FAIL-CLOSED on both edges:
+ * - an empty base list stays empty — the NO_ALLOWLIST hard failure in the
+ * phases must survive, a namespace config can never resurrect a broken
+ * operator file into a partial allow-list;
+ * - only validated prefixes reach this function, so a garbage config value
+ * can never mint a glob.
+ */
+function appendNamespaceGlobs(globs: string[], ns?: DreamNamespaceGlobs): string[] {
+ if (!ns || globs.length === 0) return globs;
+ const out = [...globs];
+ for (const prefix of [ns.reflectionsPrefix, ns.originalsPrefix]) {
+ if (!prefix) continue;
+ const glob = `${prefix}/*`;
+ if (!out.includes(glob)) out.push(glob);
+ }
+ return out;
+}
+
+/** Test seam for the candidate-ladder semantics (both fail arms) + #4117 glob derivation. */
+export const __filingRulesTesting = { loadFromCandidates, appendNamespaceGlobs };
diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts
index 2e07f9bce3..0cd0172596 100644
--- a/src/core/cycle/grade-takes.ts
+++ b/src/core/cycle/grade-takes.ts
@@ -20,15 +20,15 @@
* flag because relaxing after data accumulates silently shifts which
* historical resolutions count as auto-applied.
*
- * Evidence retrieval status (v0.36.1.0 ship state):
- * The default evidence retriever returns an "evidence-retrieval not yet
- * wired" placeholder. Most verdicts produced by the stub-judge against
- * the stub-evidence will be 'unresolvable'. Real retrieval (hybrid search
- * over pages newer than the take's since_date, optionally augmented by a
- * gateway web-search recipe in v0.37+) lands as a follow-up. The phase
- * ships now so the wiring is real and the cache table accumulates
- * verdicts even if early ones are conservative; operators get the
- * end-to-end loop running ahead of the tuned-prompt arrival.
+ * Evidence retrieval (#2811):
+ * The default evidence retriever runs a real hybrid search on the take's
+ * claim (expansion off, source-scoped, the take's own page excluded) and
+ * formats the hits via the pure `formatEvidenceBlock` — each item carries
+ * its slug + effective_date and is annotated relative to the take's
+ * since_date (evidence dated BEFORE the claim is context, not outcome).
+ * Items clamp at ~500 chars; the whole block caps at 4k. Zero hits and
+ * retrieval failures fall back to explicit notes steering the judge to
+ * 'unresolvable' rather than fabricating.
*
* Test seam: opts.judge + opts.evidenceRetriever are injected so the
* phase runs hermetically in unit tests.
@@ -36,6 +36,8 @@
import { createHash } from 'node:crypto';
import { BaseCyclePhase, effectivePhaseDeadlineMs, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
+import { hybridSearch } from '../search/hybrid.ts';
+import type { SearchResult } from '../types.ts';
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } from '../ai/errors.ts';
import { splitProviderModelId } from '../model-id.ts';
@@ -49,9 +51,9 @@ import type { PhaseStatus, CyclePhase } from '../cycle.ts';
* stay valid (composite cache key includes prompt_version); new runs re-spend
* LLM tokens.
*/
-export const GRADE_TAKES_PROMPT_VERSION = 'v0.36.1.0-stub';
+export const GRADE_TAKES_PROMPT_VERSION = 'hybrid-evidence-v1';
-export const GRADE_TAKE_PROMPT = `[v0.36.1.0-stub] You are grading a single forecasting take. The author
+export const GRADE_TAKE_PROMPT = `[hybrid-evidence-v1] You are grading a single forecasting take. The author
made this claim on the given date. Based on the evidence provided, did the
claim turn out to be:
- correct (the world plays out as predicted)
@@ -309,17 +311,101 @@ export function parseJudgeOutput(raw: string): JudgeVerdict | null {
return { verdict, confidence, reasoning };
}
+/** #2811 — evidence retrieval knobs. */
+export const EVIDENCE_SEARCH_LIMIT = 8;
+export const EVIDENCE_ITEM_CLAMP_CHARS = 500;
+export const EVIDENCE_BLOCK_CAP_CHARS = 4000;
+
+/** The narrow slice of a SearchResult the evidence formatter reads. */
+export type EvidenceHit = Pick<SearchResult, 'slug' | 'title' | 'chunk_text' | 'effective_date'>;
+
/**
- * Default evidence retriever — v0.36.1.0 ship-state placeholder. Real
- * retrieval lands in v0.37+ via hybrid search over pages newer than the
- * take's since_date. Documented limitation per CDX-8 + D17.
+ * #2811 — pure evidence-block formatter (unit-testable, no engine).
+ *
+ * Each hit renders as one item carrying its slug + effective_date, annotated
+ * relative to the take's since_date: evidence dated BEFORE the claim can only
+ * be context (it cannot prove an outcome), evidence dated on/after can. Items
+ * clamp at EVIDENCE_ITEM_CLAMP_CHARS; the whole block caps at
+ * EVIDENCE_BLOCK_CAP_CHARS. Zero hits produce an explicit no-evidence note
+ * that steers the judge toward 'unresolvable'.
*/
-export async function defaultEvidenceRetriever(take: Take, _scope: ScopedReadOpts): Promise<string> {
- return `[evidence retrieval not yet wired — v0.36.1.0 ship-state]
-Take claim text (the only "evidence" available pre-T-retrieval-impl):
- ${take.claim}
-Made on: ${take.since_date ?? 'unknown'}
-`;
+export function formatEvidenceBlock(take: Take, hits: EvidenceHit[]): string {
+ const sinceDate = take.since_date ?? 'unknown';
+ if (hits.length === 0) {
+ return (
+ `No evidence found in the brain for this claim (hybrid search returned zero results).\n` +
+ `The claim was made on: ${sinceDate}. With nothing in the brain mentioning the ` +
+ `subject, grade 'unresolvable' — do not fabricate an outcome.`
+ );
+ }
+ const lines: string[] = [];
+ for (const h of hits) {
+ const itemDate = h.effective_date ? String(h.effective_date).slice(0, 10) : null;
+ let recency = '';
+ if (itemDate && take.since_date) {
+ // Lexicographic compare works for ISO prefixes (YYYY-MM vs YYYY-MM-DD:
+ // compare on the shorter's length so a same-month hit counts as after).
+ const cmpLen = Math.min(itemDate.length, take.since_date.length);
+ recency = itemDate.slice(0, cmpLen) >= take.since_date.slice(0, cmpLen)
+ ? ' (dated after the claim)'
+ : ' (dated BEFORE the claim — context only, not outcome evidence)';
+ }
+ const text = (h.chunk_text ?? '').replace(/\s+/g, ' ').trim().slice(0, EVIDENCE_ITEM_CLAMP_CHARS);
+ if (!text) continue;
+ lines.push(`- [${h.slug} • ${itemDate ?? 'undated'}]${recency}\n ${text}`);
+ }
+ if (lines.length === 0) {
+ return (
+ `No usable evidence text found in the brain for this claim.\n` +
+ `The claim was made on: ${sinceDate}. Grade 'unresolvable' — do not fabricate an outcome.`
+ );
+ }
+ let block = lines.join('\n');
+ if (block.length > EVIDENCE_BLOCK_CAP_CHARS) {
+ block = block.slice(0, EVIDENCE_BLOCK_CAP_CHARS) + '\n[evidence truncated]';
+ }
+ return block;
+}
+
+/**
+ * Default evidence retriever (#2811) — real hybrid search on the take's
+ * claim text: expansion off (deterministic, no extra LLM spend), source
+ * scope threaded (federated array beats scalar per sourceScopeOpts), and
+ * the take's OWN page excluded (its body restates the claim — feeding it
+ * back in would let the judge grade a claim against itself). Fail-open:
+ * a retrieval error degrades to a claim-only note steering the judge to
+ * 'unresolvable' rather than aborting the phase.
+ *
+ * Takes the engine explicitly; process() binds it so the injected-seam
+ * type (EvidenceRetrieverFn) is unchanged.
+ */
+export async function defaultEvidenceRetriever(
+ engine: BrainEngine,
+ take: Take,
+ scope: ScopedReadOpts,
+): Promise<string> {
+ try {
+ const hits = await hybridSearch(engine, take.claim, {
+ limit: EVIDENCE_SEARCH_LIMIT,
+ expansion: false,
+ ...(scope.sourceIds && scope.sourceIds.length > 0
+ ? { sourceIds: scope.sourceIds }
+ : scope.sourceId
+ ? { sourceId: scope.sourceId }
+ : {}),
+ ...(take.page_slug ? { exclude_slugs: [take.page_slug] } : {}),
+ });
+ // Belt-and-suspenders on top of exclude_slugs.
+ const filtered = hits.filter((h) => h.slug !== take.page_slug);
+ return formatEvidenceBlock(take, filtered);
+ } catch (err) {
+ return (
+ `[evidence retrieval failed: ${(err as Error).message}]\n` +
+ `Claim: ${take.claim}\n` +
+ `Made on: ${take.since_date ?? 'unknown'}\n` +
+ `With no retrievable evidence, grade 'unresolvable' — do not fabricate an outcome.`
+ );
+ }
}
/**
@@ -414,7 +500,11 @@ class GradeTakesPhase extends BaseCyclePhase {
opts: GradeTakesOpts,
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
const judge = opts.judge ?? defaultJudge;
- const evidenceRetriever = opts.evidenceRetriever ?? defaultEvidenceRetriever;
+ // #2811: bind the engine here so the injected-seam type stays
+ // (take, scope) => Promise<string>.
+ const evidenceRetriever: EvidenceRetrieverFn =
+ opts.evidenceRetriever ??
+ ((take: Take, takeScope: ScopedReadOpts) => defaultEvidenceRetriever(engine, take, takeScope));
const promptVersion = opts.promptVersion ?? GRADE_TAKES_PROMPT_VERSION;
const minAgeMonths = opts.minAgeMonths ?? 6;
const takeLimit = opts.takeLimit ?? 50;
@@ -533,10 +623,14 @@ class GradeTakesPhase extends BaseCyclePhase {
continue;
}
- // Budget pre-check.
+ // Budget pre-check. #2811: the input estimate is size-derived — real
+ // evidence blocks vary from a one-line no-evidence note to the 4k cap,
+ // and the old fixed 1200 underestimated a full block by ~2x.
const budget = this.checkBudget({
modelId: judgeModelId,
- estimatedInputTokens: 1200,
+ estimatedInputTokens: Math.ceil(
+ (GRADE_TAKE_PROMPT.length + take.claim.length + evidence.length) / 4,
+ ),
maxOutputTokens: 400,
});
if (!budget.allowed) {
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index 9205d901ce..0a1c9fb3b7 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -46,6 +46,7 @@ import { normalizeModelId } from '../model-id.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
import { upsertExtractRollup } from '../extract/rollup-writer.ts';
import { GBrainError } from '../types.ts';
+import { isConfigTruthy } from '../config.ts';
import type { OperationContext } from '../operations.ts';
import type { BrainEngine } from '../engine.ts';
import type { PhaseStatus, CyclePhase } from '../cycle.ts';
@@ -160,6 +161,12 @@ export interface ProposeTakesOpts extends BasePhaseOpts {
skipPagesWithFence?: boolean;
/** Override the phase wall-clock deadline (tests). Default: 30 min. */
deadlineMs?: number;
+ /**
+ * #4102 — `gbrain dream --phase propose_takes --once` bypasses the
+ * `cycle.propose_takes.enabled` off switch for THIS call only (mirrors the
+ * conversation_facts_backfill `once` semantics; never reads/writes config).
+ */
+ once?: boolean;
}
export interface ProposeTakesResult {
@@ -180,6 +187,14 @@ export interface ProposeTakesResult {
* hide behind a green summary.
*/
aborted_global_error?: GlobalLlmErrorClass;
+ /**
+ * #3763: set when the page loop halted because EVERY extractor call failed
+ * (zero successes) for EXTRACTOR_FAILURE_HALT_STREAK consecutive pages —
+ * a dead extractor lane (bad model id, broken recipe, systematic truncation)
+ * that would otherwise re-bill every remaining page. Folds into `halted`
+ * and reports the phase as 'fail'.
+ */
+ aborted_failure_streak?: boolean;
/** Extractor calls that returned (idempotency cache hits don't count). */
llm_calls_succeeded: number;
/** Extractor calls that threw (global or per-page alike). */
@@ -286,6 +301,27 @@ export function extractExistingTakesForDedup(pageBody: string): Array<{
/** Per-call wall-clock timeout for the extractor LLM call. */
const EXTRACTOR_CALL_TIMEOUT_MS = 90_000;
+/**
+ * #3763 — output caps for the extractor call. A stopReason 'length' response
+ * at the base cap retries ONCE at the escalated cap (facts/extract.ts #2113
+ * 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).
+ */
+export const PROPOSE_TAKES_MAX_TOKENS = 2048;
+export const PROPOSE_TAKES_RETRY_MAX_TOKENS = 4096;
+
+/**
+ * #3763 — halt streak for a dead extractor lane. When EVERY extractor call in
+ * the run has failed (zero successes) and the failure count reaches this
+ * streak, the page loop halts instead of burning an LLM call (and its input
+ * tokens) on every remaining page. Any single success disarms the halt for
+ * the rest of the run — a mixed run is per-page noise, not a dead lane.
+ * Deliberately NO failure tombstone (#3910 policy): failed pages retry next
+ * cycle once the underlying cause clears.
+ */
+export const EXTRACTOR_FAILURE_HALT_STREAK = 5;
+
/**
* Production extractor — calls gateway.chat with the EXTRACT_TAKES_PROMPT
* and parses the JSON array output. Returns [] on parse failure (logged as
@@ -306,12 +342,35 @@ export async function defaultExtractor(
// 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.
- const result = await gatewayChat({
+ const call = (maxTokens: number) => gatewayChat({
messages: [{ role: 'user', content: prompt }],
...(input.modelHint ? { model: input.modelHint } : {}),
- maxTokens: 2048,
+ maxTokens,
abortSignal: AbortSignal.timeout(EXTRACTOR_CALL_TIMEOUT_MS),
});
+ let result = await call(PROPOSE_TAKES_MAX_TOKENS);
+
+ // #3763: a truncated response (stopReason 'length' — e.g. reasoning tokens
+ // eating the cap, or a dense page extracting many claims) produced
+ // unparseable JSON that the ambiguity guard below rethrew as a GENERIC
+ // 'transient — retry', so the page was re-billed at the same too-small cap
+ // every cycle forever. Retry ONCE at the escalated cap (#2113 parity);
+ // still-truncated throws a message that NAMES the truncation so the phase
+ // 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`,
+ );
+ result = await call(PROPOSE_TAKES_RETRY_MAX_TOKENS);
+ 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`,
+ );
+ }
+ }
// ChatResult.text is already the concatenated text content.
const takes = parseExtractorOutput(result.text);
@@ -496,6 +555,37 @@ class ProposeTakesPhase extends BaseCyclePhase {
_ctx: OperationContext,
opts: ProposeTakesOpts,
): Promise<{ summary: string; details: Record<string, unknown>; status?: PhaseStatus }> {
+ // #4102 — off switch. The phase is ON by default (it ships in the default
+ // phase list), but `gbrain config set cycle.propose_takes.enabled false`
+ // must actually stop the LLM spend. Only an EXPLICIT falsy value skips
+ // (unset = default on, fail-open on read errors so a config-plane blip
+ // never silently disables the phase); `--once` bypasses for one run.
+ if (!opts.once) {
+ let enabledRaw: string | null = null;
+ try {
+ enabledRaw = await engine.getConfig?.('cycle.propose_takes.enabled') ?? null;
+ } catch {
+ enabledRaw = null;
+ }
+ if (enabledRaw != null && !isConfigTruthy(enabledRaw)) {
+ return {
+ summary: 'propose_takes skipped: cycle.propose_takes.enabled=false',
+ details: {
+ reason: 'disabled',
+ enable_hint: 'gbrain config set cycle.propose_takes.enabled true',
+ pages_scanned: 0,
+ cache_hits: 0,
+ cache_misses: 0,
+ proposals_inserted: 0,
+ tombstones_written: 0,
+ budget_exhausted: false,
+ warnings: [],
+ },
+ status: 'skipped',
+ };
+ }
+ }
+
const extractor = opts.extractor ?? defaultExtractor;
const promptVersion = opts.promptVersion ?? PROPOSE_TAKES_PROMPT_VERSION;
const pageLimit = opts.pageLimit ?? 100;
@@ -693,6 +783,22 @@ class ProposeTakesPhase extends BaseCyclePhase {
break;
}
result.warnings.push(detail);
+ // #3763: N consecutive failures with ZERO successes = dead lane.
+ // Halt instead of spending an LLM call on every remaining page. A
+ // single success anywhere in the run keeps llm_calls_succeeded > 0
+ // and permanently disarms this halt (mixed runs are per-page noise).
+ if (
+ result.llm_calls_succeeded === 0 &&
+ result.llm_calls_failed >= EXTRACTOR_FAILURE_HALT_STREAK
+ ) {
+ result.aborted_failure_streak = true;
+ result.warnings.push(
+ `aborting phase at page ${result.pages_scanned}/${pages.length}: ` +
+ `${result.llm_calls_failed} consecutive extractor failures with zero successes — ` +
+ `halting to avoid re-billing every remaining page (no tombstones written; pages retry next cycle)`,
+ );
+ break;
+ }
continue;
}
result.llm_calls_succeeded += 1;
@@ -794,7 +900,8 @@ class ProposeTakesPhase extends BaseCyclePhase {
const halted =
result.budget_exhausted ||
result.deadline_hit === true ||
- result.aborted_global_error !== undefined;
+ result.aborted_global_error !== undefined ||
+ result.aborted_failure_streak === true;
await upsertExtractRollup(engine, {
kind: 'takes.proposed',
source_id: sourceIdForReceipt,
@@ -810,14 +917,20 @@ class ProposeTakesPhase extends BaseCyclePhase {
// the autopilot handler deliberately does not throw on partial). A halt
// after some successes is a partial run → 'warn'.
const warningCount = result.warnings.length;
+ // #3763: an all-failures streak halt is the same severity as a
+ // zero-success global halt — the whole extractor lane is down.
const phaseFailed =
- result.aborted_global_error !== undefined && result.llm_calls_succeeded === 0;
+ (result.aborted_global_error !== undefined && result.llm_calls_succeeded === 0) ||
+ result.aborted_failure_streak === true;
return {
summary:
`propose_takes: scanned ${result.pages_scanned} pages, ${result.cache_hits} cached, ${result.proposals_inserted} new proposals, ${result.tombstones_written} empty (run ${proposalRunId})` +
(result.aborted_global_error
? `; aborted on ${result.aborted_global_error} error after ${result.pages_scanned} page(s)`
: '') +
+ (result.aborted_failure_streak
+ ? `; aborted after ${result.llm_calls_failed} consecutive extractor failures (zero successes)`
+ : '') +
(warningCount > 0 ? ` (${warningCount} warning(s))` : ''),
details: { ...result, halted, proposal_run_id: proposalRunId, prompt_version: promptVersion },
status: phaseFailed ? 'fail' : halted || warningCount > 0 ? 'warn' : 'ok',
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 1a4ee9428b..c0cefff079 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -522,7 +522,12 @@ export async function runPhaseSynthesize(
// Fan-out: submit one subagent per worth-processing transcript (or one
// per chunk for transcripts that exceed the model's per-prompt budget).
- const allowedSlugPrefixes = await loadAllowedSlugPrefixes(config.outputRoot, engine);
+ // #4117: the validated per-lane namespaces derive extra allow-list globs
+ // so a custom reflections/originals prefix is actually writable.
+ const allowedSlugPrefixes = await loadAllowedSlugPrefixes(config.outputRoot, engine, {
+ reflectionsPrefix: config.reflectionsPrefix,
+ originalsPrefix: config.originalsPrefix,
+ });
if (allowedSlugPrefixes.length === 0) {
return failed(makeError('InternalError', 'NO_ALLOWLIST',
'skills/_brain-filing-rules.json missing dream_synthesize_paths.globs'));
@@ -724,6 +729,9 @@ export async function runPhaseSynthesize(
buildTriageMapBlock(triageVerdict, chunks[i], chunks.length),
manifestBlock,
allowedSlugPrefixes,
+ // #4117: validated per-lane namespaces.
+ config.reflectionsPrefix,
+ config.originalsPrefix,
),
model: subagentModel,
max_turns: config.maxTurns,
@@ -1228,6 +1236,13 @@ export interface SynthConfig {
* grammar; invalid values fall back to 'wiki' with a stderr warning.
*/
outputRoot: string;
+ /**
+ * #4117: per-lane namespaces (see loadDreamNamespaces). Defaults derive
+ * from outputRoot; config keys dream.synthesize.reflections_slug_prefix /
+ * dream.synthesize.originals_slug_prefix override them individually.
+ */
+ reflectionsPrefix: string;
+ originalsPrefix: string;
subagentTimeoutMs: number;
subagentWaitTimeoutMs: number;
/**
@@ -1274,6 +1289,47 @@ export async function loadOutputRoot(engine: BrainEngine): Promise<string> {
return 'wiki';
}
+/**
+ * #4117: per-lane output namespaces. `dream.synthesize.output_root` moves
+ * the whole tree; these two keys move the REFLECTIONS and ORIGINALS lanes
+ * individually (brains whose schema has no `personal/reflections` /
+ * `originals/ideas` convention). SUMMARY_SLUG_RE-validated with a stderr
+ * warning + default fallback — an invalid value can never leak an
+ * unvalidated prefix into the prompt or the write allow-list (fail-closed:
+ * the derived allow-list glob only ever comes from a validated prefix).
+ * Mirrors the `dream.patterns.{source,output}_slug_prefix` shape.
+ */
+export interface DreamNamespaces {
+ /** Where reflections land. Config `dream.synthesize.reflections_slug_prefix`; default `<output_root>/personal/reflections`. */
+ reflectionsPrefix: string;
+ /** Where originals land. Config `dream.synthesize.originals_slug_prefix`; default `<output_root>/originals/ideas`. */
+ originalsPrefix: string;
+}
+
+export async function loadDreamNamespaces(
+ engine: BrainEngine,
+ outputRoot: string,
+): Promise<DreamNamespaces> {
+ const resolvePrefix = async (key: string, fallback: string): Promise<string> => {
+ const raw = await engine.getConfig(key);
+ if (!raw) return fallback;
+ const trimmed = raw.trim().replace(/^\/+|\/+$/g, '');
+ if (SUMMARY_SLUG_RE.test(trimmed)) return trimmed;
+ process.stderr.write(
+ `[dream] ${key} "${raw}" is not a valid slug prefix; falling back to "${fallback}".\n`,
+ );
+ return fallback;
+ };
+ return {
+ reflectionsPrefix: await resolvePrefix(
+ 'dream.synthesize.reflections_slug_prefix', `${outputRoot}/personal/reflections`,
+ ),
+ originalsPrefix: await resolvePrefix(
+ 'dream.synthesize.originals_slug_prefix', `${outputRoot}/originals/ideas`,
+ ),
+ };
+}
+
export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig> {
const enabledRaw = await engine.getConfig('dream.synthesize.enabled');
const corpusDir = await engine.getConfig('dream.synthesize.session_corpus_dir');
@@ -1377,6 +1433,10 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>
}
}
+ // #4117: resolve the root once, then the per-lane namespaces from it.
+ const outputRoot = await loadOutputRoot(engine);
+ const namespaces = await loadDreamNamespaces(engine, outputRoot);
+
return {
enabled,
corpusDir: corpusDir ?? null,
@@ -1397,7 +1457,9 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>
cooldownHours,
maxPromptTokens,
maxChunksPerTranscript,
- outputRoot: await loadOutputRoot(engine),
+ outputRoot,
+ // #4117: per-lane namespaces derived from outputRoot unless overridden.
+ ...namespaces,
subagentTimeoutMs,
subagentWaitTimeoutMs,
inlineConcurrency,
@@ -2284,6 +2346,11 @@ function buildSynthesisPrompt(
triageMapBlock = '',
linkManifestBlock = '',
allowedSlugPrefixes: string[] = [],
+ // #4117: per-lane namespaces. Defaults derive from outputRoot so existing
+ // callers/tests are byte-identical; loadSynthConfig passes the validated
+ // config-resolved values.
+ reflectionsPrefix = `${outputRoot}/personal/reflections`,
+ originalsPrefix = `${outputRoot}/originals/ideas`,
): string {
const dateHint = t.inferredDate ?? today();
const baseSlugSegment = sanitizeForSlug(t.basename) || `session-${dateHint}`;
@@ -2325,10 +2392,10 @@ OUTPUT POLICY (ALL of these are required)
TASKS
A. Reflections (self-knowledge, pattern recognition, emotional processing):
- slug: \`${outputRoot}/personal/reflections/${dateHint}-<topic-slug>-${hashSuffix}\`
+ slug: \`${reflectionsPrefix}/${dateHint}-<topic-slug>-${hashSuffix}\`
B. Originals (new ideas, frames, theses, mental models):
- slug: \`${outputRoot}/originals/ideas/${dateHint}-<idea-slug>-${hashSuffix}\`
+ slug: \`${originalsPrefix}/${dateHint}-<idea-slug>-${hashSuffix}\`
C. People mentions: ${linkManifestBlock ? 'check LINK CANDIDATES (and the search tool, when available) first' : 'search first, when a search tool is available'}; never write over an existing person page (the orchestrator handles people enrichment via timeline entries — your job is the reflection/original synthesis, NOT modifying existing person pages).
diff --git a/src/core/db-lock.ts b/src/core/db-lock.ts
index 8e95b12091..a647ae0dc8 100644
--- a/src/core/db-lock.ts
+++ b/src/core/db-lock.ts
@@ -379,6 +379,92 @@ export async function tryAcquireDbLock(
return null;
}
+/** Options for waitForDbLockTakeover (#2308). */
+export interface WaitForTakeoverOpts {
+ /** Poll cadence in ms (default 15s). */
+ pollMs?: number;
+ /**
+ * Hard wait bound in ms. Default: TTL + steal grace + 60s margin — the
+ * worst-case window after which a DEAD holder's row is structurally
+ * takeable by the normal upsert.
+ */
+ maxWaitMs?: number;
+ /** Called once per still-waiting poll (loud-wait logging seam). */
+ onWait?: (info: { snapshot: LockSnapshot | null; waitedMs: number; maxWaitMs: number }) => void;
+ /** Test seam: sleep implementation (default setTimeout). */
+ sleep?: (ms: number) => Promise<void>;
+}
+
+/**
+ * #2308 — bounded wait for a dead holder's lock to become takeable.
+ *
+ * The gap: a CROSS-HOST holder that died leaves a row whose TTL is still
+ * live. `tryAcquireDbLock` correctly refuses to steal it (process.kill is
+ * meaningless remotely → classify `cross_host`), so a one-shot caller (the
+ * minion supervisor's start) exits LOCK_HELD even though the lock frees
+ * itself within TTL + steal-grace. This helper polls the normal acquire up
+ * to that bound instead of failing fast — turning "dead holder on another
+ * host" from an operator page into a self-healing wait.
+ *
+ * ALIVE holders are detected early and bailed on: a holder whose
+ * `last_refreshed_at` ADVANCES between polls is actively heartbeating —
+ * return null immediately rather than burning the full window. A holder
+ * REPLACED by a different (pid, host) while we waited also returns null
+ * (someone else won the takeover; they are alive by construction).
+ *
+ * Never throws for data reasons; poll errors degrade to the next poll.
+ */
+export async function waitForDbLockTakeover(
+ engine: BrainEngine,
+ lockId: string,
+ ttlMinutes: number = DEFAULT_TTL_MINUTES,
+ opts: WaitForTakeoverOpts = {},
+): Promise<DbLockHandle | null> {
+ const pollMs = Math.max(50, opts.pollMs ?? 15_000);
+ const stealGraceSeconds = resolveStealGraceSeconds(ttlMinutes);
+ const maxWaitMs = opts.maxWaitMs ?? (ttlMinutes * 60 + stealGraceSeconds + 60) * 1000;
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const start = Date.now();
+
+ let baseline: LockSnapshot | null = null;
+ try {
+ baseline = await inspectLock(engine, lockId);
+ } catch {
+ /* observe from the first poll instead */
+ }
+
+ for (;;) {
+ const handle = await tryAcquireDbLock(engine, lockId, ttlMinutes);
+ if (handle) return handle;
+
+ let snap: LockSnapshot | null = null;
+ try {
+ snap = await inspectLock(engine, lockId);
+ } catch {
+ /* transient read failure — keep waiting within the bound */
+ }
+ if (snap && baseline) {
+ const sameHolder =
+ snap.holder_pid === baseline.holder_pid && snap.holder_host === baseline.holder_host;
+ if (!sameHolder) return null; // replaced by a live winner while we waited
+ if (
+ snap.last_refreshed_at &&
+ baseline.last_refreshed_at &&
+ snap.last_refreshed_at.getTime() > baseline.last_refreshed_at.getTime()
+ ) {
+ return null; // heartbeat advanced — holder is alive, stop waiting
+ }
+ } else if (snap && !baseline) {
+ baseline = snap; // row appeared after our first look — start observing it
+ }
+
+ const waitedMs = Date.now() - start;
+ if (waitedMs >= maxWaitMs) return null;
+ opts.onWait?.({ snapshot: snap, waitedMs, maxWaitMs });
+ await sleep(Math.min(pollMs, maxWaitMs - waitedMs));
+ }
+}
+
/**
* v0.41.6.0 D3: inspect the current holder of a named lock.
*
diff --git a/src/core/db.ts b/src/core/db.ts
index 7d89413dfa..35cdf0e563 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,6 +1,6 @@
import postgres from 'postgres';
import { GBrainError, type EngineConfig } from './types.ts';
-import { SCHEMA_SQL } from './schema-embedded.ts';
+import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import type { BrainEngine } from './engine.ts';
import { verifySchema } from './schema-verify.ts';
import { isRetryableConnError } from './retry-matcher.ts';
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 3be5fdf554..c9ad93328d 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -60,6 +60,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'calibration_freshness',
'child_table_orphans',
'chronicle_projection_health',
+ 'code_chunk_metadata',
'content_hash_duplicates',
'content_sanity_audit_recent',
'contextual_retrieval_coverage',
@@ -94,6 +95,10 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'image_assets',
'integrity',
'jsonb_integrity',
+ // #4222 — near-empty entity pages that accreted huge edge counts (junk
+ // hubs polluting the graph): a data-quality signal, sibling of
+ // scraper_junk_pages / graph_coverage.
+ 'junk_entity_hubs',
'link_resolution_opportunity',
'links_extraction_lag',
'markdown_body_completeness',
@@ -109,6 +114,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'scraper_junk_pages',
'source_config_shape',
'source_routing_health',
+ 'stale_mentions',
'stub_guard_24h',
'sync_failures',
'sync_freshness',
@@ -209,6 +215,10 @@ export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
'minions_migration',
'multi_source_drift',
'pack_upgrade_available',
+ // #550 — pages UNIQUE(source_id, slug) upsert arbiter presence: schema
+ // coherence healed by `gbrain apply-migrations` (sibling of
+ // timeline_dedup_index / schema_version).
+ 'pages_upsert_arbiter',
'schema_pack_active',
'schema_pack_consistency',
'schema_pack_source_drift',
diff --git a/src/core/embed-retry.ts b/src/core/embed-retry.ts
new file mode 100644
index 0000000000..38c1d258f4
--- /dev/null
+++ b/src/core/embed-retry.ts
@@ -0,0 +1,297 @@
+/**
+ * Embed retry/backoff primitives + the title-tier restamp helper, peeled from
+ * `src/commands/embed.ts` (mw2 layering fix).
+ *
+ * Why a core module: `src/core/import-file.ts` and `src/core/embed-stale.ts`
+ * consume `embedBatchWithBackoff` / `restampIfDemotedToTitleTier`. When these
+ * lived in the commands layer, every import-file consumer (sync, ops/pages,
+ * operations.ts, MCP) eagerly loaded the embed COMMAND module, and any future
+ * value import of operations.ts from embed.ts's closure would complete a real
+ * ESM cycle — the exact class that produced a prior release's module-cycle
+ * break. `src/commands/embed.ts` re-exports everything here (façade rule), so
+ * historical import sites and tests never chase the peel.
+ */
+
+import { embedBatch } from './embedding.ts';
+import { serr } from './console-prefix.ts';
+import { titleTierCorpusGeneration } from './contextual-retrieval-service.ts';
+import type { BrainEngine } from './engine.ts';
+import type { Page } from './types.ts';
+
+/**
+ * #3507 — after a plain re-embed fully re-embedded a `per_chunk_synopsis`
+ * page at the title-only tier (see wrapChunkTextsForStoredMode), restamp the
+ * page's CR state to 'title' so `contextual_retrieval_mode` keeps describing
+ * the vectors actually in the column. The reindex sweep restores the synopsis
+ * tier later. No-op for every other mode.
+ */
+export async function restampIfDemotedToTitleTier(
+ engine: BrainEngine,
+ page: Pick<Page, 'contextual_retrieval_mode'> | null | undefined,
+ slug: string,
+ sourceId: string,
+): Promise<void> {
+ if (page?.contextual_retrieval_mode !== 'per_chunk_synopsis') return;
+ await engine.updatePageContextualRetrievalState(slug, sourceId, 'title', titleTierCorpusGeneration());
+}
+
+/**
+ * v0.33.3: rate-limit-aware embedBatch wrapper.
+ * #3966: also retries transient gateway errors (502/503/504) that NIM and
+ * similar providers emit under sustained bulk load.
+ *
+ * The OpenAI SDK has built-in retry with exponential backoff, but its
+ * backoff window (max ~4s) is too short for TPM (tokens-per-minute)
+ * rate limits on large pages (~90K tokens). This wrapper catches
+ * 429-shaped and gateway-overload errors, parses the retry delay from
+ * the error message (e.g. "Please try again in 248ms"), and sleeps before retrying.
+ *
+ * v0.33.4 hardening (codex + re-review findings):
+ * - D4: detect 429 via the wrapped error's `cause.status` (the gateway's
+ * normalizeAIError stores the original error there). Bare `e.status`
+ * never fires against an `AITransientError` wrap. Message-match stays
+ * as a fallback.
+ * - D4a: pass `maxRetries: 0` through `embedBatch` so the AI SDK's
+ * default 2-retry stack doesn't multiply this wrapper's 5 attempts.
+ * - D2: jitter the parsed delay ±30% so 20 concurrent workers don't
+ * resynchronize on the next 429 wave.
+ * - D3a/D8: when an external AbortSignal fires (wall-clock budget), the
+ * sleep wakes up early AND the abortSignal is threaded into the gateway
+ * embed call so an in-flight HTTP request cancels too.
+ *
+ * Up to MAX_RATE_LIMIT_RETRIES attempts with the parsed (jittered) delay
+ * (or a 60s fallback when the message can't be parsed).
+ *
+ * @internal Exported for unit tests; not part of the public surface.
+ */
+export const MAX_RATE_LIMIT_RETRIES = 5;
+export const RATE_LIMIT_FALLBACK_MS = 60_000;
+export const RATE_LIMIT_PAD_MS = 500;
+export const RATE_LIMIT_JITTER = 0.3;
+
+export interface EmbedBatchWithBackoffOpts {
+ abortSignal?: AbortSignal;
+}
+
+/**
+ * Walk the cause chain looking for a 429 status. The current
+ * `normalizeAIError` wraps once into `AITransientError` with `cause = original`,
+ * so one level is sufficient — but iterate to handle future wrap layers
+ * defensively (max 5 levels to bound a malformed cyclic chain).
+ *
+ * @internal exported for unit tests.
+ */
+export function detect429FromCause(e: unknown): boolean {
+ let cur: unknown = e;
+ for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
+ const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
+ if (obj.status === 429 || obj.statusCode === 429) return true;
+ cur = obj.cause;
+ }
+ return false;
+}
+
+/** Gateway overload statuses retried with the same backoff as 429 (#3966). */
+const RETRIABLE_GATEWAY_STATUSES = new Set([502, 503, 504]);
+
+/**
+ * Walk the cause chain looking for 502/503/504. Same depth bound as
+ * detect429FromCause — one normalizeAIError wrap is typical.
+ *
+ * @internal exported for unit tests.
+ */
+export function detectGatewayErrorFromCause(e: unknown): boolean {
+ let cur: unknown = e;
+ for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
+ const obj = cur as { status?: unknown; statusCode?: unknown; cause?: unknown };
+ const status = obj.status ?? obj.statusCode;
+ if (typeof status === 'number' && RETRIABLE_GATEWAY_STATUSES.has(status)) return true;
+ cur = obj.cause;
+ }
+ return false;
+}
+
+/**
+ * Parse a Retry-After hint out of an OpenAI-style 429 message. Falls back
+ * to `RATE_LIMIT_FALLBACK_MS` when the message can't be parsed. Adds
+ * `RATE_LIMIT_PAD_MS` padding and `RATE_LIMIT_JITTER` randomization so
+ * concurrent workers don't resynchronize.
+ *
+ * @internal exported for unit tests.
+ */
+export function parseRetryDelayMs(msg: string, rng: () => number = Math.random): number {
+ let delayMs = RATE_LIMIT_FALLBACK_MS;
+ const msMatch = msg.match(/try again in (\d+)ms/i);
+ const secMatch = msg.match(/try again in ([\d.]+)s/i);
+ if (msMatch) delayMs = parseInt(msMatch[1], 10) + RATE_LIMIT_PAD_MS;
+ else if (secMatch) delayMs = Math.ceil(parseFloat(secMatch[1]) * 1000) + RATE_LIMIT_PAD_MS;
+ // D2: ±30% jitter to decorrelate the herd of 20 workers.
+ const jitterFactor = 1 + (rng() * 2 - 1) * RATE_LIMIT_JITTER;
+ return Math.max(1, Math.floor(delayMs * jitterFactor));
+}
+
+/**
+ * #3796 — attempt-scaled floor for 429 waits. Providers with ROLLING
+ * per-minute token budgets (TPM) return tiny Retry-After hints ("try again
+ * in 132ms") that are honest about the next REQUEST slot but not about the
+ * token budget: five hint-sized waits burn every retry inside the same TPM
+ * minute and the batch fails despite the limit being about to clear.
+ * Escalating floors guarantee the retry ladder spans the rolling window
+ * (sum ≈ 120s ≫ 60s even at -30% jitter) while a LARGER provider hint still
+ * wins (a 4-minute Retry-After must be honored, not floored down).
+ */
+export const RATE_LIMIT_ATTEMPT_FLOOR_MS = [1_000, 4_000, 10_000, 30_000, 75_000] as const;
+
+let _rateLimitFloorsMs: readonly number[] = RATE_LIMIT_ATTEMPT_FLOOR_MS;
+
+/**
+ * Test seam: shrink the #3796 floors so sustained-429 exhaustion tests don't
+ * spend ~2min of real wall clock (the production ladder's whole point).
+ * Pass null to restore. @internal
+ */
+export function _setRateLimitFloorsForTests(floors: readonly number[] | null): void {
+ _rateLimitFloorsMs = floors ?? RATE_LIMIT_ATTEMPT_FLOOR_MS;
+}
+
+/**
+ * #3796 — the effective 429 wait: max(jittered provider hint, jittered
+ * attempt-scaled floor). Keeps parseRetryDelayMs's contract (hint + pad +
+ * jitter) intact for its other consumers/tests; the floor gets its own
+ * jitter so a floored herd doesn't resynchronize.
+ *
+ * @internal exported for unit tests.
+ */
+export function rateLimitDelayMs(
+ msg: string,
+ attempt: number,
+ rng: () => number = Math.random,
+): number {
+ const hinted = parseRetryDelayMs(msg, rng);
+ const floorIdx = Math.min(Math.max(attempt, 0), _rateLimitFloorsMs.length - 1);
+ const jitterFactor = 1 + (rng() * 2 - 1) * RATE_LIMIT_JITTER;
+ const floored = Math.max(1, Math.floor(_rateLimitFloorsMs[floorIdx] * jitterFactor));
+ return Math.max(hinted, floored);
+}
+
+/**
+ * Sleep for `ms` milliseconds. Resolves early (not rejects) when `signal`
+ * fires, so the retry loop's caller can re-check `signal.aborted` and
+ * exit cleanly without an unhandled rejection.
+ *
+ * NOTE: distinct contract from `src/core/retry.ts:abortableSleep`, which
+ * REJECTS with RetryAbortError on abort. This one resolves.
+ *
+ * @internal exported for unit tests.
+ */
+export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve();
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+}
+
+export async function embedBatchWithBackoff(
+ texts: string[],
+ opts: EmbedBatchWithBackoffOpts = {},
+): Promise<Float32Array[]> {
+ const signal = opts.abortSignal;
+ for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
+ if (signal?.aborted) throw new Error('embed budget aborted');
+ try {
+ // D4a + D8: maxRetries:0 disables the SDK's stacked retries (so this
+ // wrapper is the single source of truth) and abortSignal threads
+ // through to the gateway so an in-flight HTTP request cancels mid-fetch.
+ return await embedBatch(texts, { maxRetries: 0, ...(signal && { abortSignal: signal }) });
+ } catch (e: unknown) {
+ // If the budget fired we may have been aborted mid-fetch; bubble out.
+ // This check is what keeps caller-initiated aborts out of BOTH retry
+ // branches below (#3374) — an abort is never reclassified as transient.
+ if (signal?.aborted) throw e;
+ const msg = e instanceof Error ? e.message : String(e);
+ const rateLimitish = isEmbedRetriableError(e);
+ // #3374 — transient NETWORK blips (socket timeout / conn reset) get a
+ // plain bounded backoff beside the 429/gateway retry-after path.
+ const netTransient = !rateLimitish && isTransientNetworkEmbedError(e);
+ if ((!rateLimitish && !netTransient) || attempt === MAX_RATE_LIMIT_RETRIES) throw e;
+
+ // #3796: 429s take the attempt-floored wait (rolling-TPM-aware);
+ // network blips keep their own bounded exponential ladder.
+ const delayMs = rateLimitish ? rateLimitDelayMs(msg, attempt) : transientBackoffMs(attempt);
+ // One label for every retriable class — 429, gateway and network blips share the loop.
+ serr(` [embed-retry] attempt ${attempt + 1}/${MAX_RATE_LIMIT_RETRIES}, waiting ${delayMs}ms...`);
+ await abortableSleep(delayMs, signal);
+ }
+ }
+ // Unreachable, but TypeScript needs it.
+ return embedBatch(texts);
+}
+
+/**
+ * Retriable embed errors: 429 rate limits plus transient gateway overload
+ * (502/503/504). Shared by embedBatchWithBackoff (retry decision) and
+ * embedPageTexts (fan-out decision). D4: structured detection first
+ * (gateway-wrapped errors via cause chain); message-match as fallback for
+ * providers whose wrappers strip `cause.status`.
+ */
+export function isEmbedRetriableError(e: unknown): boolean {
+ const msg = e instanceof Error ? e.message : String(e);
+ return (
+ detect429FromCause(e) ||
+ detectGatewayErrorFromCause(e) ||
+ /rate.?limit|429/i.test(msg) ||
+ /bad gateway|502|503|504|service unavailable|gateway timeout/i.test(msg)
+ );
+}
+
+/** #3374 — plain bounded backoff knobs for transient network errors. */
+export const TRANSIENT_NET_BASE_MS = 1_000;
+export const TRANSIENT_NET_MAX_MS = 15_000;
+
+/**
+ * #3374 — plain bounded exponential backoff for transient network errors.
+ * There is no retry-after header to parse on a conn-reset, and the 429
+ * fallback (60s) is wildly oversized for a socket blip: base × 2^attempt,
+ * capped, with the same ±30% jitter as the rate-limit path.
+ *
+ * @internal exported for unit tests.
+ */
+export function transientBackoffMs(attempt: number, rng: () => number = Math.random): number {
+ const raw = Math.min(TRANSIENT_NET_BASE_MS * 2 ** attempt, TRANSIENT_NET_MAX_MS);
+ const jitterFactor = 1 + (rng() * 2 - 1) * RATE_LIMIT_JITTER;
+ return Math.max(1, Math.floor(raw * jitterFactor));
+}
+
+/**
+ * #3374 — transient NETWORK failures: socket timeouts, connection resets,
+ * DNS blips. Structured detection first (error `code` / TimeoutError name
+ * through the cause chain, matching statusFromCause's walk), message-match
+ * fallback for wrappers that strip the code. Deliberately does NOT match
+ * caller-initiated aborts: the retry loop re-checks `signal.aborted` BEFORE
+ * classification, and nothing abort-shaped appears in these patterns.
+ *
+ * @internal exported for unit tests.
+ */
+export function isTransientNetworkEmbedError(e: unknown): boolean {
+ const TRANSIENT_CODES = /^(ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|EPIPE|ECONNABORTED|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|UND_ERR_HEADERS_TIMEOUT|UND_ERR_BODY_TIMEOUT|UND_ERR_SOCKET)$/;
+ let cur: unknown = e;
+ for (let depth = 0; depth < 5 && cur !== undefined && cur !== null; depth++) {
+ const obj = cur as { code?: unknown; name?: unknown; cause?: unknown };
+ if (typeof obj.code === 'string' && TRANSIENT_CODES.test(obj.code)) return true;
+ if (obj.name === 'TimeoutError') return true;
+ cur = obj.cause;
+ }
+ const msg = e instanceof Error ? e.message : String(e);
+ return /\b(ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|EPIPE|EAI_AGAIN)\b|socket hang up|fetch failed|connect(ion)? timeout|connection (reset|closed)|network (error|timeout)|request timed out|timed out/i.test(msg);
+}
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 7210780c1b..c22c15a695 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -19,7 +19,7 @@
import type { BrainEngine } from './engine.ts';
import type { Chunk, ChunkInput } from './types.ts';
-import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from '../commands/embed.ts';
+import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from './embed-retry.ts';
import { wrapChunkTextsForStoredMode } from './embedding-context.ts';
import { invalidateStaleSignatureEmbeddingsGuarded } from './embedding-invalidation.ts';
import {
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index edcba1ba2a..241c438e73 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -34,12 +34,17 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
'openai:text-embedding-3-small': { pricePerMTok: 0.02 },
// Legacy OpenAI ada (still common in older brains)
'openai:text-embedding-ada-002': { pricePerMTok: 0.10 },
- // Voyage (https://docs.voyageai.com/docs/pricing, verified 2026-08-15)
+ // Voyage (https://docs.voyageai.com/docs/pricing, verified 2026-08-21)
'voyage:voyage-4-large': { pricePerMTok: 0.12 },
'voyage:voyage-4': { pricePerMTok: 0.06 },
'voyage:voyage-4-lite': { pricePerMTok: 0.02 },
'voyage:voyage-code-4': { pricePerMTok: 0.12 },
- // Voyage rerankers (same pricing page, verified 2026-08-15). Same
+ // Domain + multimodal models (current-models section; multimodal rate is
+ // per 1M TEXT tokens — image pixel-token pricing is out of scope here).
+ 'voyage:voyage-finance-2': { pricePerMTok: 0.12 },
+ 'voyage:voyage-law-2': { pricePerMTok: 0.12 },
+ 'voyage:voyage-multimodal-3': { pricePerMTok: 0.12 },
+ // Voyage rerankers (same pricing page, verified 2026-08-21). Same
// budget-tracker rerank-kind fallback rationale as the zerank-2 row below.
'voyage:rerank-2.5': { pricePerMTok: 0.05 },
'voyage:rerank-2.5-lite': { pricePerMTok: 0.02 },
@@ -49,8 +54,14 @@ export const EMBEDDING_PRICING: Record<string, EmbeddingPricing> = {
// hosted API; no entry means lookupEmbeddingPrice returns `unknown` and the
// caller prints "estimate unavailable" instead of a wrong number.
// Legacy Voyage models (same page, "older models" section — no free tokens):
+ // #4344: voyage-3.5 / voyage-3.5-lite are in the hosted recipe list but had
+ // no rows, so upgrade cost estimates showed "unavailable" for their users.
+ 'voyage:voyage-3.5': { pricePerMTok: 0.06 },
+ 'voyage:voyage-3.5-lite': { pricePerMTok: 0.02 },
'voyage:voyage-3-large': { pricePerMTok: 0.18 },
'voyage:voyage-3': { pricePerMTok: 0.06 },
+ 'voyage:voyage-3-lite': { pricePerMTok: 0.02 },
+ 'voyage:voyage-code-3': { pricePerMTok: 0.18 },
// ZeroEntropy (https://www.zeroentropy.dev/pricing, verified 2026-07-28)
'zeroentropyai:zembed-1': { pricePerMTok: 0.05 },
// ZeroEntropy reranker (docs/ai-providers/zeroentropy.md — $0.025/1M tokens).
@@ -100,6 +111,18 @@ export function lookupEmbeddingPrice(modelString: string): PriceLookupResult {
const aliasHit = EMBEDDING_PRICING[aliasKey];
if (aliasHit) return { kind: 'known', pricePerMTok: aliasHit.pricePerMTok, key: aliasKey };
}
+ // #2504 — nested gateway ids: router providers wrap the upstream vendor in
+ // the model segment ('openrouter:openai/text-embedding-3-large'). On a
+ // miss, re-key on the nested vendor prefix and retry (provider aliases
+ // included via the recursion) — routers bill the upstream vendor's
+ // per-token rate, so the vendor row is the honest estimate. No nested
+ // match → still `unknown` (fail closed, never fabricate). Bounded: each
+ // recursion strips one '/segment'.
+ const slash = model.indexOf('/');
+ if (slash > 0 && slash < model.length - 1) {
+ const nested = lookupEmbeddingPrice(`${model.slice(0, slash)}:${model.slice(slash + 1)}`);
+ if (nested.kind === 'known') return nested;
+ }
return { kind: 'unknown', provider, model };
}
diff --git a/src/core/engine-factory.ts b/src/core/engine-factory.ts
index 0ec35b7ebc..bd1676dec1 100644
--- a/src/core/engine-factory.ts
+++ b/src/core/engine-factory.ts
@@ -1,5 +1,6 @@
import type { BrainEngine } from './engine.ts';
import type { EngineConfig } from './types.ts';
+import { setChatUsageSink, makeEngineChatUsageSink } from './ai/chat-usage.ts';
/**
* Create an engine instance based on config.
@@ -8,19 +9,31 @@ import type { EngineConfig } from './types.ts';
export async function createEngine(config: EngineConfig): Promise<BrainEngine> {
const engineType = config.engine || 'postgres';
- switch (engineType) {
- case 'pglite': {
- const { PGLiteEngine } = await import('./pglite-engine.ts');
- return new PGLiteEngine();
+ const engine = await (async (): Promise<BrainEngine> => {
+ switch (engineType) {
+ case 'pglite': {
+ const { PGLiteEngine } = await import('./pglite-engine.ts');
+ return new PGLiteEngine();
+ }
+ case 'postgres': {
+ const { PostgresEngine } = await import('./postgres-engine.ts');
+ return new PostgresEngine();
+ }
+ default:
+ throw new Error(
+ `Unknown engine type: "${engineType}". Supported engines: postgres, pglite.` +
+ (engineType === 'sqlite' ? ' SQLite is not supported. Use pglite instead.' : '')
+ );
}
- case 'postgres': {
- const { PostgresEngine } = await import('./postgres-engine.ts');
- return new PostgresEngine();
- }
- default:
- throw new Error(
- `Unknown engine type: "${engineType}". Supported engines: postgres, pglite.` +
- (engineType === 'sqlite' ? ' SQLite is not supported. Use pglite instead.' : '')
- );
- }
+ })();
+
+ // #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));
+
+ return engine;
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index e8810be01d..19109c0021 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -536,6 +536,16 @@ export interface NewFact {
context?: string | null;
valid_from?: Date; // default now()
valid_until?: Date | null;
+ /**
+ * v0.46 (#3014) — explicit expiry timestamp. When set, the row is
+ * inactive: excluded from active views (recall, listFactsByEntity's
+ * activeOnly default) and eligible for listSupersessions. The fence
+ * mapper stamps this for struck rows (superseded / forgotten /
+ * inactive-unrecognized) because no DB derivation from `valid_until`
+ * exists — no trigger, sweep, or read-time coalesce populates it.
+ * Active-row callers leave it undefined; insertFacts defaults it to NULL.
+ */
+ expired_at?: Date | null;
source: string; // 'mcp:put_page' | 'mcp:extract_facts' | 'cli:think' | etc
source_session?: string | null;
confidence?: number; // [0,1], default 1.0
@@ -926,11 +936,16 @@ export interface BrainEngine {
* N+1 pattern, which silently defaulted to source_id='default' and
* skipped non-default-source pages.
*
- * Cheap by design: only slug + source_id, not the full Page row. For
- * loops that need page.compiled_truth / timeline / frontmatter, use
- * `forEachPage` from src/core/engine-iter.ts instead.
+ * Cheap by design: only slug + source_id + updated_at, not the full Page
+ * row. For loops that need page.compiled_truth / timeline / frontmatter,
+ * use `forEachPage` from src/core/engine-iter.ts instead.
+ *
+ * #4304: `updated_at` (the row's last DB-write time — "touched since",
+ * NOT the content's authored date) is included so time-window walks like
+ * `gbrain extract --since` can filter refs BEFORE fetching full pages,
+ * instead of a getPage round-trip per page across the whole corpus.
*/
- listAllPageRefs(): Promise<Array<{ slug: string; source_id: string }>>;
+ listAllPageRefs(): Promise<Array<{ slug: string; source_id: string; updated_at: Date }>>;
/**
* v0.38 — lean per-source enumeration for hot-loop callers (autopilot
@@ -1251,8 +1266,13 @@ export interface BrainEngine {
* value → the page stays stale → re-extracted next run, never marked
* fresh-with-the-old-content. Sync / DB-extract sites omit per-ref values and
* pass `now()` (the page was just imported, so `now() >= updated_at`).
+ *
+ * #3957: returns the number of pages rows actually stamped. A shortfall vs
+ * `refs.length` means some refs matched no `(slug, source_id)` pair — the
+ * classic wrong-source stamp that used to fail silently while the stale
+ * backlog grew. stampExtracted (extract.ts) logs the shortfall.
*/
- markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<void>;
+ markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<number>;
// Links
/**
@@ -1307,6 +1327,35 @@ export interface BrainEngine {
linkSource?: string,
opts?: { fromSourceId?: string; toSourceId?: string },
): Promise<void>;
+ /**
+ * #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`:
+ * a per-page delete-then-insert (inside `transaction()`) replaces the
+ * additive-only write path so stale mentions rows finally die.
+ *
+ * Semantics:
+ * - Deletes rows whose from_page is one of `pages` (composite
+ * (slug, source_id) match — source isolation) AND
+ * link_source = `opts.linkSource`.
+ * - `opts.keepTypedNerPairs` protects extract-ner's verb-typed rows the
+ * mention scan cannot regenerate: a row with link_kind = 'typed_ner'
+ * whose (from, to) pair appears in the keep list SURVIVES. typed_ner
+ * rows NOT in the list (target no longer derivable) are deleted with
+ * everything else.
+ *
+ * Returns the number of rows deleted. Atomic per call (one statement).
+ * Both engines implement the identical SQL shape (parity-pinned).
+ */
+ removeLinksByPagesAndSource(
+ pages: Array<{ slug: string; source_id: string }>,
+ opts: {
+ linkSource: string;
+ keepTypedNerPairs?: Array<{
+ from_slug: string; from_source_id: string;
+ to_slug: string; to_source_id: string;
+ }>;
+ },
+ ): Promise<number>;
/**
* v0.31.8 (D12 + D16): `opts.sourceId` source-scopes the from-page lookup.
* When omitted, the read returns links from every same-slug page across
@@ -1462,15 +1511,20 @@ export interface BrainEngine {
pageIds: number[],
): Promise<Map<number, { reason: string; detail: string }>>;
/**
- * Extraction quarantine lane (issue #160): for a list of page_ids, return
- * the subset that are unverified auto-extracted entity stubs (frontmatter
+ * Extraction quarantine lane (issue #160), widened for #4220: for a list
+ * of page_ids, return a map for every page that carries a
+ * `frontmatter.status` value. Each entry reports the raw status string plus
+ * whether the page is an unverified auto-extracted entity stub (frontmatter
* `provenance: 'auto-extracted'` + `status: 'unverified'`). Used by hybrid
- * search to stamp `SearchResult.unverified` pre-fusion so the fusion-level
- * compiled-truth boost skips them. Single SQL query, not N+1. Empty input
- * → empty set (no query). SQL predicate is the shared
- * `unverifiedExtractionFragment` (src/core/extraction-review.ts).
+ * search to stamp `SearchResult.status` (always) and
+ * `SearchResult.unverified` (quarantine special case) pre-fusion so the
+ * fusion-level compiled-truth boost skips stubs. Single SQL query, not
+ * N+1. Empty input → empty map (no query). The quarantine predicate is the
+ * shared `unverifiedExtractionFragment` (src/core/extraction-review.ts).
*/
- getUnverifiedExtractionPageIds(pageIds: number[]): Promise<Set<number>>;
+ getUnverifiedExtractionPageIds(
+ pageIds: number[],
+ ): Promise<Map<number, { unverified: boolean; status: string }>>;
/**
* v0.27.0: for a list of slugs, return their updated_at timestamps (or created_at fallback).
* Used by hybrid search recency boost. Single SQL query, not N+1.
@@ -1905,11 +1959,31 @@ export interface BrainEngine {
*
* Returns the inserted ids in input-order so callers can correlate
* fence-row → DB-id without a separate lookup.
+ *
+ * v0.46 (#3014): `superseded_by_row` carries a struck row's page-local
+ * `superseded by #N` reference. A second pass in the same transaction
+ * resolves it to `facts.superseded_by` (a FK to facts.id), keyed on
+ * (source_id, source_markdown_slug, row_num). Unresolvable references
+ * (self / dangling / chained) leave `superseded_by` NULL and surface a
+ * `warnings` entry — never an FK to a guessed id (resolver:
+ * `src/core/facts/supersede-resolve.ts`).
+ *
+ * v0.46 (#3014): `opts.deleteForPageFirst` makes the wipe-then-reinsert
+ * reconcile atomic. When set, the page's fence-owned rows are DELETEd as
+ * the first statement of the SAME transaction that inserts `rows`, so a
+ * failing insert rolls the delete back and the page is never left
+ * emptied. (A standalone `deleteFactsForPage` call before `insertFacts`
+ * self-commits, so an insert throw would permanently lose the page's
+ * facts.) `slug` / `excludeSourcePrefixes` / `preserveExpiredLegacy`
+ * mirror `deleteFactsForPage`; the deleted count is returned as
+ * `deleted`. Callers that omit it get the standalone insert
+ * (deleted: 0), unchanged.
*/
insertFacts(
- rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
ctx: { source_id: string },
- ): Promise<{ inserted: number; ids: number[] }>;
+ opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean } },
+ ): Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number }>;
/**
* v0.32.2: hard-delete every fact row scoped to a single fence page.
@@ -1986,10 +2060,16 @@ export interface BrainEngine {
): Promise<FactRow[]>;
/**
- * Audit log: facts that were superseded (expired_at + superseded_by both set),
- * newest first. Drives `gbrain recall --supersessions`. `visibility` filters
- * BEFORE the LIMIT (same contract as FactListOpts.visibility) so a remote
- * world-only caller can't have a private row consume a limit slot.
+ * Audit log: facts that were superseded (superseded_by set), newest
+ * first. Drives `gbrain recall --supersessions`. v0.46 (#3014): the
+ * filter requires only `superseded_by IS NOT NULL`, not `expired_at`
+ * too — the ontology-dimension writer closes a superseded row via
+ * `valid_until` (not `expired_at`) so `--asof` time-travel still sees
+ * it, so requiring `expired_at` here would drop every ontology
+ * supersession. Ordering / `since` use COALESCE(expired_at, valid_until).
+ * `visibility` filters BEFORE the LIMIT (same contract as
+ * FactListOpts.visibility) so a remote world-only caller can't have a
+ * private row consume a limit slot.
*/
listSupersessions(
source_id: string,
diff --git a/src/core/enrichment-service.ts b/src/core/enrichment-service.ts
index 301cecb246..c165c2a989 100644
--- a/src/core/enrichment-service.ts
+++ b/src/core/enrichment-service.ts
@@ -23,6 +23,9 @@ import { quarantineMarkers } from './extraction-review.ts';
import { importFromContent } from './import-file.ts';
import { serializeMarkdown } from './markdown.ts';
import { isAvailable } from './ai/gateway.ts';
+// #4222: shared generic-token reject list — same list gates the by-mention
+// gazetteer and drives the junk_entity_hubs doctor check.
+import { isJunkEntityName } from './entity-name-quality.ts';
// ---------------------------------------------------------------------------
// Types
@@ -126,6 +129,25 @@ export async function enrichEntity(
// UPDATE path — add timeline entry
action = 'updated';
} else {
+ // #4222: refuse to MINT a page for a junk entity name — a single
+ // generic token ("Will", "Info", "Chief", "Unknown") or a bare
+ // @handle. These come from over-eager extractors and become
+ // near-empty mega-hubs that accrete thousands of mention edges.
+ // Existing pages are user-visible and stay trusted (CK12 precedent);
+ // only creation is gated — no auto-delete, ever.
+ if (isJunkEntityName(request.entityName)) {
+ return {
+ slug,
+ action: 'skipped',
+ tier,
+ backlinkCreated: false,
+ timelineAdded: false,
+ mentionCount,
+ mentionSources,
+ suggestedTier,
+ tierEscalated,
+ };
+ }
// CREATE path — new entity page
const title = request.entityName;
const type = request.entityType;
diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.ts
new file mode 100644
index 0000000000..96197bbcf8
--- /dev/null
+++ b/src/core/entity-identity.ts
@@ -0,0 +1,315 @@
+/**
+ * #4224 — cross-source entity identity (federation v1).
+ *
+ * THE IDENTITY KEY IS (source_id, slug). A brain can mount many sources and
+ * the same real-world entity routinely exists as a different page in each
+ * (`wiki:people/alice` vs `team-brain:people/alice-chen`). Nothing else in
+ * gbrain asserts "these pages are the same entity" — slugs are only unique
+ * per source, and titles collide freely. The `entity_identities` table
+ * (migration v137) records that assertion explicitly: member pages grouped
+ * under an opaque `entity_id` handle, one optional canonical member per
+ * group.
+ *
+ * v1 posture (deliberate):
+ * - MANUAL-ONLY. Rows come exclusively from the entity_identity_link op.
+ * No auto-matching, no name-similarity heuristics — a wrong identity
+ * merge silently corrupts retrieval, so v1 keeps a human in the loop.
+ * - A page belongs to at most one identity (UNIQUE (source_id, page_id));
+ * re-linking MOVES it.
+ * - Retrieval union is OFF by default, gated by the
+ * `entity_identity.union` config key. When on, the get_links /
+ * get_backlinks ops merge edges from a page's identity co-members
+ * (dedup'd), never widening past the caller's source grant.
+ *
+ * Everything here goes through `engine.executeRaw` with the SAME SQL text on
+ * both engines — parity by construction (pinned in the entity-identity test
+ * + the DATABASE_URL-gated engine-parity suite).
+ */
+
+import type { BrainEngine } from './engine.ts';
+import type { Link } from './types.ts';
+import { isUndefinedTableError } from './utils.ts';
+
+/** Config key for the flag-gated retrieval union. Default OFF. */
+export const ENTITY_IDENTITY_UNION_CONFIG_KEY = 'entity_identity.union';
+
+/**
+ * Opaque identity handle grammar. Slug-flavored so handles read well in CLI
+ * output and can't smuggle whitespace/quotes into messages.
+ */
+const ENTITY_ID_RE = /^[a-z0-9][a-z0-9._/-]{0,127}$/;
+
+export function validateEntityId(entityId: string): string {
+ const trimmed = entityId.trim();
+ if (!ENTITY_ID_RE.test(trimmed)) {
+ throw new Error(
+ `invalid entity_id '${entityId}': expected lowercase [a-z0-9._/-], starting alphanumeric, max 128 chars`,
+ );
+ }
+ return trimmed;
+}
+
+export interface EntityIdentityMember {
+ entity_id: string;
+ source_id: string;
+ slug: string;
+ title: string | null;
+ confidence: number;
+ established_by: string;
+ established_at: Date | string;
+ canonical: boolean;
+}
+
+async function resolvePageId(
+ engine: BrainEngine,
+ slug: string,
+ sourceId: string,
+): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`,
+ [slug, sourceId],
+ );
+ if (rows.length === 0) {
+ throw new Error(`page not found: ${slug} (source ${sourceId}) — the identity key is (source_id, slug)`);
+ }
+ return Number(rows[0]!.id);
+}
+
+/**
+ * Link a page into an identity group (upsert on the page: re-linking MOVES
+ * the page to the new identity — explicit manual intent). `canonical: true`
+ * demotes the group's previous canonical member first; the partial unique
+ * index is the backstop against a race leaving two canonicals.
+ */
+export async function linkEntityIdentity(
+ engine: BrainEngine,
+ opts: {
+ entityId: string;
+ slug: string;
+ sourceId: string;
+ confidence?: number;
+ establishedBy?: string;
+ canonical?: boolean;
+ },
+): Promise<EntityIdentityMember> {
+ const entityId = validateEntityId(opts.entityId);
+ const confidence = opts.confidence ?? 1.0;
+ if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
+ throw new Error(`confidence must be in [0,1], got ${opts.confidence}`);
+ }
+ const establishedBy = (opts.establishedBy ?? 'manual').trim() || 'manual';
+ const canonical = opts.canonical === true;
+ const pageId = await resolvePageId(engine, opts.slug, opts.sourceId);
+
+ if (canonical) {
+ await engine.executeRaw(
+ `UPDATE entity_identities SET canonical = false WHERE entity_id = $1 AND canonical`,
+ [entityId],
+ );
+ }
+ await engine.executeRaw(
+ `INSERT INTO entity_identities (entity_id, source_id, page_id, confidence, established_by, canonical)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (source_id, page_id) DO UPDATE SET
+ entity_id = EXCLUDED.entity_id,
+ confidence = EXCLUDED.confidence,
+ established_by = EXCLUDED.established_by,
+ canonical = EXCLUDED.canonical,
+ established_at = now()`,
+ [entityId, opts.sourceId, pageId, confidence, establishedBy, canonical],
+ );
+
+ const members = await listEntityIdentities(engine, { entityId });
+ const me = members.find(m => m.slug === opts.slug && m.source_id === opts.sourceId);
+ // The row was just written; me is only absent if a concurrent delete raced us.
+ if (!me) throw new Error(`identity link for ${opts.slug} did not persist`);
+ return me;
+}
+
+/** Remove a page from an identity group. Returns true when a row was removed. */
+export async function unlinkEntityIdentity(
+ engine: BrainEngine,
+ opts: { entityId: string; slug: string; sourceId: string },
+): Promise<boolean> {
+ const entityId = validateEntityId(opts.entityId);
+ const rows = await engine.executeRaw<{ id: number }>(
+ `DELETE FROM entity_identities ei
+ USING pages p
+ WHERE ei.page_id = p.id
+ AND ei.entity_id = $1
+ AND p.slug = $2
+ AND ei.source_id = $3
+ RETURNING ei.id`,
+ [entityId, opts.slug, opts.sourceId],
+ );
+ return rows.length > 0;
+}
+
+/**
+ * List identity members. Filters compose (AND). `allowedSources` restricts
+ * MEMBER VISIBILITY (federated read grant) — a caller who can't read source
+ * X never learns X's member pages, even when another member matched.
+ *
+ * The identity key is (source_id, slug), so the `slug` filter alone is
+ * ambiguous: pass `slugSourceId` to seed group resolution from exactly the
+ * (slug, source) page the caller is reading. Without it, the seed sub-select
+ * is scoped to `allowedSources` when provided (a caller must not discover a
+ * group through a seed page outside their grant), and only a trusted
+ * unscoped caller (neither given) seeds from any source.
+ */
+export async function listEntityIdentities(
+ engine: BrainEngine,
+ opts: { entityId?: string; slug?: string; slugSourceId?: string; allowedSources?: string[] } = {},
+): Promise<EntityIdentityMember[]> {
+ const where: string[] = [];
+ const params: unknown[] = [];
+ if (opts.entityId) {
+ params.push(validateEntityId(opts.entityId));
+ where.push(`ei.entity_id = $${params.length}`);
+ }
+ if (opts.slug) {
+ params.push(opts.slug);
+ const slugParam = params.length;
+ // #4224 review fix: the seed sub-select must be source-scoped — an
+ // unscoped `p2.slug = $` matches ANY source's page with that slug, so a
+ // read against a NON-member page unioned a foreign same-slug member's
+ // group.
+ let seedScope = '';
+ if (opts.slugSourceId) {
+ params.push(opts.slugSourceId);
+ seedScope = ` AND ei2.source_id = $${params.length}`;
+ } else if (opts.allowedSources && opts.allowedSources.length > 0) {
+ const ph = opts.allowedSources.map((s) => {
+ params.push(s);
+ return `$${params.length}`;
+ });
+ seedScope = ` AND ei2.source_id IN (${ph.join(', ')})`;
+ }
+ where.push(`ei.entity_id IN (
+ SELECT ei2.entity_id FROM entity_identities ei2
+ JOIN pages p2 ON p2.id = ei2.page_id
+ WHERE p2.slug = $${slugParam} AND p2.deleted_at IS NULL${seedScope}
+ )`);
+ }
+ if (opts.allowedSources && opts.allowedSources.length > 0) {
+ const placeholders = opts.allowedSources.map((s) => {
+ params.push(s);
+ return `$${params.length}`;
+ });
+ where.push(`ei.source_id IN (${placeholders.join(', ')})`);
+ }
+ try {
+ const rows = await engine.executeRaw<{
+ entity_id: string;
+ source_id: string;
+ slug: string;
+ title: string | null;
+ confidence: number;
+ established_by: string;
+ established_at: Date | string;
+ canonical: boolean;
+ }>(
+ `SELECT ei.entity_id, ei.source_id, p.slug, p.title, ei.confidence,
+ ei.established_by, ei.established_at, ei.canonical
+ FROM entity_identities ei
+ JOIN pages p ON p.id = ei.page_id AND p.deleted_at IS NULL
+ ${where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''}
+ ORDER BY ei.entity_id, ei.canonical DESC, ei.source_id, p.slug`,
+ params,
+ );
+ return rows.map(r => ({
+ entity_id: r.entity_id,
+ source_id: r.source_id,
+ slug: r.slug,
+ title: r.title,
+ confidence: Number(r.confidence),
+ established_by: r.established_by,
+ established_at: r.established_at,
+ canonical: r.canonical === true,
+ }));
+ } catch (e) {
+ // Pre-v137 brain (table missing): identity is simply "not set up yet".
+ if (isUndefinedTableError(e)) return [];
+ throw e;
+ }
+}
+
+/** Is the flag-gated retrieval union on? Fail-closed on any read error. */
+export async function isIdentityUnionEnabled(engine: BrainEngine): Promise<boolean> {
+ try {
+ const v = await engine.getConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY);
+ if (v === null || v === undefined) return false;
+ const s = String(v).trim().toLowerCase();
+ return s === 'true' || s === '1';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Flag-gated retrieval union for the link read ops (#4224 v1 union surface;
+ * chunk-side union is a filed follow-up — member pages' chunks already
+ * surface independently in search, so edges are where identity is invisible
+ * today).
+ *
+ * Given a page slug and the links already fetched for it, fetch the same
+ * direction's links for every identity CO-MEMBER the caller may see and
+ * merge (dedup'd on the full edge key). Sources outside `allowedSources`
+ * (when provided) are never consulted — the union must not widen a
+ * federated caller's grant.
+ *
+ * Pure no-op when the flag is off, the table is missing, or the page is not
+ * an identity member.
+ */
+export async function unionLinksAcrossIdentity(
+ engine: BrainEngine,
+ slug: string,
+ links: Link[],
+ direction: 'out' | 'in',
+ opts: { sourceId?: string; allowedSources?: string[] } = {},
+): Promise<Link[]> {
+ if (!(await isIdentityUnionEnabled(engine))) return links;
+ let members: EntityIdentityMember[];
+ try {
+ members = await listEntityIdentities(engine, {
+ slug,
+ // #4224 review fix: seed group resolution from the BASE page's
+ // (slug, source) — never from a foreign same-slug page.
+ slugSourceId: opts.sourceId,
+ allowedSources: opts.allowedSources,
+ });
+ } catch {
+ return links; // never let the union break the base read
+ }
+ // #4224 review fix: the identity key is (source_id, slug) — exclude only
+ // the BASE pair. A same-slug co-member in ANOTHER source is a real
+ // co-member whose edges the scalar-scoped base read did not fetch. When
+ // the base source is unknown (trusted unscoped / federated multi-grant),
+ // the base read already spanned every visible same-slug page, so
+ // slug-level exclusion is exact there.
+ const coMembers = opts.sourceId
+ ? members.filter(m => !(m.slug === slug && m.source_id === opts.sourceId))
+ : members.filter(m => m.slug !== slug);
+ if (coMembers.length === 0) return links;
+
+ const merged: Link[] = [...links];
+ const keyOf = (l: Link) =>
+ `${l.from_source_id}:${l.from_slug}|${l.to_source_id}:${l.to_slug}|${l.link_type}|${l.link_source ?? ''}`;
+ const seen = new Set(merged.map(keyOf));
+ for (const m of coMembers) {
+ try {
+ const memberLinks = direction === 'out'
+ ? await engine.getLinks(m.slug, { sourceId: m.source_id })
+ : await engine.getBacklinks(m.slug, { sourceId: m.source_id });
+ for (const l of memberLinks) {
+ const k = keyOf(l);
+ if (seen.has(k)) continue;
+ seen.add(k);
+ merged.push(l);
+ }
+ } catch {
+ // A single member's failure never breaks the base read.
+ }
+ }
+ return merged;
+}
diff --git a/src/core/entity-name-quality.ts b/src/core/entity-name-quality.ts
new file mode 100644
index 0000000000..fec51c7647
--- /dev/null
+++ b/src/core/entity-name-quality.ts
@@ -0,0 +1,65 @@
+/**
+ * #4222 — shared generic-token reject list for entity-name quality gating.
+ *
+ * Over-eager extractors mint entity pages from generic English tokens
+ * ("Will", "Info", "Chief", "Unknown") and bare @handles. Once minted, the
+ * by-mention auto-linker treats them as real entities and every body-text
+ * occurrence of the word accretes another edge — a near-empty page with
+ * thousands of links (a "junk hub") that poisons graph signals and
+ * relational recall.
+ *
+ * One list, three consumers (keep them in sync by importing from HERE):
+ * - `enrichEntity` (src/core/enrichment-service.ts) refuses to MINT a
+ * page for a junk name. Existing pages stay trusted (CK12 precedent:
+ * a user-created page is authoritative even if the title is on the
+ * list) — only creation is gated.
+ * - `buildGazetteer` (src/core/by-mention.ts) drops single-generic-token
+ * PERSON titles so an already-minted junk page stops accreting edges.
+ * - The `junk_entity_hubs` doctor check (warn + list, never auto-delete)
+ * surfaces hubs that predate these gates.
+ *
+ * Scope discipline: the list gates SINGLE-token names only. "Will Smith"
+ * is never affected — multi-token names bypass every consumer's check.
+ * Comparisons are case-insensitive.
+ */
+
+/**
+ * Lowercase single tokens that are almost never a real entity's full name.
+ * Conservative by design: each entry must be a word whose standalone
+ * appearance in prose is overwhelmingly NOT a reference to a specific
+ * person/company. When in doubt, leave it out — a missed junk token is a
+ * doctor warning; an over-broad one silently suppresses a real entity.
+ */
+export const GENERIC_ENTITY_TOKENS: ReadonlySet<string> = new Set([
+ // The observed junk-hub names from #4222.
+ 'will', 'something', 'info', 'chief', 'unknown', 'readme', 'founders',
+ // Same class: role/collective words extractors capitalize into "names".
+ 'founder', 'team', 'staff', 'everyone', 'someone', 'anyone', 'people',
+ 'person', 'company', 'admin', 'user', 'users', 'contact', 'support',
+ // Document/structure words that title-case into candidates.
+ 'update', 'updates', 'note', 'notes', 'meeting', 'meetings', 'summary',
+ 'general', 'misc', 'other', 'various', 'agenda', 'minutes', 'draft',
+ 'welcome', 'hello', 'thanks', 'inbox', 'untitled', 'unnamed',
+ // Placeholder tokens.
+ 'none', 'null', 'undefined', 'test', 'todo', 'tbd',
+]);
+
+/** Case-insensitive membership test against GENERIC_ENTITY_TOKENS. */
+export function isGenericEntityToken(token: string): boolean {
+ return GENERIC_ENTITY_TOKENS.has(token.trim().toLowerCase());
+}
+
+/** Bare social/@-mention handle, e.g. `@alice_dev` — not a display name. */
+const BARE_HANDLE_RE = /^@\S+$/;
+
+/**
+ * Should this name be refused as a NEW entity page? True for a single
+ * generic token or a bare @handle. Multi-word names always pass.
+ */
+export function isJunkEntityName(name: string): boolean {
+ const trimmed = name.trim();
+ if (trimmed.length === 0) return true;
+ if (BARE_HANDLE_RE.test(trimmed)) return true;
+ const words = trimmed.split(/\s+/);
+ return words.length === 1 && isGenericEntityToken(words[0]!);
+}
diff --git a/src/core/eval-contradictions/run-health.ts b/src/core/eval-contradictions/run-health.ts
new file mode 100644
index 0000000000..b8e4cfe147
--- /dev/null
+++ b/src/core/eval-contradictions/run-health.ts
@@ -0,0 +1,114 @@
+/**
+ * eval-contradictions/run-health — the #3889 honesty predicate.
+ *
+ * A run whose judge failed on EVERY pair produces a verdict_breakdown that
+ * sums to 0 while judge_errors.total > 0. Reporting that run as
+ * "0 contradictions" is a lie — no pair was ever scored. This module is the
+ * single shared predicate:
+ *
+ * - the runner stamps `run_status: 'judge_failed'` on the ProbeReport,
+ * - the CLI suppresses the 0/N headline + Wilson CI and exits 1,
+ * - doctor downgrades the green "no contradictions" check to a warn.
+ *
+ * Pure functions only — no engine, no I/O — so doctor and the CLI share one
+ * definition and the tests are hermetic.
+ */
+
+import type { VerdictBreakdown } from './types.ts';
+
+/** Sum every numeric bucket in a (possibly partial/untyped) verdict breakdown. */
+export function sumVerdicts(vb: Partial<VerdictBreakdown> | null | undefined): number {
+ if (!vb || typeof vb !== 'object') return 0;
+ let sum = 0;
+ for (const v of Object.values(vb)) {
+ if (typeof v === 'number' && Number.isFinite(v)) sum += v;
+ }
+ return sum;
+}
+
+/** True iff the run scored zero pairs while at least one judge call errored. */
+export function isJudgeFailedRun(verdictSum: number, judgeErrorsTotal: number): boolean {
+ return verdictSum === 0 && judgeErrorsTotal > 0;
+}
+
+/**
+ * Recover the run's verdict count from a persisted report_json. Prefers the
+ * v0.34+ verdict_breakdown; pre-v0.34 rows fall back to per-query
+ * pairs_judged + pairs_cache_hit (the same denominator — every judged or
+ * cache-served pair produced exactly one verdict).
+ */
+export function inferVerdictSum(report: Record<string, unknown> | null | undefined): number {
+ const vb = report?.verdict_breakdown;
+ if (vb && typeof vb === 'object') return sumVerdicts(vb as Partial<VerdictBreakdown>);
+ const perQuery = report?.per_query;
+ if (Array.isArray(perQuery)) {
+ let sum = 0;
+ for (const q of perQuery) {
+ const row = q as Record<string, unknown> | null;
+ if (typeof row?.pairs_judged === 'number') sum += row.pairs_judged;
+ if (typeof row?.pairs_cache_hit === 'number') sum += row.pairs_cache_hit;
+ }
+ return sum;
+ }
+ return 0;
+}
+
+export interface RunHealth {
+ judge_failed: boolean;
+ verdict_sum: number;
+ judge_errors_total: number;
+ /** errors / (verdicts + errors); null when the run attempted zero pairs. */
+ error_rate: number | null;
+}
+
+/** Doctor-side assessment of a persisted eval_contradictions_runs row. */
+export function assessRunHealth(row: {
+ judge_errors_total?: number | null;
+ report_json?: Record<string, unknown> | null;
+}): RunHealth {
+ const judgeErrorsTotal =
+ typeof row.judge_errors_total === 'number' && Number.isFinite(row.judge_errors_total)
+ ? row.judge_errors_total
+ : 0;
+ const verdictSum = inferVerdictSum(row.report_json);
+ const attempted = verdictSum + judgeErrorsTotal;
+ return {
+ judge_failed: isJudgeFailedRun(verdictSum, judgeErrorsTotal),
+ verdict_sum: verdictSum,
+ judge_errors_total: judgeErrorsTotal,
+ error_rate: attempted > 0 ? judgeErrorsTotal / attempted : null,
+ };
+}
+
+/**
+ * Doctor check body for the "zero suspected contradictions" case. Returns a
+ * warn (not ok) when the latest run judged nothing but errored — otherwise
+ * the honest green message, annotated with the error rate when any judge
+ * call failed.
+ */
+export function zeroTotalContradictionsCheck(latest: {
+ ran_at: string;
+ queries_evaluated: number;
+ judge_errors_total?: number | null;
+ report_json?: Record<string, unknown> | null;
+}): { status: 'ok' | 'warn'; message: string } {
+ const health = assessRunHealth(latest);
+ const day = latest.ran_at.slice(0, 10);
+ if (health.judge_failed) {
+ return {
+ status: 'warn',
+ message:
+ `Latest probe run (${day}) judged ZERO pairs — all ${health.judge_errors_total} judge calls errored. ` +
+ `The "0 contradictions" result is not trustworthy. Check the judge model/API key and re-run ` +
+ '`gbrain eval suspected-contradictions`.',
+ };
+ }
+ const errNote =
+ health.judge_errors_total > 0 && health.error_rate !== null
+ ? ` (judge errors: ${health.judge_errors_total}, ${(health.error_rate * 100).toFixed(0)}% of pairs)`
+ : '';
+ return {
+ status: 'ok',
+ message: `Latest probe run (${day}) found no suspected contradictions across ${latest.queries_evaluated} queries${errNote}.`,
+ };
+}
diff --git a/src/core/eval-contradictions/runner.ts b/src/core/eval-contradictions/runner.ts
index df1ee0aa32..14fd9028f0 100644
--- a/src/core/eval-contradictions/runner.ts
+++ b/src/core/eval-contradictions/runner.ts
@@ -39,6 +39,7 @@ import { judgeContradiction, type JudgeInput, type JudgeOutput } from './judge.t
import { JudgeErrorCollector } from './judge-errors.ts';
import { buildHotPages } from './severity-classify.ts';
import { pairToFinding } from './auto-supersession.ts';
+import { isJudgeFailedRun, sumVerdicts } from './run-health.ts';
import {
PROMPT_VERSION,
SCHEMA_VERSION,
@@ -447,8 +448,16 @@ async function _runContradictionProbeInner(opts: RunnerOpts): Promise<RunnerResu
const runId = new Date(startedAt).toISOString().replace(/[:.]/g, '-').replace(/-(?=\d{3}Z$)/, '.');
const durationMs = Date.now() - startedAt;
+ // #3889: a run where EVERY judge call errored has zero verdicts — its
+ // "0 contradictions" headline is untrustworthy. Stamp the status so the
+ // CLI + doctor can refuse to render it as a clean green result.
+ const runStatus = isJudgeFailedRun(sumVerdicts(verdictBreakdown), judgeErrors.total)
+ ? ('judge_failed' as const)
+ : ('ok' as const);
+
const report: ProbeReport = {
schema_version: SCHEMA_VERSION,
+ run_status: runStatus,
run_id: runId,
judge_model: judgeModel,
prompt_version: PROMPT_VERSION,
diff --git a/src/core/eval-contradictions/types.ts b/src/core/eval-contradictions/types.ts
index 0610e1da6d..c93faaa615 100644
--- a/src/core/eval-contradictions/types.ts
+++ b/src/core/eval-contradictions/types.ts
@@ -236,8 +236,18 @@ export interface HotPage {
max_severity: Severity;
}
+/**
+ * #3889: run-level status. 'judge_failed' when the run produced no verdicts
+ * at all (verdict_breakdown sums to 0) while judge_errors.total > 0 — every
+ * judge call errored, so the "0 contradictions" headline would be a lie.
+ * Optional (append-only): reports persisted before this field lack it.
+ */
+export type RunStatus = 'ok' | 'judge_failed';
+
export interface ProbeReport {
schema_version: typeof SCHEMA_VERSION;
+ /** #3889: absent on pre-field persisted rows; treat absent as 'ok'. */
+ run_status?: RunStatus;
run_id: string;
judge_model: string;
prompt_version: string;
diff --git a/src/core/extract/receipt-writer.ts b/src/core/extract/receipt-writer.ts
index cecd8c3328..6b87efa681 100644
--- a/src/core/extract/receipt-writer.ts
+++ b/src/core/extract/receipt-writer.ts
@@ -219,5 +219,15 @@ export async function writeReceipt(
{ sourceId: input.source_id },
);
+ // #4009: receipts are audit artifacts — deliberately never run through
+ // the contextual-retrieval ladder. Born with a NULL
+ // contextual_retrieval_mode they tripped doctor's
+ // contextual_retrieval_coverage warn on every extraction run right
+ // after a reindex. Stamp mode 'none' so receipts are born CR-evaluated.
+ // NOT permanent: a reindex that takes the DB fallback clears the stamp
+ // and it recurs per receipt — the doctor check also excludes
+ // type='extract_receipt' from mode_null (belt+braces).
+ await engine.updatePageContextualRetrievalState(slug, input.source_id, 'none', null);
+
return { slug, page };
}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 8796a6ea2b..56b2ef50dc 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -71,6 +71,18 @@ export interface FactsBackstopCtx {
visibility?: 'private' | 'world';
/** Override the chat model (extract_facts forwards user's model param when set). */
model?: string;
+ /**
+ * #4206: caller-supplied event time. Fallback ONLY — a valid_from the
+ * extractor derives from the turn itself wins; absent both, now(). Lets
+ * historical imports (old transcripts) avoid import-time stamping.
+ */
+ validFrom?: Date;
+ /**
+ * #4206: slug of the page/transcript the turn came from (e.g.
+ * 'meetings/2026-04-03'). Written to facts.context so the recall /
+ * context_pack / delta projections surface the provenance.
+ */
+ sourceSlug?: string;
}
/** Discriminated return shape based on FactsBackstopCtx.mode. */
@@ -651,6 +663,9 @@ async function runPipelineWithBody(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ // #4206: caller event-time fallback + provenance context.
+ valid_from: f.valid_from ?? ctx.validFrom,
+ context: ctx.sourceSlug ?? null,
};
const result = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: legacy DB-only fallback for unparented / thin-client facts (no entity page to fence onto)
fact_ids.push(result.id);
@@ -676,10 +691,14 @@ async function runPipelineWithBody(
kind: f.kind,
notability: f.notability,
source: f.source,
- context: null,
+ // #4206: the caller's source_slug (which page/transcript the turn came
+ // from) lands in the fence context cell — visible in recall projections.
+ context: ctx.sourceSlug ?? null,
visibility,
confidence: f.confidence,
- validFrom: f.valid_from ?? new Date(),
+ // #4206: extractor-derived date wins; then the caller's event time
+ // (historical imports); then import time.
+ validFrom: f.valid_from ?? ctx.validFrom ?? new Date(),
embedding: f.embedding ?? null,
sessionId: f.source_session ?? null,
}));
@@ -717,6 +736,9 @@ async function runPipelineWithBody(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ // #4206: caller event-time fallback + provenance context.
+ valid_from: f.valid_from ?? ctx.validFrom,
+ context: ctx.sourceSlug ?? null,
};
const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: stub-guard / unresolvable-target fallback (no fenceable page or usable tree)
fact_ids.push(legacyResult.id);
@@ -746,6 +768,9 @@ async function runPipelineWithBody(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ // #4206: caller event-time fallback + provenance context.
+ valid_from: f.valid_from ?? ctx.validFrom,
+ context: ctx.sourceSlug ?? null,
};
const legacyResult = await ctx.engine.insertFact(newFact, { source_id: ctx.sourceId }); // gbrain-allow-direct-insert: DB-only fallback when the fence lane declined the write (write_through opt-out race / localPath echo)
fact_ids.push(legacyResult.id);
diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.ts
index a404df7b43..85fd863118 100644
--- a/src/core/facts/extract-from-fence.ts
+++ b/src/core/facts/extract-from-fence.ts
@@ -11,7 +11,14 @@
* It is intentionally pure: no engine call, no I/O. Inputs are the parsed
* facts plus the page-level binding (entity slug + source_id). Output is
* a `FenceExtractedFact[]` — structural superset of `NewFact` that
- * carries the v51 fence columns (`row_num`, `source_markdown_slug`).
+ * carries the v51 fence columns (`row_num`, `source_markdown_slug`) and,
+ * for struck rows, the v0.46 (#3014) supersession-transport fields:
+ * - `expired_at` stamped on every inactive row (superseded / forgotten
+ * / inactive-unrecognized) so the row exits active views — there is
+ * no DB derivation from `valid_until`, so the mapper sets it here.
+ * - `superseded_by_row` carrying the page-local `superseded by #N`
+ * reference for the engine's insert-time resolution to a fact id
+ * (resolver: `src/core/facts/supersede-resolve.ts`).
*
* Codex Q7 resolution: engines stay markdown-unaware. The cycle phase
* (commit 7) and the backstop rewrite (commit 5) call this function to
@@ -19,12 +26,12 @@
* batch insert.
*
* Strikethrough → date derivation:
- * - `forgotten` rows get `valid_until = today` so the DB's existing
- * `expired_at = valid_until + now()` rule produces the same forget
- * state after `gbrain rebuild` (v0.32.3) as before.
+ * - `forgotten` rows get `valid_until = today` (and `expired_at`) so the
+ * row is inactive after reconcile.
* - `supersededBy` rows preserve their existing `validUntil` if set;
- * otherwise leave `valid_until = null` (the consolidator phase fills
- * this in based on the newer row's `valid_from`).
+ * otherwise leave `valid_until = null`. `expired_at` is set to
+ * `valid_until ?? today` regardless, so the struck row exits active
+ * views and satisfies `listSupersessions`.
* - Inactive rows with neither flag (parser-tolerated hand-edits) are
* treated like `forgotten` for DB-derivation purposes — the user's
* strikethrough intent is honored; the lost reason is a JSONL
@@ -43,6 +50,14 @@ import type { ParsedFact } from '../facts-fence.ts';
export type FenceExtractedFact = NewFact & {
row_num: number;
source_markdown_slug: string;
+ /**
+ * v0.46 (#3014) — page-local row reference parsed from `~~claim~~` +
+ * `superseded by #N` (the `#N`). NOT a fact id: `facts.superseded_by`
+ * is a FK to `facts.id`, so `insertFacts` resolves this row number to
+ * the target row's id in a second pass. undefined when the row is not
+ * a supersession.
+ */
+ superseded_by_row?: number;
};
/**
@@ -204,6 +219,15 @@ export function extractFactsFromFenceText(
validUntil = null;
}
+ // v0.46 (#3014) — struck rows carry their expiry + supersession
+ // reference into the DB. `expired_at` has no DB derivation from
+ // `valid_until` (no trigger, sweep, or read-time coalesce), so the
+ // mapper stamps it explicitly for EVERY inactive row (superseded,
+ // forgotten, or inactive-unrecognized) — that is how a struck row
+ // exits active views. `valid_until ?? today` keeps it deterministic
+ // under nowOverride. Active rows leave it null.
+ const expiredAt: Date | null = !f.active ? (validUntil ?? today) : null;
+
const row: FenceExtractedFact = {
fact: f.claim,
kind: f.kind as FactKind,
@@ -213,10 +237,15 @@ export function extractFactsFromFenceText(
context: f.context ?? null,
valid_from: validFrom,
valid_until: validUntil,
+ expired_at: expiredAt,
source: f.source ?? FENCE_SOURCE_DEFAULT,
confidence: f.confidence,
row_num: f.rowNum,
source_markdown_slug: slug,
+ // v0.46 (#3014) — carry the page-local `superseded by #N` reference
+ // for insertFacts to resolve to a fact id. undefined for non-struck
+ // rows and for struck rows with no supersession context.
+ superseded_by_row: f.supersededBy,
// v0.35.4 (D-CDX-5) — typed-claim threading. Metric label normalized
// here so the DB-side index hits use the canonical name; value /
// unit / period stored verbatim.
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 60b3a2cf09..2fac8986f6 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -88,6 +88,15 @@ export const ALL_EXTRACT_KINDS: readonly FactKind[] = [
'event', 'preference', 'commitment', 'belief', 'fact',
] as const;
+/**
+ * #4209 — max entity hints forwarded to the extractor prompt. Anything past
+ * this is silently dropped by the prompt builder, so the cap is NAMED here
+ * (single source of truth) and surfaced in the extract_facts op contract
+ * (param description + entity_hints_used / entity_hints_dropped response
+ * fields) instead of living as an anonymous inline slice.
+ */
+export const ENTITY_HINTS_CAP = 5;
+
export interface ExtractInput {
turnText: string;
/** Opaque session id (MCP _meta.session_id, CLI --session, or null). */
@@ -300,7 +309,7 @@ export async function extractFactsFromTurnWithOutcome(
}
const userContent = `<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${
input.entityHints && input.entityHints.length
- ? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, 5).join(', ')}.`
+ ? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, ENTITY_HINTS_CAP).join(', ')}.`
: ''
}`;
let result: ChatResult;
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 736c3d4e94..496365b883 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -449,6 +449,14 @@ export async function writeFactsToFence(
}));
const result = await engine.insertFacts(enriched, { source_id: target.sourceId }); // gbrain-allow-direct-insert: writeFactsToFence is the markdown-first reconcile path; runs only after the atomic fence write commits
+ // v0.46 (#3014) — an unresolvable `superseded by #N` reference (self
+ // / dangling / struck target) leaves superseded_by NULL; log it rather
+ // than swallow it. The row still lands (expired_at set for struck
+ // rows), never a bad FK.
+ for (const w of result.warnings) {
+ // eslint-disable-next-line no-console
+ console.warn(`[facts.supersession] ${w}`);
+ }
if (durabilityEnabled) {
await commitFactFenceFile(
writeRoot,
diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.ts
index 87be817264..16b4b41daf 100644
--- a/src/core/facts/meta-hook.ts
+++ b/src/core/facts/meta-hook.ts
@@ -148,6 +148,9 @@ export async function getBrainHotMemoryMeta(
// last wake" filters on WHEN the fact was learned, not its semantic
// validity date (a fact recorded today about last month is NEW).
created_at: r.created_at.toISOString(),
+ // #4206: provenance context (e.g. the source_slug extract_facts threaded
+ // in) rides the pack/delta projections instead of being recall-only.
+ context: r.context ?? null,
confidence: Number(effectiveConfidence(r, now).toFixed(3)),
})),
},
diff --git a/src/core/facts/supersede-resolve.ts b/src/core/facts/supersede-resolve.ts
new file mode 100644
index 0000000000..a51a4c84a2
--- /dev/null
+++ b/src/core/facts/supersede-resolve.ts
@@ -0,0 +1,93 @@
+/**
+ * v0.46 (#3014) — pure resolution of a struck fence row's
+ * `superseded by #N` page-local reference to a fact id.
+ *
+ * The fence parser (`facts-fence.ts`) maps `~~claim~~` + `context:
+ * superseded by #N` to `supersededBy: N` — a ROW NUMBER within the page,
+ * not a fact id. `facts.superseded_by` is a FK to `facts.id`, so the
+ * engines resolve the row number in a second pass inside the insert
+ * transaction (keyed on the v51 unique coordinate
+ * `(source_id, source_markdown_slug, row_num)`). The decision logic lives
+ * here — pure, no engine call, no I/O — so it is unit-testable without a
+ * DB and shared verbatim by both engines (parity) plus the cycle phase's
+ * drift re-resolution.
+ */
+
+/**
+ * The target row a struck `superseded by #N` reference resolves to, as
+ * seen at insert time.
+ */
+export interface SupersedeTarget {
+ id: number;
+ /**
+ * true when the target row is itself inactive (its `expired_at` is set)
+ * — e.g. `#N` points at a forgotten row or an already-superseded row. A
+ * supersession target must be a live row, so a struck target is rejected.
+ */
+ struck: boolean;
+}
+
+/** Outcome of resolving a `superseded by #N` reference to a fact id. */
+export interface SupersedeResolution {
+ /** The resolved target fact id, or null when the reference is unsafe. */
+ superseded_by: number | null;
+ /** A human-readable warning when the reference could not be resolved. */
+ warning: string | null;
+}
+
+/** Largest value a Postgres `int4` column (`facts.row_num`) can hold. */
+export const PG_INT4_MAX = 2147483647;
+
+/**
+ * Can `n` safely target the `row_num` (int4) column in insertFacts'
+ * supersession-resolution SELECT? The fence parser accepts any finite
+ * `#N`, but a value outside int4 range would overflow the comparison and
+ * raise `integer out of range`, aborting the whole extract cycle. The
+ * engines gate the lookup on this so an absurd `#N` is treated as a
+ * dangling reference (resolveSupersededByRow with `target` undefined →
+ * NULL + warning) rather than an uncaught throw.
+ */
+export function isInt4RowRef(n: number): boolean {
+ return Number.isInteger(n) && n >= 1 && n <= PG_INT4_MAX;
+}
+
+/**
+ * Resolve a struck row's `superseded by #N` page-local reference to a
+ * fact id. Pure: the caller supplies the already-looked-up `target`
+ * (keyed on source + slug + row_num within the same transaction) so this
+ * decision is unit-testable without a DB.
+ *
+ * Three references are unsafe and resolve to NULL + a warning (never an
+ * FK write to a guessed id); `expired_at` is set by the fence mapper
+ * regardless of the outcome so the struck row still exits active views:
+ * - self-reference (`#N` == the row's own number)
+ * - dangling (`#N` names a row absent from the page)
+ * - struck target (`#N` names a row that is itself inactive — a
+ * supersession chain, or a forgotten target)
+ */
+export function resolveSupersededByRow(
+ ownRowNum: number,
+ supersededByRow: number,
+ target: SupersedeTarget | undefined,
+ slug: string,
+): SupersedeResolution {
+ if (supersededByRow === ownRowNum) {
+ return {
+ superseded_by: null,
+ warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" references itself — leaving superseded_by NULL`,
+ };
+ }
+ if (!target) {
+ return {
+ superseded_by: null,
+ warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" names a row absent from the fence — leaving superseded_by NULL`,
+ };
+ }
+ if (target.struck) {
+ return {
+ superseded_by: null,
+ warning: `${slug} row ${ownRowNum}: "superseded by #${supersededByRow}" names a row that is itself struck (inactive) — a supersession target must be a live row; leaving superseded_by NULL`,
+ };
+ }
+ return { superseded_by: target.id, warning: null };
+}
diff --git a/src/core/git-remote.ts b/src/core/git-remote.ts
index 235956a7b4..be65ec9490 100644
--- a/src/core/git-remote.ts
+++ b/src/core/git-remote.ts
@@ -258,9 +258,15 @@ export function cloneRepo(url: string, destDir: string, opts: CloneOpts = {}): v
}
}
-/** Pull a repo with --ff-only and the same SSRF-defensive flags as cloneRepo. */
+/**
+ * Pull a repo with --ff-only and the same SSRF-defensive flags as cloneRepo.
+ * #3836: global flags build via durableSsrfFlags() so the documented
+ * GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1 escape hatch reaches sync's pull —
+ * self-hosted local-filesystem remotes could clone but never pull. Default
+ * stays `never`; the origin was already validated at clone time.
+ */
export function pullRepo(repoPath: string, opts: { timeoutMs?: number } = {}): void {
- const args: string[] = ['-C', repoPath, ...GIT_SSRF_FLAGS, 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
+ const args: string[] = ['-C', repoPath, ...durableSsrfFlags(), 'pull', ...GIT_SSRF_SUBCOMMAND_FLAGS, '--ff-only'];
try {
execFileSync('git', args, {
stdio: ['ignore', 'pipe', 'pipe'],
@@ -285,7 +291,9 @@ export function pullRepo(repoPath: string, opts: { timeoutMs?: number } = {}): v
* the estimator catches and falls back to local HEAD.
*/
export function fetchRemote(repoPath: string, branch: string, opts: { timeoutMs?: number } = {}): void {
- const args: string[] = ['-C', repoPath, ...GIT_SSRF_FLAGS, 'fetch', ...GIT_SSRF_SUBCOMMAND_FLAGS, 'origin', branch];
+ // #3836: durableSsrfFlags (not the hardcoded GIT_SSRF_FLAGS) so the
+ // file-transport escape hatch applies to the estimator's fetch too.
+ const args: string[] = ['-C', repoPath, ...durableSsrfFlags(), 'fetch', ...GIT_SSRF_SUBCOMMAND_FLAGS, 'origin', branch];
try {
execFileSync('git', args, {
stdio: ['ignore', 'pipe', 'pipe'],
diff --git a/src/core/github-source.ts b/src/core/github-source.ts
index be5ce491e9..96aa37bca3 100644
--- a/src/core/github-source.ts
+++ b/src/core/github-source.ts
@@ -1507,7 +1507,8 @@ async function runExtractAndEmbed(
// Large sync skips the inline embed; queue a capped backfill job so the
// mirrored pages don't sit unembedded until someone notices recall is
// keyword-only. Mirrors performSync's auto-defer chaser.
- const drainHint = `run 'gbrain embed --stale --source-id ${deps.sourceId}' to drain now`;
+ // #3697: embed's source filter is `--source` (embed.ts parses no --source-id).
+ const drainHint = `run 'gbrain embed --stale --source ${deps.sourceId}' to drain now`;
try {
const { submitEmbedBackfill } = await import('./embed-backfill-submit.ts');
const sub = await submitEmbedBackfill(deps.engine, deps.sourceId, { reason: 'github_sync_defer' });
diff --git a/src/core/guardrails.ts b/src/core/guardrails.ts
index 48b95e3e4b..dc69a8797a 100644
--- a/src/core/guardrails.ts
+++ b/src/core/guardrails.ts
@@ -111,6 +111,90 @@ export function hasGuardrails(): boolean {
* cost is bounded by each provider's own timeout discipline; GBrain does not
* impose one here so providers can tune per-deployment latency budgets.
*/
+/**
+ * Thrown by {@link loadGuardrailProvidersFromEnv} when GBRAIN_GUARDRAILS_MODULE
+ * is SET but unusable. Deliberately fail-CLOSED (unlike the classify path,
+ * which fails open): an operator who configured a guardrail module expects a
+ * firewall to be standing — silently running without it would defeat the
+ * point. Callers (cli.ts) abort the process on this error.
+ */
+export class GuardrailLoadError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'GuardrailLoadError';
+ }
+}
+
+export interface GuardrailEnvLoadResult {
+ /** Providers registered by this call (0 when the env var is unset). */
+ loaded: number;
+ /** The module specifier that was loaded, or null when unset. */
+ modulePath: string | null;
+}
+
+/**
+ * #3688 — the operator wiring path. Loads guardrail providers from the module
+ * named by `GBRAIN_GUARDRAILS_MODULE` (an absolute/relative file path or a
+ * bare package specifier). Accepted module shapes, all additive:
+ *
+ * - `export default provider` (a single {@link GuardrailProvider})
+ * - `export default [providerA, providerB]`
+ * - `export const guardrailProviders = [...]`
+ * - `export function register(registerGuardrailProvider) { ... }` (sync or async)
+ *
+ * Unset env var → no-op (the OSS distribution stays inert). Set-but-broken —
+ * import failure, or a module that registers zero providers — throws
+ * {@link GuardrailLoadError} (fail-closed; see class doc).
+ */
+export async function loadGuardrailProvidersFromEnv(
+ env: Record<string, string | undefined> = process.env,
+): Promise<GuardrailEnvLoadResult> {
+ const spec = env.GBRAIN_GUARDRAILS_MODULE?.trim();
+ if (!spec) return { loaded: 0, modulePath: null };
+
+ // File paths import via file:// URL so relative specs resolve against the
+ // operator's cwd, not against this module's location.
+ let target = spec;
+ if (spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('~')) {
+ const { resolve } = await import('node:path');
+ const { pathToFileURL } = await import('node:url');
+ const { homedir } = await import('node:os');
+ const expanded = spec.startsWith('~') ? spec.replace(/^~/, homedir()) : spec;
+ target = pathToFileURL(resolve(expanded)).href;
+ }
+
+ let mod: Record<string, unknown>;
+ try {
+ mod = (await import(target)) as Record<string, unknown>;
+ } catch (err) {
+ throw new GuardrailLoadError(
+ `GBRAIN_GUARDRAILS_MODULE=${spec} failed to load: ${(err as Error)?.message ?? String(err)}`,
+ );
+ }
+
+ const before = providers.size;
+ const candidates: unknown[] = [];
+ if (Array.isArray(mod.default)) candidates.push(...mod.default);
+ else if (mod.default) candidates.push(mod.default);
+ if (Array.isArray(mod.guardrailProviders)) candidates.push(...(mod.guardrailProviders as unknown[]));
+ for (const c of candidates) {
+ registerGuardrailProvider(c as GuardrailProvider);
+ }
+ if (typeof mod.register === 'function') {
+ await (mod.register as (r: typeof registerGuardrailProvider) => unknown)(registerGuardrailProvider);
+ }
+
+ const loaded = providers.size - before;
+ if (loaded <= 0) {
+ throw new GuardrailLoadError(
+ `GBRAIN_GUARDRAILS_MODULE=${spec} loaded but registered no guardrail provider ` +
+ `(expected a default-exported provider, a provider array, a guardrailProviders ` +
+ `export, or a register() function).`,
+ );
+ }
+ return { loaded, modulePath: spec };
+}
+
export async function runGuardrails(input: GuardrailInput): Promise<void> {
if (providers.size === 0) return;
const content = typeof input.content === 'string' ? input.content : '';
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 17db589f89..83310b07d9 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -9,7 +9,12 @@ import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION }
import { findChunkForOffset } from './chunkers/edge-extractor.ts';
import { planEmbeddingReuse } from './embed-reuse.ts';
import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';
-import { embedBatch, embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
+import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';
+// #3374 — import-path embeds ride the shared retry loop (429 retry-after +
+// transient network backoff) instead of bare embedBatch, so one socket blip
+// mid-sync no longer aborts the whole file import. Same core→commands edge
+// precedent as embed-stale.ts.
+import { embedBatchWithBackoff } from './embed-retry.ts';
import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';
import type { ChunkInput, PageInput, PageType } from './types.ts';
import { computeEffectiveDate } from './effective-date.ts';
@@ -37,9 +42,9 @@ import {
} from './embedding-context.ts';
import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
import { normalizeAliasList } from './search/alias-normalize.ts';
-import { isUndefinedTableError, warnOncePerProcess, validateSlug } from './utils.ts';
+import { isUndefinedTableError, warnOncePerProcess, validateSlug, contentHash, contentHashLegacy } from './utils.ts';
import { decorateEmbeddingDimError } from './embedding-dim-check.ts';
-import { computeCorpusGeneration } from './contextual-retrieval-service.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';
@@ -642,28 +647,24 @@ export async function importFromContent(
}
}
- const HASH_EPHEMERAL_FRONTMATTER_KEYS = [
- 'captured_at',
- 'ingested_at',
- QUARANTINE_KEY,
- CONTENT_FLAG_KEY,
- EMBED_SKIP_KEY,
- ];
- const stableFrontmatter: Record<string, unknown> = { ...parsed.frontmatter };
- for (const k of HASH_EPHEMERAL_FRONTMATTER_KEYS) {
- delete stableFrontmatter[k];
- }
- // Hash includes all meaningful fields for idempotency.
- const hash = createHash('sha256')
- .update(JSON.stringify({
- title: parsed.title,
- type: parsed.type,
- compiled_truth: parsed.compiled_truth,
- timeline: parsed.timeline,
- frontmatter: stableFrontmatter,
- tags: parsed.tags.sort(),
- }))
- .digest('hex');
+ // #3694: the hash formula lives in ONE place — utils.contentHash — shared
+ // with both engines' putPage fallback, so a page written via putPage and
+ // the same page re-imported by sync produce the SAME hash (pre-fix they
+ // diverged and every putPage→sync roundtrip re-chunked + re-embedded).
+ // The helper strips HASH_EPHEMERAL_FRONTMATTER_KEYS + the tags key from a
+ // frontmatter copy and folds sorted tags in — the exact former inline
+ // formula (byte-parity pinned by test/content-hash-parity-3694.test.ts).
+ // Sort tags in place first to preserve the pre-#3694 downstream behavior
+ // (parsedPage.tags was sorted by the old inline `.sort()` mutation).
+ parsed.tags.sort();
+ const hash = contentHash({
+ title: parsed.title,
+ type: parsed.type,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ tags: parsed.tags,
+ });
const parsedPage: ParsedPage = {
type: parsed.type,
@@ -678,6 +679,31 @@ export async function importFromContent(
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
}
+ // #3694 one-time reconcile: a row written by the PRE-fix putPage formula
+ // carries the legacy hash. When the parsed file matches that legacy hash,
+ // the content is unchanged — stamp the canonical hash via the narrow
+ // refreshPageBody UPDATE (no chunk churn, no re-embed, no version snapshot)
+ // and skip. The next import then hits the fast path above.
+ if (existing && !opts.forceRechunk && typeof engine.refreshPageBody === 'function') {
+ const legacyHash = contentHashLegacy({
+ title: parsed.title,
+ type: parsed.type,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ });
+ if (existing.content_hash === legacyHash) {
+ await engine.refreshPageBody(
+ slug,
+ sourceId ?? 'default',
+ parsed.compiled_truth,
+ parsed.timeline || '',
+ hash,
+ );
+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
+ }
+ }
+
// v0.41.13 (#1309) — identity-based cross-slug dedup pre-check.
//
// Catches the overlapping-ingest-roots bug class: when a user runs
@@ -791,15 +817,36 @@ export async function importFromContent(
if (!opts.noEmbed) {
const searchInput = await loadSearchModeConfig(engine);
const knobs = resolveSearchMode(searchInput);
- // Look up the source row for this import; default to host trust when
- // the engine's getConfig path doesn't surface a source row (most calls).
+ // #3885: load the REAL source row so a stored `gbrain sources
+ // set-cr-mode <id> <mode>` (and the mount trust flag) applies on the
+ // inline import path — capture + reindex --markdown — not just the
+ // Minion backfill. The prior hardcoded stub (contextual_retrieval_mode:
+ // null / trust_frontmatter_overrides: false) silently ignored the
+ // per-source override. Unknown source id / pre-sources-table brains
+ // keep the stub (host-trust defaults).
+ let sourceRow: {
+ id: string;
+ contextual_retrieval_mode?: string | null;
+ trust_frontmatter_overrides?: boolean;
+ } = {
+ id: sourceId ?? 'default',
+ contextual_retrieval_mode: null,
+ trust_frontmatter_overrides: false,
+ };
+ try {
+ const row = await loadSourceRow(engine, sourceId ?? 'default');
+ sourceRow = {
+ id: row.id,
+ contextual_retrieval_mode: row.contextual_retrieval_mode ?? null,
+ trust_frontmatter_overrides: row.trust_frontmatter_overrides === true,
+ };
+ } catch {
+ // Source row missing ('default' not seeded on a fresh brain) — the
+ // stub stands, matching pre-#3885 behavior.
+ }
const resolution = resolveContextualRetrievalMode({
pageFrontmatter: parsed.frontmatter,
- source: {
- id: sourceId ?? 'default',
- contextual_retrieval_mode: null,
- trust_frontmatter_overrides: false,
- },
+ source: sourceRow,
globalMode: knobs.contextual_retrieval,
killSwitchDisabled: knobs.contextual_retrieval_disabled,
});
@@ -819,7 +866,7 @@ export async function importFromContent(
const wrappedTexts = prefix
? chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source))
: chunks.map((c) => c.chunk_text);
- const embeddings = await embedBatch(wrappedTexts);
+ const embeddings = await embedBatchWithBackoff(wrappedTexts);
for (let i = 0; i < chunks.length; i++) {
chunks[i].embedding = embeddings[i];
// token_count tracks the wrapped string length so cost reporting
@@ -1223,6 +1270,8 @@ export async function importFromFile(
const expectedSlug = slugifyPath(relativePath);
let resolvedSlug = expectedSlug;
let usedFrontmatterFallback = false;
+ let fallbackReason: 'path slugified empty' | 'normalization-equivalent identity restore' =
+ 'path slugified empty';
if (frontmatterError) {
return {
@@ -1254,22 +1303,36 @@ export async function importFromFile(
};
}
} else if (parsed.slug !== expectedSlug) {
- // Anti-spoof preserved: path DOES derive a slug, but the frontmatter slug
- // claims a different one. Reject.
- return {
- slug: expectedSlug,
- status: 'skipped',
- chunks: 0,
- error:
- `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expectedSlug}" ` +
- `(from ${relativePath}). Remove the frontmatter "slug:" line or move the file.`,
- };
+ if (slugifyPath(parsed.slug) === expectedSlug) {
+ // #3772: normalization-equivalent — the frontmatter slug is a stored
+ // identity whose slugified spelling IS the path-derived slug. Export
+ // writes files at <slug>.md and stamps the original slug whenever it
+ // isn't a slugifyPath fixed point (legacy/hand-keyed slugs with case,
+ // apostrophes, accents…); accepting it here is what makes an
+ // export → import round-trip preserve page keys instead of silently
+ // re-keying. Anti-spoof holds: a slug claiming a DIFFERENT page
+ // normalizes to a different path and still rejects below.
+ resolvedSlug = parsed.slug;
+ usedFrontmatterFallback = true;
+ fallbackReason = 'normalization-equivalent identity restore';
+ } else {
+ // Anti-spoof preserved: path DOES derive a slug, but the frontmatter slug
+ // claims a different one. Reject.
+ return {
+ slug: expectedSlug,
+ status: 'skipped',
+ chunks: 0,
+ error:
+ `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expectedSlug}" ` +
+ `(from ${relativePath}). Remove the frontmatter "slug:" line or move the file.`,
+ };
+ }
}
// Emit the dual-channel audit entry AFTER we know we're not going to
// short-circuit, so we don't log noise for failed imports.
if (usedFrontmatterFallback) {
- logSlugFallback(resolvedSlug, relativePath);
+ logSlugFallback(resolvedSlug, relativePath, fallbackReason);
}
// Pass the resolved slug explicitly so that any future change to
@@ -1413,7 +1476,7 @@ export async function importCodeFile(
if (!opts.noEmbed && needsEmbedIndexes.length > 0) {
try {
const textsToEmbed = needsEmbedIndexes.map((i) => chunks[i]!.chunk_text);
- const embeddings = await embedBatch(textsToEmbed);
+ const embeddings = await embedBatchWithBackoff(textsToEmbed);
for (let j = 0; j < needsEmbedIndexes.length; j++) {
const i = needsEmbedIndexes[j]!;
chunks[i]!.embedding = embeddings[j]!;
@@ -1761,6 +1824,7 @@ async function readExifSafe(buf: Buffer): Promise<Record<string, unknown>> {
* - the embedding_image_ocr config flag is off (default)
* - the configured expansion model is unavailable (no API key)
* - the OCR call itself fails (logged once per session)
+ * - the per-run OCR budget is exhausted (#3973 — see _ocrRunBudget below)
*
* Eng-1B: per-call result is reflected in counters the doctor `ocr_health`
* check reads. Counter writes are best-effort; never fail the import.
@@ -1769,6 +1833,59 @@ async function readExifSafe(buf: Buffer): Promise<Record<string, unknown>> {
* embedded in the image (mitigation for the OCR-as-prompt-injection vector).
*/
let _ocrWarnedThisSession = false;
+
+// #3973: per-run OCR ceiling. A bulk import over a large image corpus with
+// OCR opted-in is an unbounded per-image LLM spend; cap it per process run.
+// Config keys (both finite by default; <= 0 disables that cap):
+// embedding_image_ocr_max_images — max OCR calls per run (default 200)
+// embedding_image_ocr_max_usd — estimated-USD ceiling per run (default 1.0,
+// estimated at OCR_EST_USD_PER_IMAGE per call — a documented constant,
+// not a billing read; actual spend lands on the budget tracker (#4121)).
+// Over-cap: skip OCR (import continues with filename-only chunk text), warn
+// once, bump the persistent `ocr_skipped_budget` counter that doctor's
+// ocr_health check surfaces.
+const OCR_EST_USD_PER_IMAGE = 0.002;
+const OCR_MAX_IMAGES_DEFAULT = 200;
+const OCR_MAX_USD_DEFAULT = 1.0;
+const _ocrRunBudget = { images: 0, estUsd: 0, warned: false };
+
+/** Test seam: reset (and optionally preset) the per-run OCR budget state. */
+export function _resetOcrRunBudgetForTests(preset?: { images?: number; estUsd?: number }): void {
+ _ocrRunBudget.images = preset?.images ?? 0;
+ _ocrRunBudget.estUsd = preset?.estUsd ?? 0;
+ _ocrRunBudget.warned = false;
+}
+
+/** Test seam: read the per-run OCR budget state. */
+export function _getOcrRunBudgetForTests(): { images: number; estUsd: number; warned: boolean } {
+ return { ..._ocrRunBudget };
+}
+
+/** Returns a human reason when this run's OCR cap is exhausted, else null. */
+async function ocrBudgetExceeded(engine: BrainEngine): Promise<string | null> {
+ let maxImages = OCR_MAX_IMAGES_DEFAULT;
+ let maxUsd = OCR_MAX_USD_DEFAULT;
+ try {
+ const rawImages = await engine.getConfig('embedding_image_ocr_max_images');
+ if (rawImages != null && rawImages !== '') {
+ const n = Number(rawImages);
+ if (Number.isFinite(n)) maxImages = n;
+ }
+ const rawUsd = await engine.getConfig('embedding_image_ocr_max_usd');
+ if (rawUsd != null && rawUsd !== '') {
+ const n = Number(rawUsd);
+ if (Number.isFinite(n)) maxUsd = n;
+ }
+ } catch { /* config unavailable → finite defaults still apply */ }
+ if (maxImages > 0 && _ocrRunBudget.images >= maxImages) {
+ return `per-run image cap reached (${_ocrRunBudget.images}/${maxImages}; raise embedding_image_ocr_max_images to OCR more)`;
+ }
+ if (maxUsd > 0 && _ocrRunBudget.estUsd >= maxUsd) {
+ return `per-run estimated-USD cap reached (~$${_ocrRunBudget.estUsd.toFixed(3)} of $${maxUsd}; raise embedding_image_ocr_max_usd to OCR more)`;
+ }
+ return null;
+}
+
async function maybeOcr(
engine: BrainEngine,
imgBuf: Buffer,
@@ -1776,6 +1893,23 @@ async function maybeOcr(
): Promise<string> {
const opt = process.env.GBRAIN_EMBEDDING_IMAGE_OCR;
if (opt !== 'true') return '';
+ return maybeOcrGated(engine, imgBuf, mime);
+}
+
+/** #3973: body of maybeOcr past the opt-in check; exported for budget tests. */
+export async function _maybeOcrGatedForTests(
+ engine: BrainEngine,
+ imgBuf: Buffer,
+ mime: string,
+): Promise<string> {
+ return maybeOcrGated(engine, imgBuf, mime);
+}
+
+async function maybeOcrGated(
+ engine: BrainEngine,
+ imgBuf: Buffer,
+ mime: string,
+): Promise<string> {
// Counter helpers — quiet failure if config table is unavailable.
async function bump(key: string) {
@@ -1785,6 +1919,20 @@ async function maybeOcr(
} catch { /* non-fatal */ }
}
+ // #3973: budget gate fires BEFORE the attempt counter — a budget skip is
+ // not an attempt, and the skip has its own counter for doctor ocr_health.
+ const overBudget = await ocrBudgetExceeded(engine);
+ if (overBudget) {
+ if (!_ocrRunBudget.warned) {
+ console.warn(`[gbrain] OCR skipped for the rest of this run: ${overBudget}`);
+ _ocrRunBudget.warned = true;
+ }
+ await bump('ocr_skipped_budget');
+ return '';
+ }
+ _ocrRunBudget.images += 1;
+ _ocrRunBudget.estUsd += OCR_EST_USD_PER_IMAGE;
+
await bump('ocr_attempted');
try {
const { isAvailable, generateOcrText } = await import('./ai/gateway.ts');
diff --git a/src/core/ingestion/daemon.ts b/src/core/ingestion/daemon.ts
index ea69eeebaf..d48e5be698 100644
--- a/src/core/ingestion/daemon.ts
+++ b/src/core/ingestion/daemon.ts
@@ -440,7 +440,16 @@ export class IngestionDaemon {
// 'trickle' for v0.38 back-compat.
const sourceMode = state.registration.source.mode ?? 'trickle';
if (sourceMode === 'trickle') {
- const isNew = this.dedup.mark(sourceKind, effectiveEvent.content_hash);
+ // #3756: tombstones dedup on (source_kind, 'tombstone', slug) — two
+ // deletes of the same slug within the window are one delete, and a
+ // tombstone must never collide with an upsert that happens to carry
+ // the same content_hash. The 'tombstone\0' prefix keeps the two key
+ // spaces disjoint (slugs can't contain NUL — validateSlug rejects
+ // control bytes; hex hashes trivially can't).
+ const dedupKey = effectiveEvent.kind === 'tombstone'
+ ? `tombstone\0${effectiveEvent.slug}`
+ : effectiveEvent.content_hash;
+ const isNew = this.dedup.mark(sourceKind, dedupKey);
if (!isNew) {
// Silent dedup hit. dedup.hits counter already incremented.
return;
diff --git a/src/core/ingestion/types.ts b/src/core/ingestion/types.ts
index 9c07fc380b..1d23593d19 100644
--- a/src/core/ingestion/types.ts
+++ b/src/core/ingestion/types.ts
@@ -95,6 +95,22 @@ export interface IngestionEvent {
* responsibility because the source knows whether content is text or
* a path-pointer. */
content_hash: string;
+ /**
+ * Event kind (#3756). 'upsert' (the default when unset — every pre-existing
+ * source keeps its behavior) imports `content` as a page. 'tombstone'
+ * signals the source observed a DELETION upstream: the daemon dedups it on
+ * (source_kind, 'tombstone', slug) instead of content_hash, and the
+ * ingest_capture handler maps it to a reconciler-style soft-delete of
+ * `slug` — trusted emitters only (untrusted_payload events must never
+ * delete).
+ */
+ kind?: 'upsert' | 'tombstone';
+ /**
+ * Target page slug (#3756). REQUIRED for kind:'tombstone' (names the page
+ * to soft-delete). Optional for upserts, where it takes precedence over
+ * `metadata.slug` and the generated inbox default.
+ */
+ slug?: string;
/**
* Trust tag. Set to true by sources that receive input from untrusted
* channels (webhook, future URL fetcher sources). The downstream put_page
@@ -309,6 +325,31 @@ export function validateIngestionEvent(event: unknown): IngestionEventError | nu
);
}
+ // kind is optional; when present it must be from the closed set (#3756).
+ if (e.kind !== undefined && e.kind !== 'upsert' && e.kind !== 'tombstone') {
+ return new IngestionEventError(
+ 'kind',
+ `must be 'upsert' or 'tombstone' when present; got '${String(e.kind)}'`,
+ e as Partial<IngestionEvent>,
+ );
+ }
+
+ // slug is optional for upserts, REQUIRED for tombstones (#3756).
+ if (e.slug !== undefined && (typeof e.slug !== 'string' || e.slug.length === 0)) {
+ return new IngestionEventError(
+ 'slug',
+ 'must be a non-empty string when present',
+ e as Partial<IngestionEvent>,
+ );
+ }
+ if (e.kind === 'tombstone' && typeof e.slug !== 'string') {
+ return new IngestionEventError(
+ 'slug',
+ "is required for kind 'tombstone' (names the page to soft-delete)",
+ e as Partial<IngestionEvent>,
+ );
+ }
+
// untrusted_payload is optional but must be boolean if present.
if (e.untrusted_payload !== undefined && typeof e.untrusted_payload !== 'boolean') {
return new IngestionEventError(
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 0938210150..98d205aa66 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -18,6 +18,19 @@ import { stripCodeBlocks } from './markdown-code.ts';
import { parseInlineCitationTimelineEntries } from './timeline-citations.ts';
import { slugifyPath } from './sync.ts';
import { SLUG_WORD_CHARS } from './cjk.ts';
+// #3190: pack-aware link typing. link-inference imports only manifest-v1
+// (zod) + redos-guard (node:vm) — no cycle back into this module.
+import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';
+import { inferLinkTypeFromPack, frontmatterLinkTypeFromPack } from './schema-pack/link-inference.ts';
+import { PageRegexBudget } from './schema-pack/redos-guard.ts';
+
+/**
+ * #3190: the slice of a schema-pack manifest link extraction consumes.
+ * Callers thread the ACTIVE pack's manifest (loadActivePackForLocalEngine /
+ * loadActivePackBestEffort → `.manifest`); null/undefined keeps the legacy
+ * in-code inference exactly as before.
+ */
+export type LinkExtractionPack = Pick<SchemaPackManifest, 'link_types' | 'frontmatter_links'>;
export { stripCodeBlocks } from './markdown-code.ts';
export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidate } from './timeline-citations.ts';
@@ -91,6 +104,15 @@ export interface EntityRef {
* — the reason subtree-scoped / nested brains got zero cross-dir edges.
*/
upLevels?: number;
+ /**
+ * #3190: set for a same-directory markdown link — `[Name](slug.md)` with
+ * no directory segment and no scheme. `slug` holds the target basename
+ * (`.md` stripped); the caller (`extractPageLinks`) resolves it against
+ * the LINKING page's directory, mirroring the FS path's `resolveSlug`.
+ * Pre-fix these refs were silently dropped (pass 1 requires `dir/`),
+ * so flat directories and sibling links produced zero DB-path edges.
+ */
+ sameDir?: boolean;
}
/**
@@ -212,6 +234,16 @@ const WIKILINK_GENERIC_RE = /\[\[([^|\]#\n[]+?)(?:#[^|\]]*?)?(?:\|([^\]]+?))?\]\
*/
const MARKDOWN_LABEL_WIKILINK_RE = /\[[^\]\n]*\[\[[^\]\n]+\]\][^\]\n]*\]\([^)\n]+\)/g;
+/**
+ * #3190: same-directory markdown link — `[Name](slug.md)` whose target has
+ * NO directory segment and NO scheme/anchor (`/`, `:`, `#` all excluded).
+ * The `.md` suffix is REQUIRED (mirrors the FS extractor's mdPattern) so
+ * bare parenthetical prose (`[sic](reference)`) never produces a ref.
+ * Resolution against the linking page's directory happens in
+ * extractPageLinks (this module has no page context here).
+ */
+const SAME_DIR_MD_RE = /\[([^\]]+)\]\(([^)/:#\s]+?)\.md\)/g;
+
/**
* A code-reference found in markdown prose. Created by extractCodeRefs and
* consumed by importFromFile's tail to build doc↔impl edges (v0.19.0 E1).
@@ -349,6 +381,23 @@ export function extractEntityRefs(content: string): EntityRef[] {
markdownRanges.push([match.index, match.index + match[0].length]);
}
+ // 1b. #3190: same-directory markdown links — `[Name](slug.md)` (no `/`,
+ // no scheme). Pass 1 requires a `dir/` segment, so sibling links in
+ // flat directories were silently dropped on the DB path while the FS
+ // walker (extractMarkdownLinks → resolveSlug) linked them. Tagged
+ // `sameDir: true`; extractPageLinks resolves against the page's dir.
+ // Disjoint from pass 1 (its targets always contain `/`).
+ const sameDirPattern = new RegExp(SAME_DIR_MD_RE.source, SAME_DIR_MD_RE.flags);
+ while ((match = sameDirPattern.exec(stripped)) !== null) {
+ const name = match[1];
+ let target = match[2];
+ if (target.includes('%')) {
+ try { target = decodeURIComponent(target); } catch { /* keep raw */ }
+ }
+ refs.push({ name, slug: target, dir: '', sameDir: true });
+ markdownRanges.push([match.index, match.index + match[0].length]);
+ }
+
// 2a. v0.17.0 qualified wikilinks: [[source-id:path]] or [[source-id:path|Display]]
// Must run BEFORE the unqualified pass or we'd double-emit. We also
// mask out the matched spans so pass 2b can't grab them.
@@ -356,7 +405,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
const qualPattern = new RegExp(QUALIFIED_WIKILINK_RE.source, QUALIFIED_WIKILINK_RE.flags);
while ((match = qualPattern.exec(stripped)) !== null) {
const sourceId = match[1];
- let slug = match[2].trim();
+ let slug = stripEscapedPipeTail(match[2].trim());
if (!slug) continue;
if (slug.includes('://')) continue;
if (slug.endsWith('.md')) slug = slug.slice(0, -3);
@@ -372,7 +421,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
const unmasked = maskRanges(stripped, qualifiedRanges);
const wikiPattern = new RegExp(WIKILINK_RE.source, WIKILINK_RE.flags);
while ((match = wikiPattern.exec(unmasked)) !== null) {
- let slug = match[1].trim();
+ let slug = stripEscapedPipeTail(match[1].trim());
if (!slug) continue;
if (slug.includes('://')) continue;
if (slug.endsWith('.md')) slug = slug.slice(0, -3);
@@ -403,7 +452,7 @@ export function extractEntityRefs(content: string): EntityRef[] {
);
const genericPattern = new RegExp(WIKILINK_GENERIC_RE.source, WIKILINK_GENERIC_RE.flags);
while ((match = genericPattern.exec(genericMasked)) !== null) {
- let slug = match[1].trim();
+ let slug = stripEscapedPipeTail(match[1].trim());
if (!slug) continue;
if (slug.includes('://')) continue;
if (slug.includes(':')) continue; // qualified-syntax token; 2a owns these
@@ -416,6 +465,20 @@ export function extractEntityRefs(content: string): EntityRef[] {
return refs;
}
+/**
+ * #4062: strip the trailing backslash(es) an escaped pipe leaves on a
+ * wikilink target. Inside a markdown table cell the pipe separating the
+ * target from its display alias MUST be escaped (`[[dir/slug\|Alias]]`,
+ * Obsidian's own table syntax) or it would end the cell. The wikilink
+ * slug captures stop at the literal `|`, so the escape backslash lands as
+ * the final character of the captured target — a slug shape that can
+ * never match a real page. Slugs never legitimately contain backslashes,
+ * so stripping the trailing run is lossless. Applied to passes 2a/2b/2c.
+ */
+function stripEscapedPipeTail(slug: string): string {
+ return slug.replace(/\\+$/, '');
+}
+
/**
* Replace the byte ranges with spaces, preserving offsets. Used by
* extractEntityRefs to prevent the unqualified wikilink regex from
@@ -522,12 +585,49 @@ export async function extractPageLinks(
frontmatter: Record<string, unknown>,
pageType: PageType,
resolver: SlugResolver,
- opts: { globalBasename?: boolean; skipFrontmatter?: boolean } = {},
+ opts: { globalBasename?: boolean; skipFrontmatter?: boolean; pack?: LinkExtractionPack | null } = {},
): Promise<PageLinksResult> {
const candidates: LinkCandidate[] = [];
+ // #3190: pack-aware verb inference. Pack-declared verbs win (page-type
+ // bindings, then pack regexes under the shared per-page ReDoS budget);
+ // the in-code inferLinkType stays the fall-through for everything the
+ // pack doesn't claim — matching the resolution order extract-ner already
+ // ships (schema-pack/link-inference.ts header). Pre-fix a user pack's
+ // `link_types[].inference.regex` (e.g. parent_of) was silently ignored
+ // here and every such edge landed as 'mentions'.
+ const pack = opts.pack ?? null;
+ const packBudget = pack ? new PageRegexBudget() : undefined;
+ const typeFor = (ctx: string, targetSlug: string): string => {
+ if (pack) {
+ const packVerb = inferLinkTypeFromPack(pack, pageType as string, ctx, packBudget);
+ if (packVerb) return packVerb;
+ }
+ return inferLinkType(pageType, ctx, content, targetSlug);
+ };
+
// 1. Markdown entity refs.
for (const ref of extractEntityRefs(content)) {
+ // #3190: same-directory markdown link — resolve against THIS page's
+ // directory (the FS path's resolveSlug does exactly this via
+ // join(fileDir, target)). Slugified through the sync grammar so
+ // `[Alice](Alice%20Chen.md)` reaches `people/alice-chen`. Downstream
+ // existence checks drop targets that aren't pages.
+ if (ref.sameDir) {
+ const dirSegs = slug.includes('/') ? slug.split('/').slice(0, -1) : [];
+ const target = slugifyPath([...dirSegs, ref.slug].join('/'));
+ if (target && target !== slug) {
+ const idx = content.indexOf(ref.name);
+ const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
+ candidates.push({
+ targetSlug: target,
+ linkType: typeFor(context, target),
+ context,
+ linkSource: 'markdown',
+ });
+ }
+ continue;
+ }
// Issue #972: refs from the generic `[[bare-name]]` pass carry the
// literal wikilink text, not a real page slug. When global_basename
// mode is on AND the resolver implements basename lookup, resolve
@@ -551,11 +651,35 @@ export async function extractPageLinks(
const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
candidates.push({
targetSlug: ref.slug,
- linkType: inferLinkType(pageType, litContext, content, ref.slug),
+ linkType: typeFor(litContext, ref.slug),
context: litContext,
linkSource: 'markdown',
});
}
+ // #4062: a bare `[[name]]` (no slash) gets a direct verb-typed
+ // candidate for its root-exact slugified form, emitted regardless of
+ // the global_basename flag — mirroring the FS path, where resolveSlug's
+ // ancestor walk resolves `[[x]]` to a root page `x` before the
+ // basename fallback ever runs. Pre-fix the DB path dropped these
+ // entirely flag-off (0 candidates) while the FS path linked them.
+ // Downstream existence checks (resolveCandidateSources / put_page's
+ // allSlugs filter / addLinksBatch's INNER JOINs) drop the candidate
+ // when no root page exists, exactly as for slash-shaped refs above.
+ let bareDirect = '';
+ if (slashIdx === -1) {
+ bareDirect = slugifyPath(ref.slug);
+ // Self-loop guard: `[[own-basename]]` on the root page itself.
+ if (bareDirect && bareDirect !== slug) {
+ const litIdx = content.indexOf(ref.slug);
+ const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
+ candidates.push({
+ targetSlug: bareDirect,
+ linkType: typeFor(litContext, bareDirect),
+ context: litContext,
+ linkSource: 'markdown',
+ });
+ }
+ }
if (typeof resolver.resolveBasenameMatches !== 'function') continue;
// Issue #972 (codex): resolve by the wikilink TARGET (ref.slug — the
// text inside `[[...]]` before any `|`), NOT the display alias
@@ -579,7 +703,11 @@ export async function extractPageLinks(
matches = (await resolver.resolveBasenameMatches(tail))
.filter(m => m !== ref.slug && (m === slugified || m.endsWith(`/${slugified}`)));
} else if (opts.globalBasename) {
- matches = await resolver.resolveBasenameMatches(ref.slug);
+ // #4062: exclude the root-exact slugified form — the direct typed
+ // candidate above already covers it (same rule the dir-qualified
+ // branch applies to its raw literal). Keeping it would double-emit.
+ matches = (await resolver.resolveBasenameMatches(ref.slug))
+ .filter(m => m !== bareDirect);
}
if (matches.length === 0) continue;
const idx = content.indexOf(ref.slug);
@@ -609,7 +737,7 @@ export async function extractPageLinks(
const targetSlug = resolveRelativeSlug(slug, ref);
candidates.push({
targetSlug,
- linkType: inferLinkType(pageType, context, content, targetSlug),
+ linkType: typeFor(context, targetSlug),
context,
linkSource: 'markdown',
});
@@ -643,7 +771,7 @@ export async function extractPageLinks(
const context = excerpt(strippedContent, m.index, 240);
candidates.push({
targetSlug: m[1],
- linkType: inferLinkType(pageType, context, content, m[1]),
+ linkType: typeFor(context, m[1]),
context,
linkSource: 'markdown',
});
@@ -659,7 +787,7 @@ export async function extractPageLinks(
// path needed `resolveBasenameMatches` on the real resolver.
let fmUnresolved: UnresolvedFrontmatterRef[] = [];
if (!opts.skipFrontmatter) {
- const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename);
+ const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename, pack);
candidates.push(...fm.candidates);
fmUnresolved = fm.unresolved;
}
@@ -1186,11 +1314,34 @@ export async function extractFrontmatterLinks(
frontmatter: Record<string, unknown>,
resolver: SlugResolver,
globalBasename = false,
+ pack?: LinkExtractionPack | null,
): Promise<FrontmatterExtractResult> {
const candidates: LinkCandidate[] = [];
const unresolved: UnresolvedFrontmatterRef[] = [];
- for (const mapping of FRONTMATTER_LINK_MAP) {
+ // #3190: append pack-declared frontmatter_links as OUTGOING mappings.
+ // Pre-fix a pack's `frontmatter_links` table (e.g. `parents:` →
+ // parent_of) was dead weight — only the hardcoded FRONTMATTER_LINK_MAP
+ // ever ran, so pack-declared fields produced 0 candidates. Field → verb
+ // resolution goes through frontmatterLinkTypeFromPack (first matching
+ // pack rule for this page type wins, the helper's documented contract).
+ // Built-ins keep their table order; pack mappings run after, and the
+ // final within-page dedup collapses exact duplicates.
+ const packMappings: FrontmatterFieldMapping[] = [];
+ if (pack && pack.frontmatter_links.length > 0) {
+ const seenFields = new Set<string>();
+ for (const fl of pack.frontmatter_links) {
+ for (const field of fl.fields) {
+ if (seenFields.has(field)) continue;
+ seenFields.add(field);
+ const type = frontmatterLinkTypeFromPack(pack, pageType as string, field);
+ if (!type) continue; // no pack rule for this page type
+ packMappings.push({ fields: [field], type, direction: 'outgoing', dirHint: '' });
+ }
+ }
+ }
+
+ for (const mapping of [...FRONTMATTER_LINK_MAP, ...packMappings]) {
if (mapping.pageType && mapping.pageType !== pageType) continue;
for (const field of mapping.fields) {
const value = frontmatter[field];
@@ -1276,15 +1427,59 @@ export interface TimelineCandidate {
summary: string;
/** Optional detail (subsequent lines until next entry/heading). */
detail: string;
+ /**
+ * #3957: source label. Pipe-separated bullets split `Source — Summary`
+ * (via findTimelineSourceDelimiter, the SAME split the FS extractor in
+ * timeline-extract.ts applies), inline citations carry their `[Source: X]`
+ * label, everything else defaults to 'markdown'. Pre-fix the DB path left
+ * this unset, so callers wrote source='' while the FS path wrote the split
+ * label + trimmed summary — the (page_id, date, summary, source) dedup
+ * index saw two shapes for the same bullet and every FS-then-DB (or
+ * DB-then-FS) re-extraction duplicated the row.
+ */
+ source?: string;
+}
+
+/**
+ * #3957 (moved from timeline-extract.ts so BOTH parsers share it): index of
+ * the first dash (—, –, -) that can serve as the `Source — Summary`
+ * delimiter: it must have whitespace on both sides and sit outside every
+ * markdown-link span. Hyphens inside link targets
+ * (`../people/alice-example.md`) and dashes inside link labels
+ * (`[Deals — Q1 Review](...)`) are content, not delimiters — splitting on
+ * them shatters one entry into two fragments whose halves re-insert on
+ * every sync (the (page_id, date, summary, source) uniqueness sees each
+ * fragment shape as a new row). Returns -1 when the line has no delimiter.
+ */
+export function findTimelineSourceDelimiter(text: string): number {
+ let depth = 0;
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if (c === '[' || c === '(') depth++;
+ else if (c === ']' || c === ')') { if (depth > 0) depth--; }
+ else if (
+ depth === 0 &&
+ (c === '—' || c === '–' || c === '-') &&
+ i > 0 && /\s/.test(text[i - 1]) &&
+ i + 1 < text.length && /\s/.test(text[i + 1])
+ ) {
+ return i;
+ }
+ }
+ return -1;
}
// Match: `- **YYYY-MM-DD** | summary` or `- **YYYY-MM-DD** -- summary`
// or `- **YYYY-MM-DD** - summary` or just `**YYYY-MM-DD** | summary`.
-const TIMELINE_LINE_RE = /^\s*-?\s*\*\*(\d{4}-\d{2}-\d{2})\*\*\s*[|\-–—]+\s*(.+?)\s*$/;
+// #3957: the separator run is captured so the parser can apply the
+// `Source — Summary` split ONLY to pipe-separated bullets (the canonical
+// shape the FS extractor matches); a dash-separated bullet's rest is one
+// summary and must not be shattered on its first interior dash.
+const TIMELINE_LINE_RE = /^\s*-?\s*\*\*(\d{4}-\d{2}-\d{2})\*\*\s*([|\-–—]+)\s*(.+?)\s*$/;
// Chinese date lines: `- 2020年1月2日 | summary` (bold optional). Requires the
// 年/月 markers so plain ASCII `- 2020-01-02 - text` does NOT match — non-bold
// ASCII dates were never timeline entries and must stay that way.
-const TIMELINE_LINE_RE_CN = /^\s*-?\s*(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*[|\-–—]+\s*(.+?)\s*$/;
+const TIMELINE_LINE_RE_CN = /^\s*-?\s*(?:\*\*)?(\d{4})年(\d{1,2})月(\d{1,2})日?(?:\*\*)?\s*([|\-–—]+)\s*(.+?)\s*$/;
/**
* Parse timeline entries from content. Looks at:
@@ -1305,17 +1500,33 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
const m = TIMELINE_LINE_RE.exec(lines[i]);
let date: string;
let summary: string;
+ let separator: string;
if (m) {
date = m[1];
- summary = m[2].trim();
+ separator = m[2];
+ summary = m[3].trim();
} else {
const cm = TIMELINE_LINE_RE_CN.exec(lines[i]);
if (!cm) { i++; continue; }
// Normalize Chinese date to YYYY-MM-DD
date = `${cm[1]}-${cm[2].padStart(2, '0')}-${cm[3].padStart(2, '0')}`;
- summary = cm[4].trim();
+ separator = cm[4];
+ summary = cm[5].trim();
}
if (!isValidDate(date) || summary.length === 0) { i++; continue; }
+ // #3957: pipe-separated bullets carry the canonical `Source — Summary`
+ // shape; split them exactly like the FS extractor (extractTimelineFromContent
+ // Format 1) so FS- and DB-extracted rows share one (source, summary) shape
+ // and the DB dedup index collapses re-extractions instead of duplicating.
+ // Dash-separated bullets (`- **DATE** - text`) are one summary — no split.
+ let source = 'markdown';
+ if (separator.includes('|')) {
+ const at = findTimelineSourceDelimiter(summary);
+ if (at >= 0) {
+ source = summary.slice(0, at).trim();
+ summary = summary.slice(at + 1).trim();
+ }
+ }
// Collect optional detail lines (indented, until next date or heading).
const detailLines: string[] = [];
let j = i + 1;
@@ -1338,7 +1549,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
}
break;
}
- result.push({ date, summary, detail: detailLines.join(' ').trim() });
+ result.push({ date, summary, detail: detailLines.join(' ').trim(), source });
i = j;
}
@@ -1352,7 +1563,10 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
for (const entry of parseInlineCitationTimelineEntries(content, {
skipLine: (line) => TIMELINE_LINE_RE.test(line) || TIMELINE_LINE_RE_CN.test(line),
})) {
- result.push({ date: entry.date, summary: entry.summary, detail: `Source: ${entry.source}` });
+ // #3957: carry the citation's source label in `source` (the dedup-key
+ // column) so the row shape matches the FS extractor's Format 3; the
+ // human-readable detail is kept for existing consumers.
+ result.push({ date: entry.date, summary: entry.summary, detail: `Source: ${entry.source}`, source: entry.source });
}
return result;
}
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index 453a51dbe9..22b05c4801 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -438,9 +438,12 @@ function collectValidationErrors(
}
// 7. SLUG_MISMATCH — only when expectedSlug was provided and a slug field exists.
+ // #3772: a declared slug whose slugified spelling equals the path-derived
+ // slug is normalization-equivalent (export stamps these to preserve
+ // legacy page identities across a round-trip) — not a mismatch.
if (ctx.expectedSlug && typeof ctx.parsedFrontmatter.slug === 'string') {
const declared = ctx.parsedFrontmatter.slug as string;
- if (declared !== ctx.expectedSlug) {
+ if (declared !== ctx.expectedSlug && slugifyPath(declared) !== ctx.expectedSlug) {
errors.push({
code: 'SLUG_MISMATCH',
message: `Frontmatter slug "${declared}" does not match path-derived slug "${ctx.expectedSlug}"`,
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 2e279d2b18..e5043db66e 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -8,7 +8,8 @@ import {
isStatementTimeoutError,
isRetryableConnError,
} from './retry-matcher.ts';
-import { repairTimelineDedupIndex } from './timeline-dedup-repair.ts';
+import { repairTimelineDedupIndex, repairLegacyTimelineSourceRows } from './timeline-dedup-repair.ts';
+import { repairPagesUpsertArbiter } from './pages-upsert-arbiter.ts';
/**
* When true, per-migration explanatory notices (e.g. the v123/v124 "here is
@@ -634,12 +635,24 @@ export const MIGRATIONS: Migration[] = [
// 0b. Swap pages.UNIQUE(slug) → UNIQUE(source_id, slug).
// Deferred from v21 so PR #356 closes the integrity
// window. PGLite already did this swap in its v21 path.
+ // #550: guard by index SHAPE (any non-partial unique index on
+ // exactly {source_id, slug}), not by constraint NAME — a
+ // name-only guard skips the ADD when the name is squatted by a
+ // misshapen constraint, leaving every putPage ON CONFLICT broken.
await tx.runMigration(23, `
ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_slug_key;
DO $$ BEGIN
IF NOT EXISTS (
- SELECT 1 FROM pg_constraint WHERE conname = 'pages_source_slug_key'
+ SELECT 1 FROM pg_index i
+ WHERE i.indrelid = 'pages'::regclass
+ AND i.indisunique
+ AND i.indpred IS NULL
+ AND (SELECT array_agg(a.attname::text ORDER BY a.attname)
+ FROM pg_attribute a
+ WHERE a.attrelid = i.indrelid
+ AND a.attnum = ANY (i.indkey::int2[])) = ARRAY['slug','source_id']
) THEN
+ ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_source_slug_key;
ALTER TABLE pages ADD CONSTRAINT pages_source_slug_key
UNIQUE (source_id, slug);
END IF;
@@ -791,10 +804,19 @@ export const MIGRATIONS: Migration[] = [
CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id);
ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_slug_key;
+ -- #550: guard by index SHAPE, not constraint NAME (see v23 twin).
DO $$ BEGIN
IF NOT EXISTS (
- SELECT 1 FROM pg_constraint WHERE conname = 'pages_source_slug_key'
+ SELECT 1 FROM pg_index i
+ WHERE i.indrelid = 'pages'::regclass
+ AND i.indisunique
+ AND i.indpred IS NULL
+ AND (SELECT array_agg(a.attname::text ORDER BY a.attname)
+ FROM pg_attribute a
+ WHERE a.attrelid = i.indrelid
+ AND a.attnum = ANY (i.indkey::int2[])) = ARRAY['slug','source_id']
) THEN
+ ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_source_slug_key;
ALTER TABLE pages ADD CONSTRAINT pages_source_slug_key
UNIQUE (source_id, slug);
END IF;
@@ -5236,7 +5258,7 @@ export const MIGRATIONS: Migration[] = [
// v110/v115 tables); pinned by the volunteer-context Postgres e2e.
// Created empty; plain CREATE INDEX is instant — no CONCURRENTLY needed.
// Keep in sync with src/schema.sql, src/core/pglite-schema.ts,
- // src/core/schema-embedded.ts.
+ // src/core/schema-embedded.generated.ts.
idempotent: true,
sql: `
CREATE TABLE IF NOT EXISTS context_volunteer_events (
@@ -6029,6 +6051,139 @@ export const MIGRATIONS: Migration[] = [
WHERE private_queue_owner_job_id IS NOT NULL;
`,
},
+ {
+ version: 137,
+ name: 'entity_identities',
+ // #4224 — cross-source entity identity groups (federation v1).
+ //
+ // The identity KEY for a page is (source_id, slug): the same real-world
+ // entity can exist as `people/alice` in the `wiki` source AND
+ // `people/alice-chen` in a mounted team source, and NOTHING today says
+ // they are the same entity. This table groups member pages (by page_id,
+ // resolved from (source_id, slug) at link time) under an opaque
+ // `entity_id` handle.
+ //
+ // v1 is MANUAL-ONLY: rows are created exclusively by the
+ // entity_identity_link op (localOnly write) — no auto-matching, no
+ // similarity heuristics. `established_by` records the linking actor
+ // ('manual' for v1; a future auto-matcher would stamp its own tag and
+ // a sub-1.0 confidence).
+ //
+ // Shape invariants:
+ // - UNIQUE (source_id, page_id): a page belongs to at most ONE
+ // identity group (re-linking moves it — explicit manual intent).
+ // - At most one canonical member per identity (partial unique index):
+ // the canonical member is the identity's display/primary page.
+ // - page_id FK ON DELETE CASCADE: deleting a page dissolves its
+ // membership, never dangles.
+ //
+ // Consumed by src/core/entity-identity.ts (helpers + the flag-gated
+ // retrieval union) and the entity_identity_* ops. Same DDL on both
+ // engines via this shared migration.
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS entity_identities (
+ id BIGSERIAL PRIMARY KEY,
+ entity_id TEXT NOT NULL,
+ source_id TEXT NOT NULL,
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ confidence DOUBLE PRECISION NOT NULL DEFAULT 1.0,
+ established_by TEXT NOT NULL DEFAULT 'manual',
+ established_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ canonical BOOLEAN NOT NULL DEFAULT false,
+ CONSTRAINT entity_identities_page_uniq UNIQUE (source_id, page_id)
+ );
+ CREATE INDEX IF NOT EXISTS entity_identities_entity_idx
+ ON entity_identities (entity_id);
+ CREATE UNIQUE INDEX IF NOT EXISTS entity_identities_canonical_uniq
+ ON entity_identities (entity_id) WHERE canonical;
+ `,
+ },
+ {
+ version: 138,
+ name: 'timeline_dedup_md5_summary',
+ // #3737 — idx_timeline_dedup keyed the RAW summary, so any incompressible
+ // summary over the btree v4 row cap ("index row size N exceeds btree
+ // version 4 maximum 2704") aborted the whole timeline insert — long
+ // transcript-derived summaries broke timeline writes brain-wide. Re-key
+ // the dedup tuple on md5(summary): fixed 32-char datum, same dedup
+ // semantics (md5-equal ⟺ summary-equal modulo negligible collisions).
+ // Both insert sites infer ON CONFLICT (page_id, date, md5(summary),
+ // source) against this expression index. Existing rows were unique on
+ // the raw tuple, so the md5 tuple is unique too — no pre-dedupe needed.
+ // The #2038 shape self-heal (timeline-dedup-repair.ts) expects the SAME
+ // md5 shape, so it converges drifted brains instead of reverting this.
+ idempotent: true,
+ sql: `
+ DROP INDEX IF EXISTS idx_timeline_dedup;
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup
+ ON timeline_entries(page_id, date, md5(summary), source);
+ `,
+ },
+ {
+ version: 139,
+ name: 'timeline_legacy_source_split_repair',
+ // #3957 follow-up — one-time legacy-row shape repair. The pre-#3957
+ // DB-path parser wrote timeline rows with source='' and the UNSPLIT
+ // `Source — Summary` bullet text as summary; the parser now emits the
+ // split (source, summary) shape (source='markdown' / the parsed label),
+ // so the (page_id, date, md5(summary), source) dedup index can never
+ // collapse a re-extraction onto a legacy row — every re-extract would
+ // duplicate it. Rewrite legacy rows to the shape the next re-extract
+ // will emit, content-anchored per page (see
+ // timeline-dedup-repair.ts:repairLegacyTimelineSourceRows). Rows whose
+ // bullet no longer exists in content are left as-is (they can't
+ // duplicate); rows whose new-shape duplicate already landed are deleted.
+ // Idempotent: rewritten rows no longer match source=''. Handler-only
+ // (runs outside a transaction; every statement is individually safe to
+ // re-run). Both engines share one SQL text via executeRaw.
+ idempotent: true,
+ sql: '',
+ handler: async (engine) => {
+ const r = await repairLegacyTimelineSourceRows(engine);
+ if (r.rowsRewritten > 0 || r.rowsDeleted > 0) {
+ migrationNotice(
+ ` NOTICE: v139 rewrote ${r.rowsRewritten} legacy timeline row(s) to the split ` +
+ `(source, summary) shape` +
+ (r.rowsDeleted > 0 ? ` and removed ${r.rowsDeleted} already-duplicated row(s)` : '') +
+ ` across ${r.pagesScanned} page(s), so re-extraction dedups instead of duplicating (#3957).\n`,
+ );
+ }
+ },
+ },
+ {
+ version: 140,
+ name: 'chat_usage_log',
+ // #4218 (revives the #3392 shape): durable per-call chat usage ledger.
+ // gateway.chat() inserts one row per SUCCESSFUL call (fire-and-forget via
+ // the chat-usage sink; see src/core/ai/chat-usage.ts) with the answering
+ // model, best-effort phase attribution, token counts incl. prompt-cache
+ // reads/writes, and a canonical-table cost estimate (NULL when the model
+ // has no pricing — never a fake 0). Read back by the `get_usage` op.
+ // Created empty; plain CREATE INDEX is instant — no CONCURRENTLY. RLS:
+ // covered by the v35 auto_rls_on_create_table event trigger on Postgres.
+ // Keep in sync with src/schema.sql, src/core/pglite-schema.ts,
+ // src/core/schema-embedded.generated.ts.
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS chat_usage_log (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ model TEXT NOT NULL,
+ provider TEXT,
+ phase TEXT,
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
+ cost_usd DOUBLE PRECISION
+ );
+ CREATE INDEX IF NOT EXISTS idx_chat_usage_log_created
+ ON chat_usage_log (created_at);
+ CREATE INDEX IF NOT EXISTS idx_chat_usage_log_model
+ ON chat_usage_log (model, created_at);
+ `,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
@@ -6379,12 +6534,30 @@ export async function runMigrations(engine: BrainEngine): Promise<{ applied: num
if (r.repaired) {
console.error(
`[migrate] healed idx_timeline_dedup drift (#2038): ${r.before.join(',') || '(absent)'} ` +
- `→ page_id,date,summary,source` +
+ `→ page_id,date,md5(summary),source` +
(r.collapsedDuplicates > 0 ? ` (collapsed ${r.collapsedDuplicates} duplicate row(s))` : ''),
);
}
} catch { /* best-effort; doctor reports the drift if this couldn't run */ }
+ // #550: same drift class for the pages upsert arbiter. When the
+ // UNIQUE(source_id, slug) constraint vanishes (partial restore, manual DDL,
+ // name-only migration guards), EVERY putPage fails with "no unique or
+ // exclusion constraint" and neither re-initSchema nor the version counter
+ // can see it. ADD-only self-heal; refuses (loudly) on duplicate rows.
+ try {
+ const p = await repairPagesUpsertArbiter(engine);
+ if (p.repaired) {
+ console.error(`[migrate] restored pages_source_slug_key UNIQUE(source_id, slug) (#550)`);
+ } else if (p.reason === 'duplicates') {
+ console.error(
+ `[migrate] cannot restore pages_source_slug_key: ${p.duplicateGroups} duplicate ` +
+ `(source_id, slug) group(s) exist — page upserts will keep failing until the ` +
+ `duplicates are resolved (#550). See \`gbrain doctor\`.`,
+ );
+ }
+ } catch { /* best-effort; doctor reports the drift if this couldn't run */ }
+
if (pending.length === 0) {
return { applied: 0, current };
}
diff --git a/src/core/minions/handlers/ingest-capture.ts b/src/core/minions/handlers/ingest-capture.ts
index cdec2e6745..16aac1d8d0 100644
--- a/src/core/minions/handlers/ingest-capture.ts
+++ b/src/core/minions/handlers/ingest-capture.ts
@@ -37,7 +37,7 @@ import { importFromContent } from '../../import-file.ts';
export interface IngestCaptureResult {
slug: string;
- status: 'imported' | 'skipped' | 'error';
+ status: 'imported' | 'skipped' | 'deleted' | 'error';
chunks: number;
untrusted_payload: boolean;
source_kind: string;
@@ -70,10 +70,14 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
throw new Error(`ingest_capture: invalid event payload: ${validationErr.message}`);
}
- // Slug resolution.
+ // Slug resolution. #3756 added the top-level event.slug (required for
+ // tombstones, optional upsert hint) between the caller-provided job slug
+ // and the legacy metadata.slug channel.
let slug: string;
if (typeof data.slug === 'string' && data.slug.length > 0) {
slug = data.slug;
+ } else if (typeof event.slug === 'string' && event.slug.length > 0) {
+ slug = event.slug;
} else if (
event.metadata &&
typeof (event.metadata as Record<string, unknown>).slug === 'string'
@@ -99,7 +103,26 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
event.content_type === 'application/json' ||
event.content_type === 'unknown';
- if (!isText) {
+ // #3756: tombstones carry no importable content — they name a page to
+ // delete. Content-type gating below is an import concern; skip it.
+ const isTombstone = event.kind === 'tombstone';
+
+ if (isTombstone && event.untrusted_payload !== false) {
+ // Trusted-source gate: an untrusted channel (webhook payload, URL
+ // fetcher) must never be able to delete pages. FAIL-CLOSED: deletes
+ // require the EXPLICIT trusted marker (untrusted_payload: false) —
+ // rejecting only `=== true` left an omitted flag treated as trusted,
+ // so any emitter that forgot the field could tombstone pages. Fail
+ // the job loud so the attempt is visible in the jobs ledger, not
+ // silently dropped.
+ throw new Error(
+ 'ingest_capture: refusing tombstone without an explicit trusted marker — ' +
+ 'deletes are only honored from trusted local emitters that set ' +
+ 'untrusted_payload: false on the event',
+ );
+ }
+
+ if (!isText && !isTombstone) {
// Binary content without a processor would land as a path-string
// page, which isn't useful. Surface as job-level error so the
// operator sees the gap in `gbrain doctor` and can decide whether
@@ -173,6 +196,29 @@ export function makeIngestCaptureHandler(engine: BrainEngine) {
if (rows.length > 0) sourceId = event.source_id;
}
+ // #3756: tombstone → reconciler-style soft-delete (deleted_at stamp, page
+ // restorable), scoped to the resolved source — never unscoped, so a
+ // same-slug page in another source is untouched. Idempotent: a missing or
+ // already-deleted page reports 'skipped'.
+ if (isTombstone) {
+ const deleted = await engine.softDeletePage(slug, { sourceId: sourceId ?? 'default' });
+ if (sourceFallback) {
+ console.error(
+ `[WARN] ingest_capture: requested source '${sourceFallback.requested}' unavailable ` +
+ `(${sourceFallback.reason}); tombstone applied under default`,
+ );
+ }
+ return {
+ slug,
+ status: deleted ? 'deleted' : 'skipped',
+ chunks: 0,
+ untrusted_payload: untrustedPayload,
+ source_kind: event.source_kind,
+ source_uri: event.source_uri,
+ ...(sourceFallback ? { source_fallback: sourceFallback } : {}),
+ };
+ }
+
// Shared across the write and its FK-violation retry so provenance can't
// drift between the two call sites.
const importOpts = {
diff --git a/src/core/minions/llm-halt-cooldown.ts b/src/core/minions/llm-halt-cooldown.ts
new file mode 100644
index 0000000000..7ba02cb306
--- /dev/null
+++ b/src/core/minions/llm-halt-cooldown.ts
@@ -0,0 +1,241 @@
+/**
+ * #4310 — provider-identity-keyed global-LLM-halt cooldown for queued LLM
+ * jobs (first consumer: the facts-absorb worker boundary in
+ * src/commands/jobs.ts).
+ *
+ * The gap: when the chat provider is GLOBALLY broken (revoked key, exhausted
+ * spend limit, hard rate limit), every queued facts-absorb job independently
+ * makes its own doomed LLM call, burns a retry attempt, and eventually
+ * dead-letters — a queue of N page writes turns into N × max_attempts wasted
+ * provider calls and N dead jobs for one shared root cause. #3044's
+ * classifyGlobalLlmError/createGlobalLlmHaltTracker already name the halt
+ * classes; this module applies them ACROSS jobs in the worker process.
+ *
+ * Policy:
+ * - A halt-class failure (auth/billing on first hit; rate_limit after
+ * RATE_LIMIT_HALT_STREAK consecutive hits, streak shared across jobs)
+ * arms a cooldown keyed on the PROVIDER identity of the model the job
+ * used. The failing job's own error still propagates (visible failure,
+ * normal retry/backoff — never swallowed).
+ * - While the cooldown is active, matching jobs are DEFERRED without
+ * burning an attempt: the wrapper throws RateLeaseUnavailableError with
+ * `retryInMs` = remaining cooldown, and the worker's lease-full path
+ * requeues them delayed (never dead-letters a job the provider outage
+ * doomed).
+ * - On expiry, exactly ONE job is admitted as the bounded PROBE; the rest
+ * keep deferring on a short retry until the probe settles. Probe success
+ * clears the cooldown (and the rate-limit streak); another halt-class
+ * failure re-arms it with doubled backoff (capped).
+ *
+ * In-process state (one worker = one cooldown view); `GBRAIN_LLM_HALT_COOLDOWN=0`
+ * disables the whole mechanism (incident escape hatch).
+ *
+ * Tested in test/llm-halt-cooldown.test.ts.
+ */
+
+import type { MinionJobContext, MinionHandler } from './types.ts';
+import {
+ createGlobalLlmHaltTracker,
+ haltedClassOf,
+ type GlobalLlmErrorClass,
+} from '../ai/errors.ts';
+import { RateLeaseUnavailableError } from './rate-leases.ts';
+import { splitProviderModelId } from '../model-id.ts';
+import { getChatModel } from '../ai/gateway.ts';
+
+/** Base cooldown per halt class (ms). Doubles per consecutive halted probe. */
+export const HALT_COOLDOWN_BASE_MS: Record<GlobalLlmErrorClass, number> = {
+ auth: 5 * 60_000, // deterministic until an operator fixes the key
+ billing: 5 * 60_000, // deterministic until quota/credit is restored
+ rate_limit: 60_000, // bursts clear on their own — probe sooner
+};
+export const HALT_COOLDOWN_MAX_MS = 30 * 60_000;
+/** Defer cadence while a probe is in flight (plus jitter). */
+const PROBE_WAIT_RETRY_MS = 15_000;
+
+interface CooldownState {
+ /** epoch ms when the cooldown lapses and a probe may go through. */
+ until: number;
+ cls: GlobalLlmErrorClass;
+ /** consecutive halted probes → exponential re-arm. */
+ strikes: number;
+ probeInFlight: boolean;
+ tracker: ReturnType<typeof createGlobalLlmHaltTracker>;
+}
+
+const cooldowns = new Map<string, CooldownState>();
+
+/** Test-only: clear all cooldown state. */
+export function _resetLlmHaltCooldownsForTests(): void {
+ cooldowns.clear();
+}
+
+/** Introspection (doctor / tests): remaining cooldown ms for a key, or 0. */
+export function llmHaltCooldownRemainingMs(key: string, now: number = Date.now()): number {
+ const s = cooldowns.get(key);
+ if (!s) return 0;
+ return Math.max(0, s.until - now);
+}
+
+function cooldownDisabled(): boolean {
+ const raw = (process.env.GBRAIN_LLM_HALT_COOLDOWN ?? '').toLowerCase();
+ return raw === '0' || raw === 'false' || raw === 'off';
+}
+
+function trackerFor(key: string): CooldownState['tracker'] {
+ const existing = cooldowns.get(key);
+ if (existing) return existing.tracker;
+ // Streak state must survive across jobs BEFORE any cooldown is armed —
+ // three rate-limited jobs in a row are the whole point. Park a zero-length
+ // cooldown row to carry the tracker.
+ const fresh: CooldownState = {
+ until: 0,
+ cls: 'rate_limit',
+ strikes: 0,
+ probeInFlight: false,
+ tracker: createGlobalLlmHaltTracker(),
+ };
+ cooldowns.set(key, fresh);
+ return fresh.tracker;
+}
+
+function armCooldown(key: string, cls: GlobalLlmErrorClass, now: number, escalate: boolean): void {
+ const s = cooldowns.get(key);
+ // Strikes escalate per halted PROBE (the documented policy), not per
+ // concurrent in-flight failure — a burst of N jobs failing on the same
+ // outage is ONE strike, not an instant jump to the 30-min max cooldown.
+ const prior = s?.strikes ?? 0;
+ const strikes = prior === 0 ? 1 : escalate ? prior + 1 : prior;
+ const base = HALT_COOLDOWN_BASE_MS[cls];
+ const durationMs = Math.min(base * 2 ** (strikes - 1), HALT_COOLDOWN_MAX_MS);
+ cooldowns.set(key, {
+ until: now + durationMs,
+ cls,
+ strikes,
+ probeInFlight: false,
+ tracker: s?.tracker ?? createGlobalLlmHaltTracker(),
+ });
+ console.error(
+ `[llm-halt] provider "${key}" ${cls} halt — cooling down ${Math.round(durationMs / 1000)}s ` +
+ `(strike ${strikes}); queued jobs defer without burning attempts (GBRAIN_LLM_HALT_COOLDOWN=0 disables)`,
+ );
+}
+
+/**
+ * Wrap a queued-job handler with the provider-halt cooldown. `resolveKey`
+ * names the provider identity the job will bill against (called per job,
+ * AFTER the registerBuiltinJob gateway refresh so config is current).
+ */
+export function withGlobalLlmHaltCooldown(
+ resolveKey: (job: MinionJobContext) => string,
+ handler: MinionHandler,
+ opts: { now?: () => number } = {},
+): MinionHandler {
+ const now = opts.now ?? Date.now;
+ return async (job) => {
+ if (cooldownDisabled()) return handler(job);
+ let key: string;
+ try {
+ key = resolveKey(job) || 'unknown';
+ } catch {
+ key = 'unknown';
+ }
+
+ const state = cooldowns.get(key);
+ const t = now();
+ let isProbe = false;
+ if (state && state.until > 0) {
+ if (t < state.until) {
+ // Cooling down: defer, no attempt burned (worker lease-full path).
+ throw new RateLeaseUnavailableError(
+ `global-llm-halt:${state.cls}:${key}`,
+ 1,
+ 1,
+ Math.max(1000, state.until - t) + Math.floor(Math.random() * 5000),
+ );
+ }
+ if (state.probeInFlight) {
+ // Expired but a probe is already out — keep deferring on a short
+ // cadence until it settles.
+ throw new RateLeaseUnavailableError(
+ `global-llm-halt:${state.cls}:${key}`,
+ 1,
+ 1,
+ PROBE_WAIT_RETRY_MS + Math.floor(Math.random() * 5000),
+ );
+ }
+ state.probeInFlight = true; // this job is the bounded probe
+ isProbe = true;
+ }
+
+ try {
+ const result = await handler(job);
+ // Success clears the cooldown AND the shared rate-limit streak.
+ cooldowns.delete(key);
+ return result;
+ } catch (err) {
+ // Deferrals thrown by a nested wrapper must pass through untouched.
+ if (err instanceof RateLeaseUnavailableError) {
+ // But a PROBE that deferred never settled the outage question: release
+ // the probe slot (and the lapsed gate) or probeInFlight stays latched
+ // forever and every later job — including the requeued probe itself —
+ // defers on the 15s cadence until worker restart.
+ if (isProbe) {
+ const s = cooldowns.get(key);
+ if (s) {
+ s.probeInFlight = false;
+ s.until = 0;
+ }
+ }
+ throw err;
+ }
+ const tracker = trackerFor(key);
+ const decision = tracker.observe(err);
+ const cls = haltedClassOf(decision);
+ if (cls) {
+ armCooldown(key, cls, now(), isProbe);
+ } else if (isProbe) {
+ // Non-halt failure settles the probe without re-arming — the outage
+ // condition is gone even though this item failed on its own merits.
+ const s = cooldowns.get(key);
+ if (s) {
+ s.probeInFlight = false;
+ s.until = 0;
+ }
+ }
+ throw err; // the failing job stays a VISIBLE failure (normal retry path)
+ }
+ };
+}
+
+/**
+ * Provider identity for a facts-absorb-shaped job: the provider half of the
+ * per-job model override when present, else of the gateway's configured chat
+ * model. Falls back to the whole model string when there is no provider
+ * prefix (bare ids share one credential domain in practice).
+ */
+export function providerIdentityForJob(job: MinionJobContext, configuredModel: () => string | null): string {
+ const jobModel = typeof job.data?.model === 'string' && job.data.model ? job.data.model : null;
+ const model = jobModel ?? (configuredModel() || 'unknown');
+ const { provider, model: tail } = splitProviderModelId(model);
+ return provider ?? (tail || model);
+}
+
+/**
+ * The facts-absorb boundary wrapper (#4310): cooldown keyed on the provider
+ * identity of the job's model override, else the gateway's configured chat
+ * model (resolved per job, AFTER registerBuiltinJob's gateway refresh).
+ */
+export function withFactsAbsorbHaltCooldown(handler: MinionHandler): MinionHandler {
+ return withGlobalLlmHaltCooldown(
+ (job) =>
+ providerIdentityForJob(job, () => {
+ try {
+ return getChatModel();
+ } catch {
+ return null;
+ }
+ }),
+ handler,
+ );
+}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 507152d181..a7974d5c91 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -701,6 +701,13 @@ export class MinionQueue {
name?: string;
limit?: number;
offset?: number;
+ /**
+ * #4098 — agent-lane ownership fence: restrict to jobs whose
+ * `data->>'__owner_client_id'` equals this OAuth client id (the JSONB
+ * predicate submit_agent stamps at enqueue). SQL-side WHERE, never a
+ * post-fetch JS filter, so a fenced list can't leak foreign rows.
+ */
+ ownerClientId?: string;
}): Promise<MinionJob[]> {
const conditions: string[] = [];
const params: unknown[] = [];
@@ -718,6 +725,10 @@ export class MinionQueue {
conditions.push(`name = $${idx++}`);
params.push(opts.name);
}
+ if (opts?.ownerClientId) {
+ conditions.push(`data->>'__owner_client_id' = $${idx++}`);
+ params.push(opts.ownerClientId);
+ }
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const limit = opts?.limit ?? 50;
@@ -754,8 +765,8 @@ export class MinionQueue {
*
* Returns the *root* (the job matching id), not an arbitrary descendant.
*/
- async cancelJob(id: number): Promise<MinionJob | null> {
- const cancelled = await this.cancelJobs([id]);
+ async cancelJob(id: number, opts?: { ownerClientId?: string }): Promise<MinionJob | null> {
+ const cancelled = await this.cancelJobs([id], opts?.ownerClientId ? { ownerClientId: opts.ownerClientId } : undefined);
const root = cancelled.find(j => j.id === id);
return root ?? null;
}
@@ -1013,7 +1024,7 @@ export class MinionQueue {
* every surface keyed on a reason prefix (jobs stats, doctor) would
* silently report zero without this parameter.
*/
- async cancelJobs(ids: number[], opts?: { reason?: string; rootStatuses?: MinionJobStatus[] }): Promise<MinionJob[]> {
+ async cancelJobs(ids: number[], opts?: { reason?: string; rootStatuses?: MinionJobStatus[]; ownerClientId?: string }): Promise<MinionJob[]> {
if (ids.length === 0) return [];
// opts.rootStatuses re-checks each ROOT id's status ATOMICALLY inside the
// cancel UPDATE's CTE seed. The waiting-TTL sweep passes ['waiting'] to
@@ -1022,13 +1033,21 @@ export class MinionQueue {
// SELECT and this UPDATE would be cancelled while ACTIVE (lock_token
// NULLed under the running handler). Operator cancels omit it — killing
// an active job is exactly what `jobs cancel` means.
+ //
+ // opts.ownerClientId (#4098) fences the CTE SEED on
+ // `data->>'__owner_client_id'`: an agent-scoped caller can cancel only
+ // roots it owns. Descendants of an owned root cascade regardless of their
+ // own data payload — the recursion follows the owned root, which is the
+ // semantic the delegating agent expects (its job tree, not per-row tags).
const rootStatuses = opts?.rootStatuses ?? null;
+ const ownerClientId = opts?.ownerClientId ?? null;
return this.engine.transaction(async (tx) => {
const rows = await tx.executeRaw<Record<string, unknown>>(
`WITH RECURSIVE descendants AS (
SELECT id, 0 AS d FROM minion_jobs
WHERE id = ANY($1::int[])
AND ($3::text[] IS NULL OR status = ANY($3::text[]))
+ AND ($4::text IS NULL OR data->>'__owner_client_id' = $4::text)
UNION ALL
SELECT m.id, descendants.d + 1
FROM minion_jobs m
@@ -1050,7 +1069,7 @@ export class MinionQueue {
WHERE id IN (SELECT id FROM descendants)
AND status IN ('waiting','active','delayed','waiting-children','paused')
RETURNING *`,
- [ids, opts?.reason ?? null, rootStatuses]
+ [ids, opts?.reason ?? null, rootStatuses, ownerClientId]
);
if (rows.length === 0) return [];
diff --git a/src/core/minions/rate-leases.ts b/src/core/minions/rate-leases.ts
index 83b56fcbda..949ef5b8fc 100644
--- a/src/core/minions/rate-leases.ts
+++ b/src/core/minions/rate-leases.ts
@@ -161,7 +161,12 @@ export async function renewLeaseWithBackoff(engine: BrainEngine, leaseId: number
* cross-cutting error type (subagent.ts re-exports it for compatibility).
*/
export class RateLeaseUnavailableError extends Error {
- constructor(public key: string, public active: number, public max: number) {
+ /**
+ * Optional caller-suggested requeue delay (ms). #4310: the global-LLM-halt
+ * cooldown defers jobs for the REMAINING cooldown, not the 1-3s lease
+ * bounce — worker.ts honors this when present, else leaseFullBackoffMs().
+ */
+ constructor(public key: string, public active: number, public max: number, public retryInMs?: number) {
super(`rate lease "${key}" full (${active}/${max})`);
this.name = 'RateLeaseUnavailableError';
}
diff --git a/src/core/minions/run-child.ts b/src/core/minions/run-child.ts
index 41b92f422b..ecc872e1be 100644
--- a/src/core/minions/run-child.ts
+++ b/src/core/minions/run-child.ts
@@ -33,6 +33,7 @@ import type { BrainEngine } from '../engine.ts';
import { MinionQueue } from './queue.ts';
import type { MinionHandler } from './types.ts';
import { buildJobContext } from './job-context.ts';
+import { withChatPhase } from '../ai/chat-usage.ts';
import {
JOB_CHILD_EXIT_NOT_CLAIMED,
JOB_CHILD_EXIT_RESULT_WRITE_FAILED,
@@ -149,7 +150,9 @@ export async function runChildJobEntry(
);
let outcome;
try {
- const result = await handler(context);
+ // #4218: same phase attribution as the in-process worker path — the
+ // isolated child runs its own gateway, so the wrap must live here too.
+ const result = await withChatPhase(`job:${job.name}`, () => handler(context));
// completeJob's {value: x} wrap decision must run BEFORE JSON
// serialization: a JSON round-trip changes typeof for Date /
// toJSON-bearing results (object → string), which would flip the wrap
diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.ts
index 3eb1805cc8..793ac94e70 100644
--- a/src/core/minions/supervisor.ts
+++ b/src/core/minions/supervisor.ts
@@ -43,8 +43,9 @@ import {
writeSync,
} from 'fs';
import { dirname, resolve } from 'path';
+import { hostname } from 'os';
import type { BrainEngine } from '../engine.ts';
-import { tryAcquireDbLock, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';
+import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';
import { MinionQueue } from './queue.ts';
import { currentBrainId, readWorkers } from './worker-registry.ts';
import { autopilotPausedMarkerPath } from '../autopilot-paths.ts';
@@ -470,6 +471,23 @@ export const SUPERVISOR_LOCK_TTL_MIN = 5;
const SUPERVISOR_LOCK_REFRESH_MS = 60_000;
const SUPERVISOR_LOCK_REFRESH_MAX_FAILURES = 3; // 3 × 60s = 180s < 5min TTL
+/**
+ * #2308 — how long start() waits for a held queue lock to become takeable
+ * (dead cross-host holder whose TTL hasn't lapsed yet).
+ * 0 → disabled (pre-#2308 one-shot LOCK_HELD exit)
+ * positive int → hard bound in seconds
+ * unset/other → -1 (waitForDbLockTakeover derives TTL + steal-grace + margin)
+ * Exported for tests.
+ */
+export function resolveSupervisorLockWaitSeconds(): number {
+ const raw = process.env.GBRAIN_SUPERVISOR_LOCK_WAIT_SECONDS;
+ if (raw !== undefined && raw !== '') {
+ const n = Number(raw);
+ if (Number.isInteger(n) && n >= 0) return n;
+ }
+ return -1;
+}
+
/**
* #1849: the queue-scoped supervisor singleton lock id. Keyed ONLY on the
* queue, because the lock ROW lives inside the target database — the (database)
@@ -699,6 +717,54 @@ export class MinionSupervisor {
// the same (db, queue). Keyed on the queue alone; the database half of the
// mutex is physical (the lock row lives in this DB).
this.dbLock = await tryAcquireDbLock(this.engine, this.supervisorLockId(), SUPERVISOR_LOCK_TTL_MIN);
+ if (!this.dbLock) {
+ // #2308: a DEAD holder on ANOTHER host leaves a row whose TTL is still
+ // live — tryAcquireDbLock correctly refuses to steal it (cross_host),
+ // but a one-shot exit here turns a self-healing condition (the row is
+ // takeable after TTL + steal-grace) into an operator page. Wait,
+ // bounded, for the takeover; bail fast when the holder's heartbeat
+ // advances (a genuinely live supervisor). CROSS-HOST holders only:
+ // same-host liveness is already probed by tryAcquireDbLock's
+ // auto-takeover (a dead local holder was reclaimed above; a live one
+ // should keep the immediate LOCK_HELD exit).
+ // GBRAIN_SUPERVISOR_LOCK_WAIT_SECONDS=0 disables the wait (pre-#2308
+ // one-shot behavior); a positive value overrides the derived TTL+grace bound.
+ const waitSeconds = resolveSupervisorLockWaitSeconds();
+ let holderIsCrossHost = false;
+ if (waitSeconds !== 0) {
+ try {
+ const snap = await inspectLock(this.engine, this.supervisorLockId());
+ holderIsCrossHost = snap !== null && snap.holder_host !== hostname();
+ } catch { /* stay one-shot on inspect failure */ }
+ }
+ if (waitSeconds !== 0 && holderIsCrossHost) {
+ console.error(
+ `Supervisor queue lock for '${this.opts.queue}' is held (possibly by a dead ` +
+ `process on another host). Waiting up to ${waitSeconds > 0 ? waitSeconds : 'TTL+grace'}s ` +
+ `for the holder to expire or heartbeat; set GBRAIN_SUPERVISOR_LOCK_WAIT_SECONDS=0 to exit immediately.`,
+ );
+ this.dbLock = await waitForDbLockTakeover(
+ this.engine,
+ this.supervisorLockId(),
+ SUPERVISOR_LOCK_TTL_MIN,
+ {
+ ...(waitSeconds > 0 ? { maxWaitMs: waitSeconds * 1000 } : {}),
+ onWait: ({ snapshot, waitedMs, maxWaitMs }) => {
+ const holder = snapshot
+ ? `pid=${snapshot.holder_pid} host=${snapshot.holder_host}`
+ : 'holder row gone';
+ console.error(
+ `[supervisor] still waiting for queue lock '${this.opts.queue}' ` +
+ `(${holder}, waited ${Math.round(waitedMs / 1000)}s of ${Math.round(maxWaitMs / 1000)}s)`,
+ );
+ },
+ },
+ );
+ if (this.dbLock) {
+ console.error(`[supervisor] queue lock '${this.opts.queue}' taken over from expired holder.`);
+ }
+ }
+ }
if (!this.dbLock) {
console.error(
`Supervisor already running for queue '${this.opts.queue}' on this database ` +
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 774125db10..9064861279 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -25,6 +25,7 @@ import {
} from './types.ts';
import { MinionQueue } from './queue.ts';
import { runWaitingTtlTick, ttlNoticeGraceMs } from './admission.ts';
+import { withChatPhase } from '../ai/chat-usage.ts';
import { calculateBackoff } from './backoff.ts';
import { RateLeaseUnavailableError } from './handlers/subagent.ts';
import { leaseFullBackoffMs } from './rate-leases.ts';
@@ -1313,7 +1314,9 @@ export class MinionWorker extends EventEmitter {
invocation: this.opts.childCliInvocation as { cmd: string; argsPrefix: string[] },
tiniPath: this.opts.childTiniPath,
})
- : await handler(context as MinionJobContext);
+ // #4218: attribute every gateway.chat() the handler makes to this
+ // job so chat_usage_log rows carry `phase = 'job:<name>'`.
+ : await withChatPhase(`job:${job.name}`, () => handler(context as MinionJobContext));
// The child spawned and ran — the spawn path is healthy again.
this._consecutiveChildSpawnFailures = 0;
@@ -1442,7 +1445,9 @@ export class MinionWorker extends EventEmitter {
// 1-3s jittered backoff (shared with the inline drain — one curve,
// no silent desync). Not the exponential curve — this is "yield the
// slot, try again soon", not "give up after a few tries."
- const leaseBackoffMs = leaseFullBackoffMs();
+ // #4310: a caller-suggested delay (the global-LLM-halt cooldown's
+ // remaining window) wins over the short lease bounce.
+ const leaseBackoffMs = leaseErr.retryInMs ?? leaseFullBackoffMs();
const released = await this.queue.releaseLeaseFullJob(
job.id, lockToken, errorText, leaseBackoffMs,
);
diff --git a/src/core/model-config.ts b/src/core/model-config.ts
index 934446c1c0..922e21a76e 100644
--- a/src/core/model-config.ts
+++ b/src/core/model-config.ts
@@ -40,13 +40,14 @@ export interface ResolveModelOpts {
/** Env var to consult after global default. Defaults to `GBRAIN_MODEL`. */
envVar?: string;
/**
- * Tier classification (v0.31.12). Looked up after `models.default` and
- * before the env var. Routing groups: `utility` (haiku-class, classification
- * + expansion + verdict), `reasoning` (sonnet-class, default chat +
- * synthesis + fact extraction), `deep` (opus-class, expensive reasoning),
- * `subagent` (Anthropic-only multi-turn tool loop — never inherits a
- * non-Anthropic `models.default`; falls back to TIER_DEFAULTS.subagent
- * with a one-shot stderr warn instead).
+ * Tier classification (v0.31.12). Looked up after the per-feature config
+ * keys and BEFORE `models.default` (#3873 — tier-specific beats generic),
+ * then before the env var. Routing groups: `utility` (haiku-class,
+ * classification + expansion + verdict), `reasoning` (sonnet-class,
+ * default chat + synthesis + fact extraction), `deep` (opus-class,
+ * expensive reasoning), `subagent` (Anthropic-only multi-turn tool loop —
+ * never inherits a non-Anthropic `models.default`; falls back to
+ * TIER_DEFAULTS.subagent with a one-shot stderr warn instead).
*/
tier?: ModelTier;
/** Hardcoded last-resort fallback. */
@@ -381,14 +382,10 @@ export async function resolveModelDetailed(
}
}
- // 4. Global default
- const def = await engine.getConfig('models.default');
- if (def && def.trim()) {
- const resolved = await resolveAlias(engine, def.trim());
- return { model: enforceSubagentCapable(resolved, opts.tier, 'models.default'), source: 'models_default' };
- }
-
- // 5. Tier override (v0.31.12)
+ // 4. Tier override (v0.31.12; hoisted above models.default by #3873).
+ // `models.tier.<tier>` is strictly more specific than the generic
+ // `models.default`, so it must win — pre-fix, setting a cheap utility
+ // tier was silently ignored on any brain that also set models.default.
if (opts.tier) {
const tierVal = await engine.getConfig(`models.tier.${opts.tier}`);
if (tierVal && tierVal.trim()) {
@@ -396,6 +393,13 @@ export async function resolveModelDetailed(
return { model: enforceSubagentCapable(resolved, opts.tier, `models.tier.${opts.tier}`), source: 'tier_config' };
}
}
+
+ // 5. Global default
+ const def = await engine.getConfig('models.default');
+ if (def && def.trim()) {
+ const resolved = await resolveAlias(engine, def.trim());
+ return { model: enforceSubagentCapable(resolved, opts.tier, 'models.default'), source: 'models_default' };
+ }
}
// 6. Env var
diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.ts
index ed876a5a11..6738d2ed82 100644
--- a/src/core/model-pricing.ts
+++ b/src/core/model-pricing.ts
@@ -41,6 +41,36 @@ export interface ModelPricing {
input: number;
/** USD per 1M output tokens. */
output: number;
+ /**
+ * #4218 — USD per 1M prompt-cache-READ tokens. Optional: present only for
+ * providers whose published cache pricing we've verified (Anthropic:
+ * 0.1x input). Consumers that price cache tokens fall back to the input
+ * rate when absent (conservative over-estimate for reads).
+ */
+ cache_read?: number;
+ /**
+ * #4218 — USD per 1M prompt-cache-WRITE tokens at the default 5-minute
+ * TTL (Anthropic: 1.25x input; the 1h TTL bills 2x and is NOT modeled —
+ * gbrain's gateway requests the default TTL unless config overrides it,
+ * so 5m is the honest best-effort rate). Fall back to input rate when
+ * absent (under-estimate for writes; documented, not silent).
+ */
+ cache_write?: number;
+}
+
+/** Anthropic prompt-cache multipliers (verified 2026-08 against published
+ * provider pricing): reads bill 0.1x the base input rate; 5-minute-TTL
+ * writes bill 1.25x. Exported so the drift guard can assert every
+ * anthropic: row's cache fields stay derived from its input rate. */
+export const ANTHROPIC_CACHE_READ_MULT = 0.1;
+export const ANTHROPIC_CACHE_WRITE_5M_MULT = 1.25;
+function anthro(input: number, output: number): ModelPricing {
+ return {
+ input,
+ output,
+ cache_read: input * ANTHROPIC_CACHE_READ_MULT,
+ cache_write: input * ANTHROPIC_CACHE_WRITE_5M_MULT,
+ };
}
/**
@@ -52,25 +82,27 @@ export interface ModelPricing {
*/
export const CANONICAL_PRICING: Record<string, ModelPricing> = {
// ── Anthropic ──────────────────────────────────────────────────────────
+ // All Anthropic rows carry derived cache_read/cache_write fields (#4218);
+ // see the anthro() helper + multiplier constants above.
// Fable 5: Anthropic's top tier, above Opus. $10 in / $50 out.
- 'anthropic:claude-fable-5': { input: 10.00, output: 50.00 },
+ 'anthropic:claude-fable-5': anthro(10.00, 50.00),
// Opus 4.x/5: $5 in / $25 out. Opus 5 (new generation) shares the same
// per-token rate as 4.8 (released 2026-05-28) — closes gbrain#1819.
- 'anthropic:claude-opus-5': { input: 5.00, output: 25.00 },
- 'anthropic:claude-opus-4-8': { input: 5.00, output: 25.00 },
- 'anthropic:claude-opus-4-7': { input: 5.00, output: 25.00 },
- 'anthropic:claude-opus-4-6': { input: 5.00, output: 25.00 },
+ 'anthropic:claude-opus-5': anthro( 5.00, 25.00),
+ 'anthropic:claude-opus-4-8': anthro( 5.00, 25.00),
+ 'anthropic:claude-opus-4-7': anthro( 5.00, 25.00),
+ 'anthropic:claude-opus-4-6': anthro( 5.00, 25.00),
// Sonnet 5 (released 2026-06-29): same $3/$15 sticker as 4.6. The launch
// intro discount ($2/$10 through 2026-08-31) is deliberately NOT modeled —
// the table carries standard rates so estimates stay conservative and
// don't need a time-bombed edit when the promo lapses.
- 'anthropic:claude-sonnet-5': { input: 3.00, output: 15.00 },
- 'anthropic:claude-sonnet-4-6': { input: 3.00, output: 15.00 },
+ 'anthropic:claude-sonnet-5': anthro( 3.00, 15.00),
+ 'anthropic:claude-sonnet-4-6': anthro( 3.00, 15.00),
// Haiku 4.5 — both the dateless canonical id and the dated snapshot.
- 'anthropic:claude-haiku-4-5': { input: 1.00, output: 5.00 },
- 'anthropic:claude-haiku-4-5-20251001': { input: 1.00, output: 5.00 },
- 'anthropic:claude-3-5-sonnet-20241022': { input: 3.00, output: 15.00 },
- 'anthropic:claude-3-5-haiku-20241022': { input: 0.80, output: 4.00 },
+ 'anthropic:claude-haiku-4-5': anthro( 1.00, 5.00),
+ 'anthropic:claude-haiku-4-5-20251001': anthro( 1.00, 5.00),
+ 'anthropic:claude-3-5-sonnet-20241022': anthro( 3.00, 15.00),
+ 'anthropic:claude-3-5-haiku-20241022': anthro( 0.80, 4.00),
// ── OpenAI ─────────────────────────────────────────────────────────────
'openai:gpt-4o': { input: 2.50, output: 10.00 },
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 6f420ac6ee..f6be18d887 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -80,6 +80,7 @@ import { syncStatusOperations } from './ops/sync-status.ts';
import { rawDataOperations } from './ops/raw-data.ts';
import { chunksOperations } from './ops/chunks.ts';
import { ingestLogOperations } from './ops/ingest-log.ts';
+import { usageOperations } from './ops/usage.ts';
import { filesOperations } from './ops/files.ts';
import { jobsOperations } from './ops/jobs.ts';
import { orphansOperations } from './ops/orphans.ts';
@@ -107,6 +108,7 @@ import { schemaPacksOperations } from './ops/schema-packs.ts';
import { skilloptOperations } from './ops/skillopt.ts';
import { chronicleOperations } from './ops/chronicle.ts';
import { extractionOperations } from './ops/extraction.ts';
+import { entityIdentityOperations } from './ops/entity-identity.ts';
import { requestToolsOperations } from './ops/request-tools.ts';
// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`
@@ -151,6 +153,8 @@ export const operations: Operation[] = [
...chunksOperations,
// Ingest log (log_ingest, get_ingest_log) — ops/ingest-log.ts
...ingestLogOperations,
+ // Usage accounting (get_usage, #4218) — ops/usage.ts
+ ...usageOperations,
// Files (file_list, file_upload, file_url) — ops/files.ts
...filesOperations,
// Jobs (Minions: submit_job, get_job, list_jobs, cancel_job, retry_job,
@@ -181,6 +185,9 @@ export const operations: Operation[] = [
// Extraction quarantine lane (#160): gated entity extraction + review
// queue — ops/extraction.ts
...extractionOperations,
+ // #4224: cross-source entity identity groups (v1 manual-only) —
+ // ops/entity-identity.ts
+ ...entityIdentityOperations,
// v0.31: hot memory (extract_facts, recall, context_pack, delta,
// forget_fact) — ops/facts.ts
...factsOperations,
@@ -227,6 +234,7 @@ const OP_AREAS: Record<string, string> = {
get_versions: 'pages', revert_version: 'pages',
resolve_slugs: 'pages', get_chunks: 'pages',
put_raw_data: 'pages', get_raw_data: 'pages',
+ fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)
// search
search: 'search', query: 'search', search_by_image: 'search',
// tags
@@ -261,6 +269,7 @@ const OP_AREAS: Record<string, string> = {
sync_brain: 'sync',
// ingest log
log_ingest: 'ingest', get_ingest_log: 'ingest',
+ get_usage: 'admin',
// files (localOnly)
file_list: 'files', file_upload: 'files', file_url: 'files',
// jobs (Minions + agent lane)
@@ -276,6 +285,9 @@ const OP_AREAS: Record<string, string> = {
// entity extraction lane
extract_entities: 'entities', extraction_pending: 'entities',
extraction_review: 'entities',
+ // #4224 cross-source entity identity (v1 manual-only)
+ entity_identity_link: 'entities', entity_identity_unlink: 'entities',
+ entity_identity_list: 'entities',
// insight / signal reads
get_recent_salience: 'insights', find_anomalies: 'insights',
find_contradictions: 'insights', find_experts: 'insights',
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 2c0bf25e33..c58e72e0e1 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -11,6 +11,7 @@
import type { Operation } from './contract.ts';
import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
import { stripTakesFence } from '../takes-fence.ts';
+import { slugHiddenFromCaller } from '../search/private-visibility.ts';
import { VERSION } from '../../version.ts';
// --- Admin ---
@@ -142,7 +143,13 @@ const get_versions: Operation = {
slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },
},
handler: async (ctx, p) => {
- const versions = await ctx.engine.getVersions(p.slug as string, sourceScopeOpts(ctx));
+ const scope = sourceScopeOpts(ctx);
+ // #4352 remediation: a `visibility: private` page's version history reads
+ // exactly like a missing page's ([]) for untrusted callers — snapshots
+ // persist historical compiled_truth verbatim, so /history was a full
+ // bypass of get_page's gate. No existence oracle.
+ if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];
+ const versions = await ctx.engine.getVersions(p.slug as string, scope);
// Same takes-allow-list privacy boundary as get_page. Snapshots persist
// historical compiled_truth verbatim, including the takes fence, so
// a remote token bypassing get_page via /history would re-introduce
diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.ts
index f475b1b74a..bcc7a731d2 100644
--- a/src/core/ops/chunks.ts
+++ b/src/core/ops/chunks.ts
@@ -8,6 +8,11 @@
import type { Operation } from './contract.ts';
import { federatedSearchScope, sourceScopeOpts } from './context.ts';
+import {
+ findPrivateOnlySlugs,
+ resolveExcludePrivatePages,
+ slugHiddenFromCaller,
+} from '../search/private-visibility.ts';
// --- Resolution & Chunks ---
@@ -22,7 +27,16 @@ const resolve_slugs: Operation = {
// slugs to any caller (the reporter's "resolve_slugs sees them but
// get_page doesn't" matrix). Route through the same visibility set as
// get_page/search: grant > federated set > scalar source.
- return ctx.engine.resolveSlugs(p.partial as string, federatedSearchScope(ctx));
+ const scope = federatedSearchScope(ctx);
+ const candidates = await ctx.engine.resolveSlugs(p.partial as string, scope);
+ // #4352 remediation: fuzzy resolution must not enumerate private slugs to
+ // an untrusted caller — same gate as get_page's candidate filter (trusted
+ // local + the operator opt-outs resolve to false and skip the probe).
+ if (candidates.length === 0 || !(await resolveExcludePrivatePages(ctx.engine, ctx.remote))) {
+ return candidates;
+ }
+ const hidden = await findPrivateOnlySlugs(ctx.engine, candidates, scope);
+ return candidates.filter(c => !hidden.has(c));
},
scope: 'read',
};
@@ -37,7 +51,11 @@ const get_chunks: Operation = {
// #2555: route through the canonical scope ladder (federated array >
// scalar floor > nothing) instead of the pre-#2200 scalar-only pattern —
// a federated grant could read the page via get_page but got [] here.
- return ctx.engine.getChunks(p.slug as string, sourceScopeOpts(ctx));
+ const scope = sourceScopeOpts(ctx);
+ // #4352 remediation: a `visibility: private` page's chunks read exactly
+ // like a missing page's ([]) for untrusted callers — no existence oracle.
+ if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];
+ return ctx.engine.getChunks(p.slug as string, scope);
},
scope: 'read',
};
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts
index e8a498c2b5..8d1ed69a97 100644
--- a/src/core/ops/code-intel.ts
+++ b/src/core/ops/code-intel.ts
@@ -54,10 +54,17 @@ const code_callers: Operation = {
sourceId,
});
const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ // #4352: thread trust — the out_of_scope brain-wide rerun is local-only.
const readiness = await resolveCodeReadiness(ctx.engine, {
- kind: 'edge', count: edges.length, sourceId, allSources,
+ kind: 'edge', count: edges.length, sourceId, allSources, remote: ctx.remote,
});
- return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callers: edges };
+ return {
+ symbol, count: edges.length, status: readiness.status, ready: readiness.ready,
+ // #3707: out_of_scope names the empty scope so a federated client can see
+ // "grant problem", not "graph never built".
+ ...(readiness.scoped_source_id ? { scoped_source_id: readiness.scoped_source_id } : {}),
+ callers: edges,
+ };
},
cliHints: { name: 'code_callers', hidden: true },
};
@@ -84,10 +91,16 @@ const code_callees: Operation = {
sourceId,
});
const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ // #4352: thread trust — see code_callers.
const readiness = await resolveCodeReadiness(ctx.engine, {
- kind: 'edge', count: edges.length, sourceId, allSources,
+ kind: 'edge', count: edges.length, sourceId, allSources, remote: ctx.remote,
});
- return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callees: edges };
+ return {
+ symbol, count: edges.length, status: readiness.status, ready: readiness.ready,
+ // #3707: see code_callers.
+ ...(readiness.scoped_source_id ? { scoped_source_id: readiness.scoped_source_id } : {}),
+ callees: edges,
+ };
},
cliHints: { name: 'code_callees', hidden: true },
};
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 193fe75ce2..1f51983c25 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -625,6 +625,16 @@ export function stampEvidenceSafe(results: SearchResult[]): void {
try { stampEvidence(results); } catch { /* non-fatal */ }
}
+/**
+ * #4039 — OpenAI deep-research contract: search results must carry an `id`
+ * that the paired `fetch` tool round-trips. id = slug (what `fetch` — the
+ * thin get_page adapter in ops/pages.ts — resolves). Additive stamp; every
+ * other consumer of SearchResult ignores it.
+ */
+export function stampDeepResearchIds(results: SearchResult[]): void {
+ for (const r of results) (r as SearchResult & { id?: string }).id = r.slug;
+}
+
/** T4 — shared eval-capture for the `search` op (keyword-only + cheap-hybrid paths). */
export function maybeCaptureSearch(
ctx: OperationContext,
diff --git a/src/core/ops/entity-identity.ts b/src/core/ops/entity-identity.ts
new file mode 100644
index 0000000000..048b79b75b
--- /dev/null
+++ b/src/core/ops/entity-identity.ts
@@ -0,0 +1,145 @@
+/**
+ * #4224 — entity identity ops (federation v1, MANUAL-ONLY).
+ *
+ * Three ops over the entity_identities table (migration v137):
+ * - entity_identity_link (write, localOnly) — link a page into a group
+ * - entity_identity_unlink (write, localOnly) — remove a page from a group
+ * - entity_identity_list (read) — inspect groups/members
+ *
+ * The identity KEY is (source_id, slug) — see src/core/entity-identity.ts
+ * and docs/architecture/brains-and-sources.md. There is NO auto-matching in
+ * v1: every row is an explicit human assertion, which is why the write ops
+ * are localOnly (identity merges change what retrieval unions together
+ * across sources — too sharp for a remote agent surface in v1).
+ *
+ * Read scoping: entity_identity_list honors a federated grant
+ * (ctx.auth.allowedSources) and a remote scalar scope by restricting MEMBER
+ * visibility. A trusted local caller sees the full cross-source group even
+ * when a .gbrain-source dotfile sets a scalar scope — cross-source IS the
+ * feature (same posture as the engine's scalar getLinks branch).
+ */
+
+import type { Operation } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+import {
+ linkEntityIdentity,
+ unlinkEntityIdentity,
+ listEntityIdentities,
+} from '../entity-identity.ts';
+import { validateSourceId } from '../utils.ts';
+
+/** Member-visibility restriction for list/union reads (fail-closed remote). */
+function identityReadScope(ctx: Parameters<Operation['handler']>[0]): string[] | undefined {
+ const scope = sourceScopeOpts(ctx);
+ if (scope.sourceIds && scope.sourceIds.length > 0) return scope.sourceIds;
+ // Remote scalar (legacy bearer / pre-federated client): restrict to it.
+ if (ctx.remote !== false && scope.sourceId) return [scope.sourceId];
+ // Trusted local: full cross-source view (the point of identity groups).
+ return undefined;
+}
+
+function resolveWriteSourceId(ctx: Parameters<Operation['handler']>[0], p: Record<string, unknown>): string {
+ const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId ?? 'default';
+ validateSourceId(sourceId);
+ return sourceId;
+}
+
+const entity_identity_link: Operation = {
+ name: 'entity_identity_link',
+ description:
+ 'Link a page into a cross-source entity identity group (v1 manual-only; no auto-matching). ' +
+ 'The identity key is (source_id, slug); a page belongs to at most one group and re-linking moves it. ' +
+ 'Set canonical=true to mark the group\'s primary page (demotes any previous canonical).',
+ params: {
+ entity_id: { type: 'string', required: true, description: "Opaque identity handle grouping the members, e.g. 'alice-chen'. Lowercase [a-z0-9._/-], max 128 chars." },
+ slug: { type: 'string', required: true, description: 'Slug of the member page to link.' },
+ source_id: { type: 'string', description: "Source the member page lives in. Defaults to the routed source ('default')." },
+ confidence: { type: 'number', description: 'Assertion confidence in [0,1]. Default 1.0 (manual assertions are certain).' },
+ canonical: { type: 'boolean', description: "Mark this member as the identity's canonical/primary page (at most one per group)." },
+ },
+ mutating: true,
+ scope: 'write',
+ localOnly: true,
+ cliHints: { name: 'entity-identity-link', positional: ['entity_id', 'slug'] },
+ handler: async (ctx, p) => {
+ const sourceId = resolveWriteSourceId(ctx, p);
+ if (ctx.dryRun) {
+ return { dry_run: true, action: 'entity_identity_link', entity_id: p.entity_id, slug: p.slug, source_id: sourceId };
+ }
+ const member = await linkEntityIdentity(ctx.engine, {
+ entityId: p.entity_id as string,
+ slug: p.slug as string,
+ sourceId,
+ confidence: p.confidence as number | undefined,
+ canonical: p.canonical as boolean | undefined,
+ establishedBy: 'manual',
+ });
+ return { linked: true, member };
+ },
+};
+
+const entity_identity_unlink: Operation = {
+ name: 'entity_identity_unlink',
+ description: 'Remove a page from a cross-source entity identity group (v1 manual-only).',
+ params: {
+ entity_id: { type: 'string', required: true, description: 'Identity handle the member currently belongs to.' },
+ slug: { type: 'string', required: true, description: 'Slug of the member page to unlink.' },
+ source_id: { type: 'string', description: "Source the member page lives in. Defaults to the routed source ('default')." },
+ },
+ mutating: true,
+ scope: 'write',
+ localOnly: true,
+ cliHints: { name: 'entity-identity-unlink', positional: ['entity_id', 'slug'] },
+ handler: async (ctx, p) => {
+ const sourceId = resolveWriteSourceId(ctx, p);
+ if (ctx.dryRun) {
+ return { dry_run: true, action: 'entity_identity_unlink', entity_id: p.entity_id, slug: p.slug, source_id: sourceId };
+ }
+ const removed = await unlinkEntityIdentity(ctx.engine, {
+ entityId: p.entity_id as string,
+ slug: p.slug as string,
+ sourceId,
+ });
+ return { unlinked: removed, entity_id: p.entity_id, slug: p.slug, source_id: sourceId };
+ },
+};
+
+const entity_identity_list: Operation = {
+ name: 'entity_identity_list',
+ description:
+ 'List cross-source entity identity groups and their member pages. Filter by entity_id or by a member slug. ' +
+ 'Federated callers only see members in sources their grant covers.',
+ params: {
+ entity_id: { type: 'string', description: 'Restrict to one identity group.' },
+ slug: { type: 'string', description: 'Restrict to the group(s) containing a page with this slug.' },
+ },
+ scope: 'read',
+ cliHints: { name: 'entity-identity-list' },
+ handler: async (ctx, p) => {
+ const members = await listEntityIdentities(ctx.engine, {
+ entityId: p.entity_id as string | undefined,
+ slug: p.slug as string | undefined,
+ allowedSources: identityReadScope(ctx),
+ });
+ // Group for readability: one object per entity_id.
+ const groups = new Map<string, typeof members>();
+ for (const m of members) {
+ const g = groups.get(m.entity_id) ?? [];
+ g.push(m);
+ groups.set(m.entity_id, g);
+ }
+ return {
+ identities: [...groups.entries()].map(([entity_id, ms]) => ({
+ entity_id,
+ canonical: ms.find(m => m.canonical) ?? null,
+ members: ms,
+ })),
+ };
+ },
+};
+
+export const entityIdentityOperations: Operation[] = [
+ entity_identity_link,
+ entity_identity_unlink,
+ entity_identity_list,
+];
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 1bc156eac4..70f800da6f 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -15,11 +15,15 @@
import type { Operation } from './contract.ts';
import { OperationError, verbError } from './contract.ts';
import { sourceScopeOpts, stampEvidenceSafe } from './context.ts';
+import { markKeywordHits } from '../search/evidence.ts';
import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';
import { dedupResults } from '../search/dedup.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { packToBudget, estimateTokens, resultTokens } from '../search/token-budget.ts';
import { isAvailable } from '../ai/gateway.ts';
+// #4209: the named entity-hints cap — surfaced in the extract_facts param
+// description and the entity_hints_used/_dropped response fields.
+import { ENTITY_HINTS_CAP } from '../facts/extract.ts';
import { MEMORY_VERBS_VERSION } from '../verbs.ts';
import type { SearchResult } from '../types.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
@@ -34,9 +38,11 @@ const extract_facts: Operation = {
'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls the configured extraction model (key-aware: any servable provider — OpenAI or Anthropic key both work), runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. With NO servable chat model, returns skipped: extraction_unavailable + an agent_action telling YOU to extract and write via `remember` (visibility: "private"). Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',
params: {
turn_text: { type: 'string', required: true, description: 'The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call.' },
- session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface.' },
- entity_hints: { type: 'array', items: { type: 'string' }, description: 'Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug.' },
+ session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface. NOTE (#4206): the session survives on the DB row at insert time, but the `## Facts` fence has no session column — a fence rebuild/reconcile re-derives rows session-less. Treat fence-backed facts as session-less across rebuilds.' },
+ entity_hints: { type: 'array', items: { type: 'string' }, description: `Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug. Only the first ${ENTITY_HINTS_CAP} are forwarded to the extractor (#4209) — the response reports entity_hints_used / entity_hints_dropped; pass the most load-bearing slugs first.` },
is_dream_generated: { type: 'boolean', description: 'When true, extraction is skipped (anti-loop). Caller flips this on for pages with dream_generated:true frontmatter.' },
+ valid_from: { type: 'string', description: '#4206: ISO 8601 event time for the extracted facts — use when the turn is historical (importing an old transcript) so facts do not get stamped with import time. Fallback only: a date the extractor derives from the turn itself wins. Default: now().' },
+ source_slug: { type: 'string', description: "#4206: slug of the page/transcript this turn came from (e.g. 'meetings/2026-04-03'). Written to facts.context so recall/context_pack/delta consumers see the provenance." },
visibility: { type: 'string', description: 'Default visibility for extracted facts. private (default) | world.' },
},
mutating: true,
@@ -46,12 +52,21 @@ const extract_facts: Operation = {
const { isFactsExtractionEnabled } = await import('../facts/extract.ts');
const { runFactsPipeline } = await import('../facts/backstop.ts');
+ // #4209: named-cap accounting. The extractor prompt forwards only the
+ // first ENTITY_HINTS_CAP hints; report used/dropped on EVERY envelope so
+ // over-cap hints are visible in the contract instead of silently eaten.
+ const entityHints = Array.isArray(p.entity_hints) ? (p.entity_hints as string[]) : undefined;
+ const hintAccounting = {
+ entity_hints_used: Math.min(entityHints?.length ?? 0, ENTITY_HINTS_CAP),
+ entity_hints_dropped: Math.max(0, (entityHints?.length ?? 0) - ENTITY_HINTS_CAP),
+ };
+
// D15: kill switch. Operator can disable facts extraction across the
// brain without binary downgrade by setting `facts.extraction_enabled`
// to false. Returns zero-counts envelope so callers see a clean
// success rather than a 'permission_denied' false alarm.
if (!(await isFactsExtractionEnabled(ctx.engine))) {
- return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_disabled' };
+ return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_disabled', ...hintAccounting };
}
// v0.31.2: routed through the shared pipeline (PR1 commit 9). Anti-loop
@@ -59,7 +74,7 @@ const extract_facts: Operation = {
// an explicit user op without a parsedPage — the eligibility predicate
// doesn't apply, but the dream-generated guard still does.
if (p.is_dream_generated === true) {
- return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'dream_generated' };
+ return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'dream_generated', ...hintAccounting };
}
const sourceId = ctx.sourceId ?? 'default';
@@ -69,13 +84,34 @@ const extract_facts: Operation = {
const { resolveVisibilityParam } = await import('../facts/visibility.ts');
const visibility: 'private' | 'world' = await resolveVisibilityParam(ctx.engine, p.visibility);
+ // #4206: optional event-time + provenance threading. An unparseable
+ // valid_from fails LOUD — silently defaulting to now() is exactly the
+ // wrong-timestamp bug the param exists to fix.
+ let validFrom: Date | undefined;
+ if (p.valid_from !== undefined && p.valid_from !== null) {
+ const d = new Date(p.valid_from as string);
+ if (!Number.isFinite(d.getTime())) {
+ throw new OperationError(
+ 'invalid_params',
+ `invalid valid_from: "${String(p.valid_from)}" — expected a parseable ISO 8601 datetime`,
+ );
+ }
+ validFrom = d;
+ }
+ const sourceSlug =
+ typeof p.source_slug === 'string' && p.source_slug.trim().length > 0
+ ? p.source_slug.trim()
+ : undefined;
+
const r = await runFactsPipeline(p.turn_text as string, {
engine: ctx.engine,
sourceId,
sessionId: typeof p.session_id === 'string' ? p.session_id : null,
- entityHints: Array.isArray(p.entity_hints) ? (p.entity_hints as string[]) : undefined,
+ entityHints,
source: 'mcp:extract_facts',
visibility,
+ validFrom,
+ sourceSlug,
mode: 'inline', // declarative; runFactsPipeline always inline
});
@@ -96,6 +132,7 @@ const extract_facts: Operation = {
if (r.skipped_reason === 'chat_unavailable') {
return {
inserted: 0, duplicate: 0, superseded: 0, fact_ids: [],
+ ...hintAccounting,
skipped: 'extraction_unavailable',
agent_action:
'No server-side chat model is available. You are an LLM: extract the facts ' +
@@ -110,6 +147,7 @@ const extract_facts: Operation = {
if (r.skipped_reason) {
return {
inserted: 0, duplicate: 0, superseded: 0, fact_ids: [],
+ ...hintAccounting,
skipped: 'extraction_failed',
reason: r.skipped_reason,
agent_action:
@@ -124,6 +162,7 @@ const extract_facts: Operation = {
duplicate: r.duplicate,
superseded: r.superseded,
fact_ids: r.fact_ids,
+ ...hintAccounting,
};
},
};
@@ -139,7 +178,7 @@ const recall: Operation = {
since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only.' },
session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
- supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (expired_at + superseded_by both set).' },
+ supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (facts with superseded_by set), newest first by COALESCE(expired_at, valid_until).' },
limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },
grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied client-side after recall.' },
include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },
@@ -180,7 +219,8 @@ const recall: Operation = {
type FactRows = Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>>;
type FactRowItem = FactRows[number];
// Per-arm merge key: each arm's engine query ORDERs by a different column
- // (supersessions by expired_at, entity by valid_from, the rest by
+ // (supersessions by COALESCE(expired_at, valid_until) — #3014, entity by
+ // valid_from, the rest by
// created_at) — the cross-source merge must sort by the SAME key or the
// truncation at `limit` silently drops the wrong rows. Decorate-sort-
// undecorate: the key is computed once per row.
@@ -215,7 +255,9 @@ const recall: Operation = {
await Promise.all(factSources.map(src =>
ctx.engine.listSupersessions(src, { since: since ?? undefined, limit, visibility }),
)),
- (rec) => rec.expired_at ?? rec.created_at,
+ // v0.46 (#3014): matches the engine's ORDER BY COALESCE(expired_at,
+ // valid_until) — ontology supersessions carry valid_until only.
+ (rec) => rec.expired_at ?? rec.valid_until ?? rec.created_at,
);
} else if (typeof p.entity === 'string' && p.entity.length > 0) {
const { resolveEntitySlug } = await import('../entities/resolve.ts');
@@ -320,9 +362,15 @@ const recall: Operation = {
let searchDegraded: string | undefined;
if (queryText) {
const searchScope = sourceScopeOpts(ctx);
+ // #4352 — recall's page-search arm enforces `visibility: private` for
+ // untrusted callers (matches the facts arms' world-only filter above).
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
if (!isAvailable('embedding')) {
- const raw = await ctx.engine.searchKeyword(queryText, { limit, ...searchScope });
+ const raw = await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, ...searchScope });
searchResults = dedupResults(raw);
+ // #3783 — direct FTS path: every row is a keyword hit by construction.
+ markKeywordHits(searchResults);
stampEvidenceSafe(searchResults);
await stampContentFlags(ctx.engine, searchResults);
searchDegraded = 'keyword_only_no_embedding_provider';
@@ -330,6 +378,7 @@ const recall: Operation = {
searchResults = await hybridSearchCached(ctx.engine, queryText, {
limit,
expansion: false,
+ excludePrivate,
...searchScope,
});
}
@@ -376,6 +425,9 @@ const recall: Operation = {
consolidated_into: r.consolidated_into,
source: r.source,
source_session: r.source_session,
+ // #4206: provenance context (e.g. extract_facts' source_slug) rides
+ // the recall projection like every other provenance field.
+ context: r.context,
confidence: r.confidence,
created_at: r.created_at.toISOString(),
// MEMORY_VERBS v1 additive fields (G1B). `fact_id` is the opaque
@@ -512,6 +564,8 @@ const context_pack: Operation = {
kind: f.kind,
entity_slug: f.entity_slug,
valid_from: f.valid_from,
+ // #4206: provenance context (parity with the recall projection).
+ context: f.context ?? null,
confidence: f.confidence,
})),
text,
@@ -694,6 +748,8 @@ const delta: Operation = {
kind: f.kind,
entity_slug: f.entity_slug,
valid_from: f.valid_from,
+ // #4206: provenance context (parity with the recall projection).
+ context: f.context ?? null,
confidence: f.confidence,
})),
threads,
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
index 1b1085d28d..2f62326f53 100644
--- a/src/core/ops/files.ts
+++ b/src/core/ops/files.ts
@@ -83,24 +83,43 @@ const file_upload: Operation = {
};
const mimeType = MIME_TYPES[extname(filePath).toLowerCase()] || null;
+ // #4302 (fail-closed honesty): a files row must never claim bytes that
+ // were stored nowhere. With no storage backend configured, the old path
+ // inserted the row and returned status:'uploaded' anyway — every later
+ // read (file_url, files verify, restore) would trust a phantom object.
+ // Typed error BEFORE any insert; git-tracked small files have their own
+ // lane (`gbrain files upload-raw --page <slug>`).
+ if (!ctx.config.storage) {
+ throw new OperationError(
+ 'storage_error',
+ 'No storage backend configured — file_upload would record a files row with no stored bytes.',
+ 'Configure `storage` in your gbrain config (supabase | s3 | local), or use `gbrain files upload-raw --page <slug>` for git-tracked small files.',
+ );
+ }
+ const { createStorage } = await import('../storage.ts');
+ const storage = await createStorage(ctx.config.storage as any);
+
const { sqlQueryForEngine } = await import('../sql-query.ts');
const sql = sqlQueryForEngine(ctx.engine);
const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;
if (existing.length > 0) {
- return { status: 'already_exists', storage_path: storagePath };
- }
-
- // Upload to storage backend if configured
- if (ctx.config.storage) {
- const { createStorage } = await import('../storage.ts');
- const storage = await createStorage(ctx.config.storage as any);
+ // #4302: only claim already_exists when the BACKEND really holds the
+ // object — a DB row whose bytes vanished must re-upload, not lie.
+ let inBackend = false;
try {
- await storage.upload(storagePath, content, mimeType || undefined);
- } catch (uploadErr) {
- throw new OperationError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`);
+ inBackend = await storage.exists(storagePath);
+ } catch { /* probe failure → treat as absent, re-upload below */ }
+ if (inBackend) {
+ return { status: 'already_exists', storage_path: storagePath };
}
}
+ try {
+ await storage.upload(storagePath, content, mimeType || undefined);
+ } catch (uploadErr) {
+ throw new OperationError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`);
+ }
+
try {
await sql`
INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
@@ -112,13 +131,9 @@ const file_upload: Operation = {
`;
} catch (dbErr) {
// Rollback: clean up storage if DB write failed
- if (ctx.config.storage) {
- try {
- const { createStorage } = await import('../storage.ts');
- const storage = await createStorage(ctx.config.storage as any);
- await storage.delete(storagePath);
- } catch { /* best effort cleanup */ }
- }
+ try {
+ await storage.delete(storagePath);
+ } catch { /* best effort cleanup */ }
throw dbErr;
}
@@ -141,8 +156,26 @@ const file_url: Operation = {
if (rows.length === 0) {
throw new OperationError('storage_error', `File not found: ${p.storage_path}`);
}
- // TODO: generate signed URL from Supabase Storage
- return { storage_path: rows[0].storage_path, url: `gbrain:files/${rows[0].storage_path}` };
+ // #4302: resolve a REAL URL from the backend, after confirming the object
+ // is actually there — the old `gbrain:files/<path>` placeholder pointed
+ // at nothing and hid rows whose bytes had vanished.
+ if (!ctx.config.storage) {
+ throw new OperationError(
+ 'storage_error',
+ `No storage backend configured — cannot produce a URL for ${p.storage_path}.`,
+ 'Configure `storage` in your gbrain config (supabase | s3 | local).',
+ );
+ }
+ const { createStorage } = await import('../storage.ts');
+ const storage = await createStorage(ctx.config.storage as any);
+ const present = await storage.exists(rows[0].storage_path as string).catch(() => false);
+ if (!present) {
+ throw new OperationError(
+ 'storage_error',
+ `File row exists but the storage backend has no object at ${rows[0].storage_path} — re-upload it.`,
+ );
+ }
+ return { storage_path: rows[0].storage_path, url: await storage.getUrl(rows[0].storage_path as string) };
},
};
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index c38479abf2..a9c5a43cb7 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -10,9 +10,60 @@
import type { Operation, OperationContext } from './contract.ts';
import { OperationError } from './contract.ts';
import { normalizeSlugPrefix } from './context.ts';
+import { hasScope } from '../scope.ts';
// --- Jobs (Minions) ---
+/**
+ * #4098 — agent-lane ownership fence for the generic jobs ops.
+ *
+ * get_job / list_jobs / get_job_progress / cancel_job are `scope: 'admin'`
+ * ops that gained `agentCallable: true` so an agent-scoped OAuth client can
+ * monitor + cancel the jobs it submitted via submit_agent — WITHOUT admin.
+ * Returns the owner client id to fence on, or null when the caller is
+ * unfenced (full visibility):
+ *
+ * - trusted local CLI (ctx.remote === false): unfenced (today's behavior)
+ * - token with admin scope: unfenced (satisfied the op's declared scope)
+ * - stdio MCP (remote, transport 'stdio', no per-token auth): unfenced —
+ * the local-pipe surface ceiling governs there, same posture as today
+ * - anything else (the agentCallable carve-out, i.e. agent scope without
+ * admin): MUST carry ctx.auth.clientId; fenced on
+ * `data->>'__owner_client_id'`. Missing identity → permission_denied
+ * (fail closed, mirroring get_agent_job).
+ */
+function agentOwnerFence(ctx: OperationContext, opName: string): string | null {
+ if (ctx.remote === false) return null;
+ const scopes = ctx.auth?.scopes;
+ if (scopes && hasScope(scopes, 'admin')) return null;
+ if (!ctx.auth && ctx.transport === 'stdio') return null;
+ const clientId = ctx.auth?.clientId;
+ if (!clientId || typeof clientId !== 'string') {
+ throw new OperationError(
+ 'permission_denied',
+ `${opName} without admin scope requires an authenticated OAuth client identity.`,
+ 'Call over HTTP MCP with an `agent`-scoped token, or use an admin-scope token for unfenced access.',
+ );
+ }
+ return clientId;
+}
+
+/**
+ * #4098 — SQL-side ownership check (the get_agent_job predicate, uniform
+ * not-found). Foreign-owned and nonexistent ids are indistinguishable by
+ * design (anti-enumeration): both throw the SAME error the unfenced path
+ * throws for a missing id.
+ */
+async function assertJobOwned(ctx: OperationContext, id: number, owner: string): Promise<void> {
+ const rows = await ctx.engine.executeRaw<{ id: number }>(
+ `SELECT id FROM minion_jobs WHERE id = $1 AND data->>'__owner_client_id' = $2`,
+ [id, owner],
+ );
+ if (rows.length === 0) {
+ throw new OperationError('invalid_params', `Job not found: ${id}`);
+ }
+}
+
const submit_job: Operation = {
name: 'submit_job',
description: 'Submit a background job to the Minions queue. Built-in types are registered by registerBuiltinHandlers (src/commands/jobs.ts) — e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle, subagent, and more; submitting an unknown name with --follow prints the full list. The `shell` type is CLI-only and rejected over MCP.',
@@ -488,12 +539,15 @@ const get_agent_job: Operation = {
const get_job: Operation = {
name: 'get_job',
- description: 'Get job status and details by ID',
+ description: 'Get job status and details by ID. Agent-scoped tokens (no admin) see only jobs they own.',
params: {
id: { type: 'number', required: true, description: 'Job ID' },
},
scope: 'admin',
+ agentCallable: true,
handler: async (ctx, p) => {
+ const owner = agentOwnerFence(ctx, 'get_job');
+ if (owner !== null) await assertJobOwned(ctx, p.id as number, owner);
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
const job = await queue.getJob(p.id as number);
@@ -506,7 +560,7 @@ const get_job: Operation = {
const list_jobs: Operation = {
name: 'list_jobs',
- description: 'List jobs with optional filters',
+ description: 'List jobs with optional filters. Agent-scoped tokens (no admin) see only jobs they own.',
params: {
status: { type: 'string', description: 'Filter by status (waiting, active, completed, failed, delayed, dead, cancelled)' },
queue: { type: 'string', description: 'Filter by queue name' },
@@ -514,7 +568,9 @@ const list_jobs: Operation = {
limit: { type: 'number', description: 'Max results (default: 50)' },
},
scope: 'admin',
+ agentCallable: true,
handler: async (ctx, p) => {
+ const owner = agentOwnerFence(ctx, 'list_jobs');
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
const jobs = await queue.getJobs({
@@ -522,6 +578,8 @@ const list_jobs: Operation = {
queue: p.queue as string | undefined,
name: p.name as string | undefined,
limit: (p.limit as number) || 50,
+ // #4098: SQL-side ownership fence for agent-scoped callers.
+ ...(owner !== null ? { ownerClientId: owner } : {}),
} as Parameters<typeof queue.getJobs>[0]);
// private_queue_owner_token is a capability credential (lease renewal /
// attach), not job data — never expose it over MCP envelopes.
@@ -531,17 +589,22 @@ const list_jobs: Operation = {
const cancel_job: Operation = {
name: 'cancel_job',
- description: 'Cancel a waiting, active, or delayed job',
+ description: 'Cancel a waiting, active, or delayed job. Agent-scoped tokens (no admin) can cancel only jobs they own.',
params: {
id: { type: 'number', required: true, description: 'Job ID' },
},
mutating: true,
scope: 'admin',
+ agentCallable: true,
handler: async (ctx, p) => {
if (ctx.dryRun) return { dry_run: true, action: 'cancel_job', id: p.id };
+ const owner = agentOwnerFence(ctx, 'cancel_job');
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
- const cancelled = await queue.cancelJob(p.id as number);
+ // #4098: the owner predicate rides the recursive cancel's CTE seed — a
+ // fenced caller can cancel only roots it owns (descendants of an owned
+ // root cascade as usual). Foreign and missing ids share one envelope.
+ const cancelled = await queue.cancelJob(p.id as number, owner !== null ? { ownerClientId: owner } : undefined);
if (!cancelled) throw new OperationError('invalid_params', `Cannot cancel job ${p.id} (may already be in terminal status)`);
return cancelled;
},
@@ -567,12 +630,15 @@ const retry_job: Operation = {
const get_job_progress: Operation = {
name: 'get_job_progress',
- description: 'Get structured progress for a running job',
+ description: 'Get structured progress for a running job. Agent-scoped tokens (no admin) see only jobs they own.',
params: {
id: { type: 'number', required: true, description: 'Job ID' },
},
scope: 'admin',
+ agentCallable: true,
handler: async (ctx, p) => {
+ const owner = agentOwnerFence(ctx, 'get_job_progress');
+ if (owner !== null) await assertJobOwned(ctx, p.id as number, owner);
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(ctx.engine);
const job = await queue.getJob(p.id as number);
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 5895fd82c9..29bdaaabcd 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -9,6 +9,39 @@
import type { Operation } from './contract.ts';
import { enforceClientSlugFence, linkReadScopeOpts, sourceScopeOpts } from './context.ts';
+// #4224: flag-gated cross-source identity union for the link read ops.
+import { unionLinksAcrossIdentity } from '../entity-identity.ts';
+import { findPrivateOnlySlugs, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { Link } from '../types.ts';
+
+/**
+ * #4352 remediation shared by get_links / get_backlinks: when the caller is
+ * untrusted, a `visibility: private` queried page reads exactly like a
+ * missing one ([]), and edges touching a private endpoint (from / to /
+ * frontmatter origin) are dropped so the link surface can't enumerate
+ * private slugs. One probe covers the queried slug + every endpoint; the
+ * probe considers deleted rows too (fail-closed). Trusted local + the
+ * operator opt-outs short-circuit before any query.
+ */
+async function dropPrivateLinkEndpoints(
+ engine: BrainEngine,
+ remote: boolean | undefined,
+ slug: string,
+ links: Link[],
+ scope: { sourceId?: string; sourceIds?: string[] },
+): Promise<Link[]> {
+ if (!(await resolveExcludePrivatePages(engine, remote))) return links;
+ const endpointSlugs = [...new Set([
+ slug,
+ ...links.flatMap(l => [l.from_slug, l.to_slug, ...(l.origin_slug ? [l.origin_slug] : [])]),
+ ])];
+ const hidden = await findPrivateOnlySlugs(engine, endpointSlugs, scope, { includeDeleted: true });
+ if (hidden.has(slug)) return [];
+ return links.filter(
+ l => !hidden.has(l.from_slug) && !hidden.has(l.to_slug) && !(l.origin_slug && hidden.has(l.origin_slug)),
+ );
+}
// --- Links ---
@@ -108,7 +141,18 @@ const get_links: Operation = {
// scalar scope (promoted to sourceIds[]) — reaches the engine's all-endpoint
// branch. Trusted local/internal callers keep the scalar cross-source view.
const sourceOpts = linkReadScopeOpts(ctx);
- return ctx.engine.getLinks(p.slug as string, sourceOpts);
+ const links = await ctx.engine.getLinks(p.slug as string, sourceOpts);
+ // #4224: flag-gated identity union — merge edges from the page's identity
+ // co-members (entity_identity.union config, default off; pure no-op then).
+ // Member visibility never widens past the caller's grant. The scalar base
+ // scope (when present) pins group resolution to the page actually read.
+ const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'out', {
+ sourceId: sourceOpts.sourceId,
+ allowedSources: sourceOpts.sourceIds,
+ });
+ // #4352: private filtering runs AFTER the identity union so co-member
+ // edges the union adds are subject to the same visibility gate.
+ return dropPrivateLinkEndpoints(ctx.engine, ctx.remote, p.slug as string, unioned, sourceOpts);
},
scope: 'read',
};
@@ -123,7 +167,14 @@ const get_backlinks: Operation = {
// #2200: linkReadScopeOpts — federated grant + untrusted remote scalar
// (promoted to sourceIds[]) reach the engine's all-endpoint branch.
const sourceOpts = linkReadScopeOpts(ctx);
- return ctx.engine.getBacklinks(p.slug as string, sourceOpts);
+ const links = await ctx.engine.getBacklinks(p.slug as string, sourceOpts);
+ // #4224: flag-gated identity union (see get_links).
+ const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'in', {
+ sourceId: sourceOpts.sourceId,
+ allowedSources: sourceOpts.sourceIds,
+ });
+ // #4352: private filtering after the union (see get_links).
+ return dropPrivateLinkEndpoints(ctx.engine, ctx.remote, p.slug as string, unioned, sourceOpts);
},
scope: 'read',
cliHints: { name: 'backlinks', positional: ['slug'] },
@@ -178,12 +229,41 @@ const traverse_graph: Operation = {
// traverseGraph / traversePaths happily followed edges into pages from
// foreign sources, leaking topology + page metadata via the graph op.
const scope = sourceScopeOpts(ctx);
+ // #4352 remediation: graph output must not enumerate private slugs to an
+ // untrusted caller. A private START page reads exactly like a missing one
+ // ([]); private nodes/edges elsewhere in the walk are stripped post-hoc
+ // (op-level gate, same as get_page — the engine CTE stays shared).
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ if (excludePrivate) {
+ const startHidden = await findPrivateOnlySlugs(ctx.engine, [slug], scope, { includeDeleted: true });
+ if (startHidden.has(slug)) return [];
+ }
// Backward compat: when neither link_type nor direction is provided, return
// the legacy GraphNode[] shape. Once either is set, switch to GraphPath[].
if (linkType === undefined && direction === undefined) {
- return ctx.engine.traverseGraph(slug, depth, scope);
+ const nodes = await ctx.engine.traverseGraph(slug, depth, scope);
+ if (!excludePrivate) return nodes;
+ const hidden = await findPrivateOnlySlugs(
+ ctx.engine,
+ [...new Set(nodes.flatMap(n => [n.slug, ...n.links.map(l => l.to_slug)]))],
+ scope,
+ { includeDeleted: true },
+ );
+ return nodes
+ .filter(n => !hidden.has(n.slug))
+ .map(n => (n.links.some(l => hidden.has(l.to_slug))
+ ? { ...n, links: n.links.filter(l => !hidden.has(l.to_slug)) }
+ : n));
}
- return ctx.engine.traversePaths(slug, { depth, linkType, direction, ...scope });
+ const paths = await ctx.engine.traversePaths(slug, { depth, linkType, direction, ...scope });
+ if (!excludePrivate) return paths;
+ const hidden = await findPrivateOnlySlugs(
+ ctx.engine,
+ [...new Set(paths.flatMap(e => [e.from_slug, e.to_slug]))],
+ scope,
+ { includeDeleted: true },
+ );
+ return paths.filter(e => !hidden.has(e.from_slug) && !hidden.has(e.to_slug));
},
scope: 'read',
cliHints: { name: 'graph', positional: ['slug'] },
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index a15355815d..6c0ac0c10d 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -14,6 +14,8 @@ import { importFromContent } from '../import-file.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { writePageThrough, type WriteThroughResult } from '../write-through.ts';
import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';
+// #3190: pack-aware link typing on the put_page auto-link path.
+import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
import { isFactsBackstopEligible } from '../facts/eligibility.ts';
import { stripTakesFence } from '../takes-fence.ts';
import type { WriterLintPayload } from '../output/post-write.ts';
@@ -21,6 +23,7 @@ import { stripFactsFence } from '../facts-fence.ts';
import { getContentFlag } from '../quarantine.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { isValidSourceId, ALL_SOURCES } from '../source-id.ts';
+import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
@@ -96,6 +99,26 @@ function assertSourceInWriteGrant(ctx: OperationContext, sourceId: string): void
);
}
+/**
+ * #4352 remediation — filter fuzzy-resolution candidates so get_page's
+ * ambiguous_slug candidate list can't enumerate private slugs to an
+ * untrusted caller. Probe SQL lives ONCE in findPrivateOnlySlugs (a slug
+ * with at least one non-private in-scope page stays visible; candidates
+ * come from resolveSlugs, so every slug has a live page row).
+ * Order-preserving (resolveSlugs returns ranked candidates). Read-only,
+ * scope-threaded — not a getPage/putPage pair (no unscoped-check/scoped-write
+ * hazard).
+ */
+async function dropPrivateSlugs(
+ engine: BrainEngine,
+ candidates: string[],
+ scope: { sourceId?: string; sourceIds?: string[] },
+ includeDeleted: boolean,
+): Promise<string[]> {
+ const hidden = await findPrivateOnlySlugs(engine, candidates, scope, { includeDeleted });
+ return candidates.filter(c => !hidden.has(c));
+}
+
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).',
@@ -126,14 +149,32 @@ const get_page: Operation = {
const sourceOpts = federatedSearchScope(ctx, sourceIdParam);
const fuzzyScope = sourceOpts;
+ // #4352 remediation: untrusted callers never read `visibility: private`
+ // bodies — the same resolveExcludePrivatePages gate search/recall/entity
+ // already apply (trusted local + the operator opt-outs resolve to false).
+ // A gated private page behaves exactly like a missing one (no existence
+ // oracle), composing with — not replacing — the source-grant scope above.
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+
let page = await ctx.engine.getPage(slug, { includeDeleted, ...sourceOpts });
+ if (page && excludePrivate && isPrivatePage(page.frontmatter)) page = null;
let resolved_slug: string | undefined;
if (!page && fuzzy) {
- const candidates = await ctx.engine.resolveSlugs(slug, fuzzyScope);
+ let candidates = await ctx.engine.resolveSlugs(slug, fuzzyScope);
+ // #4352: the ambiguous_slug candidate list must not enumerate private slugs.
+ if (excludePrivate && candidates.length > 0) {
+ candidates = await dropPrivateSlugs(ctx.engine, candidates, fuzzyScope, includeDeleted);
+ }
if (candidates.length === 1) {
- page = await ctx.engine.getPage(candidates[0], { includeDeleted, ...sourceOpts });
- resolved_slug = candidates[0];
+ const fuzzyPage = await ctx.engine.getPage(candidates[0], { includeDeleted, ...sourceOpts });
+ // Multi-source backstop: the slug may still resolve to a private
+ // variant (same slug private in one source, world in another —
+ // getPage returns the first in-scope match).
+ if (fuzzyPage && !(excludePrivate && isPrivatePage(fuzzyPage.frontmatter))) {
+ page = fuzzyPage;
+ resolved_slug = candidates[0];
+ }
} else if (candidates.length > 1) {
return { error: 'ambiguous_slug', candidates };
}
@@ -216,6 +257,75 @@ const get_page: Operation = {
cliHints: { name: 'get', positional: ['slug'] },
};
+/**
+ * #4039: OpenAI deep-research adapter. ChatGPT's deep research mode requires
+ * an MCP server to expose a `search`/`fetch` PAIR with a fixed contract:
+ * search results carry an `id`, and `fetch(id)` returns
+ * `{ id, title, text, url, metadata }`. gbrain had `search` but no `fetch`,
+ * so the connector worked in normal chat and failed in deep research. This
+ * is a thin get_page adapter: id = slug (the `search` op stamps `id: slug`
+ * on every result so the pair round-trips), same source scoping and
+ * remote-reader privacy fences as get_page, no fuzzy resolution (deep
+ * research always echoes back an id it was handed).
+ */
+const fetch_page: Operation = {
+ name: 'fetch',
+ description: "Fetch the full text of one search result by its `id` (OpenAI deep-research contract: the search/fetch pair). `id` is the page slug stamped on every `search` result. Returns { id, title, text, url, metadata } — `text` is the page's canonical markdown. For the richer gbrain-native read (fuzzy slugs, soft-delete recovery, lossless edit round-trips), use get_page.",
+ params: {
+ id: { type: 'string', required: true, description: 'Result id from a prior `search` call (= the page slug).' },
+ },
+ handler: async (ctx, p) => {
+ const id = p.id as string;
+ if (typeof id !== 'string' || !id.trim()) {
+ throw new OperationError('invalid_params', 'fetch requires a non-empty id', 'Pass the `id` field from a `search` result.');
+ }
+ const slug = id.trim();
+ // Same scope ladder as get_page's unqualified read: federated array >
+ // scalar > nothing — a remote caller only fetches what its grant spans.
+ const sourceOpts = federatedSearchScope(ctx);
+ let page = await ctx.engine.getPage(slug, sourceOpts);
+ // #4352 remediation: a `visibility: private` page reads as missing for
+ // untrusted callers (same resolveExcludePrivatePages gate as get_page —
+ // fetch is remote-facing by design, every MCP transport). Cheap row
+ // check first; the resolver short-circuits for trusted local callers.
+ if (page && isPrivatePage(page.frontmatter) && (await resolveExcludePrivatePages(ctx.engine, ctx.remote))) {
+ page = null;
+ }
+ if (!page) {
+ throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Pass an id returned by a `search` call.');
+ }
+ bumpLastRetrievedAt(ctx.engine, [page.id]);
+ const tags = await ctx.engine.getTags(page.slug, { sourceId: page.source_id });
+ // Same privacy boundary as get_page: untrusted readers (ctx.remote ===
+ // 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'] },
+ ),
+ };
+ return {
+ id: page.slug,
+ title: page.title,
+ text: serializePageToMarkdown(visibleBody as Page, tags),
+ // Pages have no public http home; a stable brain-local URI satisfies
+ // the contract's citation slot without inventing a fake web URL.
+ url: `gbrain://page/${page.source_id}/${page.slug}`,
+ metadata: {
+ type: page.type,
+ source_id: page.source_id,
+ updated_at: page.updated_at,
+ tags,
+ },
+ };
+ },
+ scope: 'read',
+ cliHints: { name: 'fetch', positional: ['id'] },
+};
+
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).',
@@ -498,11 +608,20 @@ const put_page: Operation = {
const fullContent = result.parsedPage.compiled_truth + '\n' + result.parsedPage.timeline;
const entries = parseTimelineEntries(fullContent);
if (entries.length > 0) {
+ // #3957: thread source_id — the batch JOIN maps a missing
+ // source_id to 'default', so a put_page against a named source
+ // silently dropped every timeline row (or attached them to a
+ // same-slug page in 'default'). Also carry the parsed source
+ // label so the row shape matches the FS/db extract paths and
+ // the (page_id, date, summary, source) dedup collapses
+ // re-extractions of the same bullet.
const batch = entries.map(e => ({
slug,
date: e.date,
+ source: e.source,
summary: e.summary,
detail: e.detail || '',
+ ...(ctx.sourceId ? { source_id: ctx.sourceId } : {}),
}));
// v0.41.18.0: engine self-retries on Supavisor circuit-breaker
// recovery. auditSite label routes the audit JSONL emission so
@@ -628,10 +747,35 @@ const put_page: Operation = {
writerLint = { status: 'lint_error' };
}
+ // #2822: a 0-chunk put looks like success but the page is unsearchable —
+ // say WHY instead of leaving the caller to discover it at query time.
+ let chunkSkipReason: string | undefined;
+ if (result.chunks === 0) {
+ if (result.status === 'skipped') {
+ chunkSkipReason = 'write_skipped'; // dedup / unchanged content — prior chunks stand
+ } else if (result.parsedPage) {
+ const { isQuarantined } = await import('../quarantine.ts');
+ const { isEmbedSkipped } = await import('../embed-skip.ts');
+ const fm = result.parsedPage.frontmatter as Record<string, unknown> | undefined;
+ const bodyBlank = `${result.parsedPage.compiled_truth ?? ''}${result.parsedPage.timeline ?? ''}`.trim() === '';
+ chunkSkipReason = isQuarantined(fm) ? 'quarantined'
+ : isEmbedSkipped(fm) ? 'embed_skip'
+ : bodyBlank ? 'empty_body'
+ : 'unknown';
+ }
+ }
+
return {
slug: result.slug,
status: result.status === 'imported' ? 'created_or_updated' : result.status,
chunks: result.chunks,
+ // #3984: a skipped/error status without the reason is a silent no-op to
+ // MCP callers (e.g. the >5MB size guard returned bare status 'skipped'
+ // and the agent had no idea why the page never appeared). Thread
+ // importFromContent's error text through. capture delegates here, so
+ // it inherits the reason too.
+ ...(result.error ? { error: result.error } : {}),
+ ...(chunkSkipReason ? { chunk_skip_reason: chunkSkipReason } : {}),
...(autoLinks ? { auto_links: autoLinks } : {}),
...(autoTimeline ? { auto_timeline: autoTimeline } : {}),
...(writerLint ? { writer_lint: writerLint } : {}),
@@ -739,18 +883,42 @@ async function runAutoLink(
const resolver = makeResolver(engine, { mode: 'live', sourceId: opts?.sourceId });
// Issue #972: opt-in bare-wikilink basename resolution. Off by default.
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: pack-aware link typing + pack frontmatter_links on the put_page
+ // auto-link path. Loaded via the local-engine best-effort resolver (this
+ // hook only runs for trusted-local / trusted-workspace writes); null keeps
+ // the legacy in-code inference.
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
const { candidates, unresolved } = await extractPageLinks(
slug, fullContent, parsed.frontmatter, parsed.type, resolver,
- { globalBasename },
+ { globalBasename, pack },
);
// Resolve which targets exist (skip refs to non-existent pages to avoid FK
- // violation churn in addLink). One getAllSlugs call upfront, O(1) lookup.
- // v0.31.8 (D12): scoped to the source when opts.sourceId is set so wikilink
- // resolution doesn't span unrelated sources.
- const allSlugs = await engine.getAllSlugs(sourceOpts);
+ // violation churn in addLink). #2544: targeted membership probe over just
+ // the candidate target/from slugs instead of materializing the whole slug
+ // set — getAllSlugs was a full-table scan on EVERY put_page while the
+ // candidates are typically a handful. Mirrors the proven oneshot probe
+ // (subagent-oneshot.ts). Deliberately does NOT filter deleted_at: the
+ // getAllSlugs it replaces included soft-deleted pages, and changing link
+ // visibility is out of scope here. Skips the query entirely when there are
+ // no candidates. v0.31.8 (D12): scoped to the source when opts.sourceId is
+ // set so wikilink resolution doesn't span unrelated sources.
+ const candidateSlugs = [...new Set(candidates.flatMap(c => (c.fromSlug ? [c.targetSlug, c.fromSlug] : [c.targetSlug])))];
+ let existingSlugs = new Set<string>();
+ if (candidateSlugs.length > 0) {
+ const rows = opts?.sourceId
+ ? await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2`,
+ [candidateSlugs, opts.sourceId],
+ )
+ : await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE slug = ANY($1::text[])`,
+ [candidateSlugs],
+ );
+ existingSlugs = new Set(rows.map(r => r.slug));
+ }
const valid = candidates.filter(c =>
- allSlugs.has(c.targetSlug) && (!c.fromSlug || allSlugs.has(c.fromSlug))
+ existingSlugs.has(c.targetSlug) && (!c.fromSlug || existingSlugs.has(c.fromSlug))
);
// Split candidates by direction. Outgoing (fromSlug === slug or unset) are
@@ -1035,6 +1203,12 @@ const list_pages: Operation = {
// as search/query's sourceIdParam.
const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
const scope = federatedSearchScope(ctx, sourceIdParam);
+ // #4352 remediation: untrusted listing never enumerates
+ // `visibility: private` pages (slugs + titles are the leak surface here).
+ // Composes with the #4400 per-call source_id and the v0.34.1 grant scope
+ // above — an ADDITIONAL predicate threaded into PageFilters, never a
+ // replacement for the source filter. Trusted local enumeration unchanged.
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
// The 100-row cap exists to protect remote MCP/OAuth transports from
// unbounded result dumps. Local CLI callers (ctx.remote === false — the
// same trust boundary that already bypasses scope enforcement, see the
@@ -1074,6 +1248,7 @@ const list_pages: Operation = {
includeDeleted: (p.include_deleted as boolean) === true,
updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
sort,
+ excludePrivate,
...scope,
});
const truncated = rows.length > limit;
@@ -1199,4 +1374,5 @@ const capture: Operation = {
export const pagesOperations: Operation[] = [
get_page, put_page, delete_page, list_pages,
restore_page, purge_deleted_pages, capture,
+ fetch_page,
];
diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.ts
index f91088d0ba..ec3c1520b1 100644
--- a/src/core/ops/raw-data.ts
+++ b/src/core/ops/raw-data.ts
@@ -7,6 +7,7 @@
import type { Operation } from './contract.ts';
import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+import { slugHiddenFromCaller } from '../search/private-visibility.ts';
// --- Raw Data ---
@@ -38,7 +39,12 @@ const get_raw_data: Operation = {
source: { type: 'string', description: 'Filter by source' },
},
handler: async (ctx, p) => {
- return ctx.engine.getRawData(p.slug as string, p.source as string | undefined, sourceScopeOpts(ctx));
+ const scope = sourceScopeOpts(ctx);
+ // #4352 remediation: a `visibility: private` page's raw data reads
+ // exactly like a missing page's ([]) for untrusted callers — no
+ // existence oracle.
+ if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];
+ return ctx.engine.getRawData(p.slug as string, p.source as string | undefined, scope);
},
scope: 'read',
};
diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.ts
index 0ca661e52e..802e094146 100644
--- a/src/core/ops/schema-packs.ts
+++ b/src/core/ops/schema-packs.ts
@@ -36,8 +36,14 @@ const get_active_schema_pack: Operation = {
const cfg = loadConfig();
const sourceOpts: Record<string, unknown> = {};
if (ctx.sourceId) sourceOpts.sourceId = ctx.sourceId;
- const resolution = resolveActivePackNameOnly({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
+ // #3792: thread the DB-plane schema_pack (tier 4) so this identity
+ // packet reports the SAME pack the engine actually queries with.
+ let dbConfig: string | undefined;
+ try {
+ dbConfig = (await ctx.engine.getConfig('schema_pack')) ?? undefined;
+ } catch { /* engine.config may not exist on very old brains */ }
+ const resolution = resolveActivePackNameOnly({ cfg, remote: ctx.remote ?? true, dbConfig, ...sourceOpts });
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, dbConfig, ...sourceOpts });
const primitiveSummary: Record<string, number> = {};
for (const t of pack.manifest.page_types) {
primitiveSummary[t.primitive] = (primitiveSummary[t.primitive] ?? 0) + 1;
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 973ba7ba56..9227987596 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -7,20 +7,31 @@
*/
import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';
-import { looksConceptShaped } from '../search/query-intent.ts';
+import { looksConceptShaped, classifyQueryShape } from '../search/query-intent.ts';
+import {
+ gradeRetrievalConfidence,
+ shouldEscalateRetrieval,
+ confidenceRank,
+ type CragMetaBlock,
+} from '../search/crag.ts';
import { expandQuery } from '../search/expansion.ts';
import { dedupResults } from '../search/dedup.ts';
+import { markKeywordHits } from '../search/evidence.ts';
import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';
import type { HybridSearchMeta } from '../types.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
+import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
import { OperationError } from './contract.ts';
-import type { Operation } from './contract.ts';
+import type { Operation, OperationContext } from './contract.ts';
import {
federatedSearchScope,
resolvePerCallMode,
+ stampDeepResearchIds,
stampEvidenceSafe,
maybeCaptureSearch,
+ thinkSourceScopeOpts,
} from './context.ts';
// --- Search ---
@@ -58,6 +69,69 @@ function buildRetrievalResponseMeta(
};
}
+/**
+ * #3985: normalize the `types` param. MCP passes a real array; the CLI
+ * passes `--types person,company` as one string. Rejects non-string entries
+ * and an all-empty list loudly (invalid_params) instead of silently
+ * dropping the filter. The SQL-level plumbing (SearchOpts.types → both
+ * engines' keyword/title/vector legs) has existed since v0.33 (whoknows);
+ * this just exposes it on the public search/query ops.
+ */
+function normalizeTypesParam(raw: unknown): string[] | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const arr = Array.isArray(raw)
+ ? raw
+ : typeof raw === 'string'
+ ? raw.split(',')
+ : null;
+ if (arr === null || arr.some((t) => typeof t !== 'string')) {
+ throw new OperationError(
+ 'invalid_params',
+ '`types` must be an array of page-type strings (CLI: --types person,company).',
+ );
+ }
+ const types = [...new Set((arr as string[]).map((t) => t.trim()).filter(Boolean))];
+ if (types.length === 0) {
+ throw new OperationError(
+ 'invalid_params',
+ '`types` was provided but contained no usable page-type strings (CLI: --types person,company).',
+ );
+ }
+ return types;
+}
+
+const TYPES_PARAM_DESCRIPTION =
+ "Filter results to pages whose `type` is in this list (e.g. ['person','company']). " +
+ 'CLI: --types person,company. Applied at SQL level on every retrieval leg — the same ' +
+ 'filter `whoknows` uses. Stacks with all other filters.';
+
+const SNIPPET_CHARS_PARAM_DESCRIPTION =
+ 'Cap each result\'s chunk_text at N characters (a "… [truncated]" marker names the ' +
+ 'get_page recovery move). 0 forces full text. Unset: subagent tool loops default to ' +
+ 'the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. (#3800)';
+
+/**
+ * #3800: resolve the effective snippet cap for one call. Explicit
+ * `snippet_chars` param wins (0 = full text); else subagent callers
+ * (ctx.viaSubagent — fail-closed dispatcher flag) read the
+ * `agent.search_snippet_chars` config, defaulting to 300; every other
+ * caller gets full text (cap 0 = no-op).
+ */
+async function resolveSnippetCap(ctx: OperationContext, p: Record<string, unknown>): Promise<number> {
+ if (typeof p.snippet_chars === 'number' && Number.isFinite(p.snippet_chars)) {
+ return Math.max(0, Math.floor(p.snippet_chars as number));
+ }
+ if (ctx.viaSubagent !== true) return 0;
+ try {
+ const raw = await ctx.engine.getConfig('agent.search_snippet_chars');
+ if (raw != null && raw !== '') {
+ const n = Number(raw);
+ if (Number.isFinite(n) && n >= 0) return Math.floor(n);
+ }
+ } catch { /* fail-open to the default */ }
+ return DEFAULT_AGENT_SNIPPET_CHARS;
+}
+
const search: Operation = {
name: 'search',
description: SEARCH_DESCRIPTION,
@@ -66,14 +140,25 @@ const search: Operation = {
limit: { type: 'number', description: 'Max results (default 20)' },
offset: { type: 'number', description: 'Skip first N results (for pagination)' },
mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only.' },
+ // #3985: multi-type filter (plumbing shipped v0.33; exposed here).
+ 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 },
},
handler: async (ctx, p) => {
const startedAt = Date.now();
const queryText = p.query as string;
const limit = (p.limit as number) || 20;
const offset = (p.offset as number) || 0;
+ // #3985: validated multi-type filter, threaded into both branches below.
+ 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);
+ // #4352 — untrusted callers never see `visibility: private` pages
+ // (config-gated; trusted local CLI unchanged).
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
// T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote
// OAuth client can't escalate to the costly tokenmax bundle. Local + unknown
@@ -86,8 +171,12 @@ const search: Operation = {
const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';
if (keywordOnly) {
- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, ...scope });
+ const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, ...(types ? { types } : {}), ...scope });
const results = dedupResults(raw);
+ // #3783 — every row here IS a keyword hit (direct FTS path); mark
+ // before stamping so evidence still reads keyword_exact.
+ markKeywordHits(results);
+ stampDeepResearchIds(results);
stampEvidenceSafe(results);
// #1699: the keyword-only opt-out must STILL surface the content_flag
// agent-warning channel (hybridSearch stamps it; this branch bypasses
@@ -100,7 +189,8 @@ const search: Operation = {
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);
ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, null, { conceptHint: true }));
- return results;
+ // #3800: cap AFTER capture/meta so eval + cache see the real payload.
+ return applySnippetCap(results, snippetCap);
}
// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
@@ -110,15 +200,19 @@ const search: Operation = {
limit,
offset,
expansion: false,
+ excludePrivate,
+ ...(types ? { types } : {}),
...scope,
...(perCallMode ? { mode: perCallMode } : {}),
onMeta: (m) => { capturedMeta = m; },
});
+ stampDeepResearchIds(results);
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta, { conceptHint: true }));
- return results;
+ // #3800: cap AFTER capture/meta so eval + cache see the real payload.
+ return applySnippetCap(results, snippetCap);
},
scope: 'read',
cliHints: { name: 'search', positional: ['query'] },
@@ -141,6 +235,10 @@ const query: Operation = {
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)' },
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 },
+ // #3800: subagent token economy — per-call snippet cap.
+ snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
expand: { type: 'boolean', description: 'Enable multi-query expansion (default: true)' },
detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },
mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },
@@ -228,6 +326,11 @@ const query: Operation = {
const expand = p.expand !== false;
const detail = (p.detail as 'low' | 'medium' | 'high') || undefined;
const queryText = p.query as string | undefined;
+ // #3985: validated multi-type filter (text path; the image-similarity
+ // branch below also honors it — searchVector filters types at SQL level).
+ const types = normalizeTypesParam(p.types);
+ // #3800: snippet cap (param > subagent config default > full text).
+ const snippetCap = await resolveSnippetCap(ctx, p);
const imageData = p.image as string | undefined;
const imageMime = (p.image_mime as string) || 'image/jpeg';
const embeddingColumnParam =
@@ -244,6 +347,9 @@ const query: Operation = {
// #2561: unqualified trusted-local query spans federated sources (per-call
// source_id / remote grants still resolve through resolveRequestedScope).
const querySourceScope = federatedSearchScope(ctx, sourceIdParam);
+ // #4352 — same enforcement for the full-control query op (both the image
+ // searchVector branch and the text hybrid path below).
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
// v0.27.1: image-similarity branch. Bypasses hybridSearch (which is
// text-only); embeds the image via embedMultimodal and runs a direct
@@ -261,9 +367,11 @@ const query: Operation = {
limit: (p.limit as number) || 20,
offset: (p.offset as number) || 0,
embeddingColumn: 'embedding_image',
+ excludePrivate,
+ ...(types ? { types } : {}),
...querySourceScope,
});
- return results;
+ return applySnippetCap(results, snippetCap);
}
if (!queryText) {
@@ -289,14 +397,18 @@ const query: Operation = {
// v0.32.x search-lite: route the query op through hybridSearchCached so
// semantic cache + token budget + intent weighting fire automatically.
// Plain hybridSearch remains the bare API for callers that opt out.
- const results = await hybridSearchCached(ctx.engine, queryText, {
+ // (#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,
offset: (p.offset as number) || 0,
+ excludePrivate,
expansion: expand,
expandFn: expand ? expandQuery : undefined,
// T4/D5 — per-call mode (local/trusted only; remote ignored).
...((): { mode?: string } => { const m = resolvePerCallMode(ctx, p.mode); return m ? { mode: m } : {}; })(),
detail,
+ // #3985: multi-type filter — SearchOpts.types reaches every leg.
+ types,
language: (p.lang as string) || undefined,
symbolKind: (p.symbol_kind as string) || undefined,
nearSymbol: (p.near_symbol as string) || undefined,
@@ -329,6 +441,104 @@ const query: Operation = {
// v0.43 — relational recall override. Omitted = smart default (mode bundle).
relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
});
+ // #1663 — CRAG confidence gate. Grade what retrieval returned (zero-LLM;
+ // reads the stamped honesty signals: evidence, exact_lookup, rerank
+ // score), attach grade + query shape to the retrieval meta on EVERY call,
+ // and — config-gated, default OFF — escalate a weak result once:
+ // search.crag_escalation=true → one high-ceiling retrieval re-run
+ // (expansion + relational + wide limit, autocut off). Filters
+ // (scope/types/since/until/lang) are preserved; keep the better run.
+ // search.crag_think=true → still weak + LOCAL caller → run think and
+ // attach its synthesis to the meta (spend-gated by config + trust).
+ const queryShape = classifyQueryShape(queryText);
+ let grade = gradeRetrievalConfidence(results);
+ const crag: CragMetaBlock = {
+ confidence: grade.level,
+ reason: grade.reason,
+ query_shape: queryShape,
+ ...(grade.top_rerank_score !== undefined ? { top_rerank_score: grade.top_rerank_score } : {}),
+ };
+ if (grade.level === 'weak') {
+ const [escalationCfg, thinkCfg] = await Promise.all([
+ ctx.engine.getConfig('search.crag_escalation').catch(() => null),
+ ctx.engine.getConfig('search.crag_think').catch(() => null),
+ ]);
+ if (shouldEscalateRetrieval(grade, { enabled: escalationCfg === 'true' })) {
+ try {
+ let escalatedMeta: HybridSearchMeta | null = null;
+ const escalated = await hybridSearchCached(ctx.engine, queryText, {
+ limit: Math.max((p.limit as number) || 20, 50),
+ offset: (p.offset as number) || 0,
+ expansion: true,
+ expandFn: expandQuery,
+ relationalRetrieval: true,
+ autocut: false,
+ detail,
+ // Preserve the caller's #3985 type filter on the re-run (raw
+ // pass-through; the base call already rejected malformed input).
+ ...(Array.isArray(p.types) || typeof p.types === 'string'
+ ? {
+ types: (Array.isArray(p.types) ? (p.types as string[]) : (p.types as string).split(','))
+ .map((t) => t.trim())
+ .filter(Boolean),
+ }
+ : {}),
+ language: (p.lang as string) || undefined,
+ symbolKind: (p.symbol_kind as string) || undefined,
+ // Preserve the caller's symbol-proximity constraints too — an
+ // escalated set that ignores --near-symbol/--walk-depth must not
+ // replace correctly-filtered weak results.
+ nearSymbol: (p.near_symbol as string) || undefined,
+ walkDepth: typeof p.walk_depth === 'number' ? (p.walk_depth as number) : undefined,
+ ...querySourceScope,
+ since: typeof p.since === 'string' ? p.since : undefined,
+ until: typeof p.until === 'string' ? p.until : undefined,
+ crossModal: p.cross_modal as 'text' | 'image' | 'both' | 'auto' | undefined,
+ embeddingColumn: embeddingColumnParam,
+ onMeta: (m) => { escalatedMeta = m; },
+ });
+ const regraded = gradeRetrievalConfidence(escalated);
+ crag.escalated = true;
+ crag.escalated_confidence = regraded.level;
+ if (confidenceRank(regraded.level) > confidenceRank(grade.level)) {
+ results = escalated;
+ capturedMeta = escalatedMeta;
+ grade = regraded;
+ crag.confidence = regraded.level;
+ crag.reason = regraded.reason;
+ }
+ } catch {
+ // Escalation is best-effort — never fail the original result set.
+ }
+ }
+ if (grade.level === 'weak') {
+ // The honest next move for a still-weak result. Hint always; auto-run
+ // only when the operator opted in AND the caller is trusted-local
+ // (spend + privacy: think synthesizes with the configured LLM).
+ crag.escalate_to_think = true;
+ if (thinkCfg === 'true' && ctx.remote === false) {
+ try {
+ const { runThink } = await import('../think/index.ts');
+ const thinkScope = thinkSourceScopeOpts(ctx);
+ const t = await runThink(ctx.engine, {
+ question: queryText,
+ since: typeof p.since === 'string' ? p.since : undefined,
+ until: typeof p.until === 'string' ? p.until : undefined,
+ ...thinkScope,
+ remote: false,
+ });
+ crag.think = {
+ answer: t.answer,
+ citations: t.citations.length,
+ ...(t.synthesis_status ? { synthesis_status: t.synthesis_status } : {}),
+ model: t.modelUsed,
+ };
+ } catch {
+ // think escalation is best-effort; the hint above still stands.
+ }
+ }
+ }
+ }
const latency_ms = Date.now() - startedAt;
// v0.37.0 (D11): op-layer last_retrieved_at write-back. Same shape as the
@@ -362,8 +572,14 @@ const query: Operation = {
}
// WP2/D3: query never nudges toward itself — no concept hint here.
- ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta));
- return results;
+ // #1663: the CRAG grade rides the same retrieval meta channel.
+ ctx.emitResponseMeta?.('retrieval', {
+ ...buildRetrievalResponseMeta(queryText, results, capturedMeta),
+ crag,
+ });
+ // #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
+ // and recorded the real payload; only the returned envelope is snipped.
+ return applySnippetCap(results, snippetCap);
},
scope: 'read',
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/ops/sync-status.ts b/src/core/ops/sync-status.ts
index f0ed29aa64..501fb18412 100644
--- a/src/core/ops/sync-status.ts
+++ b/src/core/ops/sync-status.ts
@@ -6,6 +6,7 @@
*/
import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
// --- Sync ---
@@ -14,6 +15,7 @@ const sync_brain: Operation = {
description: 'Sync git repo to brain (incremental)',
params: {
repo: { type: 'string', description: 'Path to git repo (optional if configured)' },
+ source_id: { type: 'string', description: 'Explicit source to sync (wins over repo-derived and ambient routing)' },
dry_run: { type: 'boolean', description: 'Preview changes without applying' },
full: { type: 'boolean', description: 'Full re-sync (ignore checkpoint)' },
no_pull: { type: 'boolean', description: 'Skip git pull' },
@@ -24,13 +26,62 @@ const sync_brain: Operation = {
localOnly: true,
handler: async (ctx, p) => {
const { performSync } = await import('../../commands/sync.ts');
- // #2830: thread ctx.sourceId (D7 pattern, same as revert_version /
- // put_page) so a no-`repo` call resolves the CALLER's sync anchor.
- // Without it, performSync read the default source's repo_path/last_commit
- // and silently synced against the wrong repo on multi-source brains.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ // #3765 routing precedence: explicit source_id param > repo-derived source
+ // (dotfile / registered local_path anchored at the REPO dir, #3765) >
+ // ctx.sourceId (#2830 ambient thread). Pre-fix, a `repo` pointing at
+ // source B's checkout synced under the CALLER's source: wrong anchor,
+ // wrong page source_id, wrong `syncLockId(sourceId)` lock key.
+ let sourceId = ctx.sourceId;
+ const explicit = p.source_id as string | undefined;
+ const repo = p.repo as string | undefined;
+ if (explicit) {
+ const { resolveSourceId, SourceTargetError, ALL_SOURCES } = await import('../source-resolver.ts');
+ if (explicit === ALL_SOURCES) {
+ throw new OperationError(
+ 'invalid_params',
+ `sync_brain targets exactly one source; '${ALL_SOURCES}' is not valid here.`,
+ );
+ }
+ try {
+ // Explicit tier of the canonical resolver: regex-validates AND asserts
+ // the source exists + is not archived (no dead-FK writes).
+ sourceId = await resolveSourceId(ctx.engine, explicit);
+ } catch (e) {
+ if (e instanceof SourceTargetError) {
+ throw new OperationError('invalid_params', e.message);
+ }
+ throw e;
+ }
+ } else if (repo) {
+ const { resolveSourceForRepoPath, SourceTargetError } = await import('../source-resolver.ts');
+ let derived: Awaited<ReturnType<typeof resolveSourceForRepoPath>> = null;
+ try {
+ derived = await resolveSourceForRepoPath(ctx.engine, repo);
+ } catch (e) {
+ if (e instanceof SourceTargetError) {
+ throw new OperationError('invalid_params', e.message);
+ }
+ throw e;
+ }
+ if (derived) {
+ // Conflict guard: the caller is PINNED to a non-default source (MCP
+ // scope / dotfile context) but `repo` belongs to a different one.
+ // Refuse with a structured error instead of silently picking a side.
+ if (ctx.sourceId && ctx.sourceId !== 'default' && ctx.sourceId !== derived.source_id) {
+ throw new OperationError(
+ 'invalid_params',
+ `repo path resolves to source '${derived.source_id}' (via ${derived.tier}) but the ` +
+ `caller is scoped to source '${ctx.sourceId}'. Pass source_id explicitly to pick one.`,
+ `Re-run with source_id: '${derived.source_id}' to sync that repo's source, or ` +
+ `source_id: '${ctx.sourceId}' to force the caller's scope.`,
+ );
+ }
+ sourceId = derived.source_id;
+ }
+ }
+ const sourceOpts = sourceId ? { sourceId } : {};
return performSync(ctx.engine, {
- repoPath: p.repo as string | undefined,
+ repoPath: repo,
dryRun: ctx.dryRun || (p.dry_run as boolean) || false,
noEmbed: (p.no_embed as boolean) || false,
noPull: (p.no_pull as boolean) || false,
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 19f69cd0db..b42382d8a0 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -234,12 +234,33 @@ const think: Operation = {
for (const w of persisted.warnings) result.warnings.push(w);
}
+ // #2556: `take` was gated (safeTake) but never EXECUTED — runThink ignores
+ // opts.take, so a local `take: true` silently persisted nothing. Persist
+ // md-first through the canonical takes write-through; refusals surface as
+ // loud machine-stable warnings + take_row:null. Remote stays blocked above.
+ let takeRow: number | null = null;
+ if (safeTake) {
+ if (!p.anchor) {
+ result.warnings.push('TAKE_REQUIRES_ANCHOR');
+ } else {
+ const { persistTakeFromSynthesis } = await import('../think/persist-take.ts');
+ const persisted = await persistTakeFromSynthesis(ctx.engine, result, {
+ anchor: String(p.anchor),
+ sourceId: ctx.sourceId,
+ lockTimeoutMs: 2000,
+ });
+ takeRow = persisted.take_row;
+ for (const w of persisted.warnings) result.warnings.push(w);
+ }
+ }
+
return {
...result,
// #1698 (#10): the persist-skip signal returns slug '' — map it (and any
// falsy) to null so callers never see an empty-string "slug".
saved_slug: savedSlug || null,
evidence_inserted: evidenceInserted,
+ take_row: takeRow,
remote_persisted_blocked: remote && (Boolean(p.save) || Boolean(p.take)),
};
},
diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.ts
index e05925c0e4..d998469d5b 100644
--- a/src/core/ops/timeline.ts
+++ b/src/core/ops/timeline.ts
@@ -8,6 +8,7 @@
import type { Operation } from './contract.ts';
import { enforceSubagentSlugFence, enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+import { slugHiddenFromCaller } from '../search/private-visibility.ts';
import { writeTimelineEntryThrough } from '../timeline-write-through.ts';
// --- Timeline ---
@@ -133,11 +134,16 @@ const get_timeline: Operation = {
handler: async (ctx, p) => {
// #2200: route through sourceScopeOpts so a federated grant reaches the
// engine via TimelineOpts.sourceIds; scalar/unset unchanged.
+ const scope = sourceScopeOpts(ctx);
+ // #4352 remediation: a `visibility: private` page's timeline reads
+ // exactly like a missing page's ([]) for untrusted callers — no
+ // existence oracle.
+ if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];
const after = typeof p.after === 'string' ? p.after : typeof p.since === 'string' ? p.since : undefined;
const before = typeof p.before === 'string' ? p.before : typeof p.until === 'string' ? p.until : undefined;
const limit = typeof p.limit === 'number' ? p.limit : undefined;
return ctx.engine.getTimeline(p.slug as string, {
- ...sourceScopeOpts(ctx),
+ ...scope,
...(after ? { after } : {}),
...(before ? { before } : {}),
...(limit !== undefined ? { limit } : {}),
diff --git a/src/core/ops/usage.ts b/src/core/ops/usage.ts
new file mode 100644
index 0000000000..9b97977e06
--- /dev/null
+++ b/src/core/ops/usage.ts
@@ -0,0 +1,166 @@
+/**
+ * Usage accounting op cluster (#4218, revives the #3392 shape).
+ *
+ * `get_usage` reads the chat_usage_log ledger (migration v136) that
+ * gateway.chat() fills at its success boundary via the chat-usage sink.
+ * Aggregates only — no raw rows — so the surface exposes spend/volume, never
+ * content. The `coverage` block is the honesty contract: it states exactly
+ * what the ledger does and does not capture so a consumer can't mistake a
+ * partial ledger for total spend.
+ *
+ * Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+
+interface UsageRow {
+ model: string;
+ phase: string | null;
+ calls: number | string;
+ input_tokens: number | string | null;
+ output_tokens: number | string | null;
+ cache_read_tokens: number | string | null;
+ cache_write_tokens: number | string | null;
+ cost_usd: number | string | null;
+ unpriced_calls: number | string | null;
+}
+
+const n = (v: number | string | null | undefined): number => Number(v ?? 0);
+
+const get_usage: Operation = {
+ name: 'get_usage',
+ description:
+ 'Aggregate chat usage + cost from the chat_usage_log ledger (per-model and per-phase token counts, cache reads/writes, USD estimates) with explicit coverage fields.',
+ params: {
+ days: { type: 'number', description: 'Window in days (default 30, max 365).' },
+ },
+ // admin, not read: chat_usage_log has no source dimension, so this is the
+ // one read-side surface that CANNOT route through sourceScopeOpts — a
+ // source-restricted/federated read token must not see brain-wide spend
+ // telemetry (models, job-phase names, USD totals). OP_AREAS already groups
+ // it under admin.
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const daysRaw = Number(p.days ?? 30);
+ const days = Number.isFinite(daysRaw) ? Math.min(365, Math.max(1, Math.round(daysRaw))) : 30;
+
+ let rows: UsageRow[] = [];
+ let loggedSince: string | null = null;
+ let tableMissing = false;
+ try {
+ rows = await ctx.engine.executeRaw<UsageRow>(
+ `SELECT model,
+ phase,
+ count(*)::int AS calls,
+ sum(input_tokens)::float8 AS input_tokens,
+ sum(output_tokens)::float8 AS output_tokens,
+ sum(cache_read_tokens)::float8 AS cache_read_tokens,
+ sum(cache_write_tokens)::float8 AS cache_write_tokens,
+ sum(cost_usd)::float8 AS cost_usd,
+ count(*) FILTER (WHERE cost_usd IS NULL)::int AS unpriced_calls
+ FROM chat_usage_log
+ WHERE created_at >= now() - make_interval(days => $1)
+ GROUP BY model, phase
+ ORDER BY sum(cost_usd) DESC NULLS LAST`,
+ [days],
+ );
+ const since = await ctx.engine.executeRaw<{ since: string | null }>(
+ `SELECT min(created_at)::text AS since FROM chat_usage_log`,
+ [],
+ );
+ loggedSince = since[0]?.since ?? null;
+ } catch {
+ // Pre-v136 brain (table absent). Report empty with coverage saying so
+ // rather than erroring — the op is a read surface, not a migration gate.
+ tableMissing = true;
+ }
+
+ const totals = {
+ calls: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ /** Sum over PRICED calls only — see coverage.unpriced_calls. */
+ cost_usd: 0,
+ };
+ const byModel = new Map<
+ string,
+ {
+ model: string;
+ calls: number;
+ input_tokens: number;
+ output_tokens: number;
+ cache_read_tokens: number;
+ cache_write_tokens: number;
+ cost_usd: number | null;
+ unpriced_calls: number;
+ }
+ >();
+ const byPhase = new Map<string, { phase: string; calls: number; cost_usd: number }>();
+ let unpricedCalls = 0;
+
+ for (const r of rows) {
+ const calls = n(r.calls);
+ const rowUnpriced = n(r.unpriced_calls);
+ totals.calls += calls;
+ totals.input_tokens += n(r.input_tokens);
+ totals.output_tokens += n(r.output_tokens);
+ totals.cache_read_tokens += n(r.cache_read_tokens);
+ totals.cache_write_tokens += n(r.cache_write_tokens);
+ totals.cost_usd += n(r.cost_usd);
+ unpricedCalls += rowUnpriced;
+
+ const m = byModel.get(r.model) ?? {
+ model: r.model,
+ calls: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ cost_usd: null as number | null,
+ unpriced_calls: 0,
+ };
+ m.calls += calls;
+ m.input_tokens += n(r.input_tokens);
+ m.output_tokens += n(r.output_tokens);
+ m.cache_read_tokens += n(r.cache_read_tokens);
+ m.cache_write_tokens += n(r.cache_write_tokens);
+ if (r.cost_usd != null) m.cost_usd = (m.cost_usd ?? 0) + n(r.cost_usd);
+ m.unpriced_calls += rowUnpriced;
+ byModel.set(r.model, m);
+
+ const phaseKey = r.phase ?? 'direct';
+ const ph = byPhase.get(phaseKey) ?? { phase: phaseKey, calls: 0, cost_usd: 0 };
+ ph.calls += calls;
+ ph.cost_usd += n(r.cost_usd);
+ byPhase.set(phaseKey, ph);
+ }
+
+ return {
+ window_days: days,
+ totals: { ...totals, cost_usd: Math.round(totals.cost_usd * 1e6) / 1e6 },
+ by_model: [...byModel.values()].sort((a, b) => (b.cost_usd ?? 0) - (a.cost_usd ?? 0)),
+ by_phase: [...byPhase.values()].sort((a, b) => b.cost_usd - a.cost_usd),
+ // Explicit coverage fields (#4218): state what the ledger captures so a
+ // consumer never mistakes a partial ledger for total spend.
+ coverage: {
+ source: 'gateway.chat',
+ /** Earliest ledger row; calls before this (or pre-v136) are invisible. */
+ logged_since: loggedSince,
+ table_present: !tableMissing,
+ priced_calls: totals.calls - unpricedCalls,
+ /** Calls whose model had no CANONICAL_PRICING entry — tokens counted, dollars unknown. */
+ unpriced_calls: unpricedCalls,
+ not_covered: [
+ 'failed chat calls (budget-tracker owns pessimistic in-flight spend)',
+ 'subagent raw-SDK calls',
+ 'embeddings (embedding-pricing.ts unit)',
+ 'calls made before migration v136 / sink registration',
+ ],
+ },
+ };
+ },
+};
+
+export const usageOperations: Operation[] = [get_usage];
diff --git a/src/core/page-summary.ts b/src/core/page-summary.ts
index d0fb325ca5..e9e68aa3f1 100644
--- a/src/core/page-summary.ts
+++ b/src/core/page-summary.ts
@@ -35,11 +35,16 @@ import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.t
import { sanitizeSynopsis } from './embedding-context.ts';
/**
- * Hard cap on synopsis output tokens. ~200 tokens gives 50-100 token
+ * Default cap on synopsis output tokens. ~200 tokens gives 50-100 token
* synopsis with some headroom; the wrapper layer caps the final
* synopsis at SUMMARY_HARD_CAP_CHARS (300) regardless.
+ *
+ * #3883: overridable per call via `GeneratePerChunkSynopsisArgs.maxTokens`,
+ * threaded from the `models.synopsis_max_tokens` config by the service
+ * layer (this module stays DB-free). Exported so the service's config
+ * resolver and tests share the default.
*/
-const SYNOPSIS_MAX_TOKENS = 200;
+export const SYNOPSIS_MAX_TOKENS = 200;
/** Default model when caller doesn't override. Resolves through the gateway. */
export const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';
@@ -112,6 +117,12 @@ export interface GeneratePerChunkSynopsisArgs {
model?: string;
/** Optional abort signal threaded through gateway.chat. */
abortSignal?: AbortSignal;
+ /**
+ * #3883: output-token cap for the synopsis call. Defaults to
+ * SYNOPSIS_MAX_TOKENS (200). The service layer threads the
+ * `models.synopsis_max_tokens` config here.
+ */
+ maxTokens?: number;
}
/**
@@ -144,12 +155,13 @@ export async function generatePerChunkSynopsis(
args: GeneratePerChunkSynopsisArgs,
): Promise<GeneratePerChunkSynopsisResult> {
const userPrompt = buildUserPrompt(args.pageTitle, args.documentText, args.chunkText);
+ const maxTokens = args.maxTokens ?? SYNOPSIS_MAX_TOKENS;
const chatOpts: ChatOpts = {
model: args.model ?? DEFAULT_SYNOPSIS_MODEL,
system: SYSTEM_PROMPT,
messages: [{ role: 'user', content: userPrompt }],
- maxTokens: SYNOPSIS_MAX_TOKENS,
+ maxTokens,
abortSignal: args.abortSignal,
cacheSystem: true,
};
@@ -188,6 +200,24 @@ export async function generatePerChunkSynopsis(
return { kind: 'refusal', detail: `stop_reason=${result.stopReason}` };
}
+ // #3883: stop_reason 'length' means the model hit maxTokens mid-sentence —
+ // the text is a truncated fragment, not a synopsis. Embedding it would bake
+ // the truncation artifact into the vector; classify as malformed so the
+ // service demotes the page to the title-only fall-back (same lane as an
+ // unparseable response), instead of silently embedding truncated text.
+ if (result.stopReason === 'length') {
+ const detail = `stop_reason=length (maxTokens=${maxTokens} exhausted; raise models.synopsis_max_tokens)`;
+ logSynopsisFailure({
+ pageSlug: args.pageSlug,
+ sourceId: args.sourceId,
+ chunkIndex: args.chunkIndex,
+ kind: 'malformed',
+ detail,
+ pageLevelFallback: true,
+ });
+ return { kind: 'malformed', detail };
+ }
+
const synopsis = sanitizeSynopsis(result.text);
if (!synopsis) {
logSynopsisFailure({
@@ -201,10 +231,11 @@ export async function generatePerChunkSynopsis(
return { kind: 'empty', detail: `length=${result.text.length}` };
}
- // No malformed detection in v0.40.3.0: synopses are plain text by
- // prompt contract. Future extension could parse a JSON-shaped
- // response with `{synopsis, confidence}` for richer signals; for now
- // any non-empty text after sanitization counts as success.
+ // Content-shape malformed detection stays minimal: synopses are plain
+ // text by prompt contract, so any non-empty text after sanitization
+ // counts as success (truncation is caught structurally via the
+ // stop_reason==='length' check above, #3883). Future extension could
+ // parse a JSON-shaped response with `{synopsis, confidence}`.
return { kind: 'success', synopsis };
}
diff --git a/src/core/pages-upsert-arbiter.ts b/src/core/pages-upsert-arbiter.ts
new file mode 100644
index 0000000000..5020fe6679
--- /dev/null
+++ b/src/core/pages-upsert-arbiter.ts
@@ -0,0 +1,118 @@
+/**
+ * #550 — pages(source_id, slug) unique-arbiter schema-drift self-heal.
+ *
+ * Every `putPage` upsert (both engines) infers ON CONFLICT (source_id, slug),
+ * which requires a non-partial UNIQUE index covering exactly those columns.
+ * When the `pages_source_slug_key` constraint vanishes (partial restore,
+ * manual DDL, a failed/renumbered migration), EVERY page write brain-wide
+ * fails with "no unique or exclusion constraint matching the ON CONFLICT
+ * specification" — and neither re-running `initSchema` nor the version
+ * counter can see the drift (migrations v21/v23 guarded the ADD by
+ * constraint NAME only, and the version counter is already stamped past
+ * them).
+ *
+ * Mirrors timeline-dedup-repair.ts (#2038): the check keys off the actual
+ * index SHAPE (any non-partial unique index whose column set is exactly
+ * {source_id, slug}, regardless of name) and the repair runs on every
+ * migrate pass. The repair only ever ADDs the constraint — it never deletes
+ * rows. If duplicate (source_id, slug) rows already snuck in through the
+ * unprotected window, it refuses and reports them for manual resolution.
+ */
+
+import type { BrainEngine } from './engine.ts';
+
+const CONSTRAINT_NAME = 'pages_source_slug_key';
+/** Sorted column set the ON CONFLICT (source_id, slug) inference needs. */
+const EXPECTED_COLUMN_SET = ['slug', 'source_id'];
+
+/** Parse the column list out of a pg_indexes `indexdef` string. */
+function parseIndexColumns(indexdef: string): string[] {
+ const open = indexdef.indexOf('(');
+ const close = indexdef.indexOf(')', open);
+ if (open < 0 || close < 0) return [];
+ return indexdef
+ .slice(open + 1, close)
+ .split(',')
+ .map(c => c.trim().split(/\s+/)[0]) // drop any "col DESC"/opclass suffix
+ .filter(Boolean);
+}
+
+/** True when the indexdef is a non-partial unique index on exactly {source_id, slug}. */
+function isArbiterShape(indexdef: string): boolean {
+ if (!/^CREATE UNIQUE INDEX/i.test(indexdef)) return false;
+ if (/\)\s+WHERE\s+/i.test(indexdef)) return false; // partial indexes can't arbitrate
+ const cols = parseIndexColumns(indexdef).sort();
+ return (
+ cols.length === EXPECTED_COLUMN_SET.length &&
+ EXPECTED_COLUMN_SET.every((c, i) => cols[i] === c)
+ );
+}
+
+export interface PagesUpsertArbiterStatus {
+ /** The pages table exists (nothing to check if not). */
+ tablePresent: boolean;
+ /** Some non-partial unique index on exactly (source_id, slug) exists — any name. */
+ arbiterPresent: boolean;
+ /** Missing arbiter: every putPage upsert is failing. */
+ needsRepair: boolean;
+ /** Duplicate (source_id, slug) groups that block adding the constraint. */
+ duplicateGroups: number;
+}
+
+export async function checkPagesUpsertArbiter(engine: BrainEngine): Promise<PagesUpsertArbiterStatus> {
+ const tbl = await engine.executeRaw<{ reg: string | null }>(
+ `SELECT to_regclass('pages')::text AS reg`,
+ );
+ const tablePresent = !!tbl[0]?.reg;
+ if (!tablePresent) {
+ return { tablePresent: false, arbiterPresent: false, needsRepair: false, duplicateGroups: 0 };
+ }
+ const rows = await engine.executeRaw<{ indexdef: string }>(
+ `SELECT indexdef FROM pg_indexes WHERE tablename = 'pages'`,
+ );
+ const arbiterPresent = rows.some(r => isArbiterShape(r.indexdef));
+ let duplicateGroups = 0;
+ if (!arbiterPresent) {
+ const dup = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM (
+ SELECT 1 FROM pages GROUP BY source_id, slug HAVING COUNT(*) > 1
+ ) d`,
+ );
+ duplicateGroups = parseInt(dup[0]?.n ?? '0', 10);
+ }
+ return { tablePresent, arbiterPresent, needsRepair: !arbiterPresent, duplicateGroups };
+}
+
+export interface PagesUpsertArbiterRepairResult {
+ repaired: boolean;
+ duplicateGroups: number;
+ reason: 'already_correct' | 'no_table' | 'duplicates' | 'restored';
+}
+
+/**
+ * Restore the UNIQUE(source_id, slug) arbiter if it's missing. ADD-only:
+ * never deletes rows. When duplicate (source_id, slug) groups exist the
+ * constraint cannot be added — refuse and report so the operator resolves
+ * the duplicates deliberately (each duplicate is a real page row).
+ */
+export async function repairPagesUpsertArbiter(engine: BrainEngine): Promise<PagesUpsertArbiterRepairResult> {
+ const status = await checkPagesUpsertArbiter(engine);
+ if (!status.tablePresent) {
+ return { repaired: false, duplicateGroups: 0, reason: 'no_table' };
+ }
+ if (!status.needsRepair) {
+ return { repaired: false, duplicateGroups: 0, reason: 'already_correct' };
+ }
+ if (status.duplicateGroups > 0) {
+ return { repaired: false, duplicateGroups: status.duplicateGroups, reason: 'duplicates' };
+ }
+ // A misshapen constraint/index may be squatting on the canonical name (the
+ // by-shape probe above already established it is NOT a valid arbiter).
+ // Free the name before re-adding. Constraint-drop also drops its index.
+ await engine.executeRaw(`ALTER TABLE pages DROP CONSTRAINT IF EXISTS ${CONSTRAINT_NAME}`);
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${CONSTRAINT_NAME}`);
+ await engine.executeRaw(
+ `ALTER TABLE pages ADD CONSTRAINT ${CONSTRAINT_NAME} UNIQUE (source_id, slug)`,
+ );
+ return { repaired: true, duplicateGroups: 0, reason: 'restored' };
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4cbf6a80bb..1b079fd708 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -93,6 +93,7 @@ import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';
+import { privatePagesFilterFragment } from './search/private-visibility.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
@@ -2010,6 +2011,10 @@ export class PGLiteEngine implements BrainEngine {
if (filters?.includeDeleted !== true) {
where.push('p.deleted_at IS NULL');
}
+ // #4352: untrusted-caller private-page filter (see PageFilters.excludePrivate).
+ if (filters?.excludePrivate === true) {
+ where.push(privatePagesFilterFragment('p'));
+ }
if (filters?.effective_after) {
params.push(filters.effective_after);
where.push(`p.effective_date >= $${params.length}::timestamptz`);
@@ -2053,16 +2058,21 @@ export class PGLiteEngine implements BrainEngine {
return new Set((rows as { slug: string }[]).map(r => r.slug));
}
- async listAllPageRefs(): Promise<Array<{ slug: string; source_id: string }>> {
+ async listAllPageRefs(): Promise<Array<{ slug: string; source_id: string; updated_at: Date }>> {
// v0.32.8: see postgres-engine.ts:listAllPageRefs for context. ORDER BY
// (source_id, slug) for determinism; WHERE deleted_at IS NULL matches
- // default page visibility.
+ // default page visibility. #4304: updated_at projected so --since walks
+ // can filter refs before any full-page fetch.
const { rows } = await this.db.query(
- `SELECT slug, source_id FROM pages
+ `SELECT slug, source_id, updated_at FROM pages
WHERE deleted_at IS NULL
ORDER BY source_id, slug`
);
- return (rows as { slug: string; source_id: string }[]).map(r => ({ slug: r.slug, source_id: r.source_id }));
+ return (rows as { slug: string; source_id: string; updated_at: string | Date }[]).map(r => ({
+ slug: r.slug,
+ source_id: r.source_id,
+ updated_at: r.updated_at instanceof Date ? r.updated_at : new Date(r.updated_at),
+ }));
}
async listAllSources(opts?: {
@@ -2328,7 +2338,7 @@ export class PGLiteEngine implements BrainEngine {
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
// v0.26.5: visibility filter (soft-deleted + archived-source).
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// v0.32.7: CJK query branch. PGLite uses websearch_to_tsquery('english')
// which can't tokenize CJK; queries return empty. Switch to ILIKE on
@@ -2464,7 +2474,7 @@ export class PGLiteEngine implements BrainEngine {
const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
@@ -2571,8 +2581,9 @@ export class PGLiteEngine implements BrainEngine {
* - Symmetric: no asymmetric whitespace strip on chunk_text.
* - Empty-query guard returns no results without binding SQL.
*
- * Postgres engine is intentionally untouched (multi-tenant deployments
- * can install pgroonga / zhparser when needed; out of scope here).
+ * #3986: the Postgres engine carries the same fallback (shared SQL
+ * builder in src/core/search/cjk-keyword-sql.ts), pinned by the
+ * DATABASE_URL-gated engine-parity e2e.
*/
private async _searchKeywordCJK(
query: string,
@@ -2618,7 +2629,7 @@ export class PGLiteEngine implements BrainEngine {
const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// v0.32.7: CJK branch (same as searchKeyword but without page-dedup).
if (hasCJK(query)) {
@@ -2777,7 +2788,7 @@ export class PGLiteEngine implements BrainEngine {
// v0.26.5: visibility filter applied in the inner CTE so HNSW sees the
// same candidate count it always did. See postgres-engine.ts for rationale.
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// v0.36 (D11): column routing via resolved descriptor. Engine doesn't
// read config — caller resolved at hybrid/op boundary. The cast SQL
@@ -3606,19 +3617,24 @@ export class PGLiteEngine implements BrainEngine {
return (rows as Record<string, unknown>[]).map(rowToStalePage);
}
- async markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<void> {
- if (refs.length === 0) return;
+ async markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<number> {
+ if (refs.length === 0) return 0;
const slugs = refs.map(r => r.slug);
const srcs = refs.map(r => r.source_id);
// Per-ref timestamp (D4 race fix): extract --stale passes each row's read
// updated_at; sites that omit it fall back to defaultExtractedAt.
const tss = refs.map(r => r.extractedAt ?? defaultExtractedAt);
- await this.db.query(
+ // #3957: RETURNING 1 makes the stamped-row count observable so callers
+ // (stampExtracted) can surface a wrong-source shortfall instead of
+ // claiming success while every ref missed.
+ const { rows } = await this.db.query(
`UPDATE pages p SET links_extracted_at = v.ts::timestamptz
FROM unnest($1::text[], $2::text[], $3::text[]) AS v(slug, source_id, ts)
- WHERE p.slug = v.slug AND p.source_id = v.source_id`,
+ WHERE p.slug = v.slug AND p.source_id = v.source_id
+ RETURNING 1`,
[slugs, srcs, tss],
);
+ return rows.length;
}
// Links
@@ -3699,6 +3715,54 @@ export class PGLiteEngine implements BrainEngine {
return result.length;
}
+ // #3674 — see BrainEngine.removeLinksByPagesAndSource JSDoc. Identical SQL
+ // shape in PostgresEngine (parity). JSONB recordset binding (never
+ // JSON.stringify into ::jsonb — executeRawJsonb passes raw objects).
+ async removeLinksByPagesAndSource(
+ pages: Array<{ slug: string; source_id: string }>,
+ opts: {
+ linkSource: string;
+ keepTypedNerPairs?: Array<{
+ from_slug: string; from_source_id: string;
+ to_slug: string; to_source_id: string;
+ }>;
+ },
+ ): Promise<number> {
+ if (pages.length === 0) return 0;
+ const payload = { pages, keep: opts.keepTypedNerPairs ?? [] };
+ const rows = await executeRawJsonb(
+ this,
+ `WITH scope AS (
+ SELECT f.id AS from_id
+ FROM jsonb_to_recordset(($2::jsonb)->'pages') AS p(slug text, source_id text)
+ JOIN pages f ON f.slug = p.slug AND f.source_id = p.source_id
+ ),
+ keep AS (
+ SELECT f.id AS from_id, t.id AS to_id
+ FROM jsonb_to_recordset(($2::jsonb)->'keep') AS k(
+ from_slug text, from_source_id text, to_slug text, to_source_id text
+ )
+ JOIN pages f ON f.slug = k.from_slug AND f.source_id = k.from_source_id
+ JOIN pages t ON t.slug = k.to_slug AND t.source_id = k.to_source_id
+ )
+ DELETE FROM links l
+ USING scope s
+ WHERE l.from_page_id = s.from_id
+ AND l.link_source = $1
+ AND NOT (
+ COALESCE(l.link_kind, '') = 'typed_ner'
+ AND EXISTS (
+ SELECT 1 FROM keep k
+ WHERE k.from_id = l.from_page_id AND k.to_id = l.to_page_id
+ )
+ )
+ RETURNING 1`,
+ [opts.linkSource],
+ [payload],
+ );
+ return rows.length;
+ }
+
async removeLink(
from: string,
to: string,
@@ -3761,7 +3825,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($2::text[])
- WHERE f.slug = $1 AND f.source_id = ANY($2::text[]) AND t.source_id = ANY($2::text[])`,
+ WHERE f.slug = $1 AND f.source_id = ANY($2::text[]) AND t.source_id = ANY($2::text[])
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug, opts.sourceIds]
);
return rows as unknown as Link[];
@@ -3770,6 +3835,9 @@ export class PGLiteEngine implements BrainEngine {
// below preserve pre-v0.31.8 semantics. Without opts.sourceId, no source filter
// (cross-source view for back-link validators and reconcileLinks). With
// opts.sourceId, scope to that source (D20).
+ // #3754: all three arms filter soft-deleted endpoints (f/t deleted_at IS NULL)
+ // so links to/from soft-deleted pages stop voting in the graph, matching
+ // orphans/get/list/search visibility.
if (opts?.sourceId) {
const { rows } = await this.db.query(
`SELECT f.slug as from_slug, f.source_id as from_source_id,
@@ -3781,7 +3849,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
- WHERE f.slug = $1 AND f.source_id = $2`,
+ WHERE f.slug = $1 AND f.source_id = $2
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug, opts.sourceId]
);
return rows as unknown as Link[];
@@ -3796,7 +3865,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
- WHERE f.slug = $1`,
+ WHERE f.slug = $1
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug]
);
return rows as unknown as Link[];
@@ -3817,12 +3887,14 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($2::text[])
- WHERE t.slug = $1 AND t.source_id = ANY($2::text[]) AND f.source_id = ANY($2::text[])`,
+ WHERE t.slug = $1 AND t.source_id = ANY($2::text[]) AND f.source_id = ANY($2::text[])
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug, opts.sourceIds]
);
return rows as unknown as Link[];
}
- // v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks.
+ // v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks
+ // (incl. the #3754 soft-delete endpoint filter on all three arms).
if (opts?.sourceId) {
const { rows } = await this.db.query(
`SELECT f.slug as from_slug, f.source_id as from_source_id,
@@ -3834,7 +3906,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
- WHERE t.slug = $1 AND t.source_id = $2`,
+ WHERE t.slug = $1 AND t.source_id = $2
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug, opts.sourceId]
);
return rows as unknown as Link[];
@@ -3849,7 +3922,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages f ON f.id = l.from_page_id
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
- WHERE t.slug = $1`,
+ WHERE t.slug = $1
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,
[slug]
);
return rows as unknown as Link[];
@@ -4056,12 +4130,15 @@ export class PGLiteEngine implements BrainEngine {
ptScope = `AND pt.source_id = $${idx}`;
}
+ // #3754: soft-deleted pages are excluded at seed, every recursive step, and
+ // the final SELECT joins — a deleted page neither anchors, relays, nor
+ // terminates a path (mirrors postgres-engine.traversePaths).
let sql: string;
if (direction === 'out') {
sql = `
WITH RECURSIVE walk AS (
SELECT p.id, p.slug, 0::int 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
SELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -4069,6 +4146,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages p2 ON p2.id = l.to_page_id
WHERE w.depth < $2
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
${linkTypeWhere}
${stepScope}
)
@@ -4078,6 +4156,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN links l ON l.from_page_id = w.id
JOIN pages p2 ON p2.id = l.to_page_id
WHERE w.depth < $2
+ AND p2.deleted_at IS NULL
${linkTypeWhere}
${stepScope}
ORDER BY depth, from_slug, to_slug
@@ -4086,7 +4165,7 @@ export class PGLiteEngine implements BrainEngine {
sql = `
WITH RECURSIVE walk AS (
SELECT p.id, p.slug, 0::int 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
SELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -4094,6 +4173,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages p2 ON p2.id = l.from_page_id
WHERE w.depth < $2
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
${linkTypeWhere}
${stepScope}
)
@@ -4103,6 +4183,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN links l ON l.to_page_id = w.id
JOIN pages p2 ON p2.id = l.from_page_id
WHERE w.depth < $2
+ AND p2.deleted_at IS NULL
${linkTypeWhere}
${stepScope}
ORDER BY depth, from_slug, to_slug
@@ -4113,7 +4194,7 @@ export class PGLiteEngine implements BrainEngine {
sql = `
WITH RECURSIVE walk AS (
SELECT p.id, 0::int 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
SELECT p2.id, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -4121,6 +4202,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END
WHERE w.depth < $2
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
${linkTypeWhere}
${stepScope}
)
@@ -4131,6 +4213,8 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages pf ON pf.id = l.from_page_id
JOIN pages pt ON pt.id = l.to_page_id
WHERE w.depth < $2
+ AND pf.deleted_at IS NULL
+ AND pt.deleted_at IS NULL
${linkTypeWhere}
${pfScope}
${ptScope}
@@ -4338,18 +4422,30 @@ export class PGLiteEngine implements BrainEngine {
return result;
}
- async getUnverifiedExtractionPageIds(pageIds: number[]): Promise<Set<number>> {
- if (pageIds.length === 0) return new Set();
- // Parity with PostgresEngine.getUnverifiedExtractionPageIds (issue #160).
- // Predicate is the shared unverifiedExtractionFragment so this query and
- // the SQL-side source-boost guard can never drift.
+ async getUnverifiedExtractionPageIds(
+ pageIds: number[],
+ ): Promise<Map<number, { unverified: boolean; status: string }>> {
+ const result = new Map<number, { unverified: boolean; status: string }>();
+ if (pageIds.length === 0) return result;
+ // Parity with PostgresEngine.getUnverifiedExtractionPageIds (issue #160,
+ // widened for #4220). Quarantine predicate is the shared
+ // unverifiedExtractionFragment so this query and the SQL-side
+ // source-boost guard can never drift; any page with a frontmatter
+ // `status` value is returned so draft/superseded/restricted surface on
+ // SearchResult.status.
const { rows } = await this.db.query(
- `SELECT id FROM pages
+ `SELECT id,
+ (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') AS status,
+ (${unverifiedExtractionFragment('pages')}) AS unverified
+ FROM pages
WHERE id = ANY($1::int[])
- AND ${unverifiedExtractionFragment('pages')}`,
+ AND (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') IS NOT NULL`,
[pageIds]
);
- return new Set((rows as { id: number }[]).map((r) => Number(r.id)));
+ for (const r of rows as { id: number; status: string; unverified: boolean }[]) {
+ result.set(Number(r.id), { unverified: r.unverified === true, status: r.status });
+ }
+ return result;
}
async getPageTimestamps(slugs: string[]): Promise<Map<string, Date>> {
@@ -4512,7 +4608,8 @@ export class PGLiteEngine implements BrainEngine {
throw new Error(`addTimelineEntry failed: page "${slug}" (source=${sourceId}) not found`);
}
}
- // ON CONFLICT DO NOTHING via the (page_id, date, summary) unique index.
+ // ON CONFLICT DO NOTHING via the (page_id, date, md5(summary), source)
+ // unique index (#3737: md5-keyed so long summaries fit the btree row cap).
// #3827: RETURNING 1 makes the outcome observable (true = inserted,
// false = deduplicated or JOIN-dropped under skipExistenceCheck),
// mirroring the Postgres engine. Source-qualify the page-id lookup so
@@ -4524,7 +4621,7 @@ export class PGLiteEngine implements BrainEngine {
`INSERT INTO timeline_entries (page_id, date, source, summary, detail)
SELECT id, $2::date, $3, $4, $5
FROM pages WHERE slug = $1 AND source_id = $6
- ON CONFLICT (page_id, date, summary, source) DO NOTHING
+ ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING
RETURNING 1`,
[slug, entry.date, sanitizeForJsonb(entry.source || ''), sanitizeForJsonb(entry.summary), sanitizeForJsonb(entry.detail || ''), sourceId]
);
@@ -4548,8 +4645,8 @@ export class PGLiteEngine implements BrainEngine {
SELECT p.id, v.date::date, v.source, v.summary, v.detail
FROM jsonb_to_recordset(($1::jsonb)->'rows')
AS v(slug text, date text, source text, summary text, detail text, source_id text)
- JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id
- ON CONFLICT (page_id, date, summary, source) DO NOTHING
+ JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL
+ ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING
RETURNING 1`,
[],
[{ rows }],
@@ -5076,10 +5173,11 @@ export class PGLiteEngine implements BrainEngine {
}
async insertFacts(
- rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
ctx: { source_id: string },
- ): Promise<{ inserted: number; ids: number[] }> {
- return factsImpl.insertFacts(this.factsDeps, rows, ctx);
+ opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean } },
+ ): Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number }> {
+ return factsImpl.insertFacts(this.factsDeps, rows, ctx, opts);
}
async deleteFactsForPage(
diff --git a/src/core/pglite-engine/cjk-search.ts b/src/core/pglite-engine/cjk-search.ts
index 006f5de633..ac4558a104 100644
--- a/src/core/pglite-engine/cjk-search.ts
+++ b/src/core/pglite-engine/cjk-search.ts
@@ -2,12 +2,17 @@
* v0.32.7: CJK keyword fallback search, peeled out of PGLiteEngine
* (containment sprint C15). Free functions over a NARROW deps surface — the
* live PGLite handle only. Never the whole engine class.
+ *
+ * #3986: the SQL itself now builds in the shared
+ * `src/core/search/cjk-keyword-sql.ts` so the Postgres engine's port
+ * (`src/core/postgres-engine/cjk-search.ts`) cannot drift from this one.
+ * This module keeps its original export surface and only supplies the
+ * PGLite executor.
*/
import type { PGlite } from '@electric-sql/pglite';
-import type { SearchOpts, SearchResult } from '../types.ts';
+import type { SearchResult } from '../types.ts';
import { rowToSearchResult } from '../utils.ts';
-import { buildBestPerPagePoolCte } from '../search/sql-ranking.ts';
-import { escapeLikePattern, splitCJKQueryTerms } from '../cjk.ts';
+import { buildCJKKeywordSql, type CjkKeywordCtx } from '../search/cjk-keyword-sql.ts';
/** Narrow slice of PGLiteEngine the CJK search operations use. */
export interface PgliteCjkSearchDeps {
@@ -19,165 +24,10 @@ export interface PgliteCjkSearchDeps {
export async function searchKeywordCJK(
deps: PgliteCjkSearchDeps,
query: string,
- ctx: {
- limit: number;
- offset: number;
- innerLimit: number;
- sourceFactorCase: string;
- hardExcludeClause: string;
- visibilityClause: string;
- detailFilter: string;
- opts: SearchOpts | undefined;
- dedup: boolean;
- },
+ ctx: CjkKeywordCtx,
): Promise<SearchResult[]> {
- const { limit, offset, innerLimit, sourceFactorCase, hardExcludeClause, visibilityClause, detailFilter, opts, dedup } = ctx;
- const qRaw = query;
- if (qRaw.length === 0) return [];
- const terms = splitCJKQueryTerms(qRaw);
- if (terms.length === 0) return [];
-
- const params: unknown[] = [];
-
- // LIKE parameters: $1 .. $N (each escaped and wrapped with %)
- const likeParamIndices: number[] = [];
- for (const term of terms) {
- params.push(`%${escapeLikePattern(term)}%`);
- likeParamIndices.push(params.length);
- }
-
- // Raw term parameters for term-frequency scoring: $N+1 .. $2N
- const rawTermIndices: number[] = [];
- for (const term of terms) {
- params.push(term);
- rawTermIndices.push(params.length);
- }
-
- // Raw full query parameter for contiguous match bonus and tiebreaker: $2N+1
- params.push(qRaw);
- const qRawIndex = params.length;
-
- // Pagination limits & offset
- let innerLimitIndex = 0;
- let limitIndex = 0;
- let offsetIndex = 0;
-
- if (dedup) {
- params.push(innerLimit);
- innerLimitIndex = params.length;
- params.push(limit);
- limitIndex = params.length;
- params.push(offset);
- offsetIndex = params.length;
- } else {
- params.push(limit);
- limitIndex = params.length;
- params.push(offset);
- offsetIndex = params.length;
- }
-
- let extraFilter = '';
- if (opts?.language) {
- params.push(opts.language);
- extraFilter += ` AND cc.language = $${params.length}`;
- }
- if (opts?.symbolKind) {
- params.push(opts.symbolKind);
- extraFilter += ` AND cc.symbol_type = $${params.length}`;
- }
- if (opts?.afterDate) {
- params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
- }
- if (opts?.beforeDate) {
- params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
- }
- // v0.34.1 (#861 — P0 leak seal): source-isolation on the CJK fallback path.
- if (opts?.sourceIds && opts.sourceIds.length > 0) {
- params.push(opts.sourceIds);
- extraFilter += ` AND p.source_id = ANY($${params.length}::text[])`;
- } else if (opts?.sourceId) {
- params.push(opts.sourceId);
- extraFilter += ` AND p.source_id = $${params.length}`;
- }
-
- const whereLikeClause = likeParamIndices
- .map(idx => `cc.chunk_text ILIKE $${idx} ESCAPE '\\'`)
- .join(' AND ');
-
- const termFreqExpr = rawTermIndices
- .map(idx => `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${idx}, ''))) / NULLIF(LENGTH($${idx}), 0)::real)`)
- .join(' + ');
-
- const qRawBonusExpr = terms.length > 1
- ? ` + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${qRawIndex}, ''))) / NULLIF(LENGTH($${qRawIndex}), 0)::real)`
- : '';
-
- const positionExpr = `COALESCE(1.0 / NULLIF(POSITION($${qRawIndex} IN cc.chunk_text), 0)::real, 0.0)`;
-
- // Term-frequency count: count occurrences of each term in chunk_text via
- // (length(chunk) - length(replace(chunk, term, ''))) / length(term),
- // plus bonus for contiguous raw query occurrences when multi-term, and
- // position()-tiebreaker so earlier-in-chunk hits outrank later ones.
- const scoreExpr = `
- ((${termFreqExpr}${qRawBonusExpr}
- + ${positionExpr})
- * ${sourceFactorCase})
- `;
-
- if (dedup) {
- const { rows } = await deps.db.query(
- `WITH ranked AS (
- SELECT
- p.slug, p.id as page_id, p.title, p.type, p.source_id,
- p.effective_date, p.effective_date_source,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- ${scoreExpr} AS score,
- CASE WHEN p.updated_at < (
- SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
- ) THEN true ELSE false END AS stale
- FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- JOIN sources s ON s.id = p.source_id
- WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
- AND cc.modality = 'text'
- ORDER BY score DESC
- LIMIT $${innerLimitIndex}
- ),
- ${buildBestPerPagePoolCte('ranked')}
- SELECT * FROM best_per_page
- ORDER BY score DESC, page_id ASC, chunk_id ASC
- LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
- params,
- );
- return (rows as Record<string, unknown>[]).map(rowToSearchResult);
- } else {
- const { rows } = await deps.db.query(
- `SELECT
- p.slug, p.id as page_id, p.title, p.type, p.source_id,
- p.effective_date, p.effective_date_source,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- ${scoreExpr} AS score,
- CASE WHEN p.updated_at < (
- SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
- ) THEN true ELSE false END AS stale
- FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- JOIN sources s ON s.id = p.source_id
- WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
- ORDER BY score DESC
- LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
- params,
- );
- return (rows as Record<string, unknown>[]).map(rowToSearchResult);
- }
+ const built = buildCJKKeywordSql(query, ctx);
+ if (!built) return [];
+ const { rows } = await deps.db.query(built.sql, built.params);
+ return (rows as Record<string, unknown>[]).map(rowToSearchResult);
}
diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts
index 2a6bdf7c6d..16843de0d6 100644
--- a/src/core/pglite-engine/facts.ts
+++ b/src/core/pglite-engine/facts.ts
@@ -10,6 +10,7 @@ import type {
} from '../engine.ts';
import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
+import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts';
/** Narrow slice of PGLiteEngine the facts operations use. */
export interface PgliteFactsDeps {
@@ -123,21 +124,64 @@ export async function expireFact(deps: PgliteFactsDeps, id: number, opts?: { sup
export async function insertFacts(
deps: PgliteFactsDeps,
- rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
ctx: { source_id: string },
- ): Promise<{ inserted: number; ids: number[] }> {
- if (rows.length === 0) return { inserted: 0, ids: [] };
+ opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean } },
+ ): Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number }> {
+ if (rows.length === 0) return { inserted: 0, ids: [], warnings: [], deleted: 0 };
+ const warnings: string[] = [];
+ // v0.46 (#3014): captured inside the transaction below when
+ // deleteForPageFirst runs; stays 0 for the standalone insert path.
+ let deleted = 0;
// Single transaction so the v51 partial UNIQUE index can roll back the
// whole batch on constraint violation. Per-row INSERTs (not multi-row
// VALUES) keep the embedding-vs-no-embedding branching readable; batch
// sizes are small (5-30 rows per page in practice) so the loop overhead
// is negligible vs the embedding compute cost.
+ // v0.46 (#3014): the fence path carries struck rows — `expired_at` is
+ // stamped inline, and `superseded by #N` references are resolved to
+ // `facts.superseded_by` in a second pass below (same transaction).
const ids = await deps.db.transaction(async (tx) => {
+ // v0.46 (#3014) — atomic reconcile: wipe the page's fence-owned rows
+ // as the FIRST statement of this transaction so a failing insert
+ // below rolls the delete back too. Inlined (not a deleteFactsForPage
+ // call) so it shares this transaction. Delete scoping mirrors
+ // deleteFactsForPage exactly (#1928 excludeSourcePrefixes + #2646
+ // preserveExpiredLegacy).
+ const del = opts?.deleteForPageFirst;
+ if (del) {
+ const expiredLegacyFilter = del.preserveExpiredLegacy
+ ? ` AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
+ : '';
+ const prefixes = del.excludeSourcePrefixes;
+ if (prefixes && prefixes.length > 0) {
+ const patterns = prefixes.map(p => `${p}%`);
+ const r = await tx.query(
+ `DELETE FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2
+ AND NOT (COALESCE(source, '') LIKE ANY($3::text[]))${expiredLegacyFilter}`,
+ [ctx.source_id, del.slug, patterns],
+ );
+ deleted = r.affectedRows ?? 0;
+ } else {
+ const r = await tx.query(
+ `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2${expiredLegacyFilter}`,
+ [ctx.source_id, del.slug],
+ );
+ deleted = r.affectedRows ?? 0;
+ }
+ }
const out: number[] = [];
+ // Per-input inserted id, aligned to `rows` (null when the v51
+ // ON CONFLICT DO NOTHING skipped the row) — the second pass below
+ // must not index `out` positionally, or a skipped row would shift
+ // every later UPDATE onto the wrong fact.
+ const rowIds: Array<number | null> = [];
for (const input of rows) {
const validFrom = input.valid_from ?? new Date();
const validUntil = input.valid_until ?? null;
+ const expiredAt = input.expired_at ?? null;
const kind = input.kind ?? 'fact';
const visibility = input.visibility ?? 'private';
const notability = input.notability ?? 'medium';
@@ -158,23 +202,23 @@ export async function insertFacts(
// Param-positional dispatch: embedStr presence shifts the trailing
// slots by one. Order of named slots stays stable across both
- // branches: embedded_at, row_num, source_markdown_slug,
+ // branches: expired_at, embedded_at, row_num, source_markdown_slug,
// claim_metric, claim_value, claim_unit, claim_period, event_type.
const ins = await tx.query<{ id: number }>(
embedStr === null
? `INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
+ valid_from, valid_until, expired_at, source, source_session, confidence,
embedding, embedded_at,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
event_type
) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- NULL, $13,
- $14, $15,
- $16, $17, $18, $19,
- $20
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,
+ NULL, $14,
+ $15, $16,
+ $17, $18, $19, $20,
+ $21
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
@@ -182,31 +226,67 @@ export async function insertFacts(
RETURNING id`
: `INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
+ valid_from, valid_until, expired_at, source, source_session, confidence,
embedding, embedded_at,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
event_type
) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- $13::vector, $14,
- $15, $16,
- $17, $18, $19, $20,
- $21
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,
+ $14::vector, $15,
+ $16, $17,
+ $18, $19, $20, $21,
+ $22
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
DO NOTHING
RETURNING id`,
embedStr === null
- ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
+ ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, expiredAt, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, expiredAt, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
);
if (ins.rows[0]) out.push(ins.rows[0].id);
+ rowIds.push(ins.rows[0] ? Number(ins.rows[0].id) : null);
+ }
+
+ // v0.46 (#3014) — second pass: resolve `superseded by #N` page-local
+ // references to fact ids. Same transaction so a target row inserted
+ // above is visible. Keyed on (source_id, source_markdown_slug,
+ // row_num) — the v51 unique index — so a reference also resolves
+ // against a target that already existed before this batch. A target
+ // whose `expired_at` is set is itself struck (chain) and rejected.
+ for (let i = 0; i < rows.length; i++) {
+ const targetRow = rows[i].superseded_by_row;
+ if (targetRow === undefined || rowIds[i] === null) continue;
+ const slug = rows[i].source_markdown_slug;
+ // Only look up an int4-safe target. An absurd `#N` (11+ digits)
+ // would overflow the `row_num` comparison and abort the cycle;
+ // skipping the lookup leaves `target` undefined, so
+ // resolveSupersededByRow treats it as a dangling reference (NULL +
+ // warning) instead of throwing.
+ let target: SupersedeTarget | undefined;
+ if (isInt4RowRef(targetRow)) {
+ const found = await tx.query<{ id: number; expired_at: Date | string | null }>(
+ `SELECT id, expired_at FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num = $3
+ LIMIT 1`,
+ [ctx.source_id, slug, targetRow],
+ );
+ const hit = found.rows[0];
+ target = hit
+ ? { id: Number(hit.id), struck: hit.expired_at != null }
+ : undefined;
+ }
+ const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug);
+ if (warning) warnings.push(warning);
+ if (superseded_by !== null) {
+ await tx.query(`UPDATE facts SET superseded_by = $1 WHERE id = $2`, [superseded_by, rowIds[i]]);
+ }
}
return out;
});
- return { inserted: ids.length, ids };
+ return { inserted: ids.length, ids, warnings, deleted };
}
export async function deleteFactsForPage(
@@ -312,10 +392,16 @@ export async function listSupersessions(
source_id: string,
opts?: { since?: Date; limit?: number; visibility?: ('private' | 'world')[] },
): Promise<FactRow[]> {
- const where: string[] = [`expired_at IS NOT NULL`, `superseded_by IS NOT NULL`];
+ // v0.46 (#3014) — filter on `superseded_by` alone; the ontology
+ // writer closes a superseded row via `valid_until` (not `expired_at`,
+ // which would break its `--asof` time-travel), so requiring both
+ // columns dropped every ontology supersession AND every fence-authored
+ // one. Order / `since` fall back to `valid_until` when `expired_at` is
+ // NULL.
+ const where: string[] = [`superseded_by IS NOT NULL`];
const params: Record<string, unknown> = {};
if (opts?.since) {
- where.push(`expired_at >= $since`);
+ where.push(`COALESCE(expired_at, valid_until) >= $since`);
params.since = opts.since;
}
return _listFacts(deps, source_id, {
@@ -324,7 +410,7 @@ export async function listSupersessions(
visibility: opts?.visibility,
whereClauses: where,
whereParams: params,
- order: 'expired_at DESC, id DESC',
+ order: 'COALESCE(expired_at, valid_until) DESC, id DESC',
});
}
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index e643e6f1d1..00b926d08d 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -386,7 +386,8 @@ CREATE INDEX IF NOT EXISTS idx_timeline_date ON timeline_entries(date);
-- Dedup constraint: same (page, date, summary) treated as same event
-- v0.41.18.0 (codex finding #11): widened to include source so distinct
-- meeting provenance survives. Legacy rows have source='' (schema default).
-CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, summary, source);
+-- #3737: keyed on md5(summary) — raw long summaries overflowed the btree cap.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, md5(summary), source);
-- v0.42.x (Life Chronicle): event-projection lookup + dedup (partial).
CREATE INDEX IF NOT EXISTS idx_timeline_event_page ON timeline_entries(event_page_id) WHERE event_page_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_event_dedup ON timeline_entries(event_page_id, date) WHERE event_page_id IS NOT NULL;
@@ -1034,6 +1035,24 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- chat_usage_log (#4218 / migration v140). See src/schema.sql for rationale.
+CREATE TABLE IF NOT EXISTS chat_usage_log (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ model TEXT NOT NULL,
+ provider TEXT,
+ phase TEXT,
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
+ cost_usd DOUBLE PRECISION
+);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_created
+ ON chat_usage_log (created_at);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_model
+ ON chat_usage_log (model, created_at);
+
-- ============================================================
-- migration_impact_log (v0.41.18.0 — gbrain onboard wave)
-- ============================================================
diff --git a/src/core/pid1-reaper.ts b/src/core/pid1-reaper.ts
new file mode 100644
index 0000000000..151c307164
--- /dev/null
+++ b/src/core/pid1-reaper.ts
@@ -0,0 +1,185 @@
+/**
+ * PID-1 orphan zombie reaper (#2443).
+ *
+ * `gbrain serve` in a container frequently runs as PID 1 (image without
+ * tini / `docker run --init`). PID 1 inherits every orphaned process in the
+ * PID namespace: when a spawned worker's own child outlives it, the
+ * grandchild re-parents to PID 1 and, on exit, becomes a zombie that the Bun
+ * runtime will NEVER reap — the SIGCHLD handler in zombie-reap.ts only makes
+ * the runtime waitpid() children Bun itself spawned and tracks. Orphan
+ * zombies then accumulate in the PID table for the container's lifetime.
+ *
+ * Strategy: an unref'd interval (default 30s) scans `/proc/<pid>/stat` for
+ * state 'Z' with ppid == self. A zombie must persist across TWO consecutive
+ * scans before it is reaped — this never steals a Bun-tracked child's exit
+ * (the runtime reaps its own within milliseconds of SIGCHLD, so a tracked
+ * exit can't survive a 30s window). Confirmed zombies are reaped with
+ * `waitpid(pid, NULL, WNOHANG)` through bun:ffi libc. Every step is
+ * fail-open: a reaper bug must never take down the serve process, and a
+ * failed dlopen simply disables reaping (the pre-fix behavior).
+ *
+ * Gates: linux + pid == 1 + `GBRAIN_PID1_REAP` not '0'/'false'. The real fix
+ * remains a proper init (tini / `docker run --init`) — see
+ * docs/mcp/DEPLOY.md — this is the in-process fallback for images without one.
+ *
+ * Tested in test/pid1-reaper.test.ts (fixture procDir + injected waitpid).
+ */
+
+import { readdirSync, readFileSync } from 'fs';
+import { join } from 'path';
+
+const WNOHANG = 1;
+
+/** Injectable deps so tests never need a real /proc or libc. */
+export interface Pid1ReaperDeps {
+ /** proc filesystem root (default '/proc'). */
+ procDir?: string;
+ /** the reaper's own pid (default process.pid). */
+ selfPid?: number;
+ /** platform gate override (default process.platform). */
+ platform?: NodeJS.Platform;
+ /** reap syscall (default libc waitpid via bun:ffi, WNOHANG). */
+ waitpid?: (pid: number) => void;
+ /** scan cadence in ms (default 30_000). */
+ intervalMs?: number;
+}
+
+/**
+ * Scan `procDir` for zombie children of `selfPid`. Reads each numeric
+ * entry's `stat` file: `<pid> (<comm>) <state> <ppid> …` — comm may contain
+ * spaces/parens, so fields are taken after the LAST ')'. Fail-open per
+ * entry (processes exit between readdir and read).
+ */
+export function scanZombieChildren(procDir: string, selfPid: number): number[] {
+ const out: number[] = [];
+ let names: string[];
+ try {
+ names = readdirSync(procDir);
+ } catch {
+ return out;
+ }
+ for (const name of names) {
+ if (!/^\d+$/.test(name)) continue;
+ const pid = Number(name);
+ if (pid === selfPid) continue;
+ try {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name is a readdir entry gated by /^\d+$/ two lines up (single numeric segment, no separators or ..); procDir is a trusted injectable ('/proc' default, test fixture dirs otherwise), never user input
+ const raw = readFileSync(join(procDir, name, 'stat'), 'utf8');
+ const close = raw.lastIndexOf(')');
+ if (close < 0) continue;
+ const fields = raw.slice(close + 1).trim().split(/\s+/);
+ const state = fields[0];
+ const ppid = Number(fields[1]);
+ if (state === 'Z' && ppid === selfPid) out.push(pid);
+ } catch {
+ /* raced a process exit — skip */
+ }
+ }
+ return out;
+}
+
+// Lazily-resolved libc waitpid. `undefined` = not attempted, `null` = failed
+// (musl/glibc name miss, sandbox) → reaping disabled, fail-open.
+let libcWaitpid: ((pid: number) => void) | null | undefined;
+
+function defaultWaitpid(pid: number): void {
+ if (libcWaitpid === undefined) {
+ libcWaitpid = null;
+ try {
+ // bun:ffi is always present under Bun; dlopen may still fail (name
+ // varies across glibc/musl) — try the common spellings, fail-open.
+ const { dlopen, FFIType } = require('bun:ffi') as typeof import('bun:ffi');
+ for (const lib of ['libc.so.6', 'libc.so', 'libSystem.B.dylib']) {
+ try {
+ const handle = dlopen(lib, {
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
+ });
+ libcWaitpid = (p: number) => {
+ handle.symbols.waitpid(p, null, WNOHANG);
+ };
+ break;
+ } catch {
+ /* try next name */
+ }
+ }
+ } catch {
+ /* no ffi — reaping disabled */
+ }
+ }
+ try {
+ libcWaitpid?.(pid);
+ } catch {
+ /* fail-open */
+ }
+}
+
+/**
+ * Build one reaper tick with 2-scan persistence: a pid is reaped only when
+ * it was a zombie on the PREVIOUS scan and still is now. Returns the count
+ * reaped (for tests/telemetry). Pure over its injected deps.
+ */
+export function createPid1ReaperTick(deps: {
+ procDir: string;
+ selfPid: number;
+ waitpid: (pid: number) => void;
+}): () => number {
+ let pendingConfirm = new Set<number>();
+ return () => {
+ const zombies = scanZombieChildren(deps.procDir, deps.selfPid);
+ let reaped = 0;
+ const nextPending = new Set<number>();
+ for (const pid of zombies) {
+ if (pendingConfirm.has(pid)) {
+ try {
+ deps.waitpid(pid);
+ } catch {
+ /* fail-open */
+ }
+ reaped++;
+ } else {
+ nextPending.add(pid); // first sighting — confirm next scan
+ }
+ }
+ pendingConfirm = nextPending;
+ return reaped;
+ };
+}
+
+let installedTimer: ReturnType<typeof setInterval> | null = null;
+
+/**
+ * Install the PID-1 orphan reaper. No-op (returns false) unless running as
+ * PID 1 on linux with `GBRAIN_PID1_REAP` not set to '0'/'false'. Idempotent.
+ */
+export function installPid1OrphanReaper(deps: Pid1ReaperDeps = {}): boolean {
+ const off = (process.env.GBRAIN_PID1_REAP ?? '').toLowerCase();
+ if (off === '0' || off === 'false') return false;
+ if ((deps.platform ?? process.platform) !== 'linux') return false;
+ const selfPid = deps.selfPid ?? process.pid;
+ if (selfPid !== 1) return false;
+ if (installedTimer) return true;
+
+ const tick = createPid1ReaperTick({
+ procDir: deps.procDir ?? '/proc',
+ selfPid,
+ waitpid: deps.waitpid ?? defaultWaitpid,
+ });
+ installedTimer = setInterval(() => {
+ try {
+ tick();
+ } catch {
+ /* fail-open — never let the reaper take down serve */
+ }
+ }, deps.intervalMs ?? 30_000);
+ // Never keep the process alive for the reaper.
+ installedTimer.unref?.();
+ return true;
+}
+
+/** Test-only: clear the interval + install latch. */
+export function _uninstallPid1OrphanReaperForTests(): void {
+ if (installedTimer) {
+ clearInterval(installedTimer);
+ installedTimer = null;
+ }
+}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index a3e60bee35..316cc8f6ec 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -41,7 +41,7 @@ import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts';
import { executeRawJsonb, type SqlValue } from './sql-query.ts';
import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
import { runMigrations } from './migrate.ts';
-import { SCHEMA_SQL } from './schema-embedded.ts';
+import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { verifySchema } from './schema-verify.ts';
import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector-index.ts';
import {
@@ -85,6 +85,7 @@ import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';
+import { privatePagesFilterFragment } from './search/private-visibility.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { DELETE_BATCH_SIZE } from './engine-constants.ts';
@@ -93,6 +94,7 @@ import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './o
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 * as factsImpl from './postgres-engine/facts.ts';
import type { PgFactsDeps } from './postgres-engine/facts.ts';
import * as takesImpl from './postgres-engine/takes.ts';
@@ -101,6 +103,9 @@ import * as codeEdgesImpl from './postgres-engine/code-edges.ts';
import type { PgCodeEdgesDeps } from './postgres-engine/code-edges.ts';
import * as salienceImpl from './postgres-engine/salience.ts';
import type { PgSalienceDeps } from './postgres-engine/salience.ts';
+import { hasCJK } from './cjk.ts';
+import { searchKeywordCJK as searchKeywordCJKImpl } from './postgres-engine/cjk-search.ts';
+import type { CjkKeywordCtx } from './search/cjk-keyword-sql.ts';
function escapeSqlStringLiteral(value: string): string {
return value.replace(/'/g, "''");
@@ -453,7 +458,11 @@ export class PostgresEngine implements BrainEngine {
caller: 'PostgresEngine.initSchema',
});
// Lock-census (PR6 D5): INTENTIONALLY brain-global (session lock, fixed key 42) — initSchema DDL mutates the whole database; a per-source key would let two initSchema calls deadlock on shared DDL.
- await conn`SELECT pg_advisory_lock(42)`;
+ // #2898: deadlined pg_try_advisory_lock loop + stderr heartbeat instead of
+ // an unbounded pg_advisory_lock — a leaked pooler session holding key 42
+ // hung every gbrain invocation forever with no output. On timeout the
+ // error names the holder pid with pg_terminate_backend recovery guidance.
+ await acquireInitSchemaAdvisoryLock((q) => conn.unsafe(q));
try {
// Pre-schema bootstrap: add forward-referenced state the embedded schema
// blob requires but that older brains don't have yet (issues #366/#375/
@@ -1612,6 +1621,12 @@ export class PostgresEngine implements BrainEngine {
const deletedCondition = filters?.includeDeleted === true
? sql``
: sql`AND p.deleted_at IS NULL`;
+ // #4352: untrusted-caller private-page filter (see PageFilters.excludePrivate).
+ // Static code-provided fragment (never user input) — same sql.unsafe
+ // pattern as the PAGE_SORT_SQL whitelist below.
+ const privateCondition = filters?.excludePrivate === true
+ ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`)
+ : sql``;
const effectiveAfterCondition = filters?.effective_after
? sql`AND p.effective_date >= ${filters.effective_after}::timestamptz`
: sql``;
@@ -1631,7 +1646,7 @@ export class PostgresEngine implements BrainEngine {
const rows = await tx`
SELECT p.* FROM pages p
${tagJoin}
- WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${sourceCondition} ${deletedCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
+ WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}
`;
return rows.map(rowToPage);
@@ -1651,18 +1666,23 @@ export class PostgresEngine implements BrainEngine {
});
}
- async listAllPageRefs(): Promise<Array<{ slug: string; source_id: string }>> {
+ async listAllPageRefs(): Promise<Array<{ slug: string; source_id: string; updated_at: Date }>> {
// v0.32.8: cross-source page enumeration. ORDER BY (source_id, slug) for
// deterministic iteration (F11) — same-slug-different-source pages stay
// grouped predictably. WHERE deleted_at IS NULL matches default getPage
- // visibility semantics (v0.26.5).
+ // visibility semantics (v0.26.5). #4304: updated_at projected so --since
+ // walks can filter refs before any full-page fetch.
const sql = this.sql;
const rows = await sql`
- SELECT slug, source_id FROM pages
+ SELECT slug, source_id, updated_at FROM pages
WHERE deleted_at IS NULL
ORDER BY source_id, slug
`;
- return rows.map((r) => ({ slug: r.slug as string, source_id: r.source_id as string }));
+ return rows.map((r) => ({
+ slug: r.slug as string,
+ source_id: r.source_id as string,
+ updated_at: r.updated_at instanceof Date ? r.updated_at : new Date(r.updated_at as string),
+ }));
}
async listAllSources(opts?: {
@@ -1972,6 +1992,19 @@ export class PostgresEngine implements BrainEngine {
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
+ // #3986: CJK query branch — engine parity with PGLite's v0.32.7
+ // fallback. websearch_to_tsquery with an ASCII-stemming config can't
+ // tokenize CJK, so the FTS path below returns empty; route to the
+ // shared term-by-term ILIKE fallback instead. ASCII path unchanged.
+ if (hasCJK(query)) {
+ return this._searchKeywordCJK(query, {
+ limit, offset, innerLimit, sourceFactorCase, hardExcludeClause,
+ visibilityClause: buildVisibilityClause('p', 's'),
+ detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
+ opts, dedup: true,
+ });
+ }
+
const params: unknown[] = [query];
let typeClause = '';
if (type) {
@@ -2038,7 +2071,7 @@ export class PostgresEngine implements BrainEngine {
// archived sources. Joined `sources s` lets the predicate compile to a
// column lookup. NOT bypassed by detail=high — soft-delete is a contract,
// not a temporal preference.
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
@@ -2145,7 +2178,7 @@ export class PostgresEngine implements BrainEngine {
const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
@@ -2286,6 +2319,19 @@ export class PostgresEngine implements BrainEngine {
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
+ // #3986: CJK branch — same fallback as searchKeyword but chunk-grain
+ // (no page-dedup). Parity with PGLite searchKeywordChunks.
+ if (hasCJK(query)) {
+ return this._searchKeywordCJK(query, {
+ limit, offset,
+ innerLimit: 0, // unused on chunk-grain (no inner CTE)
+ sourceFactorCase, hardExcludeClause,
+ visibilityClause: buildVisibilityClause('p', 's'),
+ detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
+ opts, dedup: false,
+ });
+ }
+
const params: unknown[] = [query];
let typeClause = '';
if (type) {
@@ -2342,7 +2388,7 @@ export class PostgresEngine implements BrainEngine {
const offsetParam = `$${params.length}`;
// v0.26.5: visibility filter for searchKeywordChunks (anchor primitive).
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
@@ -2388,6 +2434,24 @@ export class PostgresEngine implements BrainEngine {
return rows.map(rowToSearchResult);
}
+ /**
+ * #3986: CJK keyword fallback (parity port of PGLite's v0.32.7 branch).
+ * SQL builds in the shared cjk-keyword-sql.ts; execution goes through the
+ * same scoped read transaction (RLS scope binding + 8s statement timeout)
+ * as the FTS keyword paths. See src/core/postgres-engine/cjk-search.ts.
+ */
+ private async _searchKeywordCJK(query: string, ctx: CjkKeywordCtx): Promise<SearchResult[]> {
+ return searchKeywordCJKImpl(
+ async (sqlText, params) =>
+ await this.withScopedReadTransaction(ctx.opts?.sourceIds, ctx.opts?.sourceId, async (tx) => {
+ await tx`SET LOCAL statement_timeout = '8s'`;
+ return await tx.unsafe(sqlText, params as Parameters<typeof tx.unsafe>[1]) as unknown as Record<string, unknown>[];
+ }, { alwaysTransaction: true }),
+ query,
+ ctx,
+ );
+ }
+
async searchVector(embedding: Float32Array, opts?: SearchOpts): Promise<SearchResult[]> {
const limit = clampSearchLimit(opts?.limit);
const offset = opts?.offset || 0;
@@ -2506,7 +2570,7 @@ export class PostgresEngine implements BrainEngine {
// sees the same row count it always did. Pulling the predicate to the
// outer SELECT would force the HNSW scan to over-fetch and post-filter,
// wasting candidate slots on hidden rows.
- const visibilityClause = buildVisibilityClause('p', 's');
+ const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });
// v0.36 Phase 3: 'embedding_multimodal' is the unified column populated
// by `gbrain reindex --multimodal`. Carries BOTH text and image content
@@ -3409,19 +3473,23 @@ export class PostgresEngine implements BrainEngine {
});
}
- async markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<void> {
- if (refs.length === 0) return;
+ async markPagesExtractedBatch(refs: Array<{ slug: string; source_id: string; extractedAt?: string }>, defaultExtractedAt: string): Promise<number> {
+ if (refs.length === 0) return 0;
const slugs = refs.map(r => r.slug);
const srcs = refs.map(r => r.source_id);
// Per-ref timestamp (D4 race fix): extract --stale passes each row's read
// updated_at; sites that omit it fall back to defaultExtractedAt.
const tss = refs.map(r => r.extractedAt ?? defaultExtractedAt);
const sql = this.sql;
- await sql`
+ // #3957: count() makes the stamped-row count observable so callers
+ // (stampExtracted) can surface a wrong-source shortfall instead of
+ // claiming success while every ref missed. Mirrors the PGLite engine.
+ const result = await sql`
UPDATE pages p SET links_extracted_at = v.ts::timestamptz
FROM unnest(${slugs}::text[], ${srcs}::text[], ${tss}::text[]) AS v(slug, source_id, ts)
WHERE p.slug = v.slug AND p.source_id = v.source_id
`;
+ return result.count ?? 0;
}
// Links
@@ -3508,6 +3576,54 @@ export class PostgresEngine implements BrainEngine {
return result.length;
}
+ // #3674 — see BrainEngine.removeLinksByPagesAndSource JSDoc. Identical SQL
+ // shape in PGLiteEngine (parity). JSONB recordset binding (never
+ // JSON.stringify into ::jsonb — executeRawJsonb passes raw objects).
+ async removeLinksByPagesAndSource(
+ pages: Array<{ slug: string; source_id: string }>,
+ opts: {
+ linkSource: string;
+ keepTypedNerPairs?: Array<{
+ from_slug: string; from_source_id: string;
+ to_slug: string; to_source_id: string;
+ }>;
+ },
+ ): Promise<number> {
+ if (pages.length === 0) return 0;
+ const payload = { pages, keep: opts.keepTypedNerPairs ?? [] };
+ const rows = await executeRawJsonb(
+ this,
+ `WITH scope AS (
+ SELECT f.id AS from_id
+ FROM jsonb_to_recordset(($2::jsonb)->'pages') AS p(slug text, source_id text)
+ JOIN pages f ON f.slug = p.slug AND f.source_id = p.source_id
+ ),
+ keep AS (
+ SELECT f.id AS from_id, t.id AS to_id
+ FROM jsonb_to_recordset(($2::jsonb)->'keep') AS k(
+ from_slug text, from_source_id text, to_slug text, to_source_id text
+ )
+ JOIN pages f ON f.slug = k.from_slug AND f.source_id = k.from_source_id
+ JOIN pages t ON t.slug = k.to_slug AND t.source_id = k.to_source_id
+ )
+ DELETE FROM links l
+ USING scope s
+ WHERE l.from_page_id = s.from_id
+ AND l.link_source = $1
+ AND NOT (
+ COALESCE(l.link_kind, '') = 'typed_ner'
+ AND EXISTS (
+ SELECT 1 FROM keep k
+ WHERE k.from_id = l.from_page_id AND k.to_id = l.to_page_id
+ )
+ )
+ RETURNING 1`,
+ [opts.linkSource],
+ [payload],
+ );
+ return rows.length;
+ }
+
async removeLink(
from: string,
to: string,
@@ -3576,6 +3692,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])
WHERE f.slug = ${slug} AND f.source_id = ANY(${ids}::text[]) AND t.source_id = ANY(${ids}::text[])
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
}
@@ -3583,6 +3700,9 @@ export class PostgresEngine implements BrainEngine {
// two below preserve pre-v0.31.8 semantics. Without opts.sourceId, no
// source filter (cross-source view for internal callers). With
// opts.sourceId, scope the from-page lookup.
+ // #3754: all three arms filter soft-deleted endpoints (f/t deleted_at IS
+ // NULL) so links to/from soft-deleted pages stop voting in the graph,
+ // matching orphans/get/list/search visibility.
if (opts?.sourceId) {
const rows = await tx`
SELECT f.slug as from_slug, f.source_id as from_source_id,
@@ -3595,6 +3715,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
WHERE f.slug = ${slug} AND f.source_id = ${opts.sourceId}
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
}
@@ -3609,6 +3730,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
WHERE f.slug = ${slug}
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
});
@@ -3635,10 +3757,12 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])
WHERE t.slug = ${slug} AND t.source_id = ANY(${ids}::text[]) AND f.source_id = ANY(${ids}::text[])
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
}
- // v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks.
+ // v0.31.8 (D16) + #2200: federated arm above is first; two below mirror getLinks
+ // (incl. the #3754 soft-delete endpoint filter on all three arms).
if (opts?.sourceId) {
const rows = await tx`
SELECT f.slug as from_slug, f.source_id as from_source_id,
@@ -3651,6 +3775,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
WHERE t.slug = ${slug} AND t.source_id = ${opts.sourceId}
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
}
@@ -3665,6 +3790,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages t ON t.id = l.to_page_id
LEFT JOIN pages o ON o.id = l.origin_page_id
WHERE t.slug = ${slug}
+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL
`;
return rows as unknown as Link[];
});
@@ -3882,12 +4008,15 @@ export class PostgresEngine implements BrainEngine {
? sql`AND pt.source_id = ${opts.sourceId}`
: sql``;
+ // #3754: soft-deleted pages are excluded at seed, every recursive step, and
+ // the final SELECT joins — a deleted page neither anchors, relays, nor
+ // terminates a path (mirrors pglite-engine.traversePaths).
let rows;
if (direction === 'out') {
rows = await sql`
WITH RECURSIVE walk AS (
SELECT p.id, p.slug, 0::int 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
SELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -3895,6 +4024,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages p2 ON p2.id = l.to_page_id
WHERE w.depth < ${depth}
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${stepScope}
)
@@ -3904,6 +4034,7 @@ export class PostgresEngine implements BrainEngine {
JOIN links l ON l.from_page_id = w.id
JOIN pages p2 ON p2.id = l.to_page_id
WHERE w.depth < ${depth}
+ AND p2.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${stepScope}
ORDER BY depth, from_slug, to_slug
@@ -3912,7 +4043,7 @@ export class PostgresEngine implements BrainEngine {
rows = await sql`
WITH RECURSIVE walk AS (
SELECT p.id, p.slug, 0::int 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
SELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -3920,6 +4051,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages p2 ON p2.id = l.from_page_id
WHERE w.depth < ${depth}
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${stepScope}
)
@@ -3929,6 +4061,7 @@ export class PostgresEngine implements BrainEngine {
JOIN links l ON l.to_page_id = w.id
JOIN pages p2 ON p2.id = l.from_page_id
WHERE w.depth < ${depth}
+ AND p2.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${stepScope}
ORDER BY depth, from_slug, to_slug
@@ -3937,7 +4070,7 @@ export class PostgresEngine implements BrainEngine {
rows = await sql`
WITH RECURSIVE walk AS (
SELECT p.id, 0::int 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
SELECT p2.id, w.depth + 1, w.visited || p2.id
FROM walk w
@@ -3945,6 +4078,7 @@ export class PostgresEngine implements BrainEngine {
JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END
WHERE w.depth < ${depth}
AND NOT (p2.id = ANY(w.visited))
+ AND p2.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${stepScope}
)
@@ -3955,6 +4089,8 @@ export class PostgresEngine implements BrainEngine {
JOIN pages pf ON pf.id = l.from_page_id
JOIN pages pt ON pt.id = l.to_page_id
WHERE w.depth < ${depth}
+ AND pf.deleted_at IS NULL
+ AND pt.deleted_at IS NULL
AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})
${pfScope}
${ptScope}
@@ -4164,18 +4300,30 @@ export class PostgresEngine implements BrainEngine {
return result;
}
- async getUnverifiedExtractionPageIds(pageIds: number[]): Promise<Set<number>> {
- if (pageIds.length === 0) return new Set();
+ async getUnverifiedExtractionPageIds(
+ pageIds: number[],
+ ): Promise<Map<number, { unverified: boolean; status: string }>> {
+ const result = new Map<number, { unverified: boolean; status: string }>();
+ if (pageIds.length === 0) return result;
const sql = this.sql;
- // Predicate is the shared unverifiedExtractionFragment (issue #160) so
- // this query and the SQL-side source-boost guard can never drift.
+ // Quarantine predicate is the shared unverifiedExtractionFragment (issue
+ // #160) so this query and the SQL-side source-boost guard can never
+ // drift. #4220 widened the projection: any page with a frontmatter
+ // `status` value is returned (draft/superseded/restricted/... surface on
+ // SearchResult.status); the fragment match stays the quarantine flag.
const rows = await sql.unsafe(
- `SELECT id FROM pages
+ `SELECT id,
+ (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') AS status,
+ (${unverifiedExtractionFragment('pages')}) AS unverified
+ FROM pages
WHERE id = ANY($1::int[])
- AND ${unverifiedExtractionFragment('pages')}`,
+ AND (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') IS NOT NULL`,
[pageIds] as never,
);
- return new Set((rows as unknown as { id: number }[]).map((r) => Number(r.id)));
+ for (const r of rows as unknown as { id: number; status: string; unverified: boolean }[]) {
+ result.set(Number(r.id), { unverified: r.unverified === true, status: r.status });
+ }
+ return result;
}
async getPageTimestamps(slugs: string[]): Promise<Map<string, Date>> {
@@ -4340,7 +4488,8 @@ export class PostgresEngine implements BrainEngine {
throw new Error(`addTimelineEntry failed: page "${slug}" (source=${sourceId}) not found`);
}
}
- // ON CONFLICT DO NOTHING via the (page_id, date, summary) unique index.
+ // ON CONFLICT DO NOTHING via the (page_id, date, md5(summary), source)
+ // unique index (#3737: md5-keyed so long summaries fit the btree row cap).
// #3827: RETURNING 1 makes the outcome observable — 0 rows means either
// page missing OR duplicate; with the existence check above (default) the
// false return unambiguously means "deduplicated", and under
@@ -4354,7 +4503,7 @@ export class PostgresEngine implements BrainEngine {
INSERT INTO timeline_entries (page_id, date, source, summary, detail)
SELECT id, ${entry.date}::date, ${sanitizeForJsonb(entry.source || '')}, ${sanitizeForJsonb(entry.summary)}, ${sanitizeForJsonb(entry.detail || '')}
FROM pages WHERE slug = ${slug} AND source_id = ${sourceId}
- ON CONFLICT (page_id, date, summary, source) DO NOTHING
+ ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING
RETURNING 1
`;
return inserted.length > 0;
@@ -4378,8 +4527,8 @@ export class PostgresEngine implements BrainEngine {
SELECT p.id, v.date::date, v.source, v.summary, v.detail
FROM jsonb_to_recordset(($1::jsonb)->'rows')
AS v(slug text, date text, source text, summary text, detail text, source_id text)
- JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id
- ON CONFLICT (page_id, date, summary, source) DO NOTHING
+ JOIN pages p ON p.slug = v.slug AND p.source_id = v.source_id AND p.deleted_at IS NULL
+ ON CONFLICT (page_id, date, md5(summary), source) DO NOTHING
RETURNING 1`,
[],
[{ rows }],
@@ -4926,10 +5075,11 @@ export class PostgresEngine implements BrainEngine {
}
async insertFacts(
- rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
ctx: { source_id: string },
- ): Promise<{ inserted: number; ids: number[] }> {
- return factsImpl.insertFacts(this.factsDeps, rows, ctx);
+ opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean } },
+ ): Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number }> {
+ return factsImpl.insertFacts(this.factsDeps, rows, ctx, opts);
}
async deleteFactsForPage(
diff --git a/src/core/postgres-engine/cjk-search.ts b/src/core/postgres-engine/cjk-search.ts
new file mode 100644
index 0000000000..274eef26ab
--- /dev/null
+++ b/src/core/postgres-engine/cjk-search.ts
@@ -0,0 +1,38 @@
+/**
+ * #3986: CJK keyword fallback for the Postgres engine — parity port of the
+ * PGLite fallback that has existed since v0.32.7. `websearch_to_tsquery`
+ * with an ASCII-stemming FTS config can't tokenize CJK, so keyword recall
+ * on Postgres was silently zero for Chinese / Japanese / Korean queries
+ * (the vector arm masked it until embeddings were stale or unavailable).
+ *
+ * SQL builds in the shared `src/core/search/cjk-keyword-sql.ts` (identical
+ * text + params on both engines). This module supplies only the executor
+ * seam: a narrow runner the engine binds to its scoped read transaction
+ * (RLS scope binding + `SET LOCAL statement_timeout`), never the engine
+ * class itself.
+ *
+ * Note: the fallback is an ILIKE scan over content_chunks — correct but
+ * not index-accelerated. Deployments with heavy CJK corpora should install
+ * a CJK-aware FTS extension (pgroonga / zhparser); see
+ * docs/guides/multi-language-fts.md.
+ */
+import type { SearchResult } from '../types.ts';
+import { rowToSearchResult } from '../utils.ts';
+import { buildCJKKeywordSql, type CjkKeywordCtx } from '../search/cjk-keyword-sql.ts';
+
+/**
+ * Narrow executor dep: runs one positional-param query inside the engine's
+ * scoped read transaction and returns raw rows.
+ */
+export type CjkKeywordRunner = (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
+
+export async function searchKeywordCJK(
+ run: CjkKeywordRunner,
+ query: string,
+ ctx: CjkKeywordCtx,
+): Promise<SearchResult[]> {
+ const built = buildCJKKeywordSql(query, ctx);
+ if (!built) return [];
+ const rows = await run(built.sql, built.params);
+ return rows.map(rowToSearchResult);
+}
diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts
index af17615aa7..27a53ccddb 100644
--- a/src/core/postgres-engine/facts.ts
+++ b/src/core/postgres-engine/facts.ts
@@ -15,6 +15,7 @@ import type {
import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
import { tryParseEmbedding } from '../utils.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
+import { resolveSupersededByRow, isInt4RowRef, type SupersedeTarget } from '../facts/supersede-resolve.ts';
/** Narrow slice of PostgresEngine the facts operations use. */
export interface PgFactsDeps {
@@ -119,27 +120,70 @@ export async function expireFact(deps: PgFactsDeps, id: number, opts?: { superse
export async function insertFacts(
deps: PgFactsDeps,
- rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
ctx: { source_id: string },
- ): Promise<{ inserted: number; ids: number[] }> {
- if (rows.length === 0) return { inserted: 0, ids: [] };
+ opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean } },
+ ): Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number }> {
+ if (rows.length === 0) return { inserted: 0, ids: [], warnings: [], deleted: 0 };
const sql = deps.sql;
// v0.41.15.0 (T6, codex #20): resolve the embedding-cast suffix
// ONCE per process so the cast matches the actual column type
// (halfvec vs vector). The probe is cached after first call.
const castSuffix = await deps.resolveFactsEmbeddingCast();
+ const warnings: string[] = [];
+ // v0.46 (#3014): captured inside the transaction below when
+ // deleteForPageFirst runs; stays 0 for the standalone insert path.
+ let deleted = 0;
// Single transaction so the v51 partial UNIQUE index can roll back
// the whole batch on constraint violation. Per-row INSERTs (not
// multi-row VALUES) keep the embedding-vs-no-embedding branching
// readable; batch sizes are small (5-30 rows per page in practice).
- // No supersede flow in this path — fence reconciliation is the
- // canonical source-of-truth direction, not the consolidator path.
+ // v0.46 (#3014): the fence path carries struck rows — `expired_at` is
+ // stamped inline here, and `superseded by #N` references are resolved
+ // to `facts.superseded_by` in a second pass below (same transaction).
const ids = await sql.begin(async (tx) => {
+ // v0.46 (#3014) — atomic reconcile: wipe the page's fence-owned rows
+ // as the FIRST statement of this transaction so a failing insert
+ // below rolls the delete back too. Inlined (not a deleteFactsForPage
+ // call) so it shares this transaction — deleteFactsForPage runs on
+ // the pool (`deps.sql`), a separate self-committing transaction,
+ // which is exactly the split this fix removes. Scoping mirrors it
+ // exactly (#1928 excludeSourcePrefixes + #2646 preserveExpiredLegacy).
+ const del = opts?.deleteForPageFirst;
+ if (del) {
+ const expiredLegacyFilter = del.preserveExpiredLegacy
+ ? tx`AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
+ : tx``;
+ const prefixes = del.excludeSourcePrefixes;
+ if (prefixes && prefixes.length > 0) {
+ const patterns = prefixes.map(p => `${p}%`);
+ const r = await tx`
+ DELETE FROM facts
+ WHERE source_id = ${ctx.source_id}
+ AND source_markdown_slug = ${del.slug}
+ AND NOT (COALESCE(source, '') LIKE ANY(${patterns}))
+ ${expiredLegacyFilter}
+ `;
+ deleted = r.count ?? 0;
+ } else {
+ const r = await tx`
+ DELETE FROM facts
+ WHERE source_id = ${ctx.source_id} AND source_markdown_slug = ${del.slug} ${expiredLegacyFilter}
+ `;
+ deleted = r.count ?? 0;
+ }
+ }
const out: number[] = [];
+ // Per-input inserted id, aligned to `rows` (null when the v51
+ // ON CONFLICT DO NOTHING skipped the row) — the second pass below
+ // must not index `out` positionally, or a skipped row would shift
+ // every later UPDATE onto the wrong fact.
+ const rowIds: Array<number | null> = [];
for (const input of rows) {
const validFrom = input.valid_from ?? new Date();
const validUntil = input.valid_until ?? null;
+ const expiredAt = input.expired_at ?? null;
const kind = input.kind ?? 'fact';
const visibility = input.visibility ?? 'private';
const notability = input.notability ?? 'medium';
@@ -161,14 +205,14 @@ export async function insertFacts(
const ins = await tx<Array<{ id: number }>>`
INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
+ valid_from, valid_until, expired_at, source, source_session, confidence,
embedding, embedded_at,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
event_type
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
- ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
+ ${validFrom}, ${validUntil}, ${expiredAt}, ${input.source}, ${sourceSession}, ${confidence},
${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
${input.row_num}, ${input.source_markdown_slug},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
@@ -180,10 +224,46 @@ export async function insertFacts(
RETURNING id
`;
if (ins[0]) out.push(Number(ins[0].id));
+ rowIds.push(ins[0] ? Number(ins[0].id) : null);
+ }
+
+ // v0.46 (#3014) — second pass: resolve `superseded by #N` page-local
+ // references to fact ids. Same transaction so a target row inserted
+ // above is visible. Keyed on (source_id, source_markdown_slug,
+ // row_num) — the v51 unique index — so a reference also resolves
+ // against a target that already existed before this batch. A target
+ // whose `expired_at` is set is itself struck (chain) and rejected.
+ for (let i = 0; i < rows.length; i++) {
+ const targetRow = rows[i].superseded_by_row;
+ if (targetRow === undefined || rowIds[i] === null) continue;
+ const slug = rows[i].source_markdown_slug;
+ // Only look up an int4-safe target. An absurd `#N` (11+ digits)
+ // would overflow the `row_num` comparison and abort the cycle;
+ // skipping the lookup leaves `target` undefined, so
+ // resolveSupersededByRow treats it as a dangling reference (NULL +
+ // warning) instead of throwing.
+ let target: SupersedeTarget | undefined;
+ if (isInt4RowRef(targetRow)) {
+ const found = await tx<Array<{ id: number; expired_at: Date | null }>>`
+ SELECT id, expired_at FROM facts
+ WHERE source_id = ${ctx.source_id}
+ AND source_markdown_slug = ${slug}
+ AND row_num = ${targetRow}
+ LIMIT 1
+ `;
+ target = found[0]
+ ? { id: Number(found[0].id), struck: found[0].expired_at != null }
+ : undefined;
+ }
+ const { superseded_by, warning } = resolveSupersededByRow(rows[i].row_num, targetRow, target, slug);
+ if (warning) warnings.push(warning);
+ if (superseded_by !== null) {
+ await tx`UPDATE facts SET superseded_by = ${superseded_by} WHERE id = ${rowIds[i]}`;
+ }
}
return out;
});
- return { inserted: ids.length, ids };
+ return { inserted: ids.length, ids, warnings, deleted };
}
export async function deleteFactsForPage(
@@ -313,14 +393,19 @@ export async function listSupersessions(
const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
const since = opts?.since ?? null;
const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
+ // v0.46 (#3014) — filter on `superseded_by` alone; the ontology
+ // writer closes a superseded row via `valid_until` (not `expired_at`,
+ // which would break its `--asof` time-travel), so requiring both
+ // columns dropped every ontology supersession AND every fence-authored
+ // one. Order / `since` fall back to `valid_until` when `expired_at` is
+ // NULL.
const rows = await sql<FactRowSqlShape[]>`
SELECT * FROM facts
WHERE source_id = ${source_id}
- AND expired_at IS NOT NULL
AND superseded_by IS NOT NULL
- ${since ? sql`AND expired_at >= ${since}` : sql``}
+ ${since ? sql`AND COALESCE(expired_at, valid_until) >= ${since}` : sql``}
${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
- ORDER BY expired_at DESC, id DESC
+ ORDER BY COALESCE(expired_at, valid_until) DESC, id DESC
LIMIT ${limit}
`;
return rows.map(rowToFactPg);
diff --git a/src/core/postgres-engine/init-schema-lock.ts b/src/core/postgres-engine/init-schema-lock.ts
new file mode 100644
index 0000000000..d632923d99
--- /dev/null
+++ b/src/core/postgres-engine/init-schema-lock.ts
@@ -0,0 +1,137 @@
+/**
+ * #2898 — deadlined acquisition of the initSchema advisory lock.
+ *
+ * `PostgresEngine.initSchema` used a bare `SELECT pg_advisory_lock(42)`,
+ * which blocks FOREVER when another session holds the lock. Session-scoped
+ * advisory locks leak through transaction-mode poolers (PgBouncer/Supabase
+ * pooler strip session lock state across checkouts — the same reason the
+ * cycle lock moved to a TTL table, see migrate.ts `cycle_locks_table`): a
+ * pooled backend that acquired the lock for a client that vanished holds it
+ * indefinitely, and every subsequent `gbrain` invocation hangs at connect
+ * with no output.
+ *
+ * This helper polls `pg_try_advisory_lock(42)` with:
+ * - a stderr heartbeat (every ~5s) naming the holder pid from pg_locks so
+ * the operator can SEE the wait instead of a silent hang, and
+ * - a hard deadline (default 10 min — long enough for a legitimate
+ * concurrent migration run on the direct pool; tunable via
+ * `GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS`), after which it throws a
+ * structured error naming the holder pid with
+ * `SELECT pg_terminate_backend(<pid>)` recovery guidance.
+ *
+ * Postgres-only by design: PGLite is single-connection and takes no
+ * advisory lock in initSchema (no parity counterpart required).
+ */
+
+/** Fixed advisory-lock key for initSchema DDL — brain-global on purpose
+ * (initSchema mutates the whole database; a per-source key would let two
+ * initSchema calls deadlock on shared DDL). */
+export const INIT_SCHEMA_LOCK_KEY = 42;
+
+const DEFAULT_TIMEOUT_MS = 10 * 60_000;
+const DEFAULT_POLL_MS = 500;
+const DEFAULT_HEARTBEAT_MS = 5_000;
+
+export interface InitSchemaLockOpts {
+ /** Hard deadline in ms. Default: GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS or 600s. */
+ timeoutMs?: number;
+ /** Poll interval in ms (default 500). */
+ pollMs?: number;
+ /** Heartbeat interval in ms (default 5000). Progress goes to stderr. */
+ heartbeatMs?: number;
+ /** Log sink (default process.stderr). */
+ log?: (line: string) => void;
+ /** Clock + sleep seams for tests. */
+ now?: () => number;
+ sleep?: (ms: number) => Promise<void>;
+}
+
+/** Resolve the timeout from opts > env > default. Invalid env falls through. */
+export function resolveInitSchemaLockTimeoutMs(
+ opts: Pick<InitSchemaLockOpts, 'timeoutMs'> = {},
+ env: NodeJS.ProcessEnv = process.env,
+): number {
+ if (opts.timeoutMs !== undefined) return opts.timeoutMs;
+ const raw = env.GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS;
+ if (raw !== undefined && raw !== '') {
+ const n = Number(raw);
+ if (Number.isFinite(n) && n > 0) return n * 1000;
+ }
+ return DEFAULT_TIMEOUT_MS;
+}
+
+/** Best-effort: pid of the granted holder of the advisory lock, or null. */
+async function lockHolderPid(
+ query: (sql: string) => Promise<Array<Record<string, unknown>>>,
+): Promise<number | null> {
+ try {
+ const rows = await query(
+ `SELECT pid FROM pg_locks
+ WHERE locktype = 'advisory' AND classid = 0
+ AND objid = ${INIT_SCHEMA_LOCK_KEY} AND granted
+ LIMIT 1`,
+ );
+ const pid = rows[0]?.pid;
+ return typeof pid === 'number' ? pid : pid != null ? Number(pid) : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Acquire the initSchema advisory lock or throw after the deadline.
+ * `query` runs a raw SQL string on the SAME connection that will run the DDL
+ * (session locks are per-backend — acquiring on any other connection would
+ * be meaningless).
+ */
+export async function acquireInitSchemaAdvisoryLock(
+ query: (sql: string) => Promise<Array<Record<string, unknown>>>,
+ opts: InitSchemaLockOpts = {},
+): Promise<void> {
+ const timeoutMs = resolveInitSchemaLockTimeoutMs(opts);
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
+ const heartbeatMs = opts.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
+ const log = opts.log ?? ((line: string) => process.stderr.write(line + '\n'));
+ const now = opts.now ?? Date.now;
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+
+ const started = now();
+ let lastBeat = started;
+ for (;;) {
+ const rows = await query(`SELECT pg_try_advisory_lock(${INIT_SCHEMA_LOCK_KEY}) AS locked`);
+ if (rows[0]?.locked === true) return;
+
+ const elapsed = now() - started;
+ if (elapsed >= timeoutMs) {
+ const holder = await lockHolderPid(query);
+ const holderNote = holder != null
+ ? `Held by backend pid ${holder}.`
+ : 'Holder pid could not be determined from pg_locks.';
+ throw new Error(
+ `initSchema: timed out after ${Math.round(elapsed / 1000)}s waiting for the schema advisory lock ` +
+ `(pg_advisory_lock(${INIT_SCHEMA_LOCK_KEY})). ${holderNote} ` +
+ `Another gbrain process may be mid-migration — retry once it finishes. ` +
+ `If the holder is a LEAKED session (transaction-mode poolers like PgBouncer/Supabase ` +
+ `strip session advisory-lock state across checkouts, so a backend can hold the lock for a ` +
+ `client that is long gone), terminate it and retry:\n` +
+ (holder != null
+ ? ` SELECT pg_terminate_backend(${holder});\n`
+ : ` SELECT pid FROM pg_locks WHERE locktype = 'advisory' AND objid = ${INIT_SCHEMA_LOCK_KEY} AND granted;\n` +
+ ` SELECT pg_terminate_backend(<pid>);\n`) +
+ `Tune the wait with GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS.`,
+ );
+ }
+
+ if (now() - lastBeat >= heartbeatMs) {
+ lastBeat = now();
+ const holder = await lockHolderPid(query);
+ log(
+ ` [initSchema] waiting for the schema advisory lock` +
+ `${holder != null ? ` (held by backend pid ${holder})` : ''}` +
+ ` — ${Math.round(elapsed / 1000)}s elapsed, timeout ${Math.round(timeoutMs / 1000)}s`,
+ );
+ }
+
+ await sleep(pollMs);
+ }
+}
diff --git a/src/core/remediation/context.ts b/src/core/remediation/context.ts
index 59f93fc5ee..b9333c576b 100644
--- a/src/core/remediation/context.ts
+++ b/src/core/remediation/context.ts
@@ -54,7 +54,7 @@ export async function loadRecommendationContext(
// fileCfg loads synchronously, so the resolveKey closure is sync.
const { loadConfigFileOnly } = await import('../config.ts');
const fileCfg = loadConfigFileOnly();
- const { embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG } = await import(
+ const { embeddingProviderConfigured, HOSTED_EMBED_KEY_CONFIG, chatApiKeyConfigured } = await import(
'../brain-score-recommendations.ts'
);
const embeddingConfigured = embeddingProviderConfigured(embeddingModel, (envVar) => {
@@ -84,7 +84,9 @@ export async function loadRecommendationContext(
embeddingModel,
embeddingDimensions,
embeddingProviderConfigured: embeddingConfigured,
- hasChatApiKey: !!(process.env.ANTHROPIC_API_KEY || fileCfg?.anthropic_api_key),
+ // #3944: shared env+file-plane probe (same helper as autopilot's
+ // dispatch loop, so the two planners can never disagree on this).
+ hasChatApiKey: chatApiKeyConfigured(fileCfg),
nullSignatureCohort,
};
}
diff --git a/src/core/retry.ts b/src/core/retry.ts
index 5defca7204..2840a1c18f 100644
--- a/src/core/retry.ts
+++ b/src/core/retry.ts
@@ -86,8 +86,12 @@ export const BATCH_AUDIT_SITES = [
'extract.links_db',
'extract.timeline_db',
'extract.by_mention',
+ // #3674: --rebuild reconciling delete-then-insert of the mention scan's rows.
+ 'extract.by_mention.rebuild',
// v0.42.7 (#1696): extract --stale incremental sweep.
'extract.stale',
+ // #3961: atom-provenance edges banked after the completion-receipt flip.
+ 'cycle.extract_atoms.provenance',
// operations.ts MCP put_page auto-link path.
'mcp.put_page.autolink',
// sync.ts/reindex.ts orchestrator labels.
diff --git a/src/core/schema-embedded.ts b/src/core/schema-embedded.generated.ts
similarity index 98%
rename from src/core/schema-embedded.ts
rename to src/core/schema-embedded.generated.ts
index 095cb7ad18..5c73155755 100644
--- a/src/core/schema-embedded.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -558,7 +558,10 @@ CREATE INDEX IF NOT EXISTS idx_timeline_date ON timeline_entries(date);
-- v0.41.18.0 (codex finding #11): widened from (page_id, date, summary) to
-- include \`source\` so distinct meeting provenance survives. Legacy rows
-- have source='' (schema default) so legacy dedup behavior is preserved.
-CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, summary, source);
+-- #3737: keyed on md5(summary) — a raw long/incompressible summary overflowed
+-- the btree v4 row cap (~2704 bytes) and aborted the whole timeline insert.
+-- Both insert sites infer ON CONFLICT (page_id, date, md5(summary), source).
+CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, md5(summary), source);
-- v0.42.x (Life Chronicle): event-projection lookup + dedup. Partial
-- (event_page_id IS NOT NULL) so ordinary timeline rows are unaffected.
CREATE INDEX IF NOT EXISTS idx_timeline_event_page ON timeline_entries(event_page_id) WHERE event_page_id IS NOT NULL;
@@ -791,6 +794,28 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- chat_usage_log (#4218 / migration v140): durable per-call chat usage
+-- ledger. One row per SUCCESSFUL gateway.chat() call, written fire-and-forget
+-- by the chat-usage sink (src/core/ai/chat-usage.ts). cost_usd is a
+-- canonical-table estimate; NULL when the model has no pricing (never a fake
+-- 0). Read back by the \`get_usage\` op with explicit coverage fields.
+CREATE TABLE IF NOT EXISTS chat_usage_log (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ model TEXT NOT NULL,
+ provider TEXT,
+ phase TEXT,
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
+ cost_usd DOUBLE PRECISION
+);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_created
+ ON chat_usage_log (created_at);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_model
+ ON chat_usage_log (model, created_at);
+
-- migration_impact_log moved BELOW minion_jobs (was here, lines 645-676)
-- because its \`job_id BIGINT REFERENCES minion_jobs(id)\` FK requires
-- minion_jobs to exist FIRST during SCHEMA_SQL replay. v0.41.25.0 fix.
@@ -1412,8 +1437,8 @@ CREATE INDEX IF NOT EXISTS take_nudge_log_proposal_cooldown_idx
CREATE INDEX IF NOT EXISTS take_nudge_log_wave_idx
ON take_nudge_log (wave_version, fired_at DESC);
--- think_ab_results (v0.36.1.0 T18 / D19): A/B harness data for
--- \`gbrain think --ab\`. One row per side-by-side comparison.
+-- think_ab_results (v0.36.1.0 T18 / D19): A/B harness data for the think
+-- A/B harness (runAbTrial). One row per side-by-side comparison.
CREATE TABLE IF NOT EXISTS think_ab_results (
id BIGSERIAL PRIMARY KEY,
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
diff --git a/src/core/schema-pack/lint-rules.ts b/src/core/schema-pack/lint-rules.ts
index cade64dffd..0aad49cde8 100644
--- a/src/core/schema-pack/lint-rules.ts
+++ b/src/core/schema-pack/lint-rules.ts
@@ -16,6 +16,7 @@ import type { SchemaPackManifest } from './manifest-v1.ts';
import type { BrainEngine } from '../engine.ts';
import { readRecentMutations } from './mutate-audit.ts';
import { classifyStoredType, sanitizeTypeForDisplay, safeCliToken } from './type-usage.ts';
+import { NESTED_QUANTIFIER_RE } from './redos-guard.ts';
export type LintSeverity = 'error' | 'warning';
@@ -328,15 +329,14 @@ export const mutationCountAnomaly: LintRule = (manifest, opts) => {
// Aggregator
// ────────────────────────────────────────────────────────────────────────
-// v0.41.37.0 #1569: advisory ReDoS pre-screen for pack inference regexes.
-// Flags the classic nested-quantifier shapes ((a+)+, (a*)*, (a+)*, (\w+)+)
-// that cause catastrophic backtracking. WARNING, not error: a hard reject
-// would disable the whole pack on upgrade (pages fall back to legacy typing).
-// The runtime input-length cap (MAX_REGEX_INPUT_CHARS in redos-guard.ts) is
-// the actual safety net; this rule tells the author to fix the pattern.
-// Heuristic: an inner group containing a +/* quantifier, wrapped by an outer
-// +/* quantifier. Catches the common ReDoS class, not every possible one.
-const NESTED_QUANTIFIER_RE = /\([^()]*[+*][^()]*\)\s*[+*]/;
+// v0.41.37.0 #1569: ReDoS pre-screen for pack inference regexes. Flags the
+// classic nested-quantifier shapes ((a+)+, (a*)*, (a+)*, (\w+)+) that cause
+// catastrophic backtracking. Lint severity stays WARNING (a hard lint reject
+// would disable the whole pack on upgrade; pages fall back to legacy typing)
+// — but since the megawave vm-watchdog removal, the SAME heuristic is
+// ENFORCED at runtime by runRegexBounded (the pattern is refused, never
+// executed, that verb degrades to mentions). The shared constant lives in
+// redos-guard.ts so lint and runtime cannot drift.
export const linkRegexCatastrophicBacktrack: LintRule = (manifest) => {
const issues: LintIssue[] = [];
for (const lt of manifest.link_types) {
diff --git a/src/core/schema-pack/redos-guard.ts b/src/core/schema-pack/redos-guard.ts
index 4153f62c4d..60e1e4bd4c 100644
--- a/src/core/schema-pack/redos-guard.ts
+++ b/src/core/schema-pack/redos-guard.ts
@@ -30,9 +30,23 @@
// remaining verbs degrade to mentions. Total CPU per page is bounded by
// the budget regardless of pathological pattern count. SAFE for v0.38.
//
-// Re-run the spike when upgrading Bun: `bun scripts/spike-bun-vm-timeout.ts`
-
-import { runInContext, createContext } from 'node:vm';
+// v0.46 megawave FALSIFICATION (bootstrap-verify corpus hang): in a process
+// that ALSO hosts PGLite (WASM Postgres), repeated `vm.runInContext(...,
+// { timeout })` calls wedge Bun's event loop — after some dozens of watchdog
+// runs, ALL JS timers stop firing and the next in-flight PGLite query promise
+// never resolves (main thread parks in kevent64 at 0% CPU forever). Repro:
+// put_page x ~20 with pack regex inference (#3190) against an in-memory
+// PGLite brain; hang point drifts run-to-run. The vm timeout was therefore
+// REMOVED — it protected against a slow regex by freezing the entire brain,
+// strictly worse than the attack. This is likely the mechanism behind the
+// #1569-followup field report of syncs wedging deterministically mid-run.
+// Bounding is now: (1) the input-length cap below, (2) a runtime HARD gate
+// refusing nested-quantifier (catastrophic-shape) patterns — the same
+// heuristic the star-height lint flags, escalated from advisory to enforced
+// at execution time (degrade-to-mentions, never executed), and (3) the
+// per-page cumulative budget. If a true preemptive bound is ever needed
+// again, it must be the E6 option B worker pool — NOT node:vm — because the
+// watchdog is unsafe in PGLite-hosting processes.
export const LINK_EXTRACTION_TOTAL_BUDGET_MS = 500 as const;
export const PER_REGEX_TIMEOUT_MS = 50 as const;
@@ -41,9 +55,10 @@ export const PER_REGEX_TIMEOUT_MS = 50 as const;
// long input to blow up; a pack regex run against a multi-KB body is the blast
// radius. Capping the input length removes it cheaply — a link-extraction
// `context` is normally a sentence or short paragraph, so 64KB is generous.
-// Over the cap, the regex is skipped (degrade-to-mentions) without even
-// entering the vm. This is the real runtime safety net (the star-height lint
-// rule is advisory). Env-overridable for power users with huge contexts.
+// Over the cap, the regex is skipped (degrade-to-mentions) without ever
+// executing. Paired with the runtime nested-quantifier refusal below (the
+// star-height lint heuristic, enforced at execution time since the vm
+// watchdog's removal). Env-overridable for power users with huge contexts.
export const MAX_REGEX_INPUT_CHARS = (() => {
const raw = process.env.GBRAIN_MAX_REGEX_INPUT_CHARS;
const n = raw ? parseInt(raw, 10) : NaN;
@@ -59,6 +74,27 @@ export class RegexInputTooLargeError extends Error {
}
}
+/**
+ * Nested-quantifier (catastrophic-backtracking shape) heuristic: an inner
+ * group containing a +/* quantifier, wrapped by an outer +/* quantifier —
+ * `(a+)+`, `(a*)*`, `(\w+)+` and friends. Single source of truth: the
+ * star-height LINT rule (`linkRegexCatastrophicBacktrack` in lint-rules.ts)
+ * imports this same constant, and `runRegexBounded` below enforces it at
+ * runtime (the pattern is REFUSED, never executed) now that the vm watchdog
+ * is gone. Catches the common exponential class, not every possible one.
+ */
+export const NESTED_QUANTIFIER_RE = /\([^()]*[+*][^()]*\)\s*[+*]/;
+
+/** Tagged error thrown when a pattern matches NESTED_QUANTIFIER_RE. Treated
+ * as degrade-to-mentions by `PageRegexBudget.runBounded` (counts against the
+ * budget), same contract as the oversize-input refusal above. */
+export class RegexCatastrophicPatternError extends Error {
+ constructor(public readonly pattern: string) {
+ super(`regex pattern '${pattern}' has a nested quantifier (catastrophic-backtracking shape); refused`);
+ this.name = 'RegexCatastrophicPatternError';
+ }
+}
+
export class RegexTimeoutError extends Error {
readonly verb: string;
readonly pattern: string;
@@ -130,39 +166,45 @@ export class PageRegexBudget {
}
/**
- * Low-level bounded regex execution. Uses `vm.runInContext` with a
- * 50ms timeout to interrupt catastrophic backtracking. If T24's Bun
- * spike confirms reliability, this is the production path. Otherwise
- * the caller swaps in a worker-pool implementation with the same
- * signature.
+ * Low-level bounded regex execution. Bounding is structural, not
+ * preemptive (see the megawave falsification note in the header — the
+ * node:vm watchdog wedges Bun's event loop in PGLite-hosting processes,
+ * so it MUST NOT come back here):
+ * 1. input-length cap (MAX_REGEX_INPUT_CHARS) — throws
+ * RegexInputTooLargeError, degrade-to-mentions upstream;
+ * 2. catastrophic-shape refusal (NESTED_QUANTIFIER_RE) — throws
+ * RegexCatastrophicPatternError BEFORE the pattern ever executes;
+ * 3. the caller's per-page cumulative budget (PageRegexBudget).
+ *
+ * `timeoutMs` is retained for signature compatibility and budget
+ * accounting only; there is no in-flight interruption.
*
* NOTE: this is a single-shot match. Callers wanting global matches
- * should iterate via execAll or similar; the timeout applies to each
- * exec call, not the global iteration.
+ * should iterate via execAll or similar.
*/
export function runRegexBounded(
pattern: string,
text: string,
- timeoutMs: number = PER_REGEX_TIMEOUT_MS,
+ _timeoutMs: number = PER_REGEX_TIMEOUT_MS,
): RegExpMatchArray | null {
- // v0.41.37.0 #1569: input-length cap BEFORE the vm. Over the cap, skip the
- // regex entirely (the surrounding budget treats the throw as degrade). This
- // is the primary ReDoS safety net — catastrophic backtracking can't blow up
- // on input it never sees.
+ // v0.41.37.0 #1569: input-length cap first. Over the cap, skip the regex
+ // entirely (the surrounding budget treats the throw as degrade).
+ // Catastrophic backtracking can't blow up on input it never sees.
if (text.length > MAX_REGEX_INPUT_CHARS) {
throw new RegexInputTooLargeError(text.length);
}
- // Create a fresh context so the pack's regex can't leak state across
- // runs. Pass pattern + text as primitives only.
- const ctx = createContext({ pattern, text });
+ // Hard gate: refuse nested-quantifier shapes outright (the lint rule's
+ // heuristic, enforced). With no preemptive watchdog, an exponential
+ // pattern must never reach exec().
+ if (NESTED_QUANTIFIER_RE.test(pattern)) {
+ throw new RegexCatastrophicPatternError(pattern);
+ }
try {
- const code = `(new RegExp(pattern)).exec(text)`;
- const result = runInContext(code, ctx, { timeout: timeoutMs }) as RegExpMatchArray | null;
- return result;
- } catch (e) {
- // vm throws on timeout. Treat any error in regex compile/exec as
- // a degrade signal (return null, NOT throw — the caller will count
- // this against the budget).
+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- this function IS the bounded-exec chokepoint for community pack regexes: input is capped at MAX_REGEX_INPUT_CHARS and nested-quantifier (catastrophic-backtracking) shapes are refused above BEFORE exec, and every caller routes through PageRegexBudget's per-page cumulative budget (see header: the vm-watchdog alternative wedges Bun+PGLite)
+ return new RegExp(pattern).exec(text);
+ } catch {
+ // Malformed pattern (compile error). Treat as a degrade signal — the
+ // caller counts it against the budget, same as before.
throw new RegexTimeoutError('<unknown-verb>', pattern);
}
}
diff --git a/src/core/schema-verify.ts b/src/core/schema-verify.ts
index 64250e83b0..98cd1ddde0 100644
--- a/src/core/schema-verify.ts
+++ b/src/core/schema-verify.ts
@@ -13,7 +13,7 @@
* Called at the end of initSchema(), after all migrations complete.
*/
-import { SCHEMA_SQL } from './schema-embedded.ts';
+import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import type { BrainEngine } from './engine.ts';
/** A column expected to exist in the database. */
diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.ts
new file mode 100644
index 0000000000..584c5c554c
--- /dev/null
+++ b/src/core/search/cjk-keyword-sql.ts
@@ -0,0 +1,194 @@
+/**
+ * Shared CJK keyword-fallback SQL builder (#3986).
+ *
+ * `websearch_to_tsquery` with an ASCII-stemming FTS config ('english', …)
+ * can't tokenize CJK, so FTS keyword recall is zero for Chinese / Japanese /
+ * Korean queries. Both engines fall back to a term-by-term ILIKE match with
+ * term-frequency ranking (v0.32.7 on PGLite; ported to Postgres by #3986).
+ * The SQL is built ONCE here with $N positional params so the two engines
+ * cannot drift; each engine supplies only its own executor.
+ *
+ * Ranking: term-frequency count per term via
+ * (length(chunk) - length(replace(chunk, term, ''))) / length(term),
+ * plus a bonus for contiguous raw-query occurrences when multi-term, and a
+ * position() tiebreaker so earlier-in-chunk hits outrank later ones.
+ *
+ * Parameter bindings:
+ * - LIKE parameters are individually escaped with escapeLikePattern and
+ * wrapped with %.
+ * - Raw terms and raw query are bound unescaped for ranking arithmetic.
+ * - Explicit `ESCAPE '\'` on ILIKE clauses.
+ * - Empty-query guard returns null without binding SQL.
+ */
+import type { SearchOpts } from '../types.ts';
+import { buildBestPerPagePoolCte } from './sql-ranking.ts';
+import { escapeLikePattern, splitCJKQueryTerms } from '../cjk.ts';
+
+/** Query-shape context shared by both engines' CJK fallback call sites. */
+export interface CjkKeywordCtx {
+ limit: number;
+ offset: number;
+ /** Dedup headroom for the inner CTE; unused when dedup=false. */
+ innerLimit: number;
+ sourceFactorCase: string;
+ hardExcludeClause: string;
+ visibilityClause: string;
+ detailFilter: string;
+ opts: SearchOpts | undefined;
+ /** true = page-grain (best chunk per page); false = chunk-grain. */
+ dedup: boolean;
+}
+
+export interface CjkKeywordSql {
+ sql: string;
+ params: unknown[];
+}
+
+export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywordSql | null {
+ const { limit, offset, innerLimit, sourceFactorCase, hardExcludeClause, visibilityClause, detailFilter, opts, dedup } = ctx;
+ const qRaw = query;
+ if (qRaw.length === 0) return null;
+ const terms = splitCJKQueryTerms(qRaw);
+ if (terms.length === 0) return null;
+
+ const params: unknown[] = [];
+
+ // LIKE parameters: $1 .. $N (each escaped and wrapped with %)
+ const likeParamIndices: number[] = [];
+ for (const term of terms) {
+ params.push(`%${escapeLikePattern(term)}%`);
+ likeParamIndices.push(params.length);
+ }
+
+ // Raw term parameters for term-frequency scoring: $N+1 .. $2N
+ const rawTermIndices: number[] = [];
+ for (const term of terms) {
+ params.push(term);
+ rawTermIndices.push(params.length);
+ }
+
+ // Raw full query parameter for contiguous match bonus and tiebreaker: $2N+1
+ params.push(qRaw);
+ const qRawIndex = params.length;
+
+ // Pagination limits & offset
+ let innerLimitIndex = 0;
+ let limitIndex = 0;
+ let offsetIndex = 0;
+
+ if (dedup) {
+ params.push(innerLimit);
+ innerLimitIndex = params.length;
+ params.push(limit);
+ limitIndex = params.length;
+ params.push(offset);
+ offsetIndex = params.length;
+ } else {
+ params.push(limit);
+ limitIndex = params.length;
+ params.push(offset);
+ offsetIndex = params.length;
+ }
+
+ let extraFilter = '';
+ if (opts?.language) {
+ params.push(opts.language);
+ extraFilter += ` AND cc.language = $${params.length}`;
+ }
+ if (opts?.symbolKind) {
+ params.push(opts.symbolKind);
+ extraFilter += ` AND cc.symbol_type = $${params.length}`;
+ }
+ if (opts?.afterDate) {
+ params.push(opts.afterDate);
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ }
+ if (opts?.beforeDate) {
+ params.push(opts.beforeDate);
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ }
+ // v0.34.1 (#861 — P0 leak seal): source-isolation on the CJK fallback path.
+ if (opts?.sourceIds && opts.sourceIds.length > 0) {
+ params.push(opts.sourceIds);
+ extraFilter += ` AND p.source_id = ANY($${params.length}::text[])`;
+ } else if (opts?.sourceId) {
+ params.push(opts.sourceId);
+ extraFilter += ` AND p.source_id = $${params.length}`;
+ }
+
+ const whereLikeClause = likeParamIndices
+ .map(idx => `cc.chunk_text ILIKE $${idx} ESCAPE '\\'`)
+ .join(' AND ');
+
+ const termFreqExpr = rawTermIndices
+ .map(idx => `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${idx}, ''))) / NULLIF(LENGTH($${idx}), 0)::real)`)
+ .join(' + ');
+
+ const qRawBonusExpr = terms.length > 1
+ ? ` + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${qRawIndex}, ''))) / NULLIF(LENGTH($${qRawIndex}), 0)::real)`
+ : '';
+
+ const positionExpr = `COALESCE(1.0 / NULLIF(POSITION($${qRawIndex} IN cc.chunk_text), 0)::real, 0.0)`;
+
+ // Term-frequency count: count occurrences of each term in chunk_text via
+ // (length(chunk) - length(replace(chunk, term, ''))) / length(term),
+ // plus bonus for contiguous raw query occurrences when multi-term, and
+ // position()-tiebreaker so earlier-in-chunk hits outrank later ones.
+ const scoreExpr = `
+ ((${termFreqExpr}${qRawBonusExpr}
+ + ${positionExpr})
+ * ${sourceFactorCase})
+ `;
+
+ if (dedup) {
+ return {
+ sql: `WITH ranked AS (
+ SELECT
+ p.slug, p.id as page_id, p.title, p.type, p.source_id,
+ p.effective_date, p.effective_date_source,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
+ cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
+ ${scoreExpr} AS score,
+ CASE WHEN p.updated_at < (
+ SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
+ ) THEN true ELSE false END AS stale
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
+ AND cc.modality = 'text'
+ ORDER BY score DESC
+ LIMIT $${innerLimitIndex}
+ ),
+ ${buildBestPerPagePoolCte('ranked')}
+ SELECT * FROM best_per_page
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
+ LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
+ params,
+ };
+ }
+ return {
+ sql: `SELECT
+ p.slug, p.id as page_id, p.title, p.type, p.source_id,
+ p.effective_date, p.effective_date_source,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
+ cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
+ ${scoreExpr} AS score,
+ CASE WHEN p.updated_at < (
+ SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
+ ) THEN true ELSE false END AS stale
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
+ ORDER BY score DESC
+ LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
+ params,
+ };
+}
diff --git a/src/core/search/crag.ts b/src/core/search/crag.ts
new file mode 100644
index 0000000000..e236540185
--- /dev/null
+++ b/src/core/search/crag.ts
@@ -0,0 +1,144 @@
+/**
+ * #1663 — CRAG-style retrieval-confidence gate (the ceiling half of the
+ * floor/ceiling redesign).
+ *
+ * Corrective-RAG's core move: GRADE what retrieval returned before acting on
+ * it, and escalate when the evidence is weak instead of confidently handing
+ * the caller noise. gbrain's grade is zero-LLM — it reads the honesty
+ * signals the pipeline already stamps (T4 evidence, the reranker's
+ * cross-encoder score, the autocut weak-top floor):
+ *
+ * strong — rank-1 carries identity/vector evidence (alias_hit,
+ * exact_lookup, exact_title_match, high_vector_match) or the
+ * reranker scored the top at/above the weak-top floor.
+ * moderate — lexically verified top (keyword_exact) but no identity or
+ * calibrated-semantic signal.
+ * weak — zero results, a reranked top BELOW the weak-top floor
+ * (the #1863 "whole list is low-confidence" shape), or an
+ * unverified weak_semantic top.
+ *
+ * Consumers: the `query` op attaches the grade (+ query shape) to its
+ * retrieval response meta on every call, and — config-gated, default OFF —
+ * escalates a weak result once:
+ *
+ * search.crag_escalation=true → one high-ceiling retrieval re-run
+ * (expansion + relational + wide limit,
+ * autocut off) — keep whichever run grades
+ * better.
+ * search.crag_think=true → still-weak + local caller → run `think`
+ * (multi-round gather + synthesis) and
+ * attach its answer to the response meta.
+ *
+ * Pure module: no engine access here — grading reads stamped fields only,
+ * so it can never add latency or fail the search path.
+ */
+
+import type { SearchResult } from '../types.ts';
+
+export type RetrievalConfidence = 'strong' | 'moderate' | 'weak';
+
+export interface ConfidenceGrade {
+ level: RetrievalConfidence;
+ /** Machine-stable reason code (enumerated below; additive-only). */
+ reason:
+ | 'zero_results'
+ | 'exact_lookup'
+ | 'alias_hit'
+ | 'exact_title_match'
+ | 'high_vector_match'
+ | 'rerank_top'
+ | 'rerank_top_below_floor'
+ | 'keyword_exact_top'
+ | 'weak_semantic_top';
+ /** Rank-1 evidence label when present (auditability). */
+ top_evidence?: string;
+ /** Rank-1 cross-encoder score when the reranker ran. */
+ top_rerank_score?: number;
+}
+
+/**
+ * Default weak-top floor for the rerank-score check. Matches autocut's
+ * `search.autocut_min_top` default (the #1863 calibration): below it the
+ * cross-encoder itself says the best candidate is a poor match.
+ */
+export const DEFAULT_CRAG_MIN_TOP = 0.2;
+
+export function gradeRetrievalConfidence(
+ results: SearchResult[],
+ opts: { minTopScore?: number } = {},
+): ConfidenceGrade {
+ if (results.length === 0) return { level: 'weak', reason: 'zero_results' };
+ const top = results[0];
+ const floor = typeof opts.minTopScore === 'number' ? opts.minTopScore : DEFAULT_CRAG_MIN_TOP;
+
+ // Identity-tier signals win outright — retrieval FOUND the named thing.
+ if (top.exact_lookup !== undefined) {
+ return { level: 'strong', reason: 'exact_lookup', top_evidence: top.evidence };
+ }
+ if (top.alias_hit === true || top.evidence === 'alias_hit') {
+ return { level: 'strong', reason: 'alias_hit', top_evidence: top.evidence };
+ }
+ if (top.evidence === 'exact_title_match') {
+ return { level: 'strong', reason: 'exact_title_match', top_evidence: top.evidence };
+ }
+ if (top.evidence === 'high_vector_match') {
+ return { level: 'strong', reason: 'high_vector_match', top_evidence: top.evidence };
+ }
+
+ // Calibrated cross-encoder signal when the reranker ran.
+ if (typeof top.rerank_score === 'number' && Number.isFinite(top.rerank_score)) {
+ return top.rerank_score >= floor
+ ? { level: 'strong', reason: 'rerank_top', top_evidence: top.evidence, top_rerank_score: top.rerank_score }
+ : { level: 'weak', reason: 'rerank_top_below_floor', top_evidence: top.evidence, top_rerank_score: top.rerank_score };
+ }
+
+ // No reranker: fall back to the T4 evidence contract.
+ if (top.evidence === 'keyword_exact') {
+ return { level: 'moderate', reason: 'keyword_exact_top', top_evidence: top.evidence };
+ }
+ return { level: 'weak', reason: 'weak_semantic_top', top_evidence: top.evidence };
+}
+
+/** Meta block the `query` op attaches under `retrieval.crag`. */
+export interface CragMetaBlock {
+ confidence: RetrievalConfidence;
+ reason: ConfidenceGrade['reason'];
+ query_shape: 'factual' | 'open';
+ top_rerank_score?: number;
+ /** Present when the high-ceiling retrieval re-run fired. */
+ escalated?: boolean;
+ escalated_confidence?: RetrievalConfidence;
+ /** Still weak after (or without) escalation → the honest next move. */
+ escalate_to_think?: boolean;
+ /** Present when search.crag_think ran the think pipeline. */
+ think?: {
+ answer: string;
+ citations: number;
+ synthesis_status?: string;
+ model?: string;
+ };
+}
+
+/**
+ * Decision helper for the op layer: should the high-ceiling retrieval
+ * re-run fire? Kept pure/exported so the policy is unit-testable.
+ * Retrieval-side escalation only pays off when a better index sweep could
+ * plausibly contain the answer — which is true for BOTH shapes, but the
+ * op only re-runs when the first pass didn't already use the high-ceiling
+ * knobs (callerExpanded) — otherwise the re-run would be a no-op re-query.
+ */
+export function shouldEscalateRetrieval(
+ grade: ConfidenceGrade,
+ opts: { enabled: boolean; alreadyEscalated?: boolean },
+): boolean {
+ return opts.enabled && !opts.alreadyEscalated && grade.level === 'weak';
+}
+
+/** Rank a grade for better-of-two comparison after an escalated re-run. */
+export function confidenceRank(level: RetrievalConfidence): number {
+ switch (level) {
+ case 'strong': return 2;
+ case 'moderate': return 1;
+ case 'weak': return 0;
+ }
+}
diff --git a/src/core/search/evidence.ts b/src/core/search/evidence.ts
index c636ff946c..5f31214ed6 100644
--- a/src/core/search/evidence.ts
+++ b/src/core/search/evidence.ts
@@ -17,7 +17,9 @@
* alias_hit — query exactly matched the page's declared chosen name
* exact_title_match — query is a phrase in the page title (title boost fired)
* high_vector_match — base (pre-boost) score >= HIGH_MATCH_FLOOR
- * keyword_exact — surfaced with a solid score but no title/alias/vector tag
+ * keyword_exact — surfaced by a lexical arm (keyword/title FTS,
+ * keyword_hit=true) with a solid score (#3783 — a solid
+ * blended score alone no longer earns this label)
* weak_semantic — everything else (low-confidence tail)
*
* create_safety:
@@ -71,11 +73,32 @@ export function classifyEvidence(r: SearchResult, opts: EvidenceOpts = {}): Evid
if (typeof r.cosine === 'number' && Number.isFinite(r.cosine) && r.cosine >= floor) {
return 'high_vector_match';
}
+ // #3783 — keyword_exact requires ACTUAL lexical-arm membership
+ // (keyword_hit stamped pre-fusion by markKeywordHits, OR-propagated
+ // through RRF). Pre-fix, any base_score >= SOLID_MATCH_FLOOR was labeled
+ // keyword_exact with zero keyword verification, so a pure-vector row with
+ // a solid blended score lied to the agent about WHY it matched. Rows
+ // without the flag (incl. legacy cached rows) honestly degrade to
+ // weak_semantic — create_safety 'unknown', the safe look-closer direction.
const base = typeof r.base_score === 'number' ? r.base_score : r.score;
- if (Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) return 'keyword_exact';
+ if (r.keyword_hit === true && Number.isFinite(base) && base >= SOLID_MATCH_FLOOR) {
+ return 'keyword_exact';
+ }
return 'weak_semantic';
}
+/**
+ * #3783 — stamp lexical-arm membership on rows a keyword/title FTS query
+ * surfaced. Called on the raw arm output BEFORE fusion (hybrid pipeline) or
+ * before stampEvidence (direct keyword-only consumers: MCP keyword-only
+ * opt-out, no-embedding fallbacks, entity near-miss suggestions). Mutates in
+ * place, idempotent. RRF fusion OR-propagates the flag so a row that also
+ * appeared in a vector list keeps it regardless of merge order.
+ */
+export function markKeywordHits(results: SearchResult[]): void {
+ for (const r of results) r.keyword_hit = true;
+}
+
export function createSafetyFor(evidence: Evidence): CreateSafety {
switch (evidence) {
case 'alias_hit':
diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.ts
new file mode 100644
index 0000000000..d9a59c8305
--- /dev/null
+++ b/src/core/search/exact-lookup.ts
@@ -0,0 +1,193 @@
+/**
+ * #1663 — structural exact-lookup tier (identity resolution before ranking).
+ *
+ * The floor/ceiling redesign's floor: when the query IS a page identity — a
+ * slug ('people/alice-example'), an exact page title, or a declared alias —
+ * no amount of RRF/rerank scoring should be able to bury that page. The
+ * alias half already ships (applyAliasHop, T3); this tier adds the two
+ * structural probes it deliberately skipped:
+ *
+ * slug probe — a slug-shaped query resolves via engine.getPage directly.
+ * title probe — an exact (normalized) full-title equality match, read off
+ * the ALREADY-FETCHED page-grain title arm (zero extra
+ * queries on the hot path).
+ *
+ * Supersession-filtered: a page that a `supersedes` link marks stale is
+ * NEVER top-injected by this tier (the organic pipeline still surfaces it,
+ * downranked + stamped, via applySupersedeDownrank). Current canon wins the
+ * identity slot.
+ *
+ * Wiring: applyExactLookupTier runs right after applyAliasHop on all three
+ * hybrid return paths, gated on isLookupShapedQuery (pure, cheap). Hits
+ * already in the organic set are promoted to rank-1; absent hits inject at
+ * top-of-organic + epsilon (the alias-hop injection shape, page_id
+ * included). Injected/promoted rows carry:
+ * - exact_lookup: 'slug' | 'title' (autocut preserve predicate + telemetry)
+ * - slug hits: alias_hit=true (evidence → alias_hit → 'exists')
+ * - title hits: title_match_boost (evidence → exact_title_match → 'exists')
+ * so the T4 evidence/create_safety contract reads them as identity matches
+ * without widening the frozen EVIDENCE_ENUM.
+ *
+ * Fail-open everywhere: a probe error returns the organic results unchanged.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { SearchResult } from '../types.ts';
+import { normalizeAlias } from './alias-normalize.ts';
+import { isLookupShapedQuery } from './query-intent.ts';
+import { applySupersedeDownrank } from './hybrid.ts';
+
+/** Cap on tier injections per query (mirrors the alias hop's discipline). */
+export const MAX_EXACT_LOOKUP_INJECT = 3;
+/** title_match_boost stamped on exact-title tier hits (evidence signal). */
+export const EXACT_TITLE_STAMP = 1.25;
+
+/** Slug-shaped: one whitespace-free token containing a path separator. */
+export function isSlugShapedQuery(query: string): boolean {
+ const q = query.trim();
+ return q.length > 0 && !/\s/.test(q) && q.includes('/') && !q.startsWith('/') && !q.endsWith('/');
+}
+
+export interface ExactLookupOpts {
+ sourceId?: string;
+ sourceIds?: string[];
+ /**
+ * The page-grain title arm hybridSearch already fetched (searchTitles
+ * output). The title probe filters THIS list to normalized full-title
+ * equality — no second engine query. Callers without the arm omit it and
+ * only the slug probe runs.
+ */
+ titleCandidates?: SearchResult[];
+}
+
+/** Max distinct sources probed for a slug-shaped query on a federated call. */
+const MAX_SLUG_PROBE_SOURCES = 5;
+
+/**
+ * Probe the structural identity surfaces for a lookup-shaped query. Returns
+ * supersession-filtered, deduped, capped hits (empty for non-lookup queries
+ * and on any probe failure).
+ */
+export async function structuralExactLookup(
+ engine: BrainEngine,
+ query: string,
+ opts: ExactLookupOpts = {},
+): Promise<SearchResult[]> {
+ const q = query.trim();
+ if (!q || !isLookupShapedQuery(q)) return [];
+
+ const hits: SearchResult[] = [];
+ const seen = new Set<string>();
+ const push = (r: SearchResult) => {
+ const key = `${r.source_id ?? 'default'}::${r.slug}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ hits.push(r);
+ };
+
+ // Slug probe — only for slug-shaped queries (zero cost otherwise).
+ if (isSlugShapedQuery(q)) {
+ const scopes: Array<string | undefined> =
+ opts.sourceIds && opts.sourceIds.length > 0
+ ? [...opts.sourceIds].sort().slice(0, MAX_SLUG_PROBE_SOURCES)
+ : opts.sourceId != null
+ ? [opts.sourceId]
+ : [undefined];
+ for (const scope of scopes) {
+ try {
+ const page = scope != null
+ ? await engine.getPage(q, { sourceId: scope })
+ : await engine.getPage(q); // gbrain-allow-unscoped-getpage — read-only first-match; no paired write
+ if (!page) continue;
+ push({
+ page_id: page.id,
+ slug: page.slug,
+ title: page.title,
+ type: page.type,
+ source_id: page.source_id ?? scope ?? 'default',
+ chunk_text: (page.compiled_truth ?? '').slice(0, 200),
+ chunk_index: 0,
+ chunk_id: 0,
+ score: 0, // caller assigns the injection score
+ alias_hit: true, // identity match — evidence alias_hit → 'exists'
+ exact_lookup: 'slug',
+ } as SearchResult);
+ } catch {
+ // fail-open: slug probe error → no tier hit from this scope
+ }
+ }
+ }
+
+ // Title probe — normalized full-title equality over the existing title arm.
+ const qNorm = normalizeAlias(q);
+ if (qNorm && opts.titleCandidates && opts.titleCandidates.length > 0) {
+ for (const cand of opts.titleCandidates) {
+ if (!cand.title) continue;
+ if (normalizeAlias(cand.title) !== qNorm) continue;
+ push({
+ ...cand,
+ title_match_boost: Math.max(cand.title_match_boost ?? 1.0, EXACT_TITLE_STAMP),
+ exact_lookup: cand.exact_lookup ?? 'title',
+ });
+ }
+ }
+
+ if (hits.length === 0) return [];
+
+ // Supersession filter — a stale (superseded) page never wins the identity
+ // slot. Reuses the shared downrank stage as the lookup (it stamps
+ // `superseded`); tier scores are assigned by the caller afterwards, so the
+ // stage's score mutation on dropped rows is irrelevant.
+ try {
+ await applySupersedeDownrank(hits, engine);
+ } catch {
+ // fail-open: filter unavailable (pre-links schema) → keep hits
+ }
+ return hits.filter((h) => h.superseded !== true).slice(0, MAX_EXACT_LOOKUP_INJECT);
+}
+
+/**
+ * Promote/inject structural exact-lookup hits into a ranked result set.
+ * Mirrors applyAliasHop's contract: hits already present are promoted to the
+ * top (score = current-top + epsilon) and stamped; absent hits inject with
+ * the same top-of-organic + epsilon score shape. Returns a NEW sorted array;
+ * fail-open returns `results` unchanged.
+ */
+export async function applyExactLookupTier(
+ engine: BrainEngine,
+ results: SearchResult[],
+ query: string,
+ opts: ExactLookupOpts = {},
+): Promise<SearchResult[]> {
+ let hits: SearchResult[];
+ try {
+ hits = await structuralExactLookup(engine, query, opts);
+ } catch {
+ return results;
+ }
+ if (hits.length === 0) return results;
+
+ const out = [...results];
+ const topScore = out.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), 0);
+ let injectScore = topScore > 0 ? topScore : 1.0;
+
+ for (const hit of hits) {
+ injectScore += 1e-6;
+ const idx = out.findIndex(
+ (r) => r.slug === hit.slug && (r.source_id ?? 'default') === (hit.source_id ?? 'default'),
+ );
+ if (idx >= 0) {
+ // Promote in place: identity match outranks every scored row.
+ out[idx].score = injectScore;
+ out[idx].exact_lookup = hit.exact_lookup;
+ if (hit.alias_hit) out[idx].alias_hit = true;
+ if (hit.title_match_boost) {
+ out[idx].title_match_boost = Math.max(out[idx].title_match_boost ?? 1.0, hit.title_match_boost);
+ }
+ continue;
+ }
+ out.push({ ...hit, score: injectScore, base_score: injectScore });
+ }
+ out.sort((a, b) => b.score - a.score);
+ return out;
+}
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 9aa52192fa..1c79819dfa 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -31,14 +31,19 @@ import {
type AdaptiveReturnDecision,
} from './return-policy.ts';
import { applyAutocut, type AutocutDecision } from './autocut.ts';
-import { buildRelationalArm } from './relational-recall.ts';
+import {
+ buildRelationalArm,
+ ensureRelationalEvidenceSlot,
+ type RelationalEvidenceSlotDecision,
+} from './relational-recall.ts';
import { loadConfigWithEngine } from '../config.ts';
import { dedupResults } from './dedup.ts';
import { applyReranker } from './rerank.ts';
import { autoDetectDetail, classifyQuery, isAmbiguousModalityQuery } from './query-intent.ts';
import { isTitlePhraseMatch } from './title-match.ts';
import { normalizeAlias } from './alias-normalize.ts';
-import { stampEvidence } from './evidence.ts';
+import { stampEvidence, markKeywordHits } from './evidence.ts';
+import { applyExactLookupTier } from './exact-lookup.ts';
import { expandAnchors, hydrateChunks } from './two-pass.ts';
import { enforceTokenBudget, searchSalvageEnabled, type TokenBudgetMeta } from './token-budget.ts';
import { warnOncePerProcess } from '../utils.ts';
@@ -128,6 +133,11 @@ export async function stampContentFlags(engine: BrainEngine, results: SearchResu
* One batched query over the candidate arms' page_ids. Fail-open on the
* fetch (a marker-fetch failure must not break retrieval) — the boost then
* applies, but the SQL-side source-boost guard still holds.
+ *
+ * #4220: the same batched query now surfaces the page's raw
+ * `frontmatter.status` value, stamped on `SearchResult.status` for EVERY
+ * result whose page carries one (draft/superseded/restricted/verified/...).
+ * `unverified` remains the special case requiring the full quarantine pair.
*/
export async function stampUnverifiedExtractions(
engine: BrainEngine,
@@ -139,10 +149,13 @@ export async function stampUnverifiedExtractions(
results.map((r) => r.page_id).filter((n): n is number => typeof n === 'number' && Number.isFinite(n)),
)];
if (ids.length === 0) return;
- const unverified = await engine.getUnverifiedExtractionPageIds(ids);
- if (unverified.size === 0) return;
+ const marks = await engine.getUnverifiedExtractionPageIds(ids);
+ if (marks.size === 0) return;
for (const r of results) {
- if (unverified.has(r.page_id)) r.unverified = true;
+ const m = marks.get(r.page_id);
+ if (!m) continue;
+ r.status = m.status;
+ if (m.unverified) r.unverified = true;
}
} catch {
// best-effort: never break retrieval.
@@ -838,7 +851,7 @@ export async function applyAliasHop(
engine: import('../engine.ts').BrainEngine,
results: SearchResult[],
query: string,
- opts: { sourceId?: string; sourceIds?: string[] },
+ opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
): Promise<SearchResult[]> {
if (!query) return results;
const qNorm = normalizeAlias(query);
@@ -878,6 +891,13 @@ export async function applyAliasHop(
continue;
}
if (!page) continue;
+ // #4352 — the alias inject path bypasses the engines' SQL visibility
+ // clause (getPage, not search); re-apply the private predicate here so
+ // an untrusted caller can't hop into a `visibility: private` page.
+ if (
+ opts.excludePrivate &&
+ ((page.frontmatter as Record<string, unknown> | null | undefined)?.visibility === 'private')
+ ) continue;
injectScore += 1e-6;
out.push({
// #2339-sibling: include page_id. The `as SearchResult` cast hid its
@@ -1219,6 +1239,11 @@ export async function hybridSearch(
// ordering means we can't lazy-spread the full opts).
sourceId: opts?.sourceId,
sourceIds: opts?.sourceIds,
+ // #4352 — page-level private-visibility enforcement is trust-scoped
+ // state, same leak class as source scoping above: dropping it here would
+ // let an untrusted caller read `visibility: private` pages through the
+ // hybrid hot path.
+ excludePrivate: opts?.excludePrivate,
// v0.36 (D11): pass the pre-validated descriptor into the engine so
// it never has to read config. Engines normalize string-or-descriptor
// via normalizeEngineColumn; the descriptor path is the strict one.
@@ -1333,6 +1358,12 @@ export async function hybridSearch(
return [] as SearchResult[];
}),
]);
+ // #3783 — stamp lexical-arm membership pre-fusion so evidence's
+ // keyword_exact label is earned by an actual FTS hit, never by a solid
+ // blended score alone. Both arms are the lexical-evidence class (chunk
+ // FTS + title FTS); vector/relational arms are deliberately NOT marked.
+ markKeywordHits(keywordResults);
+ markKeywordHits(titleResults);
// v0.29.1: resolve salience/recency from caller (back-compat aliases for
// PR #618's `recencyBoost` numeric scale) or fall back to the heuristic.
@@ -1396,6 +1427,10 @@ export async function hybridSearch(
sourceIds: opts?.sourceIds,
depth: resolvedMode.relational_retrieval_depth,
limit: opts?.limit ?? resolvedMode.searchLimit,
+ // #4352 remediation: the arm hydrates titles + compiled_truth snippets
+ // straight from pages — thread the caller's private-page gate or a
+ // remote relational query bypasses the keyword/vector visibility clause.
+ excludePrivate: opts?.excludePrivate,
onMeta: opts?.onRelationalMeta,
});
}
@@ -1455,12 +1490,32 @@ export async function hybridSearch(
}
// T3/T4 — alias hop + evidence stamp even without an embedding provider
// (the named-thing fix is most valuable exactly when vector is unavailable).
- const noEmbedHopped = await applyAliasHop(engine, dedupResults(noEmbedResults), query, {
+ const noEmbedPreExact = await applyAliasHop(engine, dedupResults(noEmbedResults), query, {
+ sourceId: opts?.sourceId,
+ sourceIds: opts?.sourceIds,
+ excludePrivate: opts?.excludePrivate,
+ });
+ // #1663 — structural exact-lookup tier (slug / exact-title identity).
+ const noEmbedHopped = await applyExactLookupTier(engine, noEmbedPreExact, query, {
sourceId: opts?.sourceId,
sourceIds: opts?.sourceIds,
+ titleCandidates: titleResults,
});
stampEvidence(noEmbedHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
- const noEmbedSliced = noEmbedHopped.slice(offset, offset + limit);
+ // #3995 — guaranteed page-1 relational evidence: a fired arm's answer is
+ // often lexically unrecoverable, so its single-arm fused row can land
+ // beyond the limit slice on keyword-heavy corpora. Promote/inject before
+ // slicing (first page only; pure no-op when the arm didn't fire).
+ let noEmbedPool = noEmbedHopped;
+ let noEmbedRelSlot: RelationalEvidenceSlotDecision | undefined;
+ if (relationalList.length > 0) {
+ const r = ensureRelationalEvidenceSlot(noEmbedHopped, relationalList, limit, offset, {
+ cosineFloor: resolvedMode.evidence_cosine_floor,
+ });
+ noEmbedPool = r.pool;
+ noEmbedRelSlot = r.decision;
+ }
+ const noEmbedSliced = noEmbedPool.slice(offset, offset + limit);
// v0.32.3 search-lite: budget enforcement on the no-embedding-provider path.
const { results: noEmbedBudgeted, meta: noEmbedBudgetMeta } = enforceTokenBudget(noEmbedSliced, resolvedMode.tokenBudget);
await stampContentFlags(engine, noEmbedBudgeted);
@@ -1470,6 +1525,23 @@ export async function hybridSearch(
// vector didn't run, and whether the keyword arm itself came up empty
// (skipped-by-modality is not a keyword miss, hence the image gate).
pushDegraded(degraded, 'embed_unavailable', 'no_provider');
+ // #3808: meta names the degradation for programmatic callers, but a CLI
+ // human never saw it — mirror the embed-failure warn (once per process,
+ // stderr) with the diagnose reason so a silently keyword-only brain is
+ // visible the first time it ships results.
+ try {
+ const { diagnoseEmbedding } = await import('../ai/gateway.ts');
+ const diag = diagnoseEmbedding(providerProbe);
+ const reason = diag.ok ? 'provider_unreachable' : (diag.reason ?? 'provider_unreachable');
+ warnOncePerProcess(
+ 'search-vector-leg-unavailable',
+ `[gbrain] vector search unavailable (${reason}) — results are keyword-only. Run \`gbrain doctor\` to diagnose.`,
+ );
+ } catch {
+ // Fail-open like every sibling stage: the warning is best-effort and a
+ // gateway import/diagnose throw must never fail the already-computed
+ // keyword-only degraded results it exists to explain.
+ }
if (keywordResults.length === 0 && earlyModality !== 'image') {
pushDegraded(degraded, 'keyword_zero');
}
@@ -1486,6 +1558,7 @@ export async function hybridSearch(
...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0
? { token_budget: noEmbedBudgetMeta }
: {}),
+ ...(noEmbedRelSlot ? { relational_evidence_slot: noEmbedRelSlot } : {}),
});
return noEmbedBudgeted;
}
@@ -1804,9 +1877,16 @@ export async function hybridSearch(
await runPostFusionStages(engine, fallbackResults, postFusionOpts);
fallbackResults.sort((a, b) => b.score - a.score);
}
- const kwHopped = await applyAliasHop(engine, dedupResults(fallbackResults), query, {
+ const kwPreExact = await applyAliasHop(engine, dedupResults(fallbackResults), query, {
sourceId: opts?.sourceId,
sourceIds: opts?.sourceIds,
+ excludePrivate: opts?.excludePrivate,
+ });
+ // #1663 — structural exact-lookup tier (slug / exact-title identity).
+ const kwHopped = await applyExactLookupTier(engine, kwPreExact, query, {
+ sourceId: opts?.sourceId,
+ sourceIds: opts?.sourceIds,
+ titleCandidates: titleResults,
});
stampEvidence(kwHopped, { cosineFloor: resolvedMode.evidence_cosine_floor });
const kwSliced = kwHopped.slice(offset, offset + limit);
@@ -1999,9 +2079,22 @@ export async function hybridSearch(
// T3 — free-text alias hop. Runs AFTER rerank so a query that is a page's
// declared chosen name reliably surfaces that page regardless of how the
// reranker scored body chunks. Fail-open on pre-v110 brains.
- const aliasHopped = await applyAliasHop(engine, reranked, query, {
+ const preExact = await applyAliasHop(engine, reranked, query, {
sourceId: opts?.sourceId,
sourceIds: opts?.sourceIds,
+ excludePrivate: opts?.excludePrivate,
+ });
+
+ // #1663 — structural exact-lookup tier: a query that IS a page identity
+ // (slug / exact normalized title) gets that page at rank-1 regardless of
+ // how the scorers ranked body chunks. Supersession-filtered inside; reuses
+ // the already-fetched title arm (no extra queries); pure no-op for
+ // non-lookup-shaped queries. Runs after the alias hop so all three
+ // identity surfaces (alias, slug, title) share the same injection shape.
+ const aliasHopped = await applyExactLookupTier(engine, preExact, query, {
+ sourceId: opts?.sourceId,
+ sourceIds: opts?.sourceIds,
+ titleCandidates: titleResults,
});
// T4 — stamp evidence + create_safety so the agent's don't-duplicate
@@ -2064,12 +2157,30 @@ export async function hybridSearch(
// Preserve alias-hop exact matches: applyAliasHop injects the canonical
// page AFTER reranking, so it has no rerank_score. Without this it would
// be dropped whenever autocut cuts on the scored set (Codex P1).
- (x) => x.alias_hit === true,
+ // #1663: same guarantee for structural exact-lookup tier hits (slug /
+ // exact-title identity matches also arrive post-rerank, unscored).
+ (x) => x.alias_hit === true || x.exact_lookup !== undefined,
);
returnPool = r.kept;
autocutDecision = r.decision;
}
+ // #3995 — guaranteed page-1 relational evidence. A fired arm's answer is
+ // often lexically unrecoverable (unverified entity stub, single-arm RRF
+ // score), so its fused row can land beyond the limit slice on multi-arm
+ // corpora, and autocut's preserve predicate only covers alias hits — the
+ // relational row (no rerank_score) is exactly what a cut drops. Promote the
+ // fused row into the page-1 window, or re-inject the arm's top candidate
+ // when it was dropped entirely. First page only; pure no-op otherwise.
+ let relationalSlotDecision: RelationalEvidenceSlotDecision | undefined;
+ if (relationalList.length > 0 && effectiveModality !== 'image') {
+ const r = ensureRelationalEvidenceSlot(returnPool, relationalList, limit, offset, {
+ cosineFloor: resolvedMode.evidence_cosine_floor,
+ });
+ returnPool = r.pool;
+ relationalSlotDecision = r.decision;
+ }
+
const sliced = returnPool.slice(offset, offset + limit);
// v0.32.3 search-lite: budget enforcement at the main return path.
// hybridSearchCached used to be the only place this fired; now bare
@@ -2095,6 +2206,7 @@ export async function hybridSearch(
...(vectorPoolUnderfill ? { vector_pool_underfilled: vectorPoolUnderfill } : {}),
...(adaptiveDecision ? { adaptive_return: adaptiveDecision } : {}),
...(autocutDecision ? { autocut: autocutDecision } : {}),
+ ...(relationalSlotDecision ? { relational_evidence_slot: relationalSlotDecision } : {}),
});
return budgeted;
}
@@ -2198,6 +2310,13 @@ export async function hybridSearchCached(
// bare hybridSearch does (opts.detail ?? autoDetectDetail(query)) so an
// auto-detected `high` query keys like an explicit `high` one.
detail: opts?.detail ?? autoDetectDetail(query),
+ // #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
+ // remote-default (excludePrivate=true) caller now caches normally, on
+ // rows that can never be served to (or written by) a trusted
+ // private-included call.
+ excludePrivate: opts?.excludePrivate === true,
});
// Cache decision: opts.useCache (explicit) wins over global config; global
@@ -2230,6 +2349,10 @@ export async function hybridSearchCached(
// now-relative timestamp, which a persisted cache row can't express.
const dateFiltered =
Boolean(opts?.since ?? opts?.afterDate) || Boolean(opts?.until ?? opts?.beforeDate);
+ // #3985: type-filtered requests skip the cache — `types` is not part of
+ // knobsHash, so a filtered result set could be served to an unfiltered
+ // lookup (and vice versa). Mirrors the #3442 date-filter bypass.
+ const typeFiltered = (opts?.types?.length ?? 0) > 0;
// Offset pages are cache-hostile until the pre-slice POOL itself is what's
// stored: the cache holds the already offset/limit-sliced page (bare
// hybridSearch slices before returning), so a hit for any other offset
@@ -2240,6 +2363,12 @@ export async function hybridSearchCached(
// gated on cacheStatus === 'miss' below, so 'disabled' covers both) for
// offset>0 requests; offset===0 semantics are unchanged.
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
+ // original wholesale skip disabled the semantic cache for every remote MCP
+ // caller (excludePrivate=true is their default) — exactly the
+ // highest-volume beneficiaries of the ~50% cache savings.
const skipCache =
!cache.isEnabled() ||
(opts?.walkDepth ?? 0) > 0 ||
@@ -2247,6 +2376,7 @@ export async function hybridSearchCached(
isNonDefaultColumn ||
adaptiveReturnOn ||
dateFiltered ||
+ typeFiltered ||
pagedRequest;
let cacheStatus: 'hit' | 'miss' | 'disabled' = skipCache ? 'disabled' : 'miss';
@@ -2554,7 +2684,7 @@ export function rrfFusionWeighted(
lists: Array<{ list: SearchResult[]; k: number }>,
applyBoost = true,
): SearchResult[] {
- const scores = new Map<string, { result: SearchResult; score: number }>();
+ const scores = new Map<string, { result: SearchResult; score: number; keywordHit: boolean }>();
for (const { list, k } of lists) {
for (let rank = 0; rank < list.length; rank++) {
@@ -2565,8 +2695,12 @@ export function rrfFusionWeighted(
if (existing) {
existing.score += rrfScore;
+ // #3783 — OR-propagate lexical-arm membership: a row that fusion
+ // first saw via a vector list must still read keyword_hit when the
+ // keyword arm ALSO surfaced it.
+ if (r.keyword_hit === true) existing.keywordHit = true;
} else {
- scores.set(key, { result: r, score: rrfScore });
+ scores.set(key, { result: r, score: rrfScore, keywordHit: r.keyword_hit === true });
}
}
}
@@ -2587,7 +2721,10 @@ export function rrfFusionWeighted(
return entries
.sort((a, b) => b.score - a.score)
- .map(({ result, score }) => ({ ...result, score }));
+ .map(({ result, score, keywordHit }) =>
+ keywordHit && result.keyword_hit !== true
+ ? { ...result, score, keyword_hit: true }
+ : { ...result, score });
}
/**
@@ -2596,7 +2733,7 @@ export function rrfFusionWeighted(
* After accumulation: normalize to 0-1, then boost compiled_truth chunks.
*/
export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true): SearchResult[] {
- const scores = new Map<string, { result: SearchResult; score: number }>();
+ const scores = new Map<string, { result: SearchResult; score: number; keywordHit: boolean }>();
for (const list of lists) {
for (let rank = 0; rank < list.length; rank++) {
@@ -2607,8 +2744,10 @@ export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true)
if (existing) {
existing.score += rrfScore;
+ // #3783 — OR-propagate lexical-arm membership across merge order.
+ if (r.keyword_hit === true) existing.keywordHit = true;
} else {
- scores.set(key, { result: r, score: rrfScore });
+ scores.set(key, { result: r, score: rrfScore, keywordHit: r.keyword_hit === true });
}
}
}
@@ -2637,7 +2776,10 @@ export function rrfFusion(lists: SearchResult[][], k: number, applyBoost = true)
// Sort by boosted score descending
return entries
.sort((a, b) => b.score - a.score)
- .map(({ result, score }) => ({ ...result, score }));
+ .map(({ result, score, keywordHit }) =>
+ keywordHit && result.keyword_hit !== true
+ ? { ...result, score, keyword_hit: true }
+ : { ...result, score });
}
/**
diff --git a/src/core/search/mode.ts b/src/core/search/mode.ts
index 3ce6a453a1..6aedd671e6 100644
--- a/src/core/search/mode.ts
+++ b/src/core/search/mode.ts
@@ -878,7 +878,25 @@ export function attributeKnob<K extends keyof ModeBundle>(
// unreachable. Both bumps ship in the same release; no new key parts —
// the version bump alone invalidates. Same one-time global cold-miss
// pattern as the bumps above; refills within cache.ttl_seconds (3600s).
-export const KNOBS_HASH_VERSION = 21;
+//
+// bump 21→22 (mw2 wave): result-affecting stamp/injection changes for
+// identical knobs — #1663 exact-lookup injection, #3995 relational page-1
+// evidence slot, #3783 keyword_hit stamps, #4220 status. Pre-upgrade rows
+// (≤1h TTL) would be served missing the injected identity page + honesty
+// stamps, and CRAG then mis-grades them weak_semantic. Version-only
+// invalidation; one-time cold-miss spike on upgrade.
+//
+// bump 22→23 folds excludePrivate (#4352): the private-visibility posture
+// joins the key via ctx.excludePrivate (xp=). #4352 originally shipped a
+// wholesale cache skip for excludePrivate=true — but that posture is the
+// DEFAULT for every remote MCP caller, so the skip disabled the semantic
+// cache for exactly the highest-volume beneficiaries. Folding it instead
+// means cache rows written with private rows included can never serve a
+// private-excluding lookup and vice versa, and remote callers get their
+// ~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;
/**
* v0.36 (D8 / CDX-2) — second-arg context for the cache key. The
@@ -928,6 +946,16 @@ export interface KnobsHashContext {
* as col=/prov=. Undefined falls back to 'medium' (the documented default).
*/
detail?: 'low' | 'medium' | 'high';
+ /**
+ * v=23 (#4352 follow-up): the private-visibility posture for this call.
+ * `excludePrivate=true` (the default for every remote MCP caller) filters
+ * `visibility: private` pages out of every recall arm, so the result set
+ * differs from a trusted private-included run. Lives in ctx (not
+ * ResolvedSearchKnobs) because it's per-call trust posture, not a mode
+ * knob — same path as detail/hardExcludes. Undefined hashes like `false`
+ * (private included), matching enforcement's strict `=== true` semantics.
+ */
+ excludePrivate?: boolean;
}
export function knobsHash(
@@ -1047,6 +1075,14 @@ export function knobsHash(
// weak-top floor (v=18) already owns `acm=`. `?? 1` mirrors the defensive
// read of acj= above for partial-knobs callers.
`ack=${Math.max(1, Math.floor(knobs.autocut_min_keep ?? 1))}`,
+ // v=23 addition (#4352 follow-up, append-only): private-visibility
+ // posture. A private-included (trusted) write must never serve a
+ // private-excluding (remote-default) lookup and vice versa. Replaces
+ // #4352's wholesale skipCache bypass, which disabled the semantic cache
+ // for every remote MCP caller (excludePrivate=true is their default).
+ // Strict `=== true` mirrors the enforcement predicate so undefined and
+ // false (both private-included) hash identically.
+ `xp=${ctx?.excludePrivate === true ? 1 : 0}`,
];
const h = createHash('sha256');
h.update(parts.join('|'));
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
new file mode 100644
index 0000000000..fb8ed5d30c
--- /dev/null
+++ b/src/core/search/private-visibility.ts
@@ -0,0 +1,145 @@
+/**
+ * #4352 — page-level `visibility: private` enforcement for untrusted callers.
+ *
+ * Pages have carried `frontmatter.visibility` for a long time (the `remember`
+ * verb documents "private: local CLI reads only"), but nothing on the READ
+ * side ever enforced it for pages: a remote/MCP caller could retrieve a
+ * `visibility: private` page through search, recall's query arm, entity
+ * cards, context_pack — and the sibling read ops (get_page/fetch/list_pages,
+ * get_chunks/get_versions/get_timeline/get_raw_data, resolve_slugs,
+ * get_links/get_backlinks/traverse_graph). This module is the single
+ * trust+config resolver:
+ *
+ * ctx.remote === false → see everything (trusted local CLI)
+ * GBRAIN_REMOTE_PRIVATE_PAGES=1 → operator escape hatch, see everything
+ * config search.remote_private_pages ∈ {visible,true,1}
+ * → operator opt-out, see everything
+ * otherwise → exclude private pages (FAIL-CLOSED default)
+ *
+ * The SQL predicate itself lives in buildVisibilityClause (sql-ranking.ts)
+ * behind SearchOpts.excludePrivate; this resolver decides whether to set it.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+
+export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';
+
+/**
+ * Raw SQL predicate hiding `visibility: private` pages (absent visibility
+ * defaults to 'world'). Single source of truth for the fragment — consumed by
+ * buildVisibilityClause (search paths), both engines' listPages, the
+ * relational-arm hydrate, and get_page's fuzzy-candidate filter. `pageAlias`
+ * is a code-provided literal, never user input.
+ */
+export function privatePagesFilterFragment(pageAlias: string): string {
+ return `COALESCE(${pageAlias}.frontmatter->>'visibility', 'world') <> 'private'`;
+}
+
+/**
+ * Row-side twin of privatePagesFilterFragment for pages already fetched
+ * (get_page / fetch read one row by slug; re-querying just to filter would
+ * be a second round-trip). Same semantics: only the exact string 'private'
+ * hides a page; absent/other values default to world-visible.
+ */
+export function isPrivatePage(frontmatter: unknown): boolean {
+ return (
+ typeof frontmatter === 'object' &&
+ frontmatter !== null &&
+ (frontmatter as Record<string, unknown>).visibility === 'private'
+ );
+}
+
+/**
+ * Slugs an untrusted caller must not see enumerated: every in-scope page row
+ * for the slug is `visibility: private`. A slug with at least one non-private
+ * in-scope page stays visible (multi-source: private in one source, world in
+ * another). Slugs with no page row at all (dangling link endpoints) are not
+ * returned — they reveal nothing private. Shared by the #4352 read-op gates
+ * (get_page fuzzy candidates, resolve_slugs, link/graph endpoint filtering,
+ * and the content-op probes via slugHiddenFromCaller). `scope` follows the
+ * canonical precedence (federated array > scalar > nothing); with
+ * `includeDeleted` unset, only live rows are considered.
+ */
+export async function findPrivateOnlySlugs(
+ engine: BrainEngine,
+ slugs: string[],
+ scope: { sourceId?: string; sourceIds?: string[] } = {},
+ opts: { includeDeleted?: boolean } = {},
+): Promise<Set<string>> {
+ if (slugs.length === 0) return new Set();
+ const params: unknown[] = [slugs];
+ let scopeClause = '';
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ params.push(scope.sourceIds);
+ scopeClause = `AND p.source_id = ANY($${params.length}::text[])`;
+ } else if (scope.sourceId) {
+ params.push(scope.sourceId);
+ scopeClause = `AND p.source_id = $${params.length}`;
+ }
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT p.slug FROM pages p
+ WHERE p.slug = ANY($1::text[])
+ ${opts.includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
+ ${scopeClause}
+ GROUP BY p.slug
+ HAVING bool_and(NOT (${privatePagesFilterFragment('p')}))`,
+ params,
+ );
+ return new Set(rows.map(r => r.slug));
+}
+
+/**
+ * One-slug trust + probe combo for the sibling content ops (#4352
+ * remediation: get_chunks / get_versions / get_timeline / get_raw_data).
+ * True ⇒ the caller's read of `slug` must behave exactly like a missing
+ * page (no existence oracle). Trusted local + the operator opt-outs resolve
+ * to false via resolveExcludePrivatePages before any query runs. The probe
+ * considers DELETED rows too (fail-closed: a soft-deleted private page's
+ * history/timeline/raw data stays hidden).
+ */
+export async function slugHiddenFromCaller(
+ engine: BrainEngine,
+ remote: boolean | undefined,
+ slug: string,
+ scope: { sourceId?: string; sourceIds?: string[] } = {},
+): Promise<boolean> {
+ if (!(await resolveExcludePrivatePages(engine, remote))) return false;
+ const hidden = await findPrivateOnlySlugs(engine, [slug], scope, { includeDeleted: true });
+ return hidden.has(slug);
+}
+
+const CACHE_TTL_MS = 30_000;
+let cache = new WeakMap<BrainEngine, { at: number; expose: boolean }>();
+
+/** Test helper: drop the per-engine config cache. */
+export function __resetPrivateVisibilityCacheForTests(): void {
+ cache = new WeakMap();
+}
+
+/**
+ * Should this caller's page reads exclude `visibility: private` pages?
+ * `remote` follows the repo trust convention: anything that is not strictly
+ * `false` is untrusted. Config lookups are cached 30s per engine; a failed
+ * lookup counts as "not opted out" (fail-closed).
+ */
+export async function resolveExcludePrivatePages(
+ engine: BrainEngine,
+ remote: boolean | undefined,
+): Promise<boolean> {
+ if (remote === false) return false; // trusted local CLI sees everything
+ if (process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1') return false; // incident escape hatch
+ const hit = cache.get(engine);
+ let expose: boolean;
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) {
+ expose = hit.expose;
+ } else {
+ try {
+ const v = await engine.getConfig(REMOTE_PRIVATE_PAGES_KEY);
+ expose = v === 'visible' || v === 'true' || v === '1';
+ } catch {
+ expose = false; // config unreadable → enforce (fail-closed)
+ }
+ cache.set(engine, { at: Date.now(), expose });
+ }
+ return !expose;
+}
diff --git a/src/core/search/query-intent.ts b/src/core/search/query-intent.ts
index 028b6f7b38..4acb2d5469 100644
--- a/src/core/search/query-intent.ts
+++ b/src/core/search/query-intent.ts
@@ -488,3 +488,70 @@ export function conceptNudge(query: string): string | null {
`A nonzero search count is not proof of completeness.`
);
}
+
+// ─────────────────────────────────────────────────────────
+// #1663 — query-shape router (factual vs open)
+// ─────────────────────────────────────────────────────────
+
+/**
+ * #1663 — coarse query SHAPE, orthogonal to intent:
+ *
+ * 'factual' — a bounded lookup with a small, checkable answer (who/when/
+ * where/which, attribute possessives, quoted names, slug-ish
+ * tokens, short entity lookups). Retrieval either has the row
+ * or it doesn't; the CRAG gate's retrieval-side escalation is
+ * worth one re-run here.
+ * 'open' — synthesis-shaped (how/why/explain/summarize/compare,
+ * long multi-clause). When retrieval confidence is weak on an
+ * open query, MORE retrieval rarely fixes it — the honest
+ * escalation target is `think` (multi-round gather+synthesis).
+ *
+ * Consumed by the CRAG confidence gate (crag.ts + the `query` op) and
+ * surfaced in the retrieval response meta for auditability.
+ */
+export type QueryShape = 'factual' | 'open';
+
+const OPEN_SHAPE_PATTERNS: RegExp[] = [
+ /^\s*(how|why)\b/i,
+ /\b(explain|describe|summariz\w*|overview of|walk me through|brainstorm|compare|contrast|catch me up|tell me about|history of)\b/i,
+ /\bwhat\s+do\s+(i|we|you)\s+know\s+about\b/i,
+ /\b(pros\s+and\s+cons|trade-?offs|implications|open\s+questions)\b/i,
+];
+
+const FACTUAL_SHAPE_PATTERNS: RegExp[] = [
+ /^\s*(who|whom|whose|when|where|which)\b/i,
+ // Attribute possessive / attribute-of lookups ("alice's email", "the url of X").
+ /\b(email|phone|address|birthday|date|deadline|url|link|title|name|number|id|slug|handle)\b/i,
+ /["'“”][^"'“”]+["'“”]/, // quoted phrase — exact-match intent
+ /\b[a-z0-9]+(?:-[a-z0-9]+){1,}\b/i, // slug-like token
+];
+
+/** Word-count threshold above which an unmatched query reads as open-ended. */
+const OPEN_SHAPE_TOKEN_THRESHOLD = 9;
+
+export function classifyQueryShape(query: string): QueryShape {
+ const q = query.trim();
+ if (!q) return 'open';
+ // Explicit factual leads win over embedded open verbs: "who explained the
+ // outage" is still a who-lookup.
+ if (/^\s*(who|whom|whose|when|where|which)\b/i.test(q)) return 'factual';
+ if (matches(OPEN_SHAPE_PATTERNS, q)) return 'open';
+ if (isConceptShapedQuery(q)) return 'open'; // set-by-meaning ≈ open-ended
+ if (matches(FACTUAL_SHAPE_PATTERNS, q)) return 'factual';
+ // Unmatched: short queries are lookups; long multi-clause reads as open.
+ return q.split(/\s+/).length > OPEN_SHAPE_TOKEN_THRESHOLD ? 'open' : 'factual';
+}
+
+/**
+ * #1663 — gate for the structural exact-lookup tier (exact-lookup.ts): a
+ * query short enough to plausibly BE a page identity (slug, exact title,
+ * declared alias). Mirrors the alias hop's ≤6-token guard; slug-shaped
+ * single tokens ('people/alice-example') always qualify. Pure + cheap —
+ * called per query on the hot path.
+ */
+export function isLookupShapedQuery(query: string): boolean {
+ const q = query.trim();
+ if (!q) return false;
+ if (!/\s/.test(q) && q.includes('/')) return true; // slug-shaped
+ return q.split(/\s+/).length <= 6;
+}
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 7a8850ba0a..fe030f2385 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -28,7 +28,9 @@ import type { BrainEngine } from '../engine.ts';
import type { SearchResult, PageType, RelationalFanoutRow } from '../types.ts';
import { createAuditWriter } from '../audit/audit-writer.ts';
import { resolveEntitySlugWithSource } from '../entities/resolve.ts';
+import { buildVisibilityClause } from './sql-ranking.ts';
import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from './relational-intent.ts';
+import { stampEvidence, type EvidenceOpts } from './evidence.ts';
export interface RelationalArmOpts {
sourceId?: string;
@@ -36,6 +38,13 @@ export interface RelationalArmOpts {
depth?: number;
limit?: number;
vocab?: RelationVocab;
+ /**
+ * #4352 remediation — hide `visibility: private` pages from the arm's
+ * hydrated candidates. hybridSearch threads the caller's resolved gate
+ * (resolveExcludePrivatePages) here, same as the keyword/vector arms;
+ * without it a remote relational query leaked private titles + snippets.
+ */
+ excludePrivate?: boolean;
onMeta?: (meta: RelationalArmMeta) => void;
}
@@ -98,11 +107,16 @@ async function resolveSeedScoped(
return out;
}
-/** Batch-hydrate fanout rows into SearchResult rows in fanout (ranked) order. */
+/** Batch-hydrate fanout rows into SearchResult rows in fanout (ranked) order.
+ * #4352 remediation: the SELECT surfaces titles + compiled_truth snippets, so
+ * it applies the full shared visibility clause (deleted + archived-source +
+ * quarantine, plus the private predicate when excludePrivate) — pre-fix it
+ * filtered on deleted_at alone and leaked private/archived pages. */
async function hydrate(
engine: BrainEngine,
rows: RelationalFanoutRow[],
seedSlug: string,
+ excludePrivate: boolean,
): Promise<SearchResult[]> {
if (rows.length === 0) return [];
const slugs = Array.from(new Set(rows.map(r => r.slug)));
@@ -112,7 +126,8 @@ async function hydrate(
`SELECT p.id AS page_id, p.slug, p.source_id, p.title, p.type,
LEFT(p.compiled_truth, 240) AS synopsis
FROM pages p
- WHERE p.slug = ANY($1::text[]) AND p.deleted_at IS NULL`,
+ JOIN sources s ON s.id = p.source_id
+ WHERE p.slug = ANY($1::text[]) ${buildVisibilityClause('p', 's', { excludePrivate })}`,
[slugs],
);
const byKey = new Map<string, typeof pageRows[number]>();
@@ -146,6 +161,91 @@ async function hydrate(
return out;
}
+/**
+ * #3995 — decision stamp for the guaranteed page-1 relational evidence slot.
+ * Surfaced through HybridSearchMeta.relational_evidence_slot so `--explain`
+ * consumers can audit why a low-fused-score row appears on the first page.
+ */
+export interface RelationalEvidenceSlotDecision {
+ action: 'promoted' | 'injected';
+ slug: string;
+ source_id: string;
+ /** promoted only: the 0-based fused rank the row was lifted from. */
+ from_rank?: number;
+}
+
+/**
+ * #3995 — guarantee page-1 evidence for a FIRED relational arm.
+ *
+ * A relational answer is often lexically unrecoverable (unverified entity
+ * stub, single-arm RRF score), so the fused row can land beyond the `limit`
+ * slice (fusion overflow) or be dropped entirely by autocut (which only
+ * preserves alias hits). When the arm fired, at least one of its pages must
+ * survive to the first page or the feature silently no-ops.
+ *
+ * Pure (returns a new array; never mutates inputs). Page-level check on
+ * `(source_id, slug)`:
+ * - some relational page already in the top-`limit` window → no-op;
+ * - best-ranked fused relational row sits beyond the window → PROMOTE it
+ * into slot `limit-1` (keeps its real fused score);
+ * - no relational page in the pool at all (autocut/trim dropped it) →
+ * INJECT `relationalList[0]` at slot `limit-1` (score clamped just below
+ * its new predecessor so ordering stays monotone).
+ *
+ * First page only: `offset > 0` is a pure no-op (paginating a guaranteed
+ * slot is incoherent — the row would repeat on every page).
+ */
+export function ensureRelationalEvidenceSlot(
+ pool: SearchResult[],
+ relationalList: SearchResult[],
+ limit: number,
+ offset: number,
+ evidenceOpts?: EvidenceOpts,
+): { pool: SearchResult[]; decision?: RelationalEvidenceSlotDecision } {
+ if (offset > 0 || limit <= 0 || relationalList.length === 0) return { pool };
+ const pageKey = (r: SearchResult) => `${r.source_id ?? 'default'}:${r.slug}`;
+ const relKeys = new Set(relationalList.map(pageKey));
+
+ const window = Math.min(limit, pool.length);
+ for (let i = 0; i < window; i++) {
+ if (relKeys.has(pageKey(pool[i]))) return { pool }; // evidence already on page 1
+ }
+
+ // Fusion overflow: the arm's best fused row survived ranking but sits past
+ // the slice boundary — promote it into the last page-1 slot.
+ for (let i = limit; i < pool.length; i++) {
+ if (!relKeys.has(pageKey(pool[i]))) continue;
+ const out = pool.slice();
+ const [row] = out.splice(i, 1);
+ out.splice(limit - 1, 0, row);
+ return {
+ pool: out,
+ decision: { action: 'promoted', slug: row.slug, source_id: row.source_id ?? 'default', from_rank: i },
+ };
+ }
+
+ // Dropped entirely (autocut / trim): re-inject the arm's top candidate.
+ const out = pool.slice();
+ const insertAt = Math.min(limit - 1, out.length);
+ const prev = insertAt > 0 ? out[insertAt - 1] : undefined;
+ const top = relationalList[0];
+ // Clamp just below the predecessor when the raw arm score is non-positive
+ // OR would exceed it — the returned page must stay monotone.
+ const row =
+ prev && (!(top.score > 0) || top.score > prev.score)
+ ? { ...top, score: Math.max(0, prev.score * 0.999) }
+ : { ...top };
+ // The injected row is a raw arm row that never saw the pipeline's
+ // stampEvidence pass (which runs before this slot) — stamp it here so every
+ // page-1 row carries the evidence/create_safety contract.
+ stampEvidence([row], evidenceOpts);
+ out.splice(insertAt, 0, row);
+ return {
+ pool: out,
+ decision: { action: 'injected', slug: row.slug, source_id: row.source_id ?? 'default' },
+ };
+}
+
/**
* Build the relational recall arm. Returns an empty list (pure no-op) when the
* query isn't relational or no seed resolves. Never throws.
@@ -204,7 +304,7 @@ export async function buildRelationalArm(
.map(r => ({ row: r, combined: r.hop + bByKey.get(`${r.source_id}:${r.slug}`)!.hop }))
.sort((x, y) => x.combined - y.combined || x.row.slug.localeCompare(y.row.slug))
.map(x => x.row);
- const list = await hydrate(engine, shared, parsed.seeds.join(' ↔ '));
+ const list = await hydrate(engine, shared, parsed.seeds.join(' ↔ '), opts.excludePrivate === true);
meta.fired = list.length > 0;
return finish(list);
}
@@ -220,7 +320,7 @@ export async function buildRelationalArm(
sourceId: srcIds.length === 1 ? srcIds[0] : undefined,
sourceIds: srcIds.length > 1 ? srcIds : undefined,
});
- const list = await hydrate(engine, rows, resolved[0].slug);
+ const list = await hydrate(engine, rows, resolved[0].slug, opts.excludePrivate === true);
meta.fired = list.length > 0;
return finish(list);
} catch (err) {
diff --git a/src/core/search/snippet-cap.ts b/src/core/search/snippet-cap.ts
new file mode 100644
index 0000000000..02b201de8a
--- /dev/null
+++ b/src/core/search/snippet-cap.ts
@@ -0,0 +1,51 @@
+/**
+ * #3800: subagent token economy — cap the `chunk_text` payload of search
+ * results at the OP layer (search + query), so an LLM tool loop reading
+ * 20 results doesn't pay for 20 full chunks (~400 tokens each) when a
+ * ~300-char snippet answers "is this the right page?". The full text is one
+ * `get_page` away, and the marker tells the agent exactly that.
+ *
+ * Resolution (op layer): explicit `snippet_chars` param wins; else, when the
+ * caller is a subagent tool loop (`ctx.viaSubagent`), the
+ * `agent.search_snippet_chars` config applies (default 300; 0 = full text);
+ * every other caller gets full text — this changes nothing for humans, MCP
+ * clients, or internal consumers.
+ *
+ * Truncation is chunk_text-only and NON-mutating: results may be shared with
+ * a pending semantic-cache write (hybridSearchCached stores fire-and-forget),
+ * so capped copies are new objects — a truncated snippet must never be what
+ * gets cached.
+ */
+
+/** Default snippet budget (chars) for subagent callers when config is unset. */
+export const DEFAULT_AGENT_SNIPPET_CHARS = 300;
+
+export function buildSnippetMarker(slug: string | undefined, droppedChars: number): string {
+ const target = slug && slug.length > 0 ? `get_page ${slug}` : 'get_page <slug>';
+ return `… [truncated ${droppedChars} chars — ${target} for full text]`;
+}
+
+/**
+ * Cap each result's `chunk_text` at `chars` characters, appending a marker
+ * naming the recovery move. `chars <= 0` (or non-finite) means "no cap".
+ * Returns the ORIGINAL array (same object identities) when nothing needed
+ * truncation, so untouched paths stay allocation-free.
+ */
+export function applySnippetCap<T extends { chunk_text?: unknown; slug?: unknown }>(
+ results: T[],
+ chars: number,
+): T[] {
+ if (!Number.isFinite(chars) || chars <= 0) return results;
+ let anyTruncated = false;
+ const out = results.map((r) => {
+ const text = r.chunk_text;
+ if (typeof text !== 'string' || text.length <= chars) return r;
+ anyTruncated = true;
+ const slug = typeof r.slug === 'string' ? r.slug : undefined;
+ return {
+ ...r,
+ chunk_text: text.slice(0, chars) + buildSnippetMarker(slug, text.length - chars),
+ };
+ });
+ return anyTruncated ? out : results;
+}
diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.ts
index f9dccc8323..078bea7350 100644
--- a/src/core/search/sql-ranking.ts
+++ b/src/core/search/sql-ranking.ts
@@ -19,6 +19,7 @@
import { quarantineFilterFragment } from '../quarantine.ts';
import { unverifiedExtractionFragment } from '../extraction-review.ts';
+import { privatePagesFilterFragment } from './private-visibility.ts';
/**
* Escape `%`, `_`, and `\` so a string can be used as a LIKE prefix literal.
@@ -169,11 +170,30 @@ export function buildHardExcludeClause(slugColumn: string, prefixes: string[]):
* @returns raw SQL fragment, e.g.
* `AND p.deleted_at IS NULL AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')`
*/
-export function buildVisibilityClause(pageAlias: string, sourceAlias: string): string {
+export function buildVisibilityClause(
+ pageAlias: string,
+ sourceAlias: string,
+ opts?: {
+ /**
+ * #4352 — untrusted-caller predicate: hide pages whose frontmatter
+ * carries `visibility: private` (absent visibility defaults to 'world').
+ * Set from SearchOpts.excludePrivate by both engines; callers resolve
+ * trust + the config gate via resolveExcludePrivatePages
+ * (search/private-visibility.ts). Off by default — trusted local reads
+ * are unchanged.
+ */
+ excludePrivate?: boolean;
+ },
+): string {
// Single source of truth for the quarantine SQL lives in quarantine.ts so
// the marker key + filter can't drift from the search filter (#1699).
const quarantine = quarantineFilterFragment(pageAlias);
- return `AND ${pageAlias}.deleted_at IS NULL AND NOT ${sourceAlias}.archived AND ${quarantine}`;
+ // #4352 remediation: the predicate text lives ONCE in private-visibility.ts
+ // (shared with listPages + the relational-arm hydrate) so it cannot drift.
+ const privateClause = opts?.excludePrivate
+ ? ` AND ${privatePagesFilterFragment(pageAlias)}`
+ : '';
+ return `AND ${pageAlias}.deleted_at IS NULL AND NOT ${sourceAlias}.archived AND ${quarantine}${privateClause}`;
}
// ============================================================
diff --git a/src/core/serve-sweep-runner.ts b/src/core/serve-sweep-runner.ts
new file mode 100644
index 0000000000..3e20da90c2
--- /dev/null
+++ b/src/core/serve-sweep-runner.ts
@@ -0,0 +1,144 @@
+/**
+ * Serve-delegated maintenance-sweep job runner (#677) — the serve process's
+ * execution half of the sweep_start / sweep_status IPC kinds (wire shapes +
+ * validation in context/sweep-ipc.ts; socket plumbing in
+ * context/resolve-ipc.ts; CLI half in commands/sweep-delegate.ts).
+ *
+ * Mirror of serve-sync-runner.ts, minus the abort machinery: a sweep is a
+ * BOUNDED run (default 5s budget, runMaintenanceSweep never throws), so the
+ * client just polls to completion. One job at a time, in-memory,
+ * module-singleton; the last TERMINAL job is retained (keyed by clientToken)
+ * so a client that lost the start ack attaches instead of duplicate-running.
+ *
+ * After a successful sweep the runner kicks maybeDrainDeferredEmbeds — the
+ * lock owner closes its own embedding loop (a no-op unless a prior delegated
+ * sync deferred embeds), so a hand-run `gbrain sweep --once` against a live
+ * serve converges the same backlog `embed --stale` would if it could connect.
+ */
+
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from './engine.ts';
+import { runMaintenanceSweep, type SweepReport } from './sweep.ts';
+import { maybeDrainDeferredEmbeds } from './serve-sync-runner.ts';
+import {
+ validateDelegatedSweepOptions,
+ type DelegatedSweepState,
+ type SweepStartResponse,
+ type SweepStatusResponse,
+} from './context/sweep-ipc.ts';
+
+interface DelegatedSweepJob {
+ id: string;
+ clientToken: string;
+ state: DelegatedSweepState;
+ sourceId?: string;
+ startedAt: number;
+ finishedAt?: number;
+ report?: SweepReport;
+ jobError?: string;
+ settled: Promise<void>;
+}
+
+/** Running job, or the retained last terminal job (replaced by the next start). */
+let current: DelegatedSweepJob | null = null;
+
+const isTerminal = (s: DelegatedSweepState): boolean => s === 'done' || s === 'error';
+
+function log(msg: string): void {
+ process.stderr.write(`[serve-sweep] ${msg}\n`);
+}
+
+/**
+ * Handle a sweep_start request. `rawOptions` is the untrusted wire payload —
+ * validated here (the runner is the single authority) even though the IPC
+ * layer types it.
+ */
+export function startDelegatedSweep(
+ engine: BrainEngine,
+ rawOptions: unknown,
+ clientToken: string,
+ opts: { boundSourceId?: string } = {},
+): SweepStartResponse {
+ if (typeof clientToken !== 'string' || clientToken.length === 0 || clientToken.length > 128) {
+ return { ok: false, protocol: 2, error: 'invalid_options:clientToken' };
+ }
+ // Token attach: a retry after a lost ack finds its own job.
+ if (current && current.clientToken === clientToken) {
+ return isTerminal(current.state)
+ ? { ok: true, protocol: 2, jobId: current.id, completed: true }
+ : { ok: true, protocol: 2, jobId: current.id };
+ }
+ if (current && !isTerminal(current.state)) {
+ return { ok: false, protocol: 2, error: 'busy', jobId: current.id };
+ }
+ const v = validateDelegatedSweepOptions(rawOptions);
+ if (!v.ok) return { ok: false, protocol: 2, error: v.error };
+ const options = v.options;
+ if (options.sourceId && opts.boundSourceId && options.sourceId !== opts.boundSourceId) {
+ return { ok: false, protocol: 2, error: 'source_mismatch' };
+ }
+
+ const job: DelegatedSweepJob = {
+ id: randomUUID(),
+ clientToken,
+ state: 'running',
+ sourceId: options.sourceId ?? opts.boundSourceId ?? 'default',
+ startedAt: Date.now(),
+ settled: Promise.resolve(),
+ };
+ current = job;
+
+ job.settled = (async () => {
+ try {
+ log(`start job=${job.id} source=${job.sourceId} budgetMs=${options.budgetMs ?? 5000} batchLimit=${options.batchLimit ?? 20}`);
+ const report = await runMaintenanceSweep(engine, {
+ sourceId: job.sourceId,
+ ...(options.budgetMs !== undefined ? { budgetMs: options.budgetMs } : {}),
+ ...(options.batchLimit !== undefined ? { batchLimit: options.batchLimit } : {}),
+ log: (msg: string) => log(`job=${job.id} ${msg}`),
+ });
+ job.report = report;
+ job.state = 'done';
+ log(
+ `done job=${job.id} facts=${report.factsReconciled} links=${report.linksExtracted} ` +
+ `timeline=${report.timelineExtracted} corpus=${report.corpusIngested} in=${report.durationMs}ms`,
+ );
+ // Lock-owner embed loop: no-op unless a prior delegated sync deferred
+ // embeds. Fire-and-forget — the sweep result never waits on embeds.
+ void maybeDrainDeferredEmbeds(engine);
+ } catch (e) {
+ // runMaintenanceSweep never throws by contract; this catch covers the
+ // structural impossible-path so a poll can still settle to 'error'.
+ job.jobError = e instanceof Error ? e.message : String(e);
+ job.state = 'error';
+ log(`error job=${job.id}: ${job.jobError}`);
+ } finally {
+ job.finishedAt = Date.now();
+ }
+ })();
+
+ return { ok: true, protocol: 2, jobId: job.id };
+}
+
+/** Handle a sweep_status poll. */
+export function getDelegatedSweepStatus(jobId: string): SweepStatusResponse {
+ const job = current;
+ if (!job || job.id !== jobId) {
+ return { ok: false, protocol: 2, error: 'unknown_job' };
+ }
+ return {
+ ok: true,
+ protocol: 2,
+ state: job.state,
+ sourceId: job.sourceId,
+ startedAt: job.startedAt,
+ elapsedMs: (job.finishedAt ?? Date.now()) - job.startedAt,
+ ...(job.state === 'done' && job.report ? { report: job.report } : {}),
+ ...(job.state === 'error' && job.jobError ? { jobError: job.jobError } : {}),
+ };
+}
+
+/** Test seam: reset the module singleton (serial tests only). */
+export function __resetDelegatedSweepForTests(): void {
+ current = null;
+}
diff --git a/src/core/skillopt/audit.ts b/src/core/skillopt/audit.ts
index 092ec65e09..110a215694 100644
--- a/src/core/skillopt/audit.ts
+++ b/src/core/skillopt/audit.ts
@@ -34,9 +34,13 @@ export type SkilloptEvent =
total_steps: number; baseline_sel_score?: number; best_sel_score?: number;
baseline_test_score?: number; test_score?: number; final_cost_usd: number;
ts: string }
+ // #3516: 'error' is the truthful catch-all for unrecognized failures
+ // (provider errors, no_pricing hard-fails, bugs). 'sigint' is reserved for
+ // an actual SIGINT interrupt — pre-fix the catch-all logged every error as
+ // 'sigint', which made the audit trail lie about why runs died.
| { kind: 'abort'; run_id: string; skill: string; reason: 'budget_exhausted' |
- 'runtime_exhausted' | 'dirty_tree' | 'lock_busy' | 'sentinel_pending' |
- 'bundled_skill_no_flag' | 'd_sel_too_small' | 'sigint'; detail?: string;
+ 'runtime_exceeded' | 'dirty_tree' | 'lock_busy' | 'sentinel_pending' |
+ 'bundled_skill_no_flag' | 'd_sel_too_small' | 'sigint' | 'error'; detail?: string;
ts: string };
let _writer: AuditWriter<SkilloptEvent> | null = null;
diff --git a/src/core/skillopt/held-out.ts b/src/core/skillopt/held-out.ts
index 14f154957f..74e0e51658 100644
--- a/src/core/skillopt/held-out.ts
+++ b/src/core/skillopt/held-out.ts
@@ -110,6 +110,8 @@ export interface HeldOutGateOpts {
heldOutTasks: BenchmarkTask[];
targetModel: string;
judgeModel: string;
+ /** #4119 — in-rollout-loop deadline (epoch ms); see ValidateGateOpts. */
+ deadlineMs?: number;
abortSignal?: AbortSignal;
}
@@ -138,6 +140,7 @@ export async function runHeldOutGate(opts: HeldOutGateOpts): Promise<HeldOutGate
tasks: opts.heldOutTasks,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ ...(opts.deadlineMs !== undefined ? { deadlineMs: opts.deadlineMs } : {}),
...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),
};
const baselineScore = await scoreSkillOnTasks({ ...scoreOpts, skillText: opts.baselineSkillText });
diff --git a/src/core/skillopt/help.ts b/src/core/skillopt/help.ts
index c5377e7a49..f8a544a028 100644
--- a/src/core/skillopt/help.ts
+++ b/src/core/skillopt/help.ts
@@ -48,7 +48,10 @@ Modes:
Safety:
--max-cost-usd N Hard cap. Default 5.00. Preflight refuses
- if estimate exceeds.
+ if estimate exceeds. 0 disables the cap
+ (unpriced model ids then warn-once instead
+ of aborting with no_pricing).
+ --no-max-cost Shorthand for --max-cost-usd 0.
--max-runtime-min N Wall-clock cap. Default 30
--force Bypass dirty-working-tree refusal (rare)
--resume <run-id> Resume a prior interrupted run
diff --git a/src/core/skillopt/orchestrator.ts b/src/core/skillopt/orchestrator.ts
index 99df6e1c42..128949753f 100644
--- a/src/core/skillopt/orchestrator.ts
+++ b/src/core/skillopt/orchestrator.ts
@@ -321,8 +321,13 @@ async function runOptimizationLoop(
// Budget tracker for the whole run. BudgetExhausted propagates as
// MUST_ABORT through every gateway.chat call.
+ //
+ // #3516: maxCostUsd === 0 means "no cap" (--no-max-cost / --max-cost-usd 0).
+ // Passing undefined switches the tracker's pricing-miss behavior from a
+ // hard BudgetExhausted(no_pricing) abort to the legacy warn-once path, so
+ // unpriced model ids (openrouter:*, litellm:*) can run at the user's own risk.
const tracker = new BudgetTracker({
- maxCostUsd: opts.maxCostUsd,
+ ...(opts.maxCostUsd > 0 ? { maxCostUsd: opts.maxCostUsd } : {}),
label: `skillopt:${skillName}`,
});
@@ -331,14 +336,22 @@ async function runOptimizationLoop(
// Run the loop inside withBudgetTracker so every nested gateway call composes.
let outcome: 'accepted' | 'no_improvement' | 'aborted' | 'errored' = 'no_improvement';
+ // #3516: why a run aborted/errored — surfaced on the receipt + CLI, not
+ // just the audit JSONL, so a failed run is never a silent "Outcome: errored".
+ let abortReason: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error' | undefined;
+ let abortDetail: string | undefined;
let finalText = checkpoint.best_skill_text;
let totalStepsRun = 0;
// Hoisted for the receipt (computed inside the budget-tracker closure).
let baselineSelScore = 0;
let testScore: number | undefined;
let baselineTestScore: number | undefined;
- // maxRuntimeMin enforcement: wall-clock deadline checked between steps. A
- // breach throws `skillopt_runtime_exceeded`, caught below → outcome 'aborted'
+ // maxRuntimeMin enforcement (#4119): wall-clock deadline checked between
+ // steps AND inside every gate's rollout loop (deadlineMs is threaded into
+ // runValidationGate / scoreSkillOnTasks / runHeldOutGate, checked before
+ // each individual rollout) — a long batch can no longer blow past
+ // --max-runtime by a whole gate's worth of rollouts. A breach throws
+ // `skillopt_runtime_exceeded`, caught below → outcome 'aborted'
// (no partial commit beyond whatever already passed every gate).
const deadline = Date.now() + opts.maxRuntimeMin * 60_000;
@@ -353,6 +366,7 @@ async function runOptimizationLoop(
bestScore: -1, // any score > -1 + 0.05 accepts; we just want the score.
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ deadlineMs: deadline,
});
if (checkpoint!.best_sel_score === 0) {
// Fresh run; set baseline.
@@ -378,6 +392,7 @@ async function runOptimizationLoop(
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
runsPerTask: 1,
+ deadlineMs: deadline,
});
const rewrite = await runOneShotRewrite({
skillBodyText: baselineBody,
@@ -397,6 +412,7 @@ async function runOptimizationLoop(
candidateSkillText: candidate,
baselineSkillText: baselineText,
heldOutTasks,
+ deadlineMs: deadline,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
});
@@ -409,6 +425,7 @@ async function runOptimizationLoop(
tasks: split.sel,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ deadlineMs: deadline,
});
checkpoint!.best_sel_score = score;
checkpoint!.best_skill_text = candidate;
@@ -458,6 +475,7 @@ async function runOptimizationLoop(
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
runsPerTask: 1,
+ deadlineMs: deadline,
});
// Partition into successes vs failures (>= 0.5 threshold). Reflect
// gets the actual scored trajectories so failure-mode + success-mode
@@ -517,6 +535,7 @@ async function runOptimizationLoop(
bestScore: checkpoint!.best_sel_score,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ deadlineMs: deadline,
});
// Ablation (cat31 config D): disableValidationGate greedy-accepts any
@@ -537,6 +556,7 @@ async function runOptimizationLoop(
candidateSkillText: applied.newText,
baselineSkillText: baselineText,
heldOutTasks,
+ deadlineMs: deadline,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
});
@@ -659,6 +679,7 @@ async function runOptimizationLoop(
tasks: split.test,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ deadlineMs: deadline,
});
baselineTestScore = await scoreSkillOnTasks({
engine: opts.engine,
@@ -666,6 +687,7 @@ async function runOptimizationLoop(
tasks: split.test,
targetModel: opts.targetModel,
judgeModel: opts.judgeModel,
+ deadlineMs: deadline,
});
}
});
@@ -673,32 +695,31 @@ async function runOptimizationLoop(
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('BudgetExhausted') || msg.includes('budget_exhausted')) {
outcome = 'aborted';
- logEvent({
- kind: 'abort',
- run_id: runId,
- skill: skillName,
- reason: 'budget_exhausted',
- detail: msg,
- } as never);
+ abortReason = 'budget_exhausted';
+ abortDetail = msg;
} else if (msg.includes('skillopt_runtime_exceeded')) {
outcome = 'aborted';
- logEvent({
- kind: 'abort',
- run_id: runId,
- skill: skillName,
- reason: 'runtime_exceeded',
- detail: `exceeded --max-runtime-min ${opts.maxRuntimeMin}`,
- } as never);
+ abortReason = 'runtime_exceeded';
+ abortDetail = `exceeded --max-runtime-min ${opts.maxRuntimeMin}`;
+ } else if (msg.includes('SIGINT')) {
+ outcome = 'aborted';
+ abortReason = 'sigint';
+ abortDetail = msg;
} else {
+ // #3516: truthful catch-all. Pre-fix this logged reason:'sigint' for
+ // EVERY unrecognized error (provider failures, no_pricing hard-fails),
+ // which made the audit trail lie about why the run died.
outcome = 'errored';
- logEvent({
- kind: 'abort',
- run_id: runId,
- skill: skillName,
- reason: 'sigint',
- detail: msg,
- } as never);
+ abortReason = 'error';
+ abortDetail = msg;
}
+ logEvent({
+ kind: 'abort',
+ run_id: runId,
+ skill: skillName,
+ reason: abortReason,
+ detail: abortDetail,
+ } as never);
}
// If --no-mutate or bundled+!allowMutateBundled: write proposed.md instead.
@@ -732,6 +753,10 @@ async function runOptimizationLoop(
started_at: checkpoint.started_at,
ended_at: new Date().toISOString(),
outcome,
+ // #3516: abort/error detail rides the receipt so --json consumers and the
+ // CLI's stderr summary both see WHY, not just that the run died.
+ ...(abortReason !== undefined ? { abort_reason: abortReason } : {}),
+ ...(abortDetail !== undefined ? { abort_detail: abortDetail } : {}),
baseline_sel_score: baselineSelScore,
best_sel_score: checkpoint.best_sel_score,
...(testScore !== undefined ? { test_score: testScore } : {}),
diff --git a/src/core/skillopt/preflight.ts b/src/core/skillopt/preflight.ts
index 9f2e9dcc08..7310420921 100644
--- a/src/core/skillopt/preflight.ts
+++ b/src/core/skillopt/preflight.ts
@@ -150,7 +150,8 @@ export function estimateCost(opts: PreflightOpts): PreflightEstimate {
[opts.optimizerModel]: cachedReflectCost,
[opts.judgeModel]: cachedJudgeCost,
},
- exceeds_cap: total > opts.maxCostUsd,
+ // #3516: maxCostUsd === 0 means uncapped (--no-max-cost) — never refuse.
+ exceeds_cap: opts.maxCostUsd > 0 && total > opts.maxCostUsd,
};
}
@@ -165,7 +166,7 @@ export function formatPreflightReport(est: PreflightEstimate, opts: PreflightOpt
` Reflects: ${est.reflect_calls.toLocaleString()} calls`,
` Judges: ${est.judge_calls.toLocaleString()} calls`,
` Tokens: ~${(est.est_input_tokens / 1000).toFixed(0)}K in / ~${(est.est_output_tokens / 1000).toFixed(0)}K out`,
- ` Est. cost: $${est.est_cost_usd.toFixed(2)} (cap: $${opts.maxCostUsd.toFixed(2)})`,
+ ` Est. cost: $${est.est_cost_usd.toFixed(2)} (cap: ${opts.maxCostUsd > 0 ? `$${opts.maxCostUsd.toFixed(2)}` : 'uncapped'})`,
est.exceeds_cap ? ` WARNING: estimate exceeds --max-cost-usd cap.` : '',
].filter(Boolean).join('\n');
}
diff --git a/src/core/skillopt/types.ts b/src/core/skillopt/types.ts
index 0a99e19b54..e53c355de5 100644
--- a/src/core/skillopt/types.ts
+++ b/src/core/skillopt/types.ts
@@ -171,6 +171,9 @@ export interface SkillOptOpts {
optimizerMode?: 'reflect' | 'one-shot-rewrite';
// Safety.
+ /** USD cap for the run. #3516: 0 means UNCAPPED (--no-max-cost) — pricing
+ * misses then warn-once instead of hard-failing, so unpriced model ids
+ * (openrouter:*, litellm:*) can run. */
maxCostUsd: number;
maxRuntimeMin: number;
force: boolean;
@@ -214,6 +217,10 @@ export interface RunReceipt {
final_cost_usd?: number;
total_steps?: number;
epochs_completed?: number;
+ // #3516: present when outcome is 'aborted' | 'errored' — machine-readable
+ // reason + the underlying error message, mirrored from the audit trail.
+ abort_reason?: 'budget_exhausted' | 'runtime_exceeded' | 'sigint' | 'error';
+ abort_detail?: string;
// Ablation provenance (cat31 replayability) — present when a non-default
// ablation knob was set.
reflect_mode?: 'both' | 'failure-only';
diff --git a/src/core/skillopt/validate-gate.ts b/src/core/skillopt/validate-gate.ts
index 3b010ace0c..7776d47487 100644
--- a/src/core/skillopt/validate-gate.ts
+++ b/src/core/skillopt/validate-gate.ts
@@ -42,12 +42,26 @@ export interface ValidateGateOpts extends Omit<GateInput, 'selSet'> {
*/
runsPerTask?: number;
abortSignal?: AbortSignal;
+ /**
+ * #4119 — wall-clock deadline (epoch ms) observed INSIDE the rollout loop:
+ * checked before every individual rollout, not just between orchestrator
+ * steps. A breach throws `skillopt_runtime_exceeded` (surfaced loudly, never
+ * swallowed as a score-0 task) so a long batch can't blow past
+ * --max-runtime by a whole gate's worth of rollouts.
+ */
+ deadlineMs?: number;
/** Test seam — substitute rollout. */
rolloutFn?: typeof runRollout;
/** Test seam — substitute scoreTrajectory. */
scoreFn?: typeof scoreTrajectory;
}
+/** #4119 — the runtime-deadline breach error, shared with the orchestrator. */
+export const SKILLOPT_RUNTIME_EXCEEDED = 'skillopt_runtime_exceeded';
+function isRuntimeExceeded(e: unknown): boolean {
+ return e instanceof Error && e.message === SKILLOPT_RUNTIME_EXCEEDED;
+}
+
/**
* Run the validation gate against a candidate skill. Returns GateResult
* with accept/reject + per-task medians for the audit JSONL.
@@ -75,6 +89,10 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRes
const runs: number[] = [];
const rollouts: ScoredRollout[] = [];
for (let i = 0; i < runsPerTask; i++) {
+ // #4119: in-rollout-loop deadline — see ValidateGateOpts.deadlineMs.
+ if (opts.deadlineMs !== undefined && Date.now() > opts.deadlineMs) {
+ throw new Error(SKILLOPT_RUNTIME_EXCEEDED);
+ }
const rolloutOpts: RolloutOpts = {
engine: opts.engine,
skillText: opts.candidateSkillText,
@@ -99,7 +117,11 @@ export async function runValidationGate(opts: ValidateGateOpts): Promise<GateRes
// (the bug the SkillOpt eval surfaced: a Haiku run with --max-cost hit
// no_pricing on every rollout and the whole gate reported a vacuous 0). Surface
// them loudly so the caller aborts instead of recording a hollow measurement.
- const aborter = settled.find((s) => s && !s.ok && isMustAbortError(s.error));
+ // #4119: a deadline breach is not scoring noise either — it must surface as
+ // the orchestrator's runtime-exceeded abort, never a fake 0-score task.
+ const aborter = settled.find(
+ (s) => s && !s.ok && (isMustAbortError(s.error) || isRuntimeExceeded(s.error)),
+ );
if (aborter && !aborter.ok) throw aborter.error;
// SettledItem<TOut>[] — extract successful results; treat (non-abort) errors as
@@ -136,6 +158,8 @@ export interface ScoreOnTasksOpts {
judgeModel?: string;
/** Median-of-N runs per task. Defaults to `VALIDATION_RUNS_PER_TASK` (3). */
runsPerTask?: number;
+ /** #4119 — in-rollout-loop deadline (epoch ms); see ValidateGateOpts. */
+ deadlineMs?: number;
abortSignal?: AbortSignal;
rolloutFn?: typeof runRollout;
scoreFn?: typeof scoreTrajectory;
@@ -158,6 +182,7 @@ export async function scoreSkillOnTasks(opts: ScoreOnTasksOpts): Promise<number>
targetModel: opts.targetModel,
...(opts.judgeModel !== undefined ? { judgeModel: opts.judgeModel } : {}),
...(opts.runsPerTask !== undefined ? { runsPerTask: opts.runsPerTask } : {}),
+ ...(opts.deadlineMs !== undefined ? { deadlineMs: opts.deadlineMs } : {}),
...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),
...(opts.rolloutFn ? { rolloutFn: opts.rolloutFn } : {}),
...(opts.scoreFn ? { scoreFn: opts.scoreFn } : {}),
diff --git a/src/core/skillpack/doctor.ts b/src/core/skillpack/doctor.ts
index 6acb94c231..b6f7d91afe 100644
--- a/src/core/skillpack/doctor.ts
+++ b/src/core/skillpack/doctor.ts
@@ -273,7 +273,9 @@ async function applyAutoFixes(
'# Bootstrap',
'',
'1. show user: "<pack-name> is installed. Try one of the trigger phrases listed in skills/."',
- '2. (edit me) agent: gbrain put_page wiki/_bootstrap-stub --frontmatter type=stub',
+ // #3697: `gbrain put_page ... --frontmatter` never resolved (CLI name
+ // is `put`, content arrives on stdin, and no --frontmatter flag exists).
+ "2. (edit me) agent: printf -- '---\\ntype: stub\\n---\\n\\nstub body\\n' | gbrain put wiki/_bootstrap-stub",
'',
'<!-- v0.36 contract: gbrain displays this post-scaffold but DOES NOT auto-execute. -->',
'',
diff --git a/src/core/skillpack/init-scaffold.ts b/src/core/skillpack/init-scaffold.ts
index ca27ebe84b..ba7fd0cb67 100644
--- a/src/core/skillpack/init-scaffold.ts
+++ b/src/core/skillpack/init-scaffold.ts
@@ -178,7 +178,9 @@ export function runInitScaffold(opts: InitScaffoldOptions): InitScaffoldResult {
'The agent reads it and walks per-step at its own discretion.',
'',
`1. show user: "${opts.name} is installed. Try one of the trigger phrases from skills/${firstSlug}/SKILL.md."`,
- `2. (edit me) agent: gbrain put_page wiki/_${opts.name}-config --frontmatter type=config`,
+ // #3697: `gbrain put_page ... --frontmatter` never resolved (CLI name is
+ // `put`, content arrives on stdin, and no --frontmatter flag exists).
+ `2. (edit me) agent: printf -- '---\\ntype: config\\n---\\n\\nconfig body\\n' | gbrain put wiki/_${opts.name}-config`,
'',
].join('\n'),
});
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 871f233695..5562a6a388 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -128,9 +128,11 @@ 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.
- const registered = await engine.executeRaw<{ id: string; local_path: string }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
+ // #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
@@ -138,13 +140,19 @@ export async function resolveSourceId(
// legitimately symlinked vault matching — only one-sided symlinks break.
const cwdResolved = realpathOrResolve(cwd);
let best: { id: string; pathLen: number } | null = null;
- for (const r of registered) {
- 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 };
+ 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;
}
if (best) {
// A local_path registration can outlive source archival. Treat landing in
@@ -239,6 +247,26 @@ export function resolveSourceIdEngineFree(
* (#1434, pinned by test/sync-sole-non-default-routing.test.ts). The
* unfederate read fix lives in `localFederatedSourceIds` below.
*/
+/**
+ * #3880: list registered local_path sources WITH their archived flag so the
+ * tier-4 cwd prefix match can prefer active sources. The archived column is
+ * v34+ — fall back to the column-less query on older brains (rows then carry
+ * no `archived` key and are treated as active, the pre-v34 behavior).
+ */
+async function listRegisteredLocalPathSources(
+ engine: BrainEngine,
+): Promise<Array<{ id: string; local_path: string; archived?: boolean }>> {
+ try {
+ return await engine.executeRaw<{ id: string; local_path: string; archived?: boolean }>(
+ `SELECT id, local_path, archived FROM sources WHERE local_path IS NOT NULL`,
+ );
+ } catch {
+ return engine.executeRaw<{ id: string; local_path: string }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ }
+}
+
async function pickSoleNonDefaultSource(engine: BrainEngine): Promise<string | null> {
// archived column was added in v34 (v0.26.5). Older brains may not have
// it — fall back to the un-archived query in that case via try/catch.
@@ -306,6 +334,55 @@ async function assertSourceExists(engine: BrainEngine, id: string): Promise<void
}
}
+/**
+ * #3765 — resolve the source id for an EXPLICIT repo path (`sync --repo <dir>`
+ * / the sync_brain op's `repo` param), anchored at the REPO DIR instead of
+ * process.cwd(). Without this, `gbrain sync --repo ~/other-vault` parsed the
+ * path but resolved the SOURCE from the caller's cwd — anchors, page writes,
+ * and the per-source sync lock all routed to whatever source the cwd implied.
+ *
+ * Two tiers, mirroring resolveSourceId's dotfile + local_path tiers but
+ * rooted at `dir`:
+ * 1. `.gbrain-source` dotfile walk up from the repo dir (same trust rules)
+ * 2. registered source whose local_path contains the repo dir
+ * (longest-prefix match; realpath both sides — codex #9 rationale)
+ *
+ * Returns null when neither tier fires — the caller falls back to its ambient
+ * resolution (cwd chain / ctx.sourceId). Never consults env/cwd: an explicit
+ * repo path is a statement of intent about THAT tree.
+ */
+export async function resolveSourceForRepoPath(
+ engine: BrainEngine,
+ dir: string,
+): Promise<{ source_id: string; tier: 'dotfile' | 'local_path'; detail: string } | null> {
+ // 1. Dotfile pinned in (or above) the repo tree.
+ const dotfile = readDotfileWalk(dir);
+ if (dotfile) {
+ await assertSourceExists(engine, dotfile);
+ return { source_id: dotfile, tier: 'dotfile', detail: `.gbrain-source under ${dir}` };
+ }
+
+ // 2. Registered local_path containing the repo dir (longest prefix wins).
+ const registered = await engine.executeRaw<{ id: string; local_path: string }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ const dirResolved = realpathOrResolve(dir);
+ let best: { id: string; path: string; pathLen: number } | null = null;
+ for (const r of registered) {
+ const p = realpathOrResolve(r.local_path);
+ if (dirResolved === p || dirResolved.startsWith(p + '/')) {
+ if (!best || p.length > best.pathLen) {
+ best = { id: r.id, path: p, pathLen: p.length };
+ }
+ }
+ }
+ if (best) {
+ await assertSourceExists(engine, best.id);
+ return { source_id: best.id, tier: 'local_path', detail: best.path };
+ }
+ return null;
+}
+
/**
* Get the local_path of the resolved source (per the resolveSourceId chain).
*
@@ -409,19 +486,24 @@ export async function resolveSourceWithTier(
}
// 4. Registered source whose local_path contains CWD.
- const registered = await engine.executeRaw<{ id: string; local_path: string }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
+ // #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 r of registered) {
- 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 };
+ 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;
}
if (best) {
await assertSourceExists(engine, best.id);
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index fbefa8ad6c..6b16d71795 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -377,7 +377,13 @@ export async function addSource(
// phantom `C:\c\Users\x` and sync/write-through silently miss the real
// directory. Identity on POSIX and for already-native paths.
if (opts.localPath) {
- opts = { ...opts, localPath: msysToNativePath(opts.localPath) };
+ // #3696: resolve to ABSOLUTE before the overlap check and the INSERT.
+ // A relative `--path .` used to be stored verbatim; every later consumer
+ // that runs from a different cwd (launchd daemon at cwd=/, autopilot
+ // dispatch, sync anchors) then join-resolved a phantom path and silently
+ // missed the real directory.
+ // 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 fix
+ opts = { ...opts, localPath: resolvePath(msysToNativePath(opts.localPath)) };
}
// Q4: pre-flight collision check before any clone work.
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 98ceb6dab0..79a585227c 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -319,6 +319,10 @@ async function runLinksTimelinePass(
const resolver = makeResolver(engine, { mode: 'batch', sourceId });
const globalBasename = await isGlobalBasenameEnabled(engine);
+ // #3190: pack-aware verbs — the sweep must type edges the same way the
+ // extract command does or reconciliation flip-flops the link_type.
+ const { loadActivePackForLocalEngine } = await import('./schema-pack/best-effort.ts');
+ const pack = (await loadActivePackForLocalEngine(engine))?.manifest ?? null;
type Extracted = Awaited<ReturnType<typeof extractPageLinks>>;
@@ -345,7 +349,7 @@ async function runLinksTimelinePass(
// (frontmatter backfill stays a migration-orchestrator concern).
const extracted = await extractPageLinks(
slug, fullContent, page.frontmatter, page.type, resolver,
- { skipFrontmatter: true, globalBasename },
+ { skipFrontmatter: true, globalBasename, pack },
);
if (extracted.candidates.length > 0) {
pageCandidates.push({ slug, candidates: extracted.candidates });
@@ -355,10 +359,12 @@ async function runLinksTimelinePass(
if (timelineEnabled) {
for (const entry of parseTimelineEntries(fullContent)) {
// Same row shape as extractTimelineFromDB's batch push (extract.ts):
- // no explicit source (engine default applies), detail '' when empty.
+ // #3957 — parsed source label threaded so FS- and DB-extracted rows
+ // share one dedup shape; detail '' when empty.
tlBatch.push({
slug,
date: entry.date,
+ source: entry.source,
summary: entry.summary,
detail: entry.detail || '',
source_id: sourceId,
diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.ts
index acbc519edc..7092a5d9e2 100644
--- a/src/core/sync-anchor.ts
+++ b/src/core/sync-anchor.ts
@@ -347,3 +347,110 @@ export async function writeChunkerVersion(
[version, sourceId],
);
}
+
+// ─── #4342 — sticky per-source slug-root mode ─────────────────────────────
+//
+// When a source's local_path is a SUBDIRECTORY of a git repo, sync has two
+// possible slug namespaces:
+// 'git-root' — slugs carry the subdir prefix (git-diff-path shaped; the
+// historical #774 behavior, and the only sane shape when
+// the user explicitly scoped with --src-subpath)
+// 'source-root' — slugs are local_path-relative (matches what a plain
+// `gbrain import <dir>` of the same tree produces)
+//
+// The choice used to be IMPLICIT (whatever the first sync inferred), and a
+// later sync from a different spelling silently re-namespaced every slug.
+// The mode is now decided ONCE, persisted (sources.config.slug_root_mode for
+// scoped sources, `sync.slug_root_mode` config for the legacy no-source
+// path), and every subsequent sync obeys the pin.
+
+export type SlugRootMode = 'git-root' | 'source-root';
+
+function asSlugRootMode(raw: unknown): SlugRootMode | null {
+ return raw === 'git-root' || raw === 'source-root' ? raw : null;
+}
+
+export async function readSlugRootMode(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+): Promise<SlugRootMode | null> {
+ if (sourceId) {
+ const rows = await engine.executeRaw<{ mode: string | null }>(
+ `SELECT config->>'slug_root_mode' AS mode FROM sources WHERE id = $1`,
+ [sourceId],
+ );
+ return asSlugRootMode(rows[0]?.mode);
+ }
+ return asSlugRootMode(await engine.getConfig('sync.slug_root_mode'));
+}
+
+export async function writeSlugRootMode(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+ mode: SlugRootMode,
+): 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],
+ );
+ return;
+ }
+ await engine.setConfig('sync.slug_root_mode', mode);
+}
+
+/** Escape LIKE metacharacters so a slug prefix can't wildcard-match. */
+function escapeLike(s: string): string {
+ return s.replace(/([\\%_])/g, '\\$1');
+}
+
+/**
+ * Resolve (and PIN) the slug-root mode for a scoped sync. Precedence:
+ * 1. the stored pin (sticky forever — a live install never re-slugs)
+ * 2. explicit --src-subpath → 'git-root' (the #774 contract: the caller
+ * named the git root as the slug base)
+ * 3. auto-pin 'git-root' when existing pages already carry the inferred
+ * git-root prefix (this install has lived with git-root slugs; flipping
+ * would strand every page + its links/takes under the old namespace)
+ * 4. else 'source-root' (local_path-relative — what `gbrain import <dir>`
+ * of the same tree produces, and the least surprising default)
+ * The decision is persisted before returning so every later sync agrees.
+ *
+ * `slugPrefix` is the SLUGIFIED git-root-relative scope prefix WITHOUT a
+ * trailing slash (callers derive it via resolveSlugForPath so the probe
+ * matches slug spelling, not raw path spelling).
+ *
+ * `dryRun: true` resolves the mode in-memory only and skips the persist —
+ * a `sync --dry-run` must never mutate config (#4342 review fix). The pin
+ * is written by the first REAL sync instead.
+ */
+export async function resolveSlugRootMode(
+ engine: BrainEngine,
+ opts: {
+ sourceId: string | undefined;
+ explicitGitRoot: boolean;
+ slugPrefix: string;
+ dryRun?: boolean;
+ },
+): Promise<SlugRootMode> {
+ const stored = await readSlugRootMode(engine, opts.sourceId);
+ if (stored) return stored;
+ let mode: SlugRootMode;
+ if (opts.explicitGitRoot) {
+ mode = 'git-root';
+ } else {
+ const rows = await engine.executeRaw<{ one: number }>(
+ `SELECT 1 AS one FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE $2 LIMIT 1`,
+ [opts.sourceId ?? 'default', `${escapeLike(opts.slugPrefix)}/%`],
+ );
+ mode = rows.length > 0 ? 'git-root' : 'source-root';
+ }
+ if (opts.dryRun !== true) {
+ await writeSlugRootMode(engine, opts.sourceId, mode);
+ }
+ return mode;
+}
diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.ts
index 246a7661d0..330fe8dc5d 100644
--- a/src/core/sync-cost-gate.ts
+++ b/src/core/sync-cost-gate.ts
@@ -5,7 +5,7 @@
*/
import { readFileSync, statSync } from 'fs';
import { join } from 'path';
-import { createInterface } from 'readline';
+import { promptYesNo } from './confirm-prompt.ts';
import type { BrainEngine } from './engine.ts';
import { collectSyncableFiles } from '../commands/import.ts';
import { isSyncable } from './sync.ts';
@@ -314,18 +314,6 @@ async function resolveBackfillCapUsd(engine: BrainEngine): Promise<number> {
}
}
-/** Interactive [y/N] prompt. Resolves false on non-y answers or EOF. */
-async function promptYesNo(question: string): Promise<boolean> {
- return new Promise((resolve) => {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- rl.question(question, (answer) => {
- rl.close();
- resolve(answer.trim().toLowerCase() === 'y' || answer.trim().toLowerCase() === 'yes');
- });
- rl.on('close', () => resolve(false));
- });
-}
-
// v0.42.42.0 (#2139): paste-ready knobs appended to every gate message so the
// spend-control surface is discoverable at the moment of need (humans + agents),
// not only after reading source. Closes the issue's "takes archaeology" complaint.
diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.ts
index 9a35ab6d21..9cb9000471 100644
--- a/src/core/sync-failure-ledger.ts
+++ b/src/core/sync-failure-ledger.ts
@@ -161,6 +161,15 @@ export function classifyErrorCode(errorMsg: string): string {
if (/Anthropic has no embedding model|EMBEDDING_NO_TOUCHPOINT/i.test(errorMsg)) {
return 'EMBEDDING_NO_TOUCHPOINT';
}
+ // #3875: embed-scoped timeouts (AbortSignal.timeout firing inside the
+ // gateway's per-sub-batch AI_EMBED_TIMEOUT_MS produces
+ // `[embed(provider:model)] The operation timed out.`). Classified BEFORE the
+ // rate-limit/quota checks and distinct from STATEMENT_TIMEOUT (a DB error) —
+ // this is provider-infra unhealth, not file poison, so the auto-skip valve
+ // must never eat it.
+ if (/\[embed(?:Multimodal)?\([^)]*\)\][^\n]*\b(?:timed? ?out|timeout)\b|EMBEDDING_TIMEOUT/i.test(errorMsg)) {
+ return 'EMBEDDING_TIMEOUT';
+ }
if (/\brate.?limit|\b429\b|too many requests|rate_limited|RateLimit/i.test(errorMsg)) {
return 'EMBEDDING_RATE_LIMIT';
}
@@ -591,6 +600,26 @@ export interface GateDecision {
autoSkipPaths: string[];
}
+/**
+ * #3875: error codes that indicate the EMBEDDING PROVIDER is unhealthy, not
+ * that the file is poison. The bounded auto-skip valve exists to route around
+ * a single bad file; letting it fire on provider-infra failures silently
+ * unindexes an unbounded slice of the brain (every file "fails" while the
+ * provider is down/timing out/rate-limited). These codes always BLOCK the
+ * bookmark instead of auto-skipping — the fix is provider health, not
+ * `--skip-failed`.
+ */
+export const EMBEDDING_INFRA_CODES: ReadonlySet<string> = new Set([
+ 'EMBEDDING_TIMEOUT',
+ 'EMBEDDING_RATE_LIMIT',
+ 'EMBEDDING_QUOTA',
+]);
+
+/** True when `code` names a provider-infra embedding failure (see above). */
+export function isEmbeddingInfraCode(code: string | undefined): boolean {
+ return code !== undefined && EMBEDDING_INFRA_CODES.has(code);
+}
+
/**
* Decide what the sync gate should do, given this run's failures and the
* current attempt counts. Pure — the caller executes effects in the safe
@@ -602,10 +631,13 @@ export interface GateDecision {
* --skip-failed → advance (ack handled post-advance)
* valve disabled (threshold<=0) → block (pure fail-closed) if failures
* any fresh (attempts<threshold) → block
+ * any embedding-infra code (#3875) → block (provider unhealthy ≠ file poison;
+ * never auto-skip, regardless of attempts)
* all chronic (attempts>=threshold) → advance_then_autoskip
*/
export function decideGateAction(args: {
- fileFailures: Array<{ path: string }>;
+ /** `code` (when provided) is a classifyErrorCode() result — #3875. */
+ fileFailures: Array<{ path: string; code?: string }>;
sentinels: Array<{ path: string }>;
attemptsByPath: Map<string, number>;
threshold: number;
@@ -619,6 +651,14 @@ export function decideGateAction(args: {
const chronic: string[] = [];
let fresh = 0;
for (const f of args.fileFailures) {
+ // #3875: provider-infra failures (embed timeout / rate limit / quota) are
+ // never chronic-eligible — auto-skipping them would silently unindex every
+ // file that happened to sync while the provider was unhealthy. Treat them
+ // as fresh so the gate BLOCKS and the operator fixes the provider.
+ if (isEmbeddingInfraCode(f.code)) {
+ fresh++;
+ continue;
+ }
const a = args.attemptsByPath.get(f.path) ?? 1;
if (a >= args.threshold) chronic.push(f.path);
else fresh++;
@@ -732,7 +772,9 @@ export async function applySyncFailureGate(input: SyncGateInput): Promise<SyncGa
);
const decision = decideGateAction({
- fileFailures,
+ // #3875: thread the classified error code so provider-infra failures
+ // (embed timeout / rate limit / quota) can never ride the auto-skip valve.
+ fileFailures: fileFailures.map(f => ({ path: f.path, code: classifyErrorCode(f.error) })),
sentinels,
attemptsByPath,
threshold,
diff --git a/src/core/sync.ts b/src/core/sync.ts
index a142c1a496..98b0c554da 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -262,7 +262,14 @@ function isMultimodalEnabled(): boolean {
}
function isAllowedByStrategy(path: string, strategy: SyncStrategy): boolean {
- if (strategy === 'markdown') return isMarkdownFilePath(path);
+ // #2683: mirror import.ts's isCollectibleForWalker — the full-sync walker
+ // admits images under the (default) 'markdown' strategy when multimodal is
+ // on, but this incremental gate used to be markdown-only, so a committed
+ // image NEVER imported incrementally (it only landed via `sync --full`).
+ // Full and incremental must agree on the admission set.
+ if (strategy === 'markdown') {
+ return isMarkdownFilePath(path) || (isMultimodalEnabled() && isImageFilePath(path));
+ }
if (strategy === 'code') return isCodeFilePath(path);
// 'auto' / default: markdown + code, plus images when multimodal is on.
return (
@@ -568,6 +575,14 @@ export function slugifySegment(segment: string): string {
return segment
.normalize('NFD') // Decompose accented chars
.replace(/[\u0300-\u036f]/g, '') // Strip accent marks
+ // #3700: Hebrew niqqud (vowel points) + cantillation are optional
+ // diacritics \u2014 the same word appears pointed and bare across filenames
+ // and must land on ONE slug (the Hebrew analog of caf\u00e9 \u2192 cafe). Scoped
+ // to U+0591\u2013U+05C7 only; \p{M} stays in SLUG_WORD_CHARS so Devanagari
+ // matras, Thai vowels, Arabic text etc. keep their #3417 behavior.
+ // Runs in NFD space so precomposed presentation forms (U+FB1D\u2013FB4F)
+ // are already decomposed and their points strip too.
+ .replace(/[\u0591-\u05c7]/g, '') // Strip Hebrew niqqud + cantillation
.normalize('NFC') // Recompose Hangul Jamo back to Syllables (v0.32.7)
.toLowerCase()
.replace(SLUGIFY_KEEP_RE, '') // Keep alnum, dots, spaces, _-, and CJK (v0.32.7)
@@ -667,6 +682,8 @@ export {
resolveAutoSkipThreshold,
isSkippablePath,
decideGateAction,
+ EMBEDDING_INFRA_CODES,
+ isEmbeddingInfraCode,
decideSyncFailureSeverity,
applySyncFailureGate,
DEFAULT_SOURCE_ID,
diff --git a/src/core/take-proposals.ts b/src/core/take-proposals.ts
new file mode 100644
index 0000000000..79739d5f26
--- /dev/null
+++ b/src/core/take-proposals.ts
@@ -0,0 +1,190 @@
+/**
+ * #2411 / #4102 — drain surface for the `take_proposals` queue.
+ *
+ * The propose_takes cycle phase (src/core/cycle/propose-takes.ts) WRITES
+ * proposals; the D17 auto-resolve posture says the ONLY path from queue to
+ * canonical fence is explicit operator accept. This module is that path:
+ *
+ * - listPendingProposals — source-scoped pending queue (newest first).
+ * - acceptProposal — promote via addTakeToPage (markdown-canonical
+ * write-through), then stamp status='accepted' +
+ * promoted_row_num + acted_at/acted_by.
+ * - rejectProposal — stamp status='rejected' + acted_at/acted_by.
+ *
+ * All reads/writes are parameterized and scoped to the caller's source when
+ * one is provided (the CLI always resolves one via resolveSourceId). The
+ * accept write goes through the SAME shared write-through core the takes_*
+ * ops use, so the fence lock, holder fence, injection guards and DB mirror
+ * all apply.
+ */
+
+import type { BrainEngine, TakeKind } from './engine.ts';
+import { addTakeToPage } from './takes-write.ts';
+
+export interface TakeProposalRow {
+ id: number;
+ source_id: string;
+ page_slug: string;
+ claim_text: string;
+ kind: string;
+ holder: string;
+ weight: number;
+ domain: string | null;
+ status: string;
+ proposed_at: string | Date;
+ model_id: string;
+ promoted_row_num: number | null;
+}
+
+export type TakeProposalErrorCode = 'not_found' | 'not_pending';
+
+export class TakeProposalError extends Error {
+ constructor(
+ public readonly code: TakeProposalErrorCode,
+ message: string,
+ ) {
+ super(message);
+ this.name = 'TakeProposalError';
+ }
+}
+
+/**
+ * The producer (parseExtractorOutput) only ever writes the four canonical
+ * kinds, but the column is free TEXT — coerce defensively so a legacy or
+ * hand-inserted row can't crash the promote path. 'prediction' (the raw
+ * extractor-prompt enum) maps to 'bet'; anything else unknown maps to 'take'.
+ */
+export function coerceProposalKind(raw: string): TakeKind {
+ if (raw === 'fact' || raw === 'take' || raw === 'bet' || raw === 'hunch') return raw;
+ if (raw === 'prediction') return 'bet';
+ return 'take';
+}
+
+const PROPOSAL_COLUMNS =
+ 'id, source_id, page_slug, claim_text, kind, holder, weight, domain, status, proposed_at, model_id, promoted_row_num';
+
+export interface ListPendingOpts {
+ /** Scope to one source (the CLI always provides one). Omit = all sources (trusted local only). */
+ sourceId?: string;
+ limit?: number;
+}
+
+/** Pending proposals, newest first. Tombstones never surface (status='rejected'). */
+export async function listPendingProposals(
+ engine: BrainEngine,
+ opts: ListPendingOpts = {},
+): Promise<TakeProposalRow[]> {
+ const limit = Math.max(1, Math.min(500, opts.limit ?? 20));
+ const where = [`status = 'pending'`];
+ const params: unknown[] = [];
+ if (opts.sourceId) {
+ params.push(opts.sourceId);
+ where.push(`source_id = $${params.length}`);
+ }
+ params.push(limit);
+ return engine.executeRaw<TakeProposalRow>(
+ `SELECT ${PROPOSAL_COLUMNS}
+ FROM take_proposals
+ WHERE ${where.join(' AND ')}
+ ORDER BY proposed_at DESC, id DESC
+ LIMIT $${params.length}`,
+ params,
+ );
+}
+
+async function loadProposal(
+ engine: BrainEngine,
+ id: number,
+ sourceId?: string,
+): Promise<TakeProposalRow> {
+ const params: unknown[] = [id];
+ let scope = '';
+ if (sourceId) {
+ params.push(sourceId);
+ scope = ` AND source_id = $${params.length}`;
+ }
+ const rows = await engine.executeRaw<TakeProposalRow>(
+ `SELECT ${PROPOSAL_COLUMNS} FROM take_proposals WHERE id = $1${scope}`,
+ params,
+ );
+ if (rows.length === 0) {
+ throw new TakeProposalError('not_found', `No take proposal #${id}${sourceId ? ` in source '${sourceId}'` : ''}.`);
+ }
+ const row = rows[0];
+ if (row.status !== 'pending') {
+ throw new TakeProposalError(
+ 'not_pending',
+ `Proposal #${id} is already '${row.status}' (acted on) — only pending proposals can be accepted or rejected.`,
+ );
+ }
+ return row;
+}
+
+export interface ProposalActionTarget {
+ engine: BrainEngine;
+ /** Brain repo root — accept writes the markdown fence (markdown-canonical). */
+ brainDir?: string;
+ /** Source scope: a proposal outside this source reads as not_found. */
+ sourceId?: string;
+ /** Recorded in acted_by. Defaults to 'cli'. */
+ actedBy?: string;
+}
+
+/**
+ * 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.
+ */
+export async function acceptProposal(
+ target: ProposalActionTarget,
+ id: number,
+): Promise<{ proposal: TakeProposalRow; rowNum: number }> {
+ const { engine } = target;
+ const proposal = await loadProposal(engine, id, target.sourceId);
+ if (!target.brainDir) {
+ throw new TakeProposalError(
+ 'not_found',
+ '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),
+ },
+ );
+ 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],
+ );
+ return { proposal, rowNum };
+}
+
+/** Mark a pending proposal rejected. No markdown write. */
+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(
+ `UPDATE take_proposals
+ SET status = 'rejected', acted_at = now(), acted_by = $2
+ WHERE id = $1 AND status = 'pending'`,
+ [id, target.actedBy ?? 'cli'],
+ );
+ return proposal;
+}
diff --git a/src/core/takes-fence.ts b/src/core/takes-fence.ts
index 2e2a9b490c..a3032f4d27 100644
--- a/src/core/takes-fence.ts
+++ b/src/core/takes-fence.ts
@@ -241,7 +241,21 @@ export function parseTakesFence(body: string): ParseResult {
const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
const warnings: string[] = [];
- if (beginIdx === -1 && endIdx === -1) return { takes: [], warnings };
+ if (beginIdx === -1 && endIdx === -1) {
+ // #3769: the canonical markers use the THREE-dash comment form
+ // (`<!--- gbrain:takes:begin -->`). A body that mentions the marker text
+ // without the exact form — most commonly the standard two-dash
+ // `<!-- gbrain:takes:begin -->` an author or agent writes from memory —
+ // is a fence the author MEANT to write. Flag it instead of silently
+ // parsing zero takes.
+ if (body.includes('gbrain:takes:begin')) {
+ warnings.push(
+ 'TAKES_FENCE_NEAR_MISS: found "gbrain:takes:begin" but not the exact ' +
+ `marker "${TAKES_FENCE_BEGIN}" — use the three-dash comment form`,
+ );
+ }
+ return { takes: [], warnings };
+ }
if (beginIdx === -1 || endIdx === -1) {
warnings.push('TAKES_FENCE_UNBALANCED: missing begin or end marker');
return { takes: [], warnings };
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
index 23fa837682..54b73e1fa7 100644
--- a/src/core/takes-write.ts
+++ b/src/core/takes-write.ts
@@ -336,7 +336,10 @@ function assertFenceRoundTrips(parsed: ParseResult): void {
throw new TakesWriteError(
'fence_unparsed',
`The page's takes fence has rows this version can't safely round-trip: ${parsed.warnings[0]}`,
- "Reconcile the page's takes fence (gbrain extract takes --slugs <slug>) before mutating — it contains rows this version can't safely round-trip.",
+ // #3697: this used to name `gbrain extract takes --slugs`, which is not the
+ // command grammar (extract has links/timeline/all; takes extraction lives
+ // under `gbrain takes extract`). Point at surfaces that exist.
+ "Reconcile the page's takes fence before mutating — it contains rows this version can't safely round-trip. Fix the malformed fence rows by hand, or re-extract via `gbrain takes extract --from-pages --include-covered`.",
);
}
}
diff --git a/src/core/think/persist-take.ts b/src/core/think/persist-take.ts
new file mode 100644
index 0000000000..5ad8d1e19b
--- /dev/null
+++ b/src/core/think/persist-take.ts
@@ -0,0 +1,141 @@
+/**
+ * #2556 — persist a take row from a think synthesis (`gbrain think --take`).
+ *
+ * The `--take` flag has been documented since v0.28 ("appends a take row to
+ * the anchor page") but `RunThinkOpts.take` was never read anywhere in the
+ * pipeline: the CLI parsed it, the MCP op gated it (`safeTake`), and both
+ * forwarded it into runThink where it died silently. This module is the
+ * missing execution half, wired by commands/think.ts and the `think` op.
+ *
+ * Semantics:
+ * - synthesisOk === false → warn-skip (never persist a stub/empty answer;
+ * same gate persistSynthesis uses).
+ * - claim = the first substantive line of stripGapsSection(answer),
+ * markdown markers stripped, sanitized to a single fence-safe cell
+ * (control chars collapsed, fence-marker text removed, bounded length).
+ * - holder = resolveOwnerHolder (config emotional_weight.user_holder,
+ * else 'self') — the take is the OWNER's synthesized position.
+ * - persistence goes md-first through addTakeToPage (the same canonical
+ * write-through every takes verb uses: fence row on disk, DB mirrored,
+ * mirror failure downgraded to a warning).
+ * - no brain repo (resolveTakesRepoDir null) → TAKE_MIRROR_UNAVAILABLE
+ * warning, nothing written (md is canonical; a DB-only take would be
+ * clobbered by the next reconcile).
+ *
+ * Remote (MCP) callers never reach this — the `think` op forces
+ * safeTake=false for ctx.remote !== false, unchanged.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { stripGapsSection, type ThinkResult } from './index.ts';
+import { resolveOwnerHolder } from '../owner-holder.ts';
+import { resolveTakesRepoDir, addTakeToPage, TakesWriteError } from '../takes-write.ts';
+
+/** Max claim length for a fence cell — one readable line, not an essay. */
+export const TAKE_CLAIM_MAX_CHARS = 300;
+
+export interface PersistTakeResult {
+ /** Appended fence row number, or null when nothing was written. */
+ take_row: number | null;
+ /** Markdown file the row landed in (set iff take_row is non-null). */
+ path?: string;
+ /** Machine-stable warning codes (mirrors the think warnings channel). */
+ warnings: string[];
+}
+
+/**
+ * Extract the claim line: first substantive line of the gaps-stripped answer,
+ * heading/bullet/quote markers removed, sanitized to a single fence-safe
+ * cell. Returns null when the answer has no substantive line. Pure — the
+ * unit-test surface.
+ */
+export function claimFromAnswer(answer: string): string | null {
+ const stripped = stripGapsSection(answer ?? '');
+ for (const raw of stripped.split('\n')) {
+ let line = raw.trim();
+ if (!line) continue;
+ line = line.replace(/^#{1,6}\s+/, '').replace(/^[-*+>]\s+/, '').trim();
+ if (!line) continue;
+ // Fence-cell safety (assertSafeCellText would THROW on these; sanitizing
+ // here keeps --take best-effort instead of failing the whole think run):
+ // collapse control chars to spaces, drop the fence-marker substring.
+ line = line
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\n\r\t]+/g, ' ')
+ .replaceAll('gbrain:takes', '')
+ .replace(/\s{2,}/g, ' ')
+ .trim();
+ if (!line) continue;
+ if (line.length > TAKE_CLAIM_MAX_CHARS) {
+ line = `${line.slice(0, TAKE_CLAIM_MAX_CHARS - 1).trimEnd()}…`;
+ }
+ // A wholly-strikethrough claim round-trips as active:false — unwrap it.
+ const struck = /^~~([\s\S]*)~~$/.exec(line);
+ if (struck) line = struck[1].trim();
+ if (!line) continue;
+ return line;
+ }
+ return null;
+}
+
+/**
+ * Append the synthesis claim as a take row on the anchor page. Never throws
+ * for the expected refusal shapes (no repo, empty answer, failed synthesis) —
+ * those return take_row:null with a machine-stable warning so both callers
+ * (CLI + op) surface the same story.
+ */
+export async function persistTakeFromSynthesis(
+ engine: BrainEngine,
+ result: Pick<ThinkResult, 'answer' | 'synthesisOk'>,
+ opts: { anchor: string; sourceId?: string; lockTimeoutMs?: number },
+): Promise<PersistTakeResult> {
+ const warnings: string[] = [];
+
+ // Same persistence gate as persistSynthesis: an explicit false means the
+ // stub/malformed/empty path — a take asserting nothing must not be minted.
+ if (result.synthesisOk === false) {
+ warnings.push('TAKE_SKIPPED_SYNTHESIS_FAILED');
+ return { take_row: null, warnings };
+ }
+
+ const claim = claimFromAnswer(result.answer);
+ if (!claim) {
+ warnings.push('TAKE_SKIPPED_EMPTY_ANSWER');
+ return { take_row: null, warnings };
+ }
+
+ const brainDir = await resolveTakesRepoDir(engine);
+ if (!brainDir) {
+ // md is canonical for takes — with no repo there is nothing durable to
+ // write (a DB-only row would be deleted by the next fence reconcile).
+ warnings.push('TAKE_MIRROR_UNAVAILABLE');
+ return { take_row: null, warnings };
+ }
+
+ const holder = resolveOwnerHolder({
+ configValue: await engine.getConfig('emotional_weight.user_holder'),
+ });
+
+ try {
+ const { rowNum, mirror } = await addTakeToPage(
+ {
+ engine,
+ slug: opts.anchor,
+ brainDir,
+ sourceId: opts.sourceId,
+ ...(opts.lockTimeoutMs !== undefined ? { lockTimeoutMs: opts.lockTimeoutMs } : {}),
+ },
+ { claim, kind: 'take', holder, source: 'think' },
+ );
+ if (mirror.mirror_warning) {
+ warnings.push(`TAKE_DB_MIRROR_WARNING: ${mirror.mirror_warning}`);
+ }
+ return { take_row: rowNum, path: mirror.path, warnings };
+ } catch (e) {
+ // Typed write refusals (page not found, lock timeout, fence malformed)
+ // become a loud warning + null row — think's answer already printed and
+ // must not be lost to a persistence failure.
+ const detail = e instanceof TakesWriteError ? `${e.code}: ${e.message}` : (e instanceof Error ? e.message : String(e));
+ warnings.push(`TAKE_WRITE_FAILED: ${detail}`);
+ return { take_row: null, warnings };
+ }
+}
diff --git a/src/core/timeline-dedup-repair.ts b/src/core/timeline-dedup-repair.ts
index 4aff01223b..2946e39575 100644
--- a/src/core/timeline-dedup-repair.ts
+++ b/src/core/timeline-dedup-repair.ts
@@ -17,9 +17,17 @@
*/
import type { BrainEngine } from './engine.ts';
+import { parseTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';
const INDEX_NAME = 'idx_timeline_dedup';
-const EXPECTED_COLUMNS = ['page_id', 'date', 'summary', 'source'];
+// #3737: the dedup tuple keys md5(summary) — the raw summary overflowed the
+// btree v4 row cap (~2704 bytes) on long/incompressible summaries and aborted
+// every timeline insert for that page. Both engines' insert sites infer
+// ON CONFLICT (page_id, date, md5(summary), source) against this shape, so
+// the self-heal MUST expect (and rebuild to) the md5 form — an
+// EXPECTED_COLUMNS of the raw shape would make this repair revert migration
+// v138 on every migrate pass.
+const EXPECTED_COLUMNS = ['page_id', 'date', 'md5(summary)', 'source'];
export interface TimelineDedupStatus {
/** The timeline_entries table exists (nothing to repair if not). */
@@ -32,15 +40,39 @@ export interface TimelineDedupStatus {
needsRepair: boolean;
}
-/** Parse the column list out of a pg_indexes `indexdef` string. */
-function parseIndexColumns(indexdef: string): string[] {
- const open = indexdef.lastIndexOf('(');
+/**
+ * Parse the column list out of a pg_indexes `indexdef` string.
+ *
+ * #3737: the column list is the span from the FIRST `(` (the list opener
+ * after `USING btree`) to the LAST `)`. The previous `lastIndexOf('(')`
+ * pointed INSIDE an expression column — `... (page_id, date, md5(summary),
+ * source)` parsed as `['summary']` — so the shape check misread a healthy
+ * md5-keyed index as drifted and rebuilt it on every migrate pass. The
+ * split is paren-depth-aware so `md5(summary)` (or any future expression
+ * with internal commas) stays one entry.
+ */
+export function parseIndexColumns(indexdef: string): string[] {
+ const open = indexdef.indexOf('(');
const close = indexdef.lastIndexOf(')');
if (open < 0 || close < 0 || close < open) return [];
- return indexdef
- .slice(open + 1, close)
- .split(',')
- .map(c => c.trim().split(/\s+/)[0]) // drop any "col DESC"/opclass suffix
+ const list = indexdef.slice(open + 1, close);
+ const cols: string[] = [];
+ let depth = 0;
+ let cur = '';
+ for (const ch of list) {
+ if (ch === '(') { depth++; cur += ch; }
+ else if (ch === ')') { depth--; cur += ch; }
+ else if (ch === ',' && depth === 0) { cols.push(cur); cur = ''; }
+ else cur += ch;
+ }
+ cols.push(cur);
+ return cols
+ .map(c => {
+ const t = c.trim();
+ // Drop any "col DESC"/opclass suffix — but only for plain columns;
+ // an expression entry (contains '(') is kept whole.
+ return t.includes('(') ? t : t.split(/\s+/)[0];
+ })
.filter(Boolean);
}
@@ -74,10 +106,12 @@ export interface TimelineDedupRepairResult {
}
/**
- * Heal the index if it's missing the v102 4-column shape. Dedupes FIRST —
- * the loose 3-column index let rows differing only by `source` coexist, and
- * `CREATE UNIQUE INDEX` would throw on those collisions otherwise. Keeps the
- * earliest row (min ctid) of each 4-tuple group.
+ * Heal the index if it's missing the canonical shape (v138: (page_id, date,
+ * md5(summary), source)). Dedupes FIRST — the loose 3-column index let rows
+ * differing only by `source` coexist, and `CREATE UNIQUE INDEX` would throw
+ * on those collisions otherwise. Keeps the earliest row (min id) of each
+ * 4-tuple group (raw-summary grouping is equivalent to md5 grouping —
+ * md5-equal ⟺ summary-equal modulo negligible collisions).
*/
export async function repairTimelineDedupIndex(engine: BrainEngine): Promise<TimelineDedupRepairResult> {
const status = await checkTimelineDedupIndex(engine);
@@ -112,9 +146,145 @@ export async function repairTimelineDedupIndex(engine: BrainEngine): Promise<Tim
const collapsedDuplicates = parseInt(del[0]?.n ?? '0', 10);
await engine.executeRaw(`DROP INDEX IF EXISTS ${INDEX_NAME}`);
+ // #3737: rebuild to the md5-keyed shape (matches migration v138 + both
+ // engines' ON CONFLICT inference) — rebuilding the raw-summary shape here
+ // would revert the btree-overflow fix on the next migrate pass.
await engine.executeRaw(
`CREATE UNIQUE INDEX IF NOT EXISTS ${INDEX_NAME}
- ON timeline_entries(page_id, date, summary, source)`,
+ ON timeline_entries(page_id, date, md5(summary), source)`,
);
return { repaired: true, before: status.columns, collapsedDuplicates, reason: 'rebuilt' };
}
+
+// ─── #3957 — legacy-row (source='') shape repair ─────────────────────────
+
+export interface LegacyTimelineRepairResult {
+ /** Pages that carried at least one legacy (source='') row. */
+ pagesScanned: number;
+ /** Legacy rows rewritten in place to the split (source, summary) shape. */
+ rowsRewritten: number;
+ /** Legacy rows deleted because a new-shape duplicate already existed. */
+ rowsDeleted: number;
+ /** Legacy rows left untouched (no matching bullet in current content). */
+ rowsSkipped: number;
+}
+
+/**
+ * #3957 one-time repair: rewrite legacy DB-path timeline rows to the split
+ * (source, summary) shape the post-#3957 parser emits.
+ *
+ * Pre-#3957, `parseTimelineEntries` (the DB extract / put_page auto-timeline
+ * path) emitted no `source` — rows landed with the column default `''` and
+ * the UNSPLIT bullet rest as `summary` (`'meeting — Discussed X'`). The
+ * parser now splits pipe bullets into (source='meeting', summary=
+ * 'Discussed X') and labels the rest 'markdown', so the
+ * (page_id, date, md5(summary), source) dedup index can never collapse a
+ * re-extraction onto a legacy row — every re-extract would DUPLICATE it.
+ *
+ * The rewrite is CONTENT-ANCHORED, not a blind string split: for each page
+ * carrying legacy rows we re-parse its current content with the NEW parser
+ * and rewrite a legacy row ONLY when it provably corresponds to a candidate
+ * the next re-extract will emit — either verbatim (dash bullets, no-delimiter
+ * pipe bullets, citation rows: same summary, new source label) or via the
+ * shared link-aware `Source — Summary` split (pipe bullets). A blind split
+ * would corrupt dash-bullet rows whose text contains an interior ` - `.
+ * Legacy rows with no matching candidate (content edited/deleted since) are
+ * left as-is: a re-extract won't re-emit them, so they can't duplicate.
+ *
+ * Idempotent (rewritten rows no longer match `source = ''`); same SQL text on
+ * both engines. When the new-shape row ALREADY exists (a re-extract duplicated
+ * before this repair ran), the legacy row is deleted instead of rewritten.
+ */
+export async function repairLegacyTimelineSourceRows(
+ engine: BrainEngine,
+): Promise<LegacyTimelineRepairResult> {
+ const result: LegacyTimelineRepairResult = {
+ pagesScanned: 0, rowsRewritten: 0, rowsDeleted: 0, rowsSkipped: 0,
+ };
+ const tbl = await engine.executeRaw<{ reg: string | null }>(
+ `SELECT to_regclass('timeline_entries')::text AS reg`,
+ );
+ if (!tbl[0]?.reg) return result;
+
+ // Soft-deleted pages are skipped: their rows are never re-extracted, so
+ // they cannot duplicate — and their content is not authoritative.
+ const pageIds = await engine.executeRaw<{ page_id: number }>(
+ `SELECT DISTINCT te.page_id
+ FROM timeline_entries te
+ JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL
+ WHERE te.source = ''`,
+ );
+ if (pageIds.length === 0) return result;
+
+ const PAGE_BATCH = 100;
+ for (let i = 0; i < pageIds.length; i += PAGE_BATCH) {
+ const ids = pageIds.slice(i, i + PAGE_BATCH).map(r => Number(r.page_id));
+ const pages = await engine.executeRaw<{
+ id: number; compiled_truth: string | null; timeline: string | null;
+ }>(
+ `SELECT id, compiled_truth, timeline FROM pages WHERE id = ANY($1::int[])`,
+ [ids],
+ );
+ for (const page of pages) {
+ result.pagesScanned++;
+ // Same content assembly as the DB extract paths (extractStaleFromDB /
+ // extractTimelineFromDB): body + timeline column.
+ const fullContent = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;
+ const byDate = new Map<string, Array<{ source: string; summary: string }>>();
+ for (const c of parseTimelineEntries(fullContent)) {
+ const list = byDate.get(c.date) ?? [];
+ list.push({ source: c.source ?? '', summary: c.summary });
+ byDate.set(c.date, list);
+ }
+ const legacyRows = await engine.executeRaw<{
+ id: number; date: string; summary: string;
+ }>(
+ `SELECT id, to_char(date, 'YYYY-MM-DD') AS date, summary
+ FROM timeline_entries WHERE page_id = $1 AND source = ''
+ ORDER BY id`,
+ [page.id],
+ );
+ for (const row of legacyRows) {
+ const candidates = byDate.get(row.date) ?? [];
+ let target: { source: string; summary: string } | null = null;
+ // 1. Verbatim: the new parser emits the same summary under a real
+ // source label (dash bullets → 'markdown', citations → label).
+ target = candidates.find(c => c.source !== '' && c.summary === row.summary) ?? null;
+ // 2. Split: the legacy summary is the UNSPLIT `Source — Summary`
+ // text of a pipe bullet; the shared delimiter finder must yield
+ // exactly the candidate's (source, summary) pair.
+ if (!target) {
+ const at = findTimelineSourceDelimiter(row.summary);
+ if (at >= 0) {
+ const pre = row.summary.slice(0, at).trim();
+ const post = row.summary.slice(at + 1).trim();
+ target = candidates.find(c => c.source === pre && c.summary === post) ?? null;
+ }
+ }
+ if (!target) { result.rowsSkipped++; continue; }
+ // A new-shape duplicate may already exist (re-extract ran before this
+ // repair): drop the legacy row instead of colliding with the unique
+ // (page_id, date, md5(summary), source) index on UPDATE.
+ const del = await engine.executeRaw<{ id: number }>(
+ `DELETE FROM timeline_entries t
+ WHERE t.id = $1
+ AND EXISTS (
+ SELECT 1 FROM timeline_entries x
+ WHERE x.page_id = t.page_id AND x.date = t.date
+ AND md5(x.summary) = md5($2) AND x.source = $3 AND x.id <> t.id
+ )
+ RETURNING t.id`,
+ [row.id, target.summary, target.source],
+ );
+ if (del.length > 0) { result.rowsDeleted++; continue; }
+ await engine.executeRaw(
+ `UPDATE timeline_entries SET source = $2, summary = $3
+ WHERE id = $1 AND source = ''`,
+ [row.id, target.source, target.summary],
+ );
+ result.rowsRewritten++;
+ }
+ }
+ }
+ return result;
+}
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index 003de274b6..f7036f5124 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -11,7 +11,7 @@
* names, so its existing importers are unaffected.
*/
-import { parseInlineCitationTimelineEntries } from './link-extraction.ts';
+import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter } from './link-extraction.ts';
export interface ExtractedTimelineEntry {
slug: string;
@@ -21,33 +21,12 @@ export interface ExtractedTimelineEntry {
detail?: string;
}
-/**
- * Index of the first dash (—, –, -) that can serve as the Source — Summary
- * delimiter: it must have whitespace on both sides and sit outside every
- * markdown-link span. Hyphens inside link targets
- * (`../people/alice-example.md`) and dashes inside link labels
- * (`[Deals — Q1 Review](...)`) are content, not delimiters — splitting on
- * them shatters one entry into two fragments whose halves re-insert on
- * every sync (the (page_id, date, summary, source) uniqueness sees each
- * fragment shape as a new row). Returns -1 when the line has no delimiter.
- */
-function findDelimiterOutsideLinks(text: string): number {
- let depth = 0;
- for (let i = 0; i < text.length; i++) {
- const c = text[i];
- if (c === '[' || c === '(') depth++;
- else if (c === ']' || c === ')') { if (depth > 0) depth--; }
- else if (
- depth === 0 &&
- (c === '—' || c === '–' || c === '-') &&
- i > 0 && /\s/.test(text[i - 1]) &&
- i + 1 < text.length && /\s/.test(text[i + 1])
- ) {
- return i;
- }
- }
- return -1;
-}
+// #3957: the link-aware `Source — Summary` delimiter finder moved to
+// link-extraction.ts (findTimelineSourceDelimiter) so the DB-side parser
+// (parseTimelineEntries) applies the IDENTICAL split — FS- and DB-extracted
+// rows must share one (source, summary) shape or the timeline dedup index
+// duplicates every bullet extracted through both paths.
+const findDelimiterOutsideLinks = findTimelineSourceDelimiter;
/** Extract timeline entries from markdown content */
export function extractTimelineFromContent(content: string, slug: string): ExtractedTimelineEntry[] {
diff --git a/src/core/types.ts b/src/core/types.ts
index 718c1c82a2..d750bf8047 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -214,6 +214,14 @@ export interface PageInput {
compiled_truth: string;
timeline?: string;
frontmatter?: Record<string, unknown>;
+ /**
+ * #3694: page tags for content-hash parity with the importer. The importer
+ * (parseMarkdown) hoists `tags` out of frontmatter; putPage callers usually
+ * leave them inside `frontmatter.tags`. `contentHash` accepts either
+ * (`page.tags ?? frontmatter.tags`, sorted) so both spellings hash the same.
+ * Optional — omitting it keeps existing callers source-compatible.
+ */
+ tags?: string[];
content_hash?: string;
/**
* v0.19.0: distinguishes markdown vs code pages at the DB level. Defaults
@@ -342,6 +350,14 @@ export interface PageFilters {
/** Inclusive bounds on semantic page time. NULL effective dates do not match. */
effective_after?: string;
effective_before?: string;
+ /**
+ * #4352 remediation — hide pages whose frontmatter carries
+ * `visibility: private` (absent visibility defaults to 'world'). Set by
+ * list_pages for untrusted callers via resolveExcludePrivatePages; trusted
+ * local listing is unchanged. Predicate matches privatePagesFilterFragment
+ * (search/private-visibility.ts) in BOTH engines.
+ */
+ excludePrivate?: boolean;
}
/** v0.26.5 — opts for getPage / softDeletePage / restorePage. */
@@ -757,6 +773,17 @@ export interface SearchResult {
* pages.
*/
unverified?: boolean;
+ /**
+ * #4220: the page's raw `frontmatter.status` value (e.g. 'draft',
+ * 'superseded', 'restricted', 'unverified', 'verified'), surfaced so agents
+ * can weigh lifecycle state without a follow-up page fetch. Stamped
+ * pre-fusion by `stampUnverifiedExtractions` (hybrid.ts) from the same
+ * batched query that powers the quarantine lane. Absent when the page has
+ * no status frontmatter. NOTE: `unverified` stays the load-bearing
+ * quarantine flag (requires provenance='auto-extracted' too); `status`
+ * alone is informational.
+ */
+ status?: string;
/**
* v0.36 (cross-modal wave): the chunk's modality discriminator from
* content_chunks.modality. 'text' for the existing text-embedding rows,
@@ -903,6 +930,24 @@ export interface SearchResult {
* decision keys off (T4).
*/
alias_hit?: boolean;
+ /**
+ * #3783 — set when this result was surfaced by a LEXICAL arm (chunk-grain
+ * keyword FTS or the page-grain title arm). Stamped pre-fusion by
+ * markKeywordHits and OR-propagated through RRF fusion so a row that
+ * arrived via both vector and keyword arms keeps the flag regardless of
+ * which copy fusion saw first. `evidence: keyword_exact` fires ONLY on
+ * rows carrying this flag — a pure-vector row with a solid blended score
+ * is no longer mislabeled as a keyword match.
+ */
+ keyword_hit?: boolean;
+ /**
+ * #1663 — set when the structural exact-lookup tier promoted/injected this
+ * result (query was the page's slug or exact normalized title). Drives the
+ * autocut preserve predicate (tier hits carry no rerank_score) and
+ * `--explain` telemetry; evidence still reads via alias_hit /
+ * title_match_boost so the frozen EVIDENCE_ENUM is untouched.
+ */
+ exact_lookup?: 'slug' | 'title';
/**
* T4 — the strongest signal that surfaced this page (alias_hit >
* exact_title_match > high_vector_match > keyword_exact > weak_semantic).
@@ -1164,6 +1209,17 @@ export interface SearchOpts {
* upper bound on result size.
*/
tokenBudget?: number;
+ /**
+ * #4352 — page-level `visibility: private` enforcement for untrusted
+ * callers. When true, both engines' search paths (keyword, titles,
+ * keyword-chunks, vector) add
+ * `COALESCE(p.frontmatter->>'visibility','world') <> 'private'` to the
+ * visibility clause. Callers resolve trust + the config gate via
+ * `resolveExcludePrivatePages` (search/private-visibility.ts):
+ * ctx.remote !== false → true unless the operator opted out. Omitted /
+ * false = pre-fix behavior (trusted local reads see everything).
+ */
+ excludePrivate?: boolean;
/**
* v0.32.x (search-lite): enable/disable the semantic query cache for this
* call. When undefined, the cache decision falls back to global config
@@ -1799,6 +1855,14 @@ export interface HybridSearchMeta {
* `gbrain search --explain`.
*/
autocut?: import('./search/autocut.ts').AutocutDecision;
+ /**
+ * #3995 — guaranteed page-1 relational evidence slot. Present only when a
+ * fired relational arm's answer had to be promoted from beyond the limit
+ * window (fusion overflow) or re-injected after autocut/trim dropped it.
+ * Omitted on clean runs (evidence already on page 1) and when the arm
+ * didn't fire. Surfaced for `gbrain search --explain`.
+ */
+ relational_evidence_slot?: import('./search/relational-recall.ts').RelationalEvidenceSlotDecision;
/**
* v0.32.x (search-lite): token budget enforcement metadata. Omitted when
* no budget was applied (backward-compatible with pre-search-lite
diff --git a/src/core/utils.ts b/src/core/utils.ts
index b4da05145b..b85ae8adc3 100644
--- a/src/core/utils.ts
+++ b/src/core/utils.ts
@@ -1,6 +1,10 @@
import { createHash, randomBytes } from 'crypto';
import type { Page, PageInput, PageType, Chunk, SearchResult, StalePageRow } from './types.ts';
import type { Take, TakeKind, TakeHit } from './engine.ts';
+// Leaf modules (no imports) — safe here without a cycle. Single source of
+// truth for the hash-ephemeral frontmatter keys shared with the importer.
+import { QUARANTINE_KEY, CONTENT_FLAG_KEY } from './quarantine.ts';
+import { EMBED_SKIP_KEY } from './embed-skip.ts';
/**
* SHA-256 hash a token/secret for storage. Never store plaintext tokens.
@@ -52,11 +56,65 @@ export function validateSlug(slug: string): string {
return slug.toLowerCase();
}
+/**
+ * Frontmatter keys excluded from the content hash. Timestamp-bearing keys
+ * (`captured_at`/`ingested_at`, stamped per capture call) and gate-derived
+ * sanity markers (quarantine / content_flag / embed_skip, re-derived
+ * deterministically on every import) would otherwise churn the hash on
+ * every write and defeat the import skip — full rationale at the CV8/#1699
+ * comment in `src/core/import-file.ts`.
+ */
+export const HASH_EPHEMERAL_FRONTMATTER_KEYS: readonly string[] = [
+ 'captured_at',
+ 'ingested_at',
+ QUARANTINE_KEY,
+ CONTENT_FLAG_KEY,
+ EMBED_SKIP_KEY,
+];
+
/**
* SHA-256 hash of page content, used for import idempotency.
- * Hashes all PageInput fields to match importFromContent's hash algorithm.
+ *
+ * #3694: this is now THE canonical formula, byte-identical to the importer's
+ * (`importFromContent`). Pre-fix, this helper (used by both engines' putPage
+ * fallback) hashed a different shape — no ephemeral-key strip, no tags — so
+ * the same logical page got one hash from `putPage` and another from
+ * `gbrain sync`/import, and every putPage→sync roundtrip re-chunked +
+ * re-embedded unchanged content (real, unbounded embedding spend).
+ *
+ * Shape (field order is load-bearing — JSON.stringify serializes insertion
+ * order and the digest is over the bytes):
+ * { title, type, compiled_truth, timeline||'', frontmatter*, tags* }
+ * where frontmatter* is a copy stripped of HASH_EPHEMERAL_FRONTMATTER_KEYS
+ * and the `tags` key, and tags* is `page.tags ?? frontmatter.tags` sorted
+ * (importer parity: parseMarkdown hoists tags out of frontmatter; putPage
+ * callers usually leave them inside — both now hash identically).
*/
export function contentHash(page: PageInput): string {
+ const fm: Record<string, unknown> = { ...(page.frontmatter || {}) };
+ for (const k of HASH_EPHEMERAL_FRONTMATTER_KEYS) delete fm[k];
+ const rawTags = page.tags ?? fm.tags;
+ delete fm.tags;
+ const tags = Array.isArray(rawTags) ? rawTags.map(t => String(t)).sort() : [];
+ return createHash('sha256')
+ .update(JSON.stringify({
+ title: page.title,
+ type: page.type,
+ compiled_truth: page.compiled_truth,
+ timeline: page.timeline || '',
+ frontmatter: fm,
+ tags,
+ }))
+ .digest('hex');
+}
+
+/**
+ * The pre-#3694 putPage-side formula (no ephemeral strip, no tags array).
+ * Kept ONLY so the importer can recognize a DB row written by the old
+ * formula whose content is actually unchanged, stamp it with the canonical
+ * hash, and skip the pointless re-chunk/re-embed. Do not use in new code.
+ */
+export function contentHashLegacy(page: PageInput): string {
return createHash('sha256')
.update(JSON.stringify({
title: page.title,
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 88450ce6d5..3e4f9db5ce 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -23,7 +23,7 @@ import type { BrainEngine, FactRow } from '../engine.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
import { slugify } from '../entities/resolve.ts';
import { safeSynopsis } from '../context/retrieval-reflex.ts';
-import { stampEvidence } from '../search/evidence.ts';
+import { stampEvidence, markKeywordHits } from '../search/evidence.ts';
import type { SearchResult } from '../types.ts';
const EDGE_CAP = 10;
@@ -105,6 +105,16 @@ export async function buildEntityCard(
const trimmed = (name ?? '').trim();
if (!trimmed) return { found: false, suggestions: [] };
+ // #4352 — untrusted callers never resolve a `visibility: private` page into
+ // a card (or a near-miss suggestion). Trust + config gate resolve through
+ // the shared helper; local (remote:false) callers are unchanged. Covers
+ // entity, context_pack, and delta (all route through buildEntityCard).
+ const { resolveExcludePrivatePages, privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(engine, opts.remote ? undefined : false);
+ // Predicate text lives ONCE (private-visibility.ts) — both card queries
+ // below select `FROM pages` unaliased, so qualify with the table name.
+ const privatePredicate = excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '';
+
const norm = normalizeAlias(trimmed);
const titleLc = trimmed.toLowerCase();
// Two exact-slug candidates: the slugified form for free-text names AND the
@@ -142,7 +152,7 @@ export async function buildEntityCard(
AND source_id = $1
AND ( lower(title) = $2
OR slug = ANY($3::text[])
- OR slug LIKE $4 )`,
+ OR slug LIKE $4 )${privatePredicate}`,
[sourceId, titleLc, exactSlugs, `%/${slug || trimmed}`],
);
} catch {
@@ -162,7 +172,7 @@ export async function buildEntityCard(
const extra = await engine.executeRaw<CardPageRow>(
`SELECT slug, source_id, title, type, frontmatter, compiled_truth, updated_at, last_retrieved_at
FROM pages
- WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])`,
+ WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])${privatePredicate}`,
[sourceId, missing],
);
for (const r of extra) rowBySlug.set(r.slug, r);
@@ -178,7 +188,7 @@ export async function buildEntityCard(
.sort((a, b) => a.rank - b.rank || lastTouchedMs(b.row) - lastTouchedMs(a.row));
if (candidates.length === 0) {
- return { found: false, suggestions: await nearMissSuggestions(engine, sourceId, trimmed) };
+ return { found: false, suggestions: await nearMissSuggestions(engine, sourceId, trimmed, excludePrivate) };
}
const best = candidates[0];
@@ -317,10 +327,13 @@ async function nearMissSuggestions(
engine: BrainEngine,
sourceId: string,
name: string,
+ excludePrivate = false,
): Promise<EntitySuggestion[]> {
try {
- const raw = await engine.searchKeyword(name, { limit: SUGGESTION_CAP, sourceId });
+ const raw = await engine.searchKeyword(name, { limit: SUGGESTION_CAP, sourceId, excludePrivate });
const results = raw as SearchResult[];
+ // #3783 — direct FTS path: every row is a keyword hit by construction.
+ markKeywordHits(results);
stampEvidence(results);
return results.map(r => ({
slug: r.slug,
diff --git a/src/core/zombie-reap.ts b/src/core/zombie-reap.ts
index 4946e3e081..8288e74a6d 100644
--- a/src/core/zombie-reap.ts
+++ b/src/core/zombie-reap.ts
@@ -14,6 +14,8 @@
* same process).
*/
+import { installPid1OrphanReaper } from './pid1-reaper.ts';
+
const reapHandler = () => {};
export function installSigchldHandler(): void {
@@ -24,6 +26,12 @@ export function installSigchldHandler(): void {
if (!process.listeners('SIGCHLD').includes(reapHandler)) {
process.on('SIGCHLD', reapHandler);
}
+ // #2443: the handler above only reaps Bun-TRACKED children. When gbrain
+ // runs as PID 1 in a container (no tini / --init), orphaned grandchildren
+ // re-parent to us and their exits are never reaped — install the /proc
+ // scanning orphan reaper too. Self-gates (linux + pid==1 +
+ // GBRAIN_PID1_REAP off-switch); a pure no-op everywhere else.
+ installPid1OrphanReaper();
}
/**
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 0c1bcb164d..602b2ddfdd 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -13,10 +13,10 @@ import type { Operation } from '../core/operations.ts';
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
import {
- resolveSocketPath,
+ resolveSocketPathForConfig,
startResolveIpcServer,
cleanupStaleSocket,
- ensureIpcSecret,
+ ensureIpcSecretForConfig,
type IpcHandlers,
} from '../core/context/resolve-ipc.ts';
import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';
@@ -180,22 +180,25 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// 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.
+ // 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();
- if (cfg?.engine === 'pglite' && cfg.database_path) {
- resolveSocket = resolveSocketPath(cfg.database_path);
+ resolveSocket = resolveSocketPathForConfig(cfg);
+ if (resolveSocket) {
const { sourceId: defaultSource } = await resolveMcpStdioSourceScope(engine);
- // [S3#6] turn_context requires the shared secret from the data dir
- // (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.
+ // [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 = ensureIpcSecret(cfg.database_path);
+ 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 /
@@ -221,6 +224,26 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
);
}
}
+ // 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,
{
@@ -270,6 +293,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// complete-pack-only monotonic cursor advance.
context_pack: makeContextPackIpcHandler(engine, defaultSource),
...syncHandlers,
+ ...sweepHandlers,
},
{
// The IPC resolve path IS the ambient reflex channel. Logging happens
@@ -360,13 +384,16 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// Backward compat: used by `gbrain call` command (trusted local path).
// v0.31.8 (D22): accept opts.sourceId so `gbrain call --source X <op> <json>`
-// can scope the op handler to that source. resolveSourceId() in call.ts is
-// the upstream resolver; this layer just passes the resolved id through.
+// can scope the op handler to that source. resolveSourceWithTier() in call.ts
+// is the upstream resolver; this layer just passes the resolved id through.
+// #3874: also accept opts.localFederatedSourceIds so an ambient-tier
+// resolution widens unqualified reads across federated sources exactly like
+// the direct CLI path (cli.ts makeContext) does.
export async function handleToolCall(
engine: BrainEngine,
tool: string,
params: Record<string, unknown>,
- opts?: { sourceId?: string },
+ opts?: { sourceId?: string; localFederatedSourceIds?: string[] },
): Promise<unknown> {
const op = operations.find(o => o.name === tool);
if (!op) throw new Error(`Unknown tool: ${tool}`);
@@ -378,6 +405,9 @@ export async function handleToolCall(
remote: false,
logger: { info: console.log, warn: console.warn, error: console.error },
...(opts?.sourceId ? { sourceId: opts.sourceId } : {}),
+ ...(opts?.localFederatedSourceIds
+ ? { localFederatedSourceIds: opts.localFederatedSourceIds }
+ : {}),
});
return op.handler(ctx, params);
diff --git a/src/schema.sql b/src/schema.sql
index f625aad951..1040be4924 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -554,7 +554,10 @@ CREATE INDEX IF NOT EXISTS idx_timeline_date ON timeline_entries(date);
-- v0.41.18.0 (codex finding #11): widened from (page_id, date, summary) to
-- include `source` so distinct meeting provenance survives. Legacy rows
-- have source='' (schema default) so legacy dedup behavior is preserved.
-CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, summary, source);
+-- #3737: keyed on md5(summary) — a raw long/incompressible summary overflowed
+-- the btree v4 row cap (~2704 bytes) and aborted the whole timeline insert.
+-- Both insert sites infer ON CONFLICT (page_id, date, md5(summary), source).
+CREATE UNIQUE INDEX IF NOT EXISTS idx_timeline_dedup ON timeline_entries(page_id, date, md5(summary), source);
-- v0.42.x (Life Chronicle): event-projection lookup + dedup. Partial
-- (event_page_id IS NOT NULL) so ordinary timeline rows are unaffected.
CREATE INDEX IF NOT EXISTS idx_timeline_event_page ON timeline_entries(event_page_id) WHERE event_page_id IS NOT NULL;
@@ -787,6 +790,28 @@ CREATE TABLE IF NOT EXISTS session_context_state (
CREATE INDEX IF NOT EXISTS session_context_state_updated_idx
ON session_context_state (updated_at);
+-- chat_usage_log (#4218 / migration v140): durable per-call chat usage
+-- ledger. One row per SUCCESSFUL gateway.chat() call, written fire-and-forget
+-- by the chat-usage sink (src/core/ai/chat-usage.ts). cost_usd is a
+-- canonical-table estimate; NULL when the model has no pricing (never a fake
+-- 0). Read back by the `get_usage` op with explicit coverage fields.
+CREATE TABLE IF NOT EXISTS chat_usage_log (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ model TEXT NOT NULL,
+ provider TEXT,
+ phase TEXT,
+ input_tokens INTEGER NOT NULL DEFAULT 0,
+ output_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
+ cost_usd DOUBLE PRECISION
+);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_created
+ ON chat_usage_log (created_at);
+CREATE INDEX IF NOT EXISTS idx_chat_usage_log_model
+ ON chat_usage_log (model, created_at);
+
-- migration_impact_log moved BELOW minion_jobs (was here, lines 645-676)
-- because its `job_id BIGINT REFERENCES minion_jobs(id)` FK requires
-- minion_jobs to exist FIRST during SCHEMA_SQL replay. v0.41.25.0 fix.
@@ -1408,8 +1433,8 @@ CREATE INDEX IF NOT EXISTS take_nudge_log_proposal_cooldown_idx
CREATE INDEX IF NOT EXISTS take_nudge_log_wave_idx
ON take_nudge_log (wave_version, fired_at DESC);
--- think_ab_results (v0.36.1.0 T18 / D19): A/B harness data for
--- `gbrain think --ab`. One row per side-by-side comparison.
+-- think_ab_results (v0.36.1.0 T18 / D19): A/B harness data for the think
+-- A/B harness (runAbTrial). One row per side-by-side comparison.
CREATE TABLE IF NOT EXISTS think_ab_results (
id BIGSERIAL PRIMARY KEY,
source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 90aad460f8..b7810574ef 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.27.0 -->
+<!-- gbrain-template-stamp: 0.46.28.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/no-batch-cap-item-split.test.ts b/test/ai/no-batch-cap-item-split.test.ts
new file mode 100644
index 0000000000..2fa76a48d9
--- /dev/null
+++ b/test/ai/no-batch-cap-item-split.test.ts
@@ -0,0 +1,133 @@
+/**
+ * #3875 — `no_batch_cap` recipes get a default per-call item cap.
+ *
+ * Before this fix, recipes that declare `no_batch_cap: true` (Ollama, LiteLLM
+ * proxy) sent ALL of a file's chunks to the provider in ONE request, so the
+ * per-SDK-call AI_EMBED_TIMEOUT_MS (60s) silently became a per-FILE budget —
+ * a slow local model embedding a large file timed out deterministically and
+ * no retry could ever succeed.
+ *
+ * Now embed() caps those recipes at NO_BATCH_CAP_SUB_BATCH_ITEMS inputs per
+ * transport call (explicit `max_batch_items` still wins), making the timeout
+ * a per-batch bound. Verified through the public embed() with the transport
+ * stubbed (same seam as adaptive-embed-batch.test.ts).
+ */
+
+import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import {
+ configureGateway,
+ resetGateway,
+ embed,
+ NO_BATCH_CAP_SUB_BATCH_ITEMS,
+ __setEmbedTransportForTests,
+} from '../../src/core/ai/gateway.ts';
+import { __setTestRecipesForTests } from '../../src/core/ai/recipes/index.ts';
+import type { Recipe } from '../../src/core/ai/types.ts';
+
+// Same leak-guard rationale as adaptive-embed-batch.test.ts: never leave a
+// configured gateway (or a synthetic recipe list) behind for the next file.
+afterAll(() => {
+ __setTestRecipesForTests([]);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+});
+
+function fakeEmbeddings(values: string[], dims: number): { embeddings: number[][] } {
+ return {
+ embeddings: values.map((_, i) =>
+ Array.from({ length: dims }, (_, j) => (j === 0 ? i : 0.1)),
+ ),
+ };
+}
+
+/** A dynamic-cap recipe shaped like ollama/litellm: no token cap, no item cap. */
+const NO_CAP_RECIPE: Recipe = {
+ id: 'synthetic-nocap',
+ name: 'Synthetic no_batch_cap (test fixture)',
+ tier: 'openai-compat',
+ implementation: 'openai-compatible',
+ base_url_default: 'http://localhost:9/v1',
+ touchpoints: {
+ embedding: {
+ models: ['synthetic-embed-1'],
+ default_dims: 8,
+ no_batch_cap: true,
+ },
+ },
+};
+
+/** Same, but with an explicit max_batch_items — the explicit cap must win. */
+const EXPLICIT_CAP_RECIPE: Recipe = {
+ ...NO_CAP_RECIPE,
+ id: 'synthetic-explicitcap',
+ touchpoints: {
+ embedding: {
+ models: ['synthetic-embed-1'],
+ default_dims: 8,
+ no_batch_cap: true,
+ max_batch_items: 4,
+ },
+ },
+};
+
+describe('#3875 embed() item-caps no_batch_cap recipes', () => {
+ beforeEach(() => resetGateway());
+ afterEach(() => {
+ __setEmbedTransportForTests(null);
+ __setTestRecipesForTests([]);
+ });
+
+ test('40 texts split into ceil(40/CAP) transport calls, each <= CAP', async () => {
+ __setTestRecipesForTests([NO_CAP_RECIPE]);
+ configureGateway({
+ embedding_model: 'synthetic-nocap:synthetic-embed-1',
+ embedding_dimensions: 8,
+ env: {},
+ });
+ const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 8));
+ __setEmbedTransportForTests(stub as any);
+
+ const texts = Array.from({ length: 40 }, (_, i) => `t${i}`);
+ const result = await embed(texts);
+
+ const cap = NO_BATCH_CAP_SUB_BATCH_ITEMS;
+ const expectedCalls = Math.ceil(40 / cap);
+ expect(stub).toHaveBeenCalledTimes(expectedCalls);
+ for (const [arg] of stub.mock.calls) {
+ expect((arg as { values: string[] }).values.length).toBeLessThanOrEqual(cap);
+ }
+ // Order preserved across sub-batches: slot 0 encodes within-call index,
+ // so reassembled output must be within-call-ascending per batch and total
+ // length must match.
+ expect(result).toHaveLength(40);
+ });
+
+ test('a batch already under the cap stays a single call', async () => {
+ __setTestRecipesForTests([NO_CAP_RECIPE]);
+ configureGateway({
+ embedding_model: 'synthetic-nocap:synthetic-embed-1',
+ embedding_dimensions: 8,
+ env: {},
+ });
+ const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 8));
+ __setEmbedTransportForTests(stub as any);
+
+ await embed(['a', 'b', 'c']);
+ expect(stub).toHaveBeenCalledTimes(1);
+ });
+
+ test('an explicit max_batch_items wins over the no_batch_cap default', async () => {
+ __setTestRecipesForTests([EXPLICIT_CAP_RECIPE]);
+ configureGateway({
+ embedding_model: 'synthetic-explicitcap:synthetic-embed-1',
+ embedding_dimensions: 8,
+ env: {},
+ });
+ const stub = mock(async ({ values }: { values: string[] }) => fakeEmbeddings(values, 8));
+ __setEmbedTransportForTests(stub as any);
+
+ await embed(Array.from({ length: 10 }, (_, i) => `t${i}`));
+ const sizes = stub.mock.calls.map(([arg]) => (arg as { values: string[] }).values.length);
+ expect(sizes).toEqual([4, 4, 2]);
+ });
+});
diff --git a/test/archived-source-scoping.test.ts b/test/archived-source-scoping.test.ts
new file mode 100644
index 0000000000..174f07abb2
--- /dev/null
+++ b/test/archived-source-scoping.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #3880 — archived sources must not re-enter automatic active-source
+ * operations whose SQL used to filter only `local_path IS NOT NULL`.
+ *
+ * Two layers:
+ * 1. Behavioral: the tier-4 cwd resolver prefers ACTIVE sources — an
+ * archived deeper registration can't shadow an active parent — while a
+ * cwd landing ONLY in an archived tree still throws (the deliberate
+ * "explicit unavailable target" rule).
+ * 2. Structural: every all-source local_path selection in the affected
+ * files carries `archived IS NOT TRUE` (with the v34 legacy fallback).
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ resolveSourceId,
+ resolveSourceWithTier,
+ SourceTargetError,
+} from '../src/core/source-resolver.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+type StubSource = { id: string; local_path: string | null; archived?: boolean };
+
+function stubEngine(sources: StubSource[]): BrainEngine {
+ return {
+ executeRaw: async (sql: string, params?: unknown[]) => {
+ if (sql.includes('archived FROM sources WHERE local_path IS NOT NULL')) {
+ return sources
+ .filter((s) => s.local_path !== null)
+ .map((s) => ({ id: s.id, local_path: s.local_path, archived: s.archived === true }));
+ }
+ if (sql.includes('WHERE id = $1 AND archived = false')) {
+ return sources
+ .filter((s) => s.id === params?.[0] && s.archived !== true)
+ .map((s) => ({ id: s.id }));
+ }
+ if (sql.includes("id != 'default'")) {
+ // pickSoleNonDefaultSource — not the tier under test; return 2 rows
+ // so it never fires.
+ return [{ id: 'a' }, { id: 'b' }];
+ }
+ if (sql.includes('FROM pages')) return [];
+ return [];
+ },
+ getConfig: async () => null,
+ } as unknown as BrainEngine;
+}
+
+let root: string;
+let activeParent: string;
+let archivedChild: string;
+let archivedOnly: string;
+
+beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-3880-'));
+ activeParent = join(root, 'vault');
+ archivedChild = join(activeParent, 'sub');
+ archivedOnly = join(root, 'graveyard');
+ mkdirSync(join(archivedChild, 'notes'), { recursive: true });
+ mkdirSync(join(archivedOnly, 'notes'), { recursive: true });
+});
+
+afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('#3880 tier-4 cwd resolution vs archived sources', () => {
+ test('archived deeper registration does NOT shadow an active parent source', async () => {
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ const engine = stubEngine([
+ { id: 'vault', local_path: activeParent },
+ { id: 'old-sub', local_path: archivedChild, archived: true },
+ ]);
+ const cwd = join(archivedChild, 'notes');
+ // Pre-fix: 'old-sub' won the longest-prefix match and assertSourceExists
+ // threw. Post-fix: the active parent resolves.
+ expect(await resolveSourceId(engine, null, cwd)).toBe('vault');
+ const withTier = await resolveSourceWithTier(engine, null, cwd);
+ expect(withTier.source_id).toBe('vault');
+ expect(withTier.tier).toBe('local_path');
+ });
+ });
+
+ test('cwd ONLY inside an archived tree still throws (explicit unavailable target)', async () => {
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ const engine = stubEngine([
+ { id: 'vault', local_path: activeParent },
+ { id: 'graveyard', local_path: archivedOnly, archived: true },
+ ]);
+ const cwd = join(archivedOnly, 'notes');
+ await expect(resolveSourceId(engine, null, cwd)).rejects.toThrow(SourceTargetError);
+ });
+ });
+});
+
+describe('#3880 structural pins — all-source local_path selections filter archived', () => {
+ const sites: Array<{ file: string; patched: number }> = [
+ { file: 'src/commands/sync.ts', patched: 1 },
+ { file: 'src/core/brain-writer.ts', patched: 1 },
+ { file: 'src/commands/doctor/checks/extraction-sync.ts', patched: 3 },
+ { file: 'src/commands/frontmatter-install-hook.ts', patched: 1 },
+ { file: 'src/commands/sources-harden.ts', patched: 1 },
+ ];
+ for (const { file, patched } of sites) {
+ test(`${file} carries ${patched} archived-filtered all-source selection(s)`, () => {
+ const src = readFileSync(file, 'utf-8');
+ const filtered = src.match(/local_path IS NOT NULL AND archived IS NOT TRUE/g) ?? [];
+ expect(filtered.length).toBeGreaterThanOrEqual(patched);
+ });
+ }
+
+ test('src/core/source-resolver.ts tier-4 selects the archived column for active-over-archived tiering', () => {
+ // The resolver keeps archived rows in the SELECT (JS tiering) so a cwd
+ // landing ONLY in an archived tree still throws the deliberate
+ // 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);
+ });
+});
diff --git a/test/auto-link-targeted-probe-2544.test.ts b/test/auto-link-targeted-probe-2544.test.ts
new file mode 100644
index 0000000000..4ffa2fd2e9
--- /dev/null
+++ b/test/auto-link-targeted-probe-2544.test.ts
@@ -0,0 +1,144 @@
+/**
+ * #2544 — runAutoLink's existence check is a targeted probe, not getAllSlugs.
+ *
+ * Pre-fix, EVERY put_page with auto-link enabled materialized the whole
+ * brain's slug set (getAllSlugs = full pages scan) just to validate a
+ * handful of candidate link targets. The check now probes exactly the
+ * candidate target/from slugs (`slug = ANY($1::text[]) AND source_id = $2`,
+ * the proven oneshot pattern) and skips the query when there are no
+ * candidates.
+ *
+ * These tests pin the BEHAVIOR through put_page: resolvable references
+ * still create links, references to nonexistent pages are still dropped
+ * (FK-churn guard), link-free pages still reconcile to zero, and source
+ * scoping still confines resolution to the write's source.
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+
+// PGLite schema init (130 migrations) exceeds the 5s default hook timeout on
+// a loaded machine — same mitigation as hybrid-cache-scope-poison.serial.
+setDefaultTimeout(30_000);
+
+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);
+ resetGateway(); // no embedding provider → put_page runs noEmbed
+});
+
+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')!;
+
+type PutResult = {
+ status: string;
+ auto_links?: { created: number; removed: number; errors: number } | { error: string } | { skipped: string };
+};
+
+async function put(slug: string, body: string, ctx = makeCtx()): Promise<PutResult> {
+ return (await putPage.handler(ctx, {
+ slug,
+ content: `---\ntitle: ${slug}\n---\n\n${body}`,
+ })) as PutResult;
+}
+
+describe('#2544 — auto-link behavior through put_page (targeted probe)', () => {
+ test('a reference to an existing page still creates the link', async () => {
+ await put('people/alice-example', 'A person page.');
+ const result = await put('meetings/2026-04-03', 'Discussed roadmap with people/alice-example today.');
+ expect(result.status).toBe('created_or_updated');
+ const links = result.auto_links as { created: number };
+ expect(links.created).toBeGreaterThanOrEqual(1);
+ const rows = await engine.getLinks('meetings/2026-04-03', { sourceId: 'default' });
+ expect(rows.some((l) => l.to_slug === 'people/alice-example')).toBe(true);
+ });
+
+ test('a reference to a nonexistent page is still dropped (no FK churn)', async () => {
+ const result = await put('meetings/2026-04-04', 'Mentioned people/ghost-nobody in passing.');
+ const links = result.auto_links as { created: number; errors: number };
+ expect(links.created).toBe(0);
+ expect(links.errors).toBe(0);
+ const rows = await engine.getLinks('meetings/2026-04-04', { sourceId: 'default' });
+ expect(rows).toHaveLength(0);
+ });
+
+ test('a link-free page reconciles to zero without error (probe skipped)', async () => {
+ const result = await put('inbox/plain-note', 'No references here at all.');
+ const links = result.auto_links as { created: number; removed: number; errors: number };
+ expect(links.created).toBe(0);
+ expect(links.errors).toBe(0);
+ });
+
+ test('resolution stays scoped to the write source', async () => {
+ // Target exists ONLY in 'default'. A write into source-b must not link to it.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config, created_at)
+ VALUES ('source-b', 'source-b', '/fake/source-b', '{}'::jsonb, NOW())
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ await put('people/alice-example', 'A person page in default.');
+ const result = await put(
+ 'meetings/cross-source',
+ 'Mentions people/alice-example which lives in another source.',
+ makeCtx({ sourceId: 'source-b' }),
+ );
+ const links = result.auto_links as { created: number };
+ expect(links.created).toBe(0);
+ const rows = await engine.getLinks('meetings/cross-source', { sourceId: 'source-b' });
+ expect(rows).toHaveLength(0);
+ });
+
+ test('probe binds the slug array with an explicit ::text[] cast (postgres.js parity)', () => {
+ // The PGLite behavior tests above can't see this: postgres.js binds a JS
+ // array parameter without server-side type context, so a bare ANY($1)
+ // relies on inference the house style never does (cf. dropPrivateSlugs in
+ // the same file). Pin the cast on EVERY slug-array probe in pages.ts.
+ // test-reads-source-ok: postgres.js-only bind-cast bug is invisible on the PGLite runtime path; the ::text[] cast pin is the unit-testable seam
+ const src = readFileSync(join(import.meta.dir, '../src/core/ops/pages.ts'), 'utf8');
+ const probes = src.match(/slug = ANY\(\$1[^)]*\)/g) ?? [];
+ expect(probes.length).toBeGreaterThanOrEqual(2); // both runAutoLink branches
+ for (const probe of probes) expect(probe).toContain('::text[]');
+ });
+
+ test('stale-link removal still works (reconciliation unaffected)', async () => {
+ await put('people/alice-example', 'A person page.');
+ await put('meetings/removal-check', 'With people/alice-example.');
+ const before = await engine.getLinks('meetings/removal-check', { sourceId: 'default' });
+ expect(before.some((l) => l.to_slug === 'people/alice-example')).toBe(true);
+ // Rewrite without the reference: the edge must be reconciled away.
+ const result = await put('meetings/removal-check', 'Reference removed entirely, new content.');
+ const links = result.auto_links as { removed: number };
+ expect(links.removed).toBeGreaterThanOrEqual(1);
+ const after = await engine.getLinks('meetings/removal-check', { sourceId: 'default' });
+ expect(after.some((l) => l.to_slug === 'people/alice-example')).toBe(false);
+ });
+});
diff --git a/test/autopilot-install.test.ts b/test/autopilot-install.test.ts
index 25f4d46f5e..8f7a50cc42 100644
--- a/test/autopilot-install.test.ts
+++ b/test/autopilot-install.test.ts
@@ -51,6 +51,23 @@ afterEach(() => {
try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
});
+function makeFakeGbrainOnPath(): { binDir: string; restore: () => void } {
+ // writeWrapperScript() calls resolveGbrainCliPath(), which shells out to
+ // `which gbrain`. Put a harmless shim on PATH so the test is deterministic
+ // regardless of whether the CI/dev machine has a real gbrain on PATH.
+ const binDir = mkdtempSync(join(tmpdir(), 'gbrain-fake-bin-'));
+ writeFileSync(join(binDir, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ const originalPath = process.env.PATH;
+ process.env.PATH = `${binDir}:${originalPath ?? ''}`;
+ return {
+ binDir,
+ restore: () => {
+ process.env.PATH = originalPath;
+ rmSync(binDir, { recursive: true, force: true });
+ },
+ };
+}
+
describe('detectInstallTarget', () => {
test('returns "macos" on darwin regardless of env', () => {
if (process.platform !== 'darwin') return; // Skip on non-mac CI
@@ -152,8 +169,32 @@ describe('autopilot showStatus — wrapper-path detection', () => {
});
});
+// #2608: the wrapper's key channel. The old `source ~/.zshrc || source
+// ~/.bashrc` chain only reached bashrc when zshrc FAILED — on machines with
+// both files the bash-managed keys never loaded, every LLM phase silently
+// no-op'd, and chronicle reported clean no_events runs forever. The wrapper
+// now sources both rc files independently; the deterministic env channel is
+// the gbrain-owned env file pinned by the suite below.
+describe('autopilot wrapper script — key sourcing (#2608)', () => {
+ test('wrapper sources zshrc AND bashrc independently (no || chain)', async () => {
+ // PATH shim like the env-file suite below: writeWrapperScript resolves
+ // the gbrain CLI path and throws on CI runners with no gbrain on PATH.
+ const fakeBin = makeFakeGbrainOnPath();
+ try {
+ const { writeWrapperScript } = await import('../src/commands/autopilot.ts');
+ const path = writeWrapperScript(join(tmp, 'fake-repo'), 'linux-cron');
+ const text = readFileSync(path, 'utf8');
+ expect(text).toContain('[ -f ~/.zshrc ] && source ~/.zshrc');
+ expect(text).toContain('[ -f ~/.bashrc ] && source ~/.bashrc');
+ expect(text).not.toContain('|| source ~/.bashrc');
+ } finally {
+ fakeBin.restore();
+ }
+ });
+});
+
// #2608: the wrapper's ONLY env channel was the shell rc files (zshenv,
-// zshrc||bashrc). Non-interactive daemon shells (launchd/systemd/cron) never
+// zshrc, bashrc). Non-interactive daemon shells (launchd/systemd/cron) never
// run zshrc-only exports, and the stock Debian ~/.bashrc non-interactive
// guard blocks even the .bashrc fallback — a common config, not a rare one.
// The fix is additive: the wrapper now ALSO sources a gbrain-owned env file
@@ -161,23 +202,6 @@ describe('autopilot showStatus — wrapper-path detection', () => {
// GBRAIN_HOME) after the profiles, and silently no-ops when that file is
// absent.
describe('autopilot wrapper script — gbrain-owned env file (#2608)', () => {
- function makeFakeGbrainOnPath(): { binDir: string; restore: () => void } {
- // writeWrapperScript() calls resolveGbrainCliPath(), which shells out to
- // `which gbrain`. Put a harmless shim on PATH so the test is deterministic
- // regardless of whether the CI/dev machine has a real gbrain on PATH.
- const binDir = mkdtempSync(join(tmpdir(), 'gbrain-fake-bin-'));
- writeFileSync(join(binDir, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
- const originalPath = process.env.PATH;
- process.env.PATH = `${binDir}:${originalPath ?? ''}`;
- return {
- binDir,
- restore: () => {
- process.env.PATH = originalPath;
- rmSync(binDir, { recursive: true, force: true });
- },
- };
- }
-
test('wrapper additively sources <gbrainDir>/env after the rc-file profiles, before PATH export/exec', () => {
const fakeBin = makeFakeGbrainOnPath();
try {
diff --git a/test/autopilot-launchd-lifecycle.serial.test.ts b/test/autopilot-launchd-lifecycle.serial.test.ts
index 31a3d6149a..f5461f70fd 100644
--- a/test/autopilot-launchd-lifecycle.serial.test.ts
+++ b/test/autopilot-launchd-lifecycle.serial.test.ts
@@ -183,7 +183,17 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
}, 120_000);
test('2. install --target macos: plist + wrapper + recorded load', () => {
- const r = runCli(['autopilot', '--install', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ // #677: a PGLite brain REFUSES a daemon install without --force (the
+ // daemon would hold the single-writer DB lock 24/7). Pin the refusal at
+ // the CLI boundary first, then run the lifecycle arc through the
+ // documented dedicated-brain override.
+ const refused = runCli(['autopilot', '--install', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ expect(refused.exitCode).toBe(1);
+ expect(refused.stderr).toContain('PGLite');
+ expect(refused.stderr).toContain('--force');
+ expect(existsSync(plist())).toBe(false);
+
+ const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(plist())).toBe(true);
const xml = readFileSync(plist(), 'utf8');
@@ -194,6 +204,13 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
expect(w.indexOf('repo path gone')).toBeGreaterThan(-1);
expect(w.indexOf('repo path gone')).toBeLessThan(w.indexOf('exec '));
expect(w).toContain(`gui/$(id -u)/${label}`);
+ // #3696: the repo-cwd pin lives in the WRAPPER, between guard and exec
+ // (a plist WorkingDirectory=repo would fail every respawn once the repo
+ // is deleted, so the guard could never fire). The plist must therefore
+ // NOT point its WorkingDirectory at the repo.
+ expect(w.indexOf('repo path gone')).toBeLessThan(w.indexOf(`\ncd '`));
+ expect(w.indexOf(`\ncd '`)).toBeLessThan(w.indexOf('exec '));
+ expect(xml).not.toContain(`<key>WorkingDirectory</key><string>${repoDir}</string>`);
}, 120_000);
test('3. repo deleted → three strikes, THEN marker + recorded bootout', () => {
@@ -229,7 +246,8 @@ describe.skipIf(SKIP_SUBPROCESS)('autopilot launchd lifecycle — shimmed (all p
// Recreate first — reinstalling against the deleted path would only prove
// marker-clearing while leaving an immediately-doomed install.
mkdirSync(repoDir, { recursive: true });
- const r = runCli(['autopilot', '--install', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ // --force: PGLite daemon guard (#677) — see test 2.
+ const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(marker())).toBe(false);
}, 120_000);
@@ -317,7 +335,9 @@ describe.skipIf(SKIP_SUBPROCESS || !LAUNCHD_OK)('autopilot launchd lifecycle —
});
test('1. install loads a real job and RunAtLoad runs our wrapper', async () => {
- const r = runCli(['autopilot', '--install', '--target', 'macos', '--repo', repoDir], env, 90_000);
+ // --force: PGLite daemon guard (#677) — the shimmed describe pins the
+ // refusal; this one exercises the real-launchd arc past it.
+ const r = runCli(['autopilot', '--install', '--force', '--target', 'macos', '--repo', repoDir], env, 90_000);
expect(r.exitCode).toBe(0);
expect(existsSync(plist())).toBe(true);
diff --git a/test/autopilot-lock.test.ts b/test/autopilot-lock.test.ts
index a48efeb928..5b5da7e0e5 100644
--- a/test/autopilot-lock.test.ts
+++ b/test/autopilot-lock.test.ts
@@ -7,7 +7,7 @@ import {
decideLockAcquisition,
isPidAlive,
} from '../src/commands/autopilot.ts';
-import { looksLikeGbrainAutopilotCommand } from '../src/core/autopilot-lock.ts';
+import { looksLikeGbrainAutopilotCommand, readProcessCommand } from '../src/core/autopilot-lock.ts';
let tmp: string;
let lockPath: string;
@@ -54,6 +54,23 @@ describe('decideLockAcquisition', () => {
})).toEqual({
action: 'exit',
holderPid: 1234,
+ holderState: 'alive-autopilot',
+ });
+ });
+
+ test('keeps a STALE lock whose holder is a live gbrain autopilot process', () => {
+ // The age gate applies only to non-autopilot holders: a genuine autopilot
+ // sibling is never stolen no matter how old the lockfile mtime is.
+ writeFileSync(lockPath, '1234');
+ const stale = new Date(Date.now() - AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS - 1000);
+ utimesSync(lockPath, stale, stale);
+ expect(decideLockAcquisition(lockPath, process.pid, {
+ isPidAlive: (pid) => pid === 1234,
+ readProcessCommand: () => 'gbrain autopilot --repo repo',
+ })).toEqual({
+ action: 'exit',
+ holderPid: 1234,
+ holderState: 'alive-autopilot',
});
});
@@ -65,6 +82,7 @@ describe('decideLockAcquisition', () => {
})).toEqual({
action: 'exit',
holderPid: 1234,
+ holderState: 'alive-foreign',
});
});
@@ -81,7 +99,7 @@ describe('decideLockAcquisition', () => {
});
});
- test('keeps a live lock when process identity cannot be inspected', () => {
+ test('keeps a FRESH lock when process identity cannot be inspected', () => {
writeFileSync(lockPath, '1234');
expect(decideLockAcquisition(lockPath, process.pid, {
isPidAlive: (pid) => pid === 1234,
@@ -89,6 +107,23 @@ describe('decideLockAcquisition', () => {
})).toEqual({
action: 'exit',
holderPid: 1234,
+ holderState: 'alive-unknown',
+ });
+ });
+
+ test('takes over a STALE lock when process identity cannot be inspected (#4300)', () => {
+ // Recycled PID after reboot on a host where the command probe fails:
+ // pre-fix this exited forever (bricked daemon). alive-unknown now shares
+ // the alive-foreign age gate.
+ writeFileSync(lockPath, '1234');
+ const stale = new Date(Date.now() - AUTOPILOT_FOREIGN_PID_TAKEOVER_GRACE_MS - 1000);
+ utimesSync(lockPath, stale, stale);
+ expect(decideLockAcquisition(lockPath, process.pid, {
+ isPidAlive: (pid) => pid === 1234,
+ readProcessCommand: () => null,
+ })).toEqual({
+ action: 'takeover',
+ reason: 'unidentifiable pid 1234 with stale lock',
});
});
@@ -100,6 +135,44 @@ describe('decideLockAcquisition', () => {
});
});
+describe('readProcessCommand', () => {
+ test('prefers /proc/<pid>/cmdline when readable (#4300)', () => {
+ const seen: string[] = [];
+ const cmd = readProcessCommand(1234, {
+ readCmdlineFile: (path) => {
+ seen.push(path);
+ return Buffer.from('gbrain\0autopilot\0--repo\0repo\0');
+ },
+ });
+ expect(seen).toEqual(['/proc/1234/cmdline']);
+ expect(cmd).toBe('gbrain autopilot --repo repo');
+ });
+
+ test('falls back to ps when the cmdline probe throws', () => {
+ // The current process always exists; ps must resolve it on macOS/Linux.
+ const cmd = readProcessCommand(process.pid, {
+ readCmdlineFile: () => {
+ throw new Error('ENOENT');
+ },
+ });
+ expect(cmd).not.toBeNull();
+ expect((cmd ?? '').length).toBeGreaterThan(0);
+ });
+
+ test('falls back to ps when the cmdline file is empty (zombie)', () => {
+ const cmd = readProcessCommand(process.pid, {
+ readCmdlineFile: () => Buffer.from(''),
+ });
+ expect(cmd).not.toBeNull();
+ });
+
+ test('returns null for invalid pids without probing', () => {
+ expect(readProcessCommand(0)).toBeNull();
+ expect(readProcessCommand(-5)).toBeNull();
+ expect(readProcessCommand(Number.NaN)).toBeNull();
+ });
+});
+
describe('looksLikeGbrainAutopilotCommand', () => {
test('matches packaged and source-tree autopilot invocations', () => {
expect(looksLikeGbrainAutopilotCommand('gbrain autopilot --repo repo')).toBe(true);
diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.ts
index f52a3afe47..e57cf158f8 100644
--- a/test/bootstrap-harness.serial.test.ts
+++ b/test/bootstrap-harness.serial.test.ts
@@ -457,7 +457,7 @@ describe('--status', () => {
const code = await statusHarness(parseHarnessArgs(['--status']), f.deps);
expect(code).toBe(0);
expect(f.out.join('\n')).toMatch(/token: OK .*codex config block/);
- expect(f.out.join('\n')).toMatch(/degraded on Postgres/);
+ expect(f.out.join('\n')).toMatch(/needs a running gbrain serve on Postgres/);
});
test('revoked-under-a-green-receipt: token verify fails → exit 1', async () => {
diff --git a/test/brain-durability-hook.serial.test.ts b/test/brain-durability-hook.serial.test.ts
index d751e573d4..99ef13feea 100644
--- a/test/brain-durability-hook.serial.test.ts
+++ b/test/brain-durability-hook.serial.test.ts
@@ -48,23 +48,16 @@ async function waitForOrigin(bare: string, expectSha: string, ms = 30_000): Prom
return false;
}
-/** #2943 (index.lock form): hardenBrainRepo installs the post-commit hook
- * BEFORE committing the scaffolding, so that commit fires the hook and
- * detaches a background brain_push. If that push loses the ref race against
- * hardenBrainRepo's own synchronous push, it falls back to `git pull
- * --rebase`, which takes .git/index.lock — racing the test body's first git
- * calls ("Unable to create '.../.git/index.lock': File exists"). Wait for the
- * detached push's terminal log line before handing the repo to the test. */
-async function waitForHookPushSettled(ms = 30_000): Promise<void> {
- const log = join(process.env.HOME!, '.gbrain', 'brain-push.log');
- const terminal = /\[push\] (ok|lock-timeout|LOCAL-ONLY)/;
- const deadline = Date.now() + ms;
- while (Date.now() < deadline) {
- if (existsSync(log) && terminal.test(readFileSync(log, 'utf-8'))) return;
- await new Promise(r => setTimeout(r, 150));
- }
- throw new Error(`detached hook push did not settle within ${ms}ms (${log})`);
-}
+// #2943 historical note: hardenBrainRepo installs the post-commit hook BEFORE
+// committing the scaffolding, and the scaffolding commit used to fire it —
+// detaching a background brain_push that raced hardenBrainRepo's own
+// synchronous push on the same ref (cannot-lock-ref; the loser's `pull
+// --rebase` then took .git/index.lock, racing the test body's first git
+// calls). This file used to park in a waitForHookPushSettled() poll after
+// every harden to let that race drain. #3925 removed the race at the source:
+// commitScaffolding commits with core.hooksPath=/dev/null, so the explicit
+// fail-loud push is the ONLY push and there is nothing to wait for. The
+// regression test below pins that.
let root: string, work: string, bare: string;
let oldHome: string | undefined, oldGbrainHome: string | undefined;
@@ -87,7 +80,6 @@ beforeEach(async () => {
git(work, 'add', 'README.md'); git(work, 'commit', '-qm', 'init'); git(work, 'push', '-q', 'origin', 'main');
git(work, 'remote', 'set-head', 'origin', 'main');
await hardenBrainRepo({ repoPath: work, sourceId: 'wiki', pat: 'ghp_x', installCron: false });
- await waitForHookPushSettled();
});
afterEach(() => {
if (oldHome === undefined) delete process.env.HOME; else process.env.HOME = oldHome;
@@ -165,6 +157,22 @@ describe('brain-commit-push.sh (D13 guarantee)', () => {
});
describe('post-commit hook (D9 local, D7 self-contained)', () => {
+ test('#3925 — the scaffolding commit does NOT fire the hook (no racing background push)', async () => {
+ // beforeEach ran hardenBrainRepo. commitScaffolding commits with
+ // core.hooksPath=/dev/null, so its explicit fail-loud push is the ONLY
+ // push. Pre-fix, the commit fired the just-installed post-commit hook,
+ // detaching a background brain_push that raced the explicit push on the
+ // same ref (the #2943 cannot-lock-ref / index.lock flake class).
+ // The explicit push landed the scaffolding commit:
+ expect(originHead(bare)).toBe(git(work, 'rev-parse', 'HEAD'));
+ // ...and the hook never fired during harden: give a would-be detached
+ // push ample time to write its brain-push.log line, then assert silence.
+ await new Promise(r => setTimeout(r, 2_000));
+ const log = join(process.env.HOME!, '.gbrain', 'brain-push.log');
+ const lines = existsSync(log) ? readFileSync(log, 'utf-8') : '';
+ expect(lines).not.toMatch(/\[push\]/);
+ }, 60_000);
+
test('a direct commit auto-pushes in the background', async () => {
writeFileSync(join(work, 'note.md'), 'note\n');
git(work, 'add', 'note.md'); git(work, 'commit', '-qm', 'note'); // fires .git/hooks/post-commit
diff --git a/test/budget/pricing-overrides.test.ts b/test/budget/pricing-overrides.test.ts
new file mode 100644
index 0000000000..11eadc850d
--- /dev/null
+++ b/test/budget/pricing-overrides.test.ts
@@ -0,0 +1,150 @@
+import { describe, test, expect } from 'bun:test';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import {
+ BudgetTracker,
+ BudgetExhausted,
+ parsePricingOverrides,
+ loadPricingOverrides,
+ isModelPriceable,
+} from '../../src/core/budget/budget-tracker.ts';
+
+/**
+ * #4312 — operator config-plane price overrides (`pricing.overrides`).
+ *
+ * A LiteLLM proxy can front a PAID provider, so `litellm:*` is deliberately
+ * absent from the free-local sets and from the shipped pricing tables — which
+ * meant every `--max-cost` run through a proxy TX2 hard-failed `no_pricing`
+ * at $0. Operators now declare their real rate in the config plane; unknown
+ * paid routes without an override stay fail-closed.
+ */
+
+const auditPath = () => join(tmpdir(), `gbrain-budget-test-${Math.random().toString(36).slice(2)}.jsonl`);
+
+const est = (modelId: string, kind: 'chat' | 'embed' | 'rerank' = 'chat') => ({
+ modelId, kind, estimatedInputTokens: 1_000_000, maxOutputTokens: 0,
+});
+
+describe('parsePricingOverrides', () => {
+ test('JSON string with scalar and object forms', () => {
+ const p = parsePricingOverrides(
+ '{"litellm:text-embedding-3-large": 0.13, "litellm:gpt-4o": {"input": 2.5, "output": 10}}',
+ );
+ expect(p).toEqual({
+ 'litellm:text-embedding-3-large': { input: 0.13, output: 0.13 },
+ 'litellm:gpt-4o': { input: 2.5, output: 10 },
+ });
+ });
+
+ test('pricePerMTok spelling and key lowercasing', () => {
+ const p = parsePricingOverrides({ 'LiteLLM:MyModel': { pricePerMTok: 0.5 } });
+ expect(p).toEqual({ 'litellm:mymodel': { input: 0.5, output: 0.5 } });
+ });
+
+ test('invalid entries are dropped (stay fail-closed); junk value → undefined', () => {
+ expect(parsePricingOverrides('{"a": -1, "b": "free", "c": null}')).toBeUndefined();
+ expect(parsePricingOverrides('not json')).toBeUndefined();
+ expect(parsePricingOverrides(null)).toBeUndefined();
+ expect(parsePricingOverrides('')).toBeUndefined();
+ expect(parsePricingOverrides([1, 2])).toBeUndefined();
+ const partial = parsePricingOverrides('{"good": 1, "bad": -3}');
+ expect(partial).toEqual({ good: { input: 1, output: 1 } });
+ });
+});
+
+describe('BudgetTracker with pricingOverrides (#4312)', () => {
+ test('pre-fix behavior: unpriced proxy model under --max-cost hard-fails no_pricing', () => {
+ const t = new BudgetTracker({ maxCostUsd: 1, label: 'test', auditPath: auditPath() });
+ expect(() => t.reserve(est('litellm:custom-chat-model'))).toThrow(BudgetExhausted);
+ try {
+ t.reserve(est('litellm:custom-chat-model'));
+ } catch (e) {
+ expect((e as BudgetExhausted).reason).toBe('no_pricing');
+ }
+ });
+
+ test('chat route: override prices the call and the cap is enforced against it', () => {
+ const t = new BudgetTracker({
+ maxCostUsd: 1,
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"litellm:custom-chat-model": {"input": 0.4, "output": 2}}'),
+ });
+ // 1M input tokens at $0.4/M → $0.40 projected, under the $1 cap.
+ expect(() => t.reserve(est('litellm:custom-chat-model'))).not.toThrow();
+ t.record({ modelId: 'litellm:custom-chat-model', inputTokens: 1_000_000, outputTokens: 0, kind: 'chat' });
+ expect(t.totalSpent).toBeCloseTo(0.4, 6);
+ // output tokens bill at the output rate
+ t.record({ modelId: 'litellm:custom-chat-model', inputTokens: 0, outputTokens: 100_000, kind: 'chat' });
+ expect(t.totalSpent).toBeCloseTo(0.6, 6);
+ });
+
+ test('embed route: override prices litellm embeddings too', () => {
+ const t = new BudgetTracker({
+ maxCostUsd: 1,
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"litellm:text-embedding-3-large": 0.13}'),
+ });
+ expect(() => t.reserve(est('litellm:text-embedding-3-large', 'embed'))).not.toThrow();
+ t.record({ modelId: 'litellm:text-embedding-3-large', inputTokens: 1_000_000, kind: 'embed' });
+ expect(t.totalSpent).toBeCloseTo(0.13, 6);
+ });
+
+ test('cap still bites: an overpriced override projects past --max-cost and throws cost', () => {
+ const t = new BudgetTracker({
+ maxCostUsd: 0.05,
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"litellm:pricey": 5}'),
+ });
+ try {
+ t.reserve(est('litellm:pricey'));
+ throw new Error('expected BudgetExhausted');
+ } catch (e) {
+ expect(e).toBeInstanceOf(BudgetExhausted);
+ expect((e as BudgetExhausted).reason).toBe('cost');
+ }
+ });
+
+ test('unknown paid routes WITHOUT an override stay fail-closed', () => {
+ const t = new BudgetTracker({
+ maxCostUsd: 1,
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"litellm:other-model": 1}'),
+ });
+ expect(() => t.reserve(est('litellm:not-overridden'))).toThrow(BudgetExhausted);
+ });
+
+ test('override wins over a shipped table row (operator owns the bill)', () => {
+ const t = new BudgetTracker({
+ label: 'test',
+ auditPath: auditPath(),
+ pricingOverrides: parsePricingOverrides('{"voyage:voyage-4": 0.5}'),
+ });
+ t.record({ modelId: 'voyage:voyage-4', inputTokens: 1_000_000, kind: 'embed' });
+ expect(t.totalSpent).toBeCloseTo(0.5, 6); // table says 0.06; override says 0.5
+ });
+
+ test('isModelPriceable consults overrides', () => {
+ const overrides = parsePricingOverrides('{"litellm:x": 1}');
+ expect(isModelPriceable('litellm:x', 'chat')).toBe(false);
+ expect(isModelPriceable('litellm:x', 'chat', overrides)).toBe(true);
+ });
+});
+
+describe('loadPricingOverrides — config-plane loader', () => {
+ test('reads pricing.overrides from the engine config plane', async () => {
+ const fake = {
+ getConfig: async (key: string) =>
+ key === 'pricing.overrides' ? '{"litellm:gpt-4o": 2.5}' : null,
+ };
+ expect(await loadPricingOverrides(fake)).toEqual({ 'litellm:gpt-4o': { input: 2.5, output: 2.5 } });
+ });
+
+ test('fail-open: config read failure → undefined (models stay fail-closed)', async () => {
+ const boom = { getConfig: async () => { throw new Error('db down'); } };
+ expect(await loadPricingOverrides(boom)).toBeUndefined();
+ });
+});
diff --git a/test/call-federated-scope.test.ts b/test/call-federated-scope.test.ts
new file mode 100644
index 0000000000..1c580d01e9
--- /dev/null
+++ b/test/call-federated-scope.test.ts
@@ -0,0 +1,81 @@
+/**
+ * #3874 — `gbrain call` must compute the SAME federated read scope as the
+ * direct CLI path. Pre-fix, call.ts resolved via bare resolveSourceId and
+ * never computed localFederatedSourceIds, so an unqualified
+ * `gbrain call resolve_slugs ...` on a federated multi-source brain silently
+ * saw only the scalar source while `gbrain query` spanned the federated set.
+ */
+import { describe, test, expect } from 'bun:test';
+import { runCall } from '../src/commands/call.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+type SourceRow = { id: string; local_path: string | null; archived: boolean; config: Record<string, unknown> };
+
+const SOURCES: SourceRow[] = [
+ { id: 'default', local_path: null, archived: false, config: {} },
+ { id: 'vault', local_path: '/nonexistent/vault-3874', archived: false, config: {} },
+ { id: 'wiki', local_path: '/nonexistent/wiki-3874', archived: false, config: { federated: true } },
+];
+
+function makeEngine(capture: { resolveSlugsOpts: unknown[] }): BrainEngine {
+ return {
+ executeRaw: async (sql: string, params?: unknown[]) => {
+ if (sql.includes('WHERE id = $1 AND archived = false')) {
+ return SOURCES.filter((s) => s.id === params?.[0] && !s.archived).map((s) => ({ id: s.id }));
+ }
+ // localFederatedSourceIds: SELECT id, config, archived FROM sources ...
+ if (sql.includes('SELECT id, config, archived FROM sources')) {
+ return SOURCES.filter((s) => !s.archived).map((s) => ({
+ id: s.id, config: s.config, archived: s.archived,
+ }));
+ }
+ // Tier-4 registered query (old or #3880 shape) — paths never match cwd.
+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) {
+ return SOURCES.filter((s) => s.local_path !== null).map((s) => ({
+ id: s.id, local_path: s.local_path, archived: s.archived,
+ }));
+ }
+ if (sql.includes('FROM pages')) return [];
+ return [];
+ },
+ getConfig: async (key: string) => (key === 'sources.default' ? 'vault' : null),
+ resolveSlugs: async (_partial: string, opts?: unknown) => {
+ capture.resolveSlugsOpts.push(opts);
+ return [];
+ },
+ } as unknown as BrainEngine;
+}
+
+describe('#3874 gbrain call federated scope parity', () => {
+ test('ambient-tier resolution widens unqualified reads across federated sources', async () => {
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ const capture = { resolveSlugsOpts: [] as unknown[] };
+ const engine = makeEngine(capture);
+ const outs: string[] = [];
+ await runCall(engine, ['resolve_slugs', JSON.stringify({ partial: 'foo' })], async (s) => {
+ outs.push(s);
+ });
+ expect(capture.resolveSlugsOpts.length).toBe(1);
+ const opts = capture.resolveSlugsOpts[0] as { sourceId?: string; sourceIds?: string[] };
+ // Pre-fix: { sourceId: 'vault' } (scalar). Post-fix: the federated set.
+ expect(opts.sourceIds).toEqual(['vault', 'wiki']);
+ });
+ });
+
+ test('explicit --source keeps the scalar scope (no widening)', async () => {
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ const capture = { resolveSlugsOpts: [] as unknown[] };
+ const engine = makeEngine(capture);
+ await runCall(
+ engine,
+ ['--source', 'vault', 'resolve_slugs', JSON.stringify({ partial: 'foo' })],
+ async () => {},
+ );
+ expect(capture.resolveSlugsOpts.length).toBe(1);
+ const opts = capture.resolveSlugsOpts[0] as { sourceId?: string; sourceIds?: string[] };
+ expect(opts.sourceIds).toBeUndefined();
+ expect(opts.sourceId).toBe('vault');
+ });
+ });
+});
diff --git a/test/chat-key-plane.test.ts b/test/chat-key-plane.test.ts
new file mode 100644
index 0000000000..1e10ac91d5
--- /dev/null
+++ b/test/chat-key-plane.test.ts
@@ -0,0 +1,65 @@
+/**
+ * issue #3944 — chat-key presence is judged on env + FILE plane, shared.
+ *
+ * Autopilot's dispatch loop read `engine.getConfig('anthropic_api_key')`
+ * (the DB plane) while doctor's loadRecommendationContext read the file
+ * plane — a DB-only key made autopilot dispatch chat jobs that doctor's
+ * planner classified as blocked. Both now share
+ * `chatApiKeyConfigured(fileCfg)` from brain-score-recommendations.ts.
+ */
+
+import { describe, expect, test } from 'bun:test';
+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';
+
+describe('#3944 chatApiKeyConfigured', () => {
+ test('no env, no file key → false (a DB-only key is invisible by design)', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: undefined }, () => {
+ // The helper takes NO engine — the DB plane cannot influence it. A
+ // DB-only `gbrain config set anthropic_api_key` therefore reads as
+ // not-configured, matching doctor's file-plane verdict.
+ expect(chatApiKeyConfigured(null)).toBe(false);
+ expect(chatApiKeyConfigured(undefined)).toBe(false);
+ expect(chatApiKeyConfigured({})).toBe(false);
+ });
+ });
+
+ test('file-plane key → true', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: undefined }, () => {
+ expect(chatApiKeyConfigured({ anthropic_api_key: 'sk-file' })).toBe(true);
+ });
+ });
+
+ test('env key → true even without file config', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-env' }, () => {
+ expect(chatApiKeyConfigured(null)).toBe(true);
+ });
+ });
+
+ test('empty-string file key → false (falsy, same as absent)', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: undefined }, () => {
+ expect(chatApiKeyConfigured({ anthropic_api_key: '' })).toBe(false);
+ });
+ });
+});
+
+describe('#3944 both planner surfaces share the helper (source guard)', () => {
+ // Autopilot's dispatch loop runs deep inside the daemon poll cycle (engine +
+ // queue + timers) — not unit-runnable, so the plane choice is pinned
+ // structurally. The helper's BEHAVIOR is covered above.
+ test('autopilot no longer probes the DB plane for the chat key', () => {
+ // test-reads-source-ok: the dispatch loop cannot run hermetically; this pins that the DB-plane read does not creep back.
+ const src = readFileSync(join(import.meta.dir, '../src/commands/autopilot.ts'), 'utf-8');
+ expect(src).not.toContain("getConfig('anthropic_api_key')");
+ expect(src).toContain('chatApiKeyConfigured(fileCfg)');
+ });
+
+ test('doctor context uses the same shared helper', () => {
+ // test-reads-source-ok: pins that context.ts and autopilot resolve the chat key through ONE helper, not two drifting copies.
+ const src = readFileSync(join(import.meta.dir, '../src/core/remediation/context.ts'), 'utf-8');
+ expect(src).toContain('chatApiKeyConfigured(fileCfg)');
+ expect(src).not.toContain('process.env.ANTHROPIC_API_KEY ||');
+ });
+});
diff --git a/test/chat-usage.test.ts b/test/chat-usage.test.ts
new file mode 100644
index 0000000000..7793e7d5ce
--- /dev/null
+++ b/test/chat-usage.test.ts
@@ -0,0 +1,287 @@
+/**
+ * #4218 — chat usage accounting (revives the #3392 shape).
+ *
+ * Pins the full loop: gateway.chat() success boundary → recordChatUsage →
+ * phase attribution (direct vs job callers) → canonical cost math incl.
+ * cache tokens → engine sink INSERT into chat_usage_log (migration v140) →
+ * the admin-scope get_usage op with explicit coverage fields (admin: the
+ * ledger has no source dimension, so source-scoped read tokens are fenced). Failure paths:
+ * a failed chat writes NO row; a throwing sink never breaks a chat call;
+ * unknown-pricing models record cost_usd NULL (never a fake 0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ __setChatTransportForTests,
+ chat,
+ type ChatResult,
+} from '../src/core/ai/gateway.ts';
+import {
+ withChatPhase,
+ currentChatPhase,
+ setChatUsageSink,
+ recordChatUsage,
+ estimateChatCostUsd,
+ makeEngineChatUsageSink,
+ type ChatUsageRecord,
+} from '../src/core/ai/chat-usage.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+
+function fakeResult(over: Partial<ChatResult> = {}): ChatResult {
+ return {
+ text: 'ok',
+ blocks: [{ type: 'text', text: 'ok' }],
+ stopReason: 'end',
+ usage: { input_tokens: 1000, output_tokens: 500, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+ ...over,
+ };
+}
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+ setChatUsageSink(null);
+});
+
+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-write
+ const cost = estimateChatCostUsd('anthropic:claude-haiku-4-5', {
+ input_tokens: 1_000_000,
+ output_tokens: 1_000_000,
+ cache_read_tokens: 1_000_000,
+ cache_write_tokens: 1_000_000,
+ });
+ expect(cost).toBeCloseTo(1 + 5 + 0.1 + 1.25, 8);
+ });
+
+ test('provider without cache rates falls back to the input rate for cache tokens', () => {
+ // gpt-4o: $2.50/M in, $10/M out; no cache fields → cache tokens at input rate
+ const cost = estimateChatCostUsd('openai:gpt-4o', {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_tokens: 1_000_000,
+ cache_write_tokens: 1_000_000,
+ });
+ expect(cost).toBeCloseTo(2.5 + 2.5, 8);
+ });
+
+ test('unknown model → null, never a fake 0', () => {
+ expect(
+ estimateChatCostUsd('acme:unpriced-model-9000', { input_tokens: 10, output_tokens: 10 }),
+ ).toBeNull();
+ });
+});
+
+describe('gateway.chat() success boundary — direct vs job callers', () => {
+ test('direct caller records phase NULL; job caller records job:<name>', async () => {
+ const records: ChatUsageRecord[] = [];
+ setChatUsageSink((r) => {
+ records.push(r);
+ });
+ __setChatTransportForTests(async () => fakeResult());
+
+ await chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] });
+ await withChatPhase('job:embed-backfill', () =>
+ chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] }),
+ );
+ // sink is fire-and-forget — let the microtask queue drain
+ await new Promise((r) => setTimeout(r, 10));
+
+ expect(records.length).toBe(2);
+ expect(records[0]!.phase).toBeNull();
+ expect(records[1]!.phase).toBe('job:embed-backfill');
+ expect(records[0]!.model).toBe('anthropic:claude-haiku-4-5');
+ expect(records[0]!.input_tokens).toBe(1000);
+ expect(records[0]!.output_tokens).toBe(500);
+ // $1/M * 1000 + $5/M * 500 = 0.001 + 0.0025
+ expect(records[0]!.cost_usd).toBeCloseTo(0.0035, 8);
+ });
+
+ test('cache tokens flow through (cache_creation → cache_write)', async () => {
+ const records: ChatUsageRecord[] = [];
+ setChatUsageSink((r) => {
+ records.push(r);
+ });
+ __setChatTransportForTests(async () =>
+ fakeResult({
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 2000, cache_creation_tokens: 3000 },
+ }),
+ );
+ await chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] });
+ await new Promise((r) => setTimeout(r, 10));
+
+ expect(records[0]!.cache_read_tokens).toBe(2000);
+ expect(records[0]!.cache_write_tokens).toBe(3000);
+ expect(records[0]!.cost_usd).toBeCloseTo(
+ (100 * 1 + 50 * 5 + 2000 * 0.1 + 3000 * 1.25) / 1e6,
+ 10,
+ );
+ });
+
+ test('failed chat writes NO usage row and the error propagates', async () => {
+ const records: ChatUsageRecord[] = [];
+ setChatUsageSink((r) => {
+ records.push(r);
+ });
+ __setChatTransportForTests(async () => {
+ throw new Error('provider exploded');
+ });
+ await expect(
+ chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] }),
+ ).rejects.toThrow('provider exploded');
+ await new Promise((r) => setTimeout(r, 10));
+ expect(records.length).toBe(0);
+ });
+
+ test('a throwing sink never breaks a chat call (fail-open)', async () => {
+ setChatUsageSink(() => {
+ throw new Error('sink down');
+ });
+ __setChatTransportForTests(async () => fakeResult());
+ const res = await chat({
+ model: 'anthropic:claude-haiku-4-5',
+ messages: [{ role: 'user', content: 'hi' }],
+ });
+ expect(res.text).toBe('ok');
+ });
+
+ test('withChatPhase restores the outer phase after the callback', async () => {
+ expect(currentChatPhase()).toBeNull();
+ await withChatPhase('job:outer', async () => {
+ expect(currentChatPhase()).toBe('job:outer');
+ });
+ expect(currentChatPhase()).toBeNull();
+ });
+});
+
+describe('engine sink + get_usage op (PGLite, migration v140 schema)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM chat_usage_log');
+ });
+
+ function ctx(over: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine,
+ config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ ...over,
+ } as OperationContext;
+ }
+
+ test('sink inserts; get_usage aggregates with explicit coverage fields', async () => {
+ const sink = makeEngineChatUsageSink(engine);
+ await sink({
+ model: 'anthropic:claude-haiku-4-5',
+ provider: 'anthropic',
+ phase: null,
+ input_tokens: 1000,
+ output_tokens: 500,
+ cache_read_tokens: 200,
+ cache_write_tokens: 300,
+ cost_usd: 0.0035,
+ });
+ await sink({
+ model: 'anthropic:claude-haiku-4-5',
+ provider: 'anthropic',
+ phase: 'job:embed-backfill',
+ input_tokens: 2000,
+ output_tokens: 1000,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ cost_usd: 0.007,
+ });
+ // Unknown-pricing model: tokens counted, dollars NULL.
+ await sink({
+ model: 'acme:unpriced-model-9000',
+ provider: 'acme',
+ phase: 'job:dream',
+ input_tokens: 10,
+ output_tokens: 20,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ cost_usd: null,
+ });
+
+ const get_usage = operationsByName['get_usage']!;
+ expect(get_usage.scope).toBe('admin');
+ const out = (await get_usage.handler(ctx(), { days: 7 })) as any;
+
+ expect(out.window_days).toBe(7);
+ expect(out.totals.calls).toBe(3);
+ expect(out.totals.input_tokens).toBe(3010);
+ expect(out.totals.output_tokens).toBe(1520);
+ expect(out.totals.cache_read_tokens).toBe(200);
+ expect(out.totals.cache_write_tokens).toBe(300);
+ expect(out.totals.cost_usd).toBeCloseTo(0.0105, 8);
+
+ const haiku = out.by_model.find((m: any) => m.model === 'anthropic:claude-haiku-4-5');
+ expect(haiku.calls).toBe(2);
+ expect(haiku.cost_usd).toBeCloseTo(0.0105, 8);
+ expect(haiku.unpriced_calls).toBe(0);
+ const unpriced = out.by_model.find((m: any) => m.model === 'acme:unpriced-model-9000');
+ expect(unpriced.calls).toBe(1);
+ expect(unpriced.cost_usd).toBeNull();
+ expect(unpriced.unpriced_calls).toBe(1);
+
+ const direct = out.by_phase.find((p: any) => p.phase === 'direct');
+ expect(direct.calls).toBe(1);
+ const jobPhase = out.by_phase.find((p: any) => p.phase === 'job:embed-backfill');
+ expect(jobPhase.calls).toBe(1);
+
+ // Coverage honesty contract.
+ expect(out.coverage.source).toBe('gateway.chat');
+ expect(out.coverage.table_present).toBe(true);
+ expect(out.coverage.logged_since).not.toBeNull();
+ expect(out.coverage.priced_calls).toBe(2);
+ expect(out.coverage.unpriced_calls).toBe(1);
+ expect(Array.isArray(out.coverage.not_covered)).toBe(true);
+ expect(out.coverage.not_covered.length).toBeGreaterThan(0);
+ });
+
+ test('end-to-end: gateway transport call lands a row via the engine sink', async () => {
+ setChatUsageSink(makeEngineChatUsageSink(engine));
+ __setChatTransportForTests(async () => fakeResult());
+ await withChatPhase('job:signal-detector', () =>
+ chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] }),
+ );
+ // The sink INSERT is fire-and-forget; poll briefly for the row.
+ let rows: Array<{ phase: string | null; cost_usd: number | null }> = [];
+ for (let i = 0; i < 50 && rows.length === 0; i++) {
+ await new Promise((r) => setTimeout(r, 20));
+ rows = await engine.executeRaw(
+ 'SELECT phase, cost_usd FROM chat_usage_log',
+ [],
+ );
+ }
+ expect(rows.length).toBe(1);
+ expect(rows[0]!.phase).toBe('job:signal-detector');
+ expect(Number(rows[0]!.cost_usd)).toBeCloseTo(0.0035, 8);
+ });
+
+ test('empty window → zeroed totals, coverage still explicit', async () => {
+ const get_usage = operationsByName['get_usage']!;
+ const out = (await get_usage.handler(ctx(), {})) as any;
+ expect(out.window_days).toBe(30);
+ expect(out.totals.calls).toBe(0);
+ expect(out.by_model).toEqual([]);
+ expect(out.coverage.table_present).toBe(true);
+ });
+});
diff --git a/test/chronicle-extract.test.ts b/test/chronicle-extract.test.ts
index 4152a568d6..ce4cd9cdc5 100644
--- a/test/chronicle-extract.test.ts
+++ b/test/chronicle-extract.test.ts
@@ -128,6 +128,28 @@ describe('runChronicleExtract', () => {
expect(r.status).toBe('skipped');
expect(r.reason).toBe('judge_parse_failed');
});
+
+ // #2608: a keyless daemon (no servable chat provider) must NOT be recorded
+ // as a legitimate no_events run — pre-fix the default judge returned a bare
+ // `{events: []}` when isAvailable('chat') was false, indistinguishable from
+ // "the judge read the page and found nothing", so keyless installs reported
+ // clean chronicle runs forever.
+ test('no chat provider → skipped/judge_llm_unavailable, not no_events (#2608)', async () => {
+ const unavailable: ChronicleJudge = async () => ({ events: [], failure: 'llm_unavailable' });
+ const r = await runChronicleExtract(engine, { slug: 'meetings/2026-06-18-sync', judge: unavailable });
+ expect(r.status).toBe('skipped');
+ expect(r.reason).toBe('judge_llm_unavailable');
+ expect(await countEvents()).toBe(0);
+ });
+
+ test('defaultJudge surfaces llm_unavailable (source contract, #2608)', async () => {
+ // The default judge is not exported; pin the load-bearing line so the
+ // bare-`{events: []}` regression can't silently return.
+ const { readFileSync } = await import('fs');
+ // test-reads-source-ok: defaultJudge is module-private and needs a live gateway; the text pin is the only unit-testable seam (#2608)
+ const src = readFileSync('src/core/chronicle/extract-events.ts', 'utf8');
+ expect(src).toMatch(/isAvailable\('chat'\)\)\s*return \{ events: \[\], failure: 'llm_unavailable' \}/);
+ });
});
describe('parseJudgeJson failure signalling (#2606)', () => {
diff --git a/test/chronicle-ontology.test.ts b/test/chronicle-ontology.test.ts
index 5ef2f1bf88..343a81f410 100644
--- a/test/chronicle-ontology.test.ts
+++ b/test/chronicle-ontology.test.ts
@@ -61,6 +61,42 @@ describe('mergeOntologyFact + getOntology', () => {
expect(past[0].value).toBe('founder');
});
+ test('#3014 option B — a forward supersession surfaces in listSupersessions while --asof still sees it', async () => {
+ // The ontology writer closes the prior row via valid_until + superseded_by
+ // but leaves expired_at NULL (so --asof time-travel keeps seeing it). The
+ // pre-fix listSupersessions required expired_at IS NOT NULL, so this row
+ // was invisible. Option B filters on superseded_by alone.
+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'founder', source: 'meetings/a', validFrom: '2024-01-01' });
+ const r = await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'advisor', source: 'meetings/b', validFrom: '2026-05-01' });
+ expect(r.action).toBe('superseded_prior');
+
+ const sup = await engine.listSupersessions('default');
+ expect(sup).toHaveLength(1);
+ expect(sup[0].fact).toContain('founder'); // the superseded prior row
+ expect(sup[0].superseded_by).not.toBeNull();
+ expect(sup[0].expired_at).toBeNull(); // ontology closes via valid_until, not expired_at
+
+ // The regression that option A ("writers set both columns") would have
+ // caused: --asof time-travel must still return the superseded value.
+ const past = await engine.getOntology(SARAH, { asof: '2025-01-01' });
+ expect(past[0].value).toBe('founder');
+ });
+
+ test('#3014 — listSupersessions({since}) filters a NULL-expired_at row by COALESCE(expired_at, valid_until)', async () => {
+ // founder row: closed via valid_until = 2026-05-01, expired_at NULL.
+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'founder', source: 'meetings/a', validFrom: '2024-01-01' });
+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'advisor', source: 'meetings/b', validFrom: '2026-05-01' });
+
+ // since before the close date → COALESCE falls back to valid_until, included.
+ const included = await engine.listSupersessions('default', { since: new Date('2026-01-01T00:00:00Z') });
+ expect(included.some(s => s.fact.includes('founder'))).toBe(true);
+
+ // since after the close date → excluded (a pre-fix `expired_at >= since`
+ // would have dropped it unconditionally since expired_at is NULL).
+ const excluded = await engine.listSupersessions('default', { since: new Date('2026-09-01T00:00:00Z') });
+ expect(excluded.some(s => s.fact.includes('founder'))).toBe(false);
+ });
+
test('novel dimensions quarantine (excluded from current unless asked)', async () => {
await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'vibe', value: 'chaotic', source: 'meetings/a' });
expect(await engine.getOntology(SARAH)).toHaveLength(0); // quarantined → hidden
diff --git a/test/chunker-version-gate.test.ts b/test/chunker-version-gate.test.ts
index bc2d95481b..91f7efa461 100644
--- a/test/chunker-version-gate.test.ts
+++ b/test/chunker-version-gate.test.ts
@@ -15,19 +15,21 @@ 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 4 for Cathedral II', () => {
+ test('bumped to 5 for python decorated_definition support (#3821)', () => {
// 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.
- expect(CHUNKER_VERSION).toBe(4);
+ // v5: #3821 python decorated_definition — decorated fns/classes emitted
+ // ZERO chunks pre-fix; the bump forces recovery re-chunks.
+ expect(CHUNKER_VERSION).toBe(5);
});
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(4);
+ expect(a).toBe(5);
});
});
diff --git a/test/chunkers/code-component-markup.test.ts b/test/chunkers/code-component-markup.test.ts
new file mode 100644
index 0000000000..33cfca5006
--- /dev/null
+++ b/test/chunkers/code-component-markup.test.ts
@@ -0,0 +1,238 @@
+/**
+ * #3768 — .svelte/.astro script extraction.
+ *
+ * detectCodeLanguage maps .svelte/.astro to 'html' (the markup half really is
+ * html), which used to send the WHOLE file through the recursive fallback
+ * chunker: no symbol names, no code edges, code-def/code-callers blind to
+ * every component. The fix slices the script regions (<script> blocks and the
+ * Astro `---` frontmatter fence) with line- and offset-preserving masking so
+ * the TS/JS grammar parses them at their absolute positions, while the markup
+ * keeps its html chunks with the script interiors blanked (no double-index).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { chunkCodeTextFull } from '../../src/core/chunkers/code.ts';
+import {
+ isComponentMarkupPath,
+ extractComponentScriptRegions,
+ maskOutsideRegion,
+ maskRegions,
+} from '../../src/core/chunkers/component-markup.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importCodeFile } from '../../src/core/import-file.ts';
+import { findCodeDef } from '../../src/commands/code-def.ts';
+
+// Each symbol is deliberately large enough to stay independent under the
+// small-sibling merge threshold (~45 tokens at the default 300-token target);
+// merged chunks lose their symbolName, which is not what these tests probe.
+const SVELTE_SRC = `<script context="module" lang="ts">
+export function readModuleCounterSeed(): number {
+ const base = moduleCounterSeed + 1;
+ const doubled = base * 2;
+ const halved = Math.floor(doubled / 2);
+ console.log('module counter seed read', base, doubled, halved);
+ if (halved < 0) throw new Error('counter seed must never be negative');
+ return halved;
+}
+
+export const moduleCounterSeed: number = 41;
+</script>
+
+<script lang="ts">
+function handleComponentClick(): void {
+ const seed = readModuleCounterSeed();
+ clickTally = seed + clickTally;
+ if (clickTally > 100) console.warn('tally is getting big', clickTally);
+ if (clickTally < 0) throw new Error('tally must never go negative');
+ reportComponentTally(clickTally);
+}
+
+function reportComponentTally(total: number): void {
+ const formatted = 'tally is now ' + String(total).padStart(4, '0');
+ console.log(formatted);
+ if (total % 10 === 0) console.log('nice round number of clicks:', total);
+ if (total > 1000) console.error('implausible click volume', total);
+}
+
+let clickTally: number = 0;
+</script>
+
+<button on:click={handleComponentClick}>
+ clicked {clickTally} times
+</button>
+
+<style>
+ button { color: rebeccapurple; }
+</style>
+`;
+
+const ASTRO_SRC = `---
+import { fetchWidgets } from '../lib/widgets';
+
+function summarizeWidgetInventory(): string {
+ const count = widgetInventoryList.length;
+ const noun = count === 1 ? 'widget' : 'widgets';
+ const banner = 'we have ' + count + ' ' + noun + ' in stock today';
+ if (count === 0) return 'the warehouse is completely empty, restock soon';
+ return banner + ' (updated hourly by the inventory cron)';
+}
+
+const widgetInventoryList = await fetchWidgets();
+---
+<html>
+ <body>
+ <h1>{summarizeWidgetInventory()}</h1>
+ </body>
+</html>
+`;
+
+describe('isComponentMarkupPath', () => {
+ test('matches .svelte and .astro, not others', () => {
+ expect(isComponentMarkupPath('src/App.svelte')).toBe(true);
+ expect(isComponentMarkupPath('pages/index.ASTRO')).toBe(true);
+ expect(isComponentMarkupPath('src/app.html')).toBe(false);
+ expect(isComponentMarkupPath('src/app.vue')).toBe(false);
+ expect(isComponentMarkupPath('src/app.ts')).toBe(false);
+ });
+});
+
+describe('extractComponentScriptRegions', () => {
+ test('finds both svelte scripts with lang=ts and correct start lines', () => {
+ const regions = extractComponentScriptRegions(SVELTE_SRC, 'src/App.svelte');
+ expect(regions.length).toBe(2);
+ expect(regions[0]!.language).toBe('typescript');
+ expect(regions[1]!.language).toBe('typescript');
+ // Module script code starts on line 2 (after the opening tag on line 1).
+ expect(SVELTE_SRC.slice(regions[0]!.start, regions[0]!.end)).toContain('readModuleCounterSeed');
+ expect(SVELTE_SRC.slice(regions[1]!.start, regions[1]!.end)).toContain('handleComponentClick');
+ });
+
+ test('svelte script without lang attr is javascript', () => {
+ const src = '<script>\nlet x = 1;\n</script>\n<p>hi</p>\n';
+ const regions = extractComponentScriptRegions(src, 'a.svelte');
+ expect(regions.length).toBe(1);
+ expect(regions[0]!.language).toBe('javascript');
+ });
+
+ test('astro frontmatter fence is a typescript region', () => {
+ const regions = extractComponentScriptRegions(ASTRO_SRC, 'pages/index.astro');
+ expect(regions.length).toBe(1);
+ expect(regions[0]!.language).toBe('typescript');
+ expect(regions[0]!.startLine).toBe(2);
+ const code = ASTRO_SRC.slice(regions[0]!.start, regions[0]!.end);
+ expect(code).toContain('summarizeWidgetInventory');
+ expect(code).not.toContain('<html>');
+ });
+
+ test('unterminated script block yields no region', () => {
+ const regions = extractComponentScriptRegions('<script>\nlet x = 1;\n', 'a.svelte');
+ expect(regions).toEqual([]);
+ });
+});
+
+describe('masking preserves geometry', () => {
+ test('maskOutsideRegion keeps length, lines, and region text', () => {
+ const regions = extractComponentScriptRegions(SVELTE_SRC, 'src/App.svelte');
+ const masked = maskOutsideRegion(SVELTE_SRC, regions[1]!);
+ expect(masked.length).toBe(SVELTE_SRC.length);
+ expect(masked.split('\n').length).toBe(SVELTE_SRC.split('\n').length);
+ expect(masked).toContain('handleComponentClick');
+ expect(masked).not.toContain('export function readModuleCounterSeed');
+ expect(masked).not.toContain('<button');
+ // Region text sits at the SAME index as in the original.
+ expect(masked.indexOf('handleComponentClick')).toBe(SVELTE_SRC.indexOf('handleComponentClick'));
+ });
+
+ test('maskRegions blanks the script interiors, keeps markup', () => {
+ const regions = extractComponentScriptRegions(SVELTE_SRC, 'src/App.svelte');
+ const markup = maskRegions(SVELTE_SRC, regions);
+ expect(markup.length).toBe(SVELTE_SRC.length);
+ expect(markup).toContain('<button');
+ expect(markup).toContain('<script context="module" lang="ts">');
+ expect(markup).not.toContain('handleComponentClick(): void');
+ expect(markup).not.toContain('moduleCounterSeed: number');
+ });
+});
+
+describe('chunkCodeTextFull — svelte/astro component files (#3768)', () => {
+ test('svelte scripts produce semantic TS chunks with absolute lines', async () => {
+ const { chunks } = await chunkCodeTextFull(SVELTE_SRC, 'src/App.svelte', {});
+ const byName = new Map(chunks.map((c) => [c.metadata.symbolName, c]));
+ const handler = byName.get('handleComponentClick');
+ expect(handler).toBeDefined();
+ expect(handler!.metadata.language).toBe('typescript');
+ expect(handler!.metadata.symbolType).toBe('function');
+ // handleComponentClick is defined on line 12 of the .svelte file.
+ const expectedLine = SVELTE_SRC.slice(0, SVELTE_SRC.indexOf('function handleComponentClick')).split('\n').length;
+ expect(handler!.metadata.startLine).toBe(expectedLine);
+ // Module script symbols come through too.
+ expect(byName.get('readModuleCounterSeed')).toBeDefined();
+ });
+
+ test('svelte markup stays html and does not duplicate script code', async () => {
+ const { chunks } = await chunkCodeTextFull(SVELTE_SRC, 'src/App.svelte', {});
+ const htmlChunks = chunks.filter((c) => c.metadata.language === 'html');
+ expect(htmlChunks.length).toBeGreaterThanOrEqual(1);
+ for (const c of htmlChunks) {
+ expect(c.text).not.toContain('reportComponentTally(clickTally)');
+ expect(c.text).not.toContain('export function readModuleCounterSeed');
+ }
+ expect(htmlChunks.some((c) => c.text.includes('<button'))).toBe(true);
+ // chunk indexes are unique + sequential across script and markup chunks.
+ expect(chunks.map((c) => c.index)).toEqual(chunks.map((_, i) => i));
+ });
+
+ test('svelte call edges carry absolute offsets into the original file', async () => {
+ const { edges } = await chunkCodeTextFull(SVELTE_SRC, 'src/App.svelte', {});
+ const call = edges.find((e) => e.edgeType === 'calls' && e.toSymbol.includes('reportComponentTally'));
+ expect(call).toBeDefined();
+ // The offset must point at the call site in the ORIGINAL source text.
+ expect(SVELTE_SRC.slice(call!.callSiteByteOffset, call!.callSiteByteOffset + 'reportComponentTally'.length))
+ .toBe('reportComponentTally');
+ });
+
+ test('astro fence produces semantic TS chunks with absolute lines', async () => {
+ const { chunks } = await chunkCodeTextFull(ASTRO_SRC, 'pages/index.astro', {});
+ const fn = chunks.find((c) => c.metadata.symbolName === 'summarizeWidgetInventory');
+ expect(fn).toBeDefined();
+ expect(fn!.metadata.language).toBe('typescript');
+ const expectedLine = ASTRO_SRC.slice(0, ASTRO_SRC.indexOf('function summarizeWidgetInventory')).split('\n').length;
+ expect(fn!.metadata.startLine).toBe(expectedLine);
+ });
+
+ test('component file without any script keeps the html fallback path', async () => {
+ const src = '<div class="hero">\n <p>static content only, nothing scripted here at all</p>\n</div>\n';
+ const { chunks, edges } = await chunkCodeTextFull(src, 'src/Static.svelte', {});
+ expect(chunks.length).toBeGreaterThanOrEqual(1);
+ for (const c of chunks) expect(c.metadata.language).toBe('html');
+ expect(edges).toEqual([]);
+ });
+});
+
+describe('importCodeFile + code-def/code-edges over a svelte component (#3768)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await importCodeFile(engine, 'src/App.svelte', SVELTE_SRC, { noEmbed: true });
+ }, 60000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ }, 30000);
+
+ test('code-def finds the svelte script function', async () => {
+ const results = await findCodeDef(engine, 'handleComponentClick');
+ expect(results.length).toBeGreaterThanOrEqual(1);
+ expect(results[0]!.language).toBe('typescript');
+ expect(results[0]!.snippet).toContain('handleComponentClick');
+ });
+
+ test('call edges thread through to code_edges_symbol (code-callers substrate)', async () => {
+ const callers = await engine.getCallersOf('reportComponentTally', { allSources: true });
+ expect(callers.length).toBeGreaterThanOrEqual(1);
+ expect(callers[0]!.edge_type).toBe('calls');
+ });
+});
diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.ts
index ef98a84048..2b39b22590 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('v0.20.0 Cathedral II Layer 12 bumped to 4', () => {
- expect(CHUNKER_VERSION).toBe(4);
+ test('#3821 python decorated_definition support bumped to 5', () => {
+ expect(CHUNKER_VERSION).toBe(5);
});
});
@@ -272,6 +272,97 @@ def pet_the_dog():
const allLanguages = result.map(c => c.metadata.language);
for (const lang of allLanguages) expect(lang).toBe('python');
});
+
+ // #3821: decorated fns/classes parse as decorated_definition wrappers.
+ // Pre-fix they matched neither TOP_LEVEL_TYPES nor NESTED_EMIT_CONFIG, so
+ // decorated code emitted ZERO chunks — the text vanished from the index.
+ test('decorated top-level function emits a chunk with decorator text (#3821)', async () => {
+ // Bodies are deliberately large enough (>15% of the 300-token target) to
+ // stay independent under small-sibling merging (and no tiny leading
+ // import — a sub-threshold first chunk greedily merges its followers).
+ const src = `@functools.cache
+def decorated_fn(x):
+ """Cached doubler with validation, logging and a deliberately verbose body.
+
+ This docstring plus the statements below keep the chunk above the
+ small-sibling merge threshold so the symbol survives as its own chunk.
+ """
+ if not isinstance(x, int):
+ raise TypeError("decorated_fn expects an int, got " + type(x).__name__)
+ doubled = x * 2
+ print("decorated_fn doubling", x, "->", doubled)
+ return doubled
+
+def plain_one():
+ """Plain function with enough body text to avoid the sibling merge pass.
+
+ Returns the integer one after a redundant computation for padding.
+ """
+ value = 1
+ for _ in range(3):
+ value = value * 1
+ return value
+`;
+ const result = await chunkCodeText(src, 'decorated.py');
+ const dec = result.find(c => c.metadata.symbolName === 'decorated_fn');
+ expect(dec).toBeDefined();
+ expect(dec!.metadata.symbolType).toBe('function');
+ // Outer range keeps the decorator line in the chunk body.
+ expect(dec!.text).toContain('@functools.cache');
+ expect(dec!.text).toContain('def decorated_fn');
+ });
+
+ test('decorated class emits scope header + methods, decorated methods included (#3821)', async () => {
+ const src = `@dataclass
+class Config:
+ name: str = "x"
+
+ def plain_method(self):
+ return self.name
+
+ @property
+ def decorated_method(self):
+ return self.name.upper()
+`;
+ const result = await chunkCodeText(src, 'config.py');
+ const cls = result.find(c => c.metadata.symbolName === 'Config' && c.metadata.symbolType === 'class');
+ expect(cls).toBeDefined();
+ // Scope header carries the decorator AND the class declaration line.
+ expect(cls!.text).toContain('@dataclass');
+ expect(cls!.text).toContain('class Config:');
+
+ const plain = result.find(c => c.metadata.symbolName === 'plain_method');
+ expect(plain).toBeDefined();
+ expect(plain!.metadata.parentSymbolPath).toEqual(['Config']);
+ expect(plain!.metadata.symbolType).toBe('function');
+
+ const decorated = result.find(c => c.metadata.symbolName === 'decorated_method');
+ expect(decorated).toBeDefined();
+ expect(decorated!.metadata.parentSymbolPath).toEqual(['Config']);
+ expect(decorated!.metadata.symbolType).toBe('function');
+ expect(decorated!.text).toContain('@property');
+ });
+
+ test('no python source text is silently dropped when decorators are present (#3821)', async () => {
+ const src = `@functools.cache
+def decorated_fn(x):
+ return x * 2
+
+@dataclass
+class Config:
+ def plain_method(self):
+ return 1
+
+def plain_one():
+ return 1
+`;
+ const result = await chunkCodeText(src, 'coverage.py');
+ const names = result.map(c => c.metadata.symbolName);
+ expect(names).toContain('decorated_fn');
+ expect(names).toContain('Config');
+ expect(names).toContain('plain_method');
+ expect(names).toContain('plain_one');
+ });
});
describe('chunkCodeText — Rust', () => {
@@ -443,3 +534,111 @@ public class OrderService
expect(text).toContain('ComputeRefund');
});
});
+
+// #3602 — C# nested-chunk emission. Namespace (block + file-scoped) and
+// class are parents; methods, constructors, and properties emit their own
+// chunks with the full parent path. Bodies are `declaration_list`, which
+// the shared BODY_NODE_TYPES set must descend into.
+describe('chunkCodeText — C# nested emission (#3602)', () => {
+ const BLOCK_NS = `using System;
+
+namespace Demo
+{
+ public class OrderService
+ {
+ public OrderService(decimal rate)
+ {
+ Rate = rate;
+ }
+
+ public decimal ComputeRefund(decimal amount)
+ {
+ var validated = Validate(amount);
+ return validated * Rate;
+ }
+
+ public decimal Validate(decimal amount)
+ {
+ if (amount < 0) throw new ArgumentException("negative");
+ return amount;
+ }
+
+ public decimal Rate { get; set; }
+ }
+}
+`;
+
+ test('block namespace: methods emit with [namespace, class] parent path', async () => {
+ const result = await chunkCodeText(BLOCK_NS, 'OrderService.cs');
+ const byName = new Map(result.map(c => [c.metadata.symbolName, c.metadata]));
+ expect(byName.get('ComputeRefund')?.parentSymbolPath).toEqual(['Demo', 'OrderService']);
+ expect(byName.get('Validate')?.parentSymbolPath).toEqual(['Demo', 'OrderService']);
+ // The class scope-header chunk (constructor shares the name, so match on type).
+ const classChunk = result.find(c => c.metadata.symbolName === 'OrderService' && c.metadata.symbolType === 'class');
+ expect(classChunk?.metadata.parentSymbolPath).toEqual(['Demo']);
+ });
+
+ test('block namespace: property + constructor emit as nested chunks', async () => {
+ const result = await chunkCodeText(BLOCK_NS, 'OrderService.cs');
+ const names = result.map(c => c.metadata.symbolName);
+ expect(names).toContain('Rate');
+ const ctor = result.find(c => c.metadata.symbolType.includes('constructor'));
+ expect(ctor).toBeDefined();
+ expect(ctor!.metadata.parentSymbolPath).toEqual(['Demo', 'OrderService']);
+ });
+
+ test('file-scoped namespace: methods emit with full parent path (#3601 interplay)', async () => {
+ const source = `using System;
+namespace Demo;
+
+public class OrderService
+{
+ public decimal ComputeRefund(decimal amount)
+ {
+ var validated = Validate(amount);
+ return validated * 0.9m;
+ }
+
+ public decimal Validate(decimal amount)
+ {
+ if (amount < 0) throw new ArgumentException("negative");
+ return amount;
+ }
+}
+`;
+ const result = await chunkCodeText(source, 'OrderService.cs');
+ const byName = new Map(result.map(c => [c.metadata.symbolName, c.metadata]));
+ expect(byName.get('ComputeRefund')?.parentSymbolPath).toEqual(['Demo', 'OrderService']);
+ expect(byName.get('ComputeRefund')?.symbolNameQualified).toBe('Demo.OrderService.ComputeRefund');
+ });
+});
+
+// #3602 cross-language guard: `declaration_list` joined the shared
+// BODY_NODE_TYPES set. Rust impl/trait bodies are also declaration_list —
+// before this fix, nested emission for `impl` emitted ONLY the scope-header
+// chunk and silently dropped every method chunk. Pin the fixed behavior.
+describe('chunkCodeText — Rust impl methods emit as nested chunks (#3602 regression)', () => {
+ test('impl methods carry parentSymbolPath = [TypeName]', async () => {
+ const doc = 'Documentation line long enough to keep this method above the merge threshold in the chunker output. ';
+ const src = `impl Server {
+ /// ${doc.repeat(3)}
+ pub fn alpha(&self) -> i64 {
+ let a = self.total; let b = self.count; if b == 0 { return 0; }
+ let average = a / b; average + self.beta()
+ }
+
+ /// ${doc.repeat(3)}
+ pub fn beta(&self) -> i64 {
+ let bias = 2; let scale = 3; bias * scale
+ }
+}
+`;
+ const result = await chunkCodeText(src, 's.rs');
+ const byName = new Map(result.map(c => [c.metadata.symbolName, c.metadata]));
+ expect(byName.get('alpha')?.parentSymbolPath).toEqual(['Server']);
+ expect(byName.get('beta')?.parentSymbolPath).toEqual(['Server']);
+ // The impl scope-header chunk still ships.
+ const scope = result.find(c => c.metadata.symbolType === 'impl item');
+ expect(scope).toBeDefined();
+ });
+});
diff --git a/test/cjk-keyword-sql.test.ts b/test/cjk-keyword-sql.test.ts
new file mode 100644
index 0000000000..0b4307e655
--- /dev/null
+++ b/test/cjk-keyword-sql.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #3986: shared CJK keyword-fallback SQL builder + the Postgres engine's
+ * executor module. DB-free — the real end-to-end pin is the
+ * DATABASE_URL-gated block in test/e2e/engine-parity.test.ts.
+ */
+import { describe, test, expect } from 'bun:test';
+import { buildCJKKeywordSql, type CjkKeywordCtx } from '../src/core/search/cjk-keyword-sql.ts';
+import { searchKeywordCJK as searchKeywordCJKPg } from '../src/core/postgres-engine/cjk-search.ts';
+
+function ctx(overrides: Partial<CjkKeywordCtx> = {}): CjkKeywordCtx {
+ return {
+ limit: 5,
+ offset: 0,
+ innerLimit: 15,
+ sourceFactorCase: '1.0',
+ hardExcludeClause: '',
+ visibilityClause: '',
+ detailFilter: '',
+ opts: undefined,
+ dedup: true,
+ ...overrides,
+ };
+}
+
+describe('buildCJKKeywordSql (#3986)', () => {
+ test('empty and whitespace-only queries return null without binding SQL', () => {
+ expect(buildCJKKeywordSql('', ctx())).toBeNull();
+ expect(buildCJKKeywordSql(' ', ctx())).toBeNull();
+ });
+
+ test('one ILIKE clause per term, AND-joined, with explicit ESCAPE', () => {
+ const built = buildCJKKeywordSql('東京 会議', ctx());
+ expect(built).not.toBeNull();
+ const ilikeCount = (built!.sql.match(/ILIKE \$\d+ ESCAPE '\\'/g) || []).length;
+ expect(ilikeCount).toBe(2);
+ // Escaped + wrapped LIKE params come first, raw terms after, raw query next.
+ expect(built!.params.slice(0, 2)).toEqual(['%東京%', '%会議%']);
+ expect(built!.params.slice(2, 4)).toEqual(['東京', '会議']);
+ expect(built!.params[4]).toBe('東京 会議');
+ });
+
+ test('LIKE metacharacters in terms are escaped', () => {
+ const built = buildCJKKeywordSql('東京_50%', ctx());
+ expect(built!.params[0]).toBe('%東京\\_50\\%%');
+ // Raw term stays unescaped for ranking arithmetic.
+ expect(built!.params[1]).toBe('東京_50%');
+ });
+
+ test('dedup=true builds the best-per-page CTE; dedup=false is chunk-grain', () => {
+ const dedup = buildCJKKeywordSql('東京', ctx({ dedup: true }));
+ const flat = buildCJKKeywordSql('東京', ctx({ dedup: false }));
+ expect(dedup!.sql).toContain('best_per_page');
+ expect(flat!.sql).not.toContain('best_per_page');
+ });
+
+ test('sourceIds[] wins over scalar sourceId (federated subsumes single-source)', () => {
+ const both = buildCJKKeywordSql('東京', ctx({
+ opts: { sourceIds: ['a', 'b'], sourceId: 'c' },
+ }));
+ expect(both!.sql).toContain('p.source_id = ANY(');
+ expect(both!.params).toContainEqual(['a', 'b']);
+ expect(both!.params).not.toContain('c');
+
+ const scalar = buildCJKKeywordSql('東京', ctx({ opts: { sourceId: 'c' } }));
+ expect(scalar!.sql).toContain('p.source_id = $');
+ expect(scalar!.params).toContain('c');
+ });
+
+ 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' },
+ }));
+ expect(built!.sql).toContain('cc.language = $');
+ expect(built!.sql).toContain('cc.symbol_type = $');
+ expect(built!.sql).toContain('> $');
+ expect(built!.sql).toContain('< $');
+ expect(built!.params).toEqual(expect.arrayContaining(['2026-01-01', '2026-02-01', 'typescript', 'function']));
+ });
+
+ test('multi-term query gets contiguous-raw-query bonus; single-term does not', () => {
+ const multi = buildCJKKeywordSql('東京 会議', ctx());
+ const single = buildCJKKeywordSql('東京', ctx());
+ // The bonus references the raw-query param in REPLACE: $5 for two terms
+ // (LIKE $1-$2, raw terms $3-$4, raw query $5); $3 for one term
+ // (LIKE $1, raw term $2, raw query $3 — used only in POSITION()).
+ expect((multi!.sql.match(/REPLACE\(cc\.chunk_text, \$5,/g) || []).length).toBeGreaterThan(0);
+ expect((single!.sql.match(/REPLACE\(cc\.chunk_text, \$3,/g) || []).length).toBe(0);
+ });
+});
+
+describe('postgres-engine searchKeywordCJK executor (#3986)', () => {
+ test('runs the built SQL through the runner and maps rows to SearchResult', async () => {
+ const calls: Array<{ sql: string; params: unknown[] }> = [];
+ const results = await searchKeywordCJKPg(
+ async (sql, params) => {
+ calls.push({ sql, params });
+ return [{
+ slug: 'notes/tokyo', page_id: 1, title: '東京', type: 'note', source_id: 'default',
+ effective_date: null, effective_date_source: null,
+ message_id: null, thread_id: null, source_subject: null,
+ chunk_id: 10, chunk_index: 0, chunk_text: '東京の会議', chunk_source: 'compiled_truth',
+ score: 1.5, stale: false,
+ }];
+ },
+ '東京 会議',
+ ctx(),
+ );
+ expect(calls.length).toBe(1);
+ expect(calls[0].sql).toContain('ILIKE');
+ expect(calls[0].params[0]).toBe('%東京%');
+ expect(results.length).toBe(1);
+ expect(results[0].slug).toBe('notes/tokyo');
+ expect(results[0].score).toBe(1.5);
+ });
+
+ test('empty query never touches the runner', async () => {
+ let called = false;
+ const results = await searchKeywordCJKPg(async () => { called = true; return []; }, '', ctx());
+ expect(results).toEqual([]);
+ expect(called).toBe(false);
+ });
+});
diff --git a/test/cli-help-eval-storage-reindex.test.ts b/test/cli-help-eval-storage-reindex.test.ts
new file mode 100644
index 0000000000..e33f4eb63a
--- /dev/null
+++ b/test/cli-help-eval-storage-reindex.test.ts
@@ -0,0 +1,89 @@
+/**
+ * #3686 (the #578 residue) — `eval` / `storage` / `reindex` --help must print
+ * real usage, not the generic one-line CLI_ONLY stub.
+ *
+ * Pre-fix, all three exited 0 with `gbrain <cmd> - run gbrain --help for the
+ * full command list.` — for eval that hid a 15-subcommand surface whose help
+ * block already shipped in the binary and was reachable ONLY via the
+ * missing-required-arg error path.
+ *
+ * Same subprocess pattern as test/cli-help-discoverability.test.ts: hermetic
+ * no-brain env, so these also pin that help works on a machine with no brain
+ * configured (the state a --help reader is most likely in).
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+
+const CLI_ENTRY = join(process.cwd(), 'src/cli.ts');
+
+function runCli(args: string[]): { stdout: string; stderr: string; status: number } {
+ const env: Record<string, string | undefined> = {
+ ...process.env,
+ GBRAIN_HOME: '/tmp/gbrain-test-help-3686-nonexistent',
+ };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const result = spawnSync('bun', ['--no-env-file', 'run', CLI_ENTRY, ...args], {
+ encoding: 'utf8',
+ env,
+ });
+ return {
+ stdout: result.stdout ?? '',
+ stderr: result.stderr ?? '',
+ status: result.status ?? -1,
+ };
+}
+
+const GENERIC_STUB = 'run gbrain --help for the full command list';
+
+describe('#3686 — gbrain eval --help prints the real usage block', () => {
+ test('reaches eval.ts printHelp with the subcommand surface, engine-free', () => {
+ const { stdout, status } = runCli(['eval', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).not.toContain(GENERIC_STUB);
+ // The qrels A/B core plus subcommands the old stub hid.
+ expect(stdout).toContain('--qrels');
+ expect(stdout).toContain('replay');
+ expect(stdout).toContain('brainbench');
+ }, 60000);
+
+ test('eval brainbench --help still prints brainbench usage, not the eval block', () => {
+ const { stdout, stderr, status } = runCli(['eval', 'brainbench', '--help']);
+ // brainbench owns its 0/1/2 CI exit contract and (pre-existing on this
+ // branch) exits 2 on --help; this test pins WHICH usage wins, not the
+ // exit code. Its own usage must beat the generic eval block.
+ expect(status).not.toBe(-1);
+ const out = stdout + stderr;
+ expect(out).not.toContain(GENERIC_STUB);
+ expect(out).toContain('gbrain eval brainbench');
+ expect(out).not.toContain('--qrels');
+ }, 60000);
+});
+
+describe('#3686 — gbrain storage --help prints the real usage block', () => {
+ test('names the status subcommand and its flags, engine-free', () => {
+ const { stdout, status } = runCli(['storage', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).not.toContain(GENERIC_STUB);
+ expect(stdout).toContain('status');
+ expect(stdout).toContain('--repo');
+ expect(stdout).toContain('--json');
+ }, 60000);
+});
+
+describe('#3686 — gbrain reindex --help prints the real usage block', () => {
+ test('names all three targets incl. the dispatcher-parsed --multimodal flags, engine-free', () => {
+ const { stdout, status } = runCli(['reindex', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).not.toContain(GENERIC_STUB);
+ expect(stdout).toContain('--markdown');
+ expect(stdout).toContain('--multimodal');
+ expect(stdout).toContain('--aliases');
+ // The --multimodal flags that were parsed only in cli.ts's dispatcher
+ // and documented nowhere.
+ expect(stdout).toContain('--cost-estimate');
+ expect(stdout).toContain('--workers');
+ }, 60000);
+});
diff --git a/test/cli-input-plumbing-2822.test.ts b/test/cli-input-plumbing-2822.test.ts
new file mode 100644
index 0000000000..f75408f446
--- /dev/null
+++ b/test/cli-input-plumbing-2822.test.ts
@@ -0,0 +1,161 @@
+/**
+ * #2822 — input-plumbing honesty for put-shaped commands.
+ *
+ * Three failure modes conspired to silently destroy or no-op page content:
+ * 1. Empty/whitespace non-TTY stdin landed '' in the stdin param
+ * (covered in test/cli-stdin-hang.test.ts — param now stays unset).
+ * 2. A flag silently overwriting an already-set positional (e.g.
+ * `gbrain put notes.md --slug real-slug`) discarded a value with no
+ * trace; when the discarded value names an existing file the user
+ * almost certainly wanted `gbrain capture --file`.
+ * 3. A "successful" put with 0 chunks left the page unsearchable with no
+ * explanation — the response now carries chunk_skip_reason.
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { parseOpArgs } from '../src/cli.ts';
+import { operations, operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { resetGateway } from '../src/core/ai/gateway.ts';
+
+// PGLite schema init (130 migrations) exceeds the 5s default hook timeout on
+// a loaded machine — same mitigation as hybrid-cache-scope-poison.serial.
+setDefaultTimeout(30_000);
+
+// ── Part 2: flag-overwrites-positional warning ────────────────────────────
+
+function captureStderr(fn: () => void): string {
+ const orig = process.stderr.write.bind(process.stderr);
+ let out = '';
+ (process.stderr as { write: (c: unknown) => boolean }).write = (c: unknown) => {
+ out += String(c);
+ return true;
+ };
+ try {
+ fn();
+ } finally {
+ (process.stderr as { write: typeof orig }).write = orig;
+ }
+ return out;
+}
+
+describe('#2822 — parseOpArgs warns when a flag overwrites a set positional', () => {
+ const putOp = operationsByName.put_page ?? operations.find((o) => o.name === 'put_page')!;
+
+ test('warns on --slug overwriting the positional slug', () => {
+ let params: Record<string, unknown> = {};
+ const err = captureStderr(() => {
+ params = parseOpArgs(putOp, ['stray-value', '--slug', 'real-slug']);
+ });
+ expect(params.slug).toBe('real-slug'); // flag still wins (behavior unchanged)
+ expect(err).toContain('overwrites the positional value');
+ expect(err).toContain('stray-value');
+ });
+
+ test('suggests capture --file when the discarded positional names an existing file', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-2822-'));
+ const file = path.join(tmp, 'notes.md');
+ fs.writeFileSync(file, '# notes\n');
+ try {
+ const err = captureStderr(() => {
+ parseOpArgs(putOp, [file, '--slug', 'real-slug']);
+ });
+ expect(err).toContain('gbrain capture --file');
+ expect(err).toContain(file);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test('no warning when nothing is overwritten', () => {
+ const err = captureStderr(() => {
+ parseOpArgs(putOp, ['my-slug', '--content', 'hello world']);
+ });
+ expect(err).toBe('');
+ });
+
+ test('no warning when the flag repeats the same value', () => {
+ const err = captureStderr(() => {
+ parseOpArgs(putOp, ['same-slug', '--slug', 'same-slug']);
+ });
+ expect(err).toBe('');
+ });
+});
+
+// ── Part 3: chunk_skip_reason on 0-chunk puts ─────────────────────────────
+
+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);
+ resetGateway(); // no embedding provider → put_page runs noEmbed
+});
+
+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')!;
+
+describe('#2822 — chunk_skip_reason on 0-chunk puts', () => {
+ test('frontmatter-only content on a new slug → empty_body', async () => {
+ const result = (await putPage.handler(makeCtx(), {
+ slug: 'inbox/frontmatter-only',
+ content: '---\ntitle: Nothing else\n---\n',
+ })) as { status: string; chunks: number; chunk_skip_reason?: string };
+ expect(result.chunks).toBe(0);
+ expect(result.chunk_skip_reason).toBe('empty_body');
+ });
+
+ test('embed_skip-marked content (trusted local) → embed_skip', async () => {
+ const result = (await putPage.handler(makeCtx(), {
+ slug: 'inbox/skipped-embed',
+ content: '---\ntitle: Big\nembed_skip: true\n---\n\nSome body text that will not be chunked.',
+ })) as { chunks: number; chunk_skip_reason?: string };
+ expect(result.chunks).toBe(0);
+ expect(result.chunk_skip_reason).toBe('embed_skip');
+ });
+
+ test('normal content chunks → no chunk_skip_reason', async () => {
+ const result = (await putPage.handler(makeCtx(), {
+ slug: 'inbox/normal',
+ content: '---\ntitle: Normal\n---\n\nA real body with searchable content.',
+ })) as { chunks: number; chunk_skip_reason?: string };
+ expect(result.chunks).toBeGreaterThan(0);
+ expect(result.chunk_skip_reason).toBeUndefined();
+ });
+
+ test('unchanged rewrite (skipped) → write_skipped', async () => {
+ const content = '---\ntitle: Stable\n---\n\nSame content twice.';
+ await putPage.handler(makeCtx(), { slug: 'inbox/stable', content });
+ const second = (await putPage.handler(makeCtx(), { slug: 'inbox/stable', content })) as {
+ status: string; chunks: number; chunk_skip_reason?: string;
+ };
+ expect(second.status).toBe('skipped');
+ expect(second.chunk_skip_reason).toBe('write_skipped');
+ });
+});
diff --git a/test/cli-stdin-hang.test.ts b/test/cli-stdin-hang.test.ts
index 38459b4c84..1005b4267b 100644
--- a/test/cli-stdin-hang.test.ts
+++ b/test/cli-stdin-hang.test.ts
@@ -153,16 +153,25 @@ describe('#3513 — applyStdinParam content preservation (subprocess driver)', (
expect(params?.content).toBe('---\ntitle: x\n---\nbody');
}, 30_000);
- test('/dev/null yields empty-string content (readable, empty — pre-fix parity)', async () => {
+ // #2822: empty/whitespace stdin is NO input — the param stays unset so the
+ // required-param usage error fires, instead of '' flowing into a
+ // destructive empty write. (Pre-#2822 these pinned params.content === ''.)
+ test('/dev/null leaves the stdin param unset (#2822)', async () => {
const { exited, params } = await runDriver({ file: '/dev/null' });
expect(exited).toBe(true);
- expect(params?.content).toBe('');
+ expect(params).toEqual({});
}, 30_000);
- test('empty closed pipe yields empty-string content', async () => {
+ test('empty closed pipe leaves the stdin param unset (#2822)', async () => {
const { exited, params } = await runDriver('closed-empty');
expect(exited).toBe(true);
- expect(params?.content).toBe('');
+ expect(params).toEqual({});
+ }, 30_000);
+
+ test('whitespace-only piped input leaves the stdin param unset (#2822)', async () => {
+ const { exited, params } = await runDriver({ data: ' \n\t\n' });
+ expect(exited).toBe(true);
+ expect(params).toEqual({});
}, 30_000);
test('held-open pipe times out and leaves the param unset', async () => {
diff --git a/test/code-def-refs.test.ts b/test/code-def-refs.test.ts
index 708e66188b..914c3ab564 100644
--- a/test/code-def-refs.test.ts
+++ b/test/code-def-refs.test.ts
@@ -13,7 +13,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importCodeFile } from '../src/core/import-file.ts';
-import { findCodeDef } from '../src/commands/code-def.ts';
+import { findCodeDef, probeFilteredSymbolTypes, DEF_TYPES } from '../src/commands/code-def.ts';
import { findCodeRefs } from '../src/commands/code-refs.ts';
let engine: PGLiteEngine;
@@ -144,7 +144,32 @@ export async function performDump(engine: BrainEngine, slug: string): Promise<Br
`;
await importCodeFile(engine, 'src/engine.ts', brainEngineSrc, { noEmbed: true });
await importCodeFile(engine, 'src/sync.ts', consumerSrc, { noEmbed: true });
-});
+
+ // #3821: decorated Python defs parse as decorated_definition wrappers.
+ // Pre-fix they emitted zero chunks, so code-def could never resolve them.
+ const pythonDecoratedSrc = `import functools
+
[email protected]_cache(maxsize=64)
+def cached_lookup(key):
+ """Resolve a pricing key from the canonical table with memoization."""
+ table = {"base": 100, "premium": 250, "enterprise": 900}
+ if key not in table:
+ raise KeyError("unknown pricing key: " + key)
+ return table[key]
+
+@dataclass
+class PricingConfig:
+ currency: str = "usd"
+
+ def describe(self):
+ return self.currency.upper()
+
+ @property
+ def symbol(self):
+ return "$" if self.currency == "usd" else "?"
+`;
+ await importCodeFile(engine, 'src/pricing.py', pythonDecoratedSrc, { noEmbed: true });
+}, 120_000);
afterAll(async () => {
await engine.disconnect();
@@ -182,6 +207,22 @@ describe('findCodeDef', () => {
const results = await findCodeDef(engine, 'BrainEngine', { language: 'python' });
expect(results).toEqual([]);
});
+
+ test('resolves a decorated python function definition (#3821)', async () => {
+ const results = await findCodeDef(engine, 'cached_lookup', { language: 'python' });
+ expect(results.length).toBeGreaterThanOrEqual(1);
+ const match = results.find((r) => r.slug === 'src-pricing-py');
+ expect(match).toBeDefined();
+ expect(match!.symbol_type).toBe('function');
+ });
+
+ test('resolves a decorated python class definition (#3821)', async () => {
+ const results = await findCodeDef(engine, 'PricingConfig', { language: 'python' });
+ expect(results.length).toBeGreaterThanOrEqual(1);
+ const match = results.find((r) => r.slug === 'src-pricing-py');
+ expect(match).toBeDefined();
+ expect(match!.symbol_type).toBe('class');
+ });
});
describe('findCodeRefs', () => {
@@ -220,3 +261,110 @@ describe('findCodeRefs', () => {
}
});
});
+
+// #3789 residual — normalizeSymbolType fallthroughs invisible to code-def.
+// 56ccc14 covered methods/ctors/fields; records (Java), properties (Kotlin/C#),
+// and the other audited *_declaration/*_definition/*_item fallthroughs were
+// still filtered out by DEF_TYPES, so `code-def` returned
+// {count: 0, ready: true} for symbols the chunker HAD indexed.
+describe('findCodeDef — DEF_TYPES fallthrough residual (#3789)', () => {
+ beforeAll(async () => {
+ const javaRecordSrc = `public record PointFixtureRecord(double x, double y, double z, String label, long recordedAtMillis) {
+ public double distanceFromOrigin() {
+ return Math.sqrt(x * x + y * y + z * z);
+ }
+
+ public String describeForHumans() {
+ return label + " at (" + x + ", " + y + ", " + z + ") recorded at " + recordedAtMillis;
+ }
+}
+`;
+ const kotlinPropertySrc = `val fixtureKotlinBannerProperty: String = "a deliberately long top-level Kotlin property value that keeps this chunk comfortably above the small-sibling merge threshold used by the gbrain code chunker fixtures"
+
+fun fixtureKotlinHelper(input: String): String {
+ return input.trim().lowercase().replace(" ", "-") + "/" + fixtureKotlinBannerProperty.length
+}
+`;
+ await importCodeFile(engine, 'src/PointFixtureRecord.java', javaRecordSrc, { noEmbed: true });
+ await importCodeFile(engine, 'src/fixture.kt', kotlinPropertySrc, { noEmbed: true });
+ }, 30000);
+
+ test('Java record declaration is a definition', async () => {
+ const results = await findCodeDef(engine, 'PointFixtureRecord');
+ expect(results.length).toBeGreaterThanOrEqual(1);
+ expect(results[0]!.symbol_type).toBe('record declaration');
+ });
+
+ test('Kotlin top-level property declaration is a definition', async () => {
+ const results = await findCodeDef(engine, 'fixtureKotlinBannerProperty');
+ expect(results.length).toBeGreaterThanOrEqual(1);
+ expect(results[0]!.symbol_type).toBe('property declaration');
+ });
+
+ test('every audited fallthrough spelling is in DEF_TYPES', () => {
+ const audited = [
+ // C# / Kotlin / Java entity members + entities
+ 'property declaration', 'record declaration', 'struct declaration',
+ 'object declaration', 'namespace declaration', 'file scoped namespace declaration',
+ // PHP / Scala
+ 'trait declaration', 'trait definition', 'object definition',
+ // Solidity (bare 'contract' is never produced by normalizeSymbolType)
+ 'contract declaration', 'modifier definition', 'event definition',
+ // C / C++
+ 'namespace definition', 'template declaration', 'declaration', 'preproc def',
+ // Go
+ 'type declaration', 'const declaration', 'var declaration',
+ // Rust *_item fallthroughs
+ 'struct item', 'trait item', 'impl item', 'mod item', 'type item',
+ 'const item', 'static item',
+ // TS/JS top-level const/let/var + Lua local
+ 'lexical declaration', 'variable declaration', 'local declaration',
+ ];
+ for (const t of audited) {
+ expect(DEF_TYPES).toContain(t);
+ }
+ });
+});
+
+// #3789 aside — a count:0 that was FILTERED by the allowlist must not read as
+// a bare "ready, symbol does not exist". The probe surfaces the symbol types
+// that exist for the name but were excluded by DEF_TYPES.
+describe('probeFilteredSymbolTypes (#3789)', () => {
+ beforeAll(async () => {
+ await engine.putPage('code/exotic-fixture', {
+ type: 'note',
+ title: 'exotic fixture',
+ compiled_truth: 'exotic fixture page',
+ } as any, { sourceId: 'default' });
+ await engine.executeRaw(
+ `UPDATE pages SET page_kind = 'code' WHERE slug = 'code/exotic-fixture' AND source_id = 'default'`,
+ [],
+ );
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM pages WHERE slug = 'code/exotic-fixture' AND source_id = 'default'`,
+ [],
+ );
+ await engine.executeRaw(
+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, symbol_name, symbol_type, language)
+ VALUES ($1, 0, 'exotic fixture chunk body', 'ExoticFixtureSymbol', 'exotic gizmo kind', 'typescript')`,
+ [rows[0]!.id],
+ );
+ }, 30000);
+
+ test('returns the allowlist-filtered symbol types for a name', async () => {
+ const results = await findCodeDef(engine, 'ExoticFixtureSymbol');
+ expect(results).toEqual([]);
+ const filtered = await probeFilteredSymbolTypes(engine, 'ExoticFixtureSymbol');
+ expect(filtered).toEqual(['exotic gizmo kind']);
+ });
+
+ test('returns empty for a truly absent symbol', async () => {
+ const filtered = await probeFilteredSymbolTypes(engine, 'ThisSymbolDoesNotExist');
+ expect(filtered).toEqual([]);
+ });
+
+ test('language filter applies to the probe', async () => {
+ const filtered = await probeFilteredSymbolTypes(engine, 'ExoticFixtureSymbol', { language: 'python' });
+ expect(filtered).toEqual([]);
+ });
+});
diff --git a/test/code-graph-readiness.test.ts b/test/code-graph-readiness.test.ts
index e431c5b42d..0588322eff 100644
--- a/test/code-graph-readiness.test.ts
+++ b/test/code-graph-readiness.test.ts
@@ -5,6 +5,7 @@
* "graph not built / still indexing" apart from "genuinely no match" when
* count === 0:
* - empty brain → not_built (both grains)
+ * - code chunks with no symbol metadata → symbol grain no_symbols (#3640)
* - code synced, edges not resolved → symbol grain ready, edge grain indexing
* - edges resolved → edge grain ready
* - count > 0 → ready short-circuit (no query)
@@ -36,12 +37,28 @@ beforeEach(async () => {
await engine.executeRaw('DELETE FROM pages');
});
+// Each function must exceed the chunker's small-sibling merge threshold
+// (15% of the 300-token chunk target) so chunks keep their symbol_name.
+// Tiny functions would merge into one symbol_type='merged' chunk with
+// symbol_name NULL — which is exactly the #3640 no_symbols state, tested
+// separately below.
const SAMPLE = `export function alpha(x: number): number {
- return beta(x) + 1;
+ // Alpha computes the successor of beta applied to its input. The body is
+ // deliberately padded with commentary so the emitted chunk stays above the
+ // merge threshold and keeps its own symbol_name in content_chunks, which
+ // the readiness probe (and code-def itself) match on.
+ const intermediate = beta(x);
+ const successor = intermediate + 1;
+ return successor;
}
export function beta(y: number): number {
- return y * 2;
+ // Beta doubles its input. Same padding rationale as alpha above: keep this
+ // chunk large enough that mergeSmallSiblings passes it through verbatim
+ // instead of rolling it into an anonymous merged chunk without a
+ // symbol_name, so the 'ready' fixtures exercise symbol-bearing chunks.
+ const doubled = y * 2;
+ return doubled;
}
`;
@@ -98,14 +115,59 @@ describe('resolveCodeReadiness — code synced, edges unresolved', () => {
});
});
+describe('resolveCodeReadiness — code chunks without symbol metadata (#3640)', () => {
+ beforeEach(async () => {
+ await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });
+ // Simulate chunks written before symbol-aware chunking (or a chunker
+ // fallback that skipped extraction): code chunks exist, no symbol_name.
+ await engine.executeRaw('UPDATE content_chunks SET symbol_name = NULL');
+ });
+
+ test('symbol grain → no_symbols (not ready) when no chunk carries symbol_name', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0 });
+ expect(r.status).toBe('no_symbols');
+ expect(r.ready).toBe(false);
+ expect(r.has_code).toBe(true);
+ });
+
+ test('no_symbols hint points at reindex-code', () => {
+ const hint = readinessHint({ status: 'no_symbols', ready: false, has_code: true, pending_edges: false });
+ expect(hint).toContain('reindex-code');
+ });
+
+ test('edge grain is unaffected (still indexing on pending edges)', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'edge', count: 0 });
+ expect(r.status).toBe('indexing');
+ });
+
+ test('symbol grain scoped to a source with only symbol-less code → no_symbols', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'default' });
+ expect(r.status).toBe('no_symbols');
+ });
+});
+
describe('resolveCodeReadiness — source scoping', () => {
beforeEach(async () => {
await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });
});
- test('scoped to a source with no code → not_built', async () => {
- const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'no-such-source' });
- expect(r.status).toBe('not_built');
+ // #3707: pre-fix this reported `not_built` — indistinguishable from a
+ // never-synced brain — and the hint misdirected to `gbrain sync`. Code
+ // exists brain-wide (the beforeEach import), so a scoped miss is a
+ // scope/grant problem, not an indexing one. #4352 remediation: the
+ // brain-wide rerun is a trusted-local-only signal (remote: false).
+ test('scoped to a source with no code while code exists brain-wide → out_of_scope (symbol)', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'no-such-source', remote: false });
+ expect(r.status).toBe('out_of_scope');
+ expect(r.ready).toBe(false);
+ expect(r.has_code).toBe(false);
+ expect(r.scoped_source_id).toBe('no-such-source');
+ });
+
+ test('scoped to a source with no code while code exists brain-wide → out_of_scope (edge)', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'edge', count: 0, sourceId: 'no-such-source', remote: false });
+ expect(r.status).toBe('out_of_scope');
+ expect(r.scoped_source_id).toBe('no-such-source');
});
test('scoped to the default source (where code lives) → ready (symbol)', async () => {
@@ -121,6 +183,57 @@ describe('resolveCodeReadiness — source scoping', () => {
});
});
+describe('resolveCodeReadiness — #3707 out_of_scope vs not_built', () => {
+ test('scoped miss on a genuinely empty brain stays not_built (no code anywhere)', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'no-such-source', remote: false });
+ expect(r.status).toBe('not_built');
+ expect(r.scoped_source_id).toBeUndefined();
+ });
+
+ test('unscoped miss never reports out_of_scope', async () => {
+ await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0 });
+ expect(r.status).toBe('ready'); // brain-wide probe sees the code
+ });
+
+ test('out_of_scope hint names the scope and does NOT recommend gbrain sync', () => {
+ const hint = readinessHint({
+ status: 'out_of_scope', ready: false, has_code: false,
+ pending_edges: false, scoped_source_id: 'default',
+ });
+ expect(hint).toContain("source 'default'");
+ expect(hint).toContain('scope/grant problem');
+ expect(hint).toContain('federated_read');
+ expect(hint).not.toMatch(/Run `gbrain sync`/);
+ });
+});
+
+describe('resolveCodeReadiness — #4352 remediation: out_of_scope rerun is trusted-local only', () => {
+ beforeEach(async () => {
+ await importCodeFile(engine, 'src/sample.ts', SAMPLE, { noEmbed: true });
+ });
+
+ // The #3707 rerun probes code existence OUTSIDE the caller's resolved scope.
+ // A scoped remote caller must not learn that code exists brain-wide.
+ test('remote scoped miss stays not_built (no brain-wide existence disclosure)', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'no-such-source', remote: true });
+ expect(r.status).toBe('not_built');
+ expect(r.scoped_source_id).toBeUndefined();
+ });
+
+ test('unset trust is untrusted (fail-closed): scoped miss stays not_built', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'edge', count: 0, sourceId: 'no-such-source' });
+ expect(r.status).toBe('not_built');
+ expect(r.scoped_source_id).toBeUndefined();
+ });
+
+ test('trusted local (remote === false) keeps the #3707 out_of_scope signal', async () => {
+ const r = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceId: 'no-such-source', remote: false });
+ expect(r.status).toBe('out_of_scope');
+ expect(r.scoped_source_id).toBe('no-such-source');
+ });
+});
+
describe('resolveCodeReadiness — fail-open (CRITICAL regression)', () => {
test('DB error → status unknown, ready false, never throws', async () => {
const broken = {
diff --git a/test/config-set.test.ts b/test/config-set.test.ts
index ad8222f88c..1a9543fb56 100644
--- a/test/config-set.test.ts
+++ b/test/config-set.test.ts
@@ -359,6 +359,73 @@ describe('#2753 — the doctor-proposed gateway-loop command is accepted by `con
});
});
+describe('#3748 — budget.* rejection routes to the live spend controls', () => {
+ function setStubEngine(): { engine: BrainEngine; setCalls: Array<[string, string]> } {
+ const setCalls: Array<[string, string]> = [];
+ const engine = {
+ getConfig: async () => null,
+ setConfig: async (key: string, value: string) => { setCalls.push([key, value]); },
+ } as unknown as BrainEngine;
+ return { engine, setCalls };
+ }
+
+ async function runConfigCapture(
+ engine: BrainEngine,
+ args: string[],
+ ): Promise<{ logs: string[]; errs: string[]; exit: number | null }> {
+ const logs: string[] = [];
+ const errs: string[] = [];
+ let exit: number | null = null;
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ exit = code ?? 0;
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ try {
+ await runConfig(engine, args);
+ } catch (e) {
+ if (!(e as Error).message.startsWith('EXIT:')) throw e;
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ return { logs, errs, exit };
+ }
+
+ // Old release notes documented `budget.daily_cap_usd` as a hard spend wall,
+ // but the key was never registered and has NO readers. The rejection must
+ // name the control that actually exists (spend.posture + the spend-controls
+ // guide) instead of leaving the operator to --force a cap that caps nothing.
+ test('budget.daily_cap_usd is rejected AND the error names spend.posture + the guide', async () => {
+ const { engine, setCalls } = setStubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'budget.daily_cap_usd', '10']);
+ expect(exit).toBe(1);
+ const err = errs.join('\n');
+ expect(err).toContain('Unknown config key "budget.daily_cap_usd"');
+ expect(err).toContain('spend.posture');
+ expect(err).toContain('docs/operations/spend-controls.md');
+ expect(setCalls).toEqual([]);
+ });
+
+ test('--force still writes but warns that budget.* is not a spend cap', async () => {
+ const { engine, setCalls } = setStubEngine();
+ const { errs, exit } = await runConfigCapture(engine, ['set', 'budget.daily_cap_usd', '10', '--force']);
+ expect(exit).toBeNull();
+ const err = errs.join('\n');
+ expect(err).toContain('Nothing in gbrain reads this');
+ expect(err).toContain('NOT a spend cap');
+ expect(err).toContain('spend.posture');
+ expect(setCalls).toEqual([['budget.daily_cap_usd', '10']]);
+ });
+
+ test('budget.* stays unregistered — no readerless key gets blessed', () => {
+ expect(KNOWN_CONFIG_KEYS.some(k => k === 'budget' || k.startsWith('budget.'))).toBe(false);
+ expect(KNOWN_CONFIG_KEY_PREFIXES).not.toContain('budget.');
+ });
+});
+
describe('#2753 — doctor and the subagent worker share one truthiness set', () => {
// The doctor accepted true/1/yes/on; the worker accepted only true/1. So
// `gbrain config set agent.use_gateway_loop yes` produced a HEALTHY doctor
diff --git a/test/confirm-prompt.test.ts b/test/confirm-prompt.test.ts
new file mode 100644
index 0000000000..5172432631
--- /dev/null
+++ b/test/confirm-prompt.test.ts
@@ -0,0 +1,61 @@
+/**
+ * #4318 — promptYesNo close-race regression.
+ *
+ * The old inline twins (sync-cost-gate.ts / reindex-code.ts) called
+ * rl.close() before resolving, and their unguarded 'close' listener
+ * resolved(false) synchronously during that close — a typed "y" was read as
+ * a decline (verified reproducible under bun). Pins the shared helper:
+ * answer resolves first; 'close' only declines on a true EOF.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { PassThrough } from 'stream';
+import { promptYesNo } from '../src/core/confirm-prompt.ts';
+
+function mkStreams() {
+ return { input: new PassThrough(), output: new PassThrough() };
+}
+
+describe('promptYesNo (#4318)', () => {
+ test('"y" answer resolves TRUE (the close-race regression)', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.write('y\n');
+ expect(await p).toBe(true);
+ });
+
+ test('"yes" (case/space-insensitive) resolves true', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.write(' YES \n');
+ expect(await p).toBe(true);
+ });
+
+ test('"n" resolves false', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.write('n\n');
+ expect(await p).toBe(false);
+ });
+
+ test('empty answer resolves false (the [y/N] default)', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.write('\n');
+ expect(await p).toBe(false);
+ });
+
+ test('EOF without an answer (Ctrl-D) resolves false', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.end(); // no line ever arrives
+ expect(await p).toBe(false);
+ });
+
+ test('answer followed by immediate EOF still resolves true', async () => {
+ const { input, output } = mkStreams();
+ const p = promptYesNo('Proceed? [y/N] ', { input, output });
+ input.end('y\n');
+ expect(await p).toBe(true);
+ });
+});
diff --git a/test/content-hash-parity-3694.test.ts b/test/content-hash-parity-3694.test.ts
new file mode 100644
index 0000000000..4eff2c0260
--- /dev/null
+++ b/test/content-hash-parity-3694.test.ts
@@ -0,0 +1,233 @@
+/**
+ * #3694 — one canonical content-hash formula.
+ *
+ * Pre-fix, utils.contentHash (both engines' putPage fallback) and the
+ * importer's inline formula hashed DIFFERENT shapes (no ephemeral strip, no
+ * tags on the putPage side), so the same logical page carried two hashes and
+ * every putPage→sync roundtrip re-chunked + re-embedded unchanged content.
+ *
+ * Coverage:
+ * 1. GOLDEN byte-parity: contentHash reproduces the importer's former
+ * inline formula exactly (replicated here), pinned to a literal digest.
+ * 2. Ephemeral keys + tags spelling invariance.
+ * 3. contentHashLegacy preserves the pre-fix putPage formula.
+ * 4. PGLite e2e: putPage → importFromContent of the same logical page is a
+ * SKIP (hashes converge); a legacy-hashed row is reconciled in place
+ * (canonical hash stamped, no re-chunk) and the next import fast-skips.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { createHash } from 'crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { contentHash, contentHashLegacy, HASH_EPHEMERAL_FRONTMATTER_KEYS } from '../src/core/utils.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { parseMarkdown } from '../src/core/markdown.ts';
+
+/** The importer's former inline formula, replicated byte-for-byte. */
+function formerImporterHash(parsed: {
+ title: string;
+ type: string;
+ compiled_truth: string;
+ timeline: string;
+ frontmatter: Record<string, unknown>;
+ tags: string[];
+}): string {
+ const stableFrontmatter: Record<string, unknown> = { ...parsed.frontmatter };
+ for (const k of HASH_EPHEMERAL_FRONTMATTER_KEYS) delete stableFrontmatter[k];
+ return createHash('sha256')
+ .update(JSON.stringify({
+ title: parsed.title,
+ type: parsed.type,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: stableFrontmatter,
+ tags: [...parsed.tags].sort(),
+ }))
+ .digest('hex');
+}
+
+const FILE_CONTENT = [
+ '---',
+ 'type: concept',
+ 'title: Golden Page',
+ 'tags: [beta, alpha]',
+ 'extra: value',
+ 'captured_at: 2026-08-21T00:00:00Z',
+ '---',
+ '',
+ 'Golden body for the #3694 parity pin.',
+ '',
+].join('\n');
+
+describe('#3694 contentHash — canonical formula', () => {
+ test('GOLDEN: matches the importer former inline formula byte-for-byte', () => {
+ const parsed = parseMarkdown(FILE_CONTENT, 'topics/golden-page.md');
+ const viaHelper = contentHash({
+ title: parsed.title,
+ type: parsed.type as never,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ tags: parsed.tags,
+ });
+ const viaFormerInline = formerImporterHash({
+ title: parsed.title,
+ type: parsed.type,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ tags: parsed.tags,
+ });
+ expect(viaHelper).toBe(viaFormerInline);
+ });
+
+ test('ephemeral frontmatter keys do not perturb the hash', () => {
+ const base = {
+ title: 'T',
+ type: 'concept' as never,
+ compiled_truth: 'body',
+ timeline: '',
+ frontmatter: { extra: 'v' },
+ };
+ const withEphemeral = {
+ ...base,
+ frontmatter: {
+ extra: 'v',
+ captured_at: '2026-08-21T01:02:03Z',
+ ingested_at: '2026-08-21T01:02:03Z',
+ quarantine: { reason: 'x' },
+ content_flag: { reason: 'y' },
+ embed_skip: { bytes: 999 },
+ },
+ };
+ expect(contentHash(withEphemeral)).toBe(contentHash(base));
+ });
+
+ test('tags hash identically whether hoisted (page.tags) or inline (frontmatter.tags)', () => {
+ const hoisted = contentHash({
+ title: 'T',
+ type: 'concept' as never,
+ compiled_truth: 'body',
+ frontmatter: { extra: 'v' },
+ tags: ['b', 'a'],
+ });
+ const inline = contentHash({
+ title: 'T',
+ type: 'concept' as never,
+ compiled_truth: 'body',
+ frontmatter: { extra: 'v', tags: ['a', 'b'] },
+ });
+ expect(hoisted).toBe(inline);
+ });
+
+ test('contentHashLegacy preserves the pre-#3694 putPage formula', () => {
+ const page = {
+ title: 'T',
+ type: 'concept' as never,
+ compiled_truth: 'body',
+ timeline: '',
+ frontmatter: { extra: 'v', captured_at: 'x', tags: ['a'] },
+ };
+ const oldFormula = createHash('sha256')
+ .update(JSON.stringify({
+ title: page.title,
+ type: page.type,
+ compiled_truth: page.compiled_truth,
+ timeline: page.timeline || '',
+ frontmatter: page.frontmatter || {},
+ }))
+ .digest('hex');
+ expect(contentHashLegacy(page)).toBe(oldFormula);
+ // And the canonical formula genuinely differs on this shape (tags +
+ // ephemeral present) — otherwise the legacy shim would be dead code.
+ expect(contentHash(page)).not.toBe(oldFormula);
+ });
+});
+
+describe('#3694 putPage → import converges (PGLite e2e)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ }, 60_000);
+
+ test('a page written via putPage is SKIPPED on re-import of the same file', async () => {
+ const parsed = parseMarkdown(FILE_CONTENT, 'topics/golden-page.md');
+ // putPage the same logical page (frontmatter spelling: tags inline, the
+ // typical ops-caller shape) with NO explicit content_hash so the engine
+ // fallback computes it.
+ await engine.putPage('topics/golden-page', {
+ type: parsed.type as never,
+ title: parsed.title,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: { ...parsed.frontmatter, tags: parsed.tags, captured_at: '2026-08-21T09:00:00Z' },
+ });
+
+ const result = await importFromContent(engine, 'topics/golden-page', FILE_CONTENT, {
+ noEmbed: true,
+ });
+ expect(result.status).toBe('skipped');
+ }, 60_000);
+
+ test('a legacy-hashed row is reconciled in place and then fast-skips', async () => {
+ const slug = 'topics/legacy-page';
+ const content = [
+ '---',
+ 'type: concept',
+ 'title: Legacy Page',
+ 'tags: [x]',
+ '---',
+ '',
+ 'Legacy body.',
+ '',
+ ].join('\n');
+ const parsed = parseMarkdown(content, slug + '.md');
+ const legacy = contentHashLegacy({
+ title: parsed.title,
+ type: parsed.type as never,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ });
+ const canonical = contentHash({
+ title: parsed.title,
+ type: parsed.type as never,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ tags: parsed.tags,
+ });
+ expect(legacy).not.toBe(canonical);
+
+ // Simulate a pre-fix row: explicit legacy content_hash.
+ await engine.putPage(slug, {
+ type: parsed.type as never,
+ title: parsed.title,
+ compiled_truth: parsed.compiled_truth,
+ timeline: parsed.timeline,
+ frontmatter: parsed.frontmatter,
+ content_hash: legacy,
+ });
+
+ const first = await importFromContent(engine, slug, content, { noEmbed: true });
+ expect(first.status).toBe('skipped');
+
+ // The reconcile stamped the canonical hash without a re-import.
+ const rows = await engine.executeRaw<{ content_hash: string }>(
+ `SELECT content_hash FROM pages WHERE source_id = 'default' AND slug = $1`,
+ [slug],
+ );
+ expect(rows[0]!.content_hash).toBe(canonical);
+
+ // Second import takes the fast path (hash equality) and stays skipped.
+ const second = await importFromContent(engine, slug, content, { noEmbed: true });
+ expect(second.status).toBe('skipped');
+ }, 60_000);
+});
diff --git a/test/context/entity-salience.test.ts b/test/context/entity-salience.test.ts
index 895eb896ac..6c866f848e 100644
--- a/test/context/entity-salience.test.ts
+++ b/test/context/entity-salience.test.ts
@@ -179,3 +179,47 @@ describe('v0.46.15 ship-review F10 — rejected strong candidates do not shadow
expect(weak.some((c) => c.query === 'persona12')).toBe(true);
});
});
+
+describe('#3746 — CJK weak n-gram pass (JA/KO/ZH)', () => {
+ test('japanese: name grams extracted as weak candidates (pre-fix: zero)', () => {
+ const weak = weakQueries('田中さんの会議のメモを見せて');
+ expect(weak.length).toBeGreaterThan(0);
+ expect(weak).toContain('田中');
+ });
+
+ test('korean: whitespace-tokenized name run extracted whole', () => {
+ const weak = weakQueries('김철수 미팅 노트 보여줘');
+ expect(weak).toContain('김철수');
+ });
+
+ test('chinese: name grams extracted from an unsegmented sentence', () => {
+ const weak = weakQueries('给我看看王小明的笔记');
+ expect(weak).toContain('王小明');
+ });
+
+ test('every CJK candidate is weak (never strong)', () => {
+ const cands = extractCandidates('田中さんの会議');
+ for (const c of cands) expect(c.weak).toBe(true);
+ });
+
+ test('pure-hiragana grams (particles/function words) are skipped', () => {
+ const weak = weakQueries('それをしてください');
+ expect(weak).toEqual([]);
+ });
+
+ test('CJK pass honors its own cap', () => {
+ const long = '漢'.repeat(40) + '字'.repeat(40);
+ const weak = weakQueries(long);
+ expect(weak.length).toBeLessThanOrEqual(24);
+ });
+
+ test('no CJK in text → pass is inert (latin-only output unchanged)', () => {
+ const cands = extractCandidates('what do you think about Garry Tan?');
+ expect(cands.some((c) => /[一-鿿぀-ゟ゠-ヿ가-힯]/.test(c.query))).toBe(false);
+ });
+
+ test('grams deduplicate against strong candidates and each other', () => {
+ const weak = weakQueries('田中 田中');
+ expect(weak.filter((q) => q === '田中')).toHaveLength(1);
+ });
+});
diff --git a/test/context/resolve-ipc-sweep-kinds.test.ts b/test/context/resolve-ipc-sweep-kinds.test.ts
new file mode 100644
index 0000000000..23a1d4a50b
--- /dev/null
+++ b/test/context/resolve-ipc-sweep-kinds.test.ts
@@ -0,0 +1,151 @@
+/**
+ * #677 — delegated-sweep IPC kinds (resolve-ipc.ts + sweep-ipc.ts) protocol
+ * pins, mirroring resolve-ipc-sync-kinds.test.ts:
+ *
+ * - secret gating fails CLOSED (no secret → unauthorized, wrong secret →
+ * unauthorized) — the sweep kinds mutate the brain.
+ * - a serve WITHOUT sweep handlers answers unsupported_kind WITH the
+ * protocol echo — clients refuse politely.
+ * - a PRE-DELEGATION serve yields the typed stale_serve degrade.
+ * - validateDelegatedSweepOptions is default-deny.
+ *
+ * Parallel-safe: hermetic tmpdir sockets, no env mutation, no engine.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ IPC_UNAVAILABLE,
+ requestSweepStart,
+ requestSweepStatus,
+ resolveSocketPath,
+ startResolveIpcServer,
+ type IpcHandlers,
+} from '../../src/core/context/resolve-ipc.ts';
+import {
+ validateDelegatedSweepOptions,
+ DELEGATED_SWEEP_BUDGET_MAX_MS,
+ type SweepStartResponse,
+ type SweepStatusResponse,
+} from '../../src/core/context/sweep-ipc.ts';
+
+const servers: Array<{ close: () => void }> = [];
+const dirs: string[] = [];
+afterEach(() => {
+ for (const s of servers.splice(0)) { try { s.close(); } catch { /* noop */ } }
+ for (const d of dirs.splice(0)) { try { rmSync(d, { recursive: true, force: true }); } catch { /* noop */ } }
+});
+
+function tmpDir(): string {
+ const d = mkdtempSync(join(tmpdir(), 'swi-'));
+ dirs.push(d);
+ return d;
+}
+
+const SECRET = 'test-secret';
+
+function stubHandlers(): IpcHandlers {
+ return {
+ resolve: async () => null,
+ sweep_start: (req) =>
+ ({ ok: true, protocol: 2, jobId: `sweep-for-${req.clientToken}` }) satisfies SweepStartResponse,
+ sweep_status: () =>
+ ({ ok: true, protocol: 2, state: 'running', startedAt: 1, elapsedMs: 2 }) satisfies SweepStatusResponse,
+ };
+}
+
+async function startServer(dir: string, handlers: IpcHandlers, secret?: string) {
+ const sock = resolveSocketPath(dir);
+ const server = await startResolveIpcServer(sock, handlers, { secret });
+ expect(server).not.toBeNull();
+ servers.push(server!);
+ return sock;
+}
+
+describe('delegated-sweep IPC kinds (#677)', () => {
+ test('round-trip: sweep_start reaches the handler and echoes protocol 2', async () => {
+ const sock = await startServer(tmpDir(), stubHandlers(), SECRET);
+ const r = await requestSweepStart(sock, { secret: SECRET, clientToken: 'tok-1', options: {} });
+ expect(r).not.toBe(IPC_UNAVAILABLE);
+ const resp = r as SweepStartResponse;
+ expect(resp.ok).toBe(true);
+ expect(resp.protocol).toBe(2);
+ expect(resp.jobId).toBe('sweep-for-tok-1');
+ });
+
+ test('wrong secret → unauthorized (both kinds)', async () => {
+ const sock = await startServer(tmpDir(), stubHandlers(), SECRET);
+ const start = await requestSweepStart(sock, { secret: 'nope', clientToken: 't', options: {} });
+ expect((start as SweepStartResponse).error).toBe('unauthorized');
+ const status = await requestSweepStatus(sock, { secret: 'nope', jobId: 'j' });
+ expect((status as SweepStatusResponse).error).toBe('unauthorized');
+ });
+
+ test('NO secret configured → unauthorized (fail closed, never open service)', async () => {
+ const sock = await startServer(tmpDir(), stubHandlers(), undefined);
+ const r = await requestSweepStart(sock, { secret: SECRET, clientToken: 't', options: {} });
+ expect((r as SweepStartResponse).ok).toBe(false);
+ expect((r as SweepStartResponse).error).toBe('unauthorized');
+ });
+
+ test('handlers absent (kill switch / build failure) → unsupported_kind WITH echo', async () => {
+ const sock = await startServer(tmpDir(), { resolve: async () => null }, SECRET);
+ const r = await requestSweepStart(sock, { secret: SECRET, clientToken: 't', options: {} });
+ const resp = r as SweepStartResponse;
+ expect(resp.ok).toBe(false);
+ expect(resp.error).toBe('unsupported_kind');
+ expect(resp.protocol).toBe(2);
+ });
+
+ test('pre-delegation serve → stale_serve degrade (no protocol echo)', async () => {
+ const dir = tmpDir();
+ const sock = resolveSocketPath(dir);
+ const net = await import('node:net');
+ const raw = net.createServer((conn) => {
+ conn.on('data', () => {
+ conn.write(JSON.stringify({ ok: false, error: 'unknown_kind:sweep_start' }) + '\n');
+ conn.end();
+ });
+ });
+ await new Promise<void>((r) => raw.listen(sock, () => r()));
+ servers.push(raw);
+ const r = await requestSweepStart(sock, { secret: SECRET, clientToken: 't', options: {} });
+ expect(r).toEqual({ degraded: 'stale_serve' });
+ });
+
+ test('absent socket → IPC_UNAVAILABLE', async () => {
+ const r = await requestSweepStatus(resolveSocketPath(tmpDir()), { secret: SECRET, jobId: 'j' });
+ expect(r).toBe(IPC_UNAVAILABLE);
+ });
+});
+
+describe('validateDelegatedSweepOptions (#677) — default-deny', () => {
+ test('accepts the allowlisted fields and clamps budgetMs', () => {
+ const v = validateDelegatedSweepOptions({
+ sourceId: 'my-source',
+ budgetMs: DELEGATED_SWEEP_BUDGET_MAX_MS + 1,
+ batchLimit: 5,
+ });
+ expect(v.ok).toBe(true);
+ if (v.ok) {
+ expect(v.options.sourceId).toBe('my-source');
+ expect(v.options.budgetMs).toBe(DELEGATED_SWEEP_BUDGET_MAX_MS);
+ expect(v.options.batchLimit).toBe(5);
+ }
+ });
+
+ test('rejects unknown keys, wrong types, bad sourceId, negative numbers', () => {
+ expect(validateDelegatedSweepOptions({ repoPath: '/etc' }).ok).toBe(false);
+ expect(validateDelegatedSweepOptions({ budgetMs: 'fast' }).ok).toBe(false);
+ expect(validateDelegatedSweepOptions({ budgetMs: -1 }).ok).toBe(false);
+ expect(validateDelegatedSweepOptions({ sourceId: 'Not_Valid!' }).ok).toBe(false);
+ expect(validateDelegatedSweepOptions(null).ok).toBe(false);
+ expect(validateDelegatedSweepOptions([]).ok).toBe(false);
+ });
+
+ test('empty options are valid (all fields optional)', () => {
+ expect(validateDelegatedSweepOptions({}).ok).toBe(true);
+ });
+});
diff --git a/test/contextual-synopsis-model.serial.test.ts b/test/contextual-synopsis-model.serial.test.ts
index ae7563a03c..32a52d671c 100644
--- a/test/contextual-synopsis-model.serial.test.ts
+++ b/test/contextual-synopsis-model.serial.test.ts
@@ -101,16 +101,17 @@ describe('contextual synopsis model resolution', () => {
);
engine.unset('contextual_retrieval.haiku_model');
+ // #3873: models.tier.utility (specific) now beats models.default (generic).
expect(await resolveContextualSynopsisModel(engine as never)).toBe(
- 'codex-proxy:global-default',
+ 'codex-proxy:utility-tier',
);
- engine.unset('models.default');
+ engine.unset('models.tier.utility');
expect(await resolveContextualSynopsisModel(engine as never)).toBe(
- 'codex-proxy:utility-tier',
+ 'codex-proxy:global-default',
);
- engine.unset('models.tier.utility');
+ engine.unset('models.default');
expect(await resolveContextualSynopsisModel(engine as never)).toBe(
'codex-proxy:env-model',
);
diff --git a/test/conversation-parser-body.test.ts b/test/conversation-parser-body.test.ts
new file mode 100644
index 0000000000..673e09415d
--- /dev/null
+++ b/test/conversation-parser-body.test.ts
@@ -0,0 +1,163 @@
+/**
+ * #3911 — relative `raw_transcript` resolves against the page's OWNING
+ * source's local_path (not just the brain-global sync.repo_path), and
+ * `../` traversal outside the resolved root is rejected. Follow-up: an
+ * ABSOLUTE raw_transcript is the same untrusted frontmatter — it must land
+ * inside a registered root (source local_path or sync.repo_path) or it is
+ * rejected too (no /etc/passwd reads via synced frontmatter).
+ *
+ * Pre-fix: readConversationBodyForParsing only consulted sync.repo_path, so
+ * a multi-source brain whose transcripts live per-source silently read the
+ * wrong file (or fell back to the summary body), and an escaping relative
+ * path could read arbitrary host files.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { readConversationBodyForParsing } from '../src/core/conversation-parser/body.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { Page } from '../src/core/types.ts';
+
+let root: string;
+let sourceRepo: string;
+let globalRepo: string;
+let outsideDir: string;
+
+beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-3911-'));
+ sourceRepo = join(root, 'source-repo');
+ globalRepo = join(root, 'global-repo');
+ outsideDir = join(root, 'outside');
+ mkdirSync(join(sourceRepo, 'transcripts'), { recursive: true });
+ mkdirSync(join(globalRepo, 'transcripts'), { recursive: true });
+ mkdirSync(outsideDir, { recursive: true });
+ writeFileSync(join(sourceRepo, 'transcripts', 'meeting.txt'), 'SOURCE transcript body\n');
+ writeFileSync(join(globalRepo, 'transcripts', 'meeting.txt'), 'GLOBAL transcript body\n');
+ writeFileSync(join(outsideDir, 'secret.txt'), 'OUTSIDE THE ROOT\n');
+});
+
+afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+/** Stub engine: `sources` row lookup + sync.repo_path config. */
+function stubEngine(opts: {
+ sourceLocalPath?: string | null;
+ repoPath?: string | null;
+ sourceExists?: boolean;
+}): BrainEngine {
+ return {
+ executeRaw: async (_sql: string, params?: unknown[]) => {
+ if (opts.sourceExists === false) return [];
+ return [
+ {
+ id: (params?.[0] as string) ?? 'default',
+ name: 'stub',
+ local_path: opts.sourceLocalPath ?? null,
+ last_commit: null,
+ last_sync_at: null,
+ config: {},
+ created_at: new Date(),
+ contextual_retrieval_mode: null,
+ trust_frontmatter_overrides: false,
+ },
+ ];
+ },
+ getConfig: async (key: string) =>
+ key === 'sync.repo_path' ? (opts.repoPath ?? null) : null,
+ } as unknown as BrainEngine;
+}
+
+function pageWith(rawTranscript: string, sourceId = 'vault'): Page {
+ return {
+ slug: 'meetings/m1',
+ title: 'M1',
+ source_id: sourceId,
+ compiled_truth: 'SUMMARY body',
+ timeline: '',
+ frontmatter: { raw_transcript: rawTranscript },
+ } as unknown as Page;
+}
+
+describe('#3911 raw_transcript source-root resolution', () => {
+ test('relative path resolves against the OWNING source local_path, not sync.repo_path', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(engine, pageWith('transcripts/meeting.txt'));
+ expect(body).toBe('SOURCE transcript body');
+ });
+
+ test('escaping relative path (../) outside the source root is rejected — summary body wins', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith('../outside/secret.txt'),
+ );
+ expect(body).toBe('SUMMARY body');
+ expect(body).not.toContain('OUTSIDE THE ROOT');
+ });
+
+ test('sync.repo_path fallback still works when the source row has no local_path', async () => {
+ const engine = stubEngine({ sourceLocalPath: null, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(engine, pageWith('transcripts/meeting.txt'));
+ expect(body).toBe('GLOBAL transcript body');
+ });
+
+ test('sync.repo_path fallback also works when the source row is missing entirely', async () => {
+ const engine = stubEngine({ sourceExists: false, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(engine, pageWith('transcripts/meeting.txt'));
+ expect(body).toBe('GLOBAL transcript body');
+ });
+
+ test('escaping relative path under the repo_path fallback is rejected too', async () => {
+ const engine = stubEngine({ sourceLocalPath: null, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith('../outside/secret.txt'),
+ );
+ expect(body).toBe('SUMMARY body');
+ });
+
+ test('absolute path inside the owning source root is read', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: null });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith(join(sourceRepo, 'transcripts', 'meeting.txt')),
+ );
+ expect(body).toBe('SOURCE transcript body');
+ });
+
+ test('absolute path inside sync.repo_path is read (source root set but not containing it)', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith(join(globalRepo, 'transcripts', 'meeting.txt')),
+ );
+ expect(body).toBe('GLOBAL transcript body');
+ });
+
+ test('#3911 follow-up: absolute path OUTSIDE every registered root is rejected — summary body wins', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: globalRepo });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith(join(outsideDir, 'secret.txt')),
+ );
+ expect(body).toBe('SUMMARY body');
+ expect(body).not.toContain('OUTSIDE THE ROOT');
+ });
+
+ test('absolute path with NO registered roots is rejected (fail-closed, same as relative)', async () => {
+ const engine = stubEngine({ sourceLocalPath: null, repoPath: null });
+ const body = await readConversationBodyForParsing(
+ engine,
+ pageWith(join(sourceRepo, 'transcripts', 'meeting.txt')),
+ );
+ expect(body).toBe('SUMMARY body');
+ });
+
+ test('missing transcript file falls back to summary body', async () => {
+ const engine = stubEngine({ sourceLocalPath: sourceRepo, repoPath: null });
+ const body = await readConversationBodyForParsing(engine, pageWith('transcripts/nope.txt'));
+ expect(body).toBe('SUMMARY body');
+ });
+});
diff --git a/test/core/retry.test.ts b/test/core/retry.test.ts
index 77746da9da..c1639e7696 100644
--- a/test/core/retry.test.ts
+++ b/test/core/retry.test.ts
@@ -344,7 +344,11 @@ describe('BATCH_AUDIT_SITES typed enum + isBatchAuditSite guard (D10c codex)', (
'extract.links_fs', 'extract.timeline_fs',
'extract.links_db', 'extract.timeline_db',
'extract.by_mention',
+ // #3674: --rebuild reconciling delete-then-insert of the mention scan's rows.
+ 'extract.by_mention.rebuild',
'extract.stale',
+ // #3961: atom-provenance edges banked after the completion-receipt flip.
+ 'cycle.extract_atoms.provenance',
'mcp.put_page.autolink',
'sync.import_file',
'reindex.markdown', 'reindex.multimodal',
diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.ts
index 4a7f7625aa..6b4fc34662 100644
--- a/test/cross-modal-phase1.test.ts
+++ b/test/cross-modal-phase1.test.ts
@@ -136,7 +136,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {
return resolveSearchMode({ mode: 'balanced' });
}
- test('KNOBS_HASH_VERSION is 21 (cross-modal still appended; 17→18 autocut weak-top floor #1863; 18→19 autocut minKeep floor #3621; 19→20 pre-fusion pool floor #3002; 20→21 recency fallback re-key #895)', () => {
+ 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)', () => {
// 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.
@@ -156,7 +156,12 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {
// 19→20 (#3002): pre-fusion pool floor (innerLimit widens the candidate
// pool for the same knobs). 20→21 (#895): recency DEFAULT_FALLBACK
// 0.5→0.3 reorders cached rows. Version-only invalidation, same release.
- expect(KNOBS_HASH_VERSION).toBe(21);
+ // 21→22 (mw2): result-stamp/injection epoch — #1663 exact-lookup
+ // injection, #3995 relational page-1 slot, #3783 keyword_hit, #4220
+ // 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);
});
test('flipping unified_multimodal changes the hash', () => {
diff --git a/test/cycle-conversation-facts-backfill.test.ts b/test/cycle-conversation-facts-backfill.test.ts
new file mode 100644
index 0000000000..76dc213400
--- /dev/null
+++ b/test/cycle-conversation-facts-backfill.test.ts
@@ -0,0 +1,220 @@
+/**
+ * #3627 — conversation_facts_backfill per-source caps must be ENFORCED.
+ *
+ * Pre-fix, cfg.maxCostUsd / cfg.maxWalltimeMin were parsed and never read
+ * again: the phase created ONE brain-wide tracker, the sole walltime check
+ * sat at the source-loop top (fires at most once with a single source), and
+ * the core ignores opts.maxCostUsd when a budgetTracker is passed. One
+ * runaway source could eat the whole brain-wide budget/walltime while every
+ * later source starved.
+ *
+ * Post-fix, each source runs under its own BudgetTracker capped at
+ * min(max_cost_usd, brain-wide remainder) with maxRuntimeMs, plus an
+ * AbortController deadline threaded as the core's signal. Per-source
+ * exhaustion records and CONTINUES; only the brain-wide caps break.
+ *
+ * Hermetic: PGLite + __setChatTransportForTests (slow / token-heavy stubs).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ __setChatTransportForTests,
+ __setEmbedTransportForTests,
+ resetGateway,
+ configureGateway,
+ type ChatResult,
+} from '../src/core/ai/gateway.ts';
+import { runPhaseConversationFactsBackfill } from '../src/core/cycle/conversation-facts-backfill.ts';
+
+let engine: PGLiteEngine;
+
+/** Per-test transport knobs. */
+let chatDelayMs = 0;
+let chatOutputTokens = 50;
+let chatCalls = 0;
+let chatCallsBySource: string[] = [];
+
+const CONVO_BODY = [
+ '**Alice Example** (2024-03-15 9:00 AM): I just signed the offer letter for Acme Corp.',
+ '**Bob Demo** (2024-03-15 9:01 AM): Congrats! What is the title?',
+ '**Alice Example** (2024-03-15 9:02 AM): Staff engineer on the platform team.',
+].join('\n');
+
+async function seedSource(id: string): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`,
+ [id, id],
+ );
+ await engine.putPage(`conversations/${id}-chat`, {
+ type: 'conversation',
+ title: `Chat in ${id}`,
+ compiled_truth: CONVO_BODY,
+ timeline: '',
+ frontmatter: {},
+ }, { sourceId: id });
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ resetGateway();
+ configureGateway({
+ chat_model: 'anthropic:claude-sonnet-4-6',
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' },
+ });
+
+ __setChatTransportForTests(async (opts): Promise<ChatResult> => {
+ chatCalls++;
+ chatCallsBySource.push(String(opts.messages[0]?.content ?? '').slice(0, 40));
+ if (chatDelayMs > 0) await new Promise((r) => setTimeout(r, chatDelayMs));
+ if (opts.abortSignal?.aborted) {
+ const err = new Error('The operation was aborted.');
+ err.name = 'AbortError';
+ throw err;
+ }
+ return {
+ text: JSON.stringify({
+ facts: [{
+ fact: 'alice example joined acme corp',
+ kind: 'event',
+ entity: null,
+ confidence: 1.0,
+ notability: 'high',
+ }],
+ }),
+ blocks: [],
+ stopReason: 'end',
+ usage: {
+ input_tokens: 100,
+ output_tokens: chatOutputTokens,
+ cache_read_tokens: 0,
+ cache_creation_tokens: 0,
+ },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ };
+ });
+ __setEmbedTransportForTests(
+ (async () => ({ embeddings: [Array.from({ length: 1536 }, () => 0.1)] })) as never,
+ );
+
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+});
+
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ // Shard hygiene: restore the legacy 1536-d pin for later files.
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ chatDelayMs = 0;
+ chatOutputTokens = 50;
+ chatCalls = 0;
+ chatCallsBySource = [];
+ await engine.executeRaw(`DELETE FROM facts`);
+ await engine.executeRaw(`DELETE FROM op_checkpoints WHERE op = 'extract-conversation-facts'`);
+ await engine.executeRaw(`DELETE FROM extract_rollup_7d`);
+ // Sources persist across tests (listSources sees them all); drop their
+ // conversation pages so earlier tests' sources iterate as cheap no-ops.
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'conversations/%'`);
+ // Reset caps to generous defaults; tests tighten what they exercise.
+ await engine.setConfig('cycle.conversation_facts_backfill.max_cost_usd', '1');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_total_cost_usd', '5');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_walltime_min', '20');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_total_walltime_min', '30');
+});
+
+describe('runPhaseConversationFactsBackfill per-source caps (#3627)', () => {
+ test('happy path: two sources both extract under generous caps', async () => {
+ await seedSource('src-a');
+ await seedSource('src-b');
+ const r = await runPhaseConversationFactsBackfill(engine, {});
+ expect(r.status).toBe('ok');
+ const d = r.details as Record<string, unknown>;
+ expect(d.sources_budget_exhausted).toBe(0);
+ expect(d.sources_walltime_exhausted).toBe(0);
+ const perSource = d.per_source as Record<string, { facts_inserted: number }>;
+ expect(perSource['src-a']?.facts_inserted).toBeGreaterThan(0);
+ expect(perSource['src-b']?.facts_inserted).toBeGreaterThan(0);
+ }, 120000);
+
+ test('per-source cost cap: an expensive source is capped but the NEXT source still runs', async () => {
+ await seedSource('src-cost-a');
+ await seedSource('src-cost-b');
+ // Token-heavy responses: sonnet output pricing makes >1 call exceed a
+ // micro cap, so source A exhausts its own budget mid-run.
+ chatOutputTokens = 200_000;
+ await engine.setConfig('cycle.conversation_facts_backfill.max_cost_usd', '0.5');
+ // Brain-wide cap is far larger — a per-source overrun must NOT starve B.
+ await engine.setConfig('cycle.conversation_facts_backfill.max_total_cost_usd', '50');
+
+ const r = await runPhaseConversationFactsBackfill(engine, {});
+ const d = r.details as Record<string, unknown>;
+ const perSource = d.per_source as Record<string, { budget_exhausted?: boolean }>;
+ // Both sources were ATTEMPTED (pre-fix the brain-wide tracker exhausted
+ // once and the loop broke, starving every later source). listSources also
+ // returns sources seeded by earlier tests — containment, not equality.
+ expect(Object.keys(perSource)).toContain('src-cost-a');
+ expect(Object.keys(perSource)).toContain('src-cost-b');
+ expect(d.sources_budget_exhausted as number).toBeGreaterThan(0);
+ // Spend is summed across per-source trackers.
+ expect(d.spent_usd as number).toBeGreaterThan(0);
+ }, 120000);
+
+ test('per-source walltime: a slow source aborts but the NEXT source still runs', async () => {
+ await seedSource('src-slow-a');
+ await seedSource('src-slow-b');
+ // ~0.0005 min = 30ms per-source deadline; each chat call takes 500ms.
+ chatDelayMs = 500;
+ await engine.setConfig('cycle.conversation_facts_backfill.max_walltime_min', '0.0005');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_total_walltime_min', '30');
+
+ const r = await runPhaseConversationFactsBackfill(engine, {});
+ const d = r.details as Record<string, unknown>;
+ const perSource = d.per_source as Record<string, { walltime_exhausted?: boolean; budget_exhausted?: boolean; error?: string }>;
+ // Pre-fix maxWalltimeMin was never enforced: no per-source record ever
+ // carried an exhaustion marker and the run just took as long as it took.
+ const exhausted = (d.sources_walltime_exhausted as number) + (d.sources_budget_exhausted as number);
+ expect(exhausted).toBeGreaterThan(0);
+ // Both sources were attempted — a slow source can't starve its siblings.
+ expect(Object.keys(perSource)).toContain('src-slow-a');
+ expect(Object.keys(perSource)).toContain('src-slow-b');
+ }, 120000);
+
+ test('brain-wide walltime still skips remaining sources', async () => {
+ await seedSource('src-brain-a');
+ await seedSource('src-brain-b');
+ chatDelayMs = 300;
+ // Brain-wide cap tighter than one source's work: later sources skip.
+ await engine.setConfig('cycle.conversation_facts_backfill.max_walltime_min', '20');
+ await engine.setConfig('cycle.conversation_facts_backfill.max_total_walltime_min', '0.000001');
+
+ const r = await runPhaseConversationFactsBackfill(engine, {});
+ const d = r.details as Record<string, unknown>;
+ expect(d.skipped_by_brain_wide_walltime as number).toBeGreaterThan(0);
+ }, 120000);
+
+ test('disabled gate is untouched: skipped without once', async () => {
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'false');
+ try {
+ const r = await runPhaseConversationFactsBackfill(engine, {});
+ expect(r.status).toBe('skipped');
+ } finally {
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+ }
+ }, 120000);
+});
diff --git a/test/cycle-dream-output-root.test.ts b/test/cycle-dream-output-root.test.ts
index 6ceb208707..f7da804b44 100644
--- a/test/cycle-dream-output-root.test.ts
+++ b/test/cycle-dream-output-root.test.ts
@@ -17,7 +17,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { __testing, loadAllowedSlugPrefixes, loadOutputRoot } from '../src/core/cycle/synthesize.ts';
+import { __testing, loadAllowedSlugPrefixes, loadOutputRoot, loadDreamNamespaces } from '../src/core/cycle/synthesize.ts';
import { bundledDreamGlobs, __filingRulesTesting } from '../src/core/cycle/filing-rules.ts';
import { runPhasePatterns } from '../src/core/cycle/patterns.ts';
import type { DiscoveredTranscript } from '../src/core/cycle/transcript-discovery.ts';
@@ -334,3 +334,93 @@ describe('#4216: buildSynthesisPrompt manifest + allow-list blocks', () => {
expect(prompt).toContain('shown in the put_page schema');
});
});
+
+// ── #4117: per-lane dream namespaces ────────────────────────────────────
+
+describe('#4117: dream.synthesize.{reflections,originals}_slug_prefix', () => {
+ let nsEngine: PGLiteEngine;
+
+ beforeAll(async () => {
+ nsEngine = new PGLiteEngine();
+ await nsEngine.connect({});
+ await nsEngine.initSchema();
+ }, 120_000);
+
+ afterAll(async () => {
+ if (nsEngine) await nsEngine.disconnect();
+ }, 60_000);
+
+ test('defaults derive from output_root', async () => {
+ const ns = await loadDreamNamespaces(nsEngine, 'wiki');
+ expect(ns.reflectionsPrefix).toBe('wiki/personal/reflections');
+ expect(ns.originalsPrefix).toBe('wiki/originals/ideas');
+ const custom = await loadDreamNamespaces(nsEngine, 'notes');
+ expect(custom.reflectionsPrefix).toBe('notes/personal/reflections');
+ expect(custom.originalsPrefix).toBe('notes/originals/ideas');
+ });
+
+ test('config keys override each lane individually (SUMMARY_SLUG_RE-validated)', async () => {
+ await nsEngine.setConfig('dream.synthesize.reflections_slug_prefix', 'journal/daily');
+ try {
+ const ns = await loadDreamNamespaces(nsEngine, 'wiki');
+ expect(ns.reflectionsPrefix).toBe('journal/daily');
+ // Originals lane untouched — falls back to the root-derived default.
+ expect(ns.originalsPrefix).toBe('wiki/originals/ideas');
+ } finally {
+ await nsEngine.unsetConfig('dream.synthesize.reflections_slug_prefix');
+ }
+ });
+
+ test('an invalid prefix warns and falls back (never leaks into prompt/allow-list)', async () => {
+ await nsEngine.setConfig('dream.synthesize.originals_slug_prefix', 'NOT a/valid slug!!');
+ try {
+ const ns = await loadDreamNamespaces(nsEngine, 'wiki');
+ expect(ns.originalsPrefix).toBe('wiki/originals/ideas');
+ } finally {
+ await nsEngine.unsetConfig('dream.synthesize.originals_slug_prefix');
+ }
+ });
+
+ test('buildSynthesisPrompt uses the per-lane prefixes for the slug templates', () => {
+ const prompt = buildSynthesisPrompt(
+ transcript, 'chunk', 0, 1, '', 'wiki', '', '', [],
+ 'journal/daily', 'sparks/ideas',
+ );
+ expect(prompt).toContain('journal/daily/2026-07-17-');
+ expect(prompt).toContain('sparks/ideas/2026-07-17-');
+ expect(prompt).not.toContain('wiki/personal/reflections/');
+ expect(prompt).not.toContain('wiki/originals/ideas/');
+ });
+
+ test('loadAllowedSlugPrefixes derives globs for custom namespaces', async () => {
+ const globs = await loadAllowedSlugPrefixes('wiki', undefined, {
+ reflectionsPrefix: 'journal/daily',
+ originalsPrefix: 'sparks/ideas',
+ });
+ expect(globs).toContain('journal/daily/*');
+ expect(globs).toContain('sparks/ideas/*');
+ // Base globs survive (the filing-rules file stays authoritative).
+ expect(globs).toContain('wiki/personal/reflections/*');
+ });
+
+ test('an empty base allow-list stays empty (fail-closed: NO_ALLOWLIST survives)', () => {
+ const out = __filingRulesTesting.appendNamespaceGlobs([], {
+ reflectionsPrefix: 'journal/daily',
+ originalsPrefix: 'sparks/ideas',
+ });
+ expect(out).toEqual([]);
+ });
+
+ test('default prefixes add no duplicate globs', async () => {
+ const base = await loadAllowedSlugPrefixes('wiki');
+ const withDefaults = await loadAllowedSlugPrefixes('wiki', undefined, {
+ reflectionsPrefix: 'wiki/personal/reflections',
+ originalsPrefix: 'wiki/originals/ideas',
+ });
+ // reflections glob already covered verbatim; originals/ideas nests under
+ // the broader wiki/originals/* base glob but a redundant precise glob is
+ // harmless — assert no DUPLICATES rather than exact equality.
+ expect(new Set(withDefaults).size).toBe(withDefaults.length);
+ for (const g of base) expect(withDefaults).toContain(g);
+ });
+});
diff --git a/test/cycle-stale-drain.test.ts b/test/cycle-stale-drain.test.ts
new file mode 100644
index 0000000000..f2396f71ee
--- /dev/null
+++ b/test/cycle-stale-drain.test.ts
@@ -0,0 +1,108 @@
+/**
+ * #4062 — the cycle's extract phase drains the stale-extraction backlog.
+ *
+ * Pre-fix, runPhaseExtract only ran runExtractCore over the slugs sync
+ * reported (or an fs walk of brainDir). Pages left stale for any other
+ * reason — an extractor version bump, DB-only writes, a prior aborted
+ * sweep — never re-extracted on the cycle, so the links_extracted_at
+ * backlog grew unboundedly until someone hand-ran `gbrain extract --stale`.
+ * This pins that the extract phase follows the targeted pass with a
+ * bounded, source-scoped extractStaleFromDB drain and reports
+ * staleRemaining in the phase details.
+ *
+ * GBRAIN_HOME is isolated per test because the PGLite cycle path takes a
+ * file lock at ~/.gbrain/cycle.lock (see cycle-extract-source.test.ts).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runCycle } from '../src/core/cycle.ts';
+
+let engine: PGLiteEngine;
+let brainDir: string;
+let gbrainHome: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 30_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+}, 30_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ // Empty checkout: the targeted fs-walk pass finds nothing, so any links
+ // created can only come from the stale DB drain.
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-cycle-stale-drain-'));
+ gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-cycle-stale-drain-home-'));
+
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path) VALUES ('wiki', 'wiki', $1)
+ ON CONFLICT (id) DO UPDATE SET local_path = EXCLUDED.local_path`,
+ [brainDir],
+ );
+ // DB-only pages (never present in the checkout) with links_extracted_at
+ // NULL → stale. alice's body links to bob.
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES
+ ('people/alice', 'wiki', 'person', 'Alice', 'Met [[people/bob]] today.', ''),
+ ('people/bob', 'wiki', 'person', 'Bob', 'Quiet page.', '')`,
+ );
+});
+
+afterEach(() => {
+ rmSync(brainDir, { recursive: true, force: true });
+ rmSync(gbrainHome, { recursive: true, force: true });
+});
+
+describe('cycle extract phase stale drain (#4062)', () => {
+ test('drains stale DB-only pages after the targeted pass and reports staleRemaining', async () => {
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ const report = await runCycle(engine, {
+ brainDir,
+ sourceId: 'wiki',
+ phases: ['extract'],
+ });
+ const extractPhase = report.phases.find(p => p.phase === 'extract');
+ expect(extractPhase?.status).toBe('ok');
+ // Both stale pages processed by the drain; none left stale.
+ expect(Number(extractPhase?.details?.stale_pages_drained ?? -1)).toBe(2);
+ expect(Number(extractPhase?.details?.staleRemaining ?? -1)).toBe(0);
+ expect(Number(extractPhase?.details?.stale_links_created ?? 0)).toBeGreaterThanOrEqual(1);
+ });
+
+ // The stale drain persisted alice → bob.
+ const links = await engine.executeRaw<{ from_slug: string; to_slug: string }>(
+ `SELECT pf.slug AS from_slug, pt.slug AS to_slug
+ FROM links l
+ JOIN pages pf ON pf.id = l.from_page_id
+ JOIN pages pt ON pt.id = l.to_page_id`,
+ );
+ expect(links.some(l => l.from_slug === 'people/alice' && l.to_slug === 'people/bob')).toBe(true);
+
+ // Stamped fresh: a second cycle's drain is a no-op.
+ const stale = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM pages WHERE links_extracted_at IS NULL AND deleted_at IS NULL`,
+ );
+ expect(Number(stale[0]?.n ?? -1)).toBe(0);
+ });
+
+ test('second cycle is a no-op drain (nothing stale, staleRemaining 0)', async () => {
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ const report = await runCycle(engine, { brainDir, sourceId: 'wiki', phases: ['extract'] });
+ const extractPhase = report.phases.find(p => p.phase === 'extract');
+ expect(extractPhase?.status).toBe('ok');
+ expect(Number(extractPhase?.details?.stale_pages_drained ?? -1)).toBe(0);
+ expect(Number(extractPhase?.details?.staleRemaining ?? -1)).toBe(0);
+ });
+ });
+});
diff --git a/test/db-lock-cross-host-wait.test.ts b/test/db-lock-cross-host-wait.test.ts
new file mode 100644
index 0000000000..c1602d1f29
--- /dev/null
+++ b/test/db-lock-cross-host-wait.test.ts
@@ -0,0 +1,155 @@
+/**
+ * #2308 — bounded wait for a dead CROSS-HOST lock holder.
+ *
+ * A holder that died on another host leaves a row whose TTL is still live;
+ * tryAcquireDbLock correctly refuses to steal it (cross_host classification,
+ * process.kill is meaningless remotely) — so one-shot callers exited
+ * LOCK_HELD even though the lock frees itself within TTL + steal-grace.
+ * waitForDbLockTakeover polls the normal acquire up to that bound, bailing
+ * fast when the holder's heartbeat advances (genuinely alive).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ tryAcquireDbLock,
+ waitForDbLockTakeover,
+} from '../src/core/db-lock.ts';
+import { resolveSupervisorLockWaitSeconds } from '../src/core/minions/supervisor.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let eng: PGLiteEngine;
+
+beforeAll(async () => {
+ eng = new PGLiteEngine();
+ await eng.connect({});
+ await eng.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await eng.disconnect();
+});
+
+beforeEach(async () => {
+ await eng.executeRaw('DELETE FROM gbrain_cycle_locks', []);
+});
+
+const LOCK_ID = 'cross-host-wait-test';
+
+/** Seed a cross-host holder row. ttlMs/refreshAgoMs are relative to NOW(). */
+async function seedHolder(opts: { ttlMs: number; refreshAgoMs: number; pid?: number }) {
+ await eng.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
+ VALUES ($1, $2, 'other-host-zzz', NOW() - INTERVAL '10 minutes',
+ NOW() + ($3 || ' milliseconds')::interval,
+ NOW() - ($4 || ' milliseconds')::interval)`,
+ [LOCK_ID, opts.pid ?? 99999, String(opts.ttlMs), String(opts.refreshAgoMs)],
+ );
+}
+
+describe('waitForDbLockTakeover (#2308)', () => {
+ test('precondition: dead cross-host holder with live TTL blocks the one-shot acquire', async () => {
+ await seedHolder({ ttlMs: 60_000, refreshAgoMs: 10 * 60_000 });
+ expect(await tryAcquireDbLock(eng, LOCK_ID, 1)).toBeNull();
+ });
+
+ test('dead holder: acquired once the TTL lapses (within the bound)', async () => {
+ // TTL lapses in ~1.2s; last refresh is 10min ago (past the 60s grace for
+ // a 1-min TTL) — the normal upsert takes over on the first post-lapse poll.
+ await seedHolder({ ttlMs: 1_200, refreshAgoMs: 10 * 60_000 });
+ const handle = await waitForDbLockTakeover(eng, LOCK_ID, 1, {
+ pollMs: 200,
+ maxWaitMs: 15_000,
+ });
+ expect(handle).not.toBeNull();
+ // the row now names US
+ const rows = await eng.executeRaw<{ holder_pid: number }>(
+ 'SELECT holder_pid FROM gbrain_cycle_locks WHERE id = $1',
+ [LOCK_ID],
+ );
+ expect(Number(rows[0].holder_pid)).toBe(process.pid);
+ await handle!.release();
+ }, 30_000);
+
+ test('refreshing holder: heartbeat advance bails to null fast', async () => {
+ await seedHolder({ ttlMs: 5 * 60_000, refreshAgoMs: 0 });
+ const started = Date.now();
+ let bumped = false;
+ const handle = await waitForDbLockTakeover(eng, LOCK_ID, 1, {
+ pollMs: 100,
+ maxWaitMs: 30_000,
+ sleep: async (ms) => {
+ // Simulate the remote holder's heartbeat firing between our polls.
+ if (!bumped) {
+ bumped = true;
+ await eng.executeRaw(
+ `UPDATE gbrain_cycle_locks SET last_refreshed_at = NOW() + INTERVAL '1 second' WHERE id = $1`,
+ [LOCK_ID],
+ );
+ }
+ await new Promise((r) => setTimeout(r, ms));
+ },
+ });
+ expect(handle).toBeNull();
+ // bailed on the heartbeat, nowhere near the 30s bound
+ expect(Date.now() - started).toBeLessThan(10_000);
+ }, 30_000);
+
+ test('bound honored: unreapable holder returns null at maxWaitMs', async () => {
+ await seedHolder({ ttlMs: 10 * 60_000, refreshAgoMs: 0 });
+ const started = Date.now();
+ const handle = await waitForDbLockTakeover(eng, LOCK_ID, 1, {
+ pollMs: 150,
+ maxWaitMs: 900,
+ });
+ expect(handle).toBeNull();
+ const elapsed = Date.now() - started;
+ expect(elapsed).toBeGreaterThanOrEqual(850);
+ expect(elapsed).toBeLessThan(10_000);
+ }, 30_000);
+
+ test('holder replaced by a different (pid,host) while waiting → null (they are alive)', async () => {
+ await seedHolder({ ttlMs: 5 * 60_000, refreshAgoMs: 0, pid: 11111 });
+ let swapped = false;
+ const handle = await waitForDbLockTakeover(eng, LOCK_ID, 1, {
+ pollMs: 100,
+ maxWaitMs: 30_000,
+ sleep: async (ms) => {
+ if (!swapped) {
+ swapped = true;
+ await eng.executeRaw(
+ `UPDATE gbrain_cycle_locks SET holder_pid = 22222 WHERE id = $1`,
+ [LOCK_ID],
+ );
+ }
+ await new Promise((r) => setTimeout(r, ms));
+ },
+ });
+ expect(handle).toBeNull();
+ }, 30_000);
+});
+
+describe('resolveSupervisorLockWaitSeconds — env hatch', () => {
+ const KEY = 'GBRAIN_SUPERVISOR_LOCK_WAIT_SECONDS';
+
+ test('unset → -1 (derived TTL+grace bound)', async () => {
+ await withEnv({ [KEY]: undefined }, () => {
+ expect(resolveSupervisorLockWaitSeconds()).toBe(-1);
+ });
+ });
+
+ test('0 disables the wait', async () => {
+ await withEnv({ [KEY]: '0' }, () => {
+ expect(resolveSupervisorLockWaitSeconds()).toBe(0);
+ });
+ });
+
+ test('positive integer is the hard bound; junk falls back to derived', async () => {
+ await withEnv({ [KEY]: '90' }, () => {
+ expect(resolveSupervisorLockWaitSeconds()).toBe(90);
+ });
+ await withEnv({ [KEY]: 'nonsense' }, () => {
+ expect(resolveSupervisorLockWaitSeconds()).toBe(-1);
+ });
+ });
+});
diff --git a/test/deep-research-fetch.test.ts b/test/deep-research-fetch.test.ts
new file mode 100644
index 0000000000..839d476fa5
--- /dev/null
+++ b/test/deep-research-fetch.test.ts
@@ -0,0 +1,102 @@
+/**
+ * test/deep-research-fetch.test.ts — #4039.
+ *
+ * ChatGPT's deep-research mode requires an MCP server to expose a
+ * `search`/`fetch` PAIR: search results carry an `id`, and `fetch(id)`
+ * returns OpenAI's `{ id, title, text, url, metadata }` shape. gbrain had
+ * `search` but no `fetch` (and results carried no `id`), so the connector
+ * worked in normal chat and failed in deep research. Pins:
+ * - the `fetch` op exists, is remote-allowed read scope, returns the shape
+ * - search results are stamped with id = slug so the pair round-trips
+ * - fetch honors source scoping and the remote privacy fences
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const fetch_op = operations.find(o => o.name === 'fetch')!;
+const search_op = operations.find(o => o.name === 'search')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: console as any,
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ ...overrides,
+ };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example', compiled_truth: 'Alice runs widget-co.', frontmatter: {},
+ }, { sourceId: 'default' });
+});
+
+describe('fetch op (#4039 deep-research contract)', () => {
+ test('exists as a remote-allowed read op with a required id param', () => {
+ expect(fetch_op, "the 'fetch' op must exist").toBeDefined();
+ expect(fetch_op.scope).toBe('read');
+ expect(fetch_op.localOnly).not.toBe(true);
+ expect(fetch_op.params.id?.required).toBe(true);
+ });
+
+ test('returns the OpenAI {id,title,text,url,metadata} shape for a slug id', async () => {
+ const res = (await fetch_op.handler(ctxOf(), { id: 'people/alice-example' })) as Record<string, unknown>;
+ expect(res.id).toBe('people/alice-example');
+ expect(res.title).toBe('Alice Example');
+ expect(String(res.text)).toContain('Alice runs widget-co.');
+ expect(String(res.url)).toBe('gbrain://page/default/people/alice-example');
+ const metadata = res.metadata as Record<string, unknown>;
+ expect(metadata.type).toBe('person');
+ expect(metadata.source_id).toBe('default');
+ });
+
+ test('unknown id → page_not_found; empty id → invalid_params', async () => {
+ await expect(fetch_op.handler(ctxOf(), { id: 'no/such-page' })).rejects.toThrow(OperationError);
+ await expect(fetch_op.handler(ctxOf(), { id: ' ' })).rejects.toThrow(OperationError);
+ });
+
+ test('source scoping: a caller granted another source cannot fetch this page', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('beta', 'beta', '/tmp/beta') ON CONFLICT (id) DO NOTHING`);
+ const scoped = ctxOf({ sourceId: undefined, auth: { allowedSources: ['beta'] } as any });
+ await expect(fetch_op.handler(scoped, { id: 'people/alice-example' })).rejects.toThrow(OperationError);
+ });
+
+ test('remote privacy fence: takes fence content never crosses fetch', async () => {
+ await engine.putPage('people/bob-example', {
+ type: 'person',
+ title: 'Bob Example',
+ compiled_truth: 'Bob intro.\n\n<!--- gbrain:takes:begin -->\n| SECRET-TAKE |\n<!--- gbrain:takes:end -->\n',
+ frontmatter: {},
+ }, { sourceId: 'default' });
+ const remoteRes = (await fetch_op.handler(ctxOf({ remote: true }), { id: 'people/bob-example' })) as Record<string, unknown>;
+ expect(String(remoteRes.text)).not.toContain('SECRET-TAKE');
+ });
+
+ test('search results carry id = slug so the pair round-trips', async () => {
+ const results = (await search_op.handler(ctxOf({ remote: false }), { query: 'Alice widget' })) as Array<Record<string, unknown>>;
+ expect(results.length).toBeGreaterThan(0);
+ for (const r of results) {
+ expect(r.id).toBe(r.slug);
+ }
+ // Round-trip: the stamped id feeds fetch directly.
+ const fetched = (await fetch_op.handler(ctxOf(), { id: results[0].id as string })) as Record<string, unknown>;
+ expect(fetched.id).toBe(results[0].slug);
+ });
+});
diff --git a/test/doctor-graph-coverage-inbound.test.ts b/test/doctor-graph-coverage-inbound.test.ts
new file mode 100644
index 0000000000..b3f03fd7d8
--- /dev/null
+++ b/test/doctor-graph-coverage-inbound.test.ts
@@ -0,0 +1,89 @@
+/**
+ * test/doctor-graph-coverage-inbound.test.ts — #4191.
+ *
+ * doctor's graph_coverage used to count an entity as covered only when it
+ * had an OUTBOUND link (from_page_id), while onboard's entity_link_coverage
+ * counts INBOUND links (to_page_id EXISTS, target 70%). A brain of
+ * inbound-only entities — the normal shape: meeting/note pages link TO
+ * people and companies — read healthy in onboard and warned in doctor on
+ * the same data. graph_coverage now counts CONNECTED entities (inbound OR
+ * outbound) with the same 70% target, so the two checks can't contradict
+ * each other on inbound-only brains.
+ */
+
+import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { buildChecks } from '../src/commands/doctor.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);
+});
+
+/**
+ * Two entity pages that are LINKED TO (inbound only) from note pages, each
+ * with a timeline entry so the timeline half of the check stays green and
+ * the assertion isolates the link-direction predicate.
+ */
+async function seedInboundOnlyEntities(eng: PGLiteEngine): Promise<void> {
+ const sql = sqlQueryForEngine(eng);
+ await sql`
+ INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
+ VALUES
+ ('alice-example', 'default', 'person', 'Alice', '', '{}', 'in1', now(), now()),
+ ('acme-example', 'default', 'company', 'Acme', '', '{}', 'in2', now(), now()),
+ ('meetings/2026-04-03', 'default', 'note', 'Standup', '', '{}', 'in3', now(), now())
+ `;
+ // Inbound-only: the note links TO both entities; the entities link to nothing.
+ await sql`
+ INSERT INTO links (from_page_id, to_page_id, link_type)
+ SELECT n.id, e.id, 'mentions'
+ FROM pages n, pages e
+ WHERE n.slug = 'meetings/2026-04-03' AND e.slug IN ('alice-example', 'acme-example')
+ `;
+ await sql`
+ INSERT INTO timeline_entries (page_id, date, summary)
+ SELECT id, '2026-04-03', 'met at standup' FROM pages WHERE slug IN ('alice-example', 'acme-example')
+ `;
+}
+
+describe('graph_coverage counts inbound-connected entities (#4191)', () => {
+ test('inbound-only entities are covered — ok, no contradictory warn', async () => {
+ await seedInboundOnlyEntities(engine);
+ const checks = await buildChecks(engine, [], null);
+ const graph = checks.find((c) => c.name === 'graph_coverage');
+ expect(graph, 'graph_coverage check must be present').toBeDefined();
+ // Both entities have inbound links → 100% connected coverage, ok.
+ expect(graph!.status).toBe('ok');
+ expect(graph!.message).toContain('connected coverage (in/out)');
+ expect(graph!.message).toContain('100%');
+ });
+
+ test('unlinked entities still warn, with the 70% target named', async () => {
+ const sql = sqlQueryForEngine(engine);
+ await sql`
+ INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
+ VALUES
+ ('bob-example', 'default', 'person', 'Bob', '', '{}', 'un1', now(), now()),
+ ('widget-co', 'default', 'company', 'Widget Co', '', '{}', 'un2', now(), now())
+ `;
+ const checks = await buildChecks(engine, [], null);
+ const graph = checks.find((c) => c.name === 'graph_coverage');
+ expect(graph!.status).toBe('warn');
+ expect(graph!.message).toContain('connected coverage (in/out) 0%');
+ expect(graph!.message).toContain('target 70%');
+ });
+});
diff --git a/test/doctor-schema-pack-db-config.test.ts b/test/doctor-schema-pack-db-config.test.ts
new file mode 100644
index 0000000000..5007565722
--- /dev/null
+++ b/test/doctor-schema-pack-db-config.test.ts
@@ -0,0 +1,78 @@
+/**
+ * #3792 — doctor's schema_pack_active check (and the get_active_schema_pack
+ * op) must resolve the active pack with the FULL 7-tier input, including the
+ * DB-plane `schema_pack` config (tier 4). Pre-fix they resolved from
+ * file/env only, so a brain whose active pack was flipped via
+ * `gbrain config set schema_pack` (or the unify-types migration) had doctor
+ * reporting one pack while every query ran another.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { checkSchemaPackActive } from '../src/commands/doctor/schema-pack-checks.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let tmpHome: string;
+
+beforeEach(() => {
+ _resetPackCacheForTests();
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-3792-'));
+});
+
+afterEach(() => {
+ _resetPackCacheForTests();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+function engineWithDbPack(pack: string | null): BrainEngine {
+ return {
+ getConfig: async (key: string) => (key === 'schema_pack' ? pack : null),
+ } as unknown as BrainEngine;
+}
+
+describe('#3792 doctor schema_pack_active resolves with DB-plane config', () => {
+ test('db-plane schema_pack (tier 4) wins over the default when home config is silent', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const check = await checkSchemaPackActive(engineWithDbPack('gbrain-base-v2'));
+ expect(check.status).toBe('ok');
+ // Pre-fix: dbConfig was never threaded → resolved 'gbrain-base'.
+ expect(check.message).toContain('gbrain-base-v2');
+ });
+ });
+
+ test('no db-plane value → default resolution stands (gbrain-base)', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const check = await checkSchemaPackActive(engineWithDbPack(null));
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('gbrain-base v');
+ });
+ });
+
+ test('engine without a config table degrades to file/env resolution (no throw)', async () => {
+ const engine = {
+ getConfig: async () => { throw new Error('relation "config" does not exist'); },
+ } as unknown as BrainEngine;
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const check = await checkSchemaPackActive(engine);
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('gbrain-base v');
+ });
+ });
+});
+
+describe('#3792 get_active_schema_pack op threads the same DB-plane config', () => {
+ test('identity packet reports the db-plane pack', async () => {
+ const { handleToolCall } = await import('../src/mcp/server.ts');
+ await withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ const result = (await handleToolCall(
+ engineWithDbPack('gbrain-base-v2'),
+ 'get_active_schema_pack',
+ {},
+ )) as { pack_name: string; source_tier: string };
+ expect(result.pack_name).toBe('gbrain-base-v2');
+ });
+ });
+});
diff --git a/test/doctor-self-upgrade.test.ts b/test/doctor-self-upgrade.test.ts
index 229f27a829..d4eb2749c5 100644
--- a/test/doctor-self-upgrade.test.ts
+++ b/test/doctor-self-upgrade.test.ts
@@ -3,7 +3,7 @@ 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 { checkSelfUpgradeHealth } from '../src/commands/doctor.ts';
+import { buildChecks, checkSelfUpgradeHealth } from '../src/commands/doctor.ts';
import { writeUpdateCache } from '../src/core/self-upgrade.ts';
import { logSelfUpgrade } from '../src/core/audit/self-upgrade-audit.ts';
import { VERSION } from '../src/version.ts';
@@ -79,3 +79,28 @@ describe('checkSelfUpgradeHealth', () => {
});
});
});
+
+describe('#3747: LOCAL doctor emits self_upgrade_health', () => {
+ // Pre-fix, only the remote report (doctor/report-remote.ts) pushed this
+ // check — `gbrain doctor` on the host machine, the surface an operator
+ // actually diagnoses upgrade problems from, never showed it.
+ test('buildChecks includes self_upgrade_health (engine-free, --fast)', async () => {
+ await withHome(async () => {
+ const checks = await buildChecks(null, ['--scope=brain', '--fast']);
+ const c = checks.find((ch) => ch.name === 'self_upgrade_health');
+ expect(c).toBeDefined();
+ expect(c!.status).toBe('ok');
+ });
+ });
+
+ test('buildChecks surfaces a recent failed auto-upgrade as warn', async () => {
+ await withHome(async () => {
+ logSelfUpgrade({ channel: 'autopilot', action: 'apply', current: '0.42.0', latest: '0.99.0', outcome: 'failed', error: 'boom' });
+ const checks = await buildChecks(null, ['--scope=brain', '--fast']);
+ const c = checks.find((ch) => ch.name === 'self_upgrade_health');
+ expect(c).toBeDefined();
+ expect(c!.status).toBe('warn');
+ expect(c!.message).toContain('self-upgrade failure');
+ });
+ });
+});
diff --git a/test/doctor-silent-death-checks.test.ts b/test/doctor-silent-death-checks.test.ts
index 1b932ff3e1..9de469ae80 100644
--- a/test/doctor-silent-death-checks.test.ts
+++ b/test/doctor-silent-death-checks.test.ts
@@ -55,11 +55,11 @@ async function addSource(id: string, localPath: string | null): Promise<void> {
async function addPage(
slug: string,
- opts: { sourceId?: string; hash?: string | null; pageKind?: string; deleted?: boolean; sourcePath?: string | null } = {},
+ opts: { sourceId?: string; hash?: string | null; pageKind?: string; type?: string; deleted?: boolean; sourcePath?: string | null } = {},
): Promise<void> {
await engine.executeRaw(
`INSERT INTO pages (slug, source_id, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, deleted_at, source_path)
- VALUES ($1, $2, 'concept', $3, $1, 'body', '', '{}'::jsonb, $4, $5, $6)`,
+ VALUES ($1, $2, $7, $3, $1, 'body', '', '{}'::jsonb, $4, $5, $6)`,
[
slug,
opts.sourceId ?? 'default',
@@ -67,6 +67,7 @@ async function addPage(
opts.hash === undefined ? `h-${slug}` : opts.hash,
opts.deleted ? new Date().toISOString() : null,
opts.sourcePath ?? null,
+ opts.type ?? 'concept',
],
);
}
@@ -101,11 +102,43 @@ describe('content_hash_duplicates (#2250)', () => {
expect(c.message).toContain('my-project <-> projects/my-project');
});
- test('two path-prefixed pages with same hash → ok (not the wrong-root pattern)', async () => {
+ test('#3946: two path-prefixed pages with same hash → warn, listed, NO delete hint', async () => {
+ // Pre-#3946 the shape FILTER predicates hid every all-nested duplicate
+ // group; now it surfaces, but WITHOUT the bare-slug delete hint (#3942 —
+ // either copy may be canonical).
await addPage('people/alice-example', { hash: 'same' });
await addPage('archive/people/alice-example', { hash: 'same' });
const c = await checkContentHashDuplicates(engine);
- expect(c.status).toBe('ok');
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('people/alice-example == archive/people/alice-example');
+ expect(c.message).not.toContain('gbrain pages delete');
+ expect((c.details as any).pair_count).toBe(0);
+ expect((c.details as any).distinct_slug_group_count).toBe(1);
+ });
+
+ test('#3946: two distinct bare slugs with same hash → warn without delete hint', async () => {
+ await addPage('alice-example', { hash: 'same' });
+ await addPage('alice-copy', { hash: 'same' });
+ const c = await checkContentHashDuplicates(engine);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('alice-copy == alice-example');
+ expect(c.message).not.toContain('gbrain pages delete');
+ expect((c.details as any).pair_count).toBe(0);
+ expect((c.details as any).distinct_slug_group_count).toBe(1);
+ });
+
+ test('#3946: mixed brain — wrong-root pair keeps the delete hint, nested group listed beside it', async () => {
+ await addPage('people/alice-example', { hash: 'h1' });
+ await addPage('alice-example', { hash: 'h1' });
+ await addPage('notes/dup-a', { hash: 'h2' });
+ await addPage('archive/dup-a', { hash: 'h2' });
+ const c = await checkContentHashDuplicates(engine);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('alice-example <-> people/alice-example');
+ expect(c.message).toContain('gbrain pages delete <bare-slug>');
+ expect(c.message).toContain('notes/dup-a == archive/dup-a');
+ expect((c.details as any).pair_count).toBe(1);
+ expect((c.details as any).distinct_slug_group_count).toBe(1);
});
test('soft-deleted twin is ignored', async () => {
@@ -230,6 +263,40 @@ describe('undeclared_db_only_pages (#2784)', () => {
expect(c.status).toBe('ok');
});
+ // #3766 — legacy code rows carry page_kind='markdown' (migration-25
+ // backfill never re-stamped type='code'), and the backed set only walked
+ // .mdx? files, so every such row false-positived as "DB-only".
+ test('#3766: legacy code row (page_kind=markdown, no type stamp) backed by a .tsx file → ok', async () => {
+ const repo = makeRepo();
+ mkdirSync(join(repo, 'components'), { recursive: true });
+ writeFileSync(join(repo, 'components', 'App.tsx'), 'export const App = () => null;\n');
+ await addSource('src-a', repo);
+ // slugifyCodePath('components/App.tsx') → 'components-app-tsx'; no
+ // source_path (the pre-v0.32.7 shape) so the walk-derived set decides.
+ await addPage('components-app-tsx', { sourceId: 'src-a' });
+ const c = await checkUndeclaredDbOnlyPages(engine);
+ expect(c.status).toBe('ok');
+ });
+
+ test("#3766: properly stamped type='code' row is skipped outright", async () => {
+ const repo = makeRepo();
+ await addSource('src-a', repo);
+ await addPage('src-core-thing-ts', { sourceId: 'src-a', type: 'code' });
+ const c = await checkUndeclaredDbOnlyPages(engine);
+ expect(c.status).toBe('ok');
+ });
+
+ test('#3766: a genuinely DB-only markdown page still warns (no overreach)', async () => {
+ const repo = makeRepo();
+ mkdirSync(join(repo, 'components'), { recursive: true });
+ writeFileSync(join(repo, 'components', 'App.tsx'), 'export const App = () => null;\n');
+ await addSource('src-a', repo);
+ 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');
+ });
+
test('source whose local_path is missing on this host is skipped', async () => {
await addSource('src-gone', '/nonexistent/gbrain-test-path');
await addPage('people/ghost-page', { sourceId: 'src-gone' });
diff --git a/test/doctor-stale-mentions.test.ts b/test/doctor-stale-mentions.test.ts
new file mode 100644
index 0000000000..0484c1b9fb
--- /dev/null
+++ b/test/doctor-stale-mentions.test.ts
@@ -0,0 +1,265 @@
+/**
+ * Tests for `scanStaleMentions` (src/core/by-mention.ts) and the doctor
+ * `stale_mentions` check that formats it — issue #3674.
+ *
+ * The gap being covered: `extract links --by-mention` writes through
+ * addLinksBatch, which is additive, and put_page reconciliation deliberately
+ * excludes 'mentions'. So a mentions row outlives its own justification, and
+ * re-running the scan adds correct links alongside the stale ones instead of
+ * replacing them. This check is the read-only half — it makes the drift
+ * visible; it must never delete anything.
+ *
+ * Hermetic via PGLite.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { scanStaleMentions } from '../src/core/by-mention.ts';
+import { runDoctor, type DoctorReport } from '../src/commands/doctor.ts';
+import { setCliOptions } from '../src/core/cli-options.ts';
+import { BRAIN_CHECK_NAMES, categorizeCheck } from '../src/core/doctor-categories.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ restoreCli();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM sources WHERE id != 'default'");
+});
+
+async function putEntity(slug: string, title: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'company', title, compiled_truth: `${title} is a company.`,
+ timeline: '', frontmatter: {},
+ });
+}
+
+async function putNote(slug: string, body: string): Promise<void> {
+ await engine.putPage(slug, {
+ type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter: {},
+ });
+}
+
+async function link(from: string, to: string, kind: string | null = 'plain'): Promise<void> {
+ await engine.addLinksBatch([{
+ from_slug: from, to_slug: to, link_type: 'mentions',
+ link_source: 'mentions', ...(kind === null ? {} : { link_kind: kind }),
+ }]);
+}
+
+async function countLinks(): Promise<number> {
+ const r = await engine.executeRaw<{ count: number }>(
+ `SELECT COUNT(*)::int AS count FROM links WHERE link_source = 'mentions'`, []);
+ return r[0]?.count ?? 0;
+}
+
+describe('scanStaleMentions', () => {
+ test('empty brain — nothing to report, no gazetteer build implied', async () => {
+ const res = await scanStaleMentions(engine);
+ expect(res.totalPagesWithMentions).toBe(0);
+ expect(res.staleLinks).toBe(0);
+ expect(res.pagesScanned).toBe(0);
+ });
+
+ test('a link the current gazetteer still produces is NOT stale', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+
+ const res = await scanStaleMentions(engine);
+ expect(res.totalPagesWithMentions).toBe(1);
+ expect(res.linksScanned).toBe(1);
+ expect(res.staleLinks).toBe(0);
+ expect(res.emptyGazetteer).toBe(false);
+ });
+
+ test('body rewritten so it no longer names the entity — link goes stale', async () => {
+ // This is the exact reproduction in the issue: put_page reconciliation
+ // excludes 'mentions', so rewriting the body leaves the row behind.
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+ await putNote('notes/meeting', 'Met with nobody today. Quiet day.');
+
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(1);
+ expect(res.staleByKind).toEqual({ plain: 1 });
+ expect(res.examples).toEqual([
+ { from: 'notes/meeting', to: 'companies/acme-example', kind: 'plain' },
+ ]);
+ });
+
+ test('entity page soft-deleted — link goes stale', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+ await engine.executeRaw(
+ `UPDATE pages SET deleted_at = now() WHERE slug = 'companies/acme-example'`, []);
+
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(1);
+ // Deleting the only entity empties the gazetteer — the caller needs to
+ // distinguish that from ordinary drift.
+ expect(res.emptyGazetteer).toBe(true);
+ });
+
+ test('typed_ner rows are counted, and reported separately from plain', async () => {
+ // extract-ner shares link_source='mentions' with link_kind='typed_ner',
+ // which is precisely why a cleanup cannot delete by link_source alone.
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example', 'plain');
+ await engine.addLinksBatch([{
+ from_slug: 'notes/meeting', to_slug: 'companies/acme-example',
+ link_type: 'works_at', link_source: 'mentions', link_kind: 'typed_ner',
+ }]);
+ await putNote('notes/meeting', 'Met with nobody today. Quiet day.');
+
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(2);
+ expect(res.staleByKind).toEqual({ plain: 1, typed_ner: 1 });
+ });
+
+ test('legacy NULL link_kind reports as plain, not as a missing bucket', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example', null);
+ await putNote('notes/meeting', 'Nothing here.');
+
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(1);
+ expect(res.staleByKind).toEqual({ plain: 1 });
+ });
+
+ test('is strictly read-only — a stale row is still there afterwards', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+ await putNote('notes/meeting', 'Nothing here.');
+
+ expect(await countLinks()).toBe(1);
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(1);
+ expect(await countLinks()).toBe(1); // the check must not repair
+ // Idempotent: a second run reports the same thing.
+ expect((await scanStaleMentions(engine)).staleLinks).toBe(1);
+ expect(await countLinks()).toBe(1);
+ });
+
+ test('limit bounds the scan and totalPagesWithMentions stays unbounded', async () => {
+ // Coverage must be disclosable — a bounded scan that reported the bounded
+ // total would read as full coverage.
+ await putEntity('companies/acme-example', 'Acme Example');
+ for (const n of ['a', 'b', 'c']) {
+ await putNote(`notes/${n}`, 'Nothing here.');
+ await link(`notes/${n}`, 'companies/acme-example');
+ }
+ const res = await scanStaleMentions(engine, { limit: 2 });
+ expect(res.totalPagesWithMentions).toBe(3);
+ expect(res.pagesScanned).toBe(2);
+ expect(res.linksScanned).toBe(2);
+ expect(res.staleLinks).toBe(2);
+ });
+
+ test('self-link and cross-source guards are honoured, as in the real scan', async () => {
+ // findMentionedEntities suppresses both, so neither can ever be produced
+ // — a stored row of either shape is stale by construction.
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Acme Example is great.');
+ await link('notes/meeting', 'companies/acme-example');
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`, []);
+ await engine.executeRaw(
+ `UPDATE pages SET source_id = 'other' WHERE slug = 'companies/acme-example'`, []);
+
+ const res = await scanStaleMentions(engine);
+ expect(res.staleLinks).toBe(1); // cross-source: no longer produced
+ });
+});
+
+// ============================================================
+// Doctor surface — the check is emitted, worded, and categorized
+// ============================================================
+
+let stdoutBuffer: string[] = [];
+const origLog = console.log;
+const origErr = console.error;
+const origExit = process.exit;
+
+function captureCli(): void {
+ stdoutBuffer = [];
+ console.log = (msg?: unknown) => { stdoutBuffer.push(typeof msg === 'string' ? msg : String(msg)); };
+ console.error = () => {};
+ (process as { exit: unknown }).exit = (() => { throw new Error('__exit'); }) as unknown as typeof process.exit;
+}
+
+function restoreCli(): void {
+ console.log = origLog;
+ console.error = origErr;
+ (process as { exit: unknown }).exit = origExit;
+}
+
+async function runDoctorJson(): Promise<DoctorReport> {
+ captureCli();
+ try {
+ // No --fast: stale_mentions sits in the DB-checks group that --fast skips.
+ await runDoctor(engine, ['--json']);
+ } catch (e) {
+ if (!(e instanceof Error && e.message === '__exit')) throw e;
+ } finally {
+ restoreCli();
+ }
+ for (let i = stdoutBuffer.length - 1; i >= 0; i--) {
+ try {
+ const parsed = JSON.parse(stdoutBuffer[i]!);
+ if (parsed && typeof parsed === 'object' && 'checks' in parsed) return parsed as DoctorReport;
+ } catch { /* skip non-JSON lines */ }
+ }
+ throw new Error('No DoctorReport JSON found in stdout');
+}
+
+describe('runDoctor — stale_mentions check', () => {
+ test('clean brain → ok, and the check is actually present', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+
+ const check = (await runDoctorJson()).checks.find(c => c.name === 'stale_mentions');
+ expect(check).toBeDefined();
+ expect(check!.status).toBe('ok');
+ });
+
+ test('drifted brain → warn, names the additive write path and the workaround', async () => {
+ await putEntity('companies/acme-example', 'Acme Example');
+ await putNote('notes/meeting', 'Met with Acme Example about the widget deal.');
+ await link('notes/meeting', 'companies/acme-example');
+ await putNote('notes/meeting', 'Met with nobody today. Quiet day.');
+
+ const check = (await runDoctorJson()).checks.find(c => c.name === 'stale_mentions');
+ expect(check!.status).toBe('warn');
+ // The operator has to learn two things from this message or it is useless:
+ // that re-running the scan will NOT fix it, and what to do instead.
+ expect(check!.message).toContain('will NOT remove them');
+ expect(check!.message).toContain('gbrain unlink');
+ expect(check!.message).toContain('notes/meeting -> companies/acme-example');
+ // Read-only: no repair is offered, because none exists yet (#3674).
+ expect(check!.remediation ?? []).toEqual([]);
+ });
+
+ test('is categorized — not silently degraded to meta', () => {
+ expect(BRAIN_CHECK_NAMES.has('stale_mentions')).toBe(true);
+ expect(categorizeCheck('stale_mentions')).toBe('brain');
+ });
+});
diff --git a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts b/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
index bbaa8b8436..699705164e 100644
--- a/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
+++ b/test/e2e/bootstrap-harness-lifecycle.serial.test.ts
@@ -34,6 +34,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
let parent: string; // GBRAIN_HOME parent for the brain
let sandboxHome: string; // HOME for user-scope writes
let codexHome: string;
+ let stubBin: string; // sandbox bin dir carrying a no-op `claude` (#4325)
let server: ChildProcess | null = null;
let token = '';
let serverReady = false;
@@ -75,6 +76,12 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
HOME: sandboxHome,
CLAUDE_CONFIG_DIR: join(sandboxHome, '.claude'),
CODEX_HOME: codexHome,
+ // #4325: detectClaude() probes PATH via Bun.which('claude'); CI runners
+ // don't ship the claude CLI, so the claude lane silently un-wires and the
+ // apply test's `claude add` assertions fail. Prepend a sandbox bin dir
+ // carrying an executable no-op `claude` stub — the recording runner seam
+ // intercepts every real exec, so the stub only ever satisfies detection.
+ PATH: `${stubBin}:${process.env.PATH ?? ''}`,
// The e2e lane exports DATABASE_URL; the IN-PROCESS runBootstrap calls
// (unlike the spawned children scrubbed in beforeAll) would otherwise
// resolve it via loadConfig's env>file precedence and mint tokens
@@ -91,6 +98,10 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
codexHome = mkdtempSync(join(tmpdir(), 'gb-harness-codex-'));
// codex "installed" for detection purposes: the config file exists.
writeFileSync(codexConfig(), '# preexisting codex config\nmodel = "o5"\n');
+ // #4325: claude "installed" for detection purposes — executable no-op
+ // stub on a sandbox PATH entry (see envFor). Never actually executed.
+ stubBin = mkdtempSync(join(tmpdir(), 'gb-harness-bin-'));
+ writeFileSync(join(stubBin, 'claude'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: parent };
delete env.DATABASE_URL;
@@ -129,7 +140,7 @@ describe('bootstrap harness lifecycle E2E (PGLite + real serve --http)', () => {
afterAll(() => {
if (server) { try { server.kill('SIGTERM'); } catch { /* best-effort */ } }
- for (const d of [parent, sandboxHome, codexHome]) {
+ for (const d of [parent, sandboxHome, codexHome, stubBin]) {
try { rmSync(d, { recursive: true, force: true }); } catch { /* best-effort */ }
}
});
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index 6e952c5db5..dcc0490c97 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -27,7 +27,11 @@ import { hybridSearch } from '../../src/core/search/hybrid.ts';
import { runSchemaTransition } from '../../src/core/retrieval-upgrade-planner.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { extractTakesFromPages } from '../../src/core/extract-takes-from-pages.ts';
-import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import {
+ configureGateway,
+ resetGateway,
+ __unconfigureGatewayForTests,
+} from '../../src/core/ai/gateway.ts';
import {
verifyWorkspace,
VERIFY_PROBE_SLUG,
@@ -231,7 +235,15 @@ describe.skipIf(!OPENAI && !ANTHROPIC)('keyed auto fact-extraction (LLM takes)',
test('keyless → llm_unavailable, zero claims; keyed → a real fact/take lands', async () => {
// Keyless contrast: no chat gateway ⇒ the sweep cannot extract anything.
- resetGateway();
+ // NOT resetGateway(): since #3554 that re-applies the preload's test
+ // baseline, whose factory captures env: { ...process.env } — including
+ // the very ANTHROPIC/OPENAI key this describe is gated on (run-e2e.sh
+ // keeps provider keys via GBRAIN_TEST_KEEP_PROVIDER_KEYS=1). The gateway
+ // would come back chat-available and llm_unavailable could never be true.
+ // __unconfigureGatewayForTests() is the #3554 seam for asserting genuine
+ // no-gateway behavior; the preload's beforeEach restores the baseline
+ // before the next test.
+ __unconfigureGatewayForTests();
const keyless = await extractTakesFromPages(engine, { bootstrapEnabled: true });
expect(keyless.llm_unavailable).toBe(true);
expect(keyless.claims_extracted).toBe(0);
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index 86db2cb20c..2121162f62 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -18,6 +18,7 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import type { ChunkInput, SearchResult } from '../../src/core/types.ts';
import type { BrainEngine } from '../../src/core/engine.ts';
import { getSessionContextState, upsertSessionContextState } from '../../src/core/context/session-state.ts';
+import { linkEntityIdentity, listEntityIdentities } from '../../src/core/entity-identity.ts';
import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';
const SKIP_PG = !hasDatabase();
@@ -150,6 +151,40 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
expect(pgResults[0]?.slug).toBe(pgliteResults[0]?.slug);
});
+ test('#4304 listAllPageRefs parity: updated_at is a real Date, same (source_id, slug) ordering', async () => {
+ const pg = await pgEngine.listAllPageRefs();
+ const pl = await pgliteEngine.listAllPageRefs();
+ for (const refs of [pg, pl]) {
+ expect(refs.length).toBeGreaterThan(0);
+ for (const r of refs) {
+ expect(r.updated_at instanceof Date).toBe(true);
+ expect(Number.isFinite(r.updated_at.getTime())).toBe(true);
+ }
+ }
+ // Both engines were seeded identically — the ref key list must match.
+ expect(pg.map((r) => `${r.source_id}::${r.slug}`)).toEqual(
+ pl.map((r) => `${r.source_id}::${r.slug}`),
+ );
+ });
+
+ test('#4224 entity identity helpers: one SQL text, identical behavior on both engines', async () => {
+ for (const eng of [pgEngine, pgliteEngine]) {
+ await linkEntityIdentity(eng, {
+ entityId: 'parity-founder', slug: 'people/example-founder', sourceId: 'default', canonical: true,
+ });
+ await linkEntityIdentity(eng, {
+ entityId: 'parity-founder', slug: 'concepts/fat-code-thin-harness', sourceId: 'default',
+ });
+ }
+ const pg = await listEntityIdentities(pgEngine, { entityId: 'parity-founder' });
+ const pl = await listEntityIdentities(pgliteEngine, { entityId: 'parity-founder' });
+ const key = (m: { source_id: string; slug: string; canonical: boolean; established_by: string }) =>
+ `${m.source_id}:${m.slug}:${m.canonical}:${m.established_by}`;
+ expect(pg.map(key)).toEqual(pl.map(key));
+ expect(pg).toHaveLength(2);
+ expect(pg.filter(m => m.canonical)).toHaveLength(1);
+ });
+
test('v0.46.15 searchVector escalation parity: a dense page cannot starve the page result on either engine', async () => {
// One page with 120 chunks nearest the query + 8 sparse pages behind it.
// Pre-fix, the 100-chunk inner pool was consumed entirely by the dense
@@ -594,6 +629,32 @@ describeBoth('Engine parity — Postgres vs PGLite', () => {
}
});
+ test('#3754 soft-deleted pages hidden from getLinks/getBacklinks/traversePaths on both engines', async () => {
+ for (const engine of [pgEngine, pgliteEngine]) {
+ await engine.putPage('notes/sdl-from', {
+ type: 'note', title: 'sdl-from', compiled_truth: 'links out', timeline: '',
+ });
+ await engine.putPage('notes/sdl-to', {
+ type: 'note', title: 'sdl-to', compiled_truth: 'target', timeline: '',
+ });
+ await engine.addLink('notes/sdl-from', 'notes/sdl-to', 'ctx', 'wikilink');
+
+ expect((await engine.getBacklinks('notes/sdl-to')).length).toBe(1);
+ expect((await engine.getLinks('notes/sdl-from')).length).toBe(1);
+ expect((await engine.traversePaths('notes/sdl-to', { direction: 'in' })).length).toBe(1);
+
+ await engine.softDeletePage('notes/sdl-from', { sourceId: 'default' });
+
+ expect(await engine.getBacklinks('notes/sdl-to')).toEqual([]);
+ expect(await engine.getBacklinks('notes/sdl-to', { sourceId: 'default' })).toEqual([]);
+ expect(await engine.getBacklinks('notes/sdl-to', { sourceIds: ['default'] })).toEqual([]);
+ expect(await engine.getLinks('notes/sdl-from')).toEqual([]);
+ expect(await engine.traversePaths('notes/sdl-to', { direction: 'in' })).toEqual([]);
+ expect(await engine.traversePaths('notes/sdl-to', { direction: 'both' })).toEqual([]);
+ expect(await engine.traversePaths('notes/sdl-from', { direction: 'out' })).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) {
@@ -1379,3 +1440,145 @@ describeBoth('Engine parity — putPage empty-overwrite guard', () => {
}
});
});
+
+// #3674 — removeLinksByPagesAndSource must behave identically on both
+// engines: same delete counts, same survivors (typed_ner keep-pairs, other
+// link_sources, other sources untouched).
+describeBoth('Engine parity — removeLinksByPagesAndSource (#3674)', () => {
+ let pgEngine: BrainEngine;
+ let pgliteEngine: PGLiteEngine;
+
+ beforeAll(async () => {
+ pgEngine = await setupDB();
+ pgliteEngine = new PGLiteEngine();
+ await pgliteEngine.connect({});
+ await pgliteEngine.initSchema();
+ }, 90_000);
+
+ afterAll(async () => {
+ await pgliteEngine.disconnect();
+ await teardownDB();
+ }, 30_000);
+
+ async function seed(eng: BrainEngine): Promise<void> {
+ await eng.putPage('rlps/from-a', { type: 'note', title: 'a', compiled_truth: 'body a', timeline: '' });
+ await eng.putPage('rlps/to-x', { type: 'person', title: 'x', compiled_truth: 'body x', timeline: '' });
+ await eng.putPage('rlps/to-y', { type: 'person', title: 'y', compiled_truth: 'body y', timeline: '' });
+ await eng.addLinksBatch([
+ // plain mentions rows (one per target)
+ { from_slug: 'rlps/from-a', to_slug: 'rlps/to-x', link_type: 'mentions', link_source: 'mentions', context: 'x', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'rlps/from-a', to_slug: 'rlps/to-y', link_type: 'mentions', link_source: 'mentions', context: 'y', from_source_id: 'default', to_source_id: 'default' },
+ // typed_ner verb rows: to-x kept (still derivable), to-y stale
+ { from_slug: 'rlps/from-a', to_slug: 'rlps/to-x', link_type: 'works_at', link_source: 'mentions', link_kind: 'typed_ner', context: '', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'rlps/from-a', to_slug: 'rlps/to-y', link_type: 'works_at', link_source: 'mentions', link_kind: 'typed_ner', context: '', from_source_id: 'default', to_source_id: 'default' },
+ // a markdown row that must survive
+ { from_slug: 'rlps/from-a', to_slug: 'rlps/to-x', link_type: 'references', link_source: 'markdown', context: '', from_source_id: 'default', to_source_id: 'default' },
+ ]);
+ }
+
+ async function survivors(eng: BrainEngine): Promise<string[]> {
+ const rows = await eng.executeRaw<{ to_slug: string; link_source: string | null; link_kind: string | null }>(
+ `SELECT tp.slug AS to_slug, l.link_source, l.link_kind
+ FROM links l
+ JOIN pages fp ON fp.id = l.from_page_id
+ JOIN pages tp ON tp.id = l.to_page_id
+ WHERE fp.slug = 'rlps/from-a'
+ ORDER BY tp.slug, l.link_source, l.link_kind NULLS FIRST`,
+ [],
+ );
+ return rows.map((r) => `${r.to_slug}|${r.link_source}|${r.link_kind ?? ''}`);
+ }
+
+ test('identical removal counts and survivors on both engines', async () => {
+ const results: Array<{ removed: number; left: string[] }> = [];
+ for (const eng of [pgEngine, pgliteEngine]) {
+ await seed(eng);
+ const removed = await eng.removeLinksByPagesAndSource(
+ [{ slug: 'rlps/from-a', source_id: 'default' }],
+ {
+ linkSource: 'mentions',
+ keepTypedNerPairs: [
+ { from_slug: 'rlps/from-a', from_source_id: 'default', to_slug: 'rlps/to-x', to_source_id: 'default' },
+ ],
+ },
+ );
+ results.push({ removed, left: await survivors(eng) });
+ }
+ // 2 plain mentions + 1 stale typed_ner deleted; kept typed_ner + markdown survive.
+ expect(results[0]!.removed).toBe(3);
+ expect(results[1]!.removed).toBe(3);
+ expect(results[0]!.left).toEqual(results[1]!.left);
+ expect(results[0]!.left).toEqual([
+ 'rlps/to-x|markdown|',
+ 'rlps/to-x|mentions|typed_ner',
+ ]);
+ });
+});
+
+describeBoth('Engine parity — CJK keyword fallback (#3986)', () => {
+ let pgEngine: BrainEngine;
+ let pgliteEngine: PGLiteEngine;
+
+ const CJK_PAGES = [
+ { slug: 'notes/tokyo-meeting', title: '東京 会議メモ', body: '東京オフィスでの会議メモ。次回の議題は予算です。' },
+ { slug: 'notes/kimdaeri', title: '김대리 미팅', body: '김대리 미팅 노트. 다음 주 일정 조율이 필요합니다.' },
+ { slug: 'notes/ascii-decoy', title: 'ASCII decoy', body: 'plain english content that must not match cjk queries' },
+ ];
+
+ async function seedCJK(eng: BrainEngine) {
+ for (const [i, p] of CJK_PAGES.entries()) {
+ await eng.putPage(p.slug, { type: 'note', title: p.title, compiled_truth: p.body, timeline: '' });
+ await eng.upsertChunks(p.slug, [{
+ chunk_index: 0,
+ chunk_text: p.body,
+ chunk_source: 'compiled_truth' as const,
+ embedding: basisEmbedding(200 + i),
+ token_count: 8,
+ }]);
+ }
+ }
+
+ beforeAll(async () => {
+ pgEngine = await setupDB();
+ await seedCJK(pgEngine);
+ pgliteEngine = new PGLiteEngine();
+ await pgliteEngine.connect({});
+ await pgliteEngine.initSchema();
+ await seedCJK(pgliteEngine);
+ }, 90_000);
+
+ afterAll(async () => {
+ await pgliteEngine.disconnect();
+ await teardownDB();
+ }, 30_000);
+
+ // Pre-#3986, Postgres returned [] here (websearch_to_tsquery('english')
+ // can't tokenize CJK) while PGLite's v0.32.7 ILIKE fallback found the page.
+ test('searchKeyword: CJK query recalls the CJK page on BOTH engines', async () => {
+ const pg = await pgEngine.searchKeyword('東京 会議', { limit: 5 });
+ const pglite = await pgliteEngine.searchKeyword('東京 会議', { limit: 5 });
+ expect(pg.map(r => r.slug)).toEqual(pglite.map(r => r.slug));
+ expect(pg[0]?.slug).toBe('notes/tokyo-meeting');
+ });
+
+ test('searchKeyword: term-order-insensitive Korean recall matches across engines', async () => {
+ const pg = await pgEngine.searchKeyword('미팅 김대리', { limit: 5 });
+ const pglite = await pgliteEngine.searchKeyword('미팅 김대리', { limit: 5 });
+ expect(pg.map(r => r.slug)).toEqual(pglite.map(r => r.slug));
+ expect(pg[0]?.slug).toBe('notes/kimdaeri');
+ });
+
+ test('searchKeywordChunks: chunk-grain CJK fallback matches across engines', async () => {
+ const pg = await pgEngine.searchKeywordChunks('予算', { limit: 5 });
+ const pglite = await pgliteEngine.searchKeywordChunks('予算', { limit: 5 });
+ expect(pg.map(r => `${r.slug}#${r.chunk_index}`)).toEqual(pglite.map(r => `${r.slug}#${r.chunk_index}`));
+ expect(pg[0]?.slug).toBe('notes/tokyo-meeting');
+ });
+
+ test('searchKeyword: CJK fallback honors source isolation on both engines', async () => {
+ const pg = await pgEngine.searchKeyword('東京 会議', { limit: 5, sourceIds: ['nonexistent-source'] });
+ const pglite = await pgliteEngine.searchKeyword('東京 会議', { limit: 5, sourceIds: ['nonexistent-source'] });
+ expect(pg).toEqual([]);
+ expect(pglite).toEqual([]);
+ });
+});
diff --git a/test/e2e/enrich-pglite.test.ts b/test/e2e/enrich-pglite.test.ts
index dfc4c863d2..af107fb918 100644
--- a/test/e2e/enrich-pglite.test.ts
+++ b/test/e2e/enrich-pglite.test.ts
@@ -256,6 +256,26 @@ describe('runEnrichCore', () => {
expect(page!.compiled_truth.trim()).toBe(STUB);
}, 30000);
+ test('#2504: a failing page surfaces first_failure (pool.failures no longer write-only)', async () => {
+ await seedStub('people/fiona-example', 'Fiona Example', 'person');
+ await seedLinkInto('people/fiona-example', 'meetings/kickoff', RICH_CONTEXT);
+ const failingSynth: SynthesizeFn = async () => {
+ throw new Error('no pricing entry for model "example:example-chat" (kind=chat)');
+ };
+
+ const r = await runEnrichCore(engine, {
+ sourceId: 'default',
+ types: ['person'],
+ model: 'test:model',
+ synthesizeFn: failingSynth,
+ });
+ // Pre-fix: pages_failed:1 with zero reason anywhere. Post-fix the result
+ // carries slug + message so the operator sees WHY instead of guessing.
+ expect(r.pages_failed).toBe(1);
+ expect(r.first_failure).toContain('people/fiona-example');
+ expect(r.first_failure).toContain('no pricing entry');
+ }, 30000);
+
test('resume: pre-seeded checkpoint skips an already-completed page', async () => {
await seedStub('people/alice-example', 'Alice Example', 'person');
await seedStub('people/bob-example', 'Bob Example', 'person');
@@ -440,3 +460,91 @@ describe('runEnrichCore', () => {
expect(r.pages_enriched).toBe(0);
});
});
+
+// ---------------------------------------------------------------------------
+// #3629 — checkpoint persistence: SKIP pages must not re-bill every run.
+// ---------------------------------------------------------------------------
+
+describe('checkpoint persistence (#3629)', () => {
+ test('SKIP page is billed once: repeat runs make zero further synth calls', async () => {
+ await seedStub('people/skip-example', 'Skip Example', 'person');
+ await seedLinkInto('people/skip-example', 'meetings/skip-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,
+ };
+
+ const r1 = await runEnrichCore(engine, opts);
+ expect(synthCalls).toBe(1);
+ expect(r1.pages_model_skip).toBe(1);
+ // The page stays thin (SKIP writes nothing) — it re-enters the candidate
+ // list, and pre-fix the clean-run checkpoint clear re-billed it forever.
+ const r2 = await runEnrichCore(engine, opts);
+ expect(synthCalls).toBe(1); // no re-bill on tick 2
+ const r3 = await runEnrichCore(engine, opts);
+ expect(synthCalls).toBe(1); // no re-bill on tick 3
+ expect(r2.pages_enriched).toBe(0);
+ expect(r3.pages_enriched).toBe(0);
+ // Checkpoint row persists across clean runs (decays via the 7d purge TTL).
+ const fp = enrichFingerprint({
+ sourceId: 'default', types: ['person'], order: 'inbound-links',
+ thinThreshold: 400, model: 'test:model',
+ });
+ const done = await loadOpCheckpoint(engine, { op: CHECKPOINT_OP, fingerprint: fp });
+ expect(done).toContain('default|people/skip-example');
+ }, 60000);
+
+ test('wedge: limit=1 with the top candidate checkpointed reaches the 2nd candidate on tick 2', async () => {
+ // alice outranks bob on inbound links (2 vs 1).
+ await seedStub('people/alice-example', 'Alice Example', 'person');
+ await seedStub('people/bob-example', 'Bob Example', 'person');
+ await seedLinkInto('people/alice-example', 'meetings/w1', RICH_CONTEXT);
+ await seedLinkInto('people/alice-example', 'meetings/w2', RICH_CONTEXT);
+ await seedLinkInto('people/bob-example', 'meetings/w3', RICH_CONTEXT);
+
+ // Tick 1: alice (rank 1) consumes the single slot and SKIPs → checkpointed.
+ const r1 = await runEnrichCore(engine, {
+ sourceId: 'default', types: ['person'], limit: 1, model: 'test:model',
+ synthesizeFn: async () => 'SKIP',
+ });
+ expect(r1.pages_model_skip).toBe(1);
+
+ // Tick 2 (same limit): pre-fix the fetch window held only checkpointed
+ // alice → pending=[] forever and bob never got a turn. Post-fix the
+ // over-fetch reaches bob.
+ const r2 = await runEnrichCore(engine, {
+ sourceId: 'default', types: ['person'], limit: 1, model: 'test:model',
+ synthesizeFn: goodSynth,
+ });
+ expect(r2.pages_enriched).toBe(1);
+ const bob = await engine.getPage('people/bob-example', { sourceId: 'default' });
+ expect(bob!.compiled_truth).toContain('## Overview');
+ const alice = await engine.getPage('people/alice-example', { sourceId: 'default' });
+ expect(alice!.compiled_truth.trim()).toBe(STUB); // untouched (checkpointed)
+ }, 60000);
+
+ test('--force clears the checkpoint and retries a SKIP page', async () => {
+ await seedStub('people/force-example', 'Force Example', 'person');
+ await seedLinkInto('people/force-example', 'meetings/force-m', RICH_CONTEXT);
+
+ let synthCalls = 0;
+ const skipSynth: SynthesizeFn = async () => { synthCalls++; return 'SKIP'; };
+ const base = {
+ sourceId: 'default',
+ types: ['person' as const],
+ model: 'test:model',
+ synthesizeFn: skipSynth,
+ };
+ await runEnrichCore(engine, base);
+ expect(synthCalls).toBe(1);
+ await runEnrichCore(engine, base);
+ expect(synthCalls).toBe(1); // checkpoint holds
+ await runEnrichCore(engine, { ...base, force: true });
+ expect(synthCalls).toBe(2); // --force re-bills deliberately
+ }, 60000);
+});
diff --git a/test/e2e/extraction-review-postgres.test.ts b/test/e2e/extraction-review-postgres.test.ts
index f122e54c6d..54a762d8fb 100644
--- a/test/e2e/extraction-review-postgres.test.ts
+++ b/test/e2e/extraction-review-postgres.test.ts
@@ -52,9 +52,9 @@ d('extraction quarantine lane (live Postgres)', () => {
const real = await engine.getPage('people/pg-real');
expect(isUnverifiedExtraction(fake!.frontmatter)).toBe(true);
expect(isUnverifiedExtraction(real!.frontmatter)).toBe(false);
- const set = await engine.getUnverifiedExtractionPageIds([fake!.id, real!.id]);
- expect(set.has(fake!.id)).toBe(true);
- expect(set.has(real!.id)).toBe(false);
+ const marks = await engine.getUnverifiedExtractionPageIds([fake!.id, real!.id]);
+ expect(marks.get(fake!.id)).toEqual({ unverified: true, status: 'unverified' });
+ expect(marks.has(real!.id)).toBe(false);
});
test('SQL source-boost guard: unverified stub loses the people/ 1.2x in searchKeyword', async () => {
diff --git a/test/e2e/facts-fence-reconcile-postgres.test.ts b/test/e2e/facts-fence-reconcile-postgres.test.ts
index 16875df2f0..2475bbbcb4 100644
--- a/test/e2e/facts-fence-reconcile-postgres.test.ts
+++ b/test/e2e/facts-fence-reconcile-postgres.test.ts
@@ -1,7 +1,8 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
import { parseFactsFence, renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';
+import type { NewFact } from '../../src/core/engine.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
const databaseUrl = process.env.DATABASE_URL;
@@ -162,3 +163,290 @@ describe.skipIf(skip)('deleteFactsForPage preserveExpiredLegacy on Postgres (#26
expect(Array.from(rows)).toHaveLength(0);
}, 30_000);
});
+
+// v0.46 (#3014) — fence-authored supersession transport end to end on real
+// Postgres (parity with the PGLite coverage in extract-facts-phase.test.ts +
+// insert-facts-batch.test.ts).
+describe.skipIf(skip)('facts-fence supersession transport on Postgres (#3014)', () => {
+ const slug = 'people/zz-supersession-e2e-3014';
+ let engine: PostgresEngine;
+
+ beforeAll(async () => {
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: databaseUrl! });
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ if (engine) {
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug = $1', [slug]);
+ await engine.executeRaw('DELETE FROM pages WHERE slug = $1', [slug]);
+ await engine.disconnect();
+ }
+ });
+
+ // Each test putPages its own fence and expects a fresh reconcile, so wipe
+ // the page's DB rows first. Without this, two consecutive tests whose
+ // struck rows both resolve to NULL (e.g. dangling #9 then int4-overflow
+ // #99999999999) share a claim + slug, so the second reconcile sees no
+ // drift and skips — correct no-churn behavior, but it would starve a test
+ // that asserts a fresh warning.
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug = $1', [slug]);
+ });
+
+ // Row 1 struck + "superseded by #2"; row 2 the live superseding fact.
+ const buildFence = (): string => renderFactsTable([
+ {
+ rowNum: 1,
+ claim: 'Will close the deal by Q2',
+ kind: 'commitment',
+ confidence: 0.6,
+ visibility: 'world',
+ notability: 'medium',
+ validFrom: '2026-01-01',
+ source: 'call',
+ context: 'superseded by #2',
+ active: false,
+ supersededBy: 2,
+ },
+ {
+ rowNum: 2,
+ claim: 'Deal closed in Q3',
+ kind: 'fact',
+ confidence: 1,
+ visibility: 'world',
+ notability: 'high',
+ validFrom: '2026-07-01',
+ source: 'call',
+ active: true,
+ },
+ ]);
+
+ interface SupRow { id: number | string; row_num: number | string; superseded_by: number | string | null; expired_at: Date | string | null }
+ const readRows = async (): Promise<SupRow[]> =>
+ Array.from(await engine.executeRaw<SupRow>(
+ 'SELECT id, row_num, superseded_by, expired_at FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num',
+ [slug],
+ ));
+
+ const readIds = async (): Promise<number[]> =>
+ (await readRows()).map(r => Number(r.id));
+
+ // Row 1 struck with an unresolvable `superseded by #N`; no target row.
+ const buildDanglingFence = (ref: number): string => renderFactsTable([
+ {
+ rowNum: 1,
+ claim: 'Retired claim with a bad reference',
+ kind: 'commitment',
+ confidence: 0.6,
+ visibility: 'world',
+ notability: 'medium',
+ validFrom: '2026-01-01',
+ source: 'call',
+ context: `superseded by #${ref}`,
+ active: false,
+ supersededBy: ref,
+ },
+ ]);
+
+ test('struck row lands with superseded_by + expired_at and surfaces in listSupersessions', async () => {
+ await engine.putPage(slug, {
+ title: 'Supersession E2E Example',
+ type: 'person',
+ compiled_truth: buildFence(),
+ frontmatter: {},
+ timeline: '',
+ });
+ const result = await runExtractFacts(engine, { slugs: [slug] });
+ expect(result.factsInserted).toBe(2);
+
+ const rows = await readRows();
+ expect(rows).toHaveLength(2);
+ const [row1, row2] = rows;
+ // The struck row's page-local "#2" reference resolved to row 2's fact id.
+ expect(Number(row1.superseded_by)).toBe(Number(row2.id));
+ expect(row1.expired_at).not.toBeNull();
+ // The live superseding row is untouched.
+ expect(row2.superseded_by).toBeNull();
+ expect(row2.expired_at).toBeNull();
+
+ const sup = await engine.listSupersessions('default');
+ expect(sup.some(s => s.id === Number(row1.id) && s.superseded_by === Number(row2.id))).toBe(true);
+ }, 30_000);
+
+ test('idempotent heal: a struck row with NULL columns re-populates on re-reconcile', async () => {
+ await engine.putPage(slug, {
+ title: 'Supersession E2E Example',
+ type: 'person',
+ compiled_truth: buildFence(),
+ frontmatter: {},
+ timeline: '',
+ });
+ await runExtractFacts(engine, { slugs: [slug] });
+
+ // Simulate the pre-#3014 mis-transport: the struck row was inserted with
+ // both columns NULL. The fence is unchanged, so only the drift check on
+ // the supersession columns can trigger a re-heal.
+ await engine.executeRaw(
+ 'UPDATE facts SET superseded_by = NULL, expired_at = NULL WHERE source_markdown_slug = $1 AND row_num = 1',
+ [slug],
+ );
+ const before = await readRows();
+ expect(before.find(r => Number(r.row_num) === 1)!.superseded_by).toBeNull();
+
+ // Re-reconcile: hasSupersessionDrift fires → wipe+reinsert heals the row.
+ await runExtractFacts(engine, { slugs: [slug] });
+
+ const after = await readRows();
+ const healed = after.find(r => Number(r.row_num) === 1)!;
+ const target = after.find(r => Number(r.row_num) === 2)!;
+ expect(Number(healed.superseded_by)).toBe(Number(target.id));
+ expect(healed.expired_at).not.toBeNull();
+ }, 30_000);
+
+ // A dangling reference resolves to NULL every cycle and matches the DB's
+ // NULL, so it must not re-drift (a naive drift term would wipe + reinsert
+ // the page every cycle, advancing the fact ids).
+ test('idempotent: a dangling reference does not churn on re-reconcile', async () => {
+ await engine.putPage(slug, {
+ title: 'Supersession E2E Example',
+ type: 'person',
+ compiled_truth: buildDanglingFence(9),
+ frontmatter: {},
+ timeline: '',
+ });
+ const first = await runExtractFacts(engine, { slugs: [slug] });
+ expect(first.warnings.some(w => w.includes('absent from the fence'))).toBe(true);
+ const idsAfterFirst = await readIds();
+
+ const second = await runExtractFacts(engine, { slugs: [slug] });
+ expect(second.factsInserted).toBe(0);
+ expect(second.factsDeleted).toBe(0);
+ expect(second.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ expect(await readIds()).toEqual(idsAfterFirst);
+ }, 30_000);
+
+ // An int4-overflowing #N would raise `integer out of range` in the
+ // resolution SELECT and abort the cycle; the guard treats it as a
+ // dangling reference instead.
+ test('int4-overflow reference (11-digit #N) resolves as dangling — cycle completes', async () => {
+ await engine.putPage(slug, {
+ title: 'Supersession E2E Example',
+ type: 'person',
+ compiled_truth: buildDanglingFence(99999999999),
+ frontmatter: {},
+ timeline: '',
+ });
+ const r = await runExtractFacts(engine, { slugs: [slug] });
+ expect(r.warnings.some(w => w.includes('absent from the fence'))).toBe(true);
+ const row1 = (await readRows()).find(x => Number(x.row_num) === 1)!;
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).not.toBeNull();
+ }, 30_000);
+
+ // The wipe now runs inside insertFacts' transaction, so a failing insert
+ // rolls it back and the page is never left emptied.
+ test('deleteForPageFirst rolls the wipe back when the insert fails — the page survives', async () => {
+ type Row = NewFact & { row_num: number; source_markdown_slug: string };
+ const fixture = (rowNum: number, fact: string): Row => ({
+ fact,
+ kind: 'fact',
+ entity_slug: 'people/zz-supersession-e2e-3014',
+ visibility: 'world',
+ notability: 'medium',
+ source: 'fence:reconcile',
+ confidence: 1.0,
+ row_num: rowNum,
+ source_markdown_slug: slug,
+ });
+
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug = $1', [slug]);
+ await engine.insertFacts([fixture(1, 'keeper one'), fixture(2, 'keeper two')], { source_id: 'default' });
+
+ let threw = false;
+ try {
+ // A NULL fact violates the NOT NULL constraint AFTER the delete has
+ // run inside the same transaction (the v51 index can't be used as the
+ // failure trigger here — ON CONFLICT DO NOTHING absorbs collisions).
+ await engine.insertFacts(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ [fixture(1, 'replacement a'), fixture(2, null as any)],
+ { source_id: 'default' },
+ { deleteForPageFirst: { slug, excludeSourcePrefixes: ['cli:'] } },
+ );
+ } catch {
+ threw = true;
+ }
+ expect(threw).toBe(true);
+
+ const facts = await engine.executeRaw<{ fact: string }>(
+ 'SELECT fact FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num',
+ [slug],
+ );
+ expect(Array.from(facts).map(f => f.fact)).toEqual(['keeper one', 'keeper two']);
+ }, 30_000);
+});
+
+// v0.46 (#3014) option B — the ontology-dimension writer closes a superseded
+// row via valid_until + superseded_by (NOT expired_at, so getOntology's
+// --asof time-travel still sees it). listSupersessions must surface it anyway
+// (filter on superseded_by alone) and order/since via COALESCE(expired_at,
+// valid_until). Both verified here on real Postgres.
+describe.skipIf(skip)('facts supersession visibility on Postgres — ontology + since (#3014)', () => {
+ const SARAH = 'people/zz-sarah-ontology-3014';
+ let engine: PostgresEngine;
+
+ beforeAll(async () => {
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: databaseUrl! });
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ if (engine) {
+ await engine.executeRaw('DELETE FROM facts WHERE entity_slug = $1', [SARAH]);
+ await engine.disconnect();
+ }
+ });
+
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM facts WHERE entity_slug = $1', [SARAH]);
+ });
+
+ // founder (2024) → advisor (2026-05-01): the prior 'founder' row is closed
+ // via valid_until = 2026-05-01, superseded_by set, expired_at left NULL.
+ const supersede = async () => {
+ await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'founder', source: 'meetings/a', validFrom: '2024-01-01' });
+ const r = await engine.mergeOntologyFact({ entitySlug: SARAH, dimension: 'role', value: 'advisor', source: 'meetings/b', validFrom: '2026-05-01' });
+ expect(r.action).toBe('superseded_prior');
+ };
+
+ test('a forward ontology supersession surfaces in listSupersessions while --asof still time-travels', async () => {
+ await supersede();
+
+ const sup = await engine.listSupersessions('default');
+ const founder = sup.find(s => s.fact.includes('founder') && s.entity_slug === SARAH);
+ expect(founder).toBeDefined();
+ expect(founder!.superseded_by).not.toBeNull();
+ // Option A ("writers set both columns") would have set expired_at here and
+ // broken the --asof read below; option B leaves it NULL and surfaces anyway.
+ expect(founder!.expired_at).toBeNull();
+
+ const past = await engine.getOntology(SARAH, { asof: '2025-01-01' });
+ expect(past[0].value).toBe('founder');
+ }, 30_000);
+
+ test('listSupersessions({since}) filters a NULL-expired_at row by COALESCE(expired_at, valid_until)', async () => {
+ await supersede(); // founder row: valid_until = 2026-05-01, expired_at NULL
+
+ // since before the close date → COALESCE falls back to valid_until, included.
+ const included = await engine.listSupersessions('default', { since: new Date('2026-01-01T00:00:00Z') });
+ expect(included.some(s => s.fact.includes('founder') && s.entity_slug === SARAH)).toBe(true);
+
+ // since after the close date → excluded (a pre-fix `expired_at >= since`
+ // would have dropped it unconditionally since expired_at is NULL).
+ const excluded = await engine.listSupersessions('default', { since: new Date('2026-09-01T00:00:00Z') });
+ expect(excluded.some(s => s.fact.includes('founder') && s.entity_slug === SARAH)).toBe(false);
+ }, 30_000);
+});
diff --git a/test/e2e/jobs-agent-scope-postgres.test.ts b/test/e2e/jobs-agent-scope-postgres.test.ts
new file mode 100644
index 0000000000..ce391a61e1
--- /dev/null
+++ b/test/e2e/jobs-agent-scope-postgres.test.ts
@@ -0,0 +1,103 @@
+/**
+ * #4098 — agent-scoped jobs ops, LIVE Postgres parity.
+ *
+ * The PGLite coverage lives in test/jobs-agent-scope.test.ts; this file
+ * re-runs the SQL-touching pieces (the `data->>'__owner_client_id'` fence in
+ * assertJobOwned / MinionQueue.getJobs / the recursive-cancel CTE seed) on a
+ * real Postgres so postgres.js parameter binding is proven on both engines.
+ *
+ * Gated by DATABASE_URL via hasDatabase(); skips cleanly when unset.
+ *
+ * Run: DATABASE_URL=... bun test test/e2e/jobs-agent-scope-postgres.test.ts
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';
+
+const RUN = hasDatabase();
+const d = RUN ? describe : describe.skip;
+
+let engine: PostgresEngine;
+let queue: MinionQueue;
+
+function ctx(over: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine,
+ config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ ...over,
+ } as OperationContext;
+}
+
+const agentCtx = (clientId: string) =>
+ ctx({ auth: { clientId, scopes: ['agent'] } as OperationContext['auth'] });
+
+let seedSeq = 0;
+async function seedJob(owner: string | null): Promise<number> {
+ const data: Record<string, unknown> = { prompt: `pg-x-${++seedSeq}` };
+ if (owner) data.__owner_client_id = owner;
+ const job = await queue.add('subagent', data, { queue: 'default' }, { allowProtectedSubmit: true });
+ return job.id;
+}
+
+d('jobs agent-scope fence (live Postgres)', () => {
+ beforeAll(async () => {
+ engine = await setupDB();
+ queue = new MinionQueue(engine);
+ }, 60_000);
+
+ afterAll(async () => {
+ await teardownDB();
+ }, 60_000);
+
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_inbox', []);
+ await engine.executeRaw('DELETE FROM minion_jobs', []);
+ });
+
+ test('get_job fence: own visible, foreign uniform not-found', async () => {
+ const get_job = operationsByName['get_job']!;
+ const mine = await seedJob('pg-agent-a');
+ const theirs = await seedJob('pg-agent-b');
+ const job = (await get_job.handler(agentCtx('pg-agent-a'), { id: mine })) as { id: number };
+ expect(job.id).toBe(mine);
+ await expect(get_job.handler(agentCtx('pg-agent-a'), { id: theirs })).rejects.toThrow(/not found/i);
+ });
+
+ test('list_jobs fence rides the SQL WHERE', async () => {
+ const list_jobs = operationsByName['list_jobs']!;
+ await seedJob('pg-agent-a');
+ await seedJob('pg-agent-b');
+ const mine = (await list_jobs.handler(agentCtx('pg-agent-a'), {})) as Array<{ data: Record<string, unknown> }>;
+ expect(mine.length).toBe(1);
+ expect(mine[0]!.data.__owner_client_id).toBe('pg-agent-a');
+ });
+
+ test('cancel_job fence gates the recursive CTE seed; children cascade', async () => {
+ const cancel_job = operationsByName['cancel_job']!;
+ const rootId = await seedJob('pg-agent-a');
+ const foreign = await seedJob('pg-agent-b');
+ const child = await queue.add('subagent', { prompt: `pg-child-${++seedSeq}` }, { queue: 'default' }, { allowProtectedSubmit: true });
+ await engine.executeRaw('UPDATE minion_jobs SET parent_job_id = $1 WHERE id = $2', [rootId, child.id]);
+
+ // Foreign root refused; stays waiting.
+ await expect(cancel_job.handler(agentCtx('pg-agent-a'), { id: foreign })).rejects.toThrow(/Cannot cancel/);
+ const foreignRow = await engine.executeRaw<{ status: string }>(
+ 'SELECT status FROM minion_jobs WHERE id = $1', [foreign],
+ );
+ expect(foreignRow[0]!.status).toBe('waiting');
+
+ // Owned root cancels + cascades.
+ const cancelled = (await cancel_job.handler(agentCtx('pg-agent-a'), { id: rootId })) as { status: string };
+ expect(cancelled.status).toBe('cancelled');
+ const childRow = await engine.executeRaw<{ status: string }>(
+ 'SELECT status FROM minion_jobs WHERE id = $1', [child.id],
+ );
+ expect(childRow[0]!.status).toBe('cancelled');
+ });
+});
diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.ts
index 8b538361f3..d460a1221e 100644
--- a/test/e2e/mechanical.test.ts
+++ b/test/e2e/mechanical.test.ts
@@ -47,10 +47,19 @@ afterAll(() => {
try { if (_tmpHome) rmSync(_tmpHome, { recursive: true, force: true }); } catch { /* best-effort */ }
});
-function makeCtx(opts: { remote?: boolean } = {}): OperationContext {
+function makeCtx(
+ opts: { remote?: boolean; storage?: { backend: 'local'; localPath: string } } = {},
+): OperationContext {
return {
engine: getEngine(),
- config: { engine: 'postgres', database_url: process.env.DATABASE_URL! },
+ config: {
+ engine: 'postgres',
+ database_url: process.env.DATABASE_URL!,
+ // #4302: file_upload / file_url are fail-closed — they refuse with a
+ // typed storage_error unless a storage backend is configured. Tests
+ // that exercise the success path pass a local (temp-dir) backend here.
+ ...(opts.storage ? { storage: opts.storage } : {}),
+ },
logger: { info: () => {}, warn: () => {}, error: () => {} },
dryRun: false,
// Default: trusted local invocation (matches `gbrain call` semantics).
@@ -616,7 +625,7 @@ describeE2E('E2E: Ingest Log & Raw Data', () => {
});
// ─────────────────────────────────────────────────────────────────
-// Files (stub verification)
+// Files (fail-closed refusal without a backend + real local-backend path)
// ─────────────────────────────────────────────────────────────────
describeE2E('E2E: Files', () => {
@@ -638,7 +647,24 @@ describeE2E('E2E: Files', () => {
writeFileSync(tmpFile, 'fake pdf content');
try {
- const result = await callOp('file_upload', {
+ // #4302 (fail-closed storage honesty): with NO storage backend
+ // configured, file_upload must refuse with a typed storage_error and
+ // must NOT record a phantom files row.
+ let refused: any = null;
+ try {
+ await callOp('file_upload', { path: tmpFile, page_slug: 'people/sarah-chen' });
+ } catch (e) {
+ refused = e;
+ }
+ expect(refused).not.toBeNull();
+ expect(refused.code).toBe('storage_error');
+ expect(((await callOp('file_list', {})) as any[]).length).toBe(0);
+
+ // Success path: a real (local, temp-dir) backend — bytes stored,
+ // files row recorded, file_list + file_url read it back.
+ const storage = { backend: 'local' as const, localPath: join(tmpDir, 'storage') };
+ const uploadOp = operationsByName['file_upload'];
+ const result = await uploadOp.handler(makeCtx({ storage }), {
path: tmpFile,
page_slug: 'people/sarah-chen',
}) as any;
@@ -654,9 +680,13 @@ describeE2E('E2E: Files', () => {
expect(typeof files[0].size_bytes).toBe('number');
expect(() => JSON.stringify(files)).not.toThrow();
- // Verify file_url returns URI format
- const url = await callOp('file_url', { storage_path: result.storage_path }) as any;
- expect(url.url).toContain('gbrain:files/');
+ // Verify file_url resolves a REAL backend URL (#4302 replaced the
+ // gbrain:files/ placeholder with the backend's own URL after an
+ // existence probe; LocalStorage yields file://).
+ const urlOp = operationsByName['file_url'];
+ const url = await urlOp.handler(makeCtx({ storage }), { storage_path: result.storage_path }) as any;
+ expect(url.url).toMatch(/^file:\/\//);
+ expect(url.url).toContain('sarah-chen');
} finally {
rmSync(tmpDir, { recursive: true });
}
diff --git a/test/e2e/multi-source-bug-class.test.ts b/test/e2e/multi-source-bug-class.test.ts
index 51128e3c06..5622cf8afd 100644
--- a/test/e2e/multi-source-bug-class.test.ts
+++ b/test/e2e/multi-source-bug-class.test.ts
@@ -201,6 +201,12 @@ describe('multi-source bug class', () => {
'media-corpus::media/x/post-123',
'media-corpus::people/alice',
]);
+ // #4304: each ref carries updated_at (a real Date) so --since walks can
+ // filter before any full-page fetch.
+ for (const r of refs) {
+ expect(r.updated_at instanceof Date).toBe(true);
+ expect(Number.isFinite(r.updated_at.getTime())).toBe(true);
+ }
});
test('getPage with sourceId picks the right (source, slug) row', async () => {
diff --git a/test/e2e/pglite-cli-exit.serial.test.ts b/test/e2e/pglite-cli-exit.serial.test.ts
index 08ea42b7c5..7e12401848 100644
--- a/test/e2e/pglite-cli-exit.serial.test.ts
+++ b/test/e2e/pglite-cli-exit.serial.test.ts
@@ -33,17 +33,20 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { spawn, spawnSync } from 'child_process';
-import { randomBytes } from 'crypto';
import {
cpSync,
mkdirSync,
mkdtempSync,
+ readdirSync,
+ readFileSync,
rmSync,
writeFileSync,
chmodSync,
} from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { EngineConfig } from '../../src/core/types.ts';
const REPO_ROOT = resolve(import.meta.dir, '..', '..');
const BIN_CACHE = join(REPO_ROOT, 'test', '.cache');
@@ -425,11 +428,16 @@ describe('#2084 — explicit-exit teardown: every swept site exits clean, exit c
describe('WAL-repair wave — corrupt persistent brain, auto-repair off: owned exit 1 (#2084 class)', () => {
test('gbrain status on a torn-WAL brain with GBRAIN_PGLITE_WAL_REPAIR=off exits 1 (not 0, not 99)', async () => {
- // Fixture: a fake-but-layout-valid PG17 pglite data dir whose control +
- // WAL state is garbage, so PGlite.create aborts. With auto-repair
- // disabled the CLI must fail LOUDLY through the owned verdict channel:
- // real process exit 1 — never 0 (silent success over a broken brain),
- // never 99 (Emscripten's hijacked process.exitCode, the #2084 class).
+ // Fixture (#3922): a REAL persistent PGLite brain — created, probed,
+ // cleanly disconnected — whose WAL segments are then overwritten with
+ // deterministic garbage (Buffer.alloc(size, 0xff), the exact shape
+ // test/pglite-wal-repair.serial.test.ts pins), so PGlite.create aborts
+ // the same way every run. The prior fixture wrote randomBytes into a
+ // fake pg_control + fake WAL segment, which made the abort path
+ // nondeterministic run-to-run. With auto-repair disabled the CLI must
+ // fail LOUDLY through the owned verdict channel: real process exit 1 —
+ // never 0 (silent success over a broken brain), never 99 (Emscripten's
+ // hijacked process.exitCode, the #2084 class).
const corruptHome = mkdtempSync(join(tmpdir(), 'gbrain-pglite-corrupt-'));
try {
const dataDir = join(corruptHome, 'brain.pglite');
@@ -440,12 +448,25 @@ describe('WAL-repair wave — corrupt persistent brain, auto-repair off: owned e
JSON.stringify({ engine: 'pglite', database_path: dataDir }, null, 2) + '\n',
'utf-8',
);
- mkdirSync(join(dataDir, 'base'), { recursive: true });
- mkdirSync(join(dataDir, 'global'), { recursive: true });
- mkdirSync(join(dataDir, 'pg_wal'), { recursive: true });
- writeFileSync(join(dataDir, 'PG_VERSION'), '17\n', 'utf-8');
- writeFileSync(join(dataDir, 'global', 'pg_control'), randomBytes(8192));
- writeFileSync(join(dataDir, 'pg_wal', '000000010000000000000001'), randomBytes(1024));
+
+ // Build the real brain in-process, then shut it down cleanly so the
+ // data dir is layout-valid with a real pg_control + real WAL.
+ const builder = new PGLiteEngine();
+ await builder.connect({ engine: 'pglite', database_path: dataDir } as EngineConfig);
+ await builder.db.exec('CREATE TABLE exit_probe (id int); INSERT INTO exit_probe VALUES (1);');
+ await builder.disconnect();
+
+ // Overwrite EVERY real WAL segment with garbage, keeping its size —
+ // deterministic corruption, no RNG.
+ const segments = readdirSync(join(dataDir, 'pg_wal')).filter((f) =>
+ /^[0-9A-F]{24}$/.test(f),
+ );
+ expect(segments.length).toBeGreaterThan(0);
+ for (const seg of segments) {
+ const p = join(dataDir, 'pg_wal', seg);
+ const size = readFileSync(p).length;
+ writeFileSync(p, Buffer.alloc(size, 0xff));
+ }
const { code, stdout, stderr, durationMs } = await runWithTimeout(
['status'],
@@ -463,7 +484,7 @@ describe('WAL-repair wave — corrupt persistent brain, auto-repair off: owned e
} finally {
rmSync(corruptHome, { recursive: true, force: true });
}
- }, 60_000);
+ }, 180_000);
});
describe('v0.41.8.0 — daemon survival (regression guard for narrow force-exit)', () => {
diff --git a/test/edge-extractor.test.ts b/test/edge-extractor.test.ts
index d9dcfc22e6..795534f1e1 100644
--- a/test/edge-extractor.test.ts
+++ b/test/edge-extractor.test.ts
@@ -177,6 +177,42 @@ fun caller(input: String): String {
});
});
+describe('#3602 — C# invocation extraction', () => {
+ test('captures bare method invocations', async () => {
+ const src = `namespace Demo
+{
+ public class Svc
+ {
+ public int Helper() { return 1; }
+ public int Caller() { return Helper(); }
+ }
+}
+`;
+ const result = await chunkCodeTextFull(src, 'src/Svc.cs');
+ expect(result.edges.map(e => e.toSymbol)).toContain('Helper');
+ });
+
+ test('captures member-access invocations (obj.Method())', async () => {
+ const src = `namespace Demo
+{
+ public class Svc
+ {
+ public int Run(Other other) { return other.Compute(); }
+ }
+}
+`;
+ const result = await chunkCodeTextFull(src, 'src/Svc.cs');
+ expect(result.edges.map(e => e.toSymbol)).toContain('Compute');
+ });
+
+ test('all C# edges typed as calls', async () => {
+ const src = 'public class C { int F() { return G(); } int G() { return 1; } }';
+ const result = await chunkCodeTextFull(src, 'src/C.cs');
+ expect(result.edges.length).toBeGreaterThanOrEqual(1);
+ for (const e of result.edges) expect(e.edgeType).toBe('calls');
+ });
+});
+
describe('Layer 5 (A1) — findChunkForOffset mapping', () => {
test('finds innermost chunk for a given offset', () => {
const source = [
diff --git a/test/embed-partial-failure-3037.serial.test.ts b/test/embed-partial-failure-3037.serial.test.ts
index 211b307ade..d6712f6c0e 100644
--- a/test/embed-partial-failure-3037.serial.test.ts
+++ b/test/embed-partial-failure-3037.serial.test.ts
@@ -214,6 +214,18 @@ describe('#3037 — one bad chunk no longer darkens its page', () => {
});
describe('#3037 — cost bounding: no per-chunk fan-out on transient failures', () => {
+ // #3796: sustained-429 exhaustion now deliberately spans a rolling TPM
+ // minute (~120s of floors); shrink the ladder so these tests stay fast
+ // while still exercising every retry.
+ beforeEach(async () => {
+ const { _setRateLimitFloorsForTests } = await import('../src/commands/embed.ts');
+ _setRateLimitFloorsForTests([1, 1, 1, 1, 1]);
+ });
+ afterEach(async () => {
+ const { _setRateLimitFloorsForTests } = await import('../src/commands/embed.ts');
+ _setRateLimitFloorsForTests(null);
+ });
+
test('sustained 429 does not fan out into single-chunk calls', async () => {
embedBatchBehavior = async () => {
const err = new Error('Rate limit reached. Please try again in 0ms.');
diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.ts
index b64f8171f9..9e7a1049a4 100644
--- a/test/embed.serial.test.ts
+++ b/test/embed.serial.test.ts
@@ -37,6 +37,10 @@ mock.module('../src/core/embedding.ts', () => ({
// setPageEmbeddingSignature / invalidateStaleSignatureEmbeddings resolve to
// null via the Proxy default, so the signature value is inert here.
currentEmbeddingSignature: () => 'test:model:1536',
+ // #3374: import-file.ts (imported by the routing test below) also pulls
+ // embedMultimodal from this module; the mock must export it or the import
+ // itself throws. Inert — no test here exercises the multimodal path.
+ embedMultimodal: async (inputs: unknown[]) => inputs.map(() => new Float32Array(512)),
}));
// Import AFTER mocking.
@@ -746,6 +750,123 @@ describe('embedBatchWithBackoff (D2/D4/D4a/D8)', () => {
});
});
+// ────────────────────────────────────────────────────────────────
+// #3374: transient network retry branch (timeout / conn-reset)
+// beside the 429 path, plain bounded backoff, never caller aborts.
+// ────────────────────────────────────────────────────────────────
+
+describe('#3374 — transient network retry branch', () => {
+ test('classifier: structured codes, TimeoutError name, message fallback', async () => {
+ const { isTransientNetworkEmbedError } = await import('../src/commands/embed.ts');
+ // Structured code on the error itself and through the cause chain.
+ const reset = new Error('request failed');
+ (reset as any).code = 'ECONNRESET';
+ expect(isTransientNetworkEmbedError(reset)).toBe(true);
+ expect(isTransientNetworkEmbedError({ cause: { code: 'UND_ERR_CONNECT_TIMEOUT' } })).toBe(true);
+ expect(isTransientNetworkEmbedError({ cause: { cause: { code: 'ETIMEDOUT' } } })).toBe(true);
+ expect(isTransientNetworkEmbedError({ name: 'TimeoutError' })).toBe(true);
+ // Message fallback for wrappers that strip the code.
+ expect(isTransientNetworkEmbedError(new Error('socket hang up'))).toBe(true);
+ expect(isTransientNetworkEmbedError(new Error('fetch failed'))).toBe(true);
+ expect(isTransientNetworkEmbedError(new Error('request timed out'))).toBe(true);
+ // NOT transient: plain 500, permanent 4xx, caller aborts.
+ expect(isTransientNetworkEmbedError(new Error('500 internal server error'))).toBe(false);
+ expect(isTransientNetworkEmbedError(new Error('400 invalid input'))).toBe(false);
+ expect(isTransientNetworkEmbedError(new Error('The operation was aborted.'))).toBe(false);
+ expect(isTransientNetworkEmbedError(new Error('embed budget aborted'))).toBe(false);
+ });
+
+ test('backoff: plain bounded exponential with jitter, capped', async () => {
+ const { transientBackoffMs, TRANSIENT_NET_BASE_MS, TRANSIENT_NET_MAX_MS, RATE_LIMIT_JITTER } =
+ await import('../src/commands/embed.ts');
+ const mid = () => 0.5; // jitter multiplier = 1.0
+ expect(transientBackoffMs(0, mid)).toBe(TRANSIENT_NET_BASE_MS);
+ expect(transientBackoffMs(1, mid)).toBe(TRANSIENT_NET_BASE_MS * 2);
+ expect(transientBackoffMs(2, mid)).toBe(TRANSIENT_NET_BASE_MS * 4);
+ // Cap: attempt 10 would be 1024s uncapped.
+ expect(transientBackoffMs(10, mid)).toBe(TRANSIENT_NET_MAX_MS);
+ // Jitter bounds at the cap.
+ expect(transientBackoffMs(10, () => 0)).toBe(Math.floor(TRANSIENT_NET_MAX_MS * (1 - RATE_LIMIT_JITTER)));
+ expect(transientBackoffMs(10, () => 1)).toBe(Math.floor(TRANSIENT_NET_MAX_MS * (1 + RATE_LIMIT_JITTER)));
+ });
+
+ test('conn-reset retries then succeeds (no retry-after to parse)', async () => {
+ const { embedBatchWithBackoff } = await import('../src/commands/embed.ts');
+ let calls = 0;
+ embedBatchBehavior = async () => {
+ calls++;
+ if (calls === 1) {
+ const err = new Error('socket hang up');
+ (err as any).code = 'ECONNRESET';
+ throw err;
+ }
+ return [new Float32Array(1536)];
+ };
+ const result = await embedBatchWithBackoff(['x']);
+ expect(calls).toBe(2);
+ expect(result).toHaveLength(1);
+ }, 10_000);
+
+ test('caller-initiated abort during the transient sleep bubbles out (never retried)', async () => {
+ const { embedBatchWithBackoff } = await import('../src/commands/embed.ts');
+ const controller = new AbortController();
+ let calls = 0;
+ embedBatchBehavior = async () => {
+ calls++;
+ const err = new Error('connect timeout');
+ (err as any).code = 'UND_ERR_CONNECT_TIMEOUT';
+ throw err;
+ };
+ setTimeout(() => controller.abort(), 50);
+ const t0 = Date.now();
+ await expect(embedBatchWithBackoff(['x'], { abortSignal: controller.signal })).rejects.toThrow();
+ // One attempt, abort wakes the ~1s backoff sleep early, loop exits.
+ expect(calls).toBe(1);
+ expect(Date.now() - t0).toBeLessThan(600);
+ });
+
+ test('import-file path (#3374): a one-off conn reset no longer aborts the import', async () => {
+ const { importFromContent } = await import('../src/core/import-file.ts');
+ let calls = 0;
+ embedBatchBehavior = async (texts) => {
+ calls++;
+ if (calls === 1) {
+ const err = new Error('read ECONNRESET');
+ (err as any).code = 'ECONNRESET';
+ throw err;
+ }
+ return texts.map(() => new Float32Array(1536));
+ };
+ // Minimal working-DB mock: tx.putPage lands in a store the read-back
+ // guard can see; everything else resolves null via the Proxy default.
+ const pageStore = new Map<string, any>();
+ const tx = new Proxy({} as any, {
+ get(_, prop: string) {
+ if (prop === 'putPage') {
+ return async (slug: string, page: any) => { pageStore.set(slug, page); };
+ }
+ return () => Promise.resolve(null);
+ },
+ });
+ const engine = mockEngine({
+ getPage: async (slug: string) =>
+ pageStore.has(slug) ? { slug, ...pageStore.get(slug) } : null,
+ transaction: async (cb: (t: unknown) => Promise<unknown>) => cb(tx),
+ });
+ const res = await importFromContent(
+ engine,
+ 'notes/transient-net-test',
+ '# Transient\n\nSome body text long enough to produce a chunk for embedding.',
+ {},
+ );
+ // Pre-fix: bare embedBatch → the first ECONNRESET propagated and the
+ // import aborted. Post-fix: one retry, then the page lands.
+ expect(calls).toBe(2);
+ expect(pageStore.has('notes/transient-net-test')).toBe(true);
+ expect(res).toBeDefined();
+ }, 10_000);
+});
+
// ────────────────────────────────────────────────────────────────
// D5/D7: embedAllStale sourceId threading — invariant tests
// ────────────────────────────────────────────────────────────────
@@ -1061,3 +1182,44 @@ describe('embed --stale contextual-retrieval wrapping (#3507)', () => {
expect(restamps).toHaveLength(0);
});
});
+
+describe('#3796 — attempt-scaled 429 wait floors (rolling TPM window)', () => {
+ const mid = () => 0.5; // jitterFactor = 1 → deterministic
+
+ test('tiny provider hints get floored, and the floor escalates per attempt', async () => {
+ const { rateLimitDelayMs, RATE_LIMIT_ATTEMPT_FLOOR_MS } = await import('../src/commands/embed.ts');
+ // 'try again in 100ms' → hint = 600ms at mid jitter; every attempt floors above it.
+ const waits = [0, 1, 2, 3, 4].map((attempt) => rateLimitDelayMs('try again in 100ms', attempt, mid));
+ expect(waits).toEqual([...RATE_LIMIT_ATTEMPT_FLOOR_MS]);
+ // Strictly escalating ladder.
+ for (let i = 1; i < waits.length; i++) expect(waits[i]).toBeGreaterThan(waits[i - 1]);
+ });
+
+ test('a larger provider hint wins over the floor (Retry-After must be honored)', async () => {
+ const { rateLimitDelayMs, RATE_LIMIT_PAD_MS } = await import('../src/commands/embed.ts');
+ const hinted = 240_000 + RATE_LIMIT_PAD_MS;
+ for (const attempt of [0, 2, 4]) {
+ expect(rateLimitDelayMs('try again in 240s', attempt, mid)).toBe(hinted);
+ }
+ });
+
+ test('cumulative floored wait spans the rolling TPM minute even at worst-case jitter', async () => {
+ const { rateLimitDelayMs } = await import('../src/commands/embed.ts');
+ const low = () => 0; // jitterFactor = 1 - RATE_LIMIT_JITTER (worst case)
+ let total = 0;
+ for (let attempt = 0; attempt < 5; attempt++) {
+ total += rateLimitDelayMs('try again in 132ms', attempt, low);
+ }
+ // Pre-fix: 5 × ~442ms ≈ 2.2s — every retry burned inside the same TPM
+ // minute. Post-fix the ladder must span it.
+ expect(total).toBeGreaterThan(60_000);
+ });
+
+ test('attempts past the ladder clamp to the last floor', async () => {
+ const { rateLimitDelayMs, RATE_LIMIT_ATTEMPT_FLOOR_MS } = await import('../src/commands/embed.ts');
+ const last = RATE_LIMIT_ATTEMPT_FLOOR_MS[RATE_LIMIT_ATTEMPT_FLOOR_MS.length - 1];
+ expect(rateLimitDelayMs('429 slow down', 10, mid)).toBe(Math.max(last, rateLimitDelayMs('429 slow down', 4, mid)));
+ // Negative attempt (defensive) clamps to the first rung.
+ expect(rateLimitDelayMs('try again in 1ms', -1, mid)).toBe(RATE_LIMIT_ATTEMPT_FLOOR_MS[0]);
+ });
+});
diff --git a/test/embedding-pricing.test.ts b/test/embedding-pricing.test.ts
index 072aae29ea..731ea9c12b 100644
--- a/test/embedding-pricing.test.ts
+++ b/test/embedding-pricing.test.ts
@@ -106,6 +106,50 @@ describe('lookupEmbeddingPrice — azure-openai alias (#4032)', () => {
});
});
+describe('lookupEmbeddingPrice — nested gateway ids (#2504)', () => {
+ // Router providers (openrouter, generic gateways) wrap the upstream vendor
+ // in the model segment. The router bills the vendor's per-token rate, so
+ // the vendor row is the honest estimate on a miss.
+ test.each([
+ ['openrouter:openai/text-embedding-3-large', 0.13, 'openai:text-embedding-3-large'],
+ ['openrouter:voyage/voyage-4', 0.06, 'voyage:voyage-4'],
+ ['openrouter:mistral/mistral-embed', 0.10, 'mistral:mistral-embed'],
+ ])('%s falls back to the nested vendor row', (model, expected, key) => {
+ const r = lookupEmbeddingPrice(model as string);
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') {
+ expect(r.pricePerMTok).toBe(expected as number);
+ expect(r.key).toBe(key as string);
+ }
+ });
+
+ test('nested provider aliases still apply (router → azure-openai → openai)', () => {
+ const r = lookupEmbeddingPrice('openrouter:azure-openai/text-embedding-3-small');
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') expect(r.key).toBe('openai:text-embedding-3-small');
+ });
+
+ test('bare slash form assumes openai wrapper then unnests', () => {
+ const r = lookupEmbeddingPrice('openai/text-embedding-3-small');
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') expect(r.key).toBe('openai:text-embedding-3-small');
+ });
+
+ test('nested unknown vendor stays unknown (fail closed, never fabricate)', () => {
+ const r = lookupEmbeddingPrice('openrouter:madeup/model-9000');
+ expect(r.kind).toBe('unknown');
+ if (r.kind === 'unknown') {
+ expect(r.provider).toBe('openrouter');
+ expect(r.model).toBe('madeup/model-9000');
+ }
+ });
+
+ test('trailing/leading slash does not recurse into an empty key', () => {
+ expect(lookupEmbeddingPrice('openrouter:model-9000/').kind).toBe('unknown');
+ expect(lookupEmbeddingPrice('openrouter:/model-9000').kind).toBe('unknown');
+ });
+});
+
describe('EMBEDDING_PRICING — table integrity', () => {
test('all entries have pricePerMTok as a non-negative finite number', () => {
for (const [key, val] of Object.entries(EMBEDDING_PRICING)) {
@@ -134,3 +178,35 @@ describe('estimateCostFromChars', () => {
expect(c).toBeLessThan(3.8);
});
});
+
+// #4344 — hosted-recipe coverage gate: every embedding model the voyage
+// recipe offers as HOSTED must have a pricing row, so `gbrain upgrade`'s
+// cost estimate never says "unavailable" for a model we ship in the picker.
+// voyage-4-nano is the documented exception (open-weight, no hosted rate —
+// a fabricated 0 would under-estimate hosted-API users).
+describe('#4344 — every hosted voyage recipe model has a pricing entry', () => {
+ test('recipe models ⊆ pricing table (minus the open-weight exception)', async () => {
+ const { voyage } = await import('../src/core/ai/recipes/voyage.ts');
+ const OPEN_WEIGHT_EXCEPTIONS = new Set(['voyage-4-nano']);
+ const models: string[] = (voyage as any).touchpoints.embedding.models;
+ expect(models.length).toBeGreaterThan(0);
+ const missing = models
+ .filter((m) => !OPEN_WEIGHT_EXCEPTIONS.has(m))
+ .filter((m) => lookupEmbeddingPrice(`voyage:${m}`).kind !== 'known');
+ expect(missing).toEqual([]);
+ });
+
+ test.each([
+ ['voyage:voyage-3.5', 0.06],
+ ['voyage:voyage-3.5-lite', 0.02],
+ ['voyage:voyage-3-lite', 0.02],
+ ['voyage:voyage-code-3', 0.18],
+ ['voyage:voyage-finance-2', 0.12],
+ ['voyage:voyage-law-2', 0.12],
+ ['voyage:voyage-multimodal-3', 0.12],
+ ])('%s at $%d/MTok (docs.voyageai.com/docs/pricing, verified 2026-08-21)', (model, expected) => {
+ const r = lookupEmbeddingPrice(model);
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') expect(r.pricePerMTok).toBe(expected);
+ });
+});
diff --git a/test/enrich-cycle-phase.test.ts b/test/enrich-cycle-phase.test.ts
index 460c6cf0e7..dc4218ece6 100644
--- a/test/enrich-cycle-phase.test.ts
+++ b/test/enrich-cycle-phase.test.ts
@@ -97,4 +97,31 @@ describe('runPhaseEnrichThin', () => {
expect(r.details.max_cost_usd).toBe(0.5);
expect(r.details.max_total_cost_usd).toBe(5.0); // brain-wide default unchanged
});
+
+ test("#2504: max_cost_usd accepts 'off' (uncapped per-source; brain-wide still governs)", async () => {
+ // parseFloat('off') is NaN — the operator's explicit opt-out used to be
+ // silently replaced with the $1 default. Same off/unlimited/none spellings
+ // as `gbrain enrich --max-usd`.
+ await engine.setConfig('cycle.enrich_thin.enabled', 'true');
+ await engine.setConfig('cycle.enrich_thin.max_cost_usd', 'off');
+ const r = await runPhaseEnrichThin(engine, { dryRun: true });
+ expect(r.status).toBe('ok');
+ // Details report the operator's spelling, never Infinity→null.
+ expect(r.details.max_cost_usd).toBe('off');
+ expect(r.details.max_total_cost_usd).toBe(5.0);
+ });
+
+ test("#2504: both cost knobs 'off' still runs (fully uncapped tick)", async () => {
+ await engine.setConfig('cycle.enrich_thin.enabled', 'true');
+ await engine.setConfig('cycle.enrich_thin.max_cost_usd', 'off');
+ await engine.setConfig('cycle.enrich_thin.max_total_cost_usd', 'unlimited');
+ const r = await runPhaseEnrichThin(engine, { dryRun: true });
+ expect(r.status).toBe('ok');
+ expect(r.details.max_cost_usd).toBe('off');
+ expect(r.details.max_total_cost_usd).toBe('off');
+ // The per-source loop actually processed the default source (Infinity
+ // remaining never breaks the loop before work happens).
+ const perSource = r.details.per_source as Record<string, unknown>;
+ expect(perSource['default']).toBeTruthy();
+ });
});
diff --git a/test/entity-hints-cap.test.ts b/test/entity-hints-cap.test.ts
new file mode 100644
index 0000000000..bf1b2b74b5
--- /dev/null
+++ b/test/entity-hints-cap.test.ts
@@ -0,0 +1,68 @@
+/**
+ * #4209 — the entity-hints cap is NAMED and surfaced in the contract.
+ *
+ * The extractor prompt forwards only the first ENTITY_HINTS_CAP entity
+ * hints. Pre-fix that was an anonymous inline slice(0, 5): callers passing
+ * 20 hints had 15 silently eaten with no signal. Now the cap is exported,
+ * stated in the entity_hints param description, and every extract_facts
+ * envelope reports entity_hints_used / entity_hints_dropped.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { ENTITY_HINTS_CAP } from '../src/core/facts/extract.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const ctx = (): OperationContext =>
+ ({ engine, remote: false, sourceId: 'default' } as unknown as OperationContext);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('ENTITY_HINTS_CAP (#4209)', () => {
+ test('the cap is named, exported, and is the documented 5', () => {
+ expect(ENTITY_HINTS_CAP).toBe(5);
+ });
+
+ test('param description states the cap instead of hiding it', () => {
+ const desc = operationsByName.extract_facts!.params.entity_hints!.description ?? '';
+ expect(desc).toContain(String(ENTITY_HINTS_CAP));
+ expect(desc).toContain('entity_hints_used');
+ });
+
+ test('20 hints → used=5, dropped=15 on the response envelope', async () => {
+ // is_dream_generated short-circuits before any LLM call — deterministic,
+ // zero-key path that still exercises the cap accounting.
+ const r = await operationsByName.extract_facts!.handler(ctx(), {
+ turn_text: 'Alice moved to Berlin.',
+ entity_hints: Array.from({ length: 20 }, (_, i) => `people/p-${i}`),
+ is_dream_generated: true,
+ }) as { entity_hints_used: number; entity_hints_dropped: number; skipped: string };
+ expect(r.skipped).toBe('dream_generated');
+ expect(r.entity_hints_used).toBe(5);
+ expect(r.entity_hints_dropped).toBe(15);
+ });
+
+ test('under-cap and absent hints report honest zeros', async () => {
+ const withThree = await operationsByName.extract_facts!.handler(ctx(), {
+ turn_text: 'x', entity_hints: ['a', 'b', 'c'], is_dream_generated: true,
+ }) as { entity_hints_used: number; entity_hints_dropped: number };
+ expect(withThree.entity_hints_used).toBe(3);
+ expect(withThree.entity_hints_dropped).toBe(0);
+
+ const withNone = await operationsByName.extract_facts!.handler(ctx(), {
+ turn_text: 'x', is_dream_generated: true,
+ }) as { entity_hints_used: number; entity_hints_dropped: number };
+ expect(withNone.entity_hints_used).toBe(0);
+ expect(withNone.entity_hints_dropped).toBe(0);
+ });
+});
diff --git a/test/entity-identity.test.ts b/test/entity-identity.test.ts
new file mode 100644
index 0000000000..5d5e12f398
--- /dev/null
+++ b/test/entity-identity.test.ts
@@ -0,0 +1,356 @@
+/**
+ * #4224 — cross-source entity identity (federation v1).
+ *
+ * Covers: the v137 entity_identities migration, the manual-only helpers
+ * (link/unlink/list, identity key = (source_id, slug)), the three ops
+ * (localOnly writes, source-scoped list), and the flag-gated retrieval
+ * union on get_links/get_backlinks (default OFF; never widens a federated
+ * caller's grant).
+ *
+ * PGLite in-memory. Engine parity comes free: every helper goes through
+ * engine.executeRaw with ONE SQL text (no per-engine SQL) — see also the
+ * DATABASE_URL-gated check in test/e2e/engine-parity.test.ts.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ linkEntityIdentity,
+ unlinkEntityIdentity,
+ listEntityIdentities,
+ unionLinksAcrossIdentity,
+ isIdentityUnionEnabled,
+ validateEntityId,
+ ENTITY_IDENTITY_UNION_CONFIG_KEY,
+} from '../src/core/entity-identity.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+const localCtx = (over: Partial<OperationContext> = {}): OperationContext =>
+ ({ engine, remote: false, ...over } as unknown as OperationContext);
+const remoteCtx = (over: Partial<OperationContext> = {}): OperationContext =>
+ ({ engine, remote: true, ...over } as unknown as OperationContext);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ for (const t of ['entity_identities', 'content_chunks', 'links', 'tags', 'timeline_entries', 'page_versions', 'pages']) {
+ await (engine as unknown as { db: { exec(q: string): Promise<unknown> } }).db.exec(`DELETE FROM ${t}`);
+ }
+ await engine.unsetConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY);
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('team-brain', 'team-brain', '{}'::jsonb)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+});
+
+async function seedTwoSourceAlice() {
+ await engine.putPage('people/alice', {
+ type: 'person', title: 'Alice', compiled_truth: 'wiki alice', timeline: '',
+ }, { sourceId: 'default' });
+ await engine.putPage('people/alice-chen', {
+ type: 'person', title: 'Alice Chen', compiled_truth: 'team alice', timeline: '',
+ }, { sourceId: 'team-brain' });
+}
+
+describe('entity_identities migration (v137)', () => {
+ test('table exists with the documented shape', async () => {
+ const rows = await engine.executeRaw<{ column_name: string }>(
+ `SELECT column_name FROM information_schema.columns WHERE table_name = 'entity_identities'`,
+ );
+ const cols = new Set(rows.map(r => r.column_name));
+ for (const c of ['entity_id', 'source_id', 'page_id', 'confidence', 'established_by', 'established_at', 'canonical']) {
+ expect(cols.has(c)).toBe(true);
+ }
+ });
+});
+
+describe('identity helpers — (source_id, slug) is the key', () => {
+ beforeEach(seedTwoSourceAlice);
+
+ test('link + list round-trip across two sources', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain', canonical: true });
+
+ const members = await listEntityIdentities(engine, { entityId: 'alice-chen' });
+ expect(members).toHaveLength(2);
+ // Canonical sorts first.
+ expect(members[0]!.slug).toBe('people/alice-chen');
+ expect(members[0]!.canonical).toBe(true);
+ expect(members[0]!.source_id).toBe('team-brain');
+ expect(members[1]!.slug).toBe('people/alice');
+ expect(members[1]!.established_by).toBe('manual');
+ expect(members[1]!.confidence).toBe(1);
+ });
+
+ test('linking a missing page throws (identity key is (source_id, slug))', async () => {
+ await expect(
+ linkEntityIdentity(engine, { entityId: 'ghost', slug: 'people/alice', sourceId: 'team-brain' }),
+ ).rejects.toThrow(/page not found/);
+ });
+
+ test('re-linking MOVES the page to the new identity', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'someone-else', slug: 'people/alice', sourceId: 'default' });
+
+ expect(await listEntityIdentities(engine, { entityId: 'alice-chen' })).toHaveLength(0);
+ const moved = await listEntityIdentities(engine, { entityId: 'someone-else' });
+ expect(moved).toHaveLength(1);
+ expect(moved[0]!.slug).toBe('people/alice');
+ });
+
+ test('a new canonical demotes the previous one (at most one per group)', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default', canonical: true });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain', canonical: true });
+
+ const members = await listEntityIdentities(engine, { entityId: 'alice-chen' });
+ expect(members.filter(m => m.canonical)).toHaveLength(1);
+ expect(members.find(m => m.canonical)!.slug).toBe('people/alice-chen');
+ });
+
+ test('unlink removes exactly the (source_id, slug) member', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain' });
+
+ expect(await unlinkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' })).toBe(true);
+ expect(await unlinkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' })).toBe(false);
+ const members = await listEntityIdentities(engine, { entityId: 'alice-chen' });
+ expect(members).toHaveLength(1);
+ expect(members[0]!.source_id).toBe('team-brain');
+ });
+
+ test('list by member slug finds the whole group', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain' });
+
+ const members = await listEntityIdentities(engine, { slug: 'people/alice' });
+ expect(members).toHaveLength(2);
+ });
+
+ test('allowedSources restricts member visibility', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain' });
+
+ const members = await listEntityIdentities(engine, { entityId: 'alice-chen', allowedSources: ['default'] });
+ expect(members).toHaveLength(1);
+ expect(members[0]!.source_id).toBe('default');
+ });
+
+ test('validateEntityId rejects junk handles', () => {
+ expect(() => validateEntityId('has space')).toThrow(/invalid entity_id/);
+ expect(() => validateEntityId('')).toThrow(/invalid entity_id/);
+ expect(() => validateEntityId('UPPER')).toThrow(/invalid entity_id/);
+ expect(validateEntityId('alice-chen')).toBe('alice-chen');
+ });
+});
+
+describe('entity identity ops (v1 manual-only)', () => {
+ beforeEach(seedTwoSourceAlice);
+
+ test('write ops are localOnly; list is not', () => {
+ expect(operationsByName.entity_identity_link!.localOnly).toBe(true);
+ expect(operationsByName.entity_identity_unlink!.localOnly).toBe(true);
+ expect(operationsByName.entity_identity_list!.localOnly).toBeUndefined();
+ expect(operationsByName.entity_identity_link!.scope).toBe('write');
+ expect(operationsByName.entity_identity_list!.scope).toBe('read');
+ });
+
+ test('link + list + unlink through the op handlers', async () => {
+ await operationsByName.entity_identity_link!.handler(localCtx(), {
+ entity_id: 'alice-chen', slug: 'people/alice', source_id: 'default',
+ });
+ await operationsByName.entity_identity_link!.handler(localCtx(), {
+ entity_id: 'alice-chen', slug: 'people/alice-chen', source_id: 'team-brain', canonical: true,
+ });
+
+ const listed = await operationsByName.entity_identity_list!.handler(localCtx(), {
+ entity_id: 'alice-chen',
+ }) as { identities: Array<{ entity_id: string; canonical: { slug: string } | null; members: unknown[] }> };
+ expect(listed.identities).toHaveLength(1);
+ expect(listed.identities[0]!.members).toHaveLength(2);
+ expect(listed.identities[0]!.canonical?.slug).toBe('people/alice-chen');
+
+ const un = await operationsByName.entity_identity_unlink!.handler(localCtx(), {
+ entity_id: 'alice-chen', slug: 'people/alice', source_id: 'default',
+ }) as { unlinked: boolean };
+ expect(un.unlinked).toBe(true);
+ });
+
+ test('remote federated caller only sees granted sources in list', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain' });
+
+ const listed = await operationsByName.entity_identity_list!.handler(
+ remoteCtx({ auth: { allowedSources: ['default'] } as never }),
+ { entity_id: 'alice-chen' },
+ ) as { identities: Array<{ members: Array<{ source_id: string }> }> };
+ expect(listed.identities).toHaveLength(1);
+ expect(listed.identities[0]!.members).toHaveLength(1);
+ expect(listed.identities[0]!.members[0]!.source_id).toBe('default');
+ });
+});
+
+describe('flag-gated retrieval union (#4224 v1: link read ops)', () => {
+ beforeEach(async () => {
+ await seedTwoSourceAlice();
+ // Give each alice an outgoing edge in her own source.
+ await engine.putPage('companies/acme', {
+ type: 'company', title: 'Acme', compiled_truth: 'acme', timeline: '',
+ }, { sourceId: 'default' });
+ await engine.putPage('companies/widget-co', {
+ type: 'company', title: 'Widget Co', compiled_truth: 'widget', timeline: '',
+ }, { sourceId: 'team-brain' });
+ await engine.addLinksBatch([
+ { from_slug: 'people/alice', to_slug: 'companies/acme', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'people/alice-chen', to_slug: 'companies/widget-co', link_source: 'manual', from_source_id: 'team-brain', to_source_id: 'team-brain' },
+ ]);
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice-chen', slug: 'people/alice-chen', sourceId: 'team-brain' });
+ });
+
+ test('flag defaults OFF — get_links returns only the page\'s own edges', async () => {
+ expect(await isIdentityUnionEnabled(engine)).toBe(false);
+ const links = await operationsByName.get_links!.handler(localCtx(), { slug: 'people/alice' }) as Array<{ to_slug: string }>;
+ expect(links.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(false);
+ });
+
+ test('flag ON — get_links unions co-member edges (dedup\'d)', async () => {
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ expect(await isIdentityUnionEnabled(engine)).toBe(true);
+ const links = await operationsByName.get_links!.handler(localCtx(), { slug: 'people/alice' }) as Array<{ to_slug: string }>;
+ expect(links.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(true);
+ });
+
+ test('union never widens a federated caller\'s grant', async () => {
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ const links = await operationsByName.get_links!.handler(
+ remoteCtx({ auth: { allowedSources: ['default'] } as never }),
+ { slug: 'people/alice' },
+ ) as Array<{ to_slug: string }>;
+ expect(links.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(false);
+ });
+
+ test('unionLinksAcrossIdentity is a pure pass-through for non-members', async () => {
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ const base = await engine.getLinks('companies/acme', { sourceId: 'default' });
+ const out = await unionLinksAcrossIdentity(engine, 'companies/acme', base, 'out');
+ expect(out).toEqual(base);
+ });
+
+ test('get_backlinks unions incoming edges when flag ON', async () => {
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ // Backlinks of acme: from people/alice. Link widget-co's identity? Instead:
+ // union on the entity pages themselves — backlinks TO alice from a note.
+ await engine.putPage('notes/n1', { type: 'note', title: 'N1', compiled_truth: 'n', timeline: '' }, { sourceId: 'default' });
+ await engine.putPage('notes/n2', { type: 'note', title: 'N2', compiled_truth: 'n', timeline: '' }, { sourceId: 'team-brain' });
+ await engine.addLinksBatch([
+ { from_slug: 'notes/n1', to_slug: 'people/alice', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'notes/n2', to_slug: 'people/alice-chen', link_source: 'manual', from_source_id: 'team-brain', to_source_id: 'team-brain' },
+ ]);
+ const backs = await operationsByName.get_backlinks!.handler(localCtx(), { slug: 'people/alice' }) as Array<{ from_slug: string }>;
+ expect(backs.some(l => l.from_slug === 'notes/n1')).toBe(true);
+ expect(backs.some(l => l.from_slug === 'notes/n2')).toBe(true);
+ });
+});
+
+describe('#4224 review — the identity key is (source_id, slug) in the union too', () => {
+ // SAME slug in two sources: `people/alice` exists in BOTH default and
+ // team-brain, each with its own outgoing edge.
+ beforeEach(async () => {
+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');
+ await engine.putPage('people/alice', {
+ type: 'person', title: 'Alice (wiki)', compiled_truth: 'wiki alice', timeline: '',
+ }, { sourceId: 'default' });
+ await engine.putPage('people/alice', {
+ type: 'person', title: 'Alice (team)', compiled_truth: 'team alice', timeline: '',
+ }, { sourceId: 'team-brain' });
+ await engine.putPage('companies/acme', {
+ type: 'company', title: 'Acme', compiled_truth: 'acme', timeline: '',
+ }, { sourceId: 'default' });
+ await engine.putPage('companies/widget-co', {
+ type: 'company', title: 'Widget Co', compiled_truth: 'widget', timeline: '',
+ }, { sourceId: 'team-brain' });
+ await engine.addLinksBatch([
+ { from_slug: 'people/alice', to_slug: 'companies/acme', link_source: 'manual', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'people/alice', to_slug: 'companies/widget-co', link_source: 'manual', from_source_id: 'team-brain', to_source_id: 'team-brain' },
+ ]);
+ });
+
+ test('same-slug co-member in ANOTHER source IS unioned (only the base pair is excluded)', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alice', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alice', sourceId: 'team-brain' });
+
+ // Helper-level: base = (default, people/alice); the team-brain member
+ // shares the slug but is a REAL co-member — pre-fix `m.slug !== slug`
+ // dropped it and its edges never merged.
+ const base = await engine.getLinks('people/alice', { sourceId: 'default' });
+ const out = await unionLinksAcrossIdentity(engine, 'people/alice', base, 'out', { sourceId: 'default' });
+ expect(out.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ expect(out.some(l => l.to_slug === 'companies/widget-co')).toBe(true);
+
+ // Op-level: the scalar ctx scope threads through as the base source.
+ const links = await operationsByName.get_links!.handler(
+ localCtx({ sourceId: 'default' }), { slug: 'people/alice' },
+ ) as Array<{ to_slug: string }>;
+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(true);
+ });
+
+ test('NON-member base page with a same-slug member elsewhere is NOT unioned', async () => {
+ // Only the TEAM alice is a member, grouped with a third page that has
+ // its own edge. The default alice is NOT a member.
+ await engine.putPage('people/alicia', {
+ type: 'person', title: 'Alicia', compiled_truth: 'alicia', timeline: '',
+ }, { sourceId: 'team-brain' });
+ await engine.addLinksBatch([
+ { from_slug: 'people/alicia', to_slug: 'companies/widget-co', link_source: 'manual', from_source_id: 'team-brain', to_source_id: 'team-brain' },
+ ]);
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alice', sourceId: 'team-brain' });
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alicia', sourceId: 'team-brain' });
+
+ // Pre-fix the unscoped slug sub-select matched the TEAM alice's group and
+ // unioned foreign edges into a read of the (default) NON-member page.
+ const base = await engine.getLinks('people/alice', { sourceId: 'default' });
+ const out = await unionLinksAcrossIdentity(engine, 'people/alice', base, 'out', { sourceId: 'default' });
+ expect(out).toEqual(base);
+
+ const links = await operationsByName.get_links!.handler(
+ localCtx({ sourceId: 'default' }), { slug: 'people/alice' },
+ ) as Array<{ to_slug: string }>;
+ expect(links.some(l => l.to_slug === 'companies/acme')).toBe(true);
+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(false);
+ });
+
+ test('listEntityIdentities slugSourceId pins group resolution to the (slug, source) pair', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alice', sourceId: 'team-brain' });
+ // Unscoped slug lookup still finds the group (trusted cross-source view)…
+ expect(await listEntityIdentities(engine, { slug: 'people/alice' })).toHaveLength(1);
+ // …but the source-scoped lookup only matches the member pair.
+ expect(await listEntityIdentities(engine, { slug: 'people/alice', slugSourceId: 'default' })).toHaveLength(0);
+ expect(await listEntityIdentities(engine, { slug: 'people/alice', slugSourceId: 'team-brain' })).toHaveLength(1);
+ });
+
+ test('without slugSourceId, the seed sub-select is confined to allowedSources', async () => {
+ await linkEntityIdentity(engine, { entityId: 'alice', slug: 'people/alice', sourceId: 'team-brain' });
+ // A grant that cannot see team-brain must not discover the group through
+ // the team-brain seed page.
+ expect(await listEntityIdentities(engine, {
+ slug: 'people/alice', allowedSources: ['default'],
+ })).toHaveLength(0);
+ expect(await listEntityIdentities(engine, {
+ slug: 'people/alice', allowedSources: ['team-brain'],
+ })).toHaveLength(1);
+ });
+});
diff --git a/test/eval-contradictions-run-health.test.ts b/test/eval-contradictions-run-health.test.ts
new file mode 100644
index 0000000000..98f43bc758
--- /dev/null
+++ b/test/eval-contradictions-run-health.test.ts
@@ -0,0 +1,178 @@
+/**
+ * #3889 — all-errors probe run must not render as a clean "0 contradictions".
+ *
+ * Covers the shared honesty predicate (run-health.ts), the doctor check body
+ * for the zero-total case, and the CLI summary builder (unknown bucket
+ * printed, judge-failed banner + Wilson-CI suppression).
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ assessRunHealth,
+ inferVerdictSum,
+ isJudgeFailedRun,
+ sumVerdicts,
+ zeroTotalContradictionsCheck,
+} from '../src/core/eval-contradictions/run-health.ts';
+import { buildRunSummaryLines } from '../src/commands/eval-suspected-contradictions.ts';
+import type { ProbeReport } from '../src/core/eval-contradictions/types.ts';
+
+function mkReport(over: Partial<ProbeReport> = {}): ProbeReport {
+ return {
+ schema_version: 1,
+ run_id: 'r1',
+ judge_model: 'anthropic:claude-haiku-4-5',
+ prompt_version: '2',
+ truncation_policy: '1500-chars-utf8-safe',
+ top_k: 5,
+ sampling: 'deterministic',
+ queries_evaluated: 3,
+ queries_with_contradiction: 0,
+ queries_with_any_finding: 0,
+ total_contradictions_flagged: 0,
+ verdict_breakdown: {
+ no_contradiction: 0,
+ contradiction: 0,
+ temporal_supersession: 0,
+ temporal_regression: 0,
+ temporal_evolution: 0,
+ negation_artifact: 0,
+ },
+ calibration: {
+ queries_total: 3,
+ queries_judged_clean: 3,
+ queries_with_contradiction: 0,
+ wilson_ci_95: { point: 0, lower: 0, upper: 0.56 },
+ },
+ judge_errors: { parse_fail: 0, refusal: 0, timeout: 0, http_5xx: 0, unknown: 0, total: 0, note: 'errors are counted' },
+ cost_usd: { judge: 0, embedding: 0, total: 0, estimate_note: 'soft ceiling' },
+ cache: { hits: 0, misses: 0, hit_rate: 0 },
+ duration_ms: 12,
+ source_tier_breakdown: { curated_vs_curated: 0, curated_vs_bulk: 0, bulk_vs_bulk: 0, other: 0 },
+ per_query: [],
+ hot_pages: [],
+ ...over,
+ };
+}
+
+describe('run-health predicate (#3889)', () => {
+ test('isJudgeFailedRun: zero verdicts + errors => failed', () => {
+ expect(isJudgeFailedRun(0, 5)).toBe(true);
+ expect(isJudgeFailedRun(0, 0)).toBe(false); // nothing attempted: not failed
+ expect(isJudgeFailedRun(3, 5)).toBe(false); // partial errors: not failed
+ });
+
+ test('sumVerdicts tolerates partial/absent breakdowns', () => {
+ expect(sumVerdicts(undefined)).toBe(0);
+ expect(sumVerdicts(null)).toBe(0);
+ expect(sumVerdicts({ contradiction: 2, no_contradiction: 3 })).toBe(5);
+ });
+
+ test('inferVerdictSum falls back to per_query pairs on pre-v0.34 rows', () => {
+ // Old rows lack verdict_breakdown; pairs_judged + pairs_cache_hit is the
+ // same denominator.
+ expect(inferVerdictSum({
+ per_query: [
+ { pairs_judged: 2, pairs_cache_hit: 1 },
+ { pairs_judged: 0, pairs_cache_hit: 0 },
+ ],
+ })).toBe(3);
+ expect(inferVerdictSum({})).toBe(0);
+ expect(inferVerdictSum(undefined)).toBe(0);
+ });
+
+ test('assessRunHealth: all-errors run flags judge_failed with error rate 1', () => {
+ const h = assessRunHealth({
+ judge_errors_total: 7,
+ report_json: { verdict_breakdown: { no_contradiction: 0, contradiction: 0 } },
+ });
+ expect(h.judge_failed).toBe(true);
+ expect(h.error_rate).toBe(1);
+ });
+
+ test('assessRunHealth: partial errors do NOT flag judge_failed', () => {
+ const h = assessRunHealth({
+ judge_errors_total: 1,
+ report_json: { verdict_breakdown: { no_contradiction: 9, contradiction: 0 } },
+ });
+ expect(h.judge_failed).toBe(false);
+ expect(h.error_rate).toBeCloseTo(0.1);
+ });
+});
+
+describe('doctor zero-total check body (#3889)', () => {
+ test('all-errors run => warn, not ok', () => {
+ const check = zeroTotalContradictionsCheck({
+ ran_at: '2026-08-20T10:00:00Z',
+ queries_evaluated: 5,
+ judge_errors_total: 12,
+ report_json: { verdict_breakdown: { no_contradiction: 0, contradiction: 0 } },
+ });
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('not trustworthy');
+ expect(check.message).toContain('12');
+ });
+
+ test('clean zero-finding run stays ok', () => {
+ const check = zeroTotalContradictionsCheck({
+ ran_at: '2026-08-20T10:00:00Z',
+ queries_evaluated: 5,
+ judge_errors_total: 0,
+ report_json: { verdict_breakdown: { no_contradiction: 10, contradiction: 0 } },
+ });
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('no suspected contradictions');
+ });
+
+ test('zero-finding run with SOME errors stays ok but reports the error rate', () => {
+ const check = zeroTotalContradictionsCheck({
+ ran_at: '2026-08-20T10:00:00Z',
+ queries_evaluated: 5,
+ judge_errors_total: 2,
+ report_json: { verdict_breakdown: { no_contradiction: 8, contradiction: 0 } },
+ });
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('judge errors: 2');
+ expect(check.message).toContain('20%');
+ });
+});
+
+describe('CLI summary builder (#3889)', () => {
+ test('judge errors line prints all five buckets (unknown included) so they sum to total', () => {
+ const r = mkReport({
+ judge_errors: { parse_fail: 1, refusal: 0, timeout: 1, http_5xx: 0, unknown: 2, total: 4, note: 'counted' },
+ verdict_breakdown: {
+ no_contradiction: 3, contradiction: 0, temporal_supersession: 0,
+ temporal_regression: 0, temporal_evolution: 0, negation_artifact: 0,
+ },
+ });
+ const line = buildRunSummaryLines(r, false).find((l) => l.includes('Judge errors:'));
+ expect(line).toBeTruthy();
+ expect(line).toContain('unknown=2');
+ // Buckets sum to total: extract every printed bucket count and compare.
+ const buckets = [...line!.matchAll(/(?:parse_fail|refusal|timeout|http_5xx|unknown)=(\d+)/g)]
+ .map((m) => Number(m[1]));
+ expect(buckets.length).toBe(5);
+ expect(buckets.reduce((a, b) => a + b, 0)).toBe(4);
+ });
+
+ test('judge_failed run: banner shown, 0/N headline and Wilson CI suppressed', () => {
+ const r = mkReport({
+ run_status: 'judge_failed',
+ judge_errors: { parse_fail: 0, refusal: 0, timeout: 0, http_5xx: 6, unknown: 0, total: 6, note: 'counted' },
+ });
+ const lines = buildRunSummaryLines(r, false);
+ const text = lines.join('\n');
+ expect(text).toContain('JUDGE FAILED');
+ expect(text).toContain('unknown (judge produced no verdicts)');
+ expect(text).not.toContain('Wilson CI');
+ expect(text).not.toContain('0 / 3');
+ });
+
+ test('ok run keeps the headline + Wilson CI', () => {
+ const r = mkReport({ run_status: 'ok' });
+ const text = buildRunSummaryLines(r, false).join('\n');
+ expect(text).toContain('Queries with >=1 contradiction: 0 / 3');
+ expect(text).toContain('Wilson CI 95%');
+ });
+});
diff --git a/test/eval-contradictions-runner.test.ts b/test/eval-contradictions-runner.test.ts
index 11c4c0e1d2..07d6d34afd 100644
--- a/test/eval-contradictions-runner.test.ts
+++ b/test/eval-contradictions-runner.test.ts
@@ -507,6 +507,75 @@ describe('runContradictionProbe', () => {
expect(out.report.verdict_breakdown.no_contradiction).toBe(1);
});
+ // ---- #3889: all-errors run stamps run_status='judge_failed' ----
+ // Without the stamp, a run where every judge call threw renders as
+ // "0 contradictions" — an untrustworthy green.
+
+ test('#3889: every judge call throwing => run_status=judge_failed', async () => {
+ const idA = await seedPage('a/allfail', 'A');
+ const idB = await seedPage('b/allfail', 'B');
+ const out = await runContradictionProbe({
+ engine,
+ queries: ['q-allfail'],
+ judgeFn: stubJudge({ throwOn: () => true }),
+ searchFn: async () => [
+ mkResult('a/allfail', idA, 1, 'chunk a'),
+ mkResult('b/allfail', idB, 2, 'chunk b'),
+ ],
+ budgetUsd: 5,
+ noCache: true,
+ });
+ expect(out.report.judge_errors.total).toBe(1);
+ expect(out.report.run_status).toBe('judge_failed');
+ });
+
+ test('#3889: clean run (and zero-pair run) stamps run_status=ok', async () => {
+ const idA = await seedPage('a/ok3889', 'A');
+ const idB = await seedPage('b/ok3889', 'B');
+ const clean = await runContradictionProbe({
+ engine,
+ queries: ['q-ok3889'],
+ judgeFn: stubJudge({ verdict: 'no_contradiction' }),
+ searchFn: async () => [
+ mkResult('a/ok3889', idA, 1, 'chunk a'),
+ mkResult('b/ok3889', idB, 2, 'chunk b'),
+ ],
+ budgetUsd: 5,
+ noCache: true,
+ });
+ expect(clean.report.run_status).toBe('ok');
+
+ // Zero pairs attempted (empty search): also 'ok' — nothing failed.
+ const empty = await runContradictionProbe({
+ engine,
+ queries: ['q-empty3889'],
+ judgeFn: stubJudge({}),
+ searchFn: async () => [],
+ budgetUsd: 5,
+ });
+ expect(empty.report.run_status).toBe('ok');
+ });
+
+ test('#3889: partial errors (some verdicts landed) stays run_status=ok', async () => {
+ const idA = await seedPage('a/part3889', 'A');
+ const idB = await seedPage('b/part3889', 'B');
+ const idC = await seedPage('c/part3889', 'C');
+ const out = await runContradictionProbe({
+ engine,
+ queries: ['q-part3889'],
+ judgeFn: stubJudge({ verdict: 'no_contradiction', throwOn: (i) => i === 0 }),
+ searchFn: async () => [
+ mkResult('a/part3889', idA, 1, 'a'),
+ mkResult('b/part3889', idB, 2, 'b'),
+ mkResult('c/part3889', idC, 3, 'c'),
+ ],
+ budgetUsd: 5,
+ noCache: true,
+ });
+ expect(out.report.judge_errors.total).toBe(1);
+ expect(out.report.run_status).toBe('ok');
+ });
+
// ---- Lane D: R5 regression — cache key tuple shape stays 5 fields ----
// Lane A1 bumped PROMPT_VERSION 1→2 (invalidates cache) but kept the key
// shape unchanged. Adding a 6th field would silently break every operator's
diff --git a/test/eval-synthesize-concepts-routing.test.ts b/test/eval-synthesize-concepts-routing.test.ts
new file mode 100644
index 0000000000..335c981b7a
--- /dev/null
+++ b/test/eval-synthesize-concepts-routing.test.ts
@@ -0,0 +1,118 @@
+/**
+ * #4198 — `gbrain eval synthesize-concepts` routing regression.
+ *
+ * Pre-fix there was NO dispatch branch for the subcommand: it fell through
+ * to the generic qrels eval and died with "Error: --qrels <path|json> is
+ * required", while the programmatic scaffold reported ok:true — a scripted
+ * caller could read "pass" from a command that evaluated nothing.
+ *
+ * Pins:
+ * 1. the CLI entry returns nonzero with an honest not_implemented envelope
+ * 2. --help exits 0 with a dedicated help text (not the qrels help)
+ * 3. subprocess smoke: the real CLI routes the subcommand to the scaffold
+ * (never the qrels flow) and propagates exit 1
+ * 4. source pin: both dispatch layers (cli.ts pre-engine + eval.ts
+ * re-entry) carry the branch, so neither refactor can silently hand the
+ * subcommand back to the qrels flow
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import {
+ runEvalSynthesizeConcepts,
+ runEvalSynthesizeConceptsCli,
+} from '../src/commands/eval-synthesize-concepts.ts';
+
+describe('CLI entry (unit)', () => {
+ test('--help exits 0 with dedicated help, no qrels text', async () => {
+ const lines: string[] = [];
+ const origLog = console.log;
+ console.log = (s: unknown) => {
+ lines.push(String(s));
+ };
+ try {
+ const code = await runEvalSynthesizeConceptsCli(['--help']);
+ expect(code).toBe(0);
+ } finally {
+ console.log = origLog;
+ }
+ const out = lines.join('\n');
+ expect(out).toContain('synthesize-concepts');
+ expect(out).toContain('NOT IMPLEMENTED');
+ expect(out).not.toContain('--qrels');
+ });
+
+ test('--json exits 1 with ok:false / status not_implemented', async () => {
+ const lines: string[] = [];
+ const origLog = console.log;
+ console.log = (s: unknown) => {
+ lines.push(String(s));
+ };
+ try {
+ const code = await runEvalSynthesizeConceptsCli([
+ '--json',
+ '--parity-baseline',
+ '/tmp/concepts',
+ '--sample',
+ '250',
+ ]);
+ expect(code).toBe(1);
+ } finally {
+ console.log = origLog;
+ }
+ const envelope = JSON.parse(lines.join('\n'));
+ expect(envelope.schema_version).toBe(1);
+ expect(envelope.ok).toBe(false);
+ expect(envelope.status).toBe('not_implemented');
+ expect(envelope.details.parity_baseline_path).toBe('/tmp/concepts');
+ expect(envelope.details.sample_size).toBe(250);
+ });
+
+ test('programmatic scaffold never reads as a pass', async () => {
+ const r = await runEvalSynthesizeConcepts({});
+ expect(r.ok).toBe(false);
+ expect(r.status).toBe('not_implemented');
+ });
+});
+
+describe('dispatch-layer source pins (routing can’t regress silently)', () => {
+ test('cli.ts carries the dedicated pre-engine branch', () => {
+ const src = readFileSync(
+ fileURLToPath(new URL('../src/cli.ts', import.meta.url)),
+ 'utf8',
+ );
+ expect(src).toContain("command === 'eval' && args[0] === 'synthesize-concepts'");
+ expect(src).toContain('runEvalSynthesizeConceptsCli');
+ });
+
+ test('eval.ts re-entry branch precedes the generic qrels flow', () => {
+ const src = readFileSync(
+ fileURLToPath(new URL('../src/commands/eval.ts', import.meta.url)),
+ 'utf8',
+ );
+ const branchIdx = src.indexOf("sub === 'synthesize-concepts'");
+ const qrelsIdx = src.indexOf('--qrels <path|json> is required');
+ expect(branchIdx).toBeGreaterThan(-1);
+ expect(qrelsIdx).toBeGreaterThan(-1);
+ expect(branchIdx).toBeLessThan(qrelsIdx);
+ });
+});
+
+describe('subprocess smoke — end-to-end routing', () => {
+ test('eval synthesize-concepts --json exits 1 with the envelope, never the qrels error', () => {
+ const r = spawnSync('bun', ['src/cli.ts', 'eval', 'synthesize-concepts', '--json'], {
+ encoding: 'utf-8',
+ timeout: 60_000,
+ env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
+ });
+ expect(r.status).toBe(1);
+ expect(r.stderr).not.toContain('--qrels');
+ const jsonStart = r.stdout.indexOf('{');
+ expect(jsonStart).toBeGreaterThan(-1);
+ const envelope = JSON.parse(r.stdout.slice(jsonStart));
+ expect(envelope.ok).toBe(false);
+ expect(envelope.status).toBe('not_implemented');
+ }, 90_000);
+});
diff --git a/test/eval-v041_2-scaffolds.test.ts b/test/eval-v041_2-scaffolds.test.ts
index 3dbd7ecaad..5e619e3161 100644
--- a/test/eval-v041_2-scaffolds.test.ts
+++ b/test/eval-v041_2-scaffolds.test.ts
@@ -28,10 +28,12 @@ describe('v0.41 T11: eval command surfaces', () => {
expect(result.details.sample_size).toBe(500);
});
- test('runEvalSynthesizeConcepts returns stable schema_version=1 envelope', async () => {
+ test('runEvalSynthesizeConcepts returns an HONEST not_implemented envelope (#4198)', async () => {
const result = await runEvalSynthesizeConcepts({});
expect(result.schema_version).toBe(1);
- expect(result.status).toBe('not_yet_implemented');
+ // #4198: an eval that ran nothing must not read as a pass.
+ expect(result.ok).toBe(false);
+ expect(result.status).toBe('not_implemented');
});
test('runEvalSynthesizeConcepts preserves --parity-baseline + --sample', async () => {
@@ -58,12 +60,14 @@ describe('v0.41 T11: eval command surfaces', () => {
expect(result.details.repo_path).toBe('~/git/brain');
});
- test('all 3 commands include v0_41_1_followup pointer in details', async () => {
+ test('all 3 commands include a follow-up pointer in details', async () => {
const r1 = await runEvalExtractAtoms({});
const r2 = await runEvalSynthesizeConcepts({});
const r3 = await runEvalMarkdownGreenfield({});
expect(r1.details.v0_41_1_followup).toBeDefined();
- expect(r2.details.v0_41_1_followup).toBeDefined();
+ // #4198: synthesize-concepts renamed its pointer when the envelope
+ // flipped to the honest not_implemented shape.
+ expect(r2.details.planned).toBeDefined();
expect(r3.details.v0_41_1_followup).toBeDefined();
});
});
diff --git a/test/export-import-slug-roundtrip.test.ts b/test/export-import-slug-roundtrip.test.ts
new file mode 100644
index 0000000000..a63df1018c
--- /dev/null
+++ b/test/export-import-slug-roundtrip.test.ts
@@ -0,0 +1,116 @@
+/**
+ * #3772 — export → import slug round-trip.
+ *
+ * Export writes each page at `<slug>.md` with the stored frontmatter
+ * verbatim; import re-derives the slug via slugifyPath and rejects a
+ * frontmatter slug that differs from the path-derived one. When the stored
+ * slug is NOT a slugifyPath fixed point (legacy/hand-keyed slugs with case,
+ * apostrophes, accents…), the round-trip silently RE-KEYED the page:
+ * export people/Alice_Smith → import people/alice_smith (a different row).
+ *
+ * Fix: export stamps `slug:` into frontmatter when the slug isn't a fixed
+ * point; import accepts a frontmatter slug iff slugifyPath(slug) equals the
+ * path-derived slug (normalization-equivalent). Anti-spoof is preserved: a
+ * frontmatter slug claiming a DIFFERENT page still normalizes differently
+ * and still rejects.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExport } from '../src/commands/export.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+import { slugifyPath } from '../src/core/sync.ts';
+
+let source: PGLiteEngine;
+let target: PGLiteEngine;
+let outDir: string;
+
+// A slug that is NOT a slugifyPath fixed point. putPage's validateSlug
+// lowercases but preserves apostrophes and accents; slugifyPath strips both,
+// so this identity cannot be re-derived from its own export path.
+const LEGACY_SLUG = "people/ren\u00e9-o'brien";
+// A slug that IS a fixed point.
+const CLEAN_SLUG = 'people/bob-jones';
+
+beforeAll(async () => {
+ source = new PGLiteEngine();
+ await source.connect({});
+ await source.initSchema();
+ target = new PGLiteEngine();
+ await target.connect({});
+ await target.initSchema();
+ outDir = mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-'));
+
+ expect(slugifyPath(LEGACY_SLUG + '.md')).not.toBe(LEGACY_SLUG);
+ expect(slugifyPath(CLEAN_SLUG + '.md')).toBe(CLEAN_SLUG);
+
+ await source.putPage(LEGACY_SLUG, {
+ type: 'person',
+ title: 'Rene OBrien',
+ compiled_truth: '# Rene OBrien\n\nLegacy-keyed page whose slug predates slug normalization.',
+ frontmatter: { type: 'person', title: 'Rene OBrien' },
+ } as any, { sourceId: 'default' });
+ await source.putPage(CLEAN_SLUG, {
+ type: 'person',
+ title: 'Bob Jones',
+ compiled_truth: '# Bob Jones\n\nNormal page with an already-normalized slug.',
+ frontmatter: { type: 'person', title: 'Bob Jones' },
+ } as any, { sourceId: 'default' });
+
+ await runExport(source, ['--dir', outDir]);
+}, 60000);
+
+afterAll(async () => {
+ await source.disconnect();
+ await target.disconnect();
+ rmSync(outDir, { recursive: true, force: true });
+}, 30000);
+
+describe('export stamps the identity when slug is not a slugifyPath fixed point (#3772)', () => {
+ test('legacy slug file carries a frontmatter slug', () => {
+ const md = readFileSync(join(outDir, LEGACY_SLUG + '.md'), 'utf-8');
+ expect(md).toContain(`slug: ${LEGACY_SLUG}`);
+ });
+
+ test('fixed-point slug file does NOT grow a slug line (no diff noise)', () => {
+ const md = readFileSync(join(outDir, CLEAN_SLUG + '.md'), 'utf-8');
+ expect(md).not.toMatch(/^slug:/m);
+ });
+});
+
+describe('import accepts normalization-equivalent frontmatter slugs (#3772)', () => {
+ test('round-trip preserves the legacy slug', async () => {
+ const rel = LEGACY_SLUG + '.md';
+ const result = await importFromFile(target, join(outDir, rel), rel, { noEmbed: true });
+ expect(result.error).toBeUndefined();
+ expect(result.slug).toBe(LEGACY_SLUG);
+ const page = await target.getPage(LEGACY_SLUG, { sourceId: 'default' });
+ expect(page).not.toBeNull();
+ expect(page!.title).toBe('Rene OBrien');
+ // No re-keyed doppelganger under the normalized spelling.
+ const normalized = await target.getPage(slugifyPath(LEGACY_SLUG + '.md'), { sourceId: 'default' });
+ expect(normalized).toBeNull();
+ });
+
+ test('round-trip of the fixed-point slug still works', async () => {
+ const rel = CLEAN_SLUG + '.md';
+ const result = await importFromFile(target, join(outDir, rel), rel, { noEmbed: true });
+ expect(result.error).toBeUndefined();
+ expect(result.slug).toBe(CLEAN_SLUG);
+ });
+
+ test('anti-spoof preserved: a frontmatter slug for a DIFFERENT page still rejects', async () => {
+ const rel = 'people/eve.md';
+ mkdirSync(join(outDir, 'people'), { recursive: true });
+ writeFileSync(
+ join(outDir, rel),
+ '---\ntype: person\ntitle: Eve\nslug: people/mallory\n---\n\n# Eve\n',
+ );
+ const result = await importFromFile(target, join(outDir, rel), rel, { noEmbed: true });
+ expect(result.status).toBe('skipped');
+ expect(result.error).toContain('does not match path-derived slug');
+ });
+});
diff --git a/test/extract-atoms-provenance-links.test.ts b/test/extract-atoms-provenance-links.test.ts
new file mode 100644
index 0000000000..9f8c8879e0
--- /dev/null
+++ b/test/extract-atoms-provenance-links.test.ts
@@ -0,0 +1,94 @@
+/**
+ * #3961 — atom provenance edges in the link graph.
+ *
+ * extract_atoms writes each atom with `source_slug` frontmatter, but nothing
+ * ever materialized that lineage as a link row — `gbrain backlinks
+ * <source-page>` showed no trace of the atoms derived from it. The phase now
+ * accumulates (source-page → atom) LinkBatchInput rows during the atom loop
+ * (link_source='atom-provenance', both endpoints in the phase's source) and
+ * flushes them AFTER the completion-receipt flip. Transcript items are
+ * skipped — a transcript is a file, not a page, so there is no from-endpoint.
+ *
+ * PGLite round-trip with a stubbed chat gateway (no model calls).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.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();
+}, 120_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+const stubChat = (title: string) => async (_o: ChatOpts): Promise<ChatResult> => ({
+ text: `[{"title":"${title}","atom_type":"insight","body":"Enterprise buyers want tangible prototypes, not renders."}]`,
+ blocks: [{ type: 'text', text: '' }],
+ stopReason: 'end',
+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+});
+
+describe('atom provenance backlinks (#3961)', () => {
+ test('page-kind items get source-page → atom edges, visible as backlinks', async () => {
+ await engine.putPage('writings/essay-one', {
+ type: 'note', title: 'Essay One',
+ compiled_truth: 'A long essay with extractable claims.', timeline: '',
+ });
+
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [],
+ _pages: [{ slug: 'writings/essay-one', content: 'A long essay with extractable claims.', contentHash: 'feedbeeffeedbeef' }],
+ _chat: stubChat('Prototypes beat renders'),
+ });
+ expect(result.status).toBe('ok');
+ expect(result.details?.atoms_extracted).toBe(1);
+
+ // Outgoing edge on the source page, provenance-tagged.
+ const links = await engine.getLinks('writings/essay-one');
+ const provenance = links.filter(l => l.link_source === 'atom-provenance');
+ expect(provenance).toHaveLength(1);
+ expect(provenance[0]!.to_slug).toContain('prototypes-beat-renders');
+
+ // And the atom's backlinks point home.
+ const backs = await engine.getBacklinks(provenance[0]!.to_slug);
+ expect(backs.some(l => l.from_slug === 'writings/essay-one' && l.link_source === 'atom-provenance')).toBe(true);
+ });
+
+ test('re-running the same item upserts, never duplicates the edge', async () => {
+ // Same content hash re-run: deterministic atom slugs upsert; the batch
+ // write's ON CONFLICT dedupes the edge.
+ await runPhaseExtractAtoms(engine, {
+ _transcripts: [],
+ _pages: [{ slug: 'writings/essay-one', content: 'A long essay with extractable claims.', contentHash: 'feedbeeffeedbee2' }],
+ _chat: stubChat('Prototypes beat renders'),
+ });
+ const links = await engine.getLinks('writings/essay-one');
+ expect(links.filter(l => l.link_source === 'atom-provenance')).toHaveLength(1);
+ });
+
+ test('transcript items create NO provenance edges (files are not pages)', async () => {
+ const before = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM links WHERE link_source = 'atom-provenance'`,
+ );
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: '/fake/meeting.txt', content: 'transcript content here', contentHash: 'abc123def4567890' }],
+ _pages: [],
+ _chat: stubChat('Transcript atom'),
+ });
+ expect(result.status).toBe('ok');
+ const after = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM links WHERE link_source = 'atom-provenance'`,
+ );
+ expect(after[0]!.n).toBe(before[0]!.n);
+ });
+});
diff --git a/test/extract-by-mention-rebuild.test.ts b/test/extract-by-mention-rebuild.test.ts
new file mode 100644
index 0000000000..3d26594339
--- /dev/null
+++ b/test/extract-by-mention-rebuild.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #3674 — `gbrain extract links --by-mention --rebuild`.
+ *
+ * The by-mention write path is purely additive, so a mentions row outlives
+ * its own justification (body rewritten, entity deleted, tokenizer changed).
+ * --rebuild reconciles: per page, ONE transaction deletes the page's
+ * link_source='mentions' rows and re-inserts the current mention set.
+ * typed_ner rows whose target is still derivable survive (extract-ner owns
+ * their verbs; the mention scan cannot regenerate them); stale typed_ner
+ * rows (target no longer derivable) die with the rest.
+ *
+ * Hermetic PGLite, driven through runExtract like the CLI.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { setCliOptions } from '../src/core/cli-options.ts';
+
+let engine: PGLiteEngine;
+
+let stdoutBuffer: string[];
+let stderrBuffer: string[];
+let exitedWith: number | null;
+const origLog = console.log;
+const origErr = console.error;
+const origExit = process.exit;
+const origStdoutWrite = process.stdout.write.bind(process.stdout);
+const origStderrWrite = process.stderr.write.bind(process.stderr);
+
+function captureCli(): void {
+ stdoutBuffer = [];
+ stderrBuffer = [];
+ exitedWith = null;
+ console.log = (msg?: unknown) => { stdoutBuffer.push(typeof msg === 'string' ? msg : String(msg)); };
+ console.error = (msg?: unknown) => { stderrBuffer.push(typeof msg === 'string' ? msg : String(msg)); };
+ (process.stdout as unknown as { write: unknown }).write = ((chunk: unknown) => {
+ stdoutBuffer.push(typeof chunk === 'string' ? chunk : String(chunk));
+ return true;
+ }) as unknown as typeof process.stdout.write;
+ (process.stderr as unknown as { write: unknown }).write = ((chunk: unknown) => {
+ stderrBuffer.push(typeof chunk === 'string' ? chunk : String(chunk));
+ return true;
+ }) as unknown as typeof process.stderr.write;
+ (process as { exit: unknown }).exit = ((code?: number) => {
+ exitedWith = code ?? 0;
+ throw new Error(`__test_exit:${code ?? 0}`);
+ }) as unknown as typeof process.exit;
+}
+
+function restoreCli(): void {
+ console.log = origLog;
+ console.error = origErr;
+ (process.stdout as unknown as { write: unknown }).write = origStdoutWrite;
+ (process.stderr as unknown as { write: unknown }).write = origStderrWrite;
+ (process as { exit: unknown }).exit = origExit;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ setCliOptions({ quiet: false, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ restoreCli();
+}, 30_000);
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw('DELETE FROM op_checkpoints');
+ await engine.executeRaw('DELETE FROM pages');
+});
+
+async function seedEntities(): Promise<void> {
+ await engine.putPage('companies/acme', { type: 'company', title: 'Acme Corp', compiled_truth: 'acme body', timeline: '', frontmatter: {} });
+ await engine.putPage('people/alice', { type: 'person', title: 'Alice Example', compiled_truth: 'alice body', timeline: '', frontmatter: {} });
+}
+
+async function seedContentPage(slug: string, body: string): Promise<void> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter: {} }, { allowEmptyOverwrite: true });
+}
+
+async function runCli(args: string[]): Promise<void> {
+ captureCli();
+ try {
+ await runExtract(engine, args);
+ } catch (e) {
+ if (!(e instanceof Error && e.message.startsWith('__test_exit:'))) throw e;
+ } finally {
+ restoreCli();
+ }
+}
+
+async function mentionTargets(fromSlug: string): Promise<Array<{ to: string; kind: string | null }>> {
+ const rows = await engine.executeRaw<{ to_slug: string; link_kind: string | null }>(
+ `SELECT tp.slug AS to_slug, l.link_kind
+ FROM links l
+ JOIN pages fp ON fp.id = l.from_page_id
+ JOIN pages tp ON tp.id = l.to_page_id
+ WHERE fp.slug = $1 AND l.link_source = 'mentions'
+ ORDER BY tp.slug`,
+ [fromSlug],
+ );
+ return rows.map((r) => ({ to: r.to_slug, kind: r.link_kind }));
+}
+
+describe('extract links --by-mention --rebuild (#3674)', () => {
+ test('rebuild removes the stale mention the additive path leaves behind', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-1', 'We met with Acme Corp yesterday.');
+ await runCli(['links', '--by-mention', '--source', 'db']);
+ expect((await mentionTargets('writing/post-1')).map((t) => t.to)).toEqual(['companies/acme']);
+
+ // Body rewritten: now mentions Alice, no longer Acme.
+ await seedContentPage('writing/post-1', 'Alice Example joined the call.');
+
+ // The additive path accretes — the stale Acme row survives (the bug).
+ await runCli(['links', '--by-mention', '--source', 'db']);
+ expect((await mentionTargets('writing/post-1')).map((t) => t.to)).toEqual(
+ ['companies/acme', 'people/alice'],
+ );
+
+ // --rebuild reconciles: stale row dies, current mention stays.
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+ expect((await mentionTargets('writing/post-1')).map((t) => t.to)).toEqual(['people/alice']);
+ });
+
+ test('rebuild sweeps a page whose body no longer mentions anything', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-2', 'Acme Corp everywhere.');
+ await runCli(['links', '--by-mention', '--source', 'db']);
+ expect((await mentionTargets('writing/post-2')).length).toBe(1);
+
+ await seedContentPage('writing/post-2', 'Nothing to see here anymore.');
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+ expect(await mentionTargets('writing/post-2')).toEqual([]);
+ });
+
+ test('still-valid typed_ner rows survive; stale typed_ner rows die', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-3', 'Acme Corp and Alice Example.');
+ await runCli(['links', '--by-mention', '--source', 'db']);
+ // extract-ner style verb rows on the SAME link_source, keyed link_kind.
+ await engine.addLinksBatch([
+ { from_slug: 'writing/post-3', to_slug: 'people/alice', link_type: 'works_at', link_source: 'mentions', link_kind: 'typed_ner', context: '', from_source_id: 'default', to_source_id: 'default' },
+ { from_slug: 'writing/post-3', to_slug: 'companies/acme', link_type: 'invested_in', link_source: 'mentions', link_kind: 'typed_ner', context: '', from_source_id: 'default', to_source_id: 'default' },
+ ]);
+
+ // Body rewritten: Alice still mentioned, Acme gone.
+ await seedContentPage('writing/post-3', 'Alice Example runs the show now.');
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+
+ const rows = await mentionTargets('writing/post-3');
+ // Alice: plain mention re-inserted + typed_ner verb row preserved.
+ expect(rows.filter((r) => r.to === 'people/alice' && r.kind === 'typed_ner').length).toBe(1);
+ expect(rows.filter((r) => r.to === 'people/alice' && r.kind !== 'typed_ner').length).toBe(1);
+ // Acme: both the plain row AND the stale typed_ner row are gone.
+ expect(rows.filter((r) => r.to === 'companies/acme')).toEqual([]);
+ });
+
+ test('other link_sources are untouched by the rebuild sweep', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-4', 'No entities named in the new body.');
+ await engine.addLinksBatch([
+ { from_slug: 'writing/post-4', to_slug: 'companies/acme', link_type: 'references', link_source: 'markdown', context: '', from_source_id: 'default', to_source_id: 'default' },
+ ]);
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+ const rows = await engine.executeRaw<{ c: string }>(
+ `SELECT COUNT(*)::text AS c FROM links WHERE link_source = 'markdown'`, [],
+ );
+ expect(Number(rows[0]!.c)).toBe(1);
+ });
+
+ test('--rebuild without --by-mention is rejected with exit 2', async () => {
+ await runCli(['links', '--rebuild', '--source', 'db']);
+ expect(exitedWith).toBe(2);
+ expect(stderrBuffer.join('\n')).toContain('--rebuild only applies to the by-mention pass');
+ });
+
+ test('summary reports removed count', async () => {
+ await seedEntities();
+ await seedContentPage('writing/post-5', 'Acme Corp again.');
+ await runCli(['links', '--by-mention', '--source', 'db']);
+ await seedContentPage('writing/post-5', 'no mentions now');
+ await runCli(['links', '--by-mention', '--rebuild', '--source', 'db']);
+ expect(stdoutBuffer.join('\n')).toMatch(/removed 1 stale mention link/);
+ });
+
+ test('removeLinksByPagesAndSource: empty page list is a no-op', async () => {
+ expect(await engine.removeLinksByPagesAndSource([], { linkSource: 'mentions' })).toBe(0);
+ });
+});
diff --git a/test/extract-db.test.ts b/test/extract-db.test.ts
index 97a9f8761f..617b770bfe 100644
--- a/test/extract-db.test.ts
+++ b/test/extract-db.test.ts
@@ -249,3 +249,66 @@ describe('gbrain extract all --source db', () => {
expect(entries.length).toBe(1);
});
});
+
+describe('--since ref-level prefilter (#4304)', () => {
+ beforeEach(truncateAll);
+
+ test('listAllPageRefs returns updated_at as a real Date', async () => {
+ await engine.putPage('people/alice', personPage('Alice'));
+ const refs = await engine.listAllPageRefs();
+ expect(refs.length).toBe(1);
+ expect(refs[0].updated_at instanceof Date).toBe(true);
+ expect(Number.isFinite(refs[0].updated_at.getTime())).toBe(true);
+ });
+
+ test('--since in the future skips every page WITHOUT a getPage round-trip', async () => {
+ await engine.putPage('people/alice', personPage('Alice'));
+ await engine.putPage('meetings/standup', meetingPage(
+ 'Standup', 'Attendees: [Alice](people/alice).',
+ ));
+
+ // Spy on getPage via an own-property shadow; delete restores the
+ // prototype method. Pre-#4304 the walk called getPage once per corpus
+ // page and applied --since AFTER the fetch.
+ const proto = Object.getPrototypeOf(engine) as { getPage: typeof engine.getPage };
+ const origGetPage = proto.getPage;
+ let getPageCalls = 0;
+ (engine as unknown as Record<string, unknown>).getPage = function (this: typeof engine, ...args: Parameters<typeof origGetPage>) {
+ getPageCalls++;
+ return origGetPage.apply(this, args);
+ };
+ try {
+ await runExtract(engine, ['links', '--source', 'db', '--since', '2999-01-01']);
+ } finally {
+ delete (engine as unknown as Record<string, unknown>).getPage;
+ }
+
+ expect(getPageCalls).toBe(0);
+ expect(await engine.getLinks('meetings/standup')).toHaveLength(0);
+ });
+
+ test('--since in the past still extracts (touched-since semantics on updated_at)', async () => {
+ await engine.putPage('people/alice', personPage('Alice'));
+ await engine.putPage('meetings/standup', meetingPage(
+ 'Standup', 'Attendees: [Alice](people/alice).',
+ ));
+
+ await runExtract(engine, ['links', '--source', 'db', '--since', '2000-01-01']);
+
+ expect((await engine.getLinks('meetings/standup')).length).toBeGreaterThanOrEqual(1);
+ });
+
+ test('timeline walk applies --since at the ref level too', async () => {
+ await engine.putPage('people/alice', {
+ type: 'person', title: 'Alice',
+ compiled_truth: '- **2026-01-15** | Test event',
+ timeline: '',
+ });
+
+ await runExtract(engine, ['timeline', '--source', 'db', '--since', '2999-01-01']);
+ expect(await engine.getTimeline('people/alice')).toHaveLength(0);
+
+ await runExtract(engine, ['timeline', '--source', 'db', '--since', '2000-01-01']);
+ expect((await engine.getTimeline('people/alice')).length).toBe(1);
+ });
+});
diff --git a/test/extract-facts-guard-rollup.test.ts b/test/extract-facts-guard-rollup.test.ts
new file mode 100644
index 0000000000..8fad6192ea
--- /dev/null
+++ b/test/extract-facts-guard-rollup.test.ts
@@ -0,0 +1,77 @@
+/**
+ * #3683 — the empty-fence guard's early return skipped the facts.fence
+ * rollup write entirely, so `halt_count` could never increment and doctor
+ * extract_health / extract status / extract --explain were structurally
+ * blind to a jammed phase (halt_rate pinned at 0 while the phase refused
+ * to reconcile).
+ *
+ * Stub-engine repro from the issue: no database, no filesystem. The guard
+ * path must book exactly one rollup UPSERT with halt_delta=1 /
+ * round_completed_delta=0; the healthy path books completed=1 / halt=0.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+interface CapturedCall {
+ sql: string;
+ params: unknown[];
+}
+
+function mkEngine(legacyCount: number): { calls: CapturedCall[]; engine: BrainEngine } {
+ const calls: CapturedCall[] = [];
+ const engine = {
+ async executeRaw(sql: string, params: unknown[] = []) {
+ calls.push({ sql: sql.trim().replace(/\s+/g, ' '), params });
+ if (/COUNT\(\*\) AS n/.test(sql)) return [{ n: String(legacyCount) }];
+ return [];
+ },
+ async getAllSlugs() { return []; },
+ async getPage() { return null; },
+ async deleteFactsForPage() { return { deleted: 0 }; },
+ async insertFacts() { return { inserted: 0, ids: [], warnings: [], deleted: 0 }; },
+ } as unknown as BrainEngine;
+ return { calls, engine };
+}
+
+function rollupCalls(calls: CapturedCall[]): CapturedCall[] {
+ return calls.filter((c) => c.sql.includes('INSERT INTO extract_rollup_7d'));
+}
+
+describe('extract_facts rollup telemetry (#3683)', () => {
+ test('guard-triggered run books halt_delta=1 for facts.fence', async () => {
+ const { calls, engine } = mkEngine(3);
+ const r = await runExtractFacts(engine, { slugs: [], sourceId: 'default' });
+ expect(r.guardTriggered).toBe(true);
+
+ const rollups = rollupCalls(calls);
+ expect(rollups.length).toBe(1);
+ // Param order: kind, source_id, day, cost, halts, evalFails, evalPasses, completed, failures.
+ const p = rollups[0]!.params;
+ expect(p[0]).toBe('facts.fence');
+ expect(p[1]).toBe('default');
+ expect(p[4]).toBe(1); // halt_delta
+ expect(p[7]).toBe(0); // round_completed_delta
+ });
+
+ test('healthy run books round_completed_delta=1, halt_delta=0', async () => {
+ const { calls, engine } = mkEngine(0);
+ const r = await runExtractFacts(engine, { slugs: [], sourceId: 'default' });
+ expect(r.guardTriggered).toBe(false);
+
+ const rollups = rollupCalls(calls);
+ expect(rollups.length).toBe(1);
+ const p = rollups[0]!.params;
+ expect(p[0]).toBe('facts.fence');
+ expect(p[4]).toBe(0); // halt_delta
+ expect(p[7]).toBe(1); // round_completed_delta
+ });
+
+ test('dry-run guard trigger books nothing', async () => {
+ const { calls, engine } = mkEngine(3);
+ const r = await runExtractFacts(engine, { slugs: [], sourceId: 'default', dryRun: true });
+ expect(r.guardTriggered).toBe(true);
+ expect(rollupCalls(calls).length).toBe(0);
+ });
+});
diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.ts
index f639f5a083..178f984ece 100644
--- a/test/extract-facts-phase.test.ts
+++ b/test/extract-facts-phase.test.ts
@@ -844,3 +844,233 @@ describe('runExtractFacts — empty-slugs guard (v0.36.x #1096 regression)', ()
expect(r.pagesScanned).toBe(1);
});
});
+
+describe('runExtractFacts — v0.46 (#3014) supersession transport + heal', () => {
+ // Row 1 struck + "superseded by #2"; row 2 the live superseding fact.
+ const SUPERSEDE_FENCE = FACT_FENCE(
+ `| 1 | ~~Will close by Q2~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #2 |
+| 2 | Closed in Q3 | fact | 1.0 | world | high | 2026-07-01 | | call | |`,
+ );
+
+ const readSupersessionCols = async () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const r = await (engine as any).db.query(
+ `SELECT row_num, superseded_by, expired_at FROM facts WHERE source_markdown_slug = 'people/deal' ORDER BY row_num`,
+ );
+ return r.rows as Array<{ row_num: number; superseded_by: number | null; expired_at: unknown }>;
+ };
+
+ const readIds = async (): Promise<number[]> => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const r = await (engine as any).db.query(
+ `SELECT id FROM facts WHERE source_markdown_slug = 'people/deal' ORDER BY row_num, id`,
+ );
+ return (r.rows as Array<{ id: number }>).map(x => Number(x.id));
+ };
+
+ test('reconcile transports superseded_by (resolved to the target row id) + expired_at', async () => {
+ await putPage('people/deal', SUPERSEDE_FENCE);
+ const r = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(r.factsInserted).toBe(2);
+ // The only expected warning is the NULL-embedding notice (#2821) — no
+ // supersession-resolution warning for a clean #2 reference.
+ expect(r.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+
+ const rows = await readSupersessionCols();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const ids = await (engine as any).db.query(
+ `SELECT row_num, id FROM facts WHERE source_markdown_slug = 'people/deal' ORDER BY row_num`,
+ );
+ const row2Id = ids.rows.find((x: { row_num: number; id: number }) => x.row_num === 2).id;
+ const row1 = rows.find(x => x.row_num === 1)!;
+ expect(Number(row1.superseded_by)).toBe(Number(row2Id));
+ expect(row1.expired_at).not.toBeNull();
+
+ const sup = await engine.listSupersessions('default');
+ expect(sup.some(s => s.superseded_by === Number(row2Id))).toBe(true);
+ });
+
+ test('idempotent: a second reconcile with the struck row already healed is a no-op', async () => {
+ await putPage('people/deal', SUPERSEDE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ const r2 = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ // Columns already match the fence-desired state → no drift → no churn.
+ expect(r2.factsInserted).toBe(0);
+ expect(r2.factsDeleted).toBe(0);
+ });
+
+ test('heal: a struck row with NULL supersession columns re-populates on re-reconcile', async () => {
+ await putPage('people/deal', SUPERSEDE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+
+ // Simulate the pre-#3014 mis-transport: struck row inserted with NULL
+ // columns. The fence text is unchanged, so only the supersession-column
+ // drift check can trigger a re-heal.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE facts SET superseded_by = NULL, expired_at = NULL WHERE source_markdown_slug = 'people/deal' AND row_num = 1`,
+ );
+ const drifted = (await readSupersessionCols()).find(x => x.row_num === 1)!;
+ expect(drifted.superseded_by).toBeNull();
+ expect(drifted.expired_at).toBeNull();
+
+ const healRun = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ // Drift detected → wipe+reinsert re-transports the columns.
+ expect(healRun.factsInserted).toBeGreaterThan(0);
+
+ const healed = (await readSupersessionCols()).find(x => x.row_num === 1)!;
+ expect(healed.superseded_by).not.toBeNull();
+ expect(healed.expired_at).not.toBeNull();
+ });
+
+ test('dangling reference (#N absent from fence) → warning, superseded_by NULL, expired_at set', async () => {
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Retired claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #9 |`,
+ ));
+ const r = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(r.warnings.some(w => w.includes('absent from the fence'))).toBe(true);
+
+ const row1 = (await readSupersessionCols()).find(x => x.row_num === 1)!;
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).not.toBeNull();
+ });
+
+ // A permanently-unresolvable reference must NOT re-drift every cycle. A
+ // naive drift term keyed off "the fence has a reference" vs "the DB
+ // resolved one" would see self / dangling / chain (which correctly stay
+ // NULL) drift forever — a full wipe+reinsert + duplicate warning each
+ // cycle, with the fact ids advancing 1→2→3→…
+ test('idempotent: a dangling reference does not churn — second reconcile is a no-op', async () => {
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Retired claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #9 |`,
+ ));
+ const first = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(first.factsInserted).toBeGreaterThan(0);
+ const idsAfterFirst = await readIds();
+
+ const second = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(second.factsInserted).toBe(0);
+ expect(second.factsDeleted).toBe(0);
+ expect(second.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ expect(await readIds()).toEqual(idsAfterFirst);
+ });
+
+ test('idempotent: a self-reference does not churn — second reconcile is a no-op', async () => {
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Ouroboros claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #1 |`,
+ ));
+ const first = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(first.warnings.some(w => w.includes('references itself'))).toBe(true);
+ const idsAfterFirst = await readIds();
+
+ const second = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(second.factsInserted).toBe(0);
+ expect(second.factsDeleted).toBe(0);
+ expect(second.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ expect(await readIds()).toEqual(idsAfterFirst);
+ });
+
+ test('idempotent: a chain (struck → struck) does not churn — second reconcile is a no-op', async () => {
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Link a~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #2 |
+| 2 | ~~Link b~~ | commitment | 0.6 | world | medium | 2026-02-01 | | call | superseded by #3 |
+| 3 | Live tail | fact | 1.0 | world | high | 2026-03-01 | | call | |`,
+ ));
+ const first = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(first.warnings.some(w => w.includes('struck'))).toBe(true);
+ const idsAfterFirst = await readIds();
+
+ const second = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(second.factsInserted).toBe(0);
+ expect(second.factsDeleted).toBe(0);
+ expect(second.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ expect(await readIds()).toEqual(idsAfterFirst);
+ });
+
+ // The no-churn drift term must not mask a genuine reference change.
+ test('changed reference re-attempts: dangling → resolvable re-resolves superseded_by', async () => {
+ // Cycle 1: row 1 struck, superseded by #9 (dangling); row 2 live.
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Old claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #9 |
+| 2 | New claim | fact | 1.0 | world | high | 2026-07-01 | | call | |`,
+ ));
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect((await readSupersessionCols()).find(x => x.row_num === 1)!.superseded_by).toBeNull();
+
+ // Cycle 2: the operator fixes the reference to #2. The claim text and
+ // row_num are unchanged, so only the supersession-drift term can catch
+ // it — and it must, keying off the now-resolvable reference.
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Old claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #2 |
+| 2 | New claim | fact | 1.0 | world | high | 2026-07-01 | | call | |`,
+ ));
+ const r = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(r.factsInserted).toBeGreaterThan(0);
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const ids = await (engine as any).db.query(
+ `SELECT row_num, id FROM facts WHERE source_markdown_slug = 'people/deal' ORDER BY row_num`,
+ );
+ const row2Id = Number(ids.rows.find((x: { row_num: number }) => Number(x.row_num) === 2).id);
+ const row1 = (await readSupersessionCols()).find(x => x.row_num === 1)!;
+ expect(Number(row1.superseded_by)).toBe(row2Id);
+
+ // And it settles: a third cycle is a no-op.
+ const third = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(third.factsInserted).toBe(0);
+ expect(third.factsDeleted).toBe(0);
+ });
+
+ // Pre-fix, the reconcile deleted the page in a self-committing transaction
+ // BEFORE the separate insertFacts transaction; an insert throw left the
+ // page permanently emptied. The caller now defers the wipe into
+ // insertFacts' own transaction, so a failing insert can never empty it.
+ test('a failing insert during the wipe+reinsert path leaves the page intact', async () => {
+ await putPage('people/deal', SUPERSEDE_FENCE);
+ await runExtractFacts(engine, { slugs: ['people/deal'] });
+ const before = await readIds();
+ expect(before).toHaveLength(2);
+
+ // Force a drift so the reconcile takes the wipe+reinsert path.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `UPDATE facts SET superseded_by = NULL, expired_at = NULL WHERE source_markdown_slug = 'people/deal' AND row_num = 1`,
+ );
+
+ // Make the insert throw. Pre-fix, the separate-commit delete had already
+ // emptied the page by the time this threw; now no delete runs outside
+ // insertFacts, so the rows survive.
+ const original = engine.insertFacts.bind(engine);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (engine as any).insertFacts = async () => { throw new Error('simulated insert failure'); };
+ try {
+ await expect(runExtractFacts(engine, { slugs: ['people/deal'] })).rejects.toThrow('simulated insert failure');
+ } finally {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (engine as any).insertFacts = original;
+ }
+
+ // The page keeps its rows — not silently emptied.
+ expect(await readIds()).toEqual(before);
+ });
+
+ // An int4-overflowing #N in the fence must be treated as a dangling
+ // reference, never overflow the resolution SELECT and abort the cycle.
+ test('int4-overflow reference in the fence → warning, cycle completes, second cycle no-op', async () => {
+ await putPage('people/deal', FACT_FENCE(
+ `| 1 | ~~Retired claim~~ | commitment | 0.6 | world | medium | 2026-01-01 | | call | superseded by #99999999999 |`,
+ ));
+ const first = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(first.warnings.some(w => w.includes('absent from the fence'))).toBe(true);
+ const row1 = (await readSupersessionCols()).find(x => x.row_num === 1)!;
+ expect(row1.superseded_by).toBeNull();
+ expect(row1.expired_at).not.toBeNull();
+ const idsAfterFirst = await readIds();
+
+ const second = await runExtractFacts(engine, { slugs: ['people/deal'] });
+ expect(second.factsInserted).toBe(0);
+ expect(second.factsDeleted).toBe(0);
+ expect(second.warnings.filter(w => w.includes('superseded'))).toEqual([]);
+ expect(await readIds()).toEqual(idsAfterFirst);
+ });
+});
diff --git a/test/extract-from-fence.test.ts b/test/extract-from-fence.test.ts
index 6f3c2aa8c1..18933b34bc 100644
--- a/test/extract-from-fence.test.ts
+++ b/test/extract-from-fence.test.ts
@@ -5,6 +5,9 @@
* - All-fields happy path
* - The strikethrough date-derivation contract (forgotten / superseded
* / inactive-unrecognized branches)
+ * - v0.46 (#3014) supersession transport: struck rows carry expired_at
+ * + the `superseded by #N` row reference; resolveSupersededByRow's
+ * self / dangling / chain edge cases
* - source default when fence row has no `source` cell
* - row_num and source_markdown_slug threading
* - ISO date parsing tolerance + UTC determinism
@@ -16,6 +19,12 @@ import {
extractFactsFromFenceText,
FENCE_SOURCE_DEFAULT,
} from '../src/core/facts/extract-from-fence.ts';
+import {
+ resolveSupersededByRow,
+ isInt4RowRef,
+ PG_INT4_MAX,
+ type SupersedeTarget,
+} from '../src/core/facts/supersede-resolve.ts';
import type { ParsedFact } from '../src/core/facts-fence.ts';
const baseFact = (overrides: Partial<ParsedFact> = {}): ParsedFact => ({
@@ -135,7 +144,7 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
expect(out[0].valid_until).toBeNull();
});
- test('forgotten row → valid_until = today (UTC midnight)', () => {
+ test('forgotten row → valid_until = today (UTC midnight) + expired_at set, no supersession', () => {
const out = extractFactsFromFenceText(
[baseFact({
active: false,
@@ -147,6 +156,10 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
{ nowOverride: FROZEN_TODAY },
);
expect(out[0].valid_until).toEqual(FROZEN_TODAY);
+ // v0.46 (#3014) — a struck row stamps expired_at so it exits active
+ // views; a forgotten row is not a supersession, so no row reference.
+ expect(out[0].expired_at).toEqual(FROZEN_TODAY);
+ expect(out[0].superseded_by_row).toBeUndefined();
});
test('forgotten row with explicit validUntil → explicit value wins', () => {
@@ -168,7 +181,12 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
expect(out[0].valid_until).not.toEqual(FROZEN_TODAY);
});
- test('supersededBy row without explicit validUntil → null (consolidator owns derivation)', () => {
+ test('supersededBy row without explicit validUntil → valid_until null, expired_at today, superseded_by_row carried', () => {
+ // v0.46 (#3014): pre-fix the mapper dropped supersededBy and left
+ // valid_until null "for the consolidator". The mapper now owns the
+ // transport: it carries the row reference and stamps expired_at so the
+ // struck row exits active views. valid_until stays null (no explicit
+ // date, and the superseding row's valid_from isn't visible here).
const out = extractFactsFromFenceText(
[baseFact({
active: false,
@@ -180,9 +198,11 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
{ nowOverride: FROZEN_TODAY },
);
expect(out[0].valid_until).toBeNull();
+ expect(out[0].expired_at).toEqual(FROZEN_TODAY);
+ expect(out[0].superseded_by_row).toBe(4);
});
- test('supersededBy row with explicit validUntil → explicit value wins', () => {
+ test('supersededBy row with explicit validUntil → explicit value wins for both valid_until and expired_at', () => {
const out = extractFactsFromFenceText(
[baseFact({
active: false,
@@ -195,6 +215,10 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
{ nowOverride: FROZEN_TODAY },
);
expect(out[0].valid_until!.getUTCFullYear()).toBe(2026);
+ // expired_at derives from valid_until when present (valid_until ?? today).
+ expect(out[0].expired_at!.getUTCFullYear()).toBe(2026);
+ expect(out[0].expired_at!.getUTCMonth()).toBe(5); // June
+ expect(out[0].superseded_by_row).toBe(4);
});
test('inactive-unrecognized row (strikethrough but no forgotten/superseded flag) → today', () => {
@@ -212,6 +236,77 @@ describe('extractFactsFromFenceText — date derivation contract', () => {
{ nowOverride: FROZEN_TODAY },
);
expect(out[0].valid_until).toEqual(FROZEN_TODAY);
+ // v0.46 (#3014) — unrecognized-inactive still exits active views via
+ // expired_at, but is not a supersession.
+ expect(out[0].expired_at).toEqual(FROZEN_TODAY);
+ expect(out[0].superseded_by_row).toBeUndefined();
+ });
+
+ test('active row → expired_at null, no supersession reference', () => {
+ const out = extractFactsFromFenceText(
+ [baseFact()],
+ 'people/alice',
+ 'default',
+ { nowOverride: FROZEN_TODAY },
+ );
+ expect(out[0].expired_at).toBeNull();
+ expect(out[0].superseded_by_row).toBeUndefined();
+ });
+});
+
+describe('resolveSupersededByRow — reference resolution (#3014)', () => {
+ const live: SupersedeTarget = { id: 42, struck: false };
+
+ test('valid reference → resolves to the target fact id, no warning', () => {
+ const r = resolveSupersededByRow(1, 2, live, 'deals/acme');
+ expect(r.superseded_by).toBe(42);
+ expect(r.warning).toBeNull();
+ });
+
+ test('self-reference → NULL + warning', () => {
+ const r = resolveSupersededByRow(3, 3, { id: 99, struck: false }, 'deals/acme');
+ expect(r.superseded_by).toBeNull();
+ expect(r.warning).toContain('references itself');
+ });
+
+ test('dangling reference (target absent from fence) → NULL + warning', () => {
+ const r = resolveSupersededByRow(1, 9, undefined, 'deals/acme');
+ expect(r.superseded_by).toBeNull();
+ expect(r.warning).toContain('absent from the fence');
+ });
+
+ test('struck target (chain or forgotten) → NULL + warning', () => {
+ const r = resolveSupersededByRow(1, 2, { id: 7, struck: true }, 'deals/acme');
+ expect(r.superseded_by).toBeNull();
+ // The warning names the target as struck/inactive, not specifically a
+ // chain — a forgotten target is struck too but isn't a supersession chain.
+ expect(r.warning).toContain('struck');
+ });
+});
+
+describe('isInt4RowRef — supersession-target overflow guard (#3014)', () => {
+ test('accepts a normal positive row reference', () => {
+ expect(isInt4RowRef(1)).toBe(true);
+ expect(isInt4RowRef(42)).toBe(true);
+ });
+
+ test('accepts the int4 maximum, rejects one past it', () => {
+ expect(isInt4RowRef(PG_INT4_MAX)).toBe(true);
+ expect(isInt4RowRef(PG_INT4_MAX + 1)).toBe(false);
+ });
+
+ test('rejects an 11-digit reference (the reported overflow shape)', () => {
+ // The parser accepts any finite #N; this one would overflow int4 in the
+ // resolution SELECT and abort the cycle if it reached the DB.
+ expect(isInt4RowRef(99999999999)).toBe(false);
+ });
+
+ test('rejects zero, negatives, and non-integers', () => {
+ expect(isInt4RowRef(0)).toBe(false);
+ expect(isInt4RowRef(-5)).toBe(false);
+ expect(isInt4RowRef(1.5)).toBe(false);
+ expect(isInt4RowRef(Number.NaN)).toBe(false);
+ expect(isInt4RowRef(Number.POSITIVE_INFINITY)).toBe(false);
});
});
diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.ts
index ec95135cd3..a5678786cc 100644
--- a/test/extract-stale.test.ts
+++ b/test/extract-stale.test.ts
@@ -15,7 +15,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { runExtract } from '../src/commands/extract.ts';
+import { runExtract, extractStaleFromDB } from '../src/commands/extract.ts';
import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
import type { PageInput } from '../src/core/types.ts';
@@ -362,4 +362,27 @@ describe('gbrain extract --stale', () => {
expect(await stampOf('concepts/knowledge-graph')).not.toBeNull();
});
+ test('#4062 review: timeBudgetMs caps the sweep between batches (in-cycle drain stays bounded)', async () => {
+ // 26 stale pages > STALE_BATCH_SIZE (25): the first keyset batch drains
+ // 25, the 0ms budget trips, and the sweep exits with the remainder still
+ // stale — exactly how the cycle's in-line drain nibbles a big backlog
+ // instead of consuming the whole cycle.
+ for (let i = 0; i < 26; i++) {
+ await engine.putPage(`people/budget-${String(i).padStart(2, '0')}`, personPage(`Budget ${i}`));
+ }
+ const r = await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ timeBudgetMs: 0,
+ });
+ expect(r.pagesProcessed).toBe(25);
+ expect(r.staleRemaining).toBe(1);
+
+ // Default budget (~30 min) finishes the remainder.
+ const r2 = await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ });
+ expect(r2.pagesProcessed).toBe(1);
+ expect(r2.staleRemaining).toBe(0);
+ });
+
});
diff --git a/test/extract-stamp-source-3957.test.ts b/test/extract-stamp-source-3957.test.ts
new file mode 100644
index 0000000000..230a382d11
--- /dev/null
+++ b/test/extract-stamp-source-3957.test.ts
@@ -0,0 +1,296 @@
+/**
+ * #3957 — extraction stamping + source threading + FS/DB timeline shape parity.
+ *
+ * Pins the cluster of silent no-ops around the links_extracted_at watermark
+ * and timeline row shapes:
+ * 1. parseTimelineEntries (DB path) splits `Source — Summary` on
+ * pipe-separated bullets exactly like extractTimelineFromContent (FS
+ * path), so the same bullet extracted through both paths dedups under
+ * the (page_id, date, summary, source) index instead of duplicating.
+ * 2. markPagesExtractedBatch returns the stamped-row count (both engines —
+ * PGLite pinned here, Postgres via the DATABASE_URL-gated parity suite),
+ * and stampExtracted logs the shortfall to stderr instead of silently
+ * claiming success on a wrong-source stamp.
+ * 3. runExtractCore's full FS walk (mode 'all') stamps walked pages, so a
+ * full extract no longer leaves the whole brain permanently "stale".
+ * 4. addTimelineEntriesBatch's pages JOIN excludes soft-deleted pages.
+ * 5. put_page auto-timeline threads ctx.sourceId (+ the parsed source
+ * label), so timeline rows land on the page the write targeted instead
+ * of defaulting to 'default'.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { parseTimelineEntries, LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
+import { extractTimelineFromContent } from '../src/core/timeline-extract.ts';
+import { runExtractCore, extractStaleFromDB, stampExtracted } from '../src/commands/extract.ts';
+import { operations, type Operation, type OperationContext } from '../src/core/operations.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let engine: PGLiteEngine;
+let tempDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ tempDir = mkdtempSync(join(tmpdir(), 'gbrain-3957-'));
+});
+
+afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+});
+
+const CANON_BULLET = '- **2026-01-05** | meeting — Discussed the wiki';
+
+describe('#3957 parseTimelineEntries — FS/DB source split parity', () => {
+ test('pipe-separated bullet splits Source — Summary like the FS extractor', () => {
+ const db = parseTimelineEntries(CANON_BULLET);
+ const fs = extractTimelineFromContent(CANON_BULLET, 'people/alice');
+ expect(db).toHaveLength(1);
+ expect(fs).toHaveLength(1);
+ expect(db[0].source).toBe('meeting');
+ expect(db[0].summary).toBe('Discussed the wiki');
+ // The load-bearing parity: identical (source, summary) dedup shape.
+ expect({ source: db[0].source, summary: db[0].summary })
+ .toEqual({ source: fs[0].source, summary: fs[0].summary });
+ });
+
+ test('dash-separated bullet is one summary — never shattered on interior dashes', () => {
+ const db = parseTimelineEntries('- **2026-01-05** - moved to Berlin - permanently');
+ expect(db).toHaveLength(1);
+ expect(db[0].source).toBe('markdown');
+ expect(db[0].summary).toBe('moved to Berlin - permanently');
+ });
+
+ test('pipe bullet without a Source delimiter keeps the FS fallback source', () => {
+ const db = parseTimelineEntries('- **2026-01-05** | plain summary with no delimiter');
+ const fs = extractTimelineFromContent('- **2026-01-05** | plain summary with no delimiter', 'x');
+ expect(db[0].source).toBe('markdown');
+ expect(db[0].source).toBe(fs[0].source);
+ expect(db[0].summary).toBe(fs[0].summary);
+ });
+
+ test('delimiter inside a markdown link never splits (shared link-aware finder)', () => {
+ const line = '- **2026-01-05** | [Deals — Q1 Review](deals/q1.md) recap';
+ const db = parseTimelineEntries(line);
+ const fs = extractTimelineFromContent(line, 'x');
+ expect(db[0].summary).toBe(fs[0].summary);
+ expect(db[0].source).toBe(fs[0].source);
+ });
+
+ test('Chinese pipe-separated bullet splits too', () => {
+ const db = parseTimelineEntries('- 2020年1月2日 | 董事会 — 决定融资');
+ expect(db).toHaveLength(1);
+ expect(db[0].date).toBe('2020-01-02');
+ expect(db[0].source).toBe('董事会');
+ expect(db[0].summary).toBe('决定融资');
+ });
+});
+
+describe('#3957 markPagesExtractedBatch count + stampExtracted shortfall', () => {
+ test('returns the stamped-row count; wrong-source refs are a visible shortfall', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('wiki', 'wiki') ON CONFLICT (id) DO NOTHING`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'wiki', 'person', 'Alice', 'x', '')`,
+ );
+ const now = new Date().toISOString();
+ // Right source stamps 1; wrong source ('default') matches nothing.
+ expect(await engine.markPagesExtractedBatch(
+ [{ slug: 'people/alice', source_id: 'wiki' }], now,
+ )).toBe(1);
+ expect(await engine.markPagesExtractedBatch(
+ [{ slug: 'people/alice', source_id: 'default' }], now,
+ )).toBe(0);
+ expect(await engine.markPagesExtractedBatch([], now)).toBe(0);
+ });
+
+ test('stampExtracted logs the shortfall to stderr (never throws)', async () => {
+ const writes: string[] = [];
+ const origWrite = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: string | Uint8Array) => {
+ writes.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write;
+ try {
+ await stampExtracted(engine, [
+ { slug: 'ghost/none', source_id: 'default' },
+ ]);
+ } finally {
+ process.stderr.write = origWrite;
+ }
+ const joined = writes.join('');
+ expect(joined).toContain('stamped 0/1');
+ expect(joined).toContain('extract --stale');
+ });
+});
+
+describe('#3957 full FS walk stamps the watermark (mode all)', () => {
+ test('runExtractCore full walk leaves walked pages fresh, not stale', async () => {
+ mkdirSync(join(tempDir, 'people'), { recursive: true });
+ writeFileSync(join(tempDir, 'people', 'alice.md'), `# Alice\n\n${CANON_BULLET}\n`);
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'default', 'person', 'Alice', 'x', '')`,
+ );
+ const before = await engine.countStalePagesForExtraction({});
+ expect(before).toBe(1);
+
+ await runExtractCore(engine, { mode: 'all', dir: tempDir });
+
+ const after = await engine.countStalePagesForExtraction({});
+ expect(after).toBe(0);
+ });
+
+ test('full walk stamps the row\'s READ updated_at (clamped to versionTs), never now() (D4)', async () => {
+ mkdirSync(join(tempDir, 'people'), { recursive: true });
+ writeFileSync(join(tempDir, 'people', 'alice.md'), `# Alice\n\n${CANON_BULLET}\n`);
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'default', 'person', 'Alice', 'x', '')`,
+ );
+
+ await runExtractCore(engine, { mode: 'all', dir: tempDir });
+
+ // Pre-fix the stamp was now() — a FUTURE watermark strictly greater than
+ // updated_at, which masks a concurrent edit landing between the content
+ // read and the stamp. The D4-correct stamp equals the pre-read
+ // GREATEST(updated_at, versionTs).
+ const rows = await engine.executeRaw<{ ok: boolean }>(
+ `SELECT links_extracted_at = GREATEST(updated_at, $1::timestamptz) AS ok
+ FROM pages WHERE slug = 'people/alice' AND source_id = 'default'`,
+ [LINK_EXTRACTOR_VERSION_TS],
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].ok).toBe(true);
+ });
+
+ test('incremental (slugs) walk stamps the pre-read updated_at too (D4)', async () => {
+ mkdirSync(join(tempDir, 'people'), { recursive: true });
+ writeFileSync(join(tempDir, 'people', 'alice.md'), '# Alice\n');
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'default', 'person', 'Alice', 'x', '')`,
+ );
+
+ await runExtractCore(engine, { mode: 'all', dir: tempDir, slugs: ['people/alice'] });
+
+ const rows = await engine.executeRaw<{ ok: boolean }>(
+ `SELECT links_extracted_at = GREATEST(updated_at, $1::timestamptz) AS ok
+ FROM pages WHERE slug = 'people/alice' AND source_id = 'default'`,
+ [LINK_EXTRACTOR_VERSION_TS],
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].ok).toBe(true);
+ });
+
+ test('links- or timeline-only walks do NOT stamp (C3/D6 rule)', async () => {
+ mkdirSync(join(tempDir, 'people'), { recursive: true });
+ writeFileSync(join(tempDir, 'people', 'alice.md'), '# Alice\n');
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'default', 'person', 'Alice', 'x', '')`,
+ );
+ await runExtractCore(engine, { mode: 'links', dir: tempDir });
+ expect(await engine.countStalePagesForExtraction({})).toBe(1);
+ await runExtractCore(engine, { mode: 'timeline', dir: tempDir });
+ expect(await engine.countStalePagesForExtraction({})).toBe(1);
+ });
+});
+
+describe('#3957 timeline batch JOIN excludes soft-deleted pages', () => {
+ test('addTimelineEntriesBatch inserts 0 rows for a soft-deleted page', async () => {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, deleted_at)
+ VALUES ('people/gone', 'default', 'person', 'Gone', 'x', '', now())`,
+ );
+ const inserted = await engine.addTimelineEntriesBatch([
+ { slug: 'people/gone', date: '2026-01-05', source: 'meeting', summary: 'ghost entry', detail: '', source_id: 'default' },
+ ]);
+ expect(inserted).toBe(0);
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM timeline_entries`,
+ );
+ expect(Number(rows[0]?.n ?? -1)).toBe(0);
+ });
+});
+
+describe('#3957 stale-dedup: FS-extracted bullet does not duplicate under --stale', () => {
+ test('extract --stale re-extraction of an FS-shaped row is a no-op', async () => {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/alice', 'default', 'person', 'Alice', $1, '')`,
+ [`# Alice\n\n${CANON_BULLET}\n`],
+ );
+ // FS-path shape lands first (what sync's inline extractTimelineForSlugs
+ // writes): split source + trimmed summary.
+ const fsEntries = extractTimelineFromContent(CANON_BULLET, 'people/alice');
+ const insertedFs = await engine.addTimelineEntriesBatch(
+ fsEntries.map(e => ({ slug: e.slug, date: e.date, source: e.source, summary: e.summary, detail: e.detail ?? '', source_id: 'default' })),
+ );
+ expect(insertedFs).toBe(1);
+
+ // The DB stale sweep re-extracts the same page. Pre-fix it wrote
+ // source='' + summary 'meeting — Discussed the wiki' → a duplicate row.
+ const r = await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ });
+ expect(r.pagesProcessed).toBe(1);
+
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM timeline_entries`,
+ );
+ expect(Number(rows[0]?.n ?? -1)).toBe(1);
+ });
+});
+
+describe('#3957 put_page auto-timeline threads ctx.sourceId', () => {
+ test('timeline rows attach to the source the write targeted', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('wiki', 'wiki') ON CONFLICT (id) DO NOTHING`,
+ );
+ // Decoy same-slug page in 'default': pre-fix the batch omitted source_id,
+ // so rows landed here (or nowhere) instead of on the wiki page.
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('people/bob', 'default', 'person', 'Bob (decoy)', 'x', '')`,
+ );
+ const put_page = operations.find(o => o.name === 'put_page') as Operation;
+ const ctx = {
+ engine: engine as unknown as BrainEngine,
+ config: { engine: 'pglite' },
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ remote: false,
+ sourceId: 'wiki',
+ } as unknown as OperationContext;
+ const result = await put_page.handler(ctx, {
+ slug: 'people/bob',
+ content: `# Bob\n\n${CANON_BULLET}\n`,
+ type: 'person',
+ }) as { auto_timeline?: { created?: number } };
+ expect(result.auto_timeline?.created).toBe(1);
+
+ const rows = await engine.executeRaw<{ source_id: string; source: string; summary: string }>(
+ `SELECT p.source_id, te.source, te.summary
+ FROM timeline_entries te JOIN pages p ON p.id = te.page_id`,
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].source_id).toBe('wiki');
+ expect(rows[0].source).toBe('meeting');
+ expect(rows[0].summary).toBe('Discussed the wiki');
+ });
+});
diff --git a/test/extraction-review.test.ts b/test/extraction-review.test.ts
index 0c32f9b990..5598ea6ecb 100644
--- a/test/extraction-review.test.ts
+++ b/test/extraction-review.test.ts
@@ -32,7 +32,7 @@ import {
PROVENANCE_AUTO_EXTRACTED,
} from '../src/core/extraction-review.ts';
import { enrichEntity, extractAndEnrich } from '../src/core/enrichment-service.ts';
-import { rrfFusion, hybridSearch } from '../src/core/search/hybrid.ts';
+import { rrfFusion, hybridSearch, stampUnverifiedExtractions } from '../src/core/search/hybrid.ts';
import { buildSourceFactorCase } from '../src/core/search/sql-ranking.ts';
import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';
import { checkUnverifiedExtractions } from '../src/commands/doctor.ts';
@@ -232,16 +232,94 @@ describe('enrichEntity trust lane', () => {
expect(real.score / fake.score).toBeCloseTo(1.2, 5);
});
- test('getUnverifiedExtractionPageIds returns only marked pages', async () => {
+ test('getUnverifiedExtractionPageIds flags only quarantined pages as unverified', async () => {
await enrichEntity(engine, { entityName: 'Fake Guy', entityType: 'person', context: 'c', sourceSlug: 's' });
await enrichEntity(engine, { entityName: 'Real Guy', entityType: 'person', context: 'c', sourceSlug: 's' }, { trusted: true });
const fake = await engine.getPage('people/fake-guy');
const real = await engine.getPage('people/real-guy');
- const set = await engine.getUnverifiedExtractionPageIds([fake!.id, real!.id]);
- expect(set.has(fake!.id)).toBe(true);
- expect(set.has(real!.id)).toBe(false);
+ const marks = await engine.getUnverifiedExtractionPageIds([fake!.id, real!.id]);
+ expect(marks.get(fake!.id)).toEqual({ unverified: true, status: 'unverified' });
+ // Trusted write carries no status frontmatter at all → no entry.
+ expect(marks.has(real!.id)).toBe(false);
expect((await engine.getUnverifiedExtractionPageIds([])).size).toBe(0);
});
+
+ test('#4220: non-quarantine statuses (draft/superseded/restricted) surface without the unverified flag', async () => {
+ const statuses = ['draft', 'superseded', 'restricted'] as const;
+ const ids: number[] = [];
+ for (const status of statuses) {
+ await engine.putPage(`notes/status-${status}`, {
+ type: 'note',
+ title: `Status ${status}`,
+ compiled_truth: `A ${status} page.`,
+ timeline: '',
+ frontmatter: { status },
+ });
+ const page = await engine.getPage(`notes/status-${status}`);
+ ids.push(page!.id);
+ }
+ // A page whose status is 'unverified' but WITHOUT auto-extracted
+ // provenance must surface the status while staying un-flagged: the
+ // quarantine lane requires the marker pair.
+ await engine.putPage('notes/status-user-unverified', {
+ type: 'note',
+ title: 'User unverified',
+ compiled_truth: 'User-authored page reusing the status key.',
+ timeline: '',
+ frontmatter: { status: 'unverified' },
+ });
+ const userPage = await engine.getPage('notes/status-user-unverified');
+ ids.push(userPage!.id);
+
+ const marks = await engine.getUnverifiedExtractionPageIds(ids);
+ expect(marks.get(ids[0]!)).toEqual({ unverified: false, status: 'draft' });
+ expect(marks.get(ids[1]!)).toEqual({ unverified: false, status: 'superseded' });
+ expect(marks.get(ids[2]!)).toEqual({ unverified: false, status: 'restricted' });
+ expect(marks.get(userPage!.id)).toEqual({ unverified: false, status: 'unverified' });
+ });
+
+ test('#4220: stampUnverifiedExtractions stamps SearchResult.status always, unverified only for stubs', async () => {
+ await enrichEntity(engine, { entityName: 'Stamp Fake', entityType: 'person', context: 'c', sourceSlug: 's' });
+ await engine.putPage('notes/stamp-draft', {
+ type: 'note',
+ title: 'Stamp Draft',
+ compiled_truth: 'draft body',
+ timeline: '',
+ frontmatter: { status: 'draft' },
+ });
+ await engine.putPage('notes/stamp-clean', {
+ type: 'note',
+ title: 'Stamp Clean',
+ compiled_truth: 'clean body',
+ timeline: '',
+ frontmatter: {},
+ });
+ const stub = await engine.getPage('people/stamp-fake');
+ const draft = await engine.getPage('notes/stamp-draft');
+ const clean = await engine.getPage('notes/stamp-clean');
+
+ const mk = (page: { id: number; slug: string }): SearchResult => ({
+ slug: page.slug,
+ page_id: page.id,
+ title: page.slug,
+ type: 'note',
+ chunk_text: 'x',
+ chunk_source: 'compiled_truth',
+ chunk_id: 0,
+ chunk_index: 0,
+ score: 1,
+ stale: false,
+ });
+ const results = [mk(stub!), mk(draft!), mk(clean!)];
+ await stampUnverifiedExtractions(engine, results);
+
+ expect(results[0]!.status).toBe('unverified');
+ expect(results[0]!.unverified).toBe(true);
+ expect(results[1]!.status).toBe('draft');
+ expect(results[1]!.unverified).toBeUndefined();
+ expect(results[2]!.status).toBeUndefined();
+ expect(results[2]!.unverified).toBeUndefined();
+ });
});
// ---------------------------------------------------------------------------
diff --git a/test/facts-valid-from-context.serial.test.ts b/test/facts-valid-from-context.serial.test.ts
new file mode 100644
index 0000000000..4bddaf0bde
--- /dev/null
+++ b/test/facts-valid-from-context.serial.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #4206 — extract_facts event-time + provenance threading, and `context`
+ * in the fact projections.
+ *
+ * Gaps covered (one test per gap):
+ * 1. `valid_from` param threads through runFactsPipeline to the insert
+ * fallback — historical imports stop being stamped with import time.
+ * 2. `source_slug` param lands in facts.context.
+ * 3. An unparseable valid_from fails LOUD (silently defaulting to now()
+ * is the exact bug the param exists to fix).
+ * 4. recall / context_pack / delta projections carry `context`.
+ *
+ * Serial: mock.module replaces the LLM extractor with a canned single-fact
+ * outcome so the pipeline runs end-to-end with zero keys, deterministically.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';
+import * as factsExtract from '../src/core/facts/extract.ts';
+
+mock.module('../src/core/facts/extract.ts', () => ({
+ ...factsExtract,
+ extractFactsFromTurnWithOutcome: async () => ({
+ ok: true,
+ facts: [{
+ fact: 'Alice moved to Berlin',
+ kind: 'event',
+ notability: 'high',
+ entity_slug: null, // unparented → legacy DB-only bucket (no fence needed)
+ source: 'mcp:extract_facts',
+ source_session: null,
+ confidence: 0.9,
+ embedding: null,
+ }],
+ }),
+}));
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const ctx = (): OperationContext =>
+ ({ engine, remote: false, sourceId: 'default' } as unknown as OperationContext);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('extract_facts valid_from + source_slug threading (#4206)', () => {
+ test('caller valid_from + source_slug land on the inserted fact row', async () => {
+ const r = await operationsByName.extract_facts!.handler(ctx(), {
+ turn_text: 'Alice moved to Berlin last spring.',
+ valid_from: '2024-05-01T00:00:00.000Z',
+ source_slug: 'meetings/2026-04-03',
+ }) as { inserted: number };
+ expect(r.inserted).toBe(1);
+
+ const rows = await engine.executeRaw<{ fact: string; context: string | null; valid_from: Date | string }>(
+ `SELECT fact, context, valid_from FROM facts WHERE fact = 'Alice moved to Berlin'`,
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.context).toBe('meetings/2026-04-03');
+ const vf = rows[0]!.valid_from instanceof Date ? rows[0]!.valid_from : new Date(rows[0]!.valid_from);
+ expect(vf.toISOString()).toBe('2024-05-01T00:00:00.000Z');
+ });
+
+ test('unparseable valid_from fails loud instead of silently stamping now()', async () => {
+ await expect(operationsByName.extract_facts!.handler(ctx(), {
+ turn_text: 'x',
+ valid_from: 'last tuesday-ish',
+ })).rejects.toThrow(/valid_from/);
+ });
+});
+
+describe('context in the fact projections (#4206)', () => {
+ test('recall carries context', async () => {
+ const r = await operationsByName.recall!.handler(ctx(), {}) as {
+ facts: Array<{ fact: string; context: string | null }>;
+ };
+ const mine = r.facts.find(f => f.fact === 'Alice moved to Berlin');
+ expect(mine).toBeDefined();
+ expect(mine!.context).toBe('meetings/2026-04-03');
+ });
+
+ test('context_pack and delta fact projections carry context', async () => {
+ const pack = await operationsByName.context_pack!.handler(ctx(), {}) as {
+ facts: Array<{ fact: string; context?: string | null }>;
+ };
+ const packFact = pack.facts.find(f => f.fact === 'Alice moved to Berlin');
+ // The pack's hot-facts arm caps by confidence; presence implies context rides.
+ if (packFact) expect(packFact.context).toBe('meetings/2026-04-03');
+
+ const d = await operationsByName.delta!.handler(ctx(), {
+ since: '2020-01-01T00:00:00.000Z',
+ // The extracted fact defaults to private; delta is world-only unless a
+ // trusted local caller widens it.
+ include_private: true,
+ }) as { facts: Array<{ fact: string; context?: string | null }> };
+ const deltaFact = d.facts.find(f => f.fact === 'Alice moved to Berlin');
+ expect(deltaFact).toBeDefined();
+ expect(deltaFact!.context).toBe('meetings/2026-04-03');
+ });
+});
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index 744a60206c..866164f665 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -350,6 +350,37 @@ describe('writeFactsToFence — stub guard (v0.34.5)', () => {
});
});
+describe('writeFactsToFence — v0.46 (#3014) supersession-warning seam', () => {
+ test('forwards an unresolvable `superseded by #N` warning to console.warn', async () => {
+ // The reachable shape through this path: writeFactsToFence appends
+ // active rows, but `context` is caller-controlled free text, so a
+ // "superseded by #N" context re-parses to supersededBy=N. When #N names
+ // no row, insertFacts resolves it to NULL + a warning; this test pins
+ // that writeFactsToFence forwards that warning to console.warn (the
+ // no-swallowed-errors seam) rather than dropping it.
+ const captured: string[] = [];
+ const original = console.warn;
+ // eslint-disable-next-line no-console
+ console.warn = (msg?: unknown) => { captured.push(String(msg)); };
+ let result;
+ try {
+ result = await writeFactsToFence(
+ engine,
+ { sourceId: 'default', localPath: brainDir, slug: 'people/alice' },
+ [baseInput({ fact: 'Points at a row that is not there', context: 'superseded by #99' })],
+ );
+ } finally {
+ // eslint-disable-next-line no-console
+ console.warn = original;
+ }
+
+ // The row still lands (the bad reference doesn't block the insert).
+ expect(result.inserted).toBe(1);
+ // The warning was logged with the category tag, not swallowed.
+ expect(captured.some(w => w.includes('[facts.supersession]') && w.includes('absent from the fence'))).toBe(true);
+ });
+});
+
describe('lookupSourceLocalPath', () => {
test('returns the configured local_path for an existing source', async () => {
const got = await lookupSourceLocalPath(engine, 'default');
diff --git a/test/file-upload-engine-context.test.ts b/test/file-upload-engine-context.test.ts
index 1f475c60e2..4761a68dde 100644
--- a/test/file-upload-engine-context.test.ts
+++ b/test/file-upload-engine-context.test.ts
@@ -4,16 +4,25 @@
* A long-running `gbrain serve` owns the PGLite connection. The handler must not
* reach for the module-global db singleton, which is intentionally uninitialized
* in the MCP dispatch path and throws "connect() has not been called".
+ *
+ * #4302: file_upload is now fail-closed on storage — with no backend it
+ * refuses BEFORE inserting a row (the old path recorded a phantom upload).
+ * This suite therefore runs against a real `local` backend in a sandboxed
+ * GBRAIN_HOME, and pins the no-backend refusal explicitly.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
let fixtureDir: string;
+let sandboxHome: string;
+let storageDir: string;
beforeAll(async () => {
engine = new PGLiteEngine();
@@ -22,15 +31,32 @@ beforeAll(async () => {
// Remote MCP uploads are intentionally confined to the server working tree.
fixtureDir = mkdtempSync(join(process.cwd(), '.file-upload-engine-context-'));
+
+ // #4302: dispatch reads ctx.config via loadConfig() → $GBRAIN_HOME/.gbrain/
+ // config.json. Point GBRAIN_HOME at a sandbox carrying a `local` storage
+ // backend so uploads land in a real (temp) backend.
+ sandboxHome = mkdtempSync(join(tmpdir(), 'gb-fuec-home-'));
+ storageDir = mkdtempSync(join(tmpdir(), 'gb-fuec-storage-'));
+ mkdirSync(join(sandboxHome, '.gbrain'), { recursive: true });
+ writeFileSync(
+ join(sandboxHome, '.gbrain', 'config.json'),
+ JSON.stringify({
+ engine: 'pglite',
+ storage: { backend: 'local', bucket: 'test-bucket', localPath: storageDir },
+ }),
+ );
});
afterAll(async () => {
if (engine) await engine.disconnect();
- if (fixtureDir) rmSync(fixtureDir, { recursive: true, force: true });
+ for (const d of [fixtureDir, sandboxHome, storageDir]) {
+ if (d) rmSync(d, { recursive: true, force: true });
+ }
});
describe('file_upload engine ownership', () => {
test('uses the MCP context engine instead of the module-global DB singleton', async () => {
+ await withEnv({ GBRAIN_HOME: sandboxHome }, async () => {
const fixture = join(fixtureDir, 'capture.json');
writeFileSync(fixture, '{"source":"camofox"}\n');
@@ -50,6 +76,9 @@ describe('file_upload engine ownership', () => {
size_bytes: 21,
});
+ // #4302: the bytes actually landed in the backend.
+ expect(existsSync(join(storageDir, 'concepts/example-board/capture.json'))).toBe(true);
+
const listed = await dispatchToolCall(engine, 'file_list', {
slug: 'concepts/example-board',
}, { remote: true, transport: 'stdio', sourceId: 'default' });
@@ -61,13 +90,16 @@ describe('file_upload engine ownership', () => {
}),
]);
+ // #4302: file_url now resolves through the backend (exists + getUrl),
+ // not the old `gbrain:files/<path>` placeholder that pointed at nothing.
const url = await dispatchToolCall(engine, 'file_url', {
storage_path: 'concepts/example-board/capture.json',
}, { remote: true, transport: 'stdio', sourceId: 'default' });
expect(url.isError).toBeFalsy();
- expect(JSON.parse(url.content[0].text)).toEqual({
- storage_path: 'concepts/example-board/capture.json',
- url: 'gbrain:files/concepts/example-board/capture.json',
+ const parsed = JSON.parse(url.content[0].text) as { storage_path: string; url: string };
+ expect(parsed.storage_path).toBe('concepts/example-board/capture.json');
+ // LocalStorage canonicalizes its base (macOS /var → /private/var).
+ expect(parsed.url).toBe(`file://${join(realpathSync(storageDir), 'concepts/example-board/capture.json')}`);
});
});
});
diff --git a/test/file-upload-fail-closed.test.ts b/test/file-upload-fail-closed.test.ts
new file mode 100644
index 0000000000..6e0ad7558e
--- /dev/null
+++ b/test/file-upload-fail-closed.test.ts
@@ -0,0 +1,147 @@
+/**
+ * #4302 — file_upload / file_url fail-closed honesty.
+ *
+ * Before the fix:
+ * - file_upload with NO storage backend inserted a files row and returned
+ * status:'uploaded' — the row claimed bytes stored nowhere;
+ * - already_exists trusted the DB row alone — vanished backend bytes lied;
+ * - file_url returned a `gbrain:files/<path>` placeholder pointing at
+ * nothing, without ever consulting a backend.
+ *
+ * Runs the op handlers directly with a crafted ctx (config controlled per
+ * test) against a real `local` backend.
+ */
+
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, OperationError } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+let storageDir: string;
+let fixtureDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ storageDir = mkdtempSync(join(tmpdir(), 'gb-4302-storage-'));
+ // Remote-confinement default is strict (cwd) — keep fixtures under cwd.
+ fixtureDir = mkdtempSync(join(process.cwd(), '.gb-4302-fixtures-'));
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(storageDir, { recursive: true, force: true });
+ rmSync(fixtureDir, { recursive: true, force: true });
+});
+
+function mkCtx(withStorage: boolean) {
+ return {
+ engine,
+ config: withStorage
+ ? { engine: 'pglite', storage: { backend: 'local', bucket: 'b', localPath: storageDir } }
+ : { engine: 'pglite' },
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote: false, // local trust: loose path confinement; storage policy is what's under test
+ sourceId: 'default',
+ } as never;
+}
+
+describe('file_upload fail-closed (#4302)', () => {
+ test('no storage backend: typed storage_error BEFORE any files row', async () => {
+ const op = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'nostore.txt');
+ writeFileSync(src, 'bytes with nowhere to go');
+ let threw: unknown = null;
+ try {
+ await op.handler(mkCtx(false), { path: src, page_slug: 'notes/nostore' });
+ } catch (e) {
+ threw = e;
+ }
+ expect(threw).toBeInstanceOf(OperationError);
+ expect((threw as OperationError).code).toBe('storage_error');
+ // No phantom row.
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM files WHERE filename = 'nostore.txt'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(0);
+ });
+
+ test('upload with a local backend stores real bytes + row', async () => {
+ const op = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'real.txt');
+ writeFileSync(src, 'real bytes');
+ const out = (await op.handler(mkCtx(true), { path: src, page_slug: 'notes/real' })) as {
+ status: string; storage_path: string;
+ };
+ expect(out.status).toBe('uploaded');
+ expect(existsSync(join(storageDir, 'notes/real/real.txt'))).toBe(true);
+ });
+
+ test('already_exists only when the backend really holds the object', async () => {
+ const op = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'dup.txt');
+ writeFileSync(src, 'duplicate candidate');
+ const first = (await op.handler(mkCtx(true), { path: src, page_slug: 'notes/dup' })) as { status: string };
+ expect(first.status).toBe('uploaded');
+ // Row + backend both present → honest already_exists.
+ const second = (await op.handler(mkCtx(true), { path: src, page_slug: 'notes/dup' })) as { status: string };
+ expect(second.status).toBe('already_exists');
+ // Backend bytes vanish → the row alone must NOT claim already_exists.
+ unlinkSync(join(storageDir, 'notes/dup/dup.txt'));
+ const third = (await op.handler(mkCtx(true), { path: src, page_slug: 'notes/dup' })) as { status: string };
+ expect(third.status).toBe('uploaded');
+ expect(existsSync(join(storageDir, 'notes/dup/dup.txt'))).toBe(true);
+ });
+});
+
+describe('file_url fail-closed (#4302)', () => {
+ test('resolves a real backend URL for a present object', async () => {
+ const upload = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'url.txt');
+ writeFileSync(src, 'url target');
+ await upload.handler(mkCtx(true), { path: src, page_slug: 'notes/url' });
+ const op = operationsByName['file_url'];
+ const out = (await op.handler(mkCtx(true), { storage_path: 'notes/url/url.txt' })) as { url: string };
+ // LocalStorage canonicalizes its base (macOS /var → /private/var).
+ expect(out.url).toBe(`file://${join(realpathSync(storageDir), 'notes/url/url.txt')}`);
+ });
+
+ test('row without backend object: storage_error, not a fake URL', async () => {
+ const upload = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'gone.txt');
+ writeFileSync(src, 'soon gone');
+ await upload.handler(mkCtx(true), { path: src, page_slug: 'notes/gone' });
+ unlinkSync(join(storageDir, 'notes/gone/gone.txt'));
+ const op = operationsByName['file_url'];
+ let threw: unknown = null;
+ try {
+ await op.handler(mkCtx(true), { storage_path: 'notes/gone/gone.txt' });
+ } catch (e) {
+ threw = e;
+ }
+ expect(threw).toBeInstanceOf(OperationError);
+ expect((threw as OperationError).code).toBe('storage_error');
+ expect(String((threw as OperationError).message)).toContain('re-upload');
+ });
+
+ test('no backend configured: storage_error, never the gbrain:files placeholder', async () => {
+ const upload = operationsByName['file_upload'];
+ const src = join(fixtureDir, 'nourl.txt');
+ writeFileSync(src, 'no url backend');
+ await upload.handler(mkCtx(true), { path: src, page_slug: 'notes/nourl' });
+ const op = operationsByName['file_url'];
+ let threw: unknown = null;
+ try {
+ await op.handler(mkCtx(false), { storage_path: 'notes/nourl/nourl.txt' });
+ } catch (e) {
+ threw = e;
+ }
+ expect(threw).toBeInstanceOf(OperationError);
+ expect((threw as OperationError).code).toBe('storage_error');
+ });
+});
diff --git a/test/files.test.ts b/test/files.test.ts
index 8367b29254..ea6974c35d 100644
--- a/test/files.test.ts
+++ b/test/files.test.ts
@@ -248,3 +248,203 @@ describe('collectFiles (production import)', () => {
}
});
});
+
+// ---- #2297: upload-raw !needsCloud (git storage) must actually bank the file ----
+// Before the fix, the small-text branch printed {success:true, storage:'git',
+// path:<input>} and returned — no repo copy, no files row. These tests pin the
+// real behavior: sidecar copy under <pageDir>/.raw/<page-name>/, a files row
+// with a repo-relative storage_path + {storage:'git'} metadata, and a hard
+// exit 1 when no brain repo is resolvable.
+import { readFileSync as readFileSync2297, existsSync as existsSync2297 } from 'fs';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runFiles } from '../src/commands/files.ts';
+
+describe('files upload-raw git-storage branch (#2297)', () => {
+ let engine: PGLiteEngine;
+ let repo: string;
+ let srcDir: string;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-2297-repo-'));
+ srcDir = mkdtempSync(join(tmpdir(), 'gbrain-2297-src-'));
+ await engine.putPage('notes/small-doc', {
+ title: 'Small Doc', type: 'concept', frontmatter: {},
+ compiled_truth: 'body', timeline: '',
+ });
+ });
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (repo) rmSync(repo, { recursive: true, force: true });
+ if (srcDir) rmSync(srcDir, { recursive: true, force: true });
+ });
+
+ function captureLogs() {
+ const logs: string[] = [];
+ const errs: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ return { logs, errs, restore: () => { logSpy.mockRestore(); errSpy.mockRestore(); } };
+ }
+
+ test('small text file: sidecar copy + files row + dest path in JSON', async () => {
+ await engine.setConfig('sync.repo_path', repo);
+ const src = join(srcDir, 'report.txt');
+ writeFileSync(src, 'quarterly numbers');
+ const cap = captureLogs();
+ try {
+ await runFiles(engine, ['upload-raw', src, '--page', 'notes/small-doc', '--type', 'report']);
+ } finally {
+ cap.restore();
+ }
+ const out = JSON.parse(cap.logs.find((l) => l.trim().startsWith('{'))!);
+ expect(out.success).toBe(true);
+ expect(out.storage).toBe('git');
+ // Dest is INSIDE the brain repo (not the input path).
+ const expectedDest = join(repo, 'notes', '.raw', 'small-doc', 'report.txt');
+ expect(out.path).toBe(expectedDest);
+ expect(existsSync2297(expectedDest)).toBe(true);
+ expect(readFileSync2297(expectedDest, 'utf8')).toBe('quarterly numbers');
+ // files row exists, storage_path repo-relative, metadata {storage:'git'}.
+ const rows = await engine.executeRaw<{ storage_path: string; page_slug: string; metadata: Record<string, unknown> }>(
+ `SELECT storage_path, page_slug, metadata FROM files WHERE filename = 'report.txt'`,
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0].storage_path).toBe(join('notes', '.raw', 'small-doc', 'report.txt'));
+ expect(rows[0].page_slug).toBe('notes/small-doc');
+ const meta = typeof rows[0].metadata === 'string' ? JSON.parse(rows[0].metadata as unknown as string) : rows[0].metadata;
+ expect(meta.storage).toBe('git');
+ expect(meta.type).toBe('report');
+ });
+
+ test('no repo configured: exits 1 instead of lying success', async () => {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'sync.repo_path'`);
+ const src = join(srcDir, 'orphan.txt');
+ writeFileSync(src, 'nowhere to go');
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ const cap = captureLogs();
+ try {
+ await runFiles(engine, ['upload-raw', src, '--page', 'notes/small-doc']);
+ throw new Error('expected exit 1');
+ } catch (e) {
+ expect((e as Error).message).toBe('EXIT:1');
+ } finally {
+ cap.restore();
+ exitSpy.mockRestore();
+ }
+ expect(cap.errs.join('\n')).toContain('cannot resolve a brain-repo destination');
+ // No success JSON was printed.
+ expect(cap.logs.find((l) => l.includes('"success":true'))).toBeUndefined();
+ });
+
+ test('missing --page for a git-storage file: exits 1', async () => {
+ await engine.setConfig('sync.repo_path', repo);
+ const src = join(srcDir, 'pageless.txt');
+ writeFileSync(src, 'no page');
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ const cap = captureLogs();
+ try {
+ await runFiles(engine, ['upload-raw', src]);
+ throw new Error('expected exit 1');
+ } catch (e) {
+ expect((e as Error).message).toBe('EXIT:1');
+ } finally {
+ cap.restore();
+ exitSpy.mockRestore();
+ }
+ expect(cap.errs.join('\n')).toContain('--page');
+ });
+});
+
+// ---- verify git lane resolves each row via its OWNING source's local_path ----
+// upload-raw (#2297) banks storage_path relative to target.writeRoot — the
+// source's OWN local_path for sources with a separate working tree. verify
+// used to join every git row against sync.repo_path only, so those rows
+// falsely reported MISSING (or hash-checked the wrong file).
+describe('files verify git lane (per-source root resolution)', () => {
+ let engine: PGLiteEngine;
+ let repo: string; // sync.repo_path — the brain-global repo
+ let vault: string; // the 'vault' source's separate working tree
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-verify-repo-'));
+ vault = mkdtempSync(join(tmpdir(), 'gbrain-verify-vault-'));
+ await engine.setConfig('sync.repo_path', repo);
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config, created_at)
+ VALUES ('vault', 'vault', $1, '{}'::jsonb, NOW())
+ ON CONFLICT (id) DO NOTHING`,
+ [vault],
+ );
+ await engine.putPage('notes/vault-doc', {
+ title: 'Vault Doc', type: 'concept', frontmatter: {},
+ compiled_truth: 'body', timeline: '',
+ }, { sourceId: 'vault' });
+ await engine.putPage('notes/default-doc', {
+ title: 'Default Doc', type: 'concept', frontmatter: {},
+ compiled_truth: 'body', timeline: '',
+ });
+ });
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (repo) rmSync(repo, { recursive: true, force: true });
+ if (vault) rmSync(vault, { recursive: true, force: true });
+ });
+
+ function captureLogs() {
+ const logs: string[] = [];
+ const errs: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ return { logs, errs, restore: () => { logSpy.mockRestore(); errSpy.mockRestore(); } };
+ }
+
+ test('rows banked under a source-owned working tree verify against that tree, not sync.repo_path', async () => {
+ const srcDir = mkdtempSync(join(tmpdir(), 'gbrain-verify-src-'));
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ const cap = captureLogs();
+ try {
+ // One git row in the vault source (separate working tree), one in the
+ // default source (sync.repo_path fallback).
+ const vaultFile = join(srcDir, 'vault-report.txt');
+ writeFileSync(vaultFile, 'vault numbers');
+ await runFiles(engine, ['upload-raw', vaultFile, '--page', 'notes/vault-doc', '--source', 'vault']);
+ const defaultFile = join(srcDir, 'default-report.txt');
+ writeFileSync(defaultFile, 'default numbers');
+ await runFiles(engine, ['upload-raw', defaultFile, '--page', 'notes/default-doc', '--source', 'default']);
+
+ // Sanity: the vault row's storage_path is relative to the VAULT tree —
+ // it does not exist under sync.repo_path.
+ const rows = await engine.executeRaw<{ storage_path: string; source_id: string }>(
+ `SELECT storage_path, source_id FROM files WHERE filename = 'vault-report.txt'`,
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0].source_id).toBe('vault');
+ expect(existsSync2297(join(vault, rows[0].storage_path))).toBe(true);
+ expect(existsSync2297(join(repo, rows[0].storage_path))).toBe(false);
+
+ await runFiles(engine, ['verify']);
+ const all = [...cap.logs, ...cap.errs].join('\n');
+ expect(all).not.toContain('MISSING');
+ expect(all).not.toContain('MISMATCH');
+ expect(all).toContain('2 files verified, 0 mismatches, 0 missing');
+ } finally {
+ cap.restore();
+ exitSpy.mockRestore();
+ rmSync(srcDir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/get-timeline-op.test.ts b/test/get-timeline-op.test.ts
index b969de0d0b..06554eeb55 100644
--- a/test/get-timeline-op.test.ts
+++ b/test/get-timeline-op.test.ts
@@ -11,6 +11,10 @@ function makeCtx(): OperationContext {
calls.push({ slug, opts });
return [];
},
+ // #4352 gate surface: remote callers resolve the private-pages config
+ // (no opt-out here) and probe for private-only slugs (none here).
+ getConfig: async () => null,
+ executeRaw: async () => [],
};
return {
diff --git a/test/git-remote-pull-file-transport.serial.test.ts b/test/git-remote-pull-file-transport.serial.test.ts
new file mode 100644
index 0000000000..82575452f1
--- /dev/null
+++ b/test/git-remote-pull-file-transport.serial.test.ts
@@ -0,0 +1,99 @@
+/**
+ * #3836 — pullRepo/fetchRemote build their global git flags via
+ * durableSsrfFlags() so the documented GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1
+ * escape hatch reaches sync's pull. Pre-fix they hardcoded GIT_SSRF_FLAGS
+ * (protocol.file.allow=never, unconditionally), so a self-hosted
+ * local-filesystem remote could be CLONED (via the harden/durability paths)
+ * but `gbrain sync` could never pull it again.
+ *
+ * Default posture stays never — asserted below.
+ *
+ * .serial: process.env mutation + real git subprocesses (docs/TESTING.md R1).
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { execFileSync } from 'node:child_process';
+import {
+ pullRepo,
+ fetchRemote,
+ durableSsrfFlags,
+ GitOperationError,
+} from '../src/core/git-remote.ts';
+
+let root: string;
+
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync('git', ['-C', cwd, '-c', 'protocol.file.allow=always', ...args], {
+ stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8',
+ }).trim();
+}
+
+/** Bare origin + writer clone (pushes main) + a reader clone (the sync repo). */
+function makeTrio(): { bare: string; writer: string; reader: string } {
+ const bare = mkdtempSync(join(root, 'origin-')) + '.git';
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', bare], { stdio: 'ignore' });
+ const writer = mkdtempSync(join(root, 'writer-'));
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, writer], { stdio: 'ignore' });
+ git(writer, 'config', 'user.email', '[email protected]');
+ git(writer, 'config', 'user.name', 'tester');
+ writeFileSync(join(writer, 'README.md'), 'init\n');
+ git(writer, 'add', 'README.md');
+ git(writer, 'commit', '-qm', 'init');
+ git(writer, 'push', '-q', 'origin', 'main');
+ const reader = mkdtempSync(join(root, 'reader-'));
+ execFileSync('git', ['-c', 'protocol.file.allow=always', 'clone', '-q', bare, reader], { stdio: 'ignore' });
+ return { bare, writer, reader };
+}
+
+function pushSecondCommit(writer: string): void {
+ writeFileSync(join(writer, 'NEW.md'), 'second commit\n');
+ git(writer, 'add', 'NEW.md');
+ git(writer, 'commit', '-qm', 'second');
+ git(writer, 'push', '-q', 'origin', 'main');
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-3836-'));
+ delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT;
+});
+afterEach(() => {
+ delete process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT;
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('#3836 durableSsrfFlags env toggle (unit)', () => {
+ test('default builds protocol.file.allow=never; env=1 flips it to always', () => {
+ expect(durableSsrfFlags()).toContain('protocol.file.allow=never');
+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
+ expect(durableSsrfFlags()).toContain('protocol.file.allow=always');
+ });
+});
+
+describe('#3836 pullRepo honors the file-transport escape hatch', () => {
+ test('default posture: pull over the file transport still refuses', () => {
+ const { writer, reader } = makeTrio();
+ pushSecondCommit(writer);
+ expect(() => pullRepo(reader)).toThrow(GitOperationError);
+ expect(existsSync(join(reader, 'NEW.md'))).toBe(false);
+ });
+
+ test('GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1: sync-style pull succeeds and lands the new commit', () => {
+ const { writer, reader } = makeTrio();
+ pushSecondCommit(writer);
+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
+ pullRepo(reader);
+ expect(readFileSync(join(reader, 'NEW.md'), 'utf-8')).toContain('second commit');
+ });
+
+ test('GBRAIN_GIT_ALLOW_FILE_TRANSPORT=1: fetchRemote (cost-estimator path) succeeds too', () => {
+ const { writer, reader } = makeTrio();
+ pushSecondCommit(writer);
+ process.env.GBRAIN_GIT_ALLOW_FILE_TRANSPORT = '1';
+ fetchRemote(reader, 'main');
+ const fetched = git(reader, 'rev-parse', 'FETCH_HEAD');
+ const pushed = git(writer, 'rev-parse', 'HEAD');
+ expect(fetched).toBe(pushed);
+ });
+});
diff --git a/test/grade-takes-evidence.test.ts b/test/grade-takes-evidence.test.ts
new file mode 100644
index 0000000000..99a0016fbc
--- /dev/null
+++ b/test/grade-takes-evidence.test.ts
@@ -0,0 +1,197 @@
+/**
+ * #2811 — grade_takes evidence retrieval is REAL now.
+ *
+ * Pre-fix, defaultEvidenceRetriever returned the literal placeholder
+ * '[evidence retrieval not yet wired — v0.36.1.0 ship-state]' and the whole
+ * calibration loop graded takes against their own claim text — every verdict
+ * was structurally 'unresolvable'.
+ *
+ * Post-fix: hybrid search on the take's claim (expansion off, source-scoped,
+ * own page excluded) + the pure formatEvidenceBlock (effective_date vs
+ * since_date annotation, ~500c/item clamp, 4k block cap, no-evidence +
+ * fail-open fallbacks). PROMPT_VERSION moved off '-stub' so cached stub
+ * verdicts are cleanly invalidated.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ formatEvidenceBlock,
+ defaultEvidenceRetriever,
+ GRADE_TAKES_PROMPT_VERSION,
+ EVIDENCE_ITEM_CLAMP_CHARS,
+ EVIDENCE_BLOCK_CAP_CHARS,
+ type EvidenceHit,
+} from '../src/core/cycle/grade-takes.ts';
+import { __setEmbedTransportForTests, resetGateway, configureGateway } from '../src/core/ai/gateway.ts';
+import type { Take, BrainEngine } from '../src/core/engine.ts';
+
+function makeTake(overrides: Partial<Take> = {}): Take {
+ return {
+ id: 1,
+ page_id: 1,
+ page_slug: 'companies/acme-corp',
+ claim: 'Acme Corp will double ARR by Q4 2024',
+ kind: 'bet',
+ holder: 'brain',
+ weight: 0.7,
+ since_date: '2024-01',
+ ...overrides,
+ } as unknown as Take;
+}
+
+// ─── formatEvidenceBlock (pure) ─────────────────────────────────────
+
+describe('formatEvidenceBlock (#2811)', () => {
+ test('zero hits → explicit no-evidence note steering to unresolvable', () => {
+ const block = formatEvidenceBlock(makeTake(), []);
+ expect(block).toContain('No evidence found');
+ expect(block).toContain('2024-01');
+ expect(block).toContain('unresolvable');
+ expect(block).not.toContain('not yet wired');
+ });
+
+ test('items carry slug + date and are annotated before/after the claim', () => {
+ const hits: EvidenceHit[] = [
+ { slug: 'notes/after', title: 'After', chunk_text: 'Acme doubled ARR in November.', effective_date: '2024-11-20' },
+ { slug: 'notes/before', title: 'Before', chunk_text: 'Acme planned aggressive growth.', effective_date: '2023-06-01' },
+ { slug: 'notes/undated', title: 'Undated', chunk_text: 'Acme ships weekly.', effective_date: null },
+ ];
+ const block = formatEvidenceBlock(makeTake(), hits);
+ expect(block).toContain('[notes/after • 2024-11-20]');
+ expect(block).toContain('(dated after the claim)');
+ expect(block).toContain('[notes/before • 2023-06-01]');
+ expect(block).toContain('BEFORE the claim');
+ expect(block).toContain('[notes/undated • undated]');
+ });
+
+ test('same-month hit (YYYY-MM since_date) counts as after, not before', () => {
+ const hits: EvidenceHit[] = [
+ { slug: 'notes/same-month', title: 's', chunk_text: 'Acme signed the deal.', effective_date: '2024-01-20' },
+ ];
+ const block = formatEvidenceBlock(makeTake({ since_date: '2024-01' } as Partial<Take>), hits);
+ expect(block).toContain('(dated after the claim)');
+ });
+
+ test('items clamp at ~500 chars and the block caps at 4k', () => {
+ const long = 'x'.repeat(2000);
+ const hits: EvidenceHit[] = Array.from({ length: 20 }, (_, i) => ({
+ slug: `notes/long-${i}`,
+ title: `L${i}`,
+ chunk_text: long,
+ effective_date: '2024-06-01',
+ }));
+ const block = formatEvidenceBlock(makeTake(), hits);
+ // No single item body exceeds the clamp.
+ expect(block).not.toContain('x'.repeat(EVIDENCE_ITEM_CLAMP_CHARS + 1));
+ expect(block.length).toBeLessThanOrEqual(EVIDENCE_BLOCK_CAP_CHARS + 40);
+ expect(block).toContain('[evidence truncated]');
+ });
+
+ test('hits with only whitespace text fall back to the no-usable-evidence note', () => {
+ const hits: EvidenceHit[] = [
+ { slug: 'notes/blank', title: 'b', chunk_text: ' \n ', effective_date: null },
+ ];
+ const block = formatEvidenceBlock(makeTake(), hits);
+ expect(block).toContain('No usable evidence');
+ expect(block).toContain('unresolvable');
+ });
+});
+
+// ─── prompt version off the stub ────────────────────────────────────
+
+describe('GRADE_TAKES_PROMPT_VERSION (#2811)', () => {
+ test('moved off -stub so cached stub verdicts invalidate', () => {
+ expect(GRADE_TAKES_PROMPT_VERSION).not.toContain('stub');
+ });
+});
+
+// ─── defaultEvidenceRetriever over PGLite ───────────────────────────
+
+describe('defaultEvidenceRetriever over PGLite (#2811)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ resetGateway();
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'sk-test' },
+ });
+ __setEmbedTransportForTests(
+ (async ({ values }: { values: string[] }) => ({
+ embeddings: values.map(() => Array.from({ length: 1536 }, () => 0.1)),
+ })) as never,
+ );
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ await engine.putPage('companies/acme-corp', {
+ type: 'company',
+ title: 'Acme Corp',
+ compiled_truth: 'Acme Corp will double ARR by Q4 2024 — the take page itself.',
+ });
+ await engine.putPage('notes/acme-outcome', {
+ type: 'note',
+ title: 'Acme outcome update',
+ compiled_truth: 'Acme Corp doubled ARR in November 2024, closing the year strong.',
+ });
+ // putPage does not chunk; sync/import does. Seed chunks the way a synced
+ // brain carries them so the retriever has real chunk_text to format.
+ await engine.upsertChunks('companies/acme-corp', [{
+ chunk_index: 0,
+ chunk_text: 'Acme Corp will double ARR by Q4 2024 — the take page itself.',
+ chunk_source: 'compiled_truth',
+ embedding: new Float32Array(1536).fill(0.1),
+ token_count: 16,
+ }]);
+ await engine.upsertChunks('notes/acme-outcome', [{
+ chunk_index: 0,
+ chunk_text: 'Acme Corp doubled ARR in November 2024, closing the year strong.',
+ chunk_source: 'compiled_truth',
+ embedding: new Float32Array(1536).fill(0.1),
+ token_count: 16,
+ }]);
+ });
+
+ afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+ await engine.disconnect();
+ });
+
+ test('retrieves real brain evidence and EXCLUDES the take\'s own page', async () => {
+ const block = await defaultEvidenceRetriever(engine, makeTake(), { sourceId: 'default' });
+ expect(block).toContain('notes/acme-outcome');
+ expect(block).not.toContain('[companies/acme-corp');
+ expect(block).not.toContain('not yet wired');
+ }, 60000);
+
+ test('source scope is honored: an empty source yields the no-evidence fallback', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('empty-src', 'Empty') ON CONFLICT (id) DO NOTHING`,
+ [],
+ );
+ const block = await defaultEvidenceRetriever(engine, makeTake(), { sourceId: 'empty-src' });
+ // The default source HAS matching evidence — none of it may leak into
+ // an empty source's scope.
+ expect(block).not.toContain('notes/acme-outcome');
+ expect(block).toContain('unresolvable');
+ }, 60000);
+
+ test('fail-open: a broken engine degrades to a claim-only note instead of throwing', async () => {
+ const broken = {
+ executeRaw: async () => { throw new Error('db exploded'); },
+ getConfig: async () => { throw new Error('db exploded'); },
+ } as unknown as BrainEngine;
+ const block = await defaultEvidenceRetriever(broken, makeTake(), { sourceId: 'default' });
+ expect(block).toContain('[evidence retrieval failed');
+ expect(block).toContain('Acme Corp will double ARR');
+ expect(block).toContain('unresolvable');
+ }, 60000);
+});
diff --git a/test/guardrails-env-load.test.ts b/test/guardrails-env-load.test.ts
new file mode 100644
index 0000000000..2153e6a089
--- /dev/null
+++ b/test/guardrails-env-load.test.ts
@@ -0,0 +1,119 @@
+/**
+ * #3688 — GBRAIN_GUARDRAILS_MODULE operator wiring.
+ *
+ * Before this fix, registerGuardrailProvider existed only in-module + docs:
+ * the package exports map lacked './core/guardrails' and nothing in cli.ts
+ * ever loaded a provider, so runGuardrails no-op'd forever (providers.size
+ * === 0) — the documented firewall was unreachable. Covers:
+ * - unset env → no-op, stays inert
+ * - default-export provider, provider array, guardrailProviders, register()
+ * - fail-CLOSED: unloadable module throws GuardrailLoadError
+ * - fail-CLOSED: module that registers nothing throws GuardrailLoadError
+ */
+
+import { describe, test, expect, beforeEach, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import {
+ __resetGuardrailProvidersForTests,
+ hasGuardrails,
+ loadGuardrailProvidersFromEnv,
+ runGuardrails,
+ GuardrailLoadError,
+} from '../src/core/guardrails.ts';
+
+// One fresh mkdtemp per fixture: bun caches a directory's listing after the
+// first dynamic import from it, so a second module written into the SAME dir
+// resolves as "Cannot find module" mid-run.
+const dirs: string[] = [];
+
+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });
+beforeEach(() => __resetGuardrailProvidersForTests());
+
+/** Write a fixture module into its own temp dir; returns the absolute path. */
+function fixture(name: string, source: string): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-guardrails-3688-'));
+ dirs.push(dir);
+ const p = join(dir, name);
+ writeFileSync(p, source);
+ return p;
+}
+
+describe('loadGuardrailProvidersFromEnv (#3688)', () => {
+ test('unset env var → no-op, distribution stays inert', async () => {
+ const out = await loadGuardrailProvidersFromEnv({});
+ expect(out.loaded).toBe(0);
+ expect(out.modulePath).toBeNull();
+ expect(hasGuardrails()).toBe(false);
+ });
+
+ test('default-exported provider registers and receives classify calls', async () => {
+ const p = fixture('default-provider.mjs', `
+ globalThis.__gr3688_calls = [];
+ export default {
+ id: 'fixture-default',
+ classify(input) { globalThis.__gr3688_calls.push(input); },
+ };
+ `);
+ const out = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p });
+ expect(out.loaded).toBe(1);
+ expect(hasGuardrails()).toBe(true);
+ await runGuardrails({ hook: 'file_storage.markdown', content: 'hello world' });
+ const calls = (globalThis as Record<string, unknown>).__gr3688_calls as Array<{ hook: string; content: string }>;
+ expect(calls.length).toBe(1);
+ expect(calls[0].hook).toBe('file_storage.markdown');
+ expect(calls[0].content).toBe('hello world');
+ });
+
+ test('default-exported provider ARRAY registers every provider', async () => {
+ const p = fixture('array-provider.mjs', `
+ export default [
+ { id: 'fixture-a', classify() {} },
+ { id: 'fixture-b', classify() {} },
+ ];
+ `);
+ const out = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p });
+ expect(out.loaded).toBe(2);
+ });
+
+ test('named guardrailProviders array registers', async () => {
+ const p = fixture('named-providers.mjs', `
+ export const guardrailProviders = [{ id: 'fixture-named', classify() {} }];
+ `);
+ const out = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p });
+ expect(out.loaded).toBe(1);
+ });
+
+ test('register(fn) callback shape registers (async supported)', async () => {
+ const p = fixture('register-fn.mjs', `
+ export async function register(registerGuardrailProvider) {
+ registerGuardrailProvider({ id: 'fixture-register', classify() {} });
+ }
+ `);
+ const out = await loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p });
+ expect(out.loaded).toBe(1);
+ });
+
+ test('fail-closed: unloadable module throws GuardrailLoadError', async () => {
+ await expect(
+ loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: join(tmpdir(), 'gbrain-3688-does-not-exist.mjs') }),
+ ).rejects.toBeInstanceOf(GuardrailLoadError);
+ expect(hasGuardrails()).toBe(false);
+ });
+
+ test('fail-closed: module that registers nothing throws GuardrailLoadError', async () => {
+ const p = fixture('empty-module.mjs', `export const unrelated = 42;`);
+ await expect(
+ loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p }),
+ ).rejects.toBeInstanceOf(GuardrailLoadError);
+ expect(hasGuardrails()).toBe(false);
+ });
+
+ test('fail-closed: default export that is not a valid provider throws', async () => {
+ const p = fixture('bad-shape.mjs', `export default { id: 'no-classify' };`);
+ await expect(
+ loadGuardrailProvidersFromEnv({ GBRAIN_GUARDRAILS_MODULE: p }),
+ ).rejects.toBeInstanceOf(GuardrailLoadError);
+ });
+});
diff --git a/test/helpers/git-exec.ts b/test/helpers/git-exec.ts
new file mode 100644
index 0000000000..ebf1c7eec5
--- /dev/null
+++ b/test/helpers/git-exec.ts
@@ -0,0 +1,61 @@
+/**
+ * test/helpers/git-exec.ts — #4230.
+ *
+ * execSync git wrapper for test fixture setup. Two problems it solves:
+ *
+ * 1. **Transient flake under the pooled serial lane (pool=4).** git
+ * init/add/commit in a fresh tmp repo occasionally fails transiently
+ * when four bun workers hammer spawn + the filesystem at once. The
+ * wrapper retries twice with a small jittered backoff, so one blip
+ * doesn't fail a whole serial suite.
+ * 2. **Undiagnosable failures.** `execSync(..., { stdio: 'pipe' })` throws
+ * an error whose message is just "Command failed" — git's actual stderr
+ * is buried in a Buffer property that the test reporter never prints.
+ * On final failure the wrapper throws a single Error carrying the
+ * command, cwd, exit status, stderr, and stdout, so the NEXT flake is a
+ * one-minute diagnosis instead of a re-run guessing game.
+ *
+ * Deliberately test-only: production git use goes through the repo's own
+ * runners; this helper exists so fixture setup keeps pool=4 without flaking.
+ */
+
+import { execSync } from 'node:child_process';
+
+interface ExecError {
+ status?: number | null;
+ stderr?: Buffer | string;
+ stdout?: Buffer | string;
+ message?: string;
+}
+
+/** Total attempts = 1 + GIT_EXEC_RETRIES. */
+const GIT_EXEC_RETRIES = 2;
+
+/**
+ * Run a git command in `cwd`, retrying transient failures with jittered
+ * backoff and surfacing git's stderr in the thrown error on final failure.
+ */
+export function gitExec(cmd: string, cwd: string): string {
+ let lastErr: ExecError | null = null;
+ for (let attempt = 0; attempt <= GIT_EXEC_RETRIES; attempt++) {
+ if (attempt > 0) {
+ // Jittered backoff: 50-200ms on the first retry, 100-400ms on the
+ // second — enough to ride out a spawn/fs contention blip without
+ // meaningfully slowing a genuinely-broken setup's failure.
+ Bun.sleepSync((50 + Math.random() * 150) * attempt);
+ }
+ try {
+ return execSync(cmd, { cwd, stdio: 'pipe', encoding: 'utf8' });
+ } catch (e) {
+ lastErr = e as ExecError;
+ }
+ }
+ const stderr = lastErr?.stderr?.toString().trim();
+ const stdout = lastErr?.stdout?.toString().trim();
+ throw new Error(
+ `git exec failed after ${GIT_EXEC_RETRIES + 1} attempts: \`${cmd}\` ` +
+ `(cwd: ${cwd}, exit: ${lastErr?.status ?? 'unknown'})` +
+ (stderr ? `\nstderr: ${stderr}` : '') +
+ (stdout ? `\nstdout: ${stdout}` : ''),
+ );
+}
diff --git a/test/hybrid-exclude-private-cache-fold.serial.test.ts b/test/hybrid-exclude-private-cache-fold.serial.test.ts
new file mode 100644
index 0000000000..5efee55dba
--- /dev/null
+++ b/test/hybrid-exclude-private-cache-fold.serial.test.ts
@@ -0,0 +1,170 @@
+/**
+ * #4352 follow-up — excludePrivate searches CACHE (posture folded into
+ * knobsHash), they no longer skip the semantic query cache.
+ *
+ * #4352 originally shipped a wholesale `privateFiltered || ` skipCache term —
+ * but excludePrivate=true is the DEFAULT for every remote MCP caller, so the
+ * skip disabled the cache for exactly the highest-volume beneficiaries
+ * (~50% cost savings lost). The v=23 fold (xp=) restores caching while
+ * keeping the postures contamination-proof. Pins:
+ * 1. a remote-default (excludePrivate=true) run reports 'miss' then 'hit'
+ * on repeat — never 'disabled' — and never surfaces a private page,
+ * 2. a trusted (private-included) write is never served to a
+ * private-excluding read (distinct knobs_hash rows),
+ * 3. a private-excluding write is never served to a trusted read.
+ *
+ * Serial: mock.module + gateway/global-env mutation (same harness shape as
+ * test/hybrid-types-cache-skip.serial.test.ts).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, 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';
+import type { HybridSearchMeta } from '../src/core/types.ts';
+
+/** Deterministic 1536d unit vector so consults match writes 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.module('../src/core/embedding.ts', () => ({
+ ...realEmbedding,
+ embed: async () => fixedEmbedding(),
+ embedQuery: async () => fixedEmbedding(),
+}));
+
+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');
+
+setDefaultTimeout(30_000);
+
+let engine: InstanceType<typeof PGLiteEngine>;
+let tmpHome: string;
+const savedGbrainHome = process.env.GBRAIN_HOME;
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-private-cache-fold-'));
+ 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();
+
+ const fixtures: Array<[string, string, Record<string, unknown>]> = [
+ ['notes/world-widget', 'Widget World', { visibility: 'world' }],
+ ['notes/private-widget', 'Widget Private', { visibility: 'private' }],
+ ];
+ for (const [slug, title, frontmatter] of fixtures) {
+ const truth = `${title} is a builder.`;
+ await engine.putPage(slug, { type: 'concept', title, frontmatter, 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 */ }
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM query_cache');
+});
+
+describe('#4352 follow-up — excludePrivate folds into the cache key instead of skipping', () => {
+ test('a remote-default run gets miss then hit (never disabled) and never a private page', async () => {
+ // 1. First excludePrivate run: cache MISS (not 'disabled' — the pre-fix
+ // wholesale skip is the regression this pins), filtered results.
+ let firstMeta: HybridSearchMeta | undefined;
+ const first = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ excludePrivate: true,
+ onMeta: (m) => { firstMeta = m; },
+ });
+ expect(firstMeta?.cache?.status).toBe('miss');
+ expect(first.map((r) => r.slug)).toEqual(['notes/world-widget']);
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);
+
+ // 2. Repeat run under the SAME posture: HIT, still filtered.
+ let repeatMeta: HybridSearchMeta | undefined;
+ const repeat = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ excludePrivate: true,
+ onMeta: (m) => { repeatMeta = m; },
+ });
+ expect(repeatMeta?.cache?.status).toBe('hit');
+ expect(repeat.map((r) => r.slug)).toEqual(['notes/world-widget']);
+ });
+
+ test('a trusted (private-included) write is never served to an excludePrivate read', async () => {
+ // 1. Trusted miss-run stores a row containing BOTH pages.
+ let trustedMeta: HybridSearchMeta | undefined;
+ const trusted = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ onMeta: (m) => { trustedMeta = m; },
+ });
+ expect(trustedMeta?.cache?.status).toBe('miss');
+ expect(trusted.map((r) => r.slug).sort()).toEqual(['notes/private-widget', 'notes/world-widget']);
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);
+
+ // 2. Same query, remote posture: identical embedding — pre-fold this
+ // would have HIT the trusted row and leaked the private page. Must
+ // MISS onto its own key instead (fresh, filtered query).
+ let remoteMeta: HybridSearchMeta | undefined;
+ const remote = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ excludePrivate: true,
+ onMeta: (m) => { remoteMeta = m; },
+ });
+ expect(remoteMeta?.cache?.status).toBe('miss');
+ expect(remote.map((r) => r.slug)).toEqual(['notes/world-widget']);
+
+ // 3. The remote run stores its OWN row — two distinct knobs_hash rows.
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(2);
+ });
+
+ test('an excludePrivate write is never served to a trusted read (no hidden pages)', async () => {
+ let remoteMeta: HybridSearchMeta | undefined;
+ await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ excludePrivate: true,
+ onMeta: (m) => { remoteMeta = m; },
+ });
+ expect(remoteMeta?.cache?.status).toBe('miss');
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);
+
+ // A trusted read of the same query must NOT be served the filtered row —
+ // it is entitled to the private page.
+ let trustedMeta: HybridSearchMeta | undefined;
+ const trusted = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ onMeta: (m) => { trustedMeta = m; },
+ });
+ expect(trustedMeta?.cache?.status).toBe('miss');
+ expect(trusted.map((r) => r.slug).sort()).toEqual(['notes/private-widget', 'notes/world-widget']);
+ });
+});
diff --git a/test/hybrid-meta.serial.test.ts b/test/hybrid-meta.serial.test.ts
index a5194c3d4b..03ef67a650 100644
--- a/test/hybrid-meta.serial.test.ts
+++ b/test/hybrid-meta.serial.test.ts
@@ -100,3 +100,26 @@ describe('onMeta callback omitted', () => {
expect(Array.isArray(out)).toBe(true);
});
});
+
+describe('#3808 — keyword-only degradation is visible on stderr (once per process)', () => {
+ test('the no-provider branch warns with the diagnose reason and a doctor hint', async () => {
+ delete process.env.OPENAI_API_KEY;
+ const { _resetWarnOnceForTests } = await import('../src/core/utils.ts');
+ _resetWarnOnceForTests();
+ const warns: string[] = [];
+ const orig = console.warn;
+ console.warn = (...args: unknown[]) => { warns.push(args.map(String).join(' ')); };
+ try {
+ await hybridSearch(engine, 'alice');
+ await hybridSearch(engine, 'alice example person');
+ } finally {
+ console.warn = orig;
+ }
+ const hits = warns.filter((w) => w.includes('vector search unavailable'));
+ // Fires exactly once per process regardless of how many degraded
+ // searches run — pre-#3808 this was silent (meta-only).
+ expect(hits.length).toBe(1);
+ expect(hits[0]).toContain('keyword-only');
+ expect(hits[0]).toContain('gbrain doctor');
+ });
+});
diff --git a/test/hybrid-types-cache-skip.serial.test.ts b/test/hybrid-types-cache-skip.serial.test.ts
new file mode 100644
index 0000000000..04ef026ef5
--- /dev/null
+++ b/test/hybrid-types-cache-skip.serial.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #3985 — `types`-filtered searches must bypass the semantic query cache.
+ *
+ * `types` is not part of knobsHash, so a type-filtered result set stored in
+ * the cache could be served to an unfiltered lookup (and vice versa) — the
+ * same contamination class as #3442's date filters. Pins:
+ * 1. a types run reports cache 'disabled' (skip on lookup AND store),
+ * 2. an unfiltered write is never served to a types read,
+ * 3. a types run never stores a row for later unfiltered hits.
+ *
+ * Serial: mock.module + gateway/global-env mutation (same harness shape as
+ * test/hybrid-cache-scope-poison.serial.test.ts).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, 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';
+import type { HybridSearchMeta } from '../src/core/types.ts';
+
+/** Deterministic 1536d unit vector so consults match writes 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.module('../src/core/embedding.ts', () => ({
+ ...realEmbedding,
+ embed: async () => fixedEmbedding(),
+ embedQuery: async () => fixedEmbedding(),
+}));
+
+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');
+
+setDefaultTimeout(30_000);
+
+let engine: InstanceType<typeof PGLiteEngine>;
+let tmpHome: string;
+const savedGbrainHome = process.env.GBRAIN_HOME;
+
+beforeAll(async () => {
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-types-cache-skip-'));
+ 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();
+
+ const fixtures: Array<[string, string, string]> = [
+ ['alice-foo', 'Alice Foo', 'person'],
+ ['bob-bar', 'Bob Bar', 'company'],
+ ];
+ for (const [slug, title, type] of fixtures) {
+ const truth = `${title} is a builder.`;
+ await engine.putPage(slug, { type, title, 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 */ }
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM query_cache');
+});
+
+describe('#3985 — types-filtered requests skip the semantic cache', () => {
+ test('an unfiltered write is never served to a types read (and the types run stores nothing)', async () => {
+ // 1. Unfiltered miss-run stores a row containing BOTH pages.
+ let missMeta: HybridSearchMeta | undefined;
+ const unfiltered = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ onMeta: (m) => { missMeta = m; },
+ });
+ expect(missMeta?.cache?.status).toBe('miss');
+ expect(unfiltered.map((r) => r.slug).sort()).toEqual(['alice-foo', 'bob-bar']);
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);
+
+ // 2. Same query WITH a types filter: identical embedding + knobs would
+ // have HIT the stored all-types row pre-fix. Must bypass instead.
+ let typesMeta: HybridSearchMeta | undefined;
+ const personsOnly = await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ types: ['person'],
+ onMeta: (m) => { typesMeta = m; },
+ });
+ expect(typesMeta?.cache?.status).toBe('disabled');
+ expect(personsOnly.map((r) => r.slug)).toEqual(['alice-foo']);
+
+ // 3. The types run must not have stored anything either.
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);
+ });
+
+ test('a types-first run leaves the cache empty, so a later unfiltered read gets full recall', async () => {
+ let typesMeta: HybridSearchMeta | undefined;
+ await hybridSearchCached(engine, 'builder', {
+ limit: 10,
+ types: ['company'],
+ onMeta: (m) => { typesMeta = m; },
+ });
+ expect(typesMeta?.cache?.status).toBe('disabled');
+ await awaitPendingSearchCacheWrites();
+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);
+
+ const unfiltered = await hybridSearchCached(engine, 'builder', { limit: 10 });
+ expect(unfiltered.map((r) => r.slug).sort()).toEqual(['alice-foo', 'bob-bar']);
+ });
+});
diff --git a/test/import-source-cr-mode.serial.test.ts b/test/import-source-cr-mode.serial.test.ts
new file mode 100644
index 0000000000..070e79e7c9
--- /dev/null
+++ b/test/import-source-cr-mode.serial.test.ts
@@ -0,0 +1,117 @@
+/**
+ * #3885 — the inline import path (capture / put_page / reindex --markdown)
+ * must load the REAL source row when resolving the contextual-retrieval
+ * mode, so a stored `gbrain sources set-cr-mode <id> <mode>` applies.
+ *
+ * Pre-fix: import-file.ts hardcoded a source stub with
+ * `contextual_retrieval_mode: null / trust_frontmatter_overrides: false`,
+ * so a per-source 'none' override was ignored and the global bundle
+ * (balanced → title) silently won.
+ *
+ * .serial: real PGLite + gateway stubbing (docs/TESTING.md R1).
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import {
+ __setEmbedTransportForTests,
+ configureGateway,
+ resetGateway,
+} from '../src/core/ai/gateway.ts';
+
+const STUB_DIMS = 1536;
+
+let engine: PGLiteEngine;
+const embedderInputs: string[][] = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: STUB_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake-key-for-stub' },
+ });
+ __setEmbedTransportForTests(async ({ values }: any) => {
+ embedderInputs.push([...values]);
+ return {
+ embeddings: values.map(() => new Array<number>(STUB_DIMS).fill(0.001)),
+ usage: { tokens: 0 },
+ } as any;
+ });
+
+ // Two registered sources: one with a stored per-source CR override,
+ // one without (falls through to the global bundle).
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, contextual_retrieval_mode) VALUES ($1, $2, $3)
+ ON CONFLICT (id) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode`,
+ ['vault-off', 'Vault Off', 'none'],
+ );
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, contextual_retrieval_mode) VALUES ($1, $2, $3)
+ ON CONFLICT (id) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode`,
+ ['vault-syn', 'Vault Synopsis', 'per_chunk_synopsis'],
+ );
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`,
+ ['vault-plain', 'Vault Plain'],
+ );
+}, 120_000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(() => {
+ embedderInputs.length = 0;
+});
+
+const CONTENT = `---
+title: "CR Mode Probe"
+type: note
+---
+
+A body long enough to produce at least one chunk of prose for the
+contextual-retrieval wrapper decision to matter at embed time.
+`;
+
+async function stampedMode(slug: string, sourceId: string): Promise<string | null> {
+ const rows = await engine.executeRaw<{ contextual_retrieval_mode: string | null }>(
+ `SELECT contextual_retrieval_mode FROM pages WHERE slug = $1 AND source_id = $2`,
+ [slug, sourceId],
+ );
+ expect(rows.length).toBe(1);
+ return rows[0].contextual_retrieval_mode;
+}
+
+describe('#3885 stored per-source CR mode applies on the inline import path', () => {
+ test("source override 'none' beats the global bundle (balanced → title)", async () => {
+ await importFromContent(engine, 'notes/probe-off', CONTENT, { sourceId: 'vault-off' });
+ expect(await stampedMode('notes/probe-off', 'vault-off')).toBe('none');
+ // With mode 'none', the embedder saw the RAW chunk text — no title wrap.
+ const flat = embedderInputs.flat();
+ expect(flat.length).toBeGreaterThan(0);
+ for (const input of flat) {
+ expect(input).not.toContain('CR Mode Probe');
+ }
+ }, 60_000);
+
+ test('source WITHOUT an override keeps the global bundle (title tier wrap)', async () => {
+ await importFromContent(engine, 'notes/probe-plain', CONTENT, { sourceId: 'vault-plain' });
+ expect(await stampedMode('notes/probe-plain', 'vault-plain')).toBe('title');
+ const flat = embedderInputs.flat();
+ expect(flat.length).toBeGreaterThan(0);
+ expect(flat.some((input) => input.includes('CR Mode Probe'))).toBe(true);
+ }, 60_000);
+
+ test("source override 'per_chunk_synopsis' keeps the deliberate inline downgrade to 'title'", async () => {
+ await importFromContent(engine, 'notes/probe-syn', CONTENT, { sourceId: 'vault-syn' });
+ // Inline import never runs per-chunk synopsis (Minion backfill does);
+ // the downgrade to the free title tier is deliberate and stays.
+ expect(await stampedMode('notes/probe-syn', 'vault-syn')).toBe('title');
+ }, 60_000);
+});
diff --git a/test/ingest-log-noop-gate.test.ts b/test/ingest-log-noop-gate.test.ts
new file mode 100644
index 0000000000..773263a122
--- /dev/null
+++ b/test/ingest-log-noop-gate.test.ts
@@ -0,0 +1,87 @@
+/**
+ * issue #3969 — unconditional no-op ingest_log writes made get_ingest_log
+ * unusable on a cron (93% of rows were "Imported 0 pages, N skipped, 0
+ * chunks"). runImport (and performSync's mirror) now gate the write through
+ * shouldLogIngest: skip when imported===0 && errors===0 && chunksCreated===0,
+ * unless --log-noop opts back in.
+ *
+ * Hermetic PGLite; temp dir + sandboxed GBRAIN_HOME (checkpoint/ledger files
+ * never touch the real ~/.gbrain).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runImport, shouldLogIngest } from '../src/commands/import.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+describe('shouldLogIngest predicate (#3969)', () => {
+ test('all-zero counters without --log-noop → skip', () => {
+ expect(shouldLogIngest({ imported: 0, errors: 0, chunksCreated: 0 }, false)).toBe(false);
+ });
+
+ test('imported > 0 → log', () => {
+ expect(shouldLogIngest({ imported: 1, errors: 0, chunksCreated: 0 }, false)).toBe(true);
+ });
+
+ test('errors > 0 → log (failures are events)', () => {
+ expect(shouldLogIngest({ imported: 0, errors: 2, chunksCreated: 0 }, false)).toBe(true);
+ });
+
+ test('chunksCreated > 0 → log', () => {
+ expect(shouldLogIngest({ imported: 0, errors: 0, chunksCreated: 3 }, false)).toBe(true);
+ });
+
+ test('all-zero counters with --log-noop → log (liveness opt-in)', () => {
+ expect(shouldLogIngest({ imported: 0, errors: 0, chunksCreated: 0 }, true)).toBe(true);
+ });
+});
+
+describe('runImport ingest_log gating (#3969)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ }, 60_000);
+
+ async function ingestLogCount(): Promise<number> {
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT COUNT(*)::text AS n FROM ingest_log`,
+ );
+ return Number(rows[0]?.n ?? 0);
+ }
+
+ test('real import logs; unchanged re-import (noop poll) does not; --log-noop opts back in', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-ingest-noop-'));
+ writeFileSync(join(dir, 'note.md'), '---\ntype: note\n---\n# Note\n\nbody\n');
+ const gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-home-'));
+
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ // Run 1: a page is imported → row written.
+ const r1 = await runImport(engine, [dir, '--no-embed', '--json']);
+ expect(r1.imported).toBe(1);
+ expect(await ingestLogCount()).toBe(1);
+
+ // Run 2: nothing changed → the poll writes NO row (pre-fix: one row
+ // per poll, "Imported 0 pages, 1 skipped, 0 chunks").
+ const r2 = await runImport(engine, [dir, '--no-embed', '--json']);
+ expect(r2.imported).toBe(0);
+ expect(r2.errors).toBe(0);
+ expect(r2.chunksCreated).toBe(0);
+ expect(await ingestLogCount()).toBe(1);
+
+ // Run 3: --log-noop opts back into the per-poll row.
+ const r3 = await runImport(engine, [dir, '--no-embed', '--json', '--log-noop']);
+ expect(r3.imported).toBe(0);
+ expect(await ingestLogCount()).toBe(2);
+ });
+ }, 60_000);
+});
diff --git a/test/ingestion/daemon.test.ts b/test/ingestion/daemon.test.ts
index a9612de96f..ed8da97711 100644
--- a/test/ingestion/daemon.test.ts
+++ b/test/ingestion/daemon.test.ts
@@ -511,3 +511,48 @@ describe('IngestionDaemon — config passthrough', () => {
await daemon.stop();
});
});
+
+// #3756 — tombstone events dedup on (source_kind, 'tombstone', slug), not on
+// content_hash: two deletes of the same slug within the window are one
+// delete, and a tombstone must never shadow an upsert that happens to carry
+// the same content_hash.
+describe('daemon — tombstone dedup (#3756)', () => {
+ test('same-slug tombstones dedup; different slugs pass', async () => {
+ const { logger } = makeCaptureLogger();
+ const { dispatch, recorded } = makeRecordingDispatcher();
+ const daemon = new IngestionDaemon({
+ engine: makeThrowingEngine(),
+ logger,
+ dispatch,
+ });
+ const { source, push } = makeControllableSource('s', 'mock');
+ daemon.register({ source });
+ await daemon.start();
+ push(makeEvent({ kind: 'tombstone', slug: 'inbox/a', content: 'tombstone one' }));
+ push(makeEvent({ kind: 'tombstone', slug: 'inbox/a', content: 'tombstone two (different hash, same slug)' }));
+ push(makeEvent({ kind: 'tombstone', slug: 'inbox/b', content: 'tombstone one' }));
+ await flushMicrotasks();
+ expect(recorded).toHaveLength(2);
+ expect(recorded.map((e) => e.slug)).toEqual(['inbox/a', 'inbox/b']);
+ await daemon.stop();
+ });
+
+ test('a tombstone does not shadow an upsert with the same content_hash', async () => {
+ const { logger } = makeCaptureLogger();
+ const { dispatch, recorded } = makeRecordingDispatcher();
+ const daemon = new IngestionDaemon({
+ engine: makeThrowingEngine(),
+ logger,
+ dispatch,
+ });
+ const { source, push } = makeControllableSource('s', 'mock');
+ daemon.register({ source });
+ await daemon.start();
+ const shared = 'identical body';
+ push(makeEvent({ kind: 'tombstone', slug: 'inbox/x', content: shared }));
+ push(makeEvent({ content: shared }));
+ await flushMicrotasks();
+ expect(recorded).toHaveLength(2);
+ await daemon.stop();
+ });
+});
diff --git a/test/ingestion/ingest-capture.test.ts b/test/ingestion/ingest-capture.test.ts
index 251fe2b96c..b9397930b6 100644
--- a/test/ingestion/ingest-capture.test.ts
+++ b/test/ingestion/ingest-capture.test.ts
@@ -742,3 +742,104 @@ describe('ingest_capture handler — integration with importFromContent', () =>
expect(result.chunks).toBeGreaterThan(0);
});
});
+
+// #3756 — tombstone events map to a reconciler-style soft-delete behind the
+// trusted-source gate. Untrusted channels (webhook payloads) must never be
+// able to delete pages.
+describe('ingest_capture handler — tombstones (#3756)', () => {
+ test('soft-deletes an existing page and reports status deleted', async () => {
+ await engine.putPage('inbox/to-remove', {
+ type: 'note',
+ title: 'To Remove',
+ compiled_truth: '# To Remove\n\nbody',
+ } as any, { sourceId: 'default' });
+
+ const handler = makeIngestCaptureHandler(engine);
+ const ev = makeEvent({ kind: 'tombstone', slug: 'inbox/to-remove', content: 'tombstone', untrusted_payload: false });
+ const result = await handler(makeJob({ event: ev }));
+ expect(result.status).toBe('deleted');
+ expect(result.slug).toBe('inbox/to-remove');
+ expect(result.chunks).toBe(0);
+
+ // Soft delete: row survives with deleted_at stamped (restorable), not a hard DELETE.
+ const rows = await engine.executeRaw<{ deleted_at: string | null }>(
+ `SELECT deleted_at FROM pages WHERE slug = $1 AND source_id = 'default'`,
+ ['inbox/to-remove'],
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0]!.deleted_at).not.toBeNull();
+ });
+
+ test('tombstone for a missing page reports skipped', async () => {
+ const handler = makeIngestCaptureHandler(engine);
+ const ev = makeEvent({ kind: 'tombstone', slug: 'inbox/never-existed', content: 'tombstone', untrusted_payload: false });
+ const result = await handler(makeJob({ event: ev }));
+ expect(result.status).toBe('skipped');
+ });
+
+ test('untrusted payloads must not delete', async () => {
+ await engine.putPage('inbox/protected', {
+ type: 'note',
+ title: 'Protected',
+ compiled_truth: '# Protected\n\nbody',
+ } as any, { sourceId: 'default' });
+
+ const handler = makeIngestCaptureHandler(engine);
+ const ev = makeEvent({
+ kind: 'tombstone',
+ slug: 'inbox/protected',
+ content: 'tombstone',
+ untrusted_payload: true,
+ });
+ await expect(handler(makeJob({ event: ev }))).rejects.toThrow(/untrusted/i);
+ const page = await engine.getPage('inbox/protected', { sourceId: 'default' });
+ expect(page).not.toBeNull();
+ });
+
+ test('tombstone with the flag OMITTED is rejected (fail-closed, explicit trusted marker required)', async () => {
+ await engine.putPage('inbox/also-protected', {
+ type: 'note',
+ title: 'Also Protected',
+ compiled_truth: '# Also Protected\n\nbody',
+ } as any, { sourceId: 'default' });
+
+ const handler = makeIngestCaptureHandler(engine);
+ // No untrusted_payload at all — pre-fix this fell OPEN (treated as
+ // trusted); the gate now requires the explicit `untrusted_payload: false`.
+ const ev = makeEvent({ kind: 'tombstone', slug: 'inbox/also-protected', content: 'tombstone' });
+ expect(ev.untrusted_payload).toBeUndefined();
+ await expect(handler(makeJob({ event: ev }))).rejects.toThrow(/trusted/i);
+ const page = await engine.getPage('inbox/also-protected', { sourceId: 'default' });
+ expect(page).not.toBeNull();
+ });
+
+ test('tombstone delete is scoped to the resolved source', async () => {
+ // Same slug in two sources; tombstone under default must not touch testsrc.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('tombsrc', 'tombsrc') ON CONFLICT (id) DO NOTHING`,
+ [],
+ );
+ await engine.putPage('inbox/dupe', {
+ type: 'note', title: 'Dupe default', compiled_truth: '# d',
+ } as any, { sourceId: 'default' });
+ await engine.putPage('inbox/dupe', {
+ type: 'note', title: 'Dupe tombsrc', compiled_truth: '# t',
+ } as any, { sourceId: 'tombsrc' });
+
+ const handler = makeIngestCaptureHandler(engine);
+ const ev = makeEvent({ kind: 'tombstone', slug: 'inbox/dupe', content: 'tombstone', untrusted_payload: false });
+ const result = await handler(makeJob({ event: ev }));
+ expect(result.status).toBe('deleted');
+
+ const other = await engine.getPage('inbox/dupe', { sourceId: 'tombsrc' });
+ expect(other).not.toBeNull();
+ });
+
+ test('event.slug wins over the generated default for upserts too', async () => {
+ const handler = makeIngestCaptureHandler(engine);
+ const ev = makeEvent({ content: 'top-level slug', slug: 'inbox/from-event-slug' });
+ const result = await handler(makeJob({ event: ev }));
+ expect(result.slug).toBe('inbox/from-event-slug');
+ expect(result.status).toBe('imported');
+ });
+});
diff --git a/test/ingestion/types.test.ts b/test/ingestion/types.test.ts
index 49d19bc49c..322f370dce 100644
--- a/test/ingestion/types.test.ts
+++ b/test/ingestion/types.test.ts
@@ -193,3 +193,44 @@ describe('IngestionEventError', () => {
expect(err).toBeInstanceOf(Error);
});
});
+
+// #3756 — event kinds: 'upsert' (default) imports, 'tombstone' soft-deletes
+// the page named by `slug`. The delete signal is validated at the boundary
+// like everything else.
+describe('validateIngestionEvent — kind + slug (#3756)', () => {
+ test('accepts kind: upsert', () => {
+ expect(validateIngestionEvent(makeEvent({ kind: 'upsert' }))).toBeNull();
+ });
+
+ test('accepts kind: tombstone with a slug', () => {
+ expect(validateIngestionEvent(makeEvent({ kind: 'tombstone', slug: 'inbox/old-page' }))).toBeNull();
+ });
+
+ test('accepts optional slug on an upsert', () => {
+ expect(validateIngestionEvent(makeEvent({ slug: 'inbox/target' }))).toBeNull();
+ });
+
+ test('rejects an unknown kind', () => {
+ const err = validateIngestionEvent({ ...makeEvent(), kind: 'delete' });
+ expect(err).not.toBeNull();
+ expect(err!.field).toBe('kind');
+ });
+
+ test('rejects kind: tombstone without a slug', () => {
+ const err = validateIngestionEvent(makeEvent({ kind: 'tombstone' }));
+ expect(err).not.toBeNull();
+ expect(err!.field).toBe('slug');
+ });
+
+ test('rejects a non-string slug', () => {
+ const err = validateIngestionEvent({ ...makeEvent(), slug: 42 });
+ expect(err).not.toBeNull();
+ expect(err!.field).toBe('slug');
+ });
+
+ test('rejects an empty-string slug', () => {
+ const err = validateIngestionEvent({ ...makeEvent(), slug: '' });
+ expect(err).not.toBeNull();
+ expect(err!.field).toBe('slug');
+ });
+});
diff --git a/test/init-schema-lock.test.ts b/test/init-schema-lock.test.ts
new file mode 100644
index 0000000000..8b7bce7739
--- /dev/null
+++ b/test/init-schema-lock.test.ts
@@ -0,0 +1,136 @@
+/**
+ * #2898 — deadlined initSchema advisory-lock acquisition.
+ *
+ * Pre-fix, PostgresEngine.initSchema ran a bare `SELECT pg_advisory_lock(42)`
+ * that blocks forever when a leaked pooler session holds the lock
+ * (transaction-mode poolers strip session lock state across checkouts), so
+ * every gbrain invocation hung at connect with no output.
+ *
+ * Hermetic: drives acquireInitSchemaAdvisoryLock with a fake query fn +
+ * injected clock/sleep. Covers: immediate acquire, acquire-after-wait,
+ * heartbeat naming the holder pid, timeout error with pg_terminate_backend
+ * guidance, env-tunable timeout, and pg_locks-probe failure fallback.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ acquireInitSchemaAdvisoryLock,
+ resolveInitSchemaLockTimeoutMs,
+ INIT_SCHEMA_LOCK_KEY,
+} from '../src/core/postgres-engine/init-schema-lock.ts';
+
+type Row = Record<string, unknown>;
+
+/** Fake clock advanced by the injected sleep. */
+function makeClock() {
+ let t = 0;
+ return {
+ now: () => t,
+ sleep: async (ms: number) => { t += ms; },
+ advance: (ms: number) => { t += ms; },
+ };
+}
+
+describe('resolveInitSchemaLockTimeoutMs', () => {
+ test('opts win over env; env (seconds) wins over the 10-min default', () => {
+ expect(resolveInitSchemaLockTimeoutMs({ timeoutMs: 1234 }, { GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS: '5' })).toBe(1234);
+ expect(resolveInitSchemaLockTimeoutMs({}, { GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS: '5' })).toBe(5000);
+ expect(resolveInitSchemaLockTimeoutMs({}, {})).toBe(600_000);
+ });
+
+ test('invalid env values fall through to the default', () => {
+ expect(resolveInitSchemaLockTimeoutMs({}, { GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS: 'nope' })).toBe(600_000);
+ expect(resolveInitSchemaLockTimeoutMs({}, { GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS: '-3' })).toBe(600_000);
+ });
+});
+
+describe('acquireInitSchemaAdvisoryLock', () => {
+ test('returns immediately when the lock is free', async () => {
+ const clock = makeClock();
+ const calls: string[] = [];
+ await acquireInitSchemaAdvisoryLock(
+ async (sql) => { calls.push(sql); return [{ locked: true }]; },
+ { now: clock.now, sleep: clock.sleep },
+ );
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toContain(`pg_try_advisory_lock(${INIT_SCHEMA_LOCK_KEY})`);
+ });
+
+ test('polls until the holder releases, then acquires', async () => {
+ const clock = makeClock();
+ let attempts = 0;
+ await acquireInitSchemaAdvisoryLock(
+ async (sql) => {
+ if (sql.includes('pg_try_advisory_lock')) {
+ attempts += 1;
+ return [{ locked: attempts >= 3 }];
+ }
+ return [{ pid: 777 }];
+ },
+ { now: clock.now, sleep: clock.sleep, pollMs: 100, heartbeatMs: 1_000_000 },
+ );
+ expect(attempts).toBe(3);
+ });
+
+ test('heartbeat names the holder pid on stderr-style log sink', async () => {
+ const clock = makeClock();
+ const lines: string[] = [];
+ let attempts = 0;
+ await acquireInitSchemaAdvisoryLock(
+ async (sql) => {
+ if (sql.includes('pg_try_advisory_lock')) {
+ attempts += 1;
+ return [{ locked: attempts >= 5 }];
+ }
+ return [{ pid: 4242 }];
+ },
+ { now: clock.now, sleep: clock.sleep, pollMs: 500, heartbeatMs: 1000, log: (l) => lines.push(l) },
+ );
+ expect(lines.length).toBeGreaterThanOrEqual(1);
+ expect(lines[0]).toContain('waiting for the schema advisory lock');
+ expect(lines[0]).toContain('4242');
+ });
+
+ test('times out with holder pid + pg_terminate_backend guidance', async () => {
+ const clock = makeClock();
+ let err: Error | null = null;
+ try {
+ await acquireInitSchemaAdvisoryLock(
+ async (sql) => {
+ if (sql.includes('pg_try_advisory_lock')) return [{ locked: false }];
+ expect(sql).toContain('pg_locks');
+ return [{ pid: 999 }];
+ },
+ { now: clock.now, sleep: clock.sleep, timeoutMs: 2000, pollMs: 500, heartbeatMs: 1_000_000 },
+ );
+ } catch (e) {
+ err = e as Error;
+ }
+ expect(err).not.toBeNull();
+ expect(err!.message).toContain('timed out');
+ expect(err!.message).toContain('pid 999');
+ expect(err!.message).toContain('pg_terminate_backend(999)');
+ expect(err!.message).toContain('GBRAIN_INITSCHEMA_LOCK_TIMEOUT_SECONDS');
+ // Names the pooler failure mode so operators recognize the leak class.
+ expect(err!.message.toLowerCase()).toContain('pooler');
+ });
+
+ test('pg_locks probe failure still produces a useful timeout error', async () => {
+ const clock = makeClock();
+ let err: Error | null = null;
+ try {
+ await acquireInitSchemaAdvisoryLock(
+ async (sql) => {
+ if (sql.includes('pg_try_advisory_lock')) return [{ locked: false }];
+ throw new Error('pg_locks not readable');
+ },
+ { now: clock.now, sleep: clock.sleep, timeoutMs: 1000, pollMs: 500, heartbeatMs: 1_000_000 },
+ );
+ } catch (e) {
+ err = e as Error;
+ }
+ expect(err).not.toBeNull();
+ expect(err!.message).toContain('could not be determined');
+ expect(err!.message).toContain('pg_terminate_backend(<pid>)');
+ });
+});
diff --git a/test/insert-facts-batch.test.ts b/test/insert-facts-batch.test.ts
index 8f7149f909..6f669ad54b 100644
--- a/test/insert-facts-batch.test.ts
+++ b/test/insert-facts-batch.test.ts
@@ -43,7 +43,7 @@ beforeEach(async () => {
await (engine as any).db.query('DELETE FROM facts');
});
-type BatchFact = NewFact & { row_num: number; source_markdown_slug: string };
+type BatchFact = NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number };
const fixtureFact = (rowNum: number, overrides: Partial<BatchFact> = {}): BatchFact => ({
fact: `Claim ${rowNum}`,
@@ -61,7 +61,7 @@ const fixtureFact = (rowNum: number, overrides: Partial<BatchFact> = {}): BatchF
describe('engine.insertFacts — batch insert', () => {
test('empty batch returns inserted:0, ids:[]', async () => {
const r = await engine.insertFacts([], { source_id: 'default' });
- expect(r).toEqual({ inserted: 0, ids: [] });
+ expect(r).toEqual({ inserted: 0, ids: [], warnings: [], deleted: 0 });
});
test('single-row batch inserts and persists v51 columns', async () => {
@@ -314,3 +314,229 @@ describe('insertFacts + deleteFactsForPage round-trip (the reconciliation patter
expect(rows.rows[1]).toMatchObject({ fact: 'B', row_num: 2, source_markdown_slug: 'people/alice' });
});
});
+
+describe('engine.insertFacts — v0.46 (#3014) supersession transport', () => {
+ const struck = (rowNum: number, supersededByRow: number, overrides: Partial<BatchFact> = {}): BatchFact =>
+ fixtureFact(rowNum, {
+ expired_at: new Date('2026-06-01T00:00:00Z'),
+ superseded_by_row: supersededByRow,
+ ...overrides,
+ });
+
+ test('struck row resolves superseded by #N to the target fact id + persists expired_at', async () => {
+ // Row 1 struck, superseded by row 2 (active). Same batch.
+ const r = await engine.insertFacts(
+ [struck(1, 2, { fact: 'old claim' }), fixtureFact(2, { fact: 'new claim' })],
+ { source_id: 'default' },
+ );
+ expect(r.warnings).toEqual([]);
+ const targetId = r.ids[1];
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT row_num, superseded_by, expired_at FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,
+ );
+ expect(Number(persisted.rows[0].superseded_by)).toBe(Number(targetId));
+ expect(persisted.rows[0].expired_at).not.toBeNull();
+ // The active target keeps superseded_by NULL.
+ expect(persisted.rows[1].superseded_by).toBeNull();
+
+ // The row surfaces in listSupersessions (superseded_by filter, option B).
+ const sup = await engine.listSupersessions('default');
+ expect(sup.some(s => s.id === r.ids[0] && s.superseded_by === Number(targetId))).toBe(true);
+ });
+
+ test('reference to a pre-existing target row (not in this batch) still resolves', async () => {
+ // Insert the target first (its own batch), then the struck row later.
+ const target = await engine.insertFacts([fixtureFact(2, { fact: 'survivor' })], { source_id: 'default' });
+ const r = await engine.insertFacts([struck(1, 2, { fact: 'retired' })], { source_id: 'default' });
+ expect(r.warnings).toEqual([]);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT superseded_by FROM facts WHERE row_num = 1 AND source_markdown_slug = 'people/alice'`,
+ );
+ expect(Number(persisted.rows[0].superseded_by)).toBe(Number(target.ids[0]));
+ });
+
+ test('dangling reference (#N absent) → superseded_by NULL + warning, expired_at still set', async () => {
+ const r = await engine.insertFacts([struck(1, 99, { fact: 'orphaned' })], { source_id: 'default' });
+ expect(r.warnings).toHaveLength(1);
+ expect(r.warnings[0]).toContain('absent from the fence');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT superseded_by, expired_at FROM facts WHERE row_num = 1 AND source_markdown_slug = 'people/alice'`,
+ );
+ expect(persisted.rows[0].superseded_by).toBeNull();
+ expect(persisted.rows[0].expired_at).not.toBeNull();
+ });
+
+ test('self-reference (#N == own row) → superseded_by NULL + warning', async () => {
+ const r = await engine.insertFacts([struck(1, 1, { fact: 'ouroboros' })], { source_id: 'default' });
+ expect(r.warnings).toHaveLength(1);
+ expect(r.warnings[0]).toContain('references itself');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT superseded_by FROM facts WHERE row_num = 1 AND source_markdown_slug = 'people/alice'`,
+ );
+ expect(persisted.rows[0].superseded_by).toBeNull();
+ });
+
+ test('chain (#N names another struck row) → superseded_by NULL + warning', async () => {
+ // Row 1 superseded by #2; row 2 is itself struck (superseded by #3).
+ const r = await engine.insertFacts(
+ [struck(1, 2, { fact: 'link a' }), struck(2, 3, { fact: 'link b' }), fixtureFact(3, { fact: 'live tail' })],
+ { source_id: 'default' },
+ );
+ // Row 1 → row 2 is a chain (row 2 struck) → NULL + warning.
+ // Row 2 → row 3 (live) resolves cleanly.
+ expect(r.warnings.some(w => w.includes('struck'))).toBe(true);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT row_num, superseded_by FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,
+ );
+ expect(persisted.rows[0].superseded_by).toBeNull(); // row 1: chain rejected
+ expect(Number(persisted.rows[1].superseded_by)).toBe(Number(r.ids[2])); // row 2 → row 3
+ });
+
+ test('int4-overflow reference (11-digit #N) resolves as dangling — never throws', async () => {
+ // The fence parser accepts any finite #N; an 11-digit value would
+ // overflow the int4 row_num comparison in the resolution SELECT and
+ // abort the whole cycle. The guard treats it as a dangling reference:
+ // NULL superseded_by + warning, expired_at still set, no exception.
+ const r = await engine.insertFacts(
+ [struck(1, 99999999999, { fact: 'points at an absurd row' })],
+ { source_id: 'default' },
+ );
+ expect(r.warnings).toHaveLength(1);
+ expect(r.warnings[0]).toContain('absent from the fence');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT superseded_by, expired_at FROM facts WHERE row_num = 1 AND source_markdown_slug = 'people/alice'`,
+ );
+ expect(persisted.rows[0].superseded_by).toBeNull();
+ expect(persisted.rows[0].expired_at).not.toBeNull();
+ });
+
+ test('ON CONFLICT-skipped row does not shift later supersession UPDATEs (alignment)', async () => {
+ // Seed row 1 so the batch's first row collides on the v51 unique index
+ // and is skipped by ON CONFLICT DO NOTHING. The batch's LATER struck row
+ // must still resolve against its own inserted id — a positional index
+ // into the compacted ids array would target the wrong fact.
+ await engine.insertFacts([fixtureFact(1, { fact: 'pre-existing' })], { source_id: 'default' });
+ const r = await engine.insertFacts(
+ [
+ fixtureFact(1, { fact: 'collides and is skipped' }),
+ struck(2, 3, { fact: 'retired' }),
+ fixtureFact(3, { fact: 'live target' }),
+ ],
+ { source_id: 'default' },
+ );
+ expect(r.inserted).toBe(2); // row 1 skipped
+ expect(r.warnings).toEqual([]);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const persisted = await (engine as any).db.query(
+ `SELECT row_num, superseded_by FROM facts WHERE source_markdown_slug = 'people/alice' ORDER BY row_num`,
+ );
+ const byRow = new Map(persisted.rows.map((x: { row_num: number; superseded_by: number | null }) => [Number(x.row_num), x.superseded_by]));
+ expect(byRow.get(1)).toBeNull(); // untouched pre-existing row
+ expect(Number(byRow.get(2))).toBe(Number(r.ids[1])); // row 2 → row 3's id (second INSERTED id)
+ });
+});
+
+describe('engine.insertFacts — v0.46 (#3014) atomic deleteForPageFirst reconcile', () => {
+ test('replaces the page atomically and reports the deleted count', async () => {
+ await engine.insertFacts(
+ [fixtureFact(1, { fact: 'old one' }), fixtureFact(2, { fact: 'old two' })],
+ { source_id: 'default' },
+ );
+ const r = await engine.insertFacts(
+ [fixtureFact(1, { fact: 'new one' })],
+ { source_id: 'default' },
+ { deleteForPageFirst: { slug: 'people/alice', excludeSourcePrefixes: ['cli:'] } },
+ );
+ expect(r.inserted).toBe(1);
+ expect(r.deleted).toBe(2);
+ // 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((x: { fact: string }) => x.fact)).toEqual(['new one']);
+ });
+
+ test('a failing insert rolls the wipe back — the page is never left emptied', async () => {
+ // Seed the page's current rows (the ones a pre-fix separate-commit delete
+ // would have destroyed before the insert threw).
+ await engine.insertFacts(
+ [fixtureFact(1, { fact: 'keeper one' }), fixtureFact(2, { fact: 'keeper two' })],
+ { source_id: 'default' },
+ );
+
+ // The insert batch violates a NOT NULL constraint AFTER the delete has
+ // already run inside the same transaction, rolling the whole txn back.
+ let threw = false;
+ try {
+ await engine.insertFacts(
+ [
+ fixtureFact(1, { fact: 'replacement a' }),
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fixtureFact(2, { fact: null as any }),
+ ],
+ { source_id: 'default' },
+ { deleteForPageFirst: { slug: 'people/alice', excludeSourcePrefixes: ['cli:'] } },
+ );
+ } catch {
+ threw = true;
+ }
+ expect(threw).toBe(true);
+
+ // Atomicity: the delete rolled back with the failed insert, so the
+ // original rows survive rather than the page being silently emptied.
+ // 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((x: { fact: string }) => x.fact)).toEqual(['keeper one', 'keeper two']);
+ });
+
+ test('cli:-origin rows survive the atomic wipe (excludeSourcePrefixes honored)', async () => {
+ await engine.insertFacts(
+ [
+ fixtureFact(1, { fact: 'fence row', source: 'fence:reconcile' }),
+ fixtureFact(2, { fact: 'conversation row', source: 'cli:think' }),
+ ],
+ { source_id: 'default' },
+ );
+ const r = await engine.insertFacts(
+ [fixtureFact(1, { fact: 'fresh fence row', source: 'fence:reconcile' })],
+ { source_id: 'default' },
+ { deleteForPageFirst: { slug: 'people/alice', excludeSourcePrefixes: ['cli:'] } },
+ );
+ expect(r.deleted).toBe(1); // only the fence row was wiped
+ // 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((x: { fact: string }) => x.fact)).toEqual(['fresh fence row', 'conversation row']);
+ });
+
+ test('soft-expired legacy rows survive the atomic wipe (preserveExpiredLegacy honored, #2646)', async () => {
+ // A legacy forget record: row_num NULL + expired_at set, same page slug.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await (engine as any).db.query(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, confidence, source_markdown_slug, expired_at)
+ VALUES ('default', 'people/alice', 'legacy forget record', 'fact', 'world', 'medium', 'mcp:forget_fact', 1.0, 'people/alice', now())`,
+ );
+ await engine.insertFacts([fixtureFact(1, { fact: 'fence row' })], { source_id: 'default' });
+
+ const r = await engine.insertFacts(
+ [fixtureFact(1, { fact: 'fresh fence row' })],
+ { source_id: 'default' },
+ { deleteForPageFirst: { slug: 'people/alice', excludeSourcePrefixes: ['cli:'], preserveExpiredLegacy: true } },
+ );
+ expect(r.deleted).toBe(1); // only the fence-owned row was wiped
+ // 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 NULLS LAST`,
+ );
+ expect(rows.rows.map((x: { fact: string }) => x.fact)).toEqual(['fresh fence row', 'legacy forget record']);
+ });
+});
diff --git a/test/jobs-agent-scope.test.ts b/test/jobs-agent-scope.test.ts
new file mode 100644
index 0000000000..24c1de0234
--- /dev/null
+++ b/test/jobs-agent-scope.test.ts
@@ -0,0 +1,163 @@
+/**
+ * #4098 — agent-scoped access to the generic jobs ops (PGLite lane; the
+ * Postgres parity twin is test/e2e/jobs-agent-scope-postgres.test.ts).
+ *
+ * get_job / list_jobs / get_job_progress / cancel_job are admin ops that
+ * gained `agentCallable: true`: an agent-scoped OAuth client can monitor and
+ * cancel ONLY the jobs it owns (fenced SQL-side on
+ * `data->>'__owner_client_id'` — the predicate submit_agent stamps).
+ * Foreign-owned and missing ids share one uniform error (anti-enumeration).
+ * Admin/local callers stay unfenced.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_inbox');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+function ctx(over: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine,
+ config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ ...over,
+ } as OperationContext;
+}
+
+const agentCtx = (clientId = 'agent-a') =>
+ ctx({ auth: { clientId, scopes: ['agent'] } as OperationContext['auth'] });
+const adminCtx = () =>
+ ctx({ auth: { clientId: 'admin-tok', scopes: ['admin'] } as OperationContext['auth'] });
+const localCtx = () => ctx({ remote: false });
+
+let seedSeq = 0;
+async function seedJob(owner: string | null, name = 'subagent'): Promise<number> {
+ // Unique payload per seed — identical waiting jobs get coalesced by add().
+ const data: Record<string, unknown> = { prompt: `x-${++seedSeq}` };
+ if (owner) data.__owner_client_id = owner;
+ const job = await queue.add(name, data, { queue: 'default' }, { allowProtectedSubmit: true });
+ return job.id;
+}
+
+const get_job = operationsByName['get_job']!;
+const list_jobs = operationsByName['list_jobs']!;
+const get_job_progress = operationsByName['get_job_progress']!;
+const cancel_job = operationsByName['cancel_job']!;
+
+describe('op surface flags (#4098)', () => {
+ test('the four generic jobs ops are agentCallable, still admin-scoped', () => {
+ for (const op of [get_job, list_jobs, get_job_progress, cancel_job]) {
+ expect(op.agentCallable).toBe(true);
+ expect(op.scope).toBe('admin');
+ }
+ });
+});
+
+describe('get_job / get_job_progress — ownership fence', () => {
+ test('agent sees its own job; foreign job = uniform not-found', async () => {
+ const mine = await seedJob('agent-a');
+ const theirs = await seedJob('agent-b');
+
+ const job = (await get_job.handler(agentCtx('agent-a'), { id: mine })) as { id: number };
+ expect(job.id).toBe(mine);
+
+ let foreignErr: Error | null = null;
+ let missingErr: Error | null = null;
+ await get_job.handler(agentCtx('agent-a'), { id: theirs }).catch((e) => { foreignErr = e; });
+ await get_job.handler(agentCtx('agent-a'), { id: 999_999 }).catch((e) => { missingErr = e; });
+ expect(foreignErr).not.toBeNull();
+ expect(missingErr).not.toBeNull();
+ // Anti-enumeration: byte-identical envelopes modulo the id.
+ expect(String(foreignErr).replace(String(theirs), 'N')).toBe(
+ String(missingErr).replace('999999', 'N'),
+ );
+
+ const prog = (await get_job_progress.handler(agentCtx('agent-a'), { id: mine })) as { id: number };
+ expect(prog.id).toBe(mine);
+ await expect(get_job_progress.handler(agentCtx('agent-a'), { id: theirs })).rejects.toThrow(/not found/i);
+ });
+
+ test('agent scope WITHOUT a client identity is refused (fail closed)', async () => {
+ const id = await seedJob('agent-a');
+ const noIdentity = ctx({ auth: { scopes: ['agent'] } as OperationContext['auth'] });
+ await expect(get_job.handler(noIdentity, { id })).rejects.toThrow(/client identity/);
+ });
+
+ test('admin token and local CLI stay unfenced', async () => {
+ const theirs = await seedJob('agent-b');
+ expect(((await get_job.handler(adminCtx(), { id: theirs })) as { id: number }).id).toBe(theirs);
+ expect(((await get_job.handler(localCtx(), { id: theirs })) as { id: number }).id).toBe(theirs);
+ });
+});
+
+describe('list_jobs — ownership fence', () => {
+ test('agent lists only its own jobs; admin sees all', async () => {
+ await seedJob('agent-a');
+ await seedJob('agent-a');
+ await seedJob('agent-b');
+ await seedJob(null, 'embed'); // unowned operator job
+
+ const mine = (await list_jobs.handler(agentCtx('agent-a'), {})) as Array<{ data: Record<string, unknown> }>;
+ expect(mine.length).toBe(2);
+ for (const j of mine) expect(j.data.__owner_client_id).toBe('agent-a');
+
+ const all = (await list_jobs.handler(adminCtx(), {})) as unknown[];
+ expect(all.length).toBe(4);
+ const local = (await list_jobs.handler(localCtx(), {})) as unknown[];
+ expect(local.length).toBe(4);
+ });
+});
+
+describe('cancel_job — ownership fence rides the recursive cancel', () => {
+ test('agent cancels its own job tree; children cascade', async () => {
+ const rootId = await seedJob('agent-a');
+ // Child spawned by the job itself — carries no owner tag of its own.
+ const child = await queue.add('subagent', { prompt: 'child' }, { queue: 'default' }, { allowProtectedSubmit: true });
+ await engine.executeRaw('UPDATE minion_jobs SET parent_job_id = $1 WHERE id = $2', [rootId, child.id]);
+
+ const cancelled = (await cancel_job.handler(agentCtx('agent-a'), { id: rootId })) as { id: number; status: string };
+ expect(cancelled.id).toBe(rootId);
+ expect(cancelled.status).toBe('cancelled');
+
+ const childRow = await engine.executeRaw<{ status: string }>(
+ 'SELECT status FROM minion_jobs WHERE id = $1', [child.id],
+ );
+ expect(childRow[0]!.status).toBe('cancelled');
+ });
+
+ test('agent cannot cancel a foreign job — job stays waiting, uniform envelope', async () => {
+ const theirs = await seedJob('agent-b');
+ await expect(cancel_job.handler(agentCtx('agent-a'), { id: theirs })).rejects.toThrow(/Cannot cancel/);
+ const row = await engine.executeRaw<{ status: string }>(
+ 'SELECT status FROM minion_jobs WHERE id = $1', [theirs],
+ );
+ expect(row[0]!.status).toBe('waiting');
+ });
+
+ test('admin cancel stays unfenced', async () => {
+ const theirs = await seedJob('agent-b');
+ const cancelled = (await cancel_job.handler(adminCtx(), { id: theirs })) as { status: string };
+ expect(cancelled.status).toBe('cancelled');
+ });
+});
diff --git a/test/jobs-gateway-refresh-set.test.ts b/test/jobs-gateway-refresh-set.test.ts
new file mode 100644
index 0000000000..4a440f350e
--- /dev/null
+++ b/test/jobs-gateway-refresh-set.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #3387 — GATEWAY_REFRESH_JOB_NAMES drift guard.
+ *
+ * `registerBuiltinJob` wraps a handler with `refreshGatewayForJob` ONLY when
+ * its name is in GATEWAY_REFRESH_JOB_NAMES. Two silent drift modes exist:
+ *
+ * 1. A gateway-using handler registered via bare `worker.register(...)`
+ * never refreshes — a worker booted before `gbrain config set` ran with
+ * a stale gateway. chronicle_extract hit exactly this: the DB-plane chat
+ * model never reached the judge, so every extraction silently returned
+ * no_events (#3387).
+ * 2. A `registerBuiltinJob(...)` call whose name is missing from the set
+ * LOOKS wrapped at the call site but silently registers bare.
+ *
+ * This test pins set ⇔ call-site equality by scanning the source text, so
+ * both drift modes fail loudly in CI.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+const JOBS_SRC = fs.readFileSync(
+ path.join(import.meta.dir, '..', 'src', 'commands', 'jobs.ts'),
+ 'utf8',
+);
+
+/** Extract the string entries of the GATEWAY_REFRESH_JOB_NAMES set literal. */
+function parseRefreshSet(src: string): string[] {
+ const m = src.match(/const GATEWAY_REFRESH_JOB_NAMES = new Set\(\[([\s\S]*?)\]\);/);
+ if (!m) throw new Error('GATEWAY_REFRESH_JOB_NAMES set literal not found in jobs.ts');
+ // Strip // comments first — apostrophes inside comment prose would otherwise
+ // corrupt the quote matcher.
+ const body = m[1]!.split('\n').map((l) => l.replace(/\/\/.*$/, '')).join('\n');
+ return [...body.matchAll(/'([^']+)'/g)].map((x) => x[1]!);
+}
+
+/** Extract every job name passed to registerBuiltinJob(worker, engine, '<name>', ...). */
+function parseBuiltinRegistrations(src: string): string[] {
+ return [...src.matchAll(/registerBuiltinJob\(\s*worker,\s*engine,\s*'([^']+)'/g)].map((x) => x[1]!);
+}
+
+describe('#3387 — GATEWAY_REFRESH_JOB_NAMES ⇔ registerBuiltinJob call sites', () => {
+ const setNames = parseRefreshSet(JOBS_SRC);
+ const registered = parseBuiltinRegistrations(JOBS_SRC);
+
+ test('chronicle_extract is in the refresh set (the #3387 regression)', () => {
+ expect(setNames).toContain('chronicle_extract');
+ });
+
+ test('chronicle_extract is registered via registerBuiltinJob, not bare worker.register', () => {
+ expect(registered).toContain('chronicle_extract');
+ expect(JOBS_SRC).not.toMatch(/worker\.register\(\s*'chronicle_extract'/);
+ });
+
+ test('every set entry has a registerBuiltinJob call site (no dead entries)', () => {
+ const missing = setNames.filter((n) => !registered.includes(n));
+ expect(missing).toEqual([]);
+ });
+
+ test('every registerBuiltinJob name is in the set (no silently-unwrapped registrations)', () => {
+ const unwrapped = registered.filter((n) => !setNames.includes(n));
+ expect(unwrapped).toEqual([]);
+ });
+
+ test('set entries are unique', () => {
+ expect(new Set(setNames).size).toBe(setNames.length);
+ });
+});
diff --git a/test/junk-entity-guards.test.ts b/test/junk-entity-guards.test.ts
new file mode 100644
index 0000000000..7a9d5bc2bc
--- /dev/null
+++ b/test/junk-entity-guards.test.ts
@@ -0,0 +1,219 @@
+/**
+ * #4222 — generic-token entity junk guards.
+ *
+ * Three seams share one reject list (src/core/entity-name-quality.ts):
+ * 1. enrichEntity refuses to MINT a page for a single generic token or a
+ * bare @handle (existing pages stay trusted — update path unaffected).
+ * 2. buildGazetteer drops single-generic-token PERSON titles so an
+ * already-minted junk page stops accreting mention edges.
+ * 3. The junk_entity_hubs doctor check surfaces near-empty pages with
+ * huge edge counts (warn + list, never auto-delete).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ GENERIC_ENTITY_TOKENS,
+ isGenericEntityToken,
+ isJunkEntityName,
+} from '../src/core/entity-name-quality.ts';
+import { enrichEntity } from '../src/core/enrichment-service.ts';
+import { buildGazetteer } from '../src/core/by-mention.ts';
+import {
+ checkJunkEntityHubs,
+ JUNK_HUB_EDGE_THRESHOLD,
+ JUNK_HUB_MAX_CHUNKS,
+} from '../src/commands/doctor/checks/graph-embedding.ts';
+import type { LinkBatchInput } from '../src/core/engine.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+async function truncateAll() {
+ for (const t of ['content_chunks', 'links', 'tags', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {
+ await (engine as unknown as { db: { exec(q: string): Promise<unknown> } }).db.exec(`DELETE FROM ${t}`);
+ }
+}
+
+// ── 1. Shared reject list ───────────────────────────────────────────────
+
+describe('entity-name-quality (#4222)', () => {
+ test('the observed junk-hub tokens are all on the list', () => {
+ for (const t of ['will', 'something', 'info', 'chief', 'unknown', 'readme', 'founders']) {
+ expect(GENERIC_ENTITY_TOKENS.has(t)).toBe(true);
+ expect(isGenericEntityToken(t)).toBe(true);
+ }
+ });
+
+ test('matching is case-insensitive', () => {
+ expect(isGenericEntityToken('Will')).toBe(true);
+ expect(isGenericEntityToken('CHIEF')).toBe(true);
+ });
+
+ test('isJunkEntityName: single generic token or bare @handle', () => {
+ expect(isJunkEntityName('Will')).toBe(true);
+ expect(isJunkEntityName('info')).toBe(true);
+ expect(isJunkEntityName('@alice_dev')).toBe(true);
+ expect(isJunkEntityName('@AcmeCorp')).toBe(true);
+ expect(isJunkEntityName(' ')).toBe(true);
+ });
+
+ test('isJunkEntityName: multi-word names and real names always pass', () => {
+ expect(isJunkEntityName('Will Smith')).toBe(false);
+ expect(isJunkEntityName('Alice Chen')).toBe(false);
+ expect(isJunkEntityName('Acme')).toBe(false); // single but NOT generic
+ expect(isJunkEntityName('Info Systems Inc')).toBe(false);
+ });
+});
+
+// ── 2. enrichEntity mint gate ───────────────────────────────────────────
+
+describe('enrichEntity mint gate (#4222)', () => {
+ beforeEach(truncateAll);
+
+ test('single generic token is skipped — no page minted', async () => {
+ const result = await enrichEntity(engine, {
+ entityName: 'Will',
+ entityType: 'person',
+ context: 'Will follow up next week',
+ sourceSlug: 'meetings/standup',
+ }, { trusted: true });
+
+ expect(result.action).toBe('skipped');
+ expect(await engine.getPage('people/will')).toBeNull();
+ });
+
+ test('bare @handle is skipped — no page minted', async () => {
+ const result = await enrichEntity(engine, {
+ entityName: '@alice_dev',
+ entityType: 'person',
+ context: 'mentioned by @alice_dev',
+ sourceSlug: 'meetings/standup',
+ }, { trusted: true });
+
+ expect(result.action).toBe('skipped');
+ expect(await engine.getPage('people/alice-dev')).toBeNull();
+ });
+
+ test('an EXISTING page with a generic title stays trusted (update path)', async () => {
+ await engine.putPage('people/will', {
+ type: 'person', title: 'Will', compiled_truth: 'A real person the user created.', timeline: '',
+ });
+
+ const result = await enrichEntity(engine, {
+ entityName: 'Will',
+ entityType: 'person',
+ context: 'update for existing page',
+ sourceSlug: 'meetings/standup',
+ }, { trusted: true });
+
+ expect(result.action).toBe('updated');
+ });
+
+ test('multi-word names still mint', async () => {
+ const result = await enrichEntity(engine, {
+ entityName: 'Will Smith',
+ entityType: 'person',
+ context: 'met Will Smith',
+ sourceSlug: 'meetings/standup',
+ }, { trusted: true });
+
+ expect(result.action).toBe('created');
+ expect(await engine.getPage('people/will-smith')).not.toBeNull();
+ });
+});
+
+// ── 3. buildGazetteer drop ──────────────────────────────────────────────
+
+describe('buildGazetteer generic person-title drop (#4222)', () => {
+ beforeEach(truncateAll);
+
+ test('single-generic-token person title is dropped; multi-token and non-person kept', async () => {
+ await engine.putPage('people/will', {
+ type: 'person', title: 'Will', compiled_truth: 'junk hub magnet', timeline: '',
+ });
+ await engine.putPage('people/will-smith', {
+ type: 'person', title: 'Will Smith', compiled_truth: 'a real person', timeline: '',
+ });
+ // Non-person types are NOT dropped (scope pin: the gate is person-only).
+ await engine.putPage('companies/info', {
+ type: 'company', title: 'Info', compiled_truth: 'a company', timeline: '',
+ });
+
+ const gazetteer = await buildGazetteer(engine);
+
+ const willBucket = gazetteer.get('will') ?? [];
+ expect(willBucket.some(e => e.slug === 'people/will')).toBe(false);
+ expect(willBucket.some(e => e.slug === 'people/will-smith')).toBe(true);
+ const infoBucket = gazetteer.get('info') ?? [];
+ expect(infoBucket.some(e => e.slug === 'companies/info')).toBe(true);
+ });
+});
+
+// ── 4. junk_entity_hubs doctor check ────────────────────────────────────
+
+describe('junk_entity_hubs doctor check (#4222)', () => {
+ beforeEach(truncateAll);
+
+ test('shipped thresholds are the documented ones', () => {
+ expect(JUNK_HUB_EDGE_THRESHOLD).toBe(1000);
+ expect(JUNK_HUB_MAX_CHUNKS).toBe(2);
+ });
+
+ test('warns and lists near-empty pages with edge counts over threshold', async () => {
+ await engine.putPage('people/will', {
+ type: 'person', title: 'Will', compiled_truth: 'stub', timeline: '',
+ });
+ const batch: LinkBatchInput[] = [];
+ for (let i = 0; i < 4; i++) {
+ const slug = `notes/n-${i}`;
+ await engine.putPage(slug, { type: 'note', title: `Note ${i}`, compiled_truth: 'body', timeline: '' });
+ batch.push({ from_slug: slug, to_slug: 'people/will', link_source: 'mentions' });
+ }
+ await engine.addLinksBatch(batch);
+
+ // Threshold overridden for test-scale corpus; production uses defaults.
+ const check = await checkJunkEntityHubs(engine, { edgeThreshold: 3, maxChunks: 2 });
+
+ expect(check.name).toBe('junk_entity_hubs');
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('people/will');
+ const hubs = (check.details as { hubs: Array<{ slug: string; edges: number }> }).hubs;
+ expect(hubs.some(h => h.slug === 'people/will' && h.edges >= 4)).toBe(true);
+ // The note pages have few edges — not listed.
+ expect(hubs.some(h => h.slug.startsWith('notes/'))).toBe(false);
+ });
+
+ test('content-rich pages are exempt even with many edges', async () => {
+ await engine.putPage('people/notable', {
+ type: 'person', title: 'Notable Person', compiled_truth: 'real content', timeline: '',
+ });
+ await engine.upsertChunks('people/notable', [0, 1, 2].map(i => ({
+ chunk_index: i, chunk_text: `chunk ${i}`, chunk_source: 'compiled_truth' as const, token_count: 2,
+ })));
+ const batch: LinkBatchInput[] = [];
+ for (let i = 0; i < 4; i++) {
+ const slug = `notes/m-${i}`;
+ await engine.putPage(slug, { type: 'note', title: `M ${i}`, compiled_truth: 'body', timeline: '' });
+ batch.push({ from_slug: slug, to_slug: 'people/notable', link_source: 'mentions' });
+ }
+ await engine.addLinksBatch(batch);
+
+ const check = await checkJunkEntityHubs(engine, { edgeThreshold: 3, maxChunks: 2 });
+ expect(check.status).toBe('ok');
+ });
+
+ test('ok on an empty brain', async () => {
+ const check = await checkJunkEntityHubs(engine);
+ expect(check.status).toBe('ok');
+ });
+});
diff --git a/test/link-extraction-dir-whitelist-2576.test.ts b/test/link-extraction-dir-whitelist-2576.test.ts
index 37567a1d89..b990505ded 100644
--- a/test/link-extraction-dir-whitelist-2576.test.ts
+++ b/test/link-extraction-dir-whitelist-2576.test.ts
@@ -116,19 +116,24 @@ describe('#2576 bug 2 — non-whitelisted dirs produce candidates (ops/ = people
expect(candidates).toEqual([]);
});
- test('bare [[name]] wikilinks (no slash) keep the flag-gated behavior', async () => {
+ test('bare [[name]] wikilinks (no slash) keep the flag-gated BASENAME behavior', async () => {
+ // #4062: the flag gates only basename resolution. The root-exact direct
+ // candidate (`struktura` at the brain root) is emitted regardless —
+ // downstream existence checks drop it when no root page exists — so
+ // bare wikilinks get parity with the FS path's resolveSlug ancestor walk.
const resolver = setResolver(['projects/struktura']);
const off = await extractPageLinks(
'concepts/x', 'This relates to [[struktura]].',
{}, 'concept', resolver, { skipFrontmatter: true },
);
- expect(off.candidates).toEqual([]);
+ expect(off.candidates.filter(c => c.linkSource === 'wikilink-resolved')).toEqual([]);
+ expect(off.candidates.map(c => c.targetSlug)).toEqual(['struktura']);
const on = await extractPageLinks(
'concepts/x', 'This relates to [[struktura]].',
{}, 'concept', resolver, { skipFrontmatter: true, globalBasename: true },
);
- expect(on.candidates.map(c => c.targetSlug)).toEqual(['projects/struktura']);
- expect(on.candidates[0].linkType).toBe('wikilink_basename');
+ const basename = on.candidates.filter(c => c.linkType === 'wikilink_basename');
+ expect(basename.map(c => c.targetSlug)).toEqual(['projects/struktura']);
});
test('LINK_EXTRACTOR_VERSION_TS was bumped so stamped pages re-extract', () => {
diff --git a/test/link-extraction-pack-3190.test.ts b/test/link-extraction-pack-3190.test.ts
new file mode 100644
index 0000000000..81ebd8d02a
--- /dev/null
+++ b/test/link-extraction-pack-3190.test.ts
@@ -0,0 +1,217 @@
+/**
+ * #3190 — pack-aware link extraction + same-directory markdown links.
+ *
+ * Four gates, each dead pre-fix:
+ * 1. `[Name](slug.md)` (no `/`, no scheme) produced ZERO refs on the DB
+ * path (pass 1 requires `dir/`), while the FS walker linked it. Now a
+ * `sameDir` ref resolves against the linking page's directory.
+ * 2. extractPageLinks ignored the active pack — a user pack's
+ * `link_types[].inference.regex` (e.g. parent_of) typed nothing; every
+ * such edge landed as 'mentions'.
+ * 3. extractFrontmatterLinks ignored pack `frontmatter_links` — a pack
+ * field like `parents:` produced 0 candidates.
+ * 4. PGLite e2e: an ACTIVE custom pack (engine config `schema_pack` +
+ * locator seam) types edges through `gbrain extract --stale` end to end.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import {
+ extractEntityRefs,
+ extractPageLinks,
+ extractFrontmatterLinks,
+ type SlugResolver,
+} from '../src/core/link-extraction.ts';
+import {
+ parseSchemaPackManifest,
+ __setPackLocatorForTests,
+ _resetPackLocatorForTests,
+ _resetPackCacheForTests,
+} from '../src/core/schema-pack/index.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+
+const nullResolver: SlugResolver = { resolve: async () => null };
+
+const PACK = parseSchemaPackManifest({
+ api_version: 'gbrain-schema-pack-v1',
+ name: 'pack-3190',
+ version: '0.1.0',
+ extends: null,
+ page_types: [],
+ link_types: [
+ { name: 'parent_of', inference: { regex: '\\bparent of\\b' } },
+ ],
+ frontmatter_links: [
+ { page_type: 'concept', fields: ['parents'], link_type: 'parent_of' },
+ ],
+});
+
+describe('#3190 gate 1 — same-directory markdown links', () => {
+ test('extractEntityRefs surfaces [N](slug.md) as a sameDir ref', () => {
+ const refs = extractEntityRefs('See [Beta Notes](beta.md) for details.');
+ expect(refs).toHaveLength(1);
+ expect(refs[0].name).toBe('Beta Notes');
+ expect(refs[0].slug).toBe('beta');
+ expect(refs[0].sameDir).toBe(true);
+ });
+
+ test('scheme/anchor/dir targets never match the sameDir pass', () => {
+ expect(extractEntityRefs('[x](https://example.com/a.md)').filter(r => r.sameDir)).toEqual([]);
+ expect(extractEntityRefs('[x](beta.md#section)').filter(r => r.sameDir)).toEqual([]);
+ // dir-shaped targets belong to pass 1, not the sameDir pass
+ const dirRefs = extractEntityRefs('[x](people/beta.md)');
+ expect(dirRefs).toHaveLength(1);
+ expect(dirRefs[0].sameDir).toBeUndefined();
+ });
+
+ test('extractPageLinks resolves sameDir against the linking page directory', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/notes/alpha', 'See [Beta](beta.md).', {}, 'concept', nullResolver,
+ { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['wiki/notes/beta']);
+ expect(candidates[0].linkSource).toBe('markdown');
+ });
+
+ test('sameDir self-loop is guarded', async () => {
+ const { candidates } = await extractPageLinks(
+ 'wiki/notes/alpha', 'See [Alpha](alpha.md).', {}, 'concept', nullResolver,
+ { skipFrontmatter: true },
+ );
+ expect(candidates).toEqual([]);
+ });
+
+ test('percent-encoded sameDir target slugifies through the sync grammar', async () => {
+ const { candidates } = await extractPageLinks(
+ 'people/index', 'Met [Alice](Alice%20Chen.md).', {}, 'concept', nullResolver,
+ { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toEqual(['people/alice-chen']);
+ });
+});
+
+describe('#3190 gate 2 — pack regex verbs in extractPageLinks', () => {
+ test('pack regex types the edge (pre-fix: mentions)', async () => {
+ const { candidates } = await extractPageLinks(
+ 'companies/acme', 'Acme is the parent of [Sub Co](companies/sub-co).',
+ {}, 'company', nullResolver, { skipFrontmatter: true, pack: PACK },
+ );
+ expect(candidates).toHaveLength(1);
+ expect(candidates[0].targetSlug).toBe('companies/sub-co');
+ expect(candidates[0].linkType).toBe('parent_of');
+ });
+
+ test('no pack → legacy inference unchanged', async () => {
+ const { candidates } = await extractPageLinks(
+ 'companies/acme', 'Acme is the parent of [Sub Co](companies/sub-co).',
+ {}, 'company', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates[0].linkType).toBe('mentions');
+ });
+
+ test('pack miss falls through to legacy verbs', async () => {
+ const { candidates } = await extractPageLinks(
+ 'people/carol', 'Carol founded [Anchor](companies/anchor).',
+ {}, 'person', nullResolver, { skipFrontmatter: true, pack: PACK },
+ );
+ expect(candidates[0].linkType).toBe('founded');
+ });
+});
+
+describe('#3190 gate 3 — pack frontmatter_links in extractFrontmatterLinks', () => {
+ const resolver: SlugResolver = {
+ resolve: async (name) => (name === 'concepts/parent-page' ? 'concepts/parent-page' : null),
+ };
+
+ test('pack field emits an outgoing typed candidate (pre-fix: 0 candidates)', async () => {
+ const { candidates } = await extractFrontmatterLinks(
+ 'concepts/x', 'concept' as never, { parents: ['concepts/parent-page'] },
+ resolver, false, PACK,
+ );
+ expect(candidates).toHaveLength(1);
+ expect(candidates[0].fromSlug).toBe('concepts/x');
+ expect(candidates[0].targetSlug).toBe('concepts/parent-page');
+ expect(candidates[0].linkType).toBe('parent_of');
+ expect(candidates[0].linkSource).toBe('frontmatter');
+ expect(candidates[0].originField).toBe('parents');
+ });
+
+ test('pack rule scoped to its page_type', async () => {
+ const { candidates } = await extractFrontmatterLinks(
+ 'people/x', 'person' as never, { parents: ['concepts/parent-page'] },
+ resolver, false, PACK,
+ );
+ expect(candidates).toEqual([]);
+ });
+
+ test('no pack → pack fields stay inert (built-in map only)', async () => {
+ const { candidates } = await extractFrontmatterLinks(
+ 'concepts/x', 'concept' as never, { parents: ['concepts/parent-page'] },
+ resolver, false,
+ );
+ expect(candidates).toEqual([]);
+ });
+});
+
+describe('#3190 gate 4 — PGLite e2e: active pack types edges via extract --stale', () => {
+ let engine: PGLiteEngine;
+ let packDir: string;
+
+ beforeAll(async () => {
+ packDir = mkdtempSync(join(tmpdir(), 'gbrain-3190-pack-'));
+ writeFileSync(join(packDir, 'pack.yaml'), [
+ 'api_version: gbrain-schema-pack-v1',
+ 'name: pack-3190',
+ 'version: 0.1.0',
+ 'extends: null',
+ 'page_types: []',
+ 'link_types:',
+ ' - name: parent_of',
+ ' inference:',
+ ' regex: \\bparent of\\b',
+ 'frontmatter_links: []',
+ '',
+ ].join('\n'));
+ _resetPackCacheForTests();
+ __setPackLocatorForTests((name) => (name === 'pack-3190' ? join(packDir, 'pack.yaml') : null));
+
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('schema_pack', 'pack-3190');
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES
+ ('companies/acme', 'default', 'company', 'Acme', 'Acme is the parent of [Sub Co](companies/sub-co). Also see [Beta](sibling.md).', ''),
+ ('companies/sub-co', 'default', 'company', 'Sub Co', 'x', ''),
+ ('companies/sibling', 'default', 'company', 'Sibling', 'x', '')`,
+ );
+ }, 60_000);
+
+ afterAll(async () => {
+ _resetPackLocatorForTests();
+ _resetPackCacheForTests();
+ await engine.disconnect();
+ rmSync(packDir, { recursive: true, force: true });
+ });
+
+ test('stale sweep produces pack-typed + same-dir edges (>0)', async () => {
+ const r = await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ });
+ expect(r.pagesProcessed).toBeGreaterThan(0);
+
+ const rows = await engine.executeRaw<{ to_slug: string; link_type: string }>(
+ `SELECT pt.slug AS to_slug, l.link_type
+ FROM links l
+ JOIN pages pf ON pf.id = l.from_page_id AND pf.slug = 'companies/acme'
+ JOIN pages pt ON pt.id = l.to_page_id`,
+ );
+ // Gate 2 e2e: the pack verb typed the edge.
+ expect(rows.some(x => x.to_slug === 'companies/sub-co' && x.link_type === 'parent_of')).toBe(true);
+ // Gate 1 e2e: the same-dir markdown link produced an edge at all.
+ expect(rows.some(x => x.to_slug === 'companies/sibling')).toBe(true);
+ });
+});
diff --git a/test/link-extraction.test.ts b/test/link-extraction.test.ts
index ca70d91029..6617bd75bd 100644
--- a/test/link-extraction.test.ts
+++ b/test/link-extraction.test.ts
@@ -380,9 +380,12 @@ describe('extractPageLinks', () => {
// ─── issue #972: bare wikilink → resolver.resolveBasenameMatches ─────────
- test('bare wikilink drops silently when globalBasename flag is OFF', async () => {
+ test('bare wikilink skips basename resolution when globalBasename flag is OFF', async () => {
// Resolver that WOULD resolve, but we never reach it because the
- // flag is off — this is the back-compat invariant.
+ // flag is off — this is the back-compat invariant. #4062: the flag
+ // only gates BASENAME resolution; the root-exact direct candidate is
+ // emitted regardless (downstream existence checks drop it when no
+ // root page exists).
const resolver: SlugResolver = {
resolve: async () => null,
resolveBasenameMatches: async () => ['projects/struktura'],
@@ -394,7 +397,8 @@ describe('extractPageLinks', () => {
// opts.globalBasename omitted (= false)
);
expect(candidates.find(c => c.targetSlug === 'projects/struktura')).toBeUndefined();
- expect(candidates).toEqual([]);
+ expect(candidates.map(c => c.targetSlug)).toEqual(['struktura']);
+ expect(candidates[0].linkSource).toBe('markdown');
});
test('bare wikilink emits one candidate per basename match when flag ON', async () => {
@@ -410,13 +414,17 @@ describe('extractPageLinks', () => {
'This relates to [[struktura]].',
{}, 'concept', resolver, { globalBasename: true },
);
- const targets = candidates.map(c => c.targetSlug).sort();
- expect(targets).toEqual(['archive/struktura', 'projects/struktura']);
- // Both edges stamped with the new edge type + provenance.
- for (const c of candidates) {
- expect(c.linkType).toBe('wikilink_basename');
+ // #4062: the root-exact direct candidate rides along (dropped downstream
+ // when no root page exists); the basename matches carry the wikilink
+ // edge type + provenance.
+ const basename = candidates.filter(c => c.linkType === 'wikilink_basename');
+ expect(basename.map(c => c.targetSlug).sort()).toEqual(['archive/struktura', 'projects/struktura']);
+ for (const c of basename) {
expect(c.linkSource).toBe('wikilink-resolved');
}
+ expect(candidates.map(c => c.targetSlug).sort()).toEqual(
+ ['archive/struktura', 'projects/struktura', 'struktura'],
+ );
});
test('bare wikilink with single basename match emits one candidate', async () => {
@@ -430,9 +438,11 @@ describe('extractPageLinks', () => {
'See [[struktura]] for details.',
{}, 'concept', resolver, { globalBasename: true },
);
- expect(candidates.length).toBe(1);
- expect(candidates[0].targetSlug).toBe('projects/struktura');
- expect(candidates[0].linkType).toBe('wikilink_basename');
+ const basename = candidates.filter(c => c.linkType === 'wikilink_basename');
+ expect(basename.length).toBe(1);
+ expect(basename[0].targetSlug).toBe('projects/struktura');
+ // #4062: plus the root-exact direct candidate.
+ expect(candidates.map(c => c.targetSlug).sort()).toEqual(['projects/struktura', 'struktura']);
});
test('basename self-link is dropped (codex P2c)', async () => {
@@ -449,7 +459,10 @@ describe('extractPageLinks', () => {
{}, 'concept', resolver, { globalBasename: true },
);
// Only the OTHER match survives; no self-edge to concepts/struktura.
- expect(candidates.map(c => c.targetSlug)).toEqual(['projects/struktura']);
+ // (#4062: the root-exact direct candidate `struktura` rides along.)
+ expect(candidates.find(c => c.targetSlug === 'concepts/struktura')).toBeUndefined();
+ expect(candidates.filter(c => c.linkType === 'wikilink_basename').map(c => c.targetSlug))
+ .toEqual(['projects/struktura']);
});
test('aliased wikilink resolves the TARGET, not the display text (codex #972)', async () => {
@@ -471,10 +484,13 @@ describe('extractPageLinks', () => {
);
expect(seen).toContain('struktura');
expect(seen).not.toContain('the project');
- expect(candidates.map(c => c.targetSlug)).toEqual(['projects/struktura']);
+ expect(candidates.filter(c => c.linkType === 'wikilink_basename').map(c => c.targetSlug))
+ .toEqual(['projects/struktura']);
+ // #4062: the direct candidate also targets the TARGET, never the alias.
+ expect(candidates.find(c => c.targetSlug === 'the-project')).toBeUndefined();
});
- test('bare wikilink with zero basename matches drops silently (no dangling row)', async () => {
+ test('bare wikilink with zero basename matches emits no basename rows', async () => {
const resolver: SlugResolver = {
resolve: async () => null,
resolveBasenameMatches: async () => [],
@@ -483,8 +499,13 @@ describe('extractPageLinks', () => {
'concepts/x', 'Mention [[never-existed]].',
{}, 'concept', resolver, { globalBasename: true },
);
- expect(candidates.find(c => c.targetSlug === 'never-existed')).toBeUndefined();
- expect(candidates).toEqual([]);
+ // No wikilink-resolved rows. #4062: the root-exact direct candidate is
+ // still emitted — downstream existence checks (resolveCandidateSources /
+ // put_page allSlugs filter / addLinksBatch JOINs) drop it since no page
+ // named `never-existed` exists, so no dangling row is ever persisted.
+ expect(candidates.filter(c => c.linkSource === 'wikilink-resolved')).toEqual([]);
+ expect(candidates.map(c => c.targetSlug)).toEqual(['never-existed']);
+ expect(candidates[0].linkSource).toBe('markdown');
});
test('path-qualified wikilink outside DIR_PATTERN queries by final segment', async () => {
@@ -700,13 +721,15 @@ describe('extractPageLinks', () => {
test('globalBasename does nothing when resolver lacks resolveBasenameMatches', async () => {
// The frontmatter-only synthetic resolver doesn't implement basename
- // lookup. Make sure we don't blow up — just drop the bare ref.
+ // lookup. Make sure we don't blow up — no basename rows are emitted.
+ // (#4062: the root-exact direct candidate doesn't need the resolver.)
const resolver: SlugResolver = { resolve: async () => null };
const { candidates } = await extractPageLinks(
'concepts/x', 'See [[struktura]].',
{}, 'concept', resolver, { globalBasename: true },
);
- expect(candidates).toEqual([]);
+ expect(candidates.filter(c => c.linkSource === 'wikilink-resolved')).toEqual([]);
+ expect(candidates.map(c => c.targetSlug)).toEqual(['struktura']);
});
});
@@ -899,7 +922,7 @@ describe('parseTimelineEntries', () => {
test('parses standard format: - **YYYY-MM-DD** | summary', () => {
const entries = parseTimelineEntries('- **2026-01-15** | Met with Alice');
expect(entries.length).toBe(1);
- expect(entries[0]).toEqual({ date: '2026-01-15', summary: 'Met with Alice', detail: '' });
+ expect(entries[0]).toEqual({ date: '2026-01-15', summary: 'Met with Alice', detail: '', source: 'markdown' });
});
test('parses dash variant: - **YYYY-MM-DD** -- summary', () => {
@@ -1626,6 +1649,7 @@ Follow-up decision recorded. [Source: memo, 2025-03-20]`);
date: '2025-03-20',
summary: 'Follow-up decision recorded.',
detail: 'Source: memo',
+ source: 'memo', // #3957: citation label carried in the dedup-key column
});
});
@@ -1639,6 +1663,7 @@ Real claim. [Source: memo, 2025-01-02]`);
date: '2025-01-02',
summary: 'Real claim.',
detail: 'Source: memo',
+ source: 'memo', // #3957
});
});
@@ -1891,3 +1916,84 @@ describe('normalizeBasename — CJK + accent folding (#2367)', () => {
.toEqual(['meetings/루카텍-올핸즈-미팅']);
});
});
+
+// ─── #4062: table-escaped pipes + bare-wikilink flag-off candidates ────
+
+describe('#4062 — escaped-pipe wikilinks (markdown tables)', () => {
+ test('pass 2b: [[dir/slug\\|Alias]] strips the escape backslash from the slug', () => {
+ const refs = extractEntityRefs('| [[companies/example-co\\|Example Co]] | note |');
+ expect(refs.length).toBe(1);
+ expect(refs[0].slug).toBe('companies/example-co');
+ expect(refs[0].name).toBe('Example Co');
+ });
+
+ test('pass 2a: qualified [[src:dir/slug\\|Alias]] strips the escape backslash', () => {
+ const refs = extractEntityRefs('| [[wiki:companies/example-co\\|X]] | note |');
+ expect(refs.length).toBe(1);
+ expect(refs[0].slug).toBe('companies/example-co');
+ expect(refs[0].sourceId).toBe('wiki');
+ });
+
+ test('pass 2c: generic [[bare-name\\|Alias]] strips the escape backslash', () => {
+ const refs = extractEntityRefs('| [[example-rail\\|Example Rail]] | note |');
+ expect(refs.length).toBe(1);
+ expect(refs[0].slug).toBe('example-rail');
+ expect(refs[0].needsResolution).toBe(true);
+ });
+
+ test('escaped pipe before .md suffix still strips the extension', () => {
+ const refs = extractEntityRefs('| [[companies/example-co.md\\|Example]] |');
+ expect(refs.length).toBe(1);
+ expect(refs[0].slug).toBe('companies/example-co');
+ });
+});
+
+describe('#4062 — bare [[name]] emits a root-exact direct candidate flag-off', () => {
+ const resolver: SlugResolver = {
+ async resolve() { return null; },
+ async resolveBasenameMatches(name: string) {
+ return name === 'example-rail' ? ['example-rail', 'projects/example-rail'] : [];
+ },
+ };
+
+ test('flag-off: [[example-rail]] yields a verb-typed root-exact candidate', async () => {
+ const r = await extractPageLinks(
+ 'notes/some-page', 'see [[example-rail]] for details', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.length).toBe(1);
+ expect(r.candidates[0].targetSlug).toBe('example-rail');
+ expect(r.candidates[0].linkType).toBe('mentions');
+ expect(r.candidates[0].linkSource).toBe('markdown');
+ });
+
+ test('flag-off: display alias slugifies to the root-exact target', async () => {
+ const r = await extractPageLinks(
+ 'notes/some-page', 'see [[Example Rail]] for details', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.map(c => c.targetSlug)).toEqual(['example-rail']);
+ });
+
+ test('flag-off: self-loop guarded — [[own-slug]] on the root page emits nothing', async () => {
+ const r = await extractPageLinks(
+ 'example-rail', 'this page is [[example-rail]] itself', {}, 'concept' as any,
+ resolver, { globalBasename: false, skipFrontmatter: true },
+ );
+ expect(r.candidates.length).toBe(0);
+ });
+
+ test('flag-on: root-exact match not double-emitted (direct candidate covers it)', async () => {
+ const r = await extractPageLinks(
+ 'notes/some-page', 'see [[example-rail]] for details', {}, 'concept' as any,
+ resolver, { globalBasename: true, skipFrontmatter: true },
+ );
+ const targets = r.candidates.map(c => `${c.targetSlug}:${c.linkType}`).sort();
+ // Root-exact gets the direct verb-typed edge; the OTHER basename match
+ // keeps the wikilink_basename provenance.
+ expect(targets).toEqual([
+ 'example-rail:mentions',
+ 'projects/example-rail:wikilink_basename',
+ ]);
+ });
+});
diff --git a/test/lint-3958.test.ts b/test/lint-3958.test.ts
new file mode 100644
index 0000000000..d8c9f50e35
--- /dev/null
+++ b/test/lint-3958.test.ts
@@ -0,0 +1,184 @@
+/**
+ * issue #3958 — three lint honesty fixes:
+ *
+ * 1. The "Run with --fix" hint only prints when at least one finding is
+ * actually fixable (LintResult.total_fixable), so an all-unfixable report
+ * can't send the operator on a no-op --fix run.
+ * 2. missing-created is FIXABLE when the page's own frontmatter carries a
+ * capture timestamp (captured_at / ingested_at) — fixContent promotes it
+ * to created.
+ * 3. placeholder-date skips lines inside fenced code blocks: a page
+ * DOCUMENTING date formats (```\ncreated: YYYY-MM-DD\n```) is not a page
+ * with an unfilled placeholder.
+ */
+
+import { test, expect, describe, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import {
+ lintContent,
+ fixContent,
+ promoteCreatedFromCapture,
+ runLintCore,
+ runLint,
+} from '../src/commands/lint.ts';
+
+const SANITY_OFF = { disabled: true } as const;
+
+describe('#3958 placeholder-date skips fenced code blocks', () => {
+ test('YYYY-MM-DD inside a ``` fence is not a placeholder', () => {
+ const content =
+ '---\ntitle: Date docs\ntype: note\ncreated: 2026-01-05\n---\n\n# Formats\n\n' +
+ '```\ncreated: YYYY-MM-DD\n```\n\nDone.\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ expect(issues.filter(i => i.rule === 'placeholder-date')).toHaveLength(0);
+ });
+
+ test('YYYY-MM-DD inside a ~~~ fence is not a placeholder', () => {
+ const content =
+ '---\ntitle: Date docs\ntype: note\ncreated: 2026-01-05\n---\n\n' +
+ '~~~yaml\ndate: YYYY-MM-DD\n~~~\n\nDone.\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ expect(issues.filter(i => i.rule === 'placeholder-date')).toHaveLength(0);
+ });
+
+ test('placeholder OUTSIDE a fence still fires, with the right line', () => {
+ const content =
+ '---\ntitle: T\ntype: note\ncreated: 2026-01-05\n---\n\n' +
+ '```\nexample: YYYY-MM-DD\n```\n\n- 2026-XX-XX | unfilled event\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ const hits = issues.filter(i => i.rule === 'placeholder-date');
+ expect(hits).toHaveLength(1);
+ // Line 11 is the "- 2026-XX-XX | ..." line (1-indexed).
+ expect(hits[0].line).toBe(11);
+ });
+
+ test('placeholder in frontmatter still fires (frontmatter is not a fence)', () => {
+ const content = '---\ntitle: T\ntype: note\ncreated: YYYY-MM-DD\n---\n\n# T\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ expect(issues.some(i => i.rule === 'placeholder-date')).toBe(true);
+ });
+});
+
+describe('#3958 missing-created is fixable via capture-timestamp promotion', () => {
+ test('captured_at present -> missing-created is fixable', () => {
+ const content = '---\ntitle: T\ntype: note\ncaptured_at: 2026-01-05T10:00:00Z\n---\n\n# T\n\nBody.\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ const mc = issues.find(i => i.rule === 'missing-created');
+ expect(mc).toBeDefined();
+ expect(mc!.fixable).toBe(true);
+ });
+
+ test('no capture field -> missing-created stays unfixable', () => {
+ const content = '---\ntitle: T\ntype: note\n---\n\n# T\n\nBody.\n';
+ const issues = lintContent(content, 'test.md', { contentSanity: SANITY_OFF });
+ const mc = issues.find(i => i.rule === 'missing-created');
+ expect(mc).toBeDefined();
+ expect(mc!.fixable).toBe(false);
+ });
+
+ test('promoteCreatedFromCapture copies captured_at verbatim', () => {
+ const content = '---\ntitle: T\ncaptured_at: 2026-01-05T10:00:00Z\n---\n\nBody.\n';
+ const out = promoteCreatedFromCapture(content);
+ expect(out).toContain('created: 2026-01-05T10:00:00Z');
+ // Inserted inside the frontmatter block, directly after captured_at.
+ expect(out.indexOf('created:')).toBeGreaterThan(out.indexOf('captured_at:'));
+ expect(out.indexOf('created:')).toBeLessThan(out.indexOf('---', 3) + 4);
+ });
+
+ test('promoteCreatedFromCapture falls back to ingested_at', () => {
+ const content = '---\ntitle: T\ningested_at: "2026-02-01"\n---\n\nBody.\n';
+ const out = promoteCreatedFromCapture(content);
+ expect(out).toContain('created: "2026-02-01"');
+ });
+
+ test('promoteCreatedFromCapture prefers captured_at over ingested_at', () => {
+ const content = '---\ntitle: T\ningested_at: 2026-02-01\ncaptured_at: 2026-01-05\n---\n\nBody.\n';
+ const out = promoteCreatedFromCapture(content);
+ expect(out).toContain('created: 2026-01-05');
+ expect(out).not.toContain('created: 2026-02-01');
+ });
+
+ test('promoteCreatedFromCapture is a no-op when created exists / no frontmatter', () => {
+ const withCreated = '---\ntitle: T\ncreated: 2025-12-31\ncaptured_at: 2026-01-05\n---\n\nBody.\n';
+ expect(promoteCreatedFromCapture(withCreated)).toBe(withCreated);
+ const noFm = '# Just a heading\n\ncaptured_at: 2026-01-05\n';
+ expect(promoteCreatedFromCapture(noFm)).toBe(noFm);
+ });
+
+ test('fixContent heals missing-created end-to-end (incl. fence-wrapped pages)', () => {
+ const wrapped =
+ '```markdown\n---\ntitle: T\ntype: note\ncaptured_at: 2026-01-05\n---\n\n# T\n\nBody.\n```';
+ const fixed = fixContent(wrapped);
+ expect(fixed.startsWith('---')).toBe(true);
+ expect(fixed).toContain('created: 2026-01-05');
+ const after = lintContent(fixed, 'test.md', { contentSanity: SANITY_OFF });
+ expect(after.filter(i => i.rule === 'missing-created')).toHaveLength(0);
+ expect(after.filter(i => i.rule === 'code-fence-wrap')).toHaveLength(0);
+ });
+});
+
+describe('#3958 total_fixable + the --fix hint gate', () => {
+ let dir: string;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-lint-3958-'));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('runLintCore reports total_fixable separately from total_issues', async () => {
+ // One unfixable issue (placeholder-date in the body) + one fixable page
+ // (missing-created promotable from captured_at).
+ writeFileSync(
+ join(dir, 'unfixable.md'),
+ '---\ntitle: A\ntype: note\ncreated: 2026-01-05\n---\n\n- 2026-XX-XX | pending\n',
+ );
+ writeFileSync(
+ join(dir, 'fixable.md'),
+ '---\ntitle: B\ntype: note\ncaptured_at: 2026-01-05\n---\n\n# B\n\nBody.\n',
+ );
+ const result = await runLintCore({ target: dir, contentSanity: SANITY_OFF as never });
+ expect(result.total_issues).toBe(2);
+ expect(result.total_fixable).toBe(1);
+ });
+
+ test('runLintCore --fix writes the promoted created field', async () => {
+ const page = join(dir, 'fixable.md');
+ writeFileSync(page, '---\ntitle: B\ntype: note\ncaptured_at: 2026-01-05\n---\n\n# B\n\nBody.\n');
+ const result = await runLintCore({ target: dir, fix: true, contentSanity: SANITY_OFF as never });
+ expect(result.total_fixed).toBe(1);
+ expect(readFileSync(page, 'utf-8')).toContain('created: 2026-01-05');
+ });
+
+ test('hint prints only when something is fixable', async () => {
+ writeFileSync(
+ join(dir, 'unfixable.md'),
+ '---\ntitle: A\ntype: note\ncreated: 2026-01-05\n---\n\n- 2026-XX-XX | pending\n',
+ );
+ const logged: string[] = [];
+ const orig = console.log;
+ console.log = (...a: unknown[]) => { logged.push(a.join(' ')); };
+ try {
+ await runLint([dir]);
+ } finally {
+ console.log = orig;
+ }
+ expect(logged.join('\n')).not.toContain('Run with --fix');
+
+ // Add a fixable page: the hint appears.
+ writeFileSync(
+ join(dir, 'fixable.md'),
+ '---\ntitle: B\ntype: note\ncaptured_at: 2026-01-05\n---\n\n# B\n\nBody.\n',
+ );
+ const logged2: string[] = [];
+ console.log = (...a: unknown[]) => { logged2.push(a.join(' ')); };
+ try {
+ await runLint([dir]);
+ } finally {
+ console.log = orig;
+ }
+ expect(logged2.join('\n')).toContain('Run with --fix');
+ });
+});
diff --git a/test/llm-halt-cooldown.test.ts b/test/llm-halt-cooldown.test.ts
new file mode 100644
index 0000000000..6b650be8ae
--- /dev/null
+++ b/test/llm-halt-cooldown.test.ts
@@ -0,0 +1,252 @@
+/**
+ * #4310 — provider-identity-keyed global-LLM-halt cooldown at the queued-job
+ * boundary (facts-absorb).
+ *
+ * Pre-fix: a globally-broken provider (revoked key, exhausted quota, hard
+ * rate limit) made every queued facts-absorb job burn its own attempts on
+ * doomed LLM calls and dead-letter independently. The wrapper arms one
+ * provider-keyed cooldown on a halt-class error, DEFERS matching jobs without
+ * burning attempts (RateLeaseUnavailableError + retryInMs → worker lease-full
+ * requeue), and admits exactly one bounded probe on expiry.
+ */
+
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import {
+ withGlobalLlmHaltCooldown,
+ providerIdentityForJob,
+ _resetLlmHaltCooldownsForTests,
+ llmHaltCooldownRemainingMs,
+ HALT_COOLDOWN_BASE_MS,
+} from '../src/core/minions/llm-halt-cooldown.ts';
+import { RateLeaseUnavailableError } from '../src/core/minions/rate-leases.ts';
+import { RATE_LIMIT_HALT_STREAK } from '../src/core/ai/errors.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const job = (data: Record<string, unknown> = {}): MinionJobContext =>
+ ({
+ id: 1,
+ name: 'facts-absorb',
+ data,
+ attempts_made: 0,
+ signal: new AbortController().signal,
+ deadlineAtMs: null,
+ updateProgress: async () => {},
+ }) as unknown as MinionJobContext;
+
+const authError = () => Object.assign(new Error('provider rejected'), { status: 401 });
+const billingError = () => new Error('insufficient_quota: monthly spend limit reached');
+const rateLimitError = () => Object.assign(new Error('slow down'), { status: 429 });
+
+beforeEach(() => _resetLlmHaltCooldownsForTests());
+afterEach(() => {
+ _resetLlmHaltCooldownsForTests();
+});
+
+function makeWrapped(opts: {
+ key?: string;
+ fail?: () => Error | null; // null = succeed
+ now?: () => number;
+ calls?: { count: number };
+}) {
+ const calls = opts.calls ?? { count: 0 };
+ const handler = async () => {
+ calls.count++;
+ const err = opts.fail?.();
+ if (err) throw err;
+ return { ok: true };
+ };
+ return {
+ calls,
+ run: withGlobalLlmHaltCooldown(() => opts.key ?? 'prov-a', handler, { now: opts.now }),
+ };
+}
+
+describe('auth class', () => {
+ test('first failure propagates AND arms the cooldown; next job defers without a handler call', async () => {
+ const { run, calls } = makeWrapped({ fail: authError });
+ await expect(run(job())).rejects.toThrow('provider rejected'); // visible failure
+ expect(llmHaltCooldownRemainingMs('prov-a')).toBeGreaterThan(0);
+
+ await expect(run(job())).rejects.toBeInstanceOf(RateLeaseUnavailableError);
+ expect(calls.count).toBe(1); // deferred job never reached the provider
+ });
+
+ test('deferral carries retryInMs ≈ remaining cooldown (worker requeues delayed, no attempt burned)', async () => {
+ const { run } = makeWrapped({ fail: authError });
+ await run(job()).catch(() => {});
+ try {
+ await run(job());
+ throw new Error('expected deferral');
+ } catch (e) {
+ const lease = e as RateLeaseUnavailableError;
+ expect(lease).toBeInstanceOf(RateLeaseUnavailableError);
+ expect(lease.key).toBe('global-llm-halt:auth:prov-a');
+ expect(lease.retryInMs).toBeGreaterThanOrEqual(1000);
+ expect(lease.retryInMs!).toBeLessThanOrEqual(HALT_COOLDOWN_BASE_MS.auth + 6000);
+ }
+ });
+});
+
+describe('billing class', () => {
+ test('first billing failure arms the cooldown', async () => {
+ const { run, calls } = makeWrapped({ fail: billingError });
+ await expect(run(job())).rejects.toThrow('insufficient_quota');
+ await expect(run(job())).rejects.toBeInstanceOf(RateLeaseUnavailableError);
+ expect(calls.count).toBe(1);
+ });
+});
+
+describe('rate_limit class', () => {
+ test(`arms only after ${RATE_LIMIT_HALT_STREAK} consecutive 429s (streak shared ACROSS jobs)`, async () => {
+ const { run, calls } = makeWrapped({ fail: rateLimitError });
+ for (let i = 0; i < RATE_LIMIT_HALT_STREAK - 1; i++) {
+ await expect(run(job())).rejects.toThrow('slow down'); // still per-item
+ expect(llmHaltCooldownRemainingMs('prov-a')).toBe(0);
+ }
+ await expect(run(job())).rejects.toThrow('slow down'); // streak crosses threshold
+ expect(llmHaltCooldownRemainingMs('prov-a')).toBeGreaterThan(0);
+ await expect(run(job())).rejects.toBeInstanceOf(RateLeaseUnavailableError);
+ expect(calls.count).toBe(RATE_LIMIT_HALT_STREAK);
+ });
+
+ test('a success between 429s clears the shared streak', async () => {
+ let n = 0;
+ const { run } = makeWrapped({ fail: () => (++n === 2 ? null : rateLimitError()) });
+ await run(job()).catch(() => {});
+ await run(job()); // success → streak reset
+ await run(job()).catch(() => {});
+ await run(job()).catch(() => {});
+ expect(llmHaltCooldownRemainingMs('prov-a')).toBe(0); // 2 consecutive < threshold
+ });
+});
+
+describe('probe on expiry', () => {
+ test('one probe admitted; success clears the cooldown', async () => {
+ let t = 1_000_000;
+ let failNow = true;
+ const { run, calls } = makeWrapped({ fail: () => (failNow ? authError() : null), now: () => t });
+ await run(job()).catch(() => {});
+ expect(llmHaltCooldownRemainingMs('prov-a', t)).toBe(HALT_COOLDOWN_BASE_MS.auth);
+
+ t += HALT_COOLDOWN_BASE_MS.auth + 1; // cooldown lapsed
+ failNow = false; // provider recovered
+ const result = await run(job()); // the bounded probe
+ expect(result).toEqual({ ok: true });
+ expect(llmHaltCooldownRemainingMs('prov-a', t)).toBe(0);
+ await run(job()); // steady state restored
+ expect(calls.count).toBe(3);
+ });
+
+ test('probe failure re-arms with DOUBLED backoff', async () => {
+ let t = 1_000_000;
+ const { run } = makeWrapped({ fail: authError, now: () => t });
+ await run(job()).catch(() => {});
+ t += HALT_COOLDOWN_BASE_MS.auth + 1;
+ await expect(run(job())).rejects.toThrow('provider rejected'); // probe fails
+ const remaining = llmHaltCooldownRemainingMs('prov-a', t);
+ expect(remaining).toBe(HALT_COOLDOWN_BASE_MS.auth * 2);
+ });
+
+ test('while the probe is in flight, other jobs defer on a short retry', async () => {
+ let t = 1_000_000;
+ let release: () => void = () => {};
+ const gate = new Promise<void>((r) => { release = r; });
+ let armed = true;
+ const handler = async () => {
+ if (armed) { armed = false; throw authError(); }
+ await gate;
+ return { ok: true };
+ };
+ const run = withGlobalLlmHaltCooldown(() => 'prov-a', handler, { now: () => t });
+ await run(job()).catch(() => {});
+ t += HALT_COOLDOWN_BASE_MS.auth + 1;
+ const probe = run(job()); // in flight, parked on the gate
+ await expect(run(job())).rejects.toBeInstanceOf(RateLeaseUnavailableError);
+ release();
+ expect(await probe).toEqual({ ok: true });
+ });
+
+ test('a nested deferral from the probe releases the probe slot (no permanent wedge)', async () => {
+ let t = 1_000_000;
+ let mode: 'halt' | 'nested-defer' | 'ok' = 'halt';
+ const handler = async () => {
+ if (mode === 'halt') throw authError();
+ if (mode === 'nested-defer') throw new RateLeaseUnavailableError('model-lease', 1, 1, 500);
+ return { ok: true };
+ };
+ const run = withGlobalLlmHaltCooldown(() => 'prov-a', handler, { now: () => t });
+ await run(job()).catch(() => {}); // arms the cooldown
+ t += HALT_COOLDOWN_BASE_MS.auth + 1;
+ mode = 'nested-defer';
+ // The admitted probe defers via a nested lease wrapper — passes through.
+ await expect(run(job())).rejects.toBeInstanceOf(RateLeaseUnavailableError);
+ // Pre-fix: probeInFlight stayed latched forever, so this job (and the
+ // requeued probe itself) deferred on the 15s cadence until worker restart.
+ mode = 'ok';
+ expect(await run(job())).toEqual({ ok: true });
+ });
+});
+
+describe('strikes escalate per probe, not per concurrent failure', () => {
+ test('a burst of concurrent halt-class failures arms ONE strike (base cooldown, not escalated)', async () => {
+ let t = 1_000_000;
+ let release: () => void = () => {};
+ const gate = new Promise<void>((r) => { release = r; });
+ const handler = async () => { await gate; throw authError(); };
+ const run = withGlobalLlmHaltCooldown(() => 'prov-a', handler, { now: () => t });
+ // Three jobs in flight BEFORE any cooldown exists — all fail together.
+ const a = run(job()).catch(() => {});
+ const b = run(job()).catch(() => {});
+ const c = run(job()).catch(() => {});
+ release();
+ await Promise.all([a, b, c]);
+ // Pre-fix: each concurrent failure incremented strikes (3 → 20min).
+ // The documented policy is consecutive halted PROBES → exponential re-arm.
+ expect(llmHaltCooldownRemainingMs('prov-a', t)).toBe(HALT_COOLDOWN_BASE_MS.auth);
+ });
+});
+
+describe('isolation + hatches', () => {
+ test('cooldown is provider-keyed: a different provider is unaffected', async () => {
+ const a = makeWrapped({ key: 'prov-a', fail: authError });
+ const b = makeWrapped({ key: 'prov-b', fail: () => null });
+ await a.run(job()).catch(() => {});
+ expect(await b.run(job())).toEqual({ ok: true });
+ });
+
+ test('non-halt errors stay per-item (no cooldown)', async () => {
+ const { run } = makeWrapped({ fail: () => new Error('context length exceeded for this page') });
+ await run(job()).catch(() => {});
+ expect(llmHaltCooldownRemainingMs('prov-a')).toBe(0);
+ await expect(run(job())).rejects.toThrow('context length'); // handler ran again
+ });
+
+ test('GBRAIN_LLM_HALT_COOLDOWN=0 disables the mechanism', async () => {
+ await withEnv({ GBRAIN_LLM_HALT_COOLDOWN: '0' }, async () => {
+ const { run, calls } = makeWrapped({ fail: authError });
+ await run(job()).catch(() => {});
+ await run(job()).catch(() => {});
+ expect(calls.count).toBe(2); // no deferral — pre-#4310 behavior
+ });
+ });
+});
+
+describe('providerIdentityForJob', () => {
+ test('job model override wins; provider half is the key', () => {
+ expect(providerIdentityForJob(job({ model: 'anthropic:claude-x' }), () => 'openai:gpt-4o')).toBe('anthropic');
+ });
+ test('falls back to the configured chat model', () => {
+ expect(providerIdentityForJob(job(), () => 'openai:gpt-4o')).toBe('openai');
+ });
+ test('bare model ids key on the whole string', () => {
+ expect(providerIdentityForJob(job({ model: 'gpt-4o' }), () => null)).toBe('gpt-4o');
+ });
+});
+
+describe('RateLeaseUnavailableError.retryInMs (worker contract)', () => {
+ test('optional field carried for the worker lease-full path', () => {
+ expect(new RateLeaseUnavailableError('k', 1, 1, 5000).retryInMs).toBe(5000);
+ expect(new RateLeaseUnavailableError('k', 1, 1).retryInMs).toBeUndefined();
+ });
+});
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 6b8329986d..02e4524a03 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -250,7 +250,7 @@ describe('migrate v36 — subagent_provider_neutral_persistence_v0_27', () => {
});
test('embedded schema (src/core/schema-embedded.ts) reflects v36 columns', async () => {
- const { SCHEMA_SQL } = await import('../src/core/schema-embedded.ts');
+ const { SCHEMA_SQL } = await import('../src/core/schema-embedded.generated.ts');
expect(SCHEMA_SQL).toContain('schema_version');
expect(SCHEMA_SQL).toContain('provider_id');
expect(SCHEMA_SQL).toContain('idx_subagent_messages_provider');
diff --git a/test/migrations-v0_14_0.test.ts b/test/migrations-v0_14_0.test.ts
index 210c3ec1eb..2c12879da2 100644
--- a/test/migrations-v0_14_0.test.ts
+++ b/test/migrations-v0_14_0.test.ts
@@ -94,7 +94,7 @@ describe('Bug 8 — max_stalled default bumped in schema files', () => {
// non-terminal rows via migration v15. These structural assertions track the
// current schema source state (not historical).
test('schema-embedded.ts has max_stalled DEFAULT 5', async () => {
- const source = await Bun.file(new URL('../src/core/schema-embedded.ts', import.meta.url)).text();
+ const source = await Bun.file(new URL('../src/core/schema-embedded.generated.ts', import.meta.url)).text();
expect(source).toContain('max_stalled INTEGER NOT NULL DEFAULT 5');
});
test('pglite-schema.ts has max_stalled DEFAULT 5', async () => {
diff --git a/test/migrations-v0_16_0.test.ts b/test/migrations-v0_16_0.test.ts
index ffa32f74b5..2b824f5039 100644
--- a/test/migrations-v0_16_0.test.ts
+++ b/test/migrations-v0_16_0.test.ts
@@ -78,7 +78,7 @@ describe('v0.16.0 migration', () => {
describe('schema-embedded.ts contains subagent tables', () => {
test('embedded schema references all three subagent tables', async () => {
- const { SCHEMA_SQL } = await import('../src/core/schema-embedded.ts');
+ const { SCHEMA_SQL } = await import('../src/core/schema-embedded.generated.ts');
expect(SCHEMA_SQL).toContain('CREATE TABLE IF NOT EXISTS subagent_messages');
expect(SCHEMA_SQL).toContain('CREATE TABLE IF NOT EXISTS subagent_tool_executions');
expect(SCHEMA_SQL).toContain('CREATE TABLE IF NOT EXISTS subagent_rate_leases');
diff --git a/test/model-config.serial.test.ts b/test/model-config.serial.test.ts
index 5274715ba6..8f50c4b4fb 100644
--- a/test/model-config.serial.test.ts
+++ b/test/model-config.serial.test.ts
@@ -187,13 +187,31 @@ describe('resolveModel — 6-tier precedence', () => {
});
describe('resolveModel — v0.31.12 tier system', () => {
- test('models.default beats tier override', async () => {
+ test('models.tier.<tier> beats models.default (#3873 — specific over generic)', async () => {
stub.set('models.default', 'opus');
stub.set('models.tier.reasoning', 'haiku');
const m = await resolveModel(stub as never, {
tier: 'reasoning',
fallback: 'sonnet',
});
+ expect(m).toBe(DEFAULT_ALIASES.haiku);
+ });
+
+ test('models.default still applies when the call has no tier (#3873)', async () => {
+ stub.set('models.default', 'opus');
+ stub.set('models.tier.reasoning', 'haiku');
+ const m = await resolveModel(stub as never, {
+ fallback: 'sonnet',
+ });
+ expect(m).toBe(DEFAULT_ALIASES.opus);
+ });
+
+ test('models.default still applies when the tier has no override (#3873)', async () => {
+ stub.set('models.default', 'opus');
+ const m = await resolveModel(stub as never, {
+ tier: 'reasoning',
+ fallback: 'sonnet',
+ });
expect(m).toBe(DEFAULT_ALIASES.opus);
});
diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.ts
index cf0052c08b..aa77b96fbc 100644
--- a/test/model-pricing.test.ts
+++ b/test/model-pricing.test.ts
@@ -16,6 +16,8 @@ import { fileURLToPath } from 'node:url';
import {
CANONICAL_PRICING,
canonicalLookup,
+ ANTHROPIC_CACHE_READ_MULT,
+ ANTHROPIC_CACHE_WRITE_5M_MULT,
} from '../src/core/model-pricing.ts';
import { ANTHROPIC_PRICING } from '../src/core/anthropic-pricing.ts';
import { MODEL_PRICING } from '../src/core/takes-quality-eval/pricing.ts';
@@ -36,23 +38,23 @@ describe('CANONICAL_PRICING — table integrity', () => {
});
test('Opus 5 present at $5/$25 (same tier as Opus 4.8)', () => {
- expect(CANONICAL_PRICING['anthropic:claude-opus-5']).toEqual({ input: 5.0, output: 25.0 });
+ expect(CANONICAL_PRICING['anthropic:claude-opus-5']).toMatchObject({ input: 5.0, output: 25.0 });
});
test('Opus 4.8 present at $5/$25 (closes gbrain#1819)', () => {
- expect(CANONICAL_PRICING['anthropic:claude-opus-4-8']).toEqual({ input: 5.0, output: 25.0 });
+ expect(CANONICAL_PRICING['anthropic:claude-opus-4-8']).toMatchObject({ input: 5.0, output: 25.0 });
});
test('Opus 4.7 at $5/$25 (not the stale $15/$75)', () => {
- expect(CANONICAL_PRICING['anthropic:claude-opus-4-7']).toEqual({ input: 5.0, output: 25.0 });
+ expect(CANONICAL_PRICING['anthropic:claude-opus-4-7']).toMatchObject({ input: 5.0, output: 25.0 });
});
test('Sonnet 5 present at $3/$15 (standard rate, intro discount not modeled)', () => {
- expect(CANONICAL_PRICING['anthropic:claude-sonnet-5']).toEqual({ input: 3.0, output: 15.0 });
+ expect(CANONICAL_PRICING['anthropic:claude-sonnet-5']).toMatchObject({ input: 3.0, output: 15.0 });
});
test('Fable 5 present at $10/$50', () => {
- expect(CANONICAL_PRICING['anthropic:claude-fable-5']).toEqual({ input: 10.0, output: 50.0 });
+ expect(CANONICAL_PRICING['anthropic:claude-fable-5']).toMatchObject({ input: 10.0, output: 50.0 });
});
test('Gemini 2.0 Flash reconciled to $0.10/$0.40; legacy alias agrees', () => {
@@ -61,19 +63,51 @@ describe('CANONICAL_PRICING — table integrity', () => {
CANONICAL_PRICING['google:gemini-2.0-flash'],
);
});
+
+ // #4218 drift guard extension: cache_read/cache_write are DERIVED from the
+ // input rate via the exported multipliers — a hand-edited cache number that
+ // drifts from input*mult fails here.
+ test('every anthropic: row carries cache_read = 0.1x input and cache_write = 1.25x input', () => {
+ for (const [key, p] of Object.entries(CANONICAL_PRICING)) {
+ if (!key.startsWith('anthropic:')) continue;
+ expect(p.cache_read).toBeCloseTo(p.input * ANTHROPIC_CACHE_READ_MULT, 10);
+ expect(p.cache_write).toBeCloseTo(p.input * ANTHROPIC_CACHE_WRITE_5M_MULT, 10);
+ }
+ });
+
+ test('cache fields, when present, are finite positive with read < input < write', () => {
+ for (const [key, p] of Object.entries(CANONICAL_PRICING)) {
+ if (p.cache_read !== undefined) {
+ expect(Number.isFinite(p.cache_read)).toBe(true);
+ expect(p.cache_read).toBeGreaterThan(0);
+ expect(p.cache_read).toBeLessThan(p.input);
+ }
+ if (p.cache_write !== undefined) {
+ expect(Number.isFinite(p.cache_write)).toBe(true);
+ expect(p.cache_write).toBeGreaterThan(p.input);
+ }
+ // Non-Anthropic rows deliberately carry NO cache fields until their
+ // provider's cache pricing is verified — consumers fall back to the
+ // input rate (documented in ModelPricing).
+ if (!key.startsWith('anthropic:')) {
+ expect(p.cache_read).toBeUndefined();
+ expect(p.cache_write).toBeUndefined();
+ }
+ }
+ });
});
describe('canonicalLookup — id normalization', () => {
test('bare anthropic id → hit (defaults to anthropic provider)', () => {
- expect(canonicalLookup('claude-opus-4-8')).toEqual({ input: 5.0, output: 25.0 });
+ expect(canonicalLookup('claude-opus-4-8')).toMatchObject({ input: 5.0, output: 25.0 });
});
test('colon form → hit', () => {
- expect(canonicalLookup('anthropic:claude-opus-4-8')).toEqual({ input: 5.0, output: 25.0 });
+ expect(canonicalLookup('anthropic:claude-opus-4-8')).toMatchObject({ input: 5.0, output: 25.0 });
});
test('slash form → hit', () => {
- expect(canonicalLookup('anthropic/claude-opus-4-8')).toEqual({ input: 5.0, output: 25.0 });
+ expect(canonicalLookup('anthropic/claude-opus-4-8')).toMatchObject({ input: 5.0, output: 25.0 });
});
test('non-anthropic bare id → miss (preserves prior null contract)', () => {
@@ -177,11 +211,11 @@ describe('no heavy import (cycle guard)', () => {
describe('canonicalLookup — case-insensitive fallback (#4123 / TODOS case-sensitivity)', () => {
test('cased provider prefix resolves', () => {
- expect(canonicalLookup('ANTHROPIC:claude-opus-4-8')).toEqual({ input: 5.0, output: 25.0 });
+ expect(canonicalLookup('ANTHROPIC:claude-opus-4-8')).toMatchObject({ input: 5.0, output: 25.0 });
});
test('cased model tail resolves', () => {
- expect(canonicalLookup('anthropic:CLAUDE-OPUS-4-8')).toEqual({ input: 5.0, output: 25.0 });
+ expect(canonicalLookup('anthropic:CLAUDE-OPUS-4-8')).toMatchObject({ input: 5.0, output: 25.0 });
});
test('nested OpenRouter ids still intentionally MISS (markup never repriced as native)', () => {
diff --git a/test/native-base-url-fold.serial.test.ts b/test/native-base-url-fold.serial.test.ts
new file mode 100644
index 0000000000..fca8ac670d
--- /dev/null
+++ b/test/native-base-url-fold.serial.test.ts
@@ -0,0 +1,148 @@
+/**
+ * #3350 — file-plane provider_base_urls.{anthropic,openai} fold into the
+ * gateway env.
+ *
+ * Native providers read their base URL exclusively from env
+ * (`resolveNativeBaseUrl` on ANTHROPIC_BASE_URL / OPENAI_BASE_URL), so a
+ * config.json `provider_base_urls.anthropic` was silently ignored by native
+ * chat/embed calls. buildGatewayConfig now folds the FILE-plane values into
+ * the env (env wins), same shape as its credential folds.
+ *
+ * Mount safety (the gateway.ts reconfigure rationale): the fold reads the
+ * file plane directly — a DB-merged config passed INTO buildGatewayConfig
+ * must never contaminate the env, so DB-plane base_urls (mergeable from a
+ * shared brain) can never steer native bearer keys.
+ *
+ * Serial: mutates GBRAIN_HOME + process env + global gateway state.
+ */
+
+import { describe, test, expect, beforeEach, afterEach, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from '../src/core/ai/build-gateway-config.ts';
+import {
+ configureGateway,
+ resetGateway,
+ resolveNativeBaseUrl,
+ refreshGatewayEnvFromFilePlane,
+ requireConfig,
+} from '../src/core/ai/gateway.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+const PINNED = ['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'GBRAIN_HOME'] as const;
+let saved: Record<string, string | undefined>;
+let tmpHome: string;
+
+beforeEach(() => {
+ saved = {};
+ for (const k of PINNED) { saved[k] = process.env[k]; delete process.env[k]; }
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-baseurl-'));
+ process.env.GBRAIN_HOME = tmpHome;
+ resetGateway();
+});
+
+afterEach(() => {
+ rmSync(tmpHome, { recursive: true, force: true });
+ for (const k of PINNED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ resetGateway();
+});
+
+afterAll(() => {
+ // Shard hygiene: restore a plain gateway for later tests in this process.
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+});
+
+function writeFileConfig(cfg: Record<string, unknown>): void {
+ mkdirSync(join(tmpHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmpHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...cfg }));
+}
+
+describe('foldNativeBaseUrlsFromFilePlane (unit)', () => {
+ test('folds anthropic + openai from the file config when env has none', () => {
+ const env = foldNativeBaseUrlsFromFilePlane(
+ { provider_base_urls: { anthropic: 'https://proxy.example/anthropic', openai: 'https://proxy.example/openai' } },
+ {},
+ );
+ expect(env.ANTHROPIC_BASE_URL).toBe('https://proxy.example/anthropic');
+ expect(env.OPENAI_BASE_URL).toBe('https://proxy.example/openai');
+ });
+
+ test('env wins over the file plane', () => {
+ const env = foldNativeBaseUrlsFromFilePlane(
+ { provider_base_urls: { anthropic: 'https://file.example' } },
+ { ANTHROPIC_BASE_URL: 'https://env.example' },
+ );
+ expect(env.ANTHROPIC_BASE_URL).toBe('https://env.example');
+ });
+
+ test('blank env value is treated as unset (fold applies)', () => {
+ const env = foldNativeBaseUrlsFromFilePlane(
+ { provider_base_urls: { openai: 'https://file.example' } },
+ { OPENAI_BASE_URL: ' ' },
+ );
+ expect(env.OPENAI_BASE_URL).toBe('https://file.example');
+ });
+
+ test('non-native providers are ignored; null config is a no-op', () => {
+ const env1 = foldNativeBaseUrlsFromFilePlane(
+ { provider_base_urls: { ollama: 'http://localhost:11434' } },
+ {},
+ );
+ expect(env1.ANTHROPIC_BASE_URL).toBeUndefined();
+ expect(env1.OPENAI_BASE_URL).toBeUndefined();
+ const base = { OPENAI_API_KEY: 'sk-x' };
+ expect(foldNativeBaseUrlsFromFilePlane(null, base)).toEqual(base);
+ });
+});
+
+describe('buildGatewayConfig — file-plane fold (#3350)', () => {
+ test('config.json provider_base_urls.anthropic reaches the gateway env', () => {
+ writeFileConfig({ provider_base_urls: { anthropic: 'https://gw.example/anthropic' } });
+ const cfg = buildGatewayConfig({ engine: 'pglite' } as GBrainConfig);
+ expect(cfg.env.ANTHROPIC_BASE_URL).toBe('https://gw.example/anthropic');
+ // resolveNativeBaseUrl (env-only) sees it and normalizes /v1.
+ expect(resolveNativeBaseUrl('anthropic', cfg)).toBe('https://gw.example/anthropic/v1');
+ });
+
+ test('process env base URL wins over the file plane', () => {
+ writeFileConfig({ provider_base_urls: { openai: 'https://file.example' } });
+ process.env.OPENAI_BASE_URL = 'https://env-wins.example';
+ const cfg = buildGatewayConfig({ engine: 'pglite' } as GBrainConfig);
+ expect(cfg.env.OPENAI_BASE_URL).toBe('https://env-wins.example');
+ });
+
+ test('MOUNT SAFETY: base urls on the PASSED (possibly DB-merged) config never reach the env', () => {
+ // File plane has NO provider_base_urls; the passed config simulates a
+ // DB-merged one carrying a hostile base URL.
+ writeFileConfig({});
+ const cfg = buildGatewayConfig({
+ engine: 'pglite',
+ provider_base_urls: { anthropic: 'https://attacker.example' },
+ } as GBrainConfig);
+ expect(cfg.env.ANTHROPIC_BASE_URL).toBeUndefined();
+ // base_urls (compat-recipe routing) still carries it — unchanged behavior;
+ // only the NATIVE env fold is file-plane-gated.
+ expect(cfg.base_urls?.anthropic).toBe('https://attacker.example');
+ });
+});
+
+describe('refreshGatewayEnvFromFilePlane keeps the fold (#3350)', () => {
+ test('a worker env refresh re-applies the file-plane base URL', () => {
+ writeFileConfig({ provider_base_urls: { anthropic: 'https://gw.example/anthropic' } });
+ configureGateway(buildGatewayConfig({ engine: 'pglite' } as GBrainConfig));
+ expect(requireConfig().env.ANTHROPIC_BASE_URL).toBe('https://gw.example/anthropic');
+ // Simulate the worker's env-only refresh; pre-fix this dropped the fold
+ // (the refresh re-stamped env from mergedProviderEnv alone).
+ refreshGatewayEnvFromFilePlane();
+ expect(requireConfig().env.ANTHROPIC_BASE_URL).toBe('https://gw.example/anthropic');
+ expect(resolveNativeBaseUrl('anthropic', requireConfig())).toBe('https://gw.example/anthropic/v1');
+ });
+});
diff --git a/test/nudge.test.ts b/test/nudge.test.ts
index 2ba260c271..80721eb051 100644
--- a/test/nudge.test.ts
+++ b/test/nudge.test.ts
@@ -265,10 +265,14 @@ describe('evaluateAndFireNudge', () => {
// ─── buildNudgeText ─────────────────────────────────────────────────
describe('buildNudgeText', () => {
- test('contains the matched tag for hush command', () => {
+ test('contains the matched tag and the auto-quiet notice (no fake hush command, #3697)', () => {
const out = buildNudgeText({ matchedTag: 'over-confident-geography', conviction: 0.85 });
expect(out).toContain('over-confident-geography');
- expect(out).toContain('gbrain takes nudge --hush over-confident-geography');
+ // #3697: `gbrain takes nudge --hush` does not exist — the 14-day quiet
+ // period is automatic (take_nudge_log cooldown). The text must say that
+ // instead of advertising a subcommand that exits "Unknown subcommand".
+ expect(out).not.toContain('gbrain takes nudge --hush');
+ expect(out).toContain('auto-quiets');
});
test('contains the conviction value', () => {
diff --git a/test/ocr-run-budget.test.ts b/test/ocr-run-budget.test.ts
new file mode 100644
index 0000000000..fc0b9b465c
--- /dev/null
+++ b/test/ocr-run-budget.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #3973: per-run OCR ceiling in maybeOcr. An OCR-opted-in bulk import over a
+ * large image corpus was an unbounded per-image LLM spend; the gate caps it
+ * per process run via config embedding_image_ocr_max_images / _max_usd
+ * (finite defaults), skips OCR over-cap, and bumps the persistent
+ * `ocr_skipped_budget` counter that doctor's ocr_health check surfaces.
+ *
+ * Tests drive the gated body directly (_maybeOcrGatedForTests) so no env
+ * mutation is needed, and preset the run state so the over-cap paths never
+ * reach the gateway (deterministic offline). The under-cap path stubs the
+ * generateText transport so a key-carrying dev environment can't make a
+ * real call.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ _maybeOcrGatedForTests,
+ _resetOcrRunBudgetForTests,
+ _getOcrRunBudgetForTests,
+} from '../src/core/import-file.ts';
+import { __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+let engine: PGLiteEngine;
+const buf = Buffer.from('fake-image-bytes');
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ _resetOcrRunBudgetForTests();
+ __setGenerateTextTransportForTests(null);
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetOcrRunBudgetForTests();
+});
+
+describe('per-run OCR budget gate (#3973)', () => {
+ test('over the default image cap: skips OCR, bumps ocr_skipped_budget, never counts an attempt', async () => {
+ _resetOcrRunBudgetForTests({ images: 200 }); // default cap is 200
+ const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(out).toBe('');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');
+ expect(await engine.getConfig('ocr_attempted')).toBeFalsy();
+ // Skips don't consume budget.
+ expect(_getOcrRunBudgetForTests().images).toBe(200);
+ // Warned exactly once per run; a second skip stays quiet but still counts.
+ expect(_getOcrRunBudgetForTests().warned).toBe(true);
+ await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBe('2');
+ });
+
+ test('over the default estimated-USD cap trips independently of the image cap', async () => {
+ _resetOcrRunBudgetForTests({ images: 1, estUsd: 1.0 }); // default USD cap is 1.0
+ const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(out).toBe('');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');
+ expect(await engine.getConfig('ocr_attempted')).toBeFalsy();
+ });
+
+ test('config lowers the image cap below the default', async () => {
+ await engine.setConfig('embedding_image_ocr_max_images', '5');
+ _resetOcrRunBudgetForTests({ images: 5 });
+ const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(out).toBe('');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');
+ });
+
+ test('config lowers the USD cap below the default', async () => {
+ await engine.setConfig('embedding_image_ocr_max_usd', '0.01');
+ _resetOcrRunBudgetForTests({ images: 1, estUsd: 0.02 });
+ const out = await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(out).toBe('');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBe('1');
+ });
+
+ test('under the cap: the gate passes, consumes budget, and never bumps the skip counter', async () => {
+ // Stub the final generateText call so a dev machine with a real API key
+ // can't make a network call; keyless environments take the
+ // ocr_failed_no_key branch. Either way the GATE behavior is identical.
+ __setGenerateTextTransportForTests(async () => ({ text: 'stubbed ocr text', usage: {} }) as never);
+ try {
+ await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ const state = _getOcrRunBudgetForTests();
+ expect(state.images).toBe(1);
+ expect(state.estUsd).toBeGreaterThan(0);
+ expect(await engine.getConfig('ocr_skipped_budget')).toBeFalsy();
+ expect(await engine.getConfig('ocr_attempted')).toBe('1');
+ } finally {
+ __setGenerateTextTransportForTests(null);
+ }
+ });
+
+ test('cap of 0 disables that ceiling (explicit unlimited opt-out)', async () => {
+ await engine.setConfig('embedding_image_ocr_max_images', '0');
+ await engine.setConfig('embedding_image_ocr_max_usd', '0');
+ _resetOcrRunBudgetForTests({ images: 100_000, estUsd: 500 });
+ __setGenerateTextTransportForTests(async () => ({ text: 'stubbed', usage: {} }) as never);
+ try {
+ await _maybeOcrGatedForTests(engine, buf, 'image/png');
+ expect(await engine.getConfig('ocr_skipped_budget')).toBeFalsy();
+ expect(_getOcrRunBudgetForTests().images).toBe(100_001);
+ } finally {
+ __setGenerateTextTransportForTests(null);
+ }
+ });
+});
+
+describe('doctor ocr_health surfaces the budget-skip counter (#3973)', () => {
+ test('doctor source reads ocr_skipped_budget and names the raise-cap fix', async () => {
+ const { doctorSource } = await import('./helpers/doctor-source.ts');
+ const src = doctorSource();
+ expect(src).toContain("ocr_skipped_budget");
+ expect(src).toContain('embedding_image_ocr_max_images');
+ expect(src).toContain('embedding_image_ocr_max_usd');
+ });
+});
diff --git a/test/ops-search-types.test.ts b/test/ops-search-types.test.ts
new file mode 100644
index 0000000000..80de8fd612
--- /dev/null
+++ b/test/ops-search-types.test.ts
@@ -0,0 +1,117 @@
+/**
+ * #3985 — expose `types?: string[]` on the public search + query ops.
+ *
+ * The SQL-level plumbing (SearchOpts.types → both engines' keyword / title /
+ * vector legs) has existed since v0.33 for whoknows; pre-fix the search and
+ * query ops simply never accepted the param, so MCP/CLI callers could not
+ * type-scope retrieval. Pins: param reaches the engine on both ops, CLI
+ * comma-string form works, junk is rejected as invalid_params.
+ */
+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';
+import type { SearchResult } from '../src/core/types.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const searchOp = operations.find((o) => o.name === 'search')!;
+const queryOp = operations.find((o) => o.name === 'query')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as never,
+ config: {} as never,
+ logger: console as never,
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ ...overrides,
+ } as OperationContext;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const pages: Array<[slug: string, type: string]> = [
+ ['people/alice-example', 'person'],
+ ['companies/acme-example', 'company'],
+ ['notes/telescope-note', 'note'],
+ ];
+ for (const [slug, type] of pages) {
+ await engine.putPage(slug, {
+ type,
+ title: `Zebra telescope ${type}`,
+ compiled_truth: `the zebra telescope appears in this ${type} page`,
+ frontmatter: {},
+ });
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: `the zebra telescope appears in this ${type} page`, chunk_source: 'compiled_truth' },
+ ]);
+ }
+ // Keyword-only path for the search op: no embedding provider needed.
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+function slugsOf(results: unknown): string[] {
+ return (results as SearchResult[]).map((r) => r.slug).sort();
+}
+
+describe('search op — types param (#3985)', () => {
+ test('no types → all matching pages (baseline)', async () => {
+ const out = await searchOp.handler(ctxOf(), { query: 'zebra telescope' });
+ expect(slugsOf(out)).toEqual(['companies/acme-example', 'notes/telescope-note', 'people/alice-example']);
+ });
+
+ test('types array filters at SQL level', async () => {
+ const out = await searchOp.handler(ctxOf(), { query: 'zebra telescope', types: ['person'] });
+ expect(slugsOf(out)).toEqual(['people/alice-example']);
+ });
+
+ test('CLI comma-string form works (--types person,company)', async () => {
+ const out = await searchOp.handler(ctxOf(), { query: 'zebra telescope', types: 'person,company' });
+ expect(slugsOf(out)).toEqual(['companies/acme-example', 'people/alice-example']);
+ });
+
+ test('non-string entries reject loudly as invalid_params', async () => {
+ await expect(
+ searchOp.handler(ctxOf(), { query: 'zebra telescope', types: [42] }),
+ ).rejects.toThrow(/types.*must be an array/i);
+ });
+
+ test('all-empty list rejects loudly instead of silently dropping the filter', async () => {
+ await expect(
+ searchOp.handler(ctxOf(), { query: 'zebra telescope', types: ' , ' }),
+ ).rejects.toThrow(/no usable page-type/i);
+ });
+});
+
+describe('query op — types param (#3985)', () => {
+ test('types filter applies on the no-provider hybrid path', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ const out = await queryOp.handler(ctxOf(), {
+ query: 'zebra telescope',
+ expand: false,
+ types: ['company'],
+ });
+ expect(slugsOf(out)).toEqual(['companies/acme-example']);
+ });
+ });
+
+ test('query without types keeps full recall', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ const out = await queryOp.handler(ctxOf(), { query: 'zebra telescope', expand: false });
+ expect(slugsOf(out)).toEqual(['companies/acme-example', 'notes/telescope-note', 'people/alice-example']);
+ });
+ });
+
+ test('junk types reject before any retrieval work', async () => {
+ await expect(
+ queryOp.handler(ctxOf(), { query: 'zebra telescope', types: { person: true } }),
+ ).rejects.toThrow(/types.*must be an array/i);
+ });
+});
diff --git a/test/page-summary-length.serial.test.ts b/test/page-summary-length.serial.test.ts
new file mode 100644
index 0000000000..c04bcc097a
--- /dev/null
+++ b/test/page-summary-length.serial.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #3883: generatePerChunkSynopsis must classify stopReason==='length' as
+ * 'malformed' (page-level fall-back + audit) instead of embedding truncated
+ * text, and the output-token cap must be overridable per call (threaded from
+ * models.synopsis_max_tokens by the service layer).
+ *
+ * Serial: installs the process-global chat transport stub and redirects the
+ * audit dir.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {
+ generatePerChunkSynopsis,
+ SYNOPSIS_MAX_TOKENS,
+} from '../src/core/page-summary.ts';
+import { __setChatTransportForTests, type ChatOpts } from '../src/core/ai/gateway.ts';
+import { readRecentSynopsisFailures } from '../src/core/audit-synopsis.ts';
+
+let tmpDir: string;
+const originalAuditDir = process.env.GBRAIN_AUDIT_DIR;
+
+function stubChat(overrides: { text?: string; stopReason?: 'end' | 'length' | 'refusal' }, capture?: ChatOpts[]) {
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ capture?.push(opts);
+ return {
+ text: overrides.text ?? 'A one-sentence synopsis about the chunk.',
+ blocks: [],
+ stopReason: overrides.stopReason ?? 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:stub',
+ providerId: 'anthropic',
+ };
+ });
+}
+
+const baseArgs = {
+ documentText: 'Full document text about acme-example fundraising.',
+ chunkText: 'The chunk text about the series A.',
+ pageTitle: 'Acme Example',
+ pageSlug: 'companies/acme-example',
+ sourceId: 'default',
+ chunkIndex: 0,
+};
+
+beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-synopsis-length-test-'));
+ process.env.GBRAIN_AUDIT_DIR = tmpDir;
+});
+
+afterAll(() => {
+ __setChatTransportForTests(null);
+ if (originalAuditDir === undefined) delete process.env.GBRAIN_AUDIT_DIR;
+ else process.env.GBRAIN_AUDIT_DIR = originalAuditDir;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+beforeEach(() => {
+ for (const f of fs.readdirSync(tmpDir)) fs.unlinkSync(path.join(tmpDir, f));
+});
+
+describe('stopReason length → malformed (#3883)', () => {
+ test('a truncated (length-stopped) response never becomes a synopsis', async () => {
+ stubChat({ text: 'This synopsis got cut off mid-sen', stopReason: 'length' });
+ const result = await generatePerChunkSynopsis(baseArgs);
+ expect(result.kind).toBe('malformed');
+ expect((result as { detail?: string }).detail).toContain('stop_reason=length');
+ expect((result as { detail?: string }).detail).toContain('models.synopsis_max_tokens');
+ // Never leaks the truncated text as a success payload.
+ expect('synopsis' in result).toBe(false);
+ });
+
+ test('the length failure lands in the synopsis audit trail with page-level fallback', async () => {
+ stubChat({ text: 'Truncated fragm', stopReason: 'length' });
+ await generatePerChunkSynopsis(baseArgs);
+ const events = readRecentSynopsisFailures(10);
+ expect(events.length).toBe(1);
+ expect(events[0].kind).toBe('malformed');
+ expect(events[0].page_level_fallback).toBe(true);
+ expect(events[0].page_slug).toBe('companies/acme-example');
+ });
+
+ test('a clean end-stop still succeeds', async () => {
+ stubChat({ stopReason: 'end' });
+ const result = await generatePerChunkSynopsis(baseArgs);
+ expect(result.kind).toBe('success');
+ });
+});
+
+describe('maxTokens threading (#3883)', () => {
+ test('default cap is SYNOPSIS_MAX_TOKENS when the arg is omitted', async () => {
+ const captured: ChatOpts[] = [];
+ stubChat({ stopReason: 'end' }, captured);
+ await generatePerChunkSynopsis(baseArgs);
+ expect(captured[0].maxTokens).toBe(SYNOPSIS_MAX_TOKENS);
+ });
+
+ test('explicit maxTokens arg reaches the chat call and the length detail', async () => {
+ const captured: ChatOpts[] = [];
+ stubChat({ stopReason: 'length' }, captured);
+ const result = await generatePerChunkSynopsis({ ...baseArgs, maxTokens: 512 });
+ expect(captured[0].maxTokens).toBe(512);
+ expect((result as { detail?: string }).detail).toContain('maxTokens=512');
+ });
+});
+
+describe('resolveSynopsisMaxTokens config resolver (#3883)', () => {
+ test('reads models.synopsis_max_tokens, clamps junk to undefined', async () => {
+ const { resolveSynopsisMaxTokens } = await import('../src/core/contextual-retrieval-service.ts');
+ const mkEngine = (val: string | null) =>
+ ({ getConfig: async () => val }) as unknown as import('../src/core/engine.ts').BrainEngine;
+ expect(await resolveSynopsisMaxTokens(mkEngine('400'))).toBe(400);
+ expect(await resolveSynopsisMaxTokens(mkEngine(null))).toBeUndefined();
+ expect(await resolveSynopsisMaxTokens(mkEngine(''))).toBeUndefined();
+ expect(await resolveSynopsisMaxTokens(mkEngine('not-a-number'))).toBeUndefined();
+ expect(await resolveSynopsisMaxTokens(mkEngine('4'))).toBeUndefined(); // below floor
+ expect(await resolveSynopsisMaxTokens(mkEngine('99999'))).toBeUndefined(); // above ceiling
+ const throwing = ({ getConfig: async () => { throw new Error('db down'); } }) as unknown as import('../src/core/engine.ts').BrainEngine;
+ expect(await resolveSynopsisMaxTokens(throwing)).toBeUndefined(); // fail-open
+ });
+});
diff --git a/test/pages-upsert-arbiter.test.ts b/test/pages-upsert-arbiter.test.ts
new file mode 100644
index 0000000000..d96afc1a82
--- /dev/null
+++ b/test/pages-upsert-arbiter.test.ts
@@ -0,0 +1,169 @@
+/**
+ * #550 — pages(source_id, slug) unique-arbiter self-heal.
+ *
+ * Repro chain pinned here: DROP the pages_source_slug_key constraint →
+ * putPage fails with "no unique or exclusion constraint" and re-initSchema
+ * does NOT restore it (version counter is already stamped past v21/v23).
+ * The arbiter module detects the drift by index SHAPE and repairs ADD-only;
+ * runMigrations self-heals on every pass; doctor fails loudly.
+ */
+
+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 {
+ checkPagesUpsertArbiter,
+ repairPagesUpsertArbiter,
+} from '../src/core/pages-upsert-arbiter.ts';
+import { runMigrations } from '../src/core/migrate.ts';
+import { pagesUpsertArbiterCheck } from '../src/commands/doctor/checks/core-health.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ // Restore the arbiter in case a prior test dropped it.
+ await repairPagesUpsertArbiter(engine);
+});
+
+async function putProbePage(slug: string): Promise<void> {
+ await engine.putPage(slug, {
+ title: slug,
+ type: 'concept',
+ frontmatter: {},
+ compiled_truth: `body for ${slug}`,
+ timeline: '',
+ });
+}
+
+async function dropArbiter(): Promise<void> {
+ await engine.executeRaw(`ALTER TABLE pages DROP CONSTRAINT IF EXISTS pages_source_slug_key`);
+}
+
+describe('checkPagesUpsertArbiter (#550)', () => {
+ test('healthy brain: arbiter present, no repair needed', async () => {
+ const s = await checkPagesUpsertArbiter(engine);
+ expect(s.tablePresent).toBe(true);
+ expect(s.arbiterPresent).toBe(true);
+ expect(s.needsRepair).toBe(false);
+ });
+
+ test('dropped constraint: putPage fails and check flags needsRepair', async () => {
+ await putProbePage('probe/before-drop');
+ await dropArbiter();
+ await expect(putProbePage('probe/after-drop')).rejects.toThrow(/no unique or exclusion constraint/);
+ const s = await checkPagesUpsertArbiter(engine);
+ expect(s.needsRepair).toBe(true);
+ expect(s.duplicateGroups).toBe(0);
+ });
+
+ test('by-shape: a differently-named non-partial unique index counts as the arbiter', async () => {
+ await dropArbiter();
+ await engine.executeRaw(
+ `CREATE UNIQUE INDEX pages_custom_arbiter ON pages(slug, source_id)`,
+ );
+ const s = await checkPagesUpsertArbiter(engine);
+ expect(s.arbiterPresent).toBe(true);
+ expect(s.needsRepair).toBe(false);
+ await engine.executeRaw(`DROP INDEX pages_custom_arbiter`);
+ });
+
+ test('by-shape: a PARTIAL unique index does NOT count (cannot arbitrate)', async () => {
+ await dropArbiter();
+ await engine.executeRaw(
+ `CREATE UNIQUE INDEX pages_partial_nope ON pages(source_id, slug) WHERE deleted_at IS NULL`,
+ );
+ const s = await checkPagesUpsertArbiter(engine);
+ expect(s.needsRepair).toBe(true);
+ await engine.executeRaw(`DROP INDEX pages_partial_nope`);
+ });
+});
+
+describe('repairPagesUpsertArbiter (#550)', () => {
+ test('drop -> putPage fails -> repair -> putPage works again', async () => {
+ await dropArbiter();
+ await expect(putProbePage('probe/broken')).rejects.toThrow(/no unique or exclusion constraint/);
+
+ const r = await repairPagesUpsertArbiter(engine);
+ expect(r.repaired).toBe(true);
+ expect(r.reason).toBe('restored');
+
+ await putProbePage('probe/healed');
+ // Upsert (same slug twice) exercises the restored ON CONFLICT arbiter.
+ await putProbePage('probe/healed');
+ const page = await engine.getPage('probe/healed', { sourceId: 'default' });
+ expect(page).toBeTruthy();
+ });
+
+ test('no-op on a healthy brain', async () => {
+ const r = await repairPagesUpsertArbiter(engine);
+ expect(r.repaired).toBe(false);
+ expect(r.reason).toBe('already_correct');
+ });
+
+ test('refuses when duplicate (source_id, slug) rows exist — never deletes rows', async () => {
+ await putProbePage('probe/dup');
+ await dropArbiter();
+ // Sneak a duplicate in through the unprotected window.
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, title, type, frontmatter, compiled_truth, timeline)
+ SELECT slug, source_id, title, type, frontmatter, compiled_truth, timeline
+ FROM pages WHERE slug = 'probe/dup'`,
+ );
+ const r = await repairPagesUpsertArbiter(engine);
+ expect(r.repaired).toBe(false);
+ expect(r.reason).toBe('duplicates');
+ expect(r.duplicateGroups).toBe(1);
+ // Both duplicate rows survive — the repair never deletes.
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM pages WHERE slug = 'probe/dup'`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(2);
+ // Clean up the duplicate so the beforeEach repair succeeds for later tests.
+ await engine.executeRaw(
+ `DELETE FROM pages WHERE id = (SELECT MAX(id) FROM pages WHERE slug = 'probe/dup')`,
+ );
+ });
+});
+
+describe('runMigrations self-heal (#550)', () => {
+ test('a fully-migrated brain with a dropped arbiter heals on the next migrate pass', async () => {
+ // Stamp the version counter to fully-migrated first (resetPgliteState
+ // clears config): the drift must heal on a NO-PENDING pass.
+ await runMigrations(engine);
+ await dropArbiter();
+ await expect(putProbePage('probe/premigrate')).rejects.toThrow(/no unique or exclusion constraint/);
+
+ const out = await runMigrations(engine);
+ expect(out.applied).toBe(0); // nothing pending — the self-heal ran anyway
+
+ await putProbePage('probe/postmigrate');
+ const page = await engine.getPage('probe/postmigrate', { sourceId: 'default' });
+ expect(page).toBeTruthy();
+ });
+});
+
+describe('doctor pages_upsert_arbiter check (#550)', () => {
+ test('ok on a healthy brain', async () => {
+ const check = await pagesUpsertArbiterCheck(engine);
+ expect(check.status).toBe('ok');
+ });
+
+ test('fail with actionable message when the arbiter is missing', async () => {
+ await dropArbiter();
+ const check = await pagesUpsertArbiterCheck(engine);
+ expect(check.status).toBe('fail');
+ expect(check.message).toContain('UNIQUE(source_id, slug)');
+ expect(check.message).toContain('apply-migrations');
+ });
+});
diff --git a/test/pid1-reaper.test.ts b/test/pid1-reaper.test.ts
new file mode 100644
index 0000000000..defb3353f2
--- /dev/null
+++ b/test/pid1-reaper.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #2443 — PID-1 orphan zombie reaper.
+ *
+ * serve-as-PID-1 (container without tini/--init) inherits orphaned
+ * grandchildren; the zombie-reap.ts SIGCHLD handler only reaps Bun-TRACKED
+ * children, so orphan zombies accumulated forever. These tests drive the
+ * reaper against a fixture procDir + injected waitpid — no real /proc, no
+ * libc, fully deterministic on any platform.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import {
+ scanZombieChildren,
+ createPid1ReaperTick,
+ installPid1OrphanReaper,
+ _uninstallPid1OrphanReaperForTests,
+} from '../src/core/pid1-reaper.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ _uninstallPid1OrphanReaperForTests();
+ for (const fn of cleanups.splice(0)) fn();
+});
+
+/** Build a fixture procDir: { pid: statLine } (plus junk entries). */
+function makeProcDir(entries: Record<string, string>): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-pid1-'));
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
+ for (const [pid, stat] of Object.entries(entries)) {
+ mkdirSync(join(dir, pid));
+ writeFileSync(join(dir, pid, 'stat'), stat);
+ }
+ // non-numeric entries must be skipped
+ mkdirSync(join(dir, 'sys'));
+ writeFileSync(join(dir, 'uptime'), '12345.67 89.0');
+ return dir;
+}
+
+const stat = (pid: number, comm: string, state: string, ppid: number) =>
+ `${pid} (${comm}) ${state} ${ppid} ${ppid} 0 0 -1 4194560 0 0 0 0 0 0 0 0 0 20 0 1 0 100 0 0`;
+
+describe('scanZombieChildren', () => {
+ test('finds only Z-state children of self', () => {
+ const dir = makeProcDir({
+ '1': stat(1, 'gbrain', 'S', 0),
+ '42': stat(42, 'dead-worker', 'Z', 1), // zombie child of pid 1 ✓
+ '43': stat(43, 'live-worker', 'S', 1), // alive
+ '44': stat(44, 'other-zombie', 'Z', 99), // zombie of someone else
+ });
+ expect(scanZombieChildren(dir, 1)).toEqual([42]);
+ });
+
+ test('comm with spaces and parens parses (fields after LAST close paren)', () => {
+ const dir = makeProcDir({
+ '55': `55 (weird) name (x)) Z 1 1 0 0 -1 0 0 0 0 0 0 0 0 0 0 20 0 1 0 1 0 0`,
+ });
+ expect(scanZombieChildren(dir, 1)).toEqual([55]);
+ });
+
+ test('missing procDir / unreadable entries fail open to []', () => {
+ expect(scanZombieChildren('/nonexistent-proc-xyz', 1)).toEqual([]);
+ });
+});
+
+describe('createPid1ReaperTick — 2-scan persistence', () => {
+ test('reaps only zombies that persist across two consecutive scans', () => {
+ const dir = makeProcDir({ '42': stat(42, 'w', 'Z', 1) });
+ const reapedPids: number[] = [];
+ const tick = createPid1ReaperTick({ procDir: dir, selfPid: 1, waitpid: (p) => reapedPids.push(p) });
+
+ expect(tick()).toBe(0); // first sighting — never steal a Bun-tracked exit
+ expect(reapedPids).toEqual([]);
+ expect(tick()).toBe(1); // persisted → reap
+ expect(reapedPids).toEqual([42]);
+ });
+
+ test('a zombie that disappears between scans is never reaped', () => {
+ const dir = makeProcDir({ '42': stat(42, 'w', 'Z', 1) });
+ const reapedPids: number[] = [];
+ const tick = createPid1ReaperTick({ procDir: dir, selfPid: 1, waitpid: (p) => reapedPids.push(p) });
+ expect(tick()).toBe(0);
+ rmSync(join(dir, '42'), { recursive: true, force: true }); // runtime reaped it
+ expect(tick()).toBe(0);
+ expect(reapedPids).toEqual([]);
+ });
+
+ test('a new zombie appearing on scan 2 waits for scan 3', () => {
+ const dir = makeProcDir({ '42': stat(42, 'w', 'Z', 1) });
+ const reapedPids: number[] = [];
+ const tick = createPid1ReaperTick({ procDir: dir, selfPid: 1, waitpid: (p) => reapedPids.push(p) });
+ tick(); // 42 pending
+ mkdirSync(join(dir, '77'));
+ writeFileSync(join(dir, '77', 'stat'), stat(77, 'late', 'Z', 1));
+ expect(tick()).toBe(1); // 42 reaped, 77 pending
+ expect(reapedPids).toEqual([42]);
+ rmSync(join(dir, '42'), { recursive: true, force: true });
+ expect(tick()).toBe(1); // 77 reaped
+ expect(reapedPids).toEqual([42, 77]);
+ });
+
+ test('a throwing waitpid is contained (fail-open)', () => {
+ const dir = makeProcDir({ '42': stat(42, 'w', 'Z', 1) });
+ const tick = createPid1ReaperTick({
+ procDir: dir, selfPid: 1,
+ waitpid: () => { throw new Error('EPERM'); },
+ });
+ tick();
+ expect(() => tick()).not.toThrow();
+ });
+});
+
+describe('installPid1OrphanReaper — gates', () => {
+ test('non-linux platform → not installed', () => {
+ expect(installPid1OrphanReaper({ platform: 'darwin', selfPid: 1 })).toBe(false);
+ });
+
+ test('linux but not PID 1 → not installed', () => {
+ expect(installPid1OrphanReaper({ platform: 'linux', selfPid: 4242 })).toBe(false);
+ });
+
+ test('GBRAIN_PID1_REAP=0 off-switch wins', async () => {
+ await withEnv({ GBRAIN_PID1_REAP: '0' }, () => {
+ expect(installPid1OrphanReaper({ platform: 'linux', selfPid: 1 })).toBe(false);
+ });
+ });
+
+ test('linux + pid 1 → installs, ticks on the interval, idempotent', async () => {
+ const dir = makeProcDir({ '42': stat(42, 'w', 'Z', 1) });
+ const reapedPids: number[] = [];
+ const ok = installPid1OrphanReaper({
+ platform: 'linux', selfPid: 1, procDir: dir, intervalMs: 15,
+ waitpid: (p) => reapedPids.push(p),
+ });
+ expect(ok).toBe(true);
+ // second install is a no-op true (no duplicate timers)
+ expect(installPid1OrphanReaper({ platform: 'linux', selfPid: 1, procDir: dir, intervalMs: 15 })).toBe(true);
+ // two ticks: scan 1 marks pending, scan 2 reaps
+ await Bun.sleep(120);
+ expect(reapedPids).toContain(42);
+ });
+});
diff --git a/test/private-queue-schema-parity.test.ts b/test/private-queue-schema-parity.test.ts
index 13964204d3..3c79a7ee11 100644
--- a/test/private-queue-schema-parity.test.ts
+++ b/test/private-queue-schema-parity.test.ts
@@ -4,7 +4,7 @@
* Three schema blobs must carry the dream-inline private-queue lifecycle
* surface in lockstep:
* - src/schema.sql (authoring source; build:schema input)
- * - src/core/schema-embedded.ts (generated Postgres blob)
+ * - src/core/schema-embedded.generated.ts (generated Postgres blob)
* - src/core/pglite-schema.ts (PGLite blob)
*
* A blob missing the columns re-introduces the v121 wedge class (its own
@@ -26,7 +26,7 @@ import { resolve as resolvePath } from 'path';
const BLOBS = [
'src/schema.sql',
- 'src/core/schema-embedded.ts',
+ 'src/core/schema-embedded.generated.ts',
'src/core/pglite-schema.ts',
] as const;
diff --git a/test/private-visibility.test.ts b/test/private-visibility.test.ts
new file mode 100644
index 0000000000..addfedd90f
--- /dev/null
+++ b/test/private-visibility.test.ts
@@ -0,0 +1,400 @@
+/**
+ * #4352 — page-level `visibility: private` enforcement for untrusted callers.
+ *
+ * Pages have persisted `frontmatter.visibility` forever, but no read path
+ * enforced it: a remote/MCP caller could pull a private page through search,
+ * recall's query arm, entity cards, and context_pack. Pins:
+ * - buildVisibilityClause emits the predicate only when excludePrivate
+ * - engines (PGLite here; SQL identical in postgres-engine — parity pinned
+ * by the shared buildVisibilityClause builder) filter private pages on
+ * searchKeyword / searchTitles / searchKeywordChunks when the flag is set
+ * - resolveExcludePrivatePages: trust rules + config gate + env hatch
+ * - recall (query arm) as a remote ctx hides private pages; local sees them
+ * - buildEntityCard (entity/context_pack/delta) hides private cards remotely
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { buildVisibilityClause } from '../src/core/search/sql-ranking.ts';
+import {
+ resolveExcludePrivatePages,
+ __resetPrivateVisibilityCacheForTests,
+ REMOTE_PRIVATE_PAGES_KEY,
+} from '../src/core/search/private-visibility.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.putPage('notes/world-page', {
+ title: 'Zebra Widget World',
+ type: 'concept',
+ frontmatter: { visibility: 'world' },
+ compiled_truth: 'zebra widget public knowledge body',
+ timeline: '',
+ });
+ await engine.putPage('notes/private-page', {
+ title: 'Zebra Widget Private',
+ type: 'concept',
+ frontmatter: { visibility: 'private' },
+ compiled_truth: 'zebra widget secret private knowledge body',
+ timeline: '',
+ });
+ // No visibility key at all → defaults to world (visible everywhere).
+ await engine.putPage('notes/unmarked-page', {
+ title: 'Zebra Widget Unmarked',
+ type: 'concept',
+ frontmatter: {},
+ compiled_truth: 'zebra widget unmarked knowledge body',
+ timeline: '',
+ });
+ // putPage doesn't chunk; the keyword/chunk arms search content_chunks.
+ for (const [slug, body] of [
+ ['notes/world-page', 'zebra widget public knowledge body'],
+ ['notes/private-page', 'zebra widget secret private knowledge body'],
+ ['notes/unmarked-page', 'zebra widget unmarked knowledge body'],
+ ] as const) {
+ await engine.upsertChunks(slug, [
+ { chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' },
+ ]);
+ }
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('buildVisibilityClause (#4352)', () => {
+ test('default: no private predicate (pre-fix SQL preserved byte-for-byte)', () => {
+ const clause = buildVisibilityClause('p', 's');
+ expect(clause).not.toContain('visibility');
+ expect(clause).toContain('p.deleted_at IS NULL');
+ });
+
+ test('excludePrivate: adds the COALESCE predicate', () => {
+ const clause = buildVisibilityClause('p', 's', { excludePrivate: true });
+ expect(clause).toContain(`COALESCE(p.frontmatter->>'visibility', 'world') <> 'private'`);
+ });
+});
+
+describe('engine search paths honor excludePrivate (#4352)', () => {
+ for (const method of ['searchKeyword', 'searchTitles', 'searchKeywordChunks'] as const) {
+ test(`${method}: private page hidden with flag, visible without`, async () => {
+ const withFlag = await engine[method]('zebra widget', { limit: 20, excludePrivate: true });
+ const withoutFlag = await engine[method]('zebra widget', { limit: 20 });
+ const slugsWith = withFlag.map((r) => r.slug);
+ const slugsWithout = withoutFlag.map((r) => r.slug);
+ expect(slugsWith).not.toContain('notes/private-page');
+ expect(slugsWith).toContain('notes/world-page');
+ // Absent visibility defaults to world — still visible under the flag.
+ expect(slugsWith).toContain('notes/unmarked-page');
+ // Trusted path unchanged: private page still retrievable.
+ expect(slugsWithout).toContain('notes/private-page');
+ });
+ }
+});
+
+describe('resolveExcludePrivatePages gate (#4352)', () => {
+ test('trusted local (remote === false) never excludes', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ expect(await resolveExcludePrivatePages(engine, false)).toBe(false);
+ });
+
+ test('remote/undefined excludes by default (fail-closed)', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ expect(await resolveExcludePrivatePages(engine, true)).toBe(true);
+ expect(await resolveExcludePrivatePages(engine, undefined)).toBe(true);
+ });
+
+ test('config opt-out disables enforcement', async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ expect(await resolveExcludePrivatePages(engine, true)).toBe(false);
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, '');
+ __resetPrivateVisibilityCacheForTests();
+ expect(await resolveExcludePrivatePages(engine, true)).toBe(true);
+ });
+
+ test('GBRAIN_REMOTE_PRIVATE_PAGES=1 env escape hatch disables enforcement', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {
+ expect(await resolveExcludePrivatePages(engine, true)).toBe(false);
+ });
+ });
+});
+
+describe('recall query arm (#4352)', () => {
+ function mkCtx(remote: boolean) {
+ return {
+ engine,
+ config: { engine: 'pglite' },
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote,
+ sourceId: 'default',
+ } as never;
+ }
+
+ test('remote recall with query hides private pages; local sees them', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['recall'];
+ // Test env strips provider keys → keyword-only search arm.
+ const remoteOut = (await op.handler(mkCtx(true), { query: 'zebra widget' })) as {
+ results: Array<{ slug: string }>;
+ };
+ const remoteSlugs = (remoteOut.results ?? []).map((r) => r.slug);
+ expect(remoteSlugs).not.toContain('notes/private-page');
+ expect(remoteSlugs).toContain('notes/world-page');
+
+ const localOut = (await op.handler(mkCtx(false), { query: 'zebra widget' })) as {
+ results: Array<{ slug: string }>;
+ };
+ const localSlugs = (localOut.results ?? []).map((r) => r.slug);
+ expect(localSlugs).toContain('notes/private-page');
+ });
+});
+
+describe('entity card (#4352 — covers entity/context_pack/delta)', () => {
+ test('remote card lookup cannot resolve a private page', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const remoteRes = await buildEntityCard(engine, 'default', 'Zebra Widget Private', { remote: true });
+ expect(remoteRes.found ? remoteRes.card?.entity.slug : null).not.toBe('notes/private-page');
+
+ const localRes = await buildEntityCard(engine, 'default', 'Zebra Widget Private', { remote: false });
+ expect(localRes.found).toBe(true);
+ expect(localRes.card?.entity.slug).toBe('notes/private-page');
+ });
+});
+
+describe('page read ops (#4352 remediation — list_pages / get_page / fetch)', () => {
+ function mkCtx(remote: boolean) {
+ return {
+ engine,
+ config: { engine: 'pglite' },
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote,
+ sourceId: 'default',
+ } as never;
+ }
+
+ test('list_pages: remote listing omits private pages; local enumerates them', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['list_pages'];
+ const remoteRows = (await op.handler(mkCtx(true), { limit: 100 })) as Array<{ slug: string }>;
+ const remoteSlugs = remoteRows.map((r) => r.slug);
+ expect(remoteSlugs).not.toContain('notes/private-page');
+ expect(remoteSlugs).toContain('notes/world-page');
+ // Absent visibility defaults to world — still listed remotely.
+ expect(remoteSlugs).toContain('notes/unmarked-page');
+
+ const localRows = (await op.handler(mkCtx(false), { limit: 100 })) as Array<{ slug: string }>;
+ expect(localRows.map((r) => r.slug)).toContain('notes/private-page');
+ });
+
+ test('get_page: remote read of a private page is page_not_found; local reads the body', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_page'];
+ await expect(op.handler(mkCtx(true), { slug: 'notes/private-page' })).rejects.toThrow(/Page not found/);
+ // No over-blocking: world pages stay readable remotely.
+ const world = (await op.handler(mkCtx(true), { slug: 'notes/world-page' })) as { slug: string };
+ expect(world.slug).toBe('notes/world-page');
+
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as { compiled_truth: string };
+ expect(local.compiled_truth).toContain('secret');
+ });
+
+ test('get_page fuzzy: remote fuzzy resolution cannot surface a private page; local can', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_page'];
+ await expect(
+ op.handler(mkCtx(true), { slug: 'notes/private-pag', fuzzy: true }),
+ ).rejects.toThrow(/Page not found/);
+
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/private-pag', fuzzy: true })) as { slug: string };
+ expect(local.slug).toBe('notes/private-page');
+ });
+
+ test('fetch: remote fetch of a private page is page_not_found; local returns full text', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['fetch'];
+ await expect(op.handler(mkCtx(true), { id: 'notes/private-page' })).rejects.toThrow(/Page not found/);
+
+ const local = (await op.handler(mkCtx(false), { id: 'notes/private-page' })) as { text: string };
+ expect(local.text).toContain('secret');
+ });
+
+ test('config opt-out restores remote reads on all three ops', async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ try {
+ const got = (await operationsByName['get_page'].handler(mkCtx(true), { slug: 'notes/private-page' })) as { slug: string };
+ expect(got.slug).toBe('notes/private-page');
+ const rows = (await operationsByName['list_pages'].handler(mkCtx(true), { limit: 100 })) as Array<{ slug: string }>;
+ expect(rows.map((r) => r.slug)).toContain('notes/private-page');
+ const fetched = (await operationsByName['fetch'].handler(mkCtx(true), { id: 'notes/private-page' })) as { id: string };
+ expect(fetched.id).toBe('notes/private-page');
+ } finally {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, '');
+ __resetPrivateVisibilityCacheForTests();
+ }
+ });
+});
+
+describe('sibling read ops (#4352 remediation — no bypass around get_page)', () => {
+ function mkCtx(remote: boolean) {
+ return {
+ engine,
+ config: { engine: 'pglite' },
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote,
+ sourceId: 'default',
+ } as never;
+ }
+
+ beforeAll(async () => {
+ // Edges in both directions so get_links / get_backlinks / traverse_graph
+ // each have a private endpoint to leak.
+ await engine.addLink('notes/world-page', 'notes/private-page', 'seen with', 'related_to');
+ await engine.addLink('notes/private-page', 'notes/world-page', 'refers to', 'related_to');
+ await engine.addLink('notes/world-page', 'notes/unmarked-page', 'also', 'related_to');
+ await engine.addTimelineEntry('notes/private-page', {
+ date: '2026-08-01', source: 'test', summary: 'secret meeting happened',
+ });
+ await engine.createVersion('notes/private-page');
+ await engine.putRawData('notes/private-page', 'crustdata', { secret: true });
+ });
+
+ test('get_chunks: private page reads as missing ([]) remotely; local + world unaffected', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_chunks'];
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ expect(((await op.handler(mkCtx(true), { slug: 'notes/world-page' })) as unknown[]).length).toBeGreaterThan(0);
+ expect(((await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as unknown[]).length).toBeGreaterThan(0);
+ });
+
+ test('get_versions: private page history reads as missing ([]) remotely; local sees it', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_versions'];
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ expect(((await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as unknown[]).length).toBeGreaterThan(0);
+ });
+
+ test('get_timeline: private page timeline reads as missing ([]) remotely; local sees it', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_timeline'];
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as Array<{ summary: string }>;
+ expect(local.map((e) => e.summary)).toContain('secret meeting happened');
+ });
+
+ test('get_raw_data: private page raw data reads as missing ([]) remotely; local sees it', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_raw_data'];
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ expect(((await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as unknown[]).length).toBeGreaterThan(0);
+ });
+
+ test('resolve_slugs: remote resolution never returns a private slug; local does', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['resolve_slugs'];
+ // Exact-slug arm: the strongest oracle — must read as no-match remotely.
+ expect((await op.handler(mkCtx(true), { partial: 'notes/private-page' })) as string[]).toEqual([]);
+ expect((await op.handler(mkCtx(false), { partial: 'notes/private-page' })) as string[]).toEqual(['notes/private-page']);
+ // Fuzzy arm: private slugs must not be enumerable via trigram candidates.
+ const fuzzy = (await op.handler(mkCtx(true), { partial: 'Zebra Widget' })) as string[];
+ expect(fuzzy).not.toContain('notes/private-page');
+ expect(fuzzy).toContain('notes/world-page');
+ });
+
+ test('get_links: edges to a private endpoint are dropped remotely; a private page reads as missing', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_links'];
+ const remote = (await op.handler(mkCtx(true), { slug: 'notes/world-page' })) as Array<{ to_slug: string }>;
+ expect(remote.map((l) => l.to_slug)).not.toContain('notes/private-page');
+ expect(remote.map((l) => l.to_slug)).toContain('notes/unmarked-page');
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/world-page' })) as Array<{ to_slug: string }>;
+ expect(local.map((l) => l.to_slug)).toContain('notes/private-page');
+ });
+
+ test('get_backlinks: edges from a private page are dropped remotely; world backlinks survive', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['get_backlinks'];
+ const remote = (await op.handler(mkCtx(true), { slug: 'notes/world-page' })) as Array<{ from_slug: string }>;
+ expect(remote.map((l) => l.from_slug)).not.toContain('notes/private-page');
+ const unmarked = (await op.handler(mkCtx(true), { slug: 'notes/unmarked-page' })) as Array<{ from_slug: string }>;
+ expect(unmarked.map((l) => l.from_slug)).toContain('notes/world-page');
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/world-page' })) as Array<{ from_slug: string }>;
+ expect(local.map((l) => l.from_slug)).toContain('notes/private-page');
+ });
+
+ test('traverse_graph (node shape): private nodes + edges to them are stripped remotely', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['traverse_graph'];
+ const remote = (await op.handler(mkCtx(true), { slug: 'notes/world-page' })) as Array<{
+ slug: string; links: Array<{ to_slug: string }>;
+ }>;
+ expect(remote.map((n) => n.slug)).not.toContain('notes/private-page');
+ for (const node of remote) {
+ expect(node.links.map((l) => l.to_slug)).not.toContain('notes/private-page');
+ }
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/world-page' })) as Array<{ slug: string }>;
+ expect(local.map((n) => n.slug)).toContain('notes/private-page');
+ });
+
+ test('traverse_graph: a private start page reads as missing ([]) remotely', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['traverse_graph'];
+ expect((await op.handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[]).toEqual([]);
+ expect(((await op.handler(mkCtx(false), { slug: 'notes/private-page' })) as unknown[]).length).toBeGreaterThan(0);
+ });
+
+ test('traverse_graph (path shape): paths touching a private slug are dropped remotely', async () => {
+ __resetPrivateVisibilityCacheForTests();
+ const op = operationsByName['traverse_graph'];
+ const remote = (await op.handler(mkCtx(true), { slug: 'notes/world-page', direction: 'out' })) as Array<{
+ from_slug: string; to_slug: string;
+ }>;
+ const touched = remote.flatMap((e) => [e.from_slug, e.to_slug]);
+ expect(touched).not.toContain('notes/private-page');
+ expect(touched).toContain('notes/unmarked-page');
+ const local = (await op.handler(mkCtx(false), { slug: 'notes/world-page', direction: 'out' })) as Array<{
+ from_slug: string; to_slug: string;
+ }>;
+ expect(local.flatMap((e) => [e.from_slug, e.to_slug])).toContain('notes/private-page');
+ });
+
+ test('config opt-out restores remote reads on the sibling ops', async () => {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, 'visible');
+ __resetPrivateVisibilityCacheForTests();
+ try {
+ const chunks = (await operationsByName['get_chunks'].handler(mkCtx(true), { slug: 'notes/private-page' })) as unknown[];
+ expect(chunks.length).toBeGreaterThan(0);
+ const resolved = (await operationsByName['resolve_slugs'].handler(mkCtx(true), { partial: 'notes/private-page' })) as string[];
+ expect(resolved).toEqual(['notes/private-page']);
+ } finally {
+ await engine.setConfig(REMOTE_PRIVATE_PAGES_KEY, '');
+ __resetPrivateVisibilityCacheForTests();
+ }
+ });
+});
+
+describe('shared private predicate lives once (#4352 remediation)', () => {
+ test('entity-card composes privatePagesFilterFragment instead of hand-rolling the predicate', () => {
+ // test-reads-source-ok: structural "lives ONCE" guard — a duplicated predicate behaves identically until visibility semantics drift, so only the text can catch it (#4352)
+ const src = readFileSync(join(import.meta.dir, '../src/core/verbs/entity-card.ts'), 'utf8');
+ expect(src).toContain('privatePagesFilterFragment');
+ // The predicate TEXT must not be duplicated — silent drift risk if
+ // visibility semantics ever change (sql-ranking.ts's "lives ONCE" claim).
+ expect(src).not.toMatch(/frontmatter->>\s*'visibility'/);
+ });
+});
diff --git a/test/propose-takes-truncation.test.ts b/test/propose-takes-truncation.test.ts
new file mode 100644
index 0000000000..16e3074270
--- /dev/null
+++ b/test/propose-takes-truncation.test.ts
@@ -0,0 +1,229 @@
+/**
+ * #3763 — propose_takes truncation + dead-lane halt.
+ *
+ * Pre-fix, defaultExtractor made exactly ONE gateway call at maxTokens=2048
+ * and never checked stopReason: a 'length' (truncated) response produced
+ * unparseable JSON, which the ambiguity guard rethrew as a GENERIC
+ * 'transient — retry'. The phase's catch warned + continued, wrote no
+ * tombstone, and re-billed the same pages at the same too-small cap every
+ * cycle forever. And a run where EVERY extractor call failed still walked
+ * the full page list, burning one LLM call per page.
+ *
+ * Post-fix:
+ * - stopReason 'length' retries ONCE at 4096 (facts/extract.ts #2113 parity);
+ * - a still-truncated retry throws an error NAMING the truncation;
+ * - the page loop halts after EXTRACTOR_FAILURE_HALT_STREAK consecutive
+ * failures with zero successes (status 'fail'); a mixed run never halts;
+ * - no failure tombstone in either case (#3910 policy).
+ *
+ * Uses the gateway chat-transport test seam — no API key, no network.
+ */
+
+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,
+ EXTRACTOR_FAILURE_HALT_STREAK,
+ 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' },
+ });
+});
+
+// Shard hygiene (facts-extract-truncation.test.ts precedent): restore the
+// legacy 1536-d embedding pin so later fresh-schema files in this shard
+// don't inherit a dimensionless gateway.
+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}]';
+
+// ─── defaultExtractor truncation retry ──────────────────────────────
+
+describe('defaultExtractor truncation retry (#3763)', () => {
+ const input = {
+ pagePath: 'companies/acme-example',
+ pageBody: 'I bet Acme doubles ARR by Q4. They ship weekly.',
+ existingTakes: [],
+ };
+
+ test('clean call: exactly one gateway call at the base cap', async () => {
+ const seen: ChatOpts[] = [];
+ __setChatTransportForTests(async (opts) => {
+ seen.push(opts);
+ return chatResult(GOOD_JSON, 'end');
+ });
+ const takes = await defaultExtractor(input);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]!.maxTokens).toBe(PROPOSE_TAKES_MAX_TOKENS);
+ expect(takes).toHaveLength(1);
+ });
+
+ test("stopReason 'length' retries ONCE at 4096 and recovers the takes", async () => {
+ const seen: ChatOpts[] = [];
+ __setChatTransportForTests(async (opts) => {
+ seen.push(opts);
+ return seen.length === 1
+ ? chatResult('[{"claim_text":"Acme dou', 'length')
+ : chatResult(GOOD_JSON, 'end');
+ });
+ const takes = await defaultExtractor(input);
+ expect(seen).toHaveLength(2);
+ expect(seen.map((s) => s.maxTokens)).toEqual([
+ PROPOSE_TAKES_MAX_TOKENS,
+ PROPOSE_TAKES_RETRY_MAX_TOKENS,
+ ]);
+ expect(takes).toHaveLength(1);
+ expect(takes[0]!.claim_text).toContain('Acme doubles ARR');
+ });
+
+ test('double truncation throws a message naming the truncation (not the generic transient)', async () => {
+ let calls = 0;
+ __setChatTransportForTests(async () => {
+ calls++;
+ return chatResult('[{"claim_text":"Acme', 'length');
+ });
+ try {
+ await defaultExtractor(input);
+ throw new Error('should have thrown');
+ } catch (err) {
+ const msg = (err as Error).message;
+ expect(msg).toContain('truncated');
+ expect(msg).toContain(String(PROPOSE_TAKES_RETRY_MAX_TOKENS));
+ expect(msg).not.toContain('transient — retry');
+ }
+ expect(calls).toBe(2); // bounded at one retry
+ });
+});
+
+// ─── phase-level dead-lane halt ─────────────────────────────────────
+
+interface CapturedSql { sql: string; params: unknown[] }
+
+function buildMockEngine(pageCount: number): { engine: BrainEngine; captured: CapturedSql[] } {
+ const captured: CapturedSql[] = [];
+ const engine = {
+ kind: 'pglite',
+ async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
+ captured.push({ sql, params: params ?? [] });
+ if (sql.includes('SELECT slug, source_id, compiled_truth')) {
+ return Array.from({ length: pageCount }, (_, i) => ({
+ slug: `wiki/page-${i}`,
+ source_id: 'default',
+ compiled_truth: `prose for page ${i} 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: captured.length } as unknown as T];
+ return [];
+ },
+ } as unknown as BrainEngine;
+ return { engine, captured };
+}
+
+function buildCtx(engine: BrainEngine): OperationContext {
+ return {
+ engine,
+ config: {} as never,
+ logger: { info() {}, warn() {}, error() {} } as never,
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ };
+}
+
+describe('extractor failure-streak halt (#3763)', () => {
+ test(`always-throwing extractor over N+2 pages halts at N with status 'fail' and no tombstones`, async () => {
+ const pageCount = EXTRACTOR_FAILURE_HALT_STREAK + 2;
+ const { engine, captured } = buildMockEngine(pageCount);
+ let calls = 0;
+ const extractor: ProposeTakesExtractor = async () => {
+ calls++;
+ throw new Error('propose_takes extractor: no parseable takes JSON (transient — retry)');
+ };
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+
+ expect(calls).toBe(EXTRACTOR_FAILURE_HALT_STREAK);
+ const details = result.details as Record<string, unknown>;
+ expect(details.pages_scanned).toBe(EXTRACTOR_FAILURE_HALT_STREAK);
+ expect(details.aborted_failure_streak).toBe(true);
+ expect(details.halted).toBe(true);
+ expect(details.llm_calls_failed).toBe(EXTRACTOR_FAILURE_HALT_STREAK);
+ expect(details.llm_calls_succeeded).toBe(0);
+ expect(result.status).toBe('fail');
+ expect(result.summary).toContain('consecutive extractor failures');
+
+ // #3910 policy: failed pages write NO tombstone — they retry next cycle.
+ const inserts = captured.filter((c) => c.sql.includes('INSERT INTO take_proposals'));
+ expect(inserts).toHaveLength(0);
+ });
+
+ test('a single success disarms the halt: mixed run walks every page', async () => {
+ const pageCount = EXTRACTOR_FAILURE_HALT_STREAK + 2;
+ const { engine } = buildMockEngine(pageCount);
+ let calls = 0;
+ const extractor: ProposeTakesExtractor = async () => {
+ calls++;
+ if (calls === 1) {
+ return [{ claim_text: 'one good claim', kind: 'take', holder: 'brain', weight: 0.6 }];
+ }
+ throw new Error('per-page failure');
+ };
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+
+ expect(calls).toBe(pageCount);
+ const details = result.details as Record<string, unknown>;
+ expect(details.pages_scanned).toBe(pageCount);
+ expect(details.aborted_failure_streak).toBeUndefined();
+ expect(details.llm_calls_succeeded).toBe(1);
+ expect(result.status).toBe('warn'); // per-page failures still surface as warnings
+ });
+
+ test('fewer failures than the streak never halts', async () => {
+ const pageCount = EXTRACTOR_FAILURE_HALT_STREAK - 1;
+ const { engine } = buildMockEngine(pageCount);
+ let calls = 0;
+ const extractor: ProposeTakesExtractor = async () => {
+ calls++;
+ throw new Error('per-page failure');
+ };
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+ expect(calls).toBe(pageCount);
+ const details = result.details as Record<string, unknown>;
+ expect(details.aborted_failure_streak).toBeUndefined();
+ expect(result.status).toBe('warn');
+ });
+});
diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.ts
index 5add3fcf2f..e071ac317f 100644
--- a/test/propose-takes.test.ts
+++ b/test/propose-takes.test.ts
@@ -977,3 +977,75 @@ describe('runPhaseProposeTakes — global-error halt (#3044)', () => {
expect(result.summary).not.toContain('aborted on');
});
});
+
+// ─── #4102: cycle.propose_takes.enabled off switch ─────────────────
+
+describe('cycle.propose_takes.enabled gate (#4102)', () => {
+ function stubConfig(engine: BrainEngine, value: string | null): void {
+ (engine as unknown as { getConfig: (k: string) => Promise<string | null> }).getConfig =
+ async (k: string) => (k === 'cycle.propose_takes.enabled' ? value : null);
+ }
+
+ function countingExtractor(): { extractor: ProposeTakesExtractor; calls: () => number } {
+ let n = 0;
+ return {
+ extractor: async () => { n += 1; return []; },
+ calls: () => n,
+ };
+ }
+
+ test('explicit false skips before any extractor call or DB write', async () => {
+ const pages = [buildPage({ slug: 'wiki/gated', body: 'Some gated prose.' })];
+ const { engine, captured } = buildMockEngine({ pages });
+ stubConfig(engine, 'false');
+ const { extractor, calls } = countingExtractor();
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+ expect(result.status).toBe('skipped');
+ const details = result.details as Record<string, unknown>;
+ expect(details.reason).toBe('disabled');
+ expect(String(details.enable_hint)).toContain('cycle.propose_takes.enabled');
+ expect(calls()).toBe(0);
+ expect(captured.filter(c => c.sql.includes('take_proposals'))).toHaveLength(0);
+ });
+
+ test("'0' and 'off' also skip (isConfigTruthy semantics)", async () => {
+ for (const value of ['0', 'off', 'no']) {
+ const pages = [buildPage({ slug: 'wiki/gated2', body: 'prose' })];
+ const { engine } = buildMockEngine({ pages });
+ stubConfig(engine, value);
+ const { extractor, calls } = countingExtractor();
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+ expect(result.status).toBe('skipped');
+ expect(calls()).toBe(0);
+ }
+ });
+
+ test('unset (null) = default ON: the phase runs', async () => {
+ const pages = [buildPage({ slug: 'wiki/ungated', body: 'Some prose worth scanning.' })];
+ const { engine } = buildMockEngine({ pages });
+ stubConfig(engine, null);
+ const { extractor, calls } = countingExtractor();
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
+ expect(result.status).not.toBe('skipped');
+ expect(calls()).toBe(1);
+ });
+
+ test("explicit 'true' runs", async () => {
+ const pages = [buildPage({ slug: 'wiki/on', body: 'More prose.' })];
+ const { engine } = buildMockEngine({ pages });
+ stubConfig(engine, 'true');
+ const { extractor, calls } = countingExtractor();
+ await runPhaseProposeTakes(buildCtx(engine), { extractor });
+ expect(calls()).toBe(1);
+ });
+
+ test('once:true bypasses an explicit false for this run only', async () => {
+ const pages = [buildPage({ slug: 'wiki/once', body: 'Once-run prose.' })];
+ const { engine } = buildMockEngine({ pages });
+ stubConfig(engine, 'false');
+ const { extractor, calls } = countingExtractor();
+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor, once: true });
+ expect(result.status).not.toBe('skipped');
+ expect(calls()).toBe(1);
+ });
+});
diff --git a/test/public-exports.test.ts b/test/public-exports.test.ts
index a7e701980d..a0272a55a2 100644
--- a/test/public-exports.test.ts
+++ b/test/public-exports.test.ts
@@ -54,6 +54,7 @@ const EXPECTED_EXPORTS: ExpectedExport[] = [
{ subpath: 'gbrain/extract', canary: [] },
{ subpath: 'gbrain/ingestion', canary: ['INGESTION_SOURCE_API_VERSION', 'validateIngestionEvent', 'computeContentHash'] },
{ subpath: 'gbrain/ingestion/test-harness', canary: ['IngestionTestHarness', 'expectEvent'] },
+ { subpath: 'gbrain/core/guardrails', canary: ['registerGuardrailProvider', 'runGuardrails', 'loadGuardrailProvidersFromEnv'] },
];
function readPackageExports(): Record<string, string> {
@@ -69,7 +70,7 @@ describe('public exports — package.json exports map', () => {
// Adding new exports: increment this + add to EXPECTED_EXPORTS below.
// Removing exports: see CLAUDE.md "Removing any of these is a
// breaking change going forward" — bump minor and update this count.
- expect(count).toBe(21);
+ expect(count).toBe(22);
});
test('EXPECTED_EXPORTS list matches the exports map exactly (no drift)', () => {
diff --git a/test/put-page-error-passthrough.test.ts b/test/put-page-error-passthrough.test.ts
new file mode 100644
index 0000000000..d64709e078
--- /dev/null
+++ b/test/put-page-error-passthrough.test.ts
@@ -0,0 +1,69 @@
+/**
+ * test/put-page-error-passthrough.test.ts — #3984.
+ *
+ * importFromContent returns { status: 'skipped'|'error', error: <reason> }
+ * for rejected writes (oversized content, invalid YAML frontmatter), but
+ * put_page's return envelope dropped the `error` field — an MCP caller
+ * pushing >5MB got bare `{ status: 'skipped', chunks: 0 }` and had no idea
+ * why the page never appeared. The reason now rides the op response.
+ * capture delegates to put_page, so it inherits the passthrough.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+const put_page = operations.find(o => o.name === 'put_page')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: console as any,
+ dryRun: false,
+ remote: true,
+ sourceId: 'default',
+ ...overrides,
+ };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+}, 30_000);
+
+describe('put_page passes the skip/error reason through (#3984)', () => {
+ test('>5MB content → status skipped WITH the error text', async () => {
+ const big = '---\ntype: note\n---\n' + 'x'.repeat(5_000_001);
+ const res = (await put_page.handler(ctxOf(), { slug: 'notes/too-big', content: big })) as Record<string, unknown>;
+ expect(res.status).toBe('skipped');
+ expect(String(res.error)).toContain('Content too large');
+ expect(String(res.error)).toContain('max 5000000');
+ });
+
+ test('invalid YAML frontmatter → status error WITH the error text', async () => {
+ const bad = '---\ntype: [unclosed\n---\nbody\n';
+ const res = (await put_page.handler(ctxOf(), { slug: 'notes/bad-yaml', content: bad })) as Record<string, unknown>;
+ expect(res.status).toBe('error');
+ expect(typeof res.error).toBe('string');
+ expect(String(res.error).length).toBeGreaterThan(0);
+ });
+
+ test('successful write carries NO error field (additive only)', async () => {
+ const res = (await put_page.handler(ctxOf(), {
+ slug: 'notes/fine', content: '---\ntype: note\n---\nfine body\n',
+ })) as Record<string, unknown>;
+ expect(res.status).toBe('created_or_updated');
+ expect('error' in res).toBe(false);
+ });
+});
diff --git a/test/query-cache-knobs-hash.serial.test.ts b/test/query-cache-knobs-hash.serial.test.ts
index 5a5f1cb4f8..20495c869b 100644
--- a/test/query-cache-knobs-hash.serial.test.ts
+++ b/test/query-cache-knobs-hash.serial.test.ts
@@ -387,3 +387,56 @@ describe('FTS language cache isolation', () => {
expect((await cache.lookup(emb, { knobsHash: portugueseHash })).hit).toBe(true);
});
});
+
+describe('excludePrivate cache isolation (#4352 follow-up)', () => {
+ // Hashes computed the way hybridSearchCached does: same resolved mode, ctx
+ // carrying the private-visibility posture. Folding the posture (xp=, v=23)
+ // replaces #4352's wholesale cache skip — excludePrivate=true is the
+ // default for every remote MCP caller, so the skip disabled the semantic
+ // cache for exactly the highest-volume beneficiaries. A trusted
+ // (private-included) write must never serve a remote-default
+ // (private-excluding) lookup, and vice versa.
+ const trustedHash = knobsHash(resolveSearchMode({ mode: 'balanced' }), { excludePrivate: false });
+ const excludingHash = knobsHash(resolveSearchMode({ mode: 'balanced' }), { excludePrivate: true });
+
+ test('postures produce different hashes; undefined keys like the trusted (included) default', () => {
+ expect(trustedHash).not.toBe(excludingHash);
+ // Mirrors enforcement's strict `=== true` predicate: legacy callers that
+ // don't thread the posture share the trusted rows.
+ expect(knobsHash(resolveSearchMode({ mode: 'balanced' }))).toBe(trustedHash);
+ });
+
+ test('private-included (trusted) write is NOT served to a private-excluding lookup', async () => {
+ const cache = new SemanticQueryCache(engine);
+ const emb = makeEmbedding(10);
+
+ // Simulate a trusted local run whose stored rows contain a private page
+ // the remote caller must never see.
+ await cache.store('who is alice', emb, makeResults('with-private', 5), {
+ vector_enabled: true, detail_resolved: null, expansion_applied: false,
+ }, { knobsHash: trustedHash });
+
+ // Remote-default (excludePrivate=true) lookup → MISS (falls through to a
+ // fresh, visibility-filtered query).
+ expect((await cache.lookup(emb, { knobsHash: excludingHash })).hit).toBe(false);
+
+ // The trusted caller still hits its own row.
+ const original = await cache.lookup(emb, { knobsHash: trustedHash });
+ expect(original.hit).toBe(true);
+ expect(original.results?.length).toBe(5);
+ });
+
+ test('private-excluding write is NOT served back to a trusted lookup', async () => {
+ const cache = new SemanticQueryCache(engine);
+ const emb = makeEmbedding(11);
+
+ // A remote write is a FILTERED result set — serving it to a trusted
+ // lookup would hide private pages the trusted caller is entitled to.
+ await cache.store('who is alice', emb, makeResults('filtered', 3), {
+ vector_enabled: true, detail_resolved: null, expansion_applied: false,
+ }, { knobsHash: excludingHash });
+
+ expect((await cache.lookup(emb, { knobsHash: trustedHash })).hit).toBe(false);
+ expect((await cache.lookup(emb, { knobsHash: excludingHash })).hit).toBe(true);
+ });
+});
diff --git a/test/receipt-cr-state.test.ts b/test/receipt-cr-state.test.ts
new file mode 100644
index 0000000000..0727785664
--- /dev/null
+++ b/test/receipt-cr-state.test.ts
@@ -0,0 +1,86 @@
+/**
+ * test/receipt-cr-state.test.ts — #4009.
+ *
+ * Extract receipts are audit artifacts written via putPage; nothing ever
+ * ran them through the contextual-retrieval ladder, so every receipt was
+ * born with contextual_retrieval_mode = NULL and tripped doctor's
+ * contextual_retrieval_coverage warn ("N page(s) never evaluated against
+ * CR ladder") — an unclearable-by-design warn that recurred on every
+ * extraction run right after a `gbrain reindex --markdown`.
+ *
+ * Two-layer fix pinned here:
+ * 1. writeReceipt stamps mode 'none' after putPage — receipts are born
+ * CR-evaluated (deliberately no CR wrapper; they're audit pages).
+ * 2. Belt+braces: the doctor check excludes type='extract_receipt' from
+ * mode_null, because layer 1 is not permanent — a reindex that takes
+ * the DB fallback can clear the stamp, and it recurs per receipt.
+ */
+
+import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { writeReceipt, type ExtractReceiptInput } from '../src/core/extract/receipt-writer.ts';
+import { checkContextualRetrievalCoverage } from '../src/commands/doctor/checks/calibration.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);
+});
+
+function receiptInput(overrides: Partial<ExtractReceiptInput> = {}): ExtractReceiptInput {
+ return {
+ kind: 'links',
+ source_id: 'default',
+ run_id: 'run-abcdef1234',
+ round: 'single',
+ extracted_at: '2026-08-21T00:00:00.000Z',
+ total_rows: 3,
+ cost_usd: 0,
+ ...overrides,
+ };
+}
+
+describe('receipts are born CR-evaluated (#4009)', () => {
+ test('writeReceipt stamps contextual_retrieval_mode = none', async () => {
+ const { slug } = await writeReceipt(engine, receiptInput());
+ const rows = await engine.executeRaw<{ mode: string | null }>(
+ `SELECT contextual_retrieval_mode AS mode FROM pages WHERE slug = $1 AND source_id = 'default'`,
+ [slug],
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0].mode).toBe('none');
+ });
+
+ test('doctor calibration check does not count receipts in mode_null (belt+braces)', async () => {
+ const { slug } = await writeReceipt(engine, receiptInput());
+ // Simulate the non-permanence path: a reindex DB fallback clearing the stamp.
+ await engine.executeRaw(
+ `UPDATE pages SET contextual_retrieval_mode = NULL WHERE slug = $1`,
+ [slug],
+ );
+ const check = await checkContextualRetrievalCoverage(engine);
+ expect(check.message).not.toContain('never evaluated against CR ladder');
+ });
+
+ test('non-receipt markdown pages still count in mode_null', async () => {
+ await engine.putPage('notes/plain', {
+ type: 'note', title: 'Plain', compiled_truth: 'body', frontmatter: {},
+ }, { sourceId: 'default' });
+ await engine.executeRaw(
+ `UPDATE pages SET contextual_retrieval_mode = NULL WHERE slug = 'notes/plain'`,
+ );
+ const check = await checkContextualRetrievalCoverage(engine);
+ expect(check.message).toContain('never evaluated against CR ladder');
+ });
+});
diff --git a/test/redos-hardening.test.ts b/test/redos-hardening.test.ts
index e122207eed..f562ed8204 100644
--- a/test/redos-hardening.test.ts
+++ b/test/redos-hardening.test.ts
@@ -11,6 +11,7 @@ import {
runRegexBounded,
PageRegexBudget,
RegexInputTooLargeError,
+ RegexCatastrophicPatternError,
MAX_REGEX_INPUT_CHARS,
} from '../src/core/schema-pack/redos-guard.ts';
import { inferLinkTypeFromPack } from '../src/core/schema-pack/link-inference.ts';
@@ -50,6 +51,49 @@ describe('#1569 input-length cap', () => {
});
});
+describe('megawave vm-watchdog removal (bootstrap-verify freeze)', () => {
+ // Bun's `vm.runInContext(..., { timeout })` watchdog wedges the event loop
+ // in processes that also host PGLite WASM: after some dozens of watchdog
+ // runs, all JS timers stop firing and the next in-flight PGLite query
+ // promise never resolves (repro: the bootstrap-verify corpus test hanging
+ // at 240s once #3190 wired pack regex inference into put_page). The guard
+ // must never route through node:vm again; bounding is structural (input
+ // cap + catastrophic-shape refusal + per-page budget).
+ test('redos-guard does not import node:vm (freeze regression pin)', () => {
+ // Import absence is the load-bearing check: without the import, no code
+ // path can reach runInContext. (The header comment intentionally KEEPS
+ // the historical vm references as the record of why it was removed.)
+ const src = readFileSync(join(import.meta.dir, '..', 'src', 'core', 'schema-pack', 'redos-guard.ts'), 'utf-8');
+ expect(src).not.toMatch(/from ['"]node:vm['"]/);
+ expect(src).not.toMatch(/require\(['"]node:vm['"]\)/);
+ expect(src).not.toMatch(/from ['"]vm['"]/);
+ });
+
+ test('runRegexBounded refuses nested-quantifier patterns before executing', () => {
+ expect(() => runRegexBounded('(a+)+$', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!')).toThrow(RegexCatastrophicPatternError);
+ });
+
+ test('PageRegexBudget.runBounded degrades (null) on catastrophic pattern, counts budget', () => {
+ const budget = new PageRegexBudget();
+ expect(budget.runBounded('verb', '(\\w+)+$', 'some ordinary context sentence')).toBeNull();
+ expect(budget.getCumulativeMs()).toBeGreaterThan(0);
+ });
+
+ test('benign first-party-shaped patterns still match (plain exec path)', () => {
+ const m = runRegexBounded('\\b(founded|founder of|co-?founded|started)\\b', 'alice founded acme');
+ expect(m).not.toBeNull();
+ });
+
+ test('inferLinkTypeFromPack degrades a catastrophic pack regex to null (no hang)', () => {
+ const pack = {
+ link_types: [{ name: 'evil', inference: { regex: '(a+)+$' } }],
+ } as unknown as Pick<SchemaPackManifest, 'link_types'>;
+ const t0 = Date.now();
+ expect(inferLinkTypeFromPack(pack, 'company', 'a'.repeat(64) + '!')).toBeNull();
+ expect(Date.now() - t0).toBeLessThan(1_000);
+ });
+});
+
describe('#1569 star-height lint rule', () => {
const mk = (regex: string): SchemaPackManifest =>
({ name: 'testpack', page_types: [], link_types: [{ name: 'founded', inference: { regex } }] }) as unknown as SchemaPackManifest;
diff --git a/test/reindex-code-recovery.test.ts b/test/reindex-code-recovery.test.ts
new file mode 100644
index 0000000000..8defa34ebd
--- /dev/null
+++ b/test/reindex-code-recovery.test.ts
@@ -0,0 +1,114 @@
+/**
+ * issue #3970 — 3-surface recovery for code pages stuck without symbol
+ * metadata (the content_hash short-circuit makes a plain reindex a no-op):
+ *
+ * 1. `reindexForceHint` — the "0 reindexed, N skipped" summary points at
+ * --force (pure helper, unit-tested here).
+ * 2. doctor `code_chunk_metadata` — counts code-page chunks with
+ * symbol_name IS NULL AND language IS NULL and names
+ * `gbrain reindex-code --force` as the cure.
+ * 3. the CLI help line for reindex-code documents --force.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { reindexForceHint } from '../src/commands/reindex-code.ts';
+import { checkCodeChunkMetadata } from '../src/commands/doctor.ts';
+
+describe('reindexForceHint (#3970 surface 3)', () => {
+ test('all-skipped pass without --force → hint naming --force', () => {
+ const hint = reindexForceHint({ reindexed: 0, skipped: 12 }, false);
+ expect(hint).not.toBeNull();
+ expect(hint!).toContain('--force');
+ expect(hint!).toContain('12');
+ expect(hint!).toContain('content_hash');
+ });
+
+ test('no hint when --force was already passed', () => {
+ expect(reindexForceHint({ reindexed: 0, skipped: 12 }, true)).toBeNull();
+ });
+
+ test('no hint when pages actually reindexed', () => {
+ expect(reindexForceHint({ reindexed: 3, skipped: 9 }, false)).toBeNull();
+ });
+
+ test('no hint when nothing was skipped', () => {
+ expect(reindexForceHint({ reindexed: 0, skipped: 0 }, false)).toBeNull();
+ });
+});
+
+describe('doctor code_chunk_metadata (#3970 surface 2)', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ if (engine) await engine.disconnect();
+ }, 60_000);
+
+ async function addPageWithChunk(
+ slug: string,
+ opts: { type?: string; symbolName?: string | null; language?: string | null; deleted?: boolean } = {},
+ ): Promise<void> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO pages (slug, source_id, type, page_kind, title, compiled_truth, timeline, frontmatter, deleted_at)
+ VALUES ($1, 'default', $2, 'markdown', $1, 'body', '', '{}'::jsonb, $3)
+ RETURNING id`,
+ [slug, opts.type ?? 'code', opts.deleted ? new Date().toISOString() : null],
+ );
+ await engine.executeRaw(
+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, symbol_name, language)
+ VALUES ($1, 0, 'chunk body', $2, $3)`,
+ [rows[0]!.id, opts.symbolName ?? null, opts.language ?? null],
+ );
+ }
+
+ test('ok when every code chunk carries symbol metadata (markdown NULLs and deleted pages ignored)', async () => {
+ // Healthy code chunk (both fields populated).
+ await addPageWithChunk('src-foo-ts', { symbolName: 'foo', language: 'typescript' });
+ // Markdown chunk with NULL metadata — not a code page, must not count.
+ await addPageWithChunk('notes/meeting', { type: 'concept', symbolName: null, language: null });
+ // Soft-deleted code page with NULL metadata — must not count.
+ await addPageWithChunk('src-dead-ts', { symbolName: null, language: null, deleted: true });
+
+ const c = await checkCodeChunkMetadata(engine);
+ expect(c.name).toBe('code_chunk_metadata');
+ expect(c.status).toBe('ok');
+ });
+
+ test('warn with reindex-code --force cure when code chunks have no metadata', async () => {
+ await addPageWithChunk('src-legacy-ts', { symbolName: null, language: null });
+ await addPageWithChunk('src-legacy2-py', { symbolName: null, language: null });
+
+ const c = await checkCodeChunkMetadata(engine);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('reindex-code --force');
+ expect(c.message).toContain('2 chunk(s)');
+ expect((c.details as { chunks_missing_metadata: number }).chunks_missing_metadata).toBe(2);
+ expect((c.details as { pages_affected: number }).pages_affected).toBe(2);
+ });
+
+ test('chunk with only language populated (symbol_name NULL) does not count — both must be NULL', async () => {
+ // e.g. a chunk between symbols still stamped with the file language.
+ await addPageWithChunk('src-partial-go', { symbolName: null, language: 'go' });
+
+ const c = await checkCodeChunkMetadata(engine);
+ // Still warns from the previous test's rows, but the count is unchanged.
+ expect((c.details as { chunks_missing_metadata: number }).chunks_missing_metadata).toBe(2);
+ });
+});
+
+describe('CLI help line (#3970 surface 1)', () => {
+ test('reindex-code help documents --force', () => {
+ const cli = readFileSync(join(import.meta.dir, '../src/cli.ts'), 'utf-8');
+ const line = cli.split('\n').find((l) => l.trimStart().startsWith('reindex-code ['));
+ expect(line).toBeDefined();
+ expect(line!).toContain('--force');
+ });
+});
diff --git a/test/relational-recall.test.ts b/test/relational-recall.test.ts
index 61eff17779..48d4debe6e 100644
--- a/test/relational-recall.test.ts
+++ b/test/relational-recall.test.ts
@@ -9,9 +9,11 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { buildRelationalArm } from '../src/core/search/relational-recall.ts';
+import { buildRelationalArm, ensureRelationalEvidenceSlot } from '../src/core/search/relational-recall.ts';
+import { hybridSearch } from '../src/core/search/hybrid.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { probeEmbeddingDim } from './fixtures/retrieval-quality/relational/corpus.ts';
-import type { ChunkInput } from '../src/core/types.ts';
+import type { ChunkInput, SearchResult, HybridSearchMeta } from '../src/core/types.ts';
let eng: PGLiteEngine;
@@ -29,6 +31,17 @@ beforeAll(async () => {
chunk_source: 'compiled_truth', embedding: new Float32Array(dim), token_count: 8,
}] satisfies ChunkInput[]);
await eng.addLink('people/alice-example', 'companies/widget-co', '', 'invested_in', 'manual');
+
+ // #4352 fixture: a `visibility: private` investor whose ONLY connection to
+ // the company is the typed edge. Pre-remediation the arm hydrated its title
+ // + compiled_truth snippet for ANY caller (hybrid.ts built the arm without
+ // excludePrivate; hydrate() filtered on deleted_at alone).
+ await eng.putPage('people/mallory-secret', {
+ type: 'person', title: 'Mallory Secret',
+ frontmatter: { visibility: 'private' },
+ compiled_truth: 'Mallory runs a stealth family office in Zurich.', timeline: '',
+ });
+ await eng.addLink('people/mallory-secret', 'companies/widget-co', '', 'invested_in', 'manual');
}, 60_000);
afterAll(async () => { await eng.disconnect(); });
@@ -57,6 +70,45 @@ describe('buildRelationalArm', () => {
expect(list).toEqual([]);
});
+ test('#4352: excludePrivate hides private pages from the arm; default keeps them (trusted)', async () => {
+ const trusted = await buildRelationalArm(eng, 'who invested in widget-co');
+ expect(trusted.map(r => r.slug)).toContain('people/mallory-secret');
+
+ const gated = await buildRelationalArm(eng, 'who invested in widget-co', { excludePrivate: true });
+ const slugs = gated.map(r => r.slug);
+ expect(slugs).not.toContain('people/mallory-secret');
+ expect(slugs).toContain('people/alice-example'); // non-private candidates survive
+ // Neither the private title nor the compiled_truth snippet leaks anywhere.
+ for (const r of gated) {
+ expect(r.title).not.toContain('Mallory');
+ expect(r.chunk_text).not.toContain('stealth family office');
+ }
+ });
+
+ test('#4352: hybridSearch threads excludePrivate into the relational arm', async () => {
+ const remoteLike = await hybridSearch(eng, 'who invested in widget-co', {
+ relationalRetrieval: true, excludePrivate: true, limit: 20,
+ });
+ const remoteSlugs = remoteLike.map(r => r.slug);
+ expect(remoteSlugs).not.toContain('people/mallory-secret');
+ expect(remoteSlugs).toContain('people/alice-example');
+
+ const localLike = await hybridSearch(eng, 'who invested in widget-co', {
+ relationalRetrieval: true, limit: 20,
+ });
+ expect(localLike.map(r => r.slug)).toContain('people/mallory-secret');
+ });
+
+ test('#4352: hydrate hides pages in archived sources (all callers)', async () => {
+ await eng.executeRaw(`UPDATE sources SET archived = true WHERE id = 'default'`, []);
+ try {
+ const list = await buildRelationalArm(eng, 'who invested in widget-co');
+ expect(list).toEqual([]);
+ } finally {
+ await eng.executeRaw(`UPDATE sources SET archived = false WHERE id = 'default'`, []);
+ }
+ });
+
test('fail-open: fanout error returns [] + errored meta, never throws', async () => {
const original = eng.relationalFanout.bind(eng);
let captured: { errored?: boolean } = {};
@@ -70,3 +122,153 @@ describe('buildRelationalArm', () => {
}
});
});
+
+// ---------------------------------------------------------------------------
+// #3995 — guaranteed page-1 relational evidence slot
+// ---------------------------------------------------------------------------
+
+function mk(slug: string, score: number, extra: Partial<SearchResult> = {}): SearchResult {
+ return {
+ slug, page_id: 1, title: slug, type: 'note',
+ chunk_text: slug, chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0,
+ score, stale: false, source_id: 'default', ...extra,
+ } as SearchResult;
+}
+
+describe('ensureRelationalEvidenceSlot (unit, #3995)', () => {
+ const rel = [mk('people/alice-example', 0, { relational_seed: 'companies/widget-co' })];
+
+ test('no-op when a relational page is already inside the limit window', () => {
+ const pool = [mk('a', 0.9), mk('people/alice-example', 0.8), mk('b', 0.7)];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 2, 0);
+ expect(r.decision).toBeUndefined();
+ expect(r.pool).toBe(pool); // untouched reference on no-op
+ });
+
+ test('fusion overflow: promotes the fused relational row into slot limit-1', () => {
+ const pool = [mk('a', 0.9), mk('b', 0.8), mk('c', 0.7), mk('people/alice-example', 0.1), mk('d', 0.05)];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 3, 0);
+ expect(r.decision).toEqual({ action: 'promoted', slug: 'people/alice-example', source_id: 'default', from_rank: 3 });
+ expect(r.pool.slice(0, 3).map(x => x.slug)).toEqual(['a', 'b', 'people/alice-example']);
+ // promoted row keeps its real fused score; input pool not mutated
+ expect(r.pool[2].score).toBe(0.1);
+ expect(pool[3].slug).toBe('people/alice-example');
+ expect(r.pool.length).toBe(pool.length);
+ });
+
+ test('autocut drop: injects relationalList[0] at slot limit-1 when absent from pool', () => {
+ const pool = [mk('a', 0.9), mk('b', 0.8), mk('c', 0.7)];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 3, 0);
+ expect(r.decision).toEqual({ action: 'injected', slug: 'people/alice-example', source_id: 'default' });
+ expect(r.pool.map(x => x.slug)).toEqual(['a', 'b', 'people/alice-example', 'c']);
+ // injected score-0 row is clamped just below its predecessor (monotone order)
+ expect(r.pool[2].score).toBeLessThanOrEqual(r.pool[1].score);
+ expect(r.pool[2].score).toBeGreaterThan(0);
+ });
+
+ test('injection appends when the pool is shorter than the limit', () => {
+ const pool = [mk('a', 0.9)];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 5, 0);
+ expect(r.decision?.action).toBe('injected');
+ expect(r.pool.map(x => x.slug)).toEqual(['a', 'people/alice-example']);
+ });
+
+ test('offset > 0 is a pure no-op (first page only)', () => {
+ const pool = [mk('a', 0.9), mk('b', 0.8), mk('c', 0.7)];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 2, 2);
+ expect(r.decision).toBeUndefined();
+ expect(r.pool).toBe(pool);
+ });
+
+ test('empty relational arm is a pure no-op', () => {
+ const pool = [mk('a', 0.9)];
+ const r = ensureRelationalEvidenceSlot(pool, [], 2, 0);
+ expect(r.decision).toBeUndefined();
+ expect(r.pool).toBe(pool);
+ });
+
+ test('page-level match counts any chunk of the relational page', () => {
+ // same page surfaced by keyword under a DIFFERENT chunk id → still evidence
+ const pool = [mk('a', 0.9), mk('people/alice-example', 0.8, { chunk_id: 42 })];
+ const r = ensureRelationalEvidenceSlot(pool, rel, 2, 0);
+ expect(r.decision).toBeUndefined();
+ });
+});
+
+describe('hybridSearch guarantees page-1 relational evidence (#3995)', () => {
+ let eng2: PGLiteEngine;
+
+ beforeAll(async () => {
+ eng2 = new PGLiteEngine();
+ await eng2.connect({});
+ await eng2.initSchema();
+ // Deterministic no-embedding-provider install (noEmbed path).
+ configureGateway({ env: {} });
+
+ await eng2.putPage('companies/widget-co', { type: 'company', title: 'Widget Co', compiled_truth: 'A payments company.', timeline: '' });
+ // Relational answer: unverified auto-extracted stub (no compiled-truth
+ // boost) whose body never contains the query tokens — the #3995 shape.
+ await eng2.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example',
+ compiled_truth: 'Alice is a seed-stage backer based in Lisbon.', timeline: '',
+ frontmatter: { provenance: 'auto-extracted', status: 'unverified' },
+ });
+ await eng2.upsertChunks('people/alice-example', [{
+ chunk_index: 0, chunk_text: 'Alice is a seed-stage backer based in Lisbon.',
+ chunk_source: 'compiled_truth', token_count: 8,
+ }] as ChunkInput[]);
+ await eng2.addLink('people/alice-example', 'companies/widget-co', '', 'invested_in', 'manual');
+
+ // Verified keyword noise that outranks the single-arm relational row.
+ for (let i = 0; i < 12; i++) {
+ const slug = `notes/noise-${i}`;
+ const text = `Fund memo ${i}: somebody invested in widget-co adjacent themes.`;
+ await eng2.putPage(slug, { type: 'note', title: `Noise ${i}`, compiled_truth: text, timeline: '' });
+ await eng2.upsertChunks(slug, [{
+ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 12,
+ }] as ChunkInput[]);
+ }
+ }, 60_000);
+
+ afterAll(async () => {
+ resetGateway();
+ await eng2.disconnect();
+ });
+
+ test('limit slice would drop the fired arm evidence — slot keeps it on page 1', async () => {
+ let meta: HybridSearchMeta | undefined;
+ const results = await hybridSearch(eng2, 'who invested in widget-co', {
+ limit: 2, relationalRetrieval: true, expansion: false, onMeta: m => { meta = m; },
+ });
+ expect(results.length).toBe(2);
+ expect(results.some(r => r.slug === 'people/alice-example')).toBe(true);
+ expect(meta?.relational_evidence_slot?.action).toBe('promoted');
+ expect(meta?.relational_evidence_slot?.slug).toBe('people/alice-example');
+ }, 60_000);
+
+ test('control: arm off → no slot, evidence page absent (proves non-lexical)', async () => {
+ let meta: HybridSearchMeta | undefined;
+ const results = await hybridSearch(eng2, 'who invested in widget-co', {
+ limit: 2, relationalRetrieval: false, expansion: false, onMeta: m => { meta = m; },
+ });
+ expect(results.some(r => r.slug === 'people/alice-example')).toBe(false);
+ expect(meta?.relational_evidence_slot).toBeUndefined();
+ }, 60_000);
+
+ test('offset page: slot does not repeat the evidence row', async () => {
+ let meta: HybridSearchMeta | undefined;
+ await hybridSearch(eng2, 'who invested in widget-co', {
+ limit: 2, offset: 2, relationalRetrieval: true, expansion: false, onMeta: m => { meta = m; },
+ });
+ expect(meta?.relational_evidence_slot).toBeUndefined();
+ }, 60_000);
+
+ test('evidence already on page 1 → clean run, no slot stamp', async () => {
+ let meta: HybridSearchMeta | undefined;
+ const results = await hybridSearch(eng2, 'who invested in widget-co', {
+ limit: 20, relationalRetrieval: true, expansion: false, onMeta: m => { meta = m; },
+ });
+ expect(results.some(r => r.slug === 'people/alice-example')).toBe(true);
+ expect(meta?.relational_evidence_slot).toBeUndefined();
+ }, 60_000);
+});
diff --git a/test/remediation-command-resolution.test.ts b/test/remediation-command-resolution.test.ts
new file mode 100644
index 0000000000..943f1dfcee
--- /dev/null
+++ b/test/remediation-command-resolution.test.ts
@@ -0,0 +1,221 @@
+/**
+ * #3697 — remediation text must name commands that actually resolve.
+ *
+ * Error messages, hints, and CHANGELOG "To take advantage" blocks routinely
+ * rotted into naming commands that do not exist (`gbrain extract status
+ * --rebuild-rollup`), flags the command never parses (`gbrain think --ab`,
+ * `gbrain embed --source-id`), or subcommands that were never wired
+ * (`gbrain takes nudge --hush`). Remediation text is the one string nobody
+ * ever runs: it is emitted only on a failure path and read only by someone
+ * already stuck — so it rots silently, in the worst possible place.
+ *
+ * Two mechanical gates (classes 1/2/4 of the issue; class 3 — a command that
+ * runs but lies — needs scenario tests and review discipline, see
+ * scripts/check-test-discriminates.sh and CONTRIBUTING.md's Discrimination
+ * test field from #3665):
+ *
+ * 1. CHANGELOG (topmost entry only): every `gbrain <verb>` in fenced code /
+ * inline spans resolves to a live command. Historical entries document
+ * their era's CLI and are never rewritten (CLAUDE.md), so only the entry
+ * being shipped is gated — rot is caught while the author is still here.
+ *
+ * 2. src remediation strings: any string in src TS files that names
+ * `gbrain <verb> ... --flag` must use a verb that resolves AND flags
+ * present in that command's CLI_FLAG_REGISTRY row. The registry is
+ * deliberately over-inclusive (help-text mentions count), so a flag it
+ * does not know for that command is a strong rot signal. Verbs without
+ * any --flag in the same string are NOT gated (prose like "this gbrain
+ * build expects" would drown the signal) — documented limitation.
+ *
+ * The companion sibling is test/docs-cli-commands.test.ts (#3502), which
+ * gates verbs in README/docs/skills.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'fs';
+import { dirname, join, relative } from 'path';
+import { CLI_ONLY, cliAliases } from '../src/cli.ts';
+import { operations } from '../src/core/operations.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+
+const ROOT = dirname(import.meta.dir);
+
+function validCommands(): Set<string> {
+ const valid = new Set<string>(CLI_ONLY);
+ for (const op of operations) {
+ const name = op.cliHints?.name;
+ if (name && !op.cliHints?.hidden) valid.add(name);
+ }
+ for (const alias of cliAliases.keys()) valid.add(alias);
+ return valid;
+}
+
+/** Flags accepted globally (parsed before command dispatch) or so widely
+ * shared that a per-command registry miss would be a false positive. */
+const GLOBAL_FLAGS = new Set([
+ '--help', '--json', '--quiet', '--progress-json', '--progress-interval', '--brain',
+]);
+
+/**
+ * Known registry gaps: the command genuinely parses the flag but the
+ * generated registry row misses it (regenerating the registry is a separate
+ * scripts/ concern). Keyed `verb → flags`. Keep this SHORT — every entry
+ * should cite where the flag is actually parsed.
+ */
+const REGISTRY_GAPS: Record<string, string[]> = {
+ // init.ts:~3130 parses `--repo` (args.find((a, i) => args[i-1] === '--repo')).
+ 'init': ['--repo'],
+};
+
+// ── Gate 1: CHANGELOG topmost entry ─────────────────────────────────────────
+
+/**
+ * Already-shipped rot in the CURRENT top entry, allowlisted because
+ * historical entries are never rewritten (CLAUDE.md). Each entry falls out
+ * of gate scope automatically when the next release pushes a new top entry —
+ * prune it from here then.
+ */
+const CHANGELOG_ALLOWLIST = new Set([
+ // v0.46.25.0 wrote `gbrain migrate-engine`; the real grammar is
+ // `gbrain migrate --to <engine>` (migrate-engine.ts is the module name,
+ // not the command).
+ 'migrate-engine',
+]);
+
+function topChangelogEntry(): string {
+ const text = readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf-8');
+ const first = text.indexOf('\n## [');
+ if (first === -1) return '';
+ const second = text.indexOf('\n## [', first + 1);
+ return second === -1 ? text.slice(first) : text.slice(first, second);
+}
+
+function commandPosition(prefix: string): boolean {
+ const p = prefix.trimEnd();
+ return p === '' || /[|;&`(={[]$/.test(p) || /\$$/.test(p);
+}
+
+function scanChangelogTopEntry(): string[] {
+ const valid = validCommands();
+ const violations: string[] = [];
+ const lines = topChangelogEntry().split('\n');
+ let inFence = false;
+ for (let i = 0; i < lines.length; i++) {
+ const l = lines[i]!;
+ if (/^\s*(```|~~~)/.test(l)) { inFence = !inFence; continue; }
+ const candidates: string[] = [];
+ if (inFence) {
+ const t = l.trim();
+ if (/^(#|\/\/|--|\*)/.test(t)) continue;
+ candidates.push(l);
+ } else {
+ for (const m of l.matchAll(/`(gbrain [^`]+)`/g)) candidates.push(m[1]!);
+ }
+ for (const code of candidates) {
+ for (const m of code.matchAll(/\bgbrain\s+([A-Za-z][\w-]*)/g)) {
+ const verb = m[1]!;
+ if (!/^[a-z][a-z0-9_-]{2,}$/.test(verb)) continue;
+ if (!commandPosition(code.slice(0, m.index))) continue;
+ if (valid.has(verb)) continue;
+ if (CHANGELOG_ALLOWLIST.has(verb)) continue;
+ violations.push(`CHANGELOG.md (top entry): \`gbrain ${verb}\` is not a real command — ${code.trim().slice(0, 90)}`);
+ }
+ }
+ }
+ return violations;
+}
+
+// ── Gate 2: src remediation strings ─────────────────────────────────────────
+
+function* tsFiles(dir: string): Generator<string> {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry);
+ if (statSync(p).isDirectory()) yield* tsFiles(p);
+ else if (p.endsWith('.ts')) yield p;
+ }
+}
+
+const SRC_EXCLUDED = [
+ 'src/commands/migrations/', // historical: each names its era's CLI
+];
+
+function srcExcluded(rel: string): boolean {
+ if (SRC_EXCLUDED.some((e) => rel.startsWith(e))) return true;
+ if (rel.endsWith('.generated.ts')) return true; // fix the generator's inputs, not the output
+ if (rel.endsWith('schema-embedded.ts')) return true; // generated from src/schema.sql (which IS scanned via this file's strings? no — sql comments; gated by hand-fix #3697)
+ return false;
+}
+
+function scanSrcStrings(): string[] {
+ const valid = validCommands();
+ const violations: string[] = [];
+ for (const file of tsFiles(join(ROOT, 'src'))) {
+ const rel = relative(ROOT, file);
+ if (srcExcluded(rel)) continue;
+ const lines = readFileSync(file, 'utf-8').split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ const l = lines[i]!;
+ const t = l.trim();
+ if (/^(\/\/|\*|\/\*|--)/.test(t)) continue; // TS comments + SQL comment lines
+ if (!/['"`]/.test(l)) continue; // only string-bearing lines
+ // Tail stops at quote/backtick so we never leak across string boundaries.
+ for (const m of l.matchAll(/\bgbrain\s+([a-z][a-z0-9_-]{2,})\b([^'"`\n]*)/g)) {
+ const verb = m[1]!;
+ // Prose separators end the command: an em-dash clause or a new
+ // sentence after the mention is instruction text, not the command's
+ // own argv ("...gbrain binary path — pass --gbrain-bin ...").
+ const tail = (m[2] ?? '').split(/\s—\s|\.\s|;\s|\?\s|!\s/)[0]!;
+ const flags = [...tail.matchAll(/--[a-z][a-z0-9-]*/g)].map((f) => f[0]);
+ if (flags.length === 0) continue; // prose-mention; not gated (see header)
+ if (!valid.has(verb)) {
+ violations.push(`${rel}:${i + 1}: \`gbrain ${verb}\` is not a real command — ${t.slice(0, 100)}`);
+ continue;
+ }
+ const registry = (CLI_FLAG_REGISTRY as Record<string, readonly string[]>)[verb];
+ if (!registry) continue; // op-dispatched commands map flags to op params
+ for (const flag of flags) {
+ if (registry.includes(flag)) continue;
+ if (GLOBAL_FLAGS.has(flag)) continue;
+ if (REGISTRY_GAPS[verb]?.includes(flag)) continue;
+ violations.push(`${rel}:${i + 1}: \`gbrain ${verb} ... ${flag}\` — flag not in ${verb}'s registry row — ${t.slice(0, 100)}`);
+ }
+ }
+ }
+ }
+ return violations;
+}
+
+describe('#3697 — remediation text resolves against the live CLI surface', () => {
+ test('CHANGELOG top entry: every gbrain verb resolves', () => {
+ const violations = scanChangelogTopEntry();
+ expect(
+ violations,
+ `The entry being shipped names gbrain commands that do not resolve:\n${violations.join('\n')}\n` +
+ `Fix the command text (or, if the command should exist, wire it).`,
+ ).toEqual([]);
+ });
+
+ test('src strings: every `gbrain <verb> --flag` uses a real verb + registered flags', () => {
+ const violations = scanSrcStrings();
+ expect(
+ violations,
+ `Remediation strings name commands/flags that do not resolve:\n${violations.join('\n')}\n` +
+ `Fix the string, or add a cited entry to REGISTRY_GAPS if the generated registry is missing a real flag.`,
+ ).toEqual([]);
+ });
+
+ // The scanner must actually catch the classes it exists for — otherwise this
+ // gate is itself the #3665 pattern (an assertion nobody checks discriminates).
+ test('scanner self-check: the historical rot shapes would have been caught', () => {
+ // fake verb: never a command
+ expect(validCommands().has('reinit-everything')).toBe(false);
+ // fake flag on a real verb: the shipped #3697 instances. If a future
+ // registry regen adds these flags, the commands grew them for real and
+ // this pin should flip WITH the hint text.
+ const think = (CLI_FLAG_REGISTRY as Record<string, readonly string[]>)['think'];
+ expect(think).toBeDefined();
+ expect(think!.includes('--ab')).toBe(false);
+ const embed = (CLI_FLAG_REGISTRY as Record<string, readonly string[]>)['embed'];
+ expect(embed).toBeDefined();
+ expect(embed!.includes('--source-id')).toBe(false);
+ });
+});
diff --git a/test/request-tools.test.ts b/test/request-tools.test.ts
index bee1220d7c..43f7397d18 100644
--- a/test/request-tools.test.ts
+++ b/test/request-tools.test.ts
@@ -153,7 +153,13 @@ describe('request_tools catalog (no args)', () => {
...HTTP, auth: authFor('agent-client', ['agent']),
});
const names = flatNames(parsed(res).catalog).sort();
- expect(names).toEqual(['get_agent_job', 'request_tools', 'submit_agent']);
+ // #4098: the generic queue ops (get/list/progress/cancel) are
+ // agentCallable with an owner-client fence, so the honest agent-lane
+ // catalog includes them alongside the submit_agent/get_agent_job pair.
+ expect(names).toEqual([
+ 'cancel_job', 'get_agent_job', 'get_job', 'get_job_progress',
+ 'list_jobs', 'request_tools', 'submit_agent',
+ ]);
});
test('D9: a slug-bound client keeps discovery; unfenceable writes stay hidden', async () => {
diff --git a/test/resolve-ipc-engine-uniform.test.ts b/test/resolve-ipc-engine-uniform.test.ts
new file mode 100644
index 0000000000..fc6ec06bc3
--- /dev/null
+++ b/test/resolve-ipc-engine-uniform.test.ts
@@ -0,0 +1,153 @@
+/**
+ * test/resolve-ipc-engine-uniform.test.ts — #4245 (TODOS "engine-uniform
+ * IPC listener").
+ *
+ * Postgres brains have no PGLite data dir, so their serve IPC socket +
+ * turn_context secret key off hash12(database_url) under ~/.gbrain/run
+ * (0700). PGLite brains keep the data-dir socket unchanged (old serves and
+ * hooks keep pairing). A postgres config carrying a LEFTOVER database_path
+ * must never key off the path (the v0.45.7 gate, preserved).
+ */
+
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { mkdtempSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ ensureIpcSecretForConfig,
+ ipcRunDir,
+ ipcSecretPath,
+ ipcSecretPathForConfig,
+ readIpcSecretForConfig,
+ resolveSocketPath,
+ resolveSocketPathForConfig,
+ startResolveIpcServer,
+ resolveViaIpc,
+ IPC_UNAVAILABLE,
+} from '../src/core/context/resolve-ipc.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const URL_A = 'postgresql://user:[email protected]:5432/brain_a';
+const URL_B = 'postgresql://user:[email protected]:5432/brain_b';
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-ipc-uniform-'));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Every assertion runs with GBRAIN_HOME pointed at this test's sandbox dir. */
+const inSandboxHome = <T>(fn: () => T | Promise<T>) => withEnv({ GBRAIN_HOME: tmp }, fn);
+
+describe('resolveSocketPathForConfig (#4245)', () => {
+ it('returns null when there is no keying material', async () => {
+ await inSandboxHome(() => {
+ expect(resolveSocketPathForConfig(null)).toBeNull();
+ expect(resolveSocketPathForConfig(undefined)).toBeNull();
+ expect(resolveSocketPathForConfig({ engine: 'postgres' })).toBeNull();
+ expect(resolveSocketPathForConfig({ engine: 'pglite' })).toBeNull();
+ });
+ });
+
+ it('pglite keeps the data-dir socket (wire location unchanged)', async () => {
+ await inSandboxHome(() => {
+ const dataDir = join(tmp, 'db');
+ expect(resolveSocketPathForConfig({ engine: 'pglite', database_path: dataDir })).toBe(
+ resolveSocketPath(dataDir),
+ );
+ });
+ });
+
+ it('postgres keys a run-dir socket off hash12(database_url), no credentials in the path', async () => {
+ await inSandboxHome(() => {
+ const p = resolveSocketPathForConfig({ engine: 'postgres', database_url: URL_A });
+ expect(p).not.toBeNull();
+ expect(p!.startsWith(ipcRunDir())).toBe(true);
+ expect(p!).toMatch(/\/resolve-[0-9a-f]{12}\.sock$/);
+ expect(p!).not.toContain('hunter2');
+ // Deterministic: both ends (serve + hook) derive the identical path.
+ expect(resolveSocketPathForConfig({ engine: 'postgres', database_url: URL_A })).toBe(p!);
+ // Two brains on one machine never share a socket.
+ expect(resolveSocketPathForConfig({ engine: 'postgres', database_url: URL_B })).not.toBe(p!);
+ });
+ });
+
+ it('a postgres config with a LEFTOVER database_path never keys off the path (v0.45.7 gate)', async () => {
+ await inSandboxHome(() => {
+ const leftover = join(tmp, 'stale-pglite-dir');
+ expect(
+ resolveSocketPathForConfig({ engine: 'postgres', database_path: leftover }),
+ ).toBeNull();
+ // With a URL present, the URL wins — the leftover path is ignored.
+ const p = resolveSocketPathForConfig({
+ engine: 'postgres',
+ database_path: leftover,
+ database_url: URL_A,
+ });
+ expect(p!.startsWith(ipcRunDir())).toBe(true);
+ expect(p!).not.toContain(leftover);
+ });
+ });
+});
+
+describe('ipcSecretPathForConfig + ensure/read (#4245)', () => {
+ it('pglite keeps the data-dir secret path', async () => {
+ await inSandboxHome(() => {
+ const dataDir = join(tmp, 'db');
+ expect(ipcSecretPathForConfig({ engine: 'pglite', database_path: dataDir })).toBe(
+ ipcSecretPath(dataDir),
+ );
+ });
+ });
+
+ it('postgres provisions a hash-keyed secret under the 0700 run dir, mode 0600', async () => {
+ await inSandboxHome(() => {
+ const cfg = { engine: 'postgres' as const, database_url: URL_A };
+ expect(readIpcSecretForConfig(cfg)).toBeNull(); // absent until a serve provisions it
+ const secret = ensureIpcSecretForConfig(cfg);
+ expect(secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(readIpcSecretForConfig(cfg)).toBe(secret!);
+ // Idempotent: a second serve reads the same secret back.
+ expect(ensureIpcSecretForConfig(cfg)).toBe(secret!);
+ const secretFile = ipcSecretPathForConfig(cfg)!;
+ expect(secretFile.startsWith(ipcRunDir())).toBe(true);
+ expect(statSync(secretFile).mode & 0o777).toBe(0o600);
+ expect(statSync(ipcRunDir()).mode & 0o777).toBe(0o700);
+ // Different brain → different secret file.
+ expect(ipcSecretPathForConfig({ engine: 'postgres', database_url: URL_B })).not.toBe(secretFile);
+ });
+ });
+
+ it('returns null with no keying material (never throws, never guesses)', async () => {
+ await inSandboxHome(() => {
+ expect(ensureIpcSecretForConfig(null)).toBeNull();
+ expect(ensureIpcSecretForConfig({ engine: 'postgres' })).toBeNull();
+ expect(readIpcSecretForConfig({ engine: 'postgres' })).toBeNull();
+ });
+ });
+});
+
+describe('postgres run-dir socket is servable end to end (#4245)', () => {
+ it('a server bound at the config-keyed path answers a resolve round-trip', async () => {
+ await inSandboxHome(async () => {
+ const cfg = { engine: 'postgres' as const, database_url: URL_A };
+ const sock = resolveSocketPathForConfig(cfg)!;
+ const server = await startResolveIpcServer(sock, async () => ({
+ text: 'pointer-block',
+ pointers: [],
+ }) as never);
+ expect(server).not.toBeNull();
+ try {
+ const res = await resolveViaIpc(sock, { candidates: [] });
+ expect(res).not.toBe(IPC_UNAVAILABLE);
+ expect((res as { text: string }).text).toBe('pointer-block');
+ } finally {
+ server?.close();
+ }
+ });
+ });
+});
diff --git a/test/retrieval-reflex-recipe-routing.test.ts b/test/retrieval-reflex-recipe-routing.test.ts
new file mode 100644
index 0000000000..76a9bff91b
--- /dev/null
+++ b/test/retrieval-reflex-recipe-routing.test.ts
@@ -0,0 +1,78 @@
+/**
+ * test/retrieval-reflex-recipe-routing.test.ts — #4292 routing MECE.
+ *
+ * The retrieval-reflex recipe ships a policy SKILL.md into the host
+ * resolver. Its triggers must be REFLEX-ONLY: the direct lookup phrases
+ * ("who is", "what do we know about", "tell me about") belong to the
+ * query skill (skills/RESOLVER.md + skills/query/SKILL.md). When both
+ * skills claim the same phrase, host routing becomes ambiguous and
+ * queries misroute silently.
+ *
+ * Also pins the install pointer honesty half of #4292: `gbrain
+ * integrations install` prints "next steps: see
+ * recipes/<id>/install/post-install-hint.md" — that pointer must be
+ * gated on the file actually existing (and retrieval-reflex now ships
+ * one).
+ */
+
+import { describe, expect, it } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import matter from 'gray-matter';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const RECIPE_ROOT = join(REPO_ROOT, 'recipes', 'retrieval-reflex');
+
+/** The query skill owns these direct-lookup phrases (skills/RESOLVER.md). */
+const QUERY_SKILL_PHRASES = ['who is', 'what do we know about', 'tell me about', 'search for', 'background on', 'notes on'];
+
+describe('retrieval-reflex recipe routing is MECE with the query skill (#4292)', () => {
+ it('SKILL.md frontmatter triggers carry no query-skill lookup phrases', () => {
+ const skillPath = join(RECIPE_ROOT, 'skills', 'retrieval-reflex', 'SKILL.md');
+ const fm = matter(readFileSync(skillPath, 'utf8'));
+ const triggers: unknown = fm.data.triggers;
+ expect(Array.isArray(triggers)).toBe(true);
+ expect((triggers as unknown[]).length).toBeGreaterThan(0);
+ for (const trigger of triggers as unknown[]) {
+ expect(typeof trigger).toBe('string');
+ const lower = (trigger as string).toLowerCase();
+ for (const phrase of QUERY_SKILL_PHRASES) {
+ expect(lower).not.toContain(phrase);
+ }
+ }
+ });
+
+ it('the query skill still owns "who is" (the phrases moved, not vanished)', () => {
+ const querySkill = readFileSync(join(REPO_ROOT, 'skills', 'query', 'SKILL.md'), 'utf8');
+ expect(querySkill.toLowerCase()).toContain('"who is"');
+ });
+
+ it('install manifest resolver row carries no query-skill lookup phrases', () => {
+ const manifest = JSON.parse(readFileSync(join(RECIPE_ROOT, 'install', 'manifest.json'), 'utf8')) as {
+ resolver_rows_to_append?: string[];
+ };
+ const rows = manifest.resolver_rows_to_append ?? [];
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ const lower = row.toLowerCase();
+ for (const phrase of QUERY_SKILL_PHRASES) {
+ expect(lower).not.toContain(phrase);
+ }
+ }
+ });
+
+ it('retrieval-reflex ships the post-install hint the install pointer names', () => {
+ expect(existsSync(join(RECIPE_ROOT, 'install', 'post-install-hint.md'))).toBe(true);
+ });
+
+ it('the install pointer is gated on the hint file existing (source guard)', () => {
+ const src = readFileSync(join(REPO_ROOT, 'src', 'commands', 'integrations.ts'), 'utf8');
+ // The "next steps" pointer must not print unconditionally: a recipe
+ // without a post-install-hint.md would send the operator to a 404.
+ const pointerIdx = src.indexOf("next steps: see recipes/");
+ expect(pointerIdx).toBeGreaterThan(-1);
+ const window = src.slice(Math.max(0, pointerIdx - 400), pointerIdx);
+ expect(window).toContain('post-install-hint.md');
+ expect(window).toContain('existsSync');
+ });
+});
diff --git a/test/retrieval-reflex.test.ts b/test/retrieval-reflex.test.ts
index 688758ef0f..6465f65e2a 100644
--- a/test/retrieval-reflex.test.ts
+++ b/test/retrieval-reflex.test.ts
@@ -671,3 +671,85 @@ describe('v0.46.15 ship-review hardening (adversarial F1/F2 + stale-alias veto)'
expect(block).toBeNull();
});
});
+
+describe('#3746 — cjk-title arm (pure-CJK weak norms probe exact title/slug)', () => {
+ test('japanese: unregistered-alias page resolves via exact title', async () => {
+ await seed('people/tanaka', '田中', '田中 is a partner at fund-a.');
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('田中さんの会議のメモを見せて'),
+ {},
+ );
+ expect(block).not.toBeNull();
+ expect(block!.pointers[0].slug).toBe('people/tanaka');
+ expect(block!.pointers[0].arm).toBe('cjk-title');
+ expect(block!.pointers[0].confidence).toBeGreaterThanOrEqual(0.7); // survives the volunteer gate
+ expect(block!.pointers[0].matchedNorm).toBe(normalizeAlias('田中'));
+ });
+
+ test('korean: registered CJK alias resolves through the alias arm (0.9)', async () => {
+ await seed('people/kim-chulsoo', 'Kim Chulsoo', 'A founder.');
+ await engine.setPageAliases('people/kim-chulsoo', 'default', [normalizeAlias('김철수')]);
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('김철수 미팅 노트 보여줘'),
+ {},
+ );
+ expect(block).not.toBeNull();
+ expect(block!.pointers[0].slug).toBe('people/kim-chulsoo');
+ expect(block!.pointers[0].arm).toBe('alias');
+ });
+
+ test('chinese: exact CJK slug resolves when the title differs', async () => {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ('王小明', 'default', 'person', 'Wang Xiaoming', 'A researcher.', '')`,
+ [],
+ );
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('给我看看王小明的笔记'),
+ {},
+ );
+ expect(block).not.toBeNull();
+ expect(block!.pointers[0].slug).toBe('王小明');
+ expect(block!.pointers[0].arm).toBe('cjk-title');
+ });
+
+ test('no matching page → resolves nothing (junk grams never fabricate)', async () => {
+ await seed('people/unrelated', 'Unrelated Person', 'Nothing CJK here.');
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('田中さんの会議のメモを見せて'),
+ {},
+ );
+ expect(block).toBeNull();
+ });
+
+ test('ambiguous gram (two pages share the title) injects nothing', async () => {
+ await seed('people/tanaka-a', '田中', 'First 田中.');
+ await seed('people/tanaka-b', '田中', 'Second 田中.');
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('田中さんの会議のメモを見せて'),
+ {},
+ );
+ expect(block).toBeNull();
+ });
+
+ test('kill switch: lexicalArms=false disables the cjk-title arm', async () => {
+ await seed('people/tanaka', '田中', '田中 is a partner.');
+ const block = await resolveEntitiesToPointers(
+ engine,
+ 'default',
+ extractCandidates('田中さんの会議のメモを見せて'),
+ { lexicalArms: false },
+ );
+ expect(block).toBeNull();
+ });
+});
diff --git a/test/rrf-source-key.test.ts b/test/rrf-source-key.test.ts
index 245682d25e..a3c2e92e36 100644
--- a/test/rrf-source-key.test.ts
+++ b/test/rrf-source-key.test.ts
@@ -68,3 +68,48 @@ describe('RRF key is source-aware', () => {
expect(out.length).toBe(2);
});
});
+
+describe('#3783 — keyword_hit OR-propagation through fusion', () => {
+ test('rrfFusionWeighted: vector copy seen FIRST, keyword copy merges later → fused row keeps the flag', () => {
+ const vectorCopy = makeResult({ slug: 'a', chunk_id: 1, source_id: 'default' });
+ const keywordCopy = makeResult({ slug: 'a', chunk_id: 1, source_id: 'default', keyword_hit: true });
+ const out = rrfFusionWeighted([
+ { list: [vectorCopy], k: 60 },
+ { list: [keywordCopy], k: 60 },
+ ]);
+ expect(out.length).toBe(1);
+ expect(out[0].keyword_hit).toBe(true);
+ });
+
+ test('rrfFusionWeighted: keyword copy seen FIRST also keeps the flag', () => {
+ const keywordCopy = makeResult({ slug: 'a', chunk_id: 1, keyword_hit: true });
+ const vectorCopy = makeResult({ slug: 'a', chunk_id: 1 });
+ const out = rrfFusionWeighted([
+ { list: [keywordCopy], k: 60 },
+ { list: [vectorCopy], k: 60 },
+ ]);
+ expect(out.length).toBe(1);
+ expect(out[0].keyword_hit).toBe(true);
+ });
+
+ test('rrfFusionWeighted: a vector-only row does NOT gain the flag', () => {
+ const vectorOnly = makeResult({ slug: 'v', chunk_id: 2 });
+ const out = rrfFusionWeighted([{ list: [vectorOnly], k: 60 }]);
+ expect(out[0].keyword_hit).not.toBe(true);
+ });
+
+ test('rrfFusion: OR-propagation across plain lists too', () => {
+ const vectorCopy = makeResult({ slug: 'a', chunk_id: 1 });
+ const keywordCopy = makeResult({ slug: 'a', chunk_id: 1, keyword_hit: true });
+ const out = rrfFusion([[vectorCopy], [keywordCopy]], 60);
+ expect(out.length).toBe(1);
+ expect(out[0].keyword_hit).toBe(true);
+ });
+
+ test('fusion does not mutate the input list rows (flag lands on the fused copy)', () => {
+ const vectorCopy = makeResult({ slug: 'a', chunk_id: 1 });
+ const keywordCopy = makeResult({ slug: 'a', chunk_id: 1, keyword_hit: true });
+ rrfFusionWeighted([{ list: [vectorCopy], k: 60 }, { list: [keywordCopy], k: 60 }]);
+ expect(vectorCopy.keyword_hit).toBeUndefined();
+ });
+});
diff --git a/test/scripts/run-verify-parallel.test.ts b/test/scripts/run-verify-parallel.test.ts
index fae4b76f9d..c7aba80661 100644
--- a/test/scripts/run-verify-parallel.test.ts
+++ b/test/scripts/run-verify-parallel.test.ts
@@ -78,6 +78,8 @@ describe("guard registration ⇒ execution coverage", () => {
"duplicates check:admin-build's vite+tsc build; embed freshness covered there",
"check-image-decoders-embedded.sh":
"runs its own bun build --compile — too heavy for per-verify cadence",
+ "check-test-discriminates.sh":
+ "manual per-PR discrimination helper (#3665): reverts named source files and re-runs bun test to prove the test fails without the fix — cannot know which hunk is 'the fix' on an arbitrary diff, so deliberately not in verify/CI (manifest row says the same)",
};
it("every manifest guard is executed by verify or explicitly exempt", () => {
diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.ts
index de37f3a648..91b7a53c3b 100644
--- a/test/search-alias-resolved-boost.test.ts
+++ b/test/search-alias-resolved-boost.test.ts
@@ -89,7 +89,9 @@ describe('alias_resolved boost stage', () => {
});
describe('KNOBS_HASH_VERSION', () => {
- it('is 21 (17→18 autocut weak-top floor #1863; 18→19 ack= autocut minKeep floor #3621; 19→20 pre-fusion pool floor #3002; 20→21 recency fallback re-key #895)', () => {
- expect(KNOBS_HASH_VERSION).toBe(21);
+ 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)', () => {
+ // 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);
});
});
diff --git a/test/search-mode.test.ts b/test/search-mode.test.ts
index 5cabc8f2e4..b37582d43b 100644
--- a/test/search-mode.test.ts
+++ b/test/search-mode.test.ts
@@ -435,7 +435,14 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {
// #3621: bumped 18→19 to fold the autocut minKeep floor (ack=).
// #895: bumped 19→21 — recency DEFAULT_FALLBACK 0.5→0.3 reorders cached
// rows (19→20 pool floor #3002, 20→21 recency fallback #895, same release).
- expect(KNOBS_HASH_VERSION).toBe(21);
+ // mw2: 21→22 — #1663 exact-lookup injection + #3995 relational slot +
+ // #3783/#4220 stamps alter stored rows for identical knobs.
+ // #4352 follow-up: bumped 22→23 to fold the private-visibility posture
+ // (xp=) — replaces the wholesale skipCache bypass that disabled the
+ // 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);
});
test('#3515: detail set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {
@@ -455,7 +462,26 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {
// v0.46.15 (#1863): 17→18 — autocut weak-top floor folds in (acm=).
// #3621: 18→19 — autocut minKeep floor folds in (ack=).
// 19→20 pool floor (#3002); 20→21 recency fallback re-key (#895).
- expect(KNOBS_HASH_VERSION).toBe(21);
+ // 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);
+ });
+
+ test('#4352 follow-up: excludePrivate true vs false produces DIFFERENT hashes (cache contamination prevention)', () => {
+ // The private-visibility posture folds into the key (xp=) instead of
+ // wholesale-skipping the cache: excludePrivate=true is the DEFAULT for
+ // every remote MCP caller, so the skip disabled the semantic cache for
+ // exactly the highest-volume beneficiaries. A private-included (trusted)
+ // write must never serve a private-excluding lookup and vice versa.
+ const knobs = resolveSearchMode({ mode: 'balanced' });
+ const excluding = knobsHash(knobs, { excludePrivate: true });
+ const including = knobsHash(knobs, { excludePrivate: false });
+ const unset = knobsHash(knobs);
+ expect(excluding).not.toBe(including);
+ // Undefined hashes like false (private included) — mirrors enforcement's
+ // strict `=== true` predicate, so legacy callers that don't thread the
+ // posture share the trusted (private-included) rows.
+ expect(unset).toBe(including);
});
test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {
@@ -620,8 +646,8 @@ describe('v0.40.4 — graph_signals knob', () => {
});
describe('v0.42.3.0 — autocut knobs', () => {
- test('KNOBS_HASH_VERSION is 21 (17→18 autocut weak-top floor #1863; 18→19 autocut minKeep floor #3621; 19→21 recency fallback re-key #895, v=20 claimed by wave-D)', () => {
- expect(KNOBS_HASH_VERSION).toBe(21);
+ 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('bundle defaults: conservative off, balanced/tokenmax on @0.20', () => {
diff --git a/test/search-snippet-cap.test.ts b/test/search-snippet-cap.test.ts
new file mode 100644
index 0000000000..af1793ec72
--- /dev/null
+++ b/test/search-snippet-cap.test.ts
@@ -0,0 +1,140 @@
+/**
+ * #3800 — subagent token economy: snippet_chars param + agent.search_snippet_chars
+ * config cap search/query chunk_text payloads for subagent tool loops.
+ *
+ * Pins: helper truncation semantics, subagent default (300), param beats
+ * config, non-subagent callers keep full text, 0 = full text.
+ */
+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';
+import { applySnippetCap, buildSnippetMarker, DEFAULT_AGENT_SNIPPET_CHARS } from '../src/core/search/snippet-cap.ts';
+import type { SearchResult } from '../src/core/types.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const searchOp = operations.find((o) => o.name === 'search')!;
+const LONG_TEXT = `walrus fanfare ${'x'.repeat(600)} tail-marker-end`;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as never,
+ config: {} as never,
+ logger: console as never,
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ ...overrides,
+ } as OperationContext;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.putPage('notes/walrus', {
+ type: 'note', title: 'Walrus fanfare', compiled_truth: LONG_TEXT, frontmatter: {},
+ });
+ await engine.upsertChunks('notes/walrus', [
+ { chunk_index: 0, chunk_text: LONG_TEXT, chunk_source: 'compiled_truth' },
+ ]);
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('applySnippetCap helper (#3800)', () => {
+ test('truncates chunk_text only and appends the get_page marker', () => {
+ const rows = [{ slug: 'a/b', chunk_text: '0123456789', title: 'keep-me' }];
+ const out = applySnippetCap(rows, 4);
+ expect(out[0].chunk_text).toBe('0123' + buildSnippetMarker('a/b', 6));
+ expect(out[0].title).toBe('keep-me');
+ // Non-mutating: the input object is untouched (pending cache writes may
+ // still hold a reference to it).
+ expect(rows[0].chunk_text).toBe('0123456789');
+ });
+
+ test('short text and cap<=0 are identity (same array back)', () => {
+ const rows = [{ slug: 'a/b', chunk_text: 'short' }];
+ expect(applySnippetCap(rows, 10)).toBe(rows);
+ const long = [{ slug: 'a/b', chunk_text: 'x'.repeat(50) }];
+ expect(applySnippetCap(long, 0)).toBe(long);
+ expect(applySnippetCap(long, Number.NaN)).toBe(long);
+ });
+});
+
+describe('search op snippet cap (#3800)', () => {
+ test('non-subagent callers keep full text', async () => {
+ const out = (await searchOp.handler(ctxOf(), { query: 'walrus fanfare' })) as SearchResult[];
+ expect(out.length).toBe(1);
+ expect(out[0].chunk_text).toBe(LONG_TEXT);
+ });
+
+ test('subagent callers default to the 300-char config default', async () => {
+ const out = (await searchOp.handler(ctxOf({ viaSubagent: true }), { query: 'walrus fanfare' })) as SearchResult[];
+ expect(out.length).toBe(1);
+ expect(out[0].chunk_text!.startsWith(LONG_TEXT.slice(0, DEFAULT_AGENT_SNIPPET_CHARS))).toBe(true);
+ expect(out[0].chunk_text!.length).toBeLessThan(LONG_TEXT.length);
+ expect(out[0].chunk_text).toContain('get_page notes/walrus');
+ });
+
+ test('agent.search_snippet_chars config governs the subagent default', async () => {
+ await engine.setConfig('agent.search_snippet_chars', '50');
+ try {
+ const out = (await searchOp.handler(ctxOf({ viaSubagent: true }), { query: 'walrus fanfare' })) as SearchResult[];
+ expect(out[0].chunk_text!.startsWith(LONG_TEXT.slice(0, 50))).toBe(true);
+ expect(out[0].chunk_text!).toContain('truncated');
+ } finally {
+ await engine.setConfig('agent.search_snippet_chars', '');
+ }
+ });
+
+ test('explicit snippet_chars param beats the config', async () => {
+ await engine.setConfig('agent.search_snippet_chars', '50');
+ try {
+ const out = (await searchOp.handler(ctxOf({ viaSubagent: true }), { query: 'walrus fanfare', snippet_chars: 20 })) as SearchResult[];
+ expect(out[0].chunk_text!.startsWith(LONG_TEXT.slice(0, 20))).toBe(true);
+ expect(out[0].chunk_text!.slice(0, 30)).not.toBe(LONG_TEXT.slice(0, 30));
+ } finally {
+ await engine.setConfig('agent.search_snippet_chars', '');
+ }
+ });
+
+ test('snippet_chars 0 forces full text even for subagents with a config cap', async () => {
+ await engine.setConfig('agent.search_snippet_chars', '50');
+ try {
+ const out = (await searchOp.handler(ctxOf({ viaSubagent: true }), { query: 'walrus fanfare', snippet_chars: 0 })) as SearchResult[];
+ expect(out[0].chunk_text).toBe(LONG_TEXT);
+ } finally {
+ await engine.setConfig('agent.search_snippet_chars', '');
+ }
+ });
+
+ test('param applies to non-subagent callers too (explicit ask wins)', async () => {
+ const out = (await searchOp.handler(ctxOf(), { query: 'walrus fanfare', snippet_chars: 25 })) as SearchResult[];
+ expect(out[0].chunk_text!.startsWith(LONG_TEXT.slice(0, 25))).toBe(true);
+ expect(out[0].chunk_text!).toContain('truncated');
+ });
+});
+
+describe('query op snippet cap (#3800)', () => {
+ const queryOp = operations.find((o) => o.name === 'query')!;
+
+ test('subagent default cap applies on the query op (no-provider hybrid path)', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ const out = (await queryOp.handler(ctxOf({ viaSubagent: true }), { query: 'walrus fanfare', expand: false })) as SearchResult[];
+ expect(out.length).toBe(1);
+ expect(out[0].chunk_text!.length).toBeLessThan(LONG_TEXT.length);
+ expect(out[0].chunk_text!).toContain('get_page notes/walrus');
+ });
+ });
+
+ test('non-subagent query keeps full text', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ const out = (await queryOp.handler(ctxOf(), { query: 'walrus fanfare', expand: false })) as SearchResult[];
+ expect(out[0].chunk_text).toBe(LONG_TEXT);
+ });
+ });
+});
diff --git a/test/search/crag-query-op.test.ts b/test/search/crag-query-op.test.ts
new file mode 100644
index 0000000000..bb8b0ee5fb
--- /dev/null
+++ b/test/search/crag-query-op.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #1663 — CRAG gate behavior on the `query` op (hermetic PGLite, keyless:
+ * the keyword-only fallback path). Pins:
+ * - the crag block rides the retrieval response meta on EVERY call
+ * - a slug-identity query grades strong end-to-end (exact-lookup tier)
+ * - weak + search.crag_escalation=true → one high-ceiling re-run
+ * - weak without the config → no re-run, hint only (default OFF)
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import type { CragMetaBlock } from '../../src/core/search/crag.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+function ctxWithMeta(): { ctx: OperationContext; meta: Record<string, unknown> } {
+ const meta: Record<string, unknown> = {};
+ const ctx = {
+ engine,
+ remote: false,
+ sourceId: 'default',
+ emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },
+ } as unknown as OperationContext;
+ return { ctx, meta };
+}
+
+function cragOf(meta: Record<string, unknown>): CragMetaBlock {
+ const retrieval = meta.retrieval as { crag?: CragMetaBlock } | undefined;
+ expect(retrieval).toBeDefined();
+ expect(retrieval!.crag).toBeDefined();
+ return retrieval!.crag!;
+}
+
+describe('query op — CRAG gate (#1663)', () => {
+ test('crag block is attached on every call (grade + query shape)', async () => {
+ await engine.putPage('notes/kelpie-workshop', {
+ type: 'note', title: 'Kelpie Workshop', compiled_truth: 'A note about the kelpie workshop agenda.',
+ });
+ const { ctx, meta } = ctxWithMeta();
+ await operationsByName.query.handler(ctx, { query: 'kelpie workshop agenda' });
+ const crag = cragOf(meta);
+ expect(['strong', 'moderate', 'weak']).toContain(crag.confidence);
+ expect(['factual', 'open']).toContain(crag.query_shape);
+ expect(typeof crag.reason).toBe('string');
+ });
+
+ test('slug-identity query grades strong end-to-end (exact-lookup tier through the op)', async () => {
+ await engine.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example', compiled_truth: 'Founder of widget-co.',
+ });
+ const { ctx, meta } = ctxWithMeta();
+ const results = (await operationsByName.query.handler(ctx, {
+ query: 'people/alice-example',
+ })) as Array<{ slug: string; exact_lookup?: string }>;
+ expect(results[0]?.slug).toBe('people/alice-example');
+ expect(results[0]?.exact_lookup).toBe('slug');
+ const crag = cragOf(meta);
+ expect(crag.confidence).toBe('strong');
+ expect(crag.reason).toBe('exact_lookup');
+ });
+
+ test('weak result WITHOUT config: no escalation, think hint only (default OFF)', async () => {
+ const { ctx, meta } = ctxWithMeta();
+ await operationsByName.query.handler(ctx, { query: 'zxqv nonexistent quux' });
+ const crag = cragOf(meta);
+ expect(crag.confidence).toBe('weak');
+ expect(crag.escalated).toBeUndefined();
+ expect(crag.escalate_to_think).toBe(true);
+ });
+
+ test('weak result + search.crag_escalation=true: one high-ceiling re-run fires', async () => {
+ await engine.setConfig('search.crag_escalation', 'true');
+ const { ctx, meta } = ctxWithMeta();
+ await operationsByName.query.handler(ctx, { query: 'zxqv nonexistent quux' });
+ const crag = cragOf(meta);
+ // Keyless corpus with no match: escalation ran and honestly stayed weak.
+ expect(crag.escalated).toBe(true);
+ expect(crag.escalated_confidence).toBe('weak');
+ expect(crag.confidence).toBe('weak');
+ expect(crag.escalate_to_think).toBe(true);
+ }, 30000);
+
+ test('escalation can rescue: identity page invisible to page-1 keyword rank still grades strong via the wide re-run', async () => {
+ // Sanity-bound version: with the tier + escalation both on, a present
+ // page keeps strong confidence and never regresses via the re-run.
+ await engine.setConfig('search.crag_escalation', 'true');
+ await engine.putPage('projects/mingtang', {
+ type: 'note', title: 'The Mingtang', compiled_truth: 'Indoor amphitheater notes.',
+ });
+ const { ctx, meta } = ctxWithMeta();
+ const results = (await operationsByName.query.handler(ctx, {
+ query: 'projects/mingtang',
+ })) as Array<{ slug: string }>;
+ expect(results[0]?.slug).toBe('projects/mingtang');
+ const crag = cragOf(meta);
+ expect(crag.confidence).toBe('strong');
+ expect(crag.escalated).toBeUndefined(); // strong first pass → no re-run
+ });
+});
diff --git a/test/search/crag.test.ts b/test/search/crag.test.ts
new file mode 100644
index 0000000000..1cbc728b17
--- /dev/null
+++ b/test/search/crag.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #1663 — CRAG confidence grading (pure). The gate the `query` op keys its
+ * meta + escalation off. No engine, no LLM — fast parallel loop.
+ */
+import { describe, test, expect } from 'bun:test';
+import {
+ gradeRetrievalConfidence,
+ shouldEscalateRetrieval,
+ confidenceRank,
+ DEFAULT_CRAG_MIN_TOP,
+} from '../../src/core/search/crag.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+
+function r(partial: Partial<SearchResult>): SearchResult {
+ return {
+ slug: 's', title: 't', chunk_text: '', type: 'note', source_id: 'default',
+ chunk_index: 0, chunk_id: 1, score: 0.5, ...partial,
+ } as SearchResult;
+}
+
+describe('gradeRetrievalConfidence (#1663)', () => {
+ test('zero results → weak / zero_results', () => {
+ expect(gradeRetrievalConfidence([])).toEqual({ level: 'weak', reason: 'zero_results' });
+ });
+
+ test('identity-tier top signals are strong', () => {
+ expect(gradeRetrievalConfidence([r({ exact_lookup: 'slug' })]).level).toBe('strong');
+ expect(gradeRetrievalConfidence([r({ exact_lookup: 'slug' })]).reason).toBe('exact_lookup');
+ expect(gradeRetrievalConfidence([r({ alias_hit: true })]).reason).toBe('alias_hit');
+ expect(gradeRetrievalConfidence([r({ evidence: 'exact_title_match' })]).reason).toBe('exact_title_match');
+ expect(gradeRetrievalConfidence([r({ evidence: 'high_vector_match' })]).reason).toBe('high_vector_match');
+ });
+
+ test('reranked top at/above the floor is strong; below is weak', () => {
+ const strong = gradeRetrievalConfidence([r({ rerank_score: DEFAULT_CRAG_MIN_TOP })]);
+ expect(strong.level).toBe('strong');
+ expect(strong.reason).toBe('rerank_top');
+ expect(strong.top_rerank_score).toBe(DEFAULT_CRAG_MIN_TOP);
+
+ const weak = gradeRetrievalConfidence([r({ rerank_score: 0.05, evidence: 'weak_semantic' })]);
+ expect(weak.level).toBe('weak');
+ expect(weak.reason).toBe('rerank_top_below_floor');
+ });
+
+ test('floor is overridable', () => {
+ expect(gradeRetrievalConfidence([r({ rerank_score: 0.15 })], { minTopScore: 0.1 }).level).toBe('strong');
+ expect(gradeRetrievalConfidence([r({ rerank_score: 0.15 })], { minTopScore: 0.3 }).level).toBe('weak');
+ });
+
+ test('no reranker: keyword_exact top is moderate; weak_semantic top is weak', () => {
+ expect(gradeRetrievalConfidence([r({ evidence: 'keyword_exact' })])).toMatchObject({
+ level: 'moderate',
+ reason: 'keyword_exact_top',
+ });
+ expect(gradeRetrievalConfidence([r({ evidence: 'weak_semantic' })])).toMatchObject({
+ level: 'weak',
+ reason: 'weak_semantic_top',
+ });
+ });
+
+ test('only rank-1 drives the grade (a weak tail below a strong top is fine)', () => {
+ const g = gradeRetrievalConfidence([
+ r({ evidence: 'high_vector_match' }),
+ r({ evidence: 'weak_semantic' }),
+ r({ evidence: 'weak_semantic' }),
+ ]);
+ expect(g.level).toBe('strong');
+ });
+});
+
+describe('shouldEscalateRetrieval / confidenceRank (#1663)', () => {
+ test('escalates only when enabled, weak, and not already escalated', () => {
+ const weak = gradeRetrievalConfidence([]);
+ expect(shouldEscalateRetrieval(weak, { enabled: true })).toBe(true);
+ expect(shouldEscalateRetrieval(weak, { enabled: false })).toBe(false);
+ expect(shouldEscalateRetrieval(weak, { enabled: true, alreadyEscalated: true })).toBe(false);
+ const strong = gradeRetrievalConfidence([r({ alias_hit: true })]);
+ expect(shouldEscalateRetrieval(strong, { enabled: true })).toBe(false);
+ });
+
+ test('rank ordering: strong > moderate > weak', () => {
+ expect(confidenceRank('strong')).toBeGreaterThan(confidenceRank('moderate'));
+ expect(confidenceRank('moderate')).toBeGreaterThan(confidenceRank('weak'));
+ });
+});
diff --git a/test/search/evidence.test.ts b/test/search/evidence.test.ts
index 56a55aebc4..46986ba151 100644
--- a/test/search/evidence.test.ts
+++ b/test/search/evidence.test.ts
@@ -5,7 +5,7 @@
*/
import { describe, test, expect } from 'bun:test';
-import { classifyEvidence, createSafetyFor, stampEvidence, HIGH_MATCH_FLOOR, SOLID_MATCH_FLOOR } from '../../src/core/search/evidence.ts';
+import { classifyEvidence, createSafetyFor, stampEvidence, markKeywordHits, HIGH_MATCH_FLOOR, SOLID_MATCH_FLOOR } from '../../src/core/search/evidence.ts';
import type { SearchResult } from '../../src/core/types.ts';
function r(partial: Partial<SearchResult>): SearchResult {
@@ -19,40 +19,62 @@ describe('classifyEvidence precedence', () => {
test('exact_title_match when title boost fired', () => {
expect(classifyEvidence(r({ title_match_boost: 1.25, base_score: 0.2 }))).toBe('exact_title_match');
});
- test('RE-PINNED (v0.46.15, #3963): a high BLENDED score without a real cosine is NOT a vector match', () => {
- // Was: base_score >= HIGH_MATCH_FLOOR → high_vector_match. That let a
- // keyword+boost pile-up read as confident semantic evidence (the exact
- // bug class this wave fixes). Without a cosine, the ceiling is
- // keyword_exact / create_safety 'probable' — the safe direction.
- expect(classifyEvidence(r({ base_score: HIGH_MATCH_FLOOR }))).toBe('keyword_exact');
- expect(classifyEvidence(r({ base_score: 0.90 }))).toBe('keyword_exact');
+ test('RE-PINNED (v0.46.15 #3963 + #3783): a high BLENDED score with neither cosine nor keyword hit is weak_semantic', () => {
+ // Was (v0.46.15): base_score >= SOLID_MATCH_FLOOR → keyword_exact with
+ // ZERO keyword verification. #3783: keyword_exact requires actual
+ // lexical-arm membership (keyword_hit). A pure-vector row with a solid
+ // blended score honestly reads weak_semantic / 'unknown'.
+ expect(classifyEvidence(r({ base_score: HIGH_MATCH_FLOOR }))).toBe('weak_semantic');
+ expect(classifyEvidence(r({ base_score: 0.90 }))).toBe('weak_semantic');
});
test('high_vector_match fires ONLY on a real cosine at/above the floor', () => {
expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.85 }))).toBe('high_vector_match');
expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.8 }))).toBe('high_vector_match');
- expect(classifyEvidence(r({ base_score: 0.95, cosine: 0.5 }))).toBe('keyword_exact');
+ expect(classifyEvidence(r({ base_score: 0.95, cosine: 0.5, keyword_hit: true }))).toBe('keyword_exact');
+ expect(classifyEvidence(r({ base_score: 0.95, cosine: 0.5 }))).toBe('weak_semantic');
});
test('cosine floor is overridable (per-model calibration knob)', () => {
expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.7 }), { cosineFloor: 0.65 })).toBe('high_vector_match');
expect(classifyEvidence(r({ base_score: 0.3, cosine: 0.7 }), { cosineFloor: 0.9 })).toBe('weak_semantic');
});
- test('keyword_exact in the solid band', () => {
- expect(classifyEvidence(r({ base_score: SOLID_MATCH_FLOOR }))).toBe('keyword_exact');
- expect(classifyEvidence(r({ base_score: 0.7 }))).toBe('keyword_exact');
+ test('#3783: keyword_exact requires a keyword hit AND the solid band', () => {
+ expect(classifyEvidence(r({ base_score: SOLID_MATCH_FLOOR, keyword_hit: true }))).toBe('keyword_exact');
+ expect(classifyEvidence(r({ base_score: 0.7, keyword_hit: true }))).toBe('keyword_exact');
+ // Solid band WITHOUT a keyword hit — the #3783 lie, now weak_semantic.
+ expect(classifyEvidence(r({ base_score: SOLID_MATCH_FLOOR }))).toBe('weak_semantic');
+ expect(classifyEvidence(r({ base_score: 0.7 }))).toBe('weak_semantic');
+ // Keyword hit BELOW the solid band stays weak_semantic (low-confidence tail).
+ expect(classifyEvidence(r({ base_score: 0.4, keyword_hit: true }))).toBe('weak_semantic');
});
test('weak_semantic below the solid floor (the incident: 0.64 body chunk... 0.5 here)', () => {
expect(classifyEvidence(r({ base_score: 0.4 }))).toBe('weak_semantic');
});
- test('RE-PINNED (v0.46.15): score fallback without cosine caps at keyword_exact', () => {
- expect(classifyEvidence(r({ score: 0.95, base_score: undefined }))).toBe('keyword_exact');
+ test('RE-PINNED (#3783): score fallback without cosine still honors the keyword-hit gate', () => {
+ expect(classifyEvidence(r({ score: 0.95, base_score: undefined, keyword_hit: true }))).toBe('keyword_exact');
+ expect(classifyEvidence(r({ score: 0.95, base_score: undefined }))).toBe('weak_semantic');
});
test('keyless fall-through: no cosine anywhere → create_safety never claims exists via vector', () => {
- const rs = [r({ base_score: 0.99 }), r({ base_score: 0.7 })];
+ const rs = [r({ base_score: 0.99, keyword_hit: true }), r({ base_score: 0.7, keyword_hit: true })];
stampEvidence(rs);
expect(rs[0].evidence).toBe('keyword_exact');
expect(rs[0].create_safety).toBe('probable'); // degraded from 'exists' — safe direction
expect(rs[1].create_safety).toBe('probable');
});
+ test('#3783: legacy rows without the keyword_hit field degrade to weak_semantic (safe direction)', () => {
+ // r() never sets keyword_hit — this models a legacy cached row.
+ const legacy = r({ base_score: 0.9 });
+ expect(legacy.keyword_hit).toBeUndefined();
+ expect(classifyEvidence(legacy)).toBe('weak_semantic');
+ });
+});
+
+describe('markKeywordHits (#3783)', () => {
+ test('stamps every row, idempotent', () => {
+ const rs = [r({}), r({ slug: 'b' })];
+ markKeywordHits(rs);
+ markKeywordHits(rs);
+ expect(rs.every(x => x.keyword_hit === true)).toBe(true);
+ });
});
describe('createSafetyFor', () => {
@@ -79,13 +101,20 @@ describe('stampEvidence', () => {
expect(rs[1].create_safety).toBe('unknown');
});
- test('the incident: a 0.64 body-chunk match reads as weak/unknown (agent should look closer, not blindly duplicate)', () => {
- const incident = r({ base_score: 0.64, score: 0.64 });
+ test('the incident: a 0.64 KEYWORD-hit body-chunk match reads as probable (prefer update over create)', () => {
+ const incident = r({ base_score: 0.64, score: 0.64, keyword_hit: true });
stampEvidence([incident]);
- expect(incident.evidence).toBe('keyword_exact'); // 0.64 is in the solid band
+ expect(incident.evidence).toBe('keyword_exact'); // 0.64 is in the solid band AND keyword-verified
expect(incident.create_safety).toBe('probable'); // not 'unknown' — prefer update over create
});
+ test('#3783: the same 0.64 WITHOUT a keyword hit reads weak/unknown (look closer, do not trust the blend)', () => {
+ const vectorOnly = r({ base_score: 0.64, score: 0.64 });
+ stampEvidence([vectorOnly]);
+ expect(vectorOnly.evidence).toBe('weak_semantic');
+ expect(vectorOnly.create_safety).toBe('unknown');
+ });
+
test('after the fix: the same page via alias/title reads as exists (do not duplicate)', () => {
const fixed = r({ base_score: 0.64, alias_hit: true });
stampEvidence([fixed]);
diff --git a/test/search/exact-lookup.test.ts b/test/search/exact-lookup.test.ts
new file mode 100644
index 0000000000..db6904e3f5
--- /dev/null
+++ b/test/search/exact-lookup.test.ts
@@ -0,0 +1,148 @@
+/**
+ * #1663 — structural exact-lookup tier (slug / exact-title identity
+ * resolution, supersession-filtered). Hermetic PGLite; the tier is tested
+ * directly (like alias-hop.test.ts) — no embedding provider needed.
+ */
+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 {
+ structuralExactLookup,
+ applyExactLookupTier,
+ isSlugShapedQuery,
+ EXACT_TITLE_STAMP,
+} from '../../src/core/search/exact-lookup.ts';
+import { _resetSupersedeProbeForTests } from '../../src/core/search/hybrid.ts';
+import { classifyEvidence } from '../../src/core/search/evidence.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetSupersedeProbeForTests();
+});
+
+function res(slug: string, score: number, extra: Partial<SearchResult> = {}): SearchResult {
+ return {
+ slug, title: slug, score, chunk_text: '', type: 'note', source_id: 'default',
+ chunk_index: 0, chunk_id: 1, ...extra,
+ } as unknown as SearchResult;
+}
+
+describe('isSlugShapedQuery', () => {
+ test('slug-shaped tokens qualify; prose and bare words do not', () => {
+ expect(isSlugShapedQuery('people/alice-example')).toBe(true);
+ expect(isSlugShapedQuery('alice example')).toBe(false);
+ expect(isSlugShapedQuery('alice')).toBe(false);
+ expect(isSlugShapedQuery('/leading')).toBe(false);
+ expect(isSlugShapedQuery('trailing/')).toBe(false);
+ });
+});
+
+describe('structuralExactLookup (#1663)', () => {
+ test('slug-shaped query resolves the page directly (evidence → exists)', async () => {
+ await engine.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example', compiled_truth: 'Founder of widget-co.',
+ });
+ const hits = await structuralExactLookup(engine, 'people/alice-example', { sourceId: 'default' });
+ expect(hits.length).toBe(1);
+ expect(hits[0].slug).toBe('people/alice-example');
+ expect(hits[0].exact_lookup).toBe('slug');
+ expect(hits[0].page_id).toBeGreaterThan(0);
+ // Evidence contract: identity match reads as 'exists' via alias_hit.
+ expect(classifyEvidence(hits[0])).toBe('alias_hit');
+ });
+
+ test('exact-title equality matches off the provided title arm (no extra query)', async () => {
+ await engine.putPage('projects/mingtang', {
+ type: 'note', title: 'The Mingtang', compiled_truth: 'Indoor amphitheater.',
+ });
+ const page = await engine.getPage('projects/mingtang', { sourceId: 'default' });
+ const titleArm = [res('projects/mingtang', 0.4, { title: 'The Mingtang', page_id: page!.id })];
+ const hits = await structuralExactLookup(engine, 'the mingtang', {
+ sourceId: 'default',
+ titleCandidates: titleArm,
+ });
+ expect(hits.length).toBe(1);
+ expect(hits[0].exact_lookup).toBe('title');
+ expect(hits[0].title_match_boost).toBeGreaterThanOrEqual(EXACT_TITLE_STAMP);
+ expect(classifyEvidence(hits[0])).toBe('exact_title_match');
+ });
+
+ test('a PARTIAL title match never qualifies (equality, not phrase)', async () => {
+ const titleArm = [res('projects/mingtang', 0.4, { title: 'The Mingtang Amphitheater Notes' })];
+ const hits = await structuralExactLookup(engine, 'the mingtang', {
+ sourceId: 'default',
+ titleCandidates: titleArm,
+ });
+ expect(hits.length).toBe(0);
+ });
+
+ test('non-lookup-shaped queries are a pure no-op', async () => {
+ const hits = await structuralExactLookup(
+ engine,
+ 'what were the three big objections raised in the partner meeting last week',
+ { sourceId: 'default' },
+ );
+ expect(hits.length).toBe(0);
+ });
+
+ test('supersession filter: a superseded page never wins the identity slot', async () => {
+ await engine.putPage('notes/canon', { type: 'note', title: 'Canon', compiled_truth: 'current' });
+ await engine.putPage('notes/stale', { type: 'note', title: 'Stale', compiled_truth: 'old' });
+ await engine.addLink('notes/canon', 'notes/stale', '', 'supersedes', 'manual');
+ const hits = await structuralExactLookup(engine, 'notes/stale', { sourceId: 'default' });
+ expect(hits.length).toBe(0); // stale identity match is filtered, not injected
+ // The canon page still resolves normally.
+ const canonHits = await structuralExactLookup(engine, 'notes/canon', { sourceId: 'default' });
+ expect(canonHits.length).toBe(1);
+ });
+
+ test('source isolation: scoped probe never resolves another source', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('team-b', 'team-b') ON CONFLICT (id) DO NOTHING`);
+ await engine.putPage('shared/page', { type: 'note', title: 'Shared', compiled_truth: 'b' }, { sourceId: 'team-b' });
+ const hits = await structuralExactLookup(engine, 'shared/page', { sourceId: 'default' });
+ expect(hits.length).toBe(0);
+ const scoped = await structuralExactLookup(engine, 'shared/page', { sourceIds: ['team-b'] });
+ expect(scoped.length).toBe(1);
+ expect(scoped[0].source_id).toBe('team-b');
+ });
+});
+
+describe('applyExactLookupTier (#1663)', () => {
+ test('injects an absent identity match at rank-1 above scored organics', async () => {
+ await engine.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example', compiled_truth: 'Founder.',
+ });
+ const organic = [res('notes/unrelated', 0.9), res('notes/other', 0.7)];
+ const out = await applyExactLookupTier(engine, organic, 'people/alice-example', { sourceId: 'default' });
+ expect(out[0].slug).toBe('people/alice-example');
+ expect(out[0].exact_lookup).toBe('slug');
+ expect(out[0].score).toBeGreaterThan(0.9);
+ expect(out.length).toBe(3);
+ });
+
+ test('promotes (does not duplicate) an identity match already in the set', async () => {
+ await engine.putPage('people/alice-example', {
+ type: 'person', title: 'Alice Example', compiled_truth: 'Founder.',
+ });
+ const organic = [res('notes/unrelated', 0.9), res('people/alice-example', 0.2)];
+ const out = await applyExactLookupTier(engine, organic, 'people/alice-example', { sourceId: 'default' });
+ expect(out.filter((r) => r.slug === 'people/alice-example').length).toBe(1);
+ expect(out[0].slug).toBe('people/alice-example');
+ expect(out[0].exact_lookup).toBe('slug');
+ });
+
+ test('no identity match → input unchanged', async () => {
+ const organic = [res('a', 0.9), res('b', 0.8)];
+ const out = await applyExactLookupTier(engine, organic, 'nonexistent/slug', { sourceId: 'default' });
+ expect(out.map((r) => r.slug)).toEqual(['a', 'b']);
+ });
+});
diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.ts
index 942c5ef1cb..d474342e95 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 21 (…; 16→17 degradation stamp; 17→18 autocut weak-top floor #1863; 18→19 autocut minKeep floor #3621; 19→20 pre-fusion pool floor #3002; 20→21 recency fallback re-key #895)', () => {
+ 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)', () => {
// 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).
@@ -79,7 +79,11 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {
// rows survive the cut, so writes and lookups must agree on it.
// D-3002: 19→20 pre-fusion pool floor — innerLimit widens the candidate
// pool for identical knobs (no new key part; version-only invalidation).
- expect(KNOBS_HASH_VERSION).toBe(21);
+ // mw2: 21→22 result-stamp/injection epoch (#1663 exact-lookup injection,
+ // #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);
});
test('hash is 16 hex chars regardless of reranker config', () => {
diff --git a/test/search/query-shape.test.ts b/test/search/query-shape.test.ts
new file mode 100644
index 0000000000..607e5c6b22
--- /dev/null
+++ b/test/search/query-shape.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #1663 — query-shape router (factual vs open) + the structural-tier gate.
+ * Pure functions; fast parallel loop.
+ */
+import { describe, test, expect } from 'bun:test';
+import { classifyQueryShape, isLookupShapedQuery } from '../../src/core/search/query-intent.ts';
+
+describe('classifyQueryShape (#1663)', () => {
+ test('wh-lookups are factual', () => {
+ expect(classifyQueryShape('who is alice-example')).toBe('factual');
+ expect(classifyQueryShape('when did the widget-co seed round close')).toBe('factual');
+ expect(classifyQueryShape('where is the 2026 offsite')).toBe('factual');
+ expect(classifyQueryShape('which fund led acme-seed')).toBe('factual');
+ });
+
+ test('attribute possessives and quoted names are factual', () => {
+ expect(classifyQueryShape("alice-example's email")).toBe('factual');
+ expect(classifyQueryShape('the url of the design doc')).toBe('factual');
+ expect(classifyQueryShape('"Hall of Light"')).toBe('factual');
+ });
+
+ test('slug-ish tokens are factual', () => {
+ expect(classifyQueryShape('acme-example series A')).toBe('factual');
+ expect(classifyQueryShape('people/alice-example')).toBe('factual');
+ });
+
+ test('how/why/explain/summarize/compare are open', () => {
+ expect(classifyQueryShape('how does the sync checkpoint work')).toBe('open');
+ expect(classifyQueryShape('why did we pick pglite as the default engine')).toBe('open');
+ expect(classifyQueryShape('explain the trust boundary')).toBe('open');
+ expect(classifyQueryShape('summarize what happened at the offsite')).toBe('open');
+ expect(classifyQueryShape('compare fund-a and fund-b on follow-on behavior')).toBe('open');
+ expect(classifyQueryShape('tell me about the ownership economy')).toBe('open');
+ });
+
+ test('"what do we know about" is open (synthesis-shaped)', () => {
+ expect(classifyQueryShape('what do we know about founder liquidity trends')).toBe('open');
+ });
+
+ test('explicit factual lead wins over an embedded open verb', () => {
+ expect(classifyQueryShape('who explained the outage postmortem')).toBe('factual');
+ });
+
+ test('unmatched short queries default factual; long multi-clause defaults open', () => {
+ expect(classifyQueryShape('offsite dinner plan')).toBe('factual');
+ expect(
+ classifyQueryShape('all the different things we could possibly try next quarter given the team constraints and roadmap'),
+ ).toBe('open');
+ });
+
+ test('empty query is open (nothing to look up)', () => {
+ expect(classifyQueryShape(' ')).toBe('open');
+ });
+});
+
+describe('isLookupShapedQuery (#1663)', () => {
+ test('slug-shaped single tokens always qualify', () => {
+ expect(isLookupShapedQuery('people/alice-example')).toBe(true);
+ expect(isLookupShapedQuery('projects/mingtang')).toBe(true);
+ });
+
+ test('short queries qualify; long ones do not', () => {
+ expect(isLookupShapedQuery('Hall of Light')).toBe(true);
+ expect(isLookupShapedQuery('alice example')).toBe(true);
+ expect(isLookupShapedQuery('what were the three big objections raised in the partner meeting')).toBe(false);
+ });
+
+ test('empty query never qualifies', () => {
+ expect(isLookupShapedQuery('')).toBe(false);
+ expect(isLookupShapedQuery(' ')).toBe(false);
+ });
+});
diff --git a/test/serve-sweep-runner-677.test.ts b/test/serve-sweep-runner-677.test.ts
new file mode 100644
index 0000000000..54a5bdd8fb
--- /dev/null
+++ b/test/serve-sweep-runner-677.test.ts
@@ -0,0 +1,105 @@
+/**
+ * #677 — serve-delegated sweep runner + autopilot PGLite install guard.
+ *
+ * 1. startDelegatedSweep runs a REAL runMaintenanceSweep against PGLite,
+ * polls to done, and returns a bounded SweepReport; busy/token-attach
+ * and source_mismatch semantics mirror the sync runner.
+ * 2. pgliteDaemonGuardMessage refuses a PGLite daemon install (with
+ * guidance) unless --force; postgres installs are untouched.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ startDelegatedSweep,
+ getDelegatedSweepStatus,
+ __resetDelegatedSweepForTests,
+} from '../src/core/serve-sweep-runner.ts';
+import { pgliteDaemonGuardMessage } from '../src/commands/autopilot.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(() => {
+ __resetDelegatedSweepForTests();
+});
+
+async function pollDone(jobId: string, timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const s = getDelegatedSweepStatus(jobId);
+ expect(s.ok).toBe(true);
+ if (s.state === 'done' || s.state === 'error') return s;
+ if (Date.now() > deadline) throw new Error('sweep did not settle');
+ await new Promise((r) => setTimeout(r, 50));
+ }
+}
+
+describe('#677 serve-sweep-runner', () => {
+ test('runs a real sweep to done and returns the report', async () => {
+ const start = startDelegatedSweep(engine, { budgetMs: 2000, batchLimit: 5 }, 'tok-1');
+ expect(start.ok).toBe(true);
+ expect(start.jobId).toBeDefined();
+
+ const s = await pollDone(start.jobId!);
+ expect(s.state).toBe('done');
+ expect(s.report).toBeDefined();
+ expect(typeof s.report!.durationMs).toBe('number');
+ expect(Array.isArray(s.report!.skipped)).toBe(true);
+ }, 60_000);
+
+ test('token attach: same clientToken returns the retained terminal job', async () => {
+ const start = startDelegatedSweep(engine, {}, 'tok-2');
+ expect(start.ok).toBe(true);
+ await pollDone(start.jobId!);
+
+ const retry = startDelegatedSweep(engine, {}, 'tok-2');
+ expect(retry.ok).toBe(true);
+ expect(retry.jobId).toBe(start.jobId);
+ expect(retry.completed).toBe(true);
+ }, 60_000);
+
+ test('invalid options refuse fail-closed', () => {
+ const r = startDelegatedSweep(engine, { repoPath: '/etc' }, 'tok-3');
+ expect(r.ok).toBe(false);
+ expect(r.error).toBe('invalid_options:repoPath');
+ });
+
+ test('bound source mismatch refuses', () => {
+ const r = startDelegatedSweep(engine, { sourceId: 'other-src' }, 'tok-4', {
+ boundSourceId: 'bound-src',
+ });
+ expect(r.ok).toBe(false);
+ expect(r.error).toBe('source_mismatch');
+ });
+
+ test('unknown job id → unknown_job', () => {
+ const s = getDelegatedSweepStatus('nope');
+ expect(s.ok).toBe(false);
+ expect(s.error).toBe('unknown_job');
+ });
+});
+
+describe('#677 autopilot PGLite install guard', () => {
+ test('PGLite without --force refuses with guidance', () => {
+ const msg = pgliteDaemonGuardMessage('pglite', false);
+ expect(msg).not.toBeNull();
+ expect(msg).toContain('single-writer');
+ expect(msg).toContain('gbrain serve');
+ expect(msg).toContain('--force');
+ });
+
+ test('PGLite with --force proceeds; postgres always proceeds', () => {
+ expect(pgliteDaemonGuardMessage('pglite', true)).toBeNull();
+ expect(pgliteDaemonGuardMessage('postgres', false)).toBeNull();
+ });
+});
diff --git a/test/skillopt/deadline-and-hermetic.test.ts b/test/skillopt/deadline-and-hermetic.test.ts
new file mode 100644
index 0000000000..6584018956
--- /dev/null
+++ b/test/skillopt/deadline-and-hermetic.test.ts
@@ -0,0 +1,124 @@
+/**
+ * #4119 skillopt hardening — two code-level pieces:
+ *
+ * 1. In-rollout-loop deadline: `deadlineMs` is observed INSIDE the gate's
+ * rollout loop (before every individual rollout), and a breach surfaces
+ * as `skillopt_runtime_exceeded` — never swallowed as a 0-score task.
+ * Pre-fix the orchestrator only checked the wall clock between steps, so
+ * a long batch blew past --max-runtime by a whole gate's worth of
+ * rollouts.
+ *
+ * 2. Opt-in hermetic config for claude-cli children: resolveHermeticConfigDir
+ * maps GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG to the child's CLAUDE_CONFIG_DIR
+ * (off by default — the config dir carries OAuth credentials on non-macOS
+ * installs, so hermetic mode is a deliberate choice, never a default).
+ */
+import { describe, test, expect } from 'bun:test';
+import { existsSync } from 'fs';
+import {
+ runValidationGate,
+ scoreSkillOnTasks,
+ SKILLOPT_RUNTIME_EXCEEDED,
+} from '../../src/core/skillopt/validate-gate.ts';
+import { resolveHermeticConfigDir } from '../../src/core/ai/providers/claude-cli-language-model.ts';
+import type { BenchmarkTask } from '../../src/core/skillopt/types.ts';
+
+const TASKS: BenchmarkTask[] = [
+ { task_id: 't1', task: 'do a thing', judge: { kind: 'rule', checks: [{ op: 'contains', arg: 'x' }] } } as never,
+ { task_id: 't2', task: 'do another', judge: { kind: 'rule', checks: [{ op: 'contains', arg: 'y' }] } } as never,
+];
+
+const okRollout = (async () => ({
+ final_text: 'x y',
+ tool_calls: [],
+ turns: 1,
+})) as never;
+
+describe('#4119 — in-rollout-loop deadline', () => {
+ test('an already-expired deadline aborts the gate before any rollout', async () => {
+ let rolloutsRun = 0;
+ const countingRollout = (async () => {
+ rolloutsRun += 1;
+ return { final_text: 'x', tool_calls: [], turns: 1 };
+ }) as never;
+ await expect(
+ runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ runsPerTask: 1,
+ deadlineMs: Date.now() - 1_000,
+ rolloutFn: countingRollout,
+ }),
+ ).rejects.toThrow(SKILLOPT_RUNTIME_EXCEEDED);
+ expect(rolloutsRun).toBe(0);
+ });
+
+ test('scoreSkillOnTasks threads the deadline too', async () => {
+ await expect(
+ scoreSkillOnTasks({
+ engine: {} as never,
+ skillText: 'skill',
+ tasks: TASKS,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ runsPerTask: 1,
+ deadlineMs: Date.now() - 1_000,
+ rolloutFn: okRollout,
+ }),
+ ).rejects.toThrow(SKILLOPT_RUNTIME_EXCEEDED);
+ });
+
+ test('a future deadline leaves the gate untouched', async () => {
+ const gate = await runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ runsPerTask: 1,
+ deadlineMs: Date.now() + 60_000,
+ rolloutFn: okRollout,
+ });
+ expect(gate.perTaskMedians.length).toBe(2);
+ });
+
+ test('no deadlineMs → no deadline behavior change (back-compat)', async () => {
+ const gate = await runValidationGate({
+ engine: {} as never,
+ candidateSkillText: 'skill',
+ selSet: TASKS,
+ bestScore: -1,
+ targetModel: 'anthropic:claude-haiku-4-5',
+ runsPerTask: 1,
+ rolloutFn: okRollout,
+ });
+ expect(gate.perTaskMedians.length).toBe(2);
+ });
+});
+
+describe('#4119 — resolveHermeticConfigDir (opt-in)', () => {
+ test('unset / 0 / false → null (child inherits the real config dir)', () => {
+ expect(resolveHermeticConfigDir(undefined)).toBeNull();
+ expect(resolveHermeticConfigDir('')).toBeNull();
+ expect(resolveHermeticConfigDir('0')).toBeNull();
+ expect(resolveHermeticConfigDir('false')).toBeNull();
+ expect(resolveHermeticConfigDir('FALSE')).toBeNull();
+ });
+
+ test('1/true → per-process isolated dir, created on demand', () => {
+ const dir = resolveHermeticConfigDir('1');
+ expect(dir).not.toBeNull();
+ expect(dir).toContain('gbrain-claude-cli-config-');
+ expect(existsSync(dir!)).toBe(true);
+ // Stable across calls (same process → same dir).
+ expect(resolveHermeticConfigDir('true')).toBe(dir);
+ });
+
+ test('an explicit path is used verbatim', () => {
+ expect(resolveHermeticConfigDir('/tmp/my-seeded-claude-config')).toBe(
+ '/tmp/my-seeded-claude-config',
+ );
+ });
+});
diff --git a/test/skillopt/silent-abort-3516.test.ts b/test/skillopt/silent-abort-3516.test.ts
new file mode 100644
index 0000000000..51d1732dee
--- /dev/null
+++ b/test/skillopt/silent-abort-3516.test.ts
@@ -0,0 +1,189 @@
+/**
+ * #3516 — skillopt silent-abort surfacing + uncapped-cost escape hatch.
+ *
+ * Pre-fix, a run that died mid-loop printed only "Outcome: errored" (the
+ * detail lived exclusively in the audit JSONL, logged under the untruthful
+ * reason 'sigint'), and there was no way to run an unpriced model id
+ * (openrouter:*, litellm:*) because --max-cost-usd rejected 0 and the
+ * BudgetTracker hard-fails reserve() with no_pricing whenever a cap is set.
+ *
+ * Covers:
+ * - parseFlags: --no-max-cost and --max-cost-usd 0 → maxCostUsd 0;
+ * negative still rejected.
+ * - preflight: maxCostUsd 0 never trips exceeds_cap; report says 'uncapped'.
+ * - BudgetTracker composition: uncapped tracker warn-onces on an unpriced
+ * model instead of throwing BudgetExhausted(no_pricing).
+ * - audit union: reason 'error' is a first-class abort reason (typed, no
+ * `as never`), so the catch-all no longer has to lie with 'sigint'.
+ * - RunReceipt carries abort_reason/abort_detail fields (type-level).
+ */
+
+import { describe, expect, test, beforeEach, afterEach } from 'bun:test';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { withEnv } from '../helpers/with-env.ts';
+import { parseFlags } from '../../src/commands/skillopt.ts';
+import { estimateCost, formatPreflightReport, preflight } from '../../src/core/skillopt/preflight.ts';
+import { BudgetTracker, _resetBudgetTrackerWarningsForTest } from '../../src/core/budget/budget-tracker.ts';
+import {
+ _resetAuditWriterForTests,
+ currentAuditFilename,
+ logEvent,
+ type SkilloptEvent,
+} from '../../src/core/skillopt/audit.ts';
+import type { RunReceipt } from '../../src/core/skillopt/types.ts';
+
+const SKILL = 'widget-example';
+
+describe('#3516 — parseFlags cost-cap escape hatch', () => {
+ test('--no-max-cost sets maxCostUsd to 0', () => {
+ const p = parseFlags([SKILL, '--no-max-cost']);
+ expect(p.maxCostUsd).toBe(0);
+ });
+
+ test('--max-cost-usd 0 is accepted (uncapped)', () => {
+ const p = parseFlags([SKILL, '--max-cost-usd', '0']);
+ expect(p.maxCostUsd).toBe(0);
+ });
+
+ test('--max-cost-usd rejects negative values', () => {
+ expect(() => parseFlags([SKILL, '--max-cost-usd', '-1'])).toThrow(/non-negative/);
+ });
+
+ test('positive --max-cost-usd still parses', () => {
+ const p = parseFlags([SKILL, '--max-cost-usd', '2.5']);
+ expect(p.maxCostUsd).toBe(2.5);
+ });
+});
+
+describe('#3516 — preflight treats 0 as uncapped', () => {
+ const baseOpts = {
+ epochs: 4,
+ batchSize: 8,
+ trainSize: 8,
+ selSize: 2,
+ testSize: 2,
+ optimizerModel: 'anthropic:claude-opus-4-7',
+ targetModel: 'anthropic:claude-sonnet-4-6',
+ judgeModel: 'anthropic:claude-sonnet-4-6',
+ heldOutSize: 0,
+ interactive: false,
+ };
+
+ test('maxCostUsd 0 never trips exceeds_cap', () => {
+ const est = estimateCost({ ...baseOpts, maxCostUsd: 0 });
+ expect(est.est_cost_usd).toBeGreaterThan(0);
+ expect(est.exceeds_cap).toBe(false);
+ const result = preflight({ ...baseOpts, maxCostUsd: 0 });
+ expect(result.proceed).toBe(true);
+ });
+
+ test('a tiny positive cap still refuses (cap behavior unchanged)', () => {
+ const result = preflight({ ...baseOpts, maxCostUsd: 0.000001 });
+ expect(result.proceed).toBe(false);
+ expect(result.abort_reason).toContain('exceeds');
+ });
+
+ test('report renders "uncapped" instead of $0.00', () => {
+ const est = estimateCost({ ...baseOpts, maxCostUsd: 0 });
+ const report = formatPreflightReport(est, { ...baseOpts, maxCostUsd: 0 });
+ expect(report).toContain('uncapped');
+ expect(report).not.toContain('cap: $0.00');
+ });
+});
+
+describe('#3516 — uncapped BudgetTracker warn-onces on unpriced models', () => {
+ beforeEach(() => _resetBudgetTrackerWarningsForTest());
+
+ test('reserve() does not throw for an unpriced openrouter id when uncapped', () => {
+ const tracker = new BudgetTracker({ label: 'skillopt:test' });
+ expect(() => tracker.reserve({
+ modelId: 'openrouter:some-lab/uncharted-model',
+ estimatedInputTokens: 1000,
+ maxOutputTokens: 500,
+ kind: 'chat',
+ })).not.toThrow();
+ });
+
+ test('reserve() still hard-fails no_pricing when a cap is set', () => {
+ const tracker = new BudgetTracker({ maxCostUsd: 5, label: 'skillopt:test' });
+ expect(() => tracker.reserve({
+ modelId: 'openrouter:some-lab/uncharted-model',
+ estimatedInputTokens: 1000,
+ maxOutputTokens: 500,
+ kind: 'chat',
+ })).toThrow(/no pricing/);
+ });
+});
+
+describe("#3516 — audit union carries a truthful 'error' reason", () => {
+ let tmpDir: string;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skillopt-3516-'));
+ _resetAuditWriterForTests();
+ });
+
+ afterEach(() => {
+ _resetAuditWriterForTests();
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ }
+ });
+
+ test("abort event with reason 'error' round-trips through the JSONL (typed)", async () => {
+ await withEnv({ GBRAIN_AUDIT_DIR: tmpDir }, async () => {
+ // NOTE: no `as never` — the union must accept 'error' at compile time.
+ const ev: Omit<Extract<SkilloptEvent, { kind: 'abort' }>, 'ts'> = {
+ kind: 'abort',
+ run_id: 'r-3516',
+ skill: SKILL,
+ reason: 'error',
+ detail: 'provider exploded: 500',
+ };
+ logEvent(ev);
+ const file = path.join(tmpDir, currentAuditFilename());
+ const row = JSON.parse(fs.readFileSync(file, 'utf8').trim());
+ expect(row.kind).toBe('abort');
+ expect(row.reason).toBe('error');
+ expect(row.detail).toBe('provider exploded: 500');
+ });
+ });
+
+ test("'sigint' and 'runtime_exceeded' remain valid reasons (typed)", () => {
+ type AbortEvent = Omit<Extract<SkilloptEvent, { kind: 'abort' }>, 'ts'>;
+ const sigint: AbortEvent = {
+ kind: 'abort', run_id: 'r', skill: SKILL, reason: 'sigint',
+ };
+ const runtime: AbortEvent = {
+ kind: 'abort', run_id: 'r', skill: SKILL, reason: 'runtime_exceeded',
+ };
+ expect(sigint.kind).toBe('abort');
+ expect(runtime.kind).toBe('abort');
+ });
+});
+
+describe('#3516 — RunReceipt carries abort_reason / abort_detail', () => {
+ test('fields are part of the receipt type and JSON-serialize', () => {
+ const receipt: RunReceipt = {
+ run_id: 'r-3516',
+ skill: SKILL,
+ skill_sha8: 'abcd1234',
+ benchmark_sha8: 'deadbeef',
+ optimizer_model: 'anthropic:claude-opus-4-7',
+ target_model: 'anthropic:claude-sonnet-4-6',
+ judge_model: 'anthropic:claude-sonnet-4-6',
+ epochs: 4,
+ batch_size: 8,
+ lr: 4,
+ lr_schedule: 'cosine',
+ max_cost_usd: 5,
+ started_at: new Date().toISOString(),
+ outcome: 'errored',
+ abort_reason: 'error',
+ abort_detail: 'provider exploded: 500',
+ };
+ const parsed = JSON.parse(JSON.stringify(receipt));
+ expect(parsed.abort_reason).toBe('error');
+ expect(parsed.abort_detail).toBe('provider exploded: 500');
+ });
+});
diff --git a/test/slug-unicode-scripts.test.ts b/test/slug-unicode-scripts.test.ts
index 71a95671a5..cee0d1d10e 100644
--- a/test/slug-unicode-scripts.test.ts
+++ b/test/slug-unicode-scripts.test.ts
@@ -113,3 +113,35 @@ describe('#3417: regressions — existing behavior unchanged', () => {
expect(() => validatePageSlug('notes/a\u0007b')).toThrow();
});
});
+
+// #3700 — Hebrew niqqud (vowel points) + cantillation marks are optional
+// diacritics: the same word appears pointed in one filename and bare in
+// another, and both MUST land on the same slug (the Hebrew analog of the
+// Latin café → cafe strip). The strip is scoped to U+0591–U+05C7 ONLY —
+// \p{M} stays in SLUG_WORD_CHARS so Devanagari matras, Arabic harakat-free
+// text, Thai vowels etc. keep working exactly as #3417 shipped them.
+describe('#3700: Hebrew niqqud + cantillation strip', () => {
+ test('pointed and bare spellings land on the same slug', () => {
+ // בְּרֵאשִׁית (pointed) vs בראשית (bare) — Genesis 1:1 word.
+ expect(slugifySegment('בְּרֵאשִׁית')).toBe(slugifySegment('בראשית'));
+ expect(slugifySegment('בְּרֵאשִׁית')).toBe('בראשית');
+ });
+
+ test('cantillation marks strip too', () => {
+ // Same word with an etnachta (U+0591) and munach (U+05A3) added.
+ expect(slugifySegment('בראש֑ית֣')).toBe('בראשית');
+ });
+
+ test('pointed path and bare path derive the same page identity', () => {
+ expect(slugifyPath('notes/שִׁעוּר תּוֹרָה.md')).toBe(slugifyPath('notes/שעור תורה.md'));
+ });
+
+ test('Devanagari matras (also \\p{M}) are untouched', () => {
+ // हिन्दी carries vowel signs + virama — all \p{M}, none Hebrew.
+ expect(slugifySegment('हिन्दी')).toBe('हिन्दी');
+ });
+
+ test('Thai vowels/tone marks are untouched', () => {
+ expect(slugifySegment('ภาษาไทย')).toBe('ภาษาไทย');
+ });
+});
diff --git a/test/soft-delete-link-visibility.test.ts b/test/soft-delete-link-visibility.test.ts
new file mode 100644
index 0000000000..a5c168f41d
--- /dev/null
+++ b/test/soft-delete-link-visibility.test.ts
@@ -0,0 +1,141 @@
+/**
+ * #3754 — soft-deleted pages must not appear in backlinks / links / graph
+ * traversal.
+ *
+ * Repro from the issue: bl-a links to bl-b; soft-delete bl-a. `get`, `list`,
+ * `search`, and `orphans` already hide bl-a, but `backlinks bl-b` and
+ * `graph-query bl-b --direction in` still returned it — the deleted_at filter
+ * was missing wherever the links table is traversed. Both endpoints (f/t) now
+ * carry `deleted_at IS NULL` in getLinks/getBacklinks, and traversePaths
+ * filters at seed + step + final joins.
+ *
+ * PGLite-only here (always runs); Postgres parity is pinned in
+ * test/e2e/engine-parity.test.ts.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {
+ await (engine as any).db.exec(`DELETE FROM ${t}`);
+ }
+});
+
+async function seedPair() {
+ await engine.putPage('bl-a', { type: 'note', title: 'bl-a', compiled_truth: 'links to bl-b', timeline: '' });
+ await engine.putPage('bl-b', { type: 'note', title: 'bl-b', compiled_truth: 'target page', timeline: '' });
+ await engine.addLink('bl-a', 'bl-b', 'This page links to [[bl-b]].', 'wikilink');
+}
+
+describe('#3754 getBacklinks hides soft-deleted endpoints', () => {
+ test('soft-deleting the referrer removes it from backlinks (all three arms)', async () => {
+ await seedPair();
+ expect((await engine.getBacklinks('bl-b')).length).toBe(1);
+
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+
+ // unscoped arm
+ expect(await engine.getBacklinks('bl-b')).toEqual([]);
+ // scalar sourceId arm
+ expect(await engine.getBacklinks('bl-b', { sourceId: 'default' })).toEqual([]);
+ // federated sourceIds arm
+ expect(await engine.getBacklinks('bl-b', { sourceIds: ['default'] })).toEqual([]);
+ });
+
+ test('soft-deleting the target page removes the backlink row too', async () => {
+ await seedPair();
+ await engine.softDeletePage('bl-b', { sourceId: 'default' });
+ expect(await engine.getBacklinks('bl-b')).toEqual([]);
+ expect(await engine.getBacklinks('bl-b', { sourceId: 'default' })).toEqual([]);
+ });
+
+ test('restore brings the backlink back (edge row itself survives soft delete)', async () => {
+ await seedPair();
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+ expect(await engine.getBacklinks('bl-b')).toEqual([]);
+
+ await engine.restorePage('bl-a', { sourceId: 'default' });
+ const restored = await engine.getBacklinks('bl-b');
+ expect(restored.length).toBe(1);
+ expect(restored[0]!.from_slug).toBe('bl-a');
+ });
+});
+
+describe('#3754 getLinks hides soft-deleted endpoints', () => {
+ test('links to a soft-deleted target disappear (all three arms)', async () => {
+ await seedPair();
+ expect((await engine.getLinks('bl-a')).length).toBe(1);
+
+ await engine.softDeletePage('bl-b', { sourceId: 'default' });
+
+ expect(await engine.getLinks('bl-a')).toEqual([]);
+ expect(await engine.getLinks('bl-a', { sourceId: 'default' })).toEqual([]);
+ expect(await engine.getLinks('bl-a', { sourceIds: ['default'] })).toEqual([]);
+ });
+
+ test('links FROM a soft-deleted page disappear', async () => {
+ await seedPair();
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+ expect(await engine.getLinks('bl-a')).toEqual([]);
+ });
+});
+
+describe('#3754 traversePaths hides soft-deleted pages', () => {
+ test('direction=in: deleted referrer is not reachable', async () => {
+ await seedPair();
+ expect((await engine.traversePaths('bl-b', { direction: 'in' })).length).toBe(1);
+
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+ expect(await engine.traversePaths('bl-b', { direction: 'in' })).toEqual([]);
+ });
+
+ test('direction=out: deleted target is not reachable', async () => {
+ await seedPair();
+ expect((await engine.traversePaths('bl-a', { direction: 'out' })).length).toBe(1);
+
+ await engine.softDeletePage('bl-b', { sourceId: 'default' });
+ expect(await engine.traversePaths('bl-a', { direction: 'out' })).toEqual([]);
+ });
+
+ test('direction=both: deleted neighbor is not reachable', async () => {
+ await seedPair();
+ expect((await engine.traversePaths('bl-b', { direction: 'both', depth: 1 })).length).toBe(1);
+
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+ expect(await engine.traversePaths('bl-b', { direction: 'both', depth: 1 })).toEqual([]);
+ expect(await engine.traversePaths('bl-b', { direction: 'both' })).toEqual([]);
+ });
+
+ test('a soft-deleted seed anchors nothing', async () => {
+ await seedPair();
+ await engine.softDeletePage('bl-a', { sourceId: 'default' });
+ expect(await engine.traversePaths('bl-a', { direction: 'out' })).toEqual([]);
+ expect(await engine.traversePaths('bl-a', { direction: 'both' })).toEqual([]);
+ });
+
+ test('a soft-deleted relay breaks multi-hop paths', async () => {
+ // a -> mid -> c; delete mid; a must not reach c.
+ await engine.putPage('hop-a', { type: 'note', title: 'a', compiled_truth: 'x', timeline: '' });
+ await engine.putPage('hop-mid', { type: 'note', title: 'mid', compiled_truth: 'x', timeline: '' });
+ await engine.putPage('hop-c', { type: 'note', title: 'c', compiled_truth: 'x', timeline: '' });
+ await engine.addLink('hop-a', 'hop-mid', '', 'wikilink');
+ await engine.addLink('hop-mid', 'hop-c', '', 'wikilink');
+ expect((await engine.traversePaths('hop-a', { direction: 'out', depth: 3 })).length).toBe(2);
+
+ await engine.softDeletePage('hop-mid', { sourceId: 'default' });
+ expect(await engine.traversePaths('hop-a', { direction: 'out', depth: 3 })).toEqual([]);
+ });
+});
diff --git a/test/source-resolver-sole-non-default.test.ts b/test/source-resolver-sole-non-default.test.ts
index 2e4c204155..870b9e5715 100644
--- a/test/source-resolver-sole-non-default.test.ts
+++ b/test/source-resolver-sole-non-default.test.ts
@@ -51,9 +51,12 @@ function makeStub(
return sources.filter(s => s.local_path !== null && s.id !== 'default')
.map(s => ({ id: s.id })) as unknown as T[];
}
- if (sql.includes('SELECT id, local_path FROM sources WHERE local_path IS NOT NULL')) {
+ if (
+ sql.includes('SELECT id, local_path FROM sources WHERE local_path IS NOT NULL') ||
+ sql.includes(', archived FROM sources WHERE local_path IS NOT NULL')
+ ) {
return sources.filter(s => s.local_path !== null)
- .map(s => ({ id: s.id, local_path: s.local_path })) as unknown as T[];
+ .map(s => ({ id: s.id, local_path: s.local_path, archived: s.archived === true })) as unknown as T[];
}
if (sql.includes('SELECT id FROM sources WHERE id =')) {
const id = (_params as string[])?.[0];
diff --git a/test/source-resolver-with-tier.test.ts b/test/source-resolver-with-tier.test.ts
index e00eb39509..7e834ef758 100644
--- a/test/source-resolver-with-tier.test.ts
+++ b/test/source-resolver-with-tier.test.ts
@@ -34,7 +34,7 @@ function makeStub(
? [{ id: target } as unknown as T]
: []);
}
- if (sql.includes('SELECT id, local_path FROM sources')) {
+ if (sql.includes('SELECT id, local_path FROM sources') || sql.includes(', archived FROM sources')) {
return paths as unknown as T[];
}
return [];
diff --git a/test/source-resolver.test.ts b/test/source-resolver.test.ts
index cd302fdb17..ea89dc8a6d 100644
--- a/test/source-resolver.test.ts
+++ b/test/source-resolver.test.ts
@@ -29,7 +29,9 @@ function makeStub(registeredSources: string[], paths: Array<{ id: string; local_
? [{ id: target } as unknown as T]
: []);
}
- if (sql.includes('SELECT id, local_path FROM sources')) {
+ // Tier-4 registered-source query — old shape and the #3880 shape
+ // (`SELECT id, local_path, archived FROM sources ...`).
+ if (sql.includes('SELECT id, local_path FROM sources') || sql.includes(', archived FROM sources')) {
return paths as unknown as T[];
}
return [];
@@ -198,7 +200,7 @@ describe('getDefaultSourcePath', () => {
}
return [];
}
- if (sql.includes('SELECT id, local_path FROM sources')) {
+ if (sql.includes('SELECT id, local_path FROM sources') || sql.includes(', archived FROM sources')) {
return Object.entries(sourcePaths)
.filter(([_, p]) => p !== null)
.map(([id, local_path]) => ({ id, local_path }) as unknown as T);
diff --git a/test/sources-abs-path-3696.test.ts b/test/sources-abs-path-3696.test.ts
new file mode 100644
index 0000000000..0f3fab1470
--- /dev/null
+++ b/test/sources-abs-path-3696.test.ts
@@ -0,0 +1,99 @@
+/**
+ * #3696 — relative paths must never reach daemon-visible state.
+ *
+ * 1. `addSource --path <relative>` stores an ABSOLUTE local_path (resolved
+ * against the registering shell's cwd) — pre-fix the relative string was
+ * inserted verbatim and every daemon-context consumer (launchd cwd=/)
+ * join-resolved a phantom path.
+ * 2. generateLaunchdPlist emits a WorkingDirectory key pinned to $HOME
+ * (spawn-safe — NEVER the repo: launchd chdir()s before exec, so a
+ * deleted repo would fail every respawn and the self-disable guard
+ * could never run). The wrapper cd's into the repo after the guard.
+ * 3. The autopilot dispatch loops skip (with a loud warning) any source
+ * whose stored local_path is still relative (legacy rows).
+ */
+
+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, basename, dirname, isAbsolute, resolve } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { addSource } from '../src/core/sources-ops.ts';
+import { generateLaunchdPlist, relativeLocalPathSkipWarning } from '../src/commands/autopilot.ts';
+
+let engine: PGLiteEngine;
+let repoDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ repoDir = mkdtempSync(join(tmpdir(), 'gbrain-3696-'));
+ execSync('git init', { cwd: repoDir, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: repoDir, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: repoDir, stdio: 'pipe' });
+ mkdirSync(join(repoDir, 'topics'), { recursive: true });
+ writeFileSync(join(repoDir, 'topics/x.md'), '---\ntype: concept\ntitle: X\n---\n\nbody.\n');
+ execSync('git add -A && git commit -m seed', { cwd: repoDir, stdio: 'pipe' });
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (repoDir) rmSync(repoDir, { recursive: true, force: true });
+}, 60_000);
+
+describe('#3696 addSource stores absolute local_path', () => {
+ test('a relative --path is resolved against cwd before INSERT', async () => {
+ const origCwd = process.cwd();
+ // cd into the temp repo's PARENT so `./<basename>` is a valid relative path.
+ process.chdir(dirname(repoDir));
+ try {
+ const relPath = `./${basename(repoDir)}`;
+ expect(isAbsolute(relPath)).toBe(false);
+ // Compute the expectation from the SAME cwd addSource resolves against
+ // (macOS: chdir realpaths /var → /private/var, so a dirname()-based
+ // expectation would compare the unrealpathed spelling).
+ const expected = resolve(relPath);
+ await addSource(engine, { id: 'rel-src-3696', localPath: relPath });
+
+ const rows = await engine.executeRaw<{ local_path: string }>(
+ `SELECT local_path FROM sources WHERE id = 'rel-src-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);
+ }
+ });
+});
+
+describe('#3696 generateLaunchdPlist WorkingDirectory', () => {
+ test('emits WorkingDirectory = $HOME (spawn-safe), never the repo', () => {
+ // launchd chdir()s into WorkingDirectory BEFORE exec: pinning the repo
+ // here means a deleted repo fails every respawn, so the wrapper's
+ // self-disable guard can never fire — a zombie KeepAlive job forever.
+ // The repo cwd lives in the wrapper, after the guard proves it exists.
+ const plist = generateLaunchdPlist('/Users/me/.gbrain/autopilot-run.sh', '/Users/me');
+ expect(plist).toContain('<key>WorkingDirectory</key><string>/Users/me</string>');
+ });
+
+ test('XML-escapes the WorkingDirectory path', () => {
+ const plist = generateLaunchdPlist('/w.sh', '/data/a&b');
+ expect(plist).toContain('<key>WorkingDirectory</key><string>/data/a&amp;b</string>');
+ });
+});
+
+describe('#3696 autopilot dispatch skips relative local_path', () => {
+ test('relative path yields a skip warning; absolute path is dispatchable', () => {
+ const warn = relativeLocalPathSkipWarning('legacy-src', 'notes/vault');
+ expect(warn).not.toBeNull();
+ expect(warn).toContain('legacy-src');
+ expect(warn).toContain('notes/vault');
+ expect(warn).toContain('cannot be resolved from a daemon');
+
+ expect(relativeLocalPathSkipWarning('ok-src', '/abs/vault')).toBeNull();
+ });
+});
diff --git a/test/sql-ranking.test.ts b/test/sql-ranking.test.ts
index 2376023505..46d1f125ae 100644
--- a/test/sql-ranking.test.ts
+++ b/test/sql-ranking.test.ts
@@ -325,8 +325,11 @@ describe('buildVisibilityClause (v0.26.5)', () => {
test('does NOT bypass on detail level — visibility is a contract, not a temporal preference', () => {
// Distinct from buildSourceFactorCase: there's no detail-gated short-circuit.
// Soft-deleted content stays hidden regardless of caller's detail level.
- // Function signature has no detail param at all; this test pins that contract.
- expect(buildVisibilityClause.length).toBe(2);
+ // Function signature has no detail param; the third param is the #4352
+ // excludePrivate opts bag (a tightening knob, never a bypass). This test
+ // pins that contract: exactly (pageAlias, sourceAlias, opts).
+ expect(buildVisibilityClause.length).toBe(3);
+ expect(String(buildVisibilityClause)).not.toContain('detail');
});
test('emits a stable string regardless of call order (idempotent for snapshot tests)', () => {
diff --git a/test/sync-embedding-infra-gate.test.ts b/test/sync-embedding-infra-gate.test.ts
new file mode 100644
index 0000000000..17a8ed85f7
--- /dev/null
+++ b/test/sync-embedding-infra-gate.test.ts
@@ -0,0 +1,148 @@
+/**
+ * #3875 — embedding-infra failures must never ride the auto-skip valve.
+ *
+ * Pure-function coverage (no ledger file, no DB):
+ *
+ * 1. classifyErrorCode maps the gateway's per-sub-batch timeout message
+ * (`[embed(provider:model)] The operation timed out.`) to
+ * EMBEDDING_TIMEOUT instead of UNKNOWN.
+ * 2. decideGateAction accepts per-path codes and treats
+ * EMBEDDING_{TIMEOUT,RATE_LIMIT,QUOTA} as never-chronic: a provider
+ * outage BLOCKS the bookmark instead of silently auto-skipping every
+ * file that synced while the provider was unhealthy.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import {
+ classifyErrorCode,
+ decideGateAction,
+ isEmbeddingInfraCode,
+ EMBEDDING_INFRA_CODES,
+} from '../src/core/sync-failure-ledger.ts';
+
+describe('#3875 classifyErrorCode — embed-scoped timeouts', () => {
+ test('gateway sub-batch timeout message classifies as EMBEDDING_TIMEOUT, not UNKNOWN', () => {
+ expect(
+ classifyErrorCode('[embed(ollama:nomic-embed-text)] The operation timed out.'),
+ ).toBe('EMBEDDING_TIMEOUT');
+ });
+
+ test('other providers and phrasings still classify', () => {
+ expect(
+ classifyErrorCode('[embed(voyage:voyage-3-large)] Request timeout after 60000ms'),
+ ).toBe('EMBEDDING_TIMEOUT');
+ expect(
+ classifyErrorCode('[embedMultimodal(voyage:voyage-multimodal-3)] The operation timed out.'),
+ ).toBe('EMBEDDING_TIMEOUT');
+ });
+
+ test('a bare timeout with no embed context stays UNKNOWN (scope stays tight)', () => {
+ expect(classifyErrorCode('The operation timed out.')).toBe('UNKNOWN');
+ });
+
+ test('DB statement timeouts are NOT reclassified', () => {
+ expect(
+ classifyErrorCode('canceling statement due to statement timeout'),
+ ).toBe('STATEMENT_TIMEOUT');
+ });
+
+ test('429 control case still maps to EMBEDDING_RATE_LIMIT', () => {
+ expect(classifyErrorCode('[embed(openai:text-embedding-3-small)] 429 too many requests')).toBe(
+ 'EMBEDDING_RATE_LIMIT',
+ );
+ });
+});
+
+describe('#3875 isEmbeddingInfraCode', () => {
+ test('the three provider-infra codes are infra; file-poison codes are not', () => {
+ for (const code of ['EMBEDDING_TIMEOUT', 'EMBEDDING_RATE_LIMIT', 'EMBEDDING_QUOTA']) {
+ expect(EMBEDDING_INFRA_CODES.has(code)).toBe(true);
+ expect(isEmbeddingInfraCode(code)).toBe(true);
+ }
+ for (const code of ['YAML_PARSE', 'EMBEDDING_OVERSIZE', 'UNKNOWN', undefined]) {
+ expect(isEmbeddingInfraCode(code)).toBe(false);
+ }
+ });
+});
+
+describe('#3875 decideGateAction — infra codes never auto-skip', () => {
+ const base = {
+ sentinels: [] as Array<{ path: string }>,
+ threshold: 3,
+ skipFailed: false,
+ };
+
+ test('chronic file WITH an infra code blocks instead of auto-skipping', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [{ path: 'notes/a.md', code: 'EMBEDDING_TIMEOUT' }],
+ attemptsByPath: new Map([['notes/a.md', 5]]),
+ });
+ expect(d.action).toBe('block');
+ expect(d.autoSkipPaths).toEqual([]);
+ });
+
+ test('chronic file with a poison code still auto-skips (valve unchanged)', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [{ path: 'notes/a.md', code: 'YAML_PARSE' }],
+ attemptsByPath: new Map([['notes/a.md', 5]]),
+ });
+ expect(d.action).toBe('advance_then_autoskip');
+ expect(d.autoSkipPaths).toEqual(['notes/a.md']);
+ });
+
+ test('mixed chronic poison + chronic infra blocks the whole gate', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [
+ { path: 'notes/poison.md', code: 'YAML_PARSE' },
+ { path: 'notes/good-but-provider-down.md', code: 'EMBEDDING_RATE_LIMIT' },
+ ],
+ attemptsByPath: new Map([
+ ['notes/poison.md', 5],
+ ['notes/good-but-provider-down.md', 5],
+ ]),
+ });
+ expect(d.action).toBe('block');
+ expect(d.autoSkipPaths).toEqual([]);
+ });
+
+ test('EMBEDDING_QUOTA behaves like TIMEOUT/RATE_LIMIT', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [{ path: 'notes/a.md', code: 'EMBEDDING_QUOTA' }],
+ attemptsByPath: new Map([['notes/a.md', 99]]),
+ });
+ expect(d.action).toBe('block');
+ });
+
+ test('explicit --skip-failed still advances (human ack wins over the valve)', () => {
+ const d = decideGateAction({
+ ...base,
+ skipFailed: true,
+ fileFailures: [{ path: 'notes/a.md', code: 'EMBEDDING_TIMEOUT' }],
+ attemptsByPath: new Map([['notes/a.md', 5]]),
+ });
+ expect(d.action).toBe('advance');
+ });
+
+ test('code-less failures keep pre-#3875 behavior (backward compatible)', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [{ path: 'notes/a.md' }],
+ attemptsByPath: new Map([['notes/a.md', 5]]),
+ });
+ expect(d.action).toBe('advance_then_autoskip');
+ });
+
+ test('sentinels still hard-block regardless of codes', () => {
+ const d = decideGateAction({
+ ...base,
+ fileFailures: [{ path: 'notes/a.md', code: 'EMBEDDING_TIMEOUT' }],
+ sentinels: [{ path: '<head>' }],
+ attemptsByPath: new Map([['notes/a.md', 5]]),
+ });
+ expect(d.action).toBe('hard_block');
+ });
+});
diff --git a/test/sync-incremental-image-2683.test.ts b/test/sync-incremental-image-2683.test.ts
new file mode 100644
index 0000000000..05fc43c7c0
--- /dev/null
+++ b/test/sync-incremental-image-2683.test.ts
@@ -0,0 +1,120 @@
+/**
+ * #2683 — incremental sync must admit images when multimodal is enabled.
+ *
+ * Pre-fix, `isAllowedByStrategy` under the default 'markdown' strategy was
+ * markdown-only (the FULL-sync walker admitted images via
+ * isCollectibleForWalker, so images only ever landed through `sync --full`),
+ * and the incremental import sites called importFile unconditionally — a
+ * committed .png that DID slip through ('auto' strategy) went down the UTF-8
+ * text path and failed.
+ *
+ * Coverage (PGLite performSync, real git repo):
+ * - default strategy: md first-sync, then a committed png imports
+ * incrementally, anchor advances, re-sync is up_to_date
+ * - 'auto' strategy: same, and no UTF-8 failure blocks the run
+ * - gate off: the png stays excluded (existing behavior preserved)
+ */
+
+import { describe, test, expect, beforeEach, afterEach, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, rmSync, copyFileSync } from 'fs';
+import { execSync } from 'child_process';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+function git(cmd: string) {
+ execSync(cmd, { cwd: repo, stdio: 'pipe' });
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-2683-'));
+ git('git init');
+ git('git config user.email "[email protected]"');
+ git('git config user.name "T"');
+ writeFileSync(join(repo, 'note.md'), '---\ntype: concept\ntitle: Note\n---\n\nSeed body.\n');
+ git('git add -A && git commit -m seed');
+});
+
+afterEach(() => {
+ if (repo) rmSync(repo, { recursive: true, force: true });
+});
+
+async function pageSlugs(): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE deleted_at IS NULL ORDER BY slug`,
+ );
+ return rows.map(r => r.slug);
+}
+
+async function syncOnce(extra: Record<string, unknown> = {}) {
+ return performSync(engine, {
+ repoPath: repo,
+ sourceId: 'default',
+ noEmbed: true,
+ noPull: true,
+ ...extra,
+ });
+}
+
+for (const strategy of [undefined, 'auto'] as const) {
+ const label = strategy ?? 'default (markdown)';
+ test(`incremental png imports under ${label} strategy when multimodal is on`, async () => {
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, async () => {
+ const strategyOpts = strategy ? { strategy } : {};
+
+ const first = await syncOnce(strategyOpts);
+ expect(['first_sync', 'synced']).toContain(first.status);
+ expect(await pageSlugs()).toContain('note');
+
+ // Commit an image AFTER the first sync — only the INCREMENTAL path sees it.
+ copyFileSync('test/fixtures/images/tiny.avif', join(repo, 'photo.png'));
+ git('git add -A && git commit -m add-image');
+
+ const second = await syncOnce(strategyOpts);
+ // Pre-fix: default strategy returned 'up_to_date'/'synced' with the image
+ // silently excluded; 'auto' recorded a UTF-8 failure and blocked. Both are
+ // wrong — the image page must land and the anchor must advance.
+ expect(second.status).toBe('synced');
+ expect(second.added).toBe(1);
+ const slugs = await pageSlugs();
+ expect(slugs.some(s => s.endsWith('photo.png'))).toBe(true);
+
+ // Anchor advanced: a third sync has nothing to do.
+ const third = await syncOnce(strategyOpts);
+ expect(third.status).toBe('up_to_date');
+ });
+ }, 90_000);
+}
+
+test('gate off: a committed png stays excluded (no image page, no failure)', async () => {
+ await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: undefined }, async () => {
+ const first = await syncOnce();
+ expect(['first_sync', 'synced']).toContain(first.status);
+
+ copyFileSync('test/fixtures/images/tiny.avif', join(repo, 'photo.png'));
+ git('git add -A && git commit -m add-image');
+
+ const second = await syncOnce();
+ // The png is filtered by strategy; nothing to import, no block.
+ expect(['up_to_date', 'synced']).toContain(second.status);
+ const slugs = await pageSlugs();
+ expect(slugs.some(s => s.endsWith('photo.png'))).toBe(false);
+ });
+}, 90_000);
diff --git a/test/sync-malformed-path.serial.test.ts b/test/sync-malformed-path.serial.test.ts
index fc8387211d..1e1759667b 100644
--- a/test/sync-malformed-path.serial.test.ts
+++ b/test/sync-malformed-path.serial.test.ts
@@ -27,7 +27,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'fs';
-import { execSync } from 'child_process';
+import { gitExec } from './helpers/git-exec.ts';
import { tmpdir } from 'os';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -39,9 +39,9 @@ let repoPath: string;
const JUNK_NAME = '[foo.md](https-example).md';
function gitInit(repo: string): void {
- execSync('git init', { cwd: repo, stdio: 'pipe' });
- execSync('git config user.email "[email protected]"', { cwd: repo, stdio: 'pipe' });
- execSync('git config user.name "Test"', { cwd: repo, stdio: 'pipe' });
+ gitExec('git init', repo);
+ gitExec('git config user.email "[email protected]"', repo);
+ gitExec('git config user.name "Test"', repo);
}
/** Seed a page row as if a pre-fix gbrain had ingested the junk file. */
@@ -83,7 +83,7 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
'',
'Baseline content.',
].join('\n'));
- execSync('git add -A && git commit -m "initial"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "initial"', repoPath);
});
afterEach(() => {
@@ -94,7 +94,7 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
const { performSync } = await import('../src/commands/sync.ts');
writeFileSync(join(repoPath, JUNK_NAME), '# junk\n');
- execSync('git add -A && git commit -m "junk lands"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "junk lands"', repoPath);
const result = await performSync(engine, { repoPath, full: true, noPull: true, noEmbed: true });
// The junk file must not block the sync or land in the index.
@@ -109,15 +109,15 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
const { performSync } = await import('../src/commands/sync.ts');
writeFileSync(join(repoPath, JUNK_NAME), '# junk\n');
- execSync('git add -A && git commit -m "junk lands"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "junk lands"', repoPath);
const first = await performSync(engine, { repoPath, noPull: true, noEmbed: true });
expect(first.status).not.toBe('blocked_by_failures');
// Simulate the pre-fix world: the junk row is already in the DB.
await seedPoisonedRow('atoms/foo-md-https-example', JUNK_NAME);
- execSync(`git rm '${JUNK_NAME}'`, { cwd: repoPath, stdio: 'pipe' });
- execSync('git commit -m "remove junk"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec(`git rm '${JUNK_NAME}'`, repoPath);
+ gitExec('git commit -m "remove junk"', repoPath);
const second = await performSync(engine, { repoPath, noPull: true, noEmbed: true });
expect(second.status).not.toBe('blocked_by_failures');
@@ -133,13 +133,13 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
const { performSync } = await import('../src/commands/sync.ts');
writeFileSync(join(repoPath, JUNK_NAME), '# junk\n');
- execSync('git add -A && git commit -m "junk lands"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "junk lands"', repoPath);
await performSync(engine, { repoPath, noPull: true, noEmbed: true });
await seedPoisonedRow('atoms/foo-md-https-example', JUNK_NAME);
writeFileSync(join(repoPath, JUNK_NAME), '# junk edited\n');
- execSync('git add -A && git commit -m "edit junk"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "edit junk"', repoPath);
await performSync(engine, { repoPath, noPull: true, noEmbed: true });
const survivor = await engine.executeRaw<{ slug: string }>(
@@ -153,7 +153,7 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
// Junk file committed AND still present in the working tree.
writeFileSync(join(repoPath, JUNK_NAME), '# junk\n');
- execSync('git add -A && git commit -m "junk lands"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "junk lands"', repoPath);
// Poisoned row exists in the default source (pre-fix ingestion).
await seedPoisonedRow('atoms/foo-md-https-example', JUNK_NAME);
@@ -183,7 +183,7 @@ describe('malformed-path sync semantics (poisoned-filename incident)', () => {
const BARE = 'notes [draft].md';
writeFileSync(join(repoPath, BARE), '# legit draft\n');
- execSync('git add -A && git commit -m "bare-bracket note"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m "bare-bracket note"', repoPath);
await seedPoisonedRow('notes-draft', BARE);
const result = await performSync(engine, {
diff --git a/test/sync-monorepo.test.ts b/test/sync-monorepo.test.ts
index 3e1f2331a0..840e0063a7 100644
--- a/test/sync-monorepo.test.ts
+++ b/test/sync-monorepo.test.ts
@@ -111,10 +111,14 @@ describe('sync monorepo subdir-source support (#753/#774)', () => {
});
expect(result.status).toBe('first_sync');
expect(result.added).toBe(2); // only wiki/page1 + wiki/page2
- // Slugs are git-root-relative in BOTH spellings (subdir repoPath and
- // --src-subpath) so full and incremental syncs of the same scope agree.
- expect(await engine.getPage('wiki/page1')).not.toBeNull();
- expect(await engine.getPage('page1')).toBeNull();
+ // #4342: a FRESH subdir source (no --src-subpath, no already-prefixed
+ // pages) pins slug_root_mode='source-root' — slugs are local_path-
+ // relative, matching what `gbrain import wiki/` produces. Full and
+ // incremental syncs of the scope agree via the sticky pin (a live
+ // install with git-root-prefixed pages auto-pins 'git-root' instead —
+ // covered by test/sync-slug-root-mode-4342.test.ts).
+ expect(await engine.getPage('page1')).not.toBeNull();
+ expect(await engine.getPage('wiki/page1')).toBeNull();
});
// ─────────────────────────────────────────────────────────────────────────
diff --git a/test/sync-reconcile-db-only.serial.test.ts b/test/sync-reconcile-db-only.serial.test.ts
index a531a7dcab..e03c1a07b6 100644
--- a/test/sync-reconcile-db-only.serial.test.ts
+++ b/test/sync-reconcile-db-only.serial.test.ts
@@ -19,7 +19,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'fs';
-import { execSync } from 'child_process';
+import { gitExec } from './helpers/git-exec.ts';
import { tmpdir } from 'os';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -30,9 +30,9 @@ let engine: PGLiteEngine;
let repoPath: string;
function gitInit(repo: string): void {
- execSync('git init', { cwd: repo, stdio: 'pipe' });
- execSync('git config user.email "[email protected]"', { cwd: repo, stdio: 'pipe' });
- execSync('git config user.name "T"', { cwd: repo, stdio: 'pipe' });
+ gitExec('git init', repo);
+ gitExec('git config user.email "[email protected]"', repo);
+ gitExec('git config user.name "T"', repo);
}
describe('listEverCommittedPaths (#2426)', () => {
@@ -42,8 +42,8 @@ describe('listEverCommittedPaths (#2426)', () => {
gitInit(repo);
writeFileSync(join(repo, 'kept.md'), 'kept\n');
writeFileSync(join(repo, 'gone.md'), 'gone\n');
- execSync('git add -A && git commit -m add', { cwd: repo, stdio: 'pipe' });
- execSync('git rm -q gone.md && git commit -m rm', { cwd: repo, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m add', repo);
+ gitExec('git rm -q gone.md && git commit -m rm', repo);
const set = listEverCommittedPaths(repo);
expect(set).not.toBeNull();
@@ -85,7 +85,7 @@ describe('#2426 — full-sync reconcile keeps never-committed (DB-only) pages',
writeFileSync(join(repoPath, 'topics/gone.md'), [
'---', 'type: concept', 'title: Gone', '---', '', 'will be git-rm-ed',
].join('\n'));
- execSync('git add -A && git commit -m initial', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git add -A && git commit -m initial', repoPath);
});
afterEach(() => {
@@ -119,7 +119,7 @@ describe('#2426 — full-sync reconcile keeps never-committed (DB-only) pages',
);
// A genuine deletion: topics/gone.md removed via git.
- execSync('git rm -q topics/gone.md && git commit -m "rm gone"', { cwd: repoPath, stdio: 'pipe' });
+ gitExec('git rm -q topics/gone.md && git commit -m "rm gone"', repoPath);
await engine.setConfig('sync.repo_path', repoPath);
// Full sync #2 runs the delete-reconcile.
diff --git a/test/sync-repo-source-routing.test.ts b/test/sync-repo-source-routing.test.ts
new file mode 100644
index 0000000000..65d80f4ad3
--- /dev/null
+++ b/test/sync-repo-source-routing.test.ts
@@ -0,0 +1,214 @@
+/**
+ * #3765 — `--repo` / the sync_brain `repo` param must anchor SOURCE resolution
+ * at the repo dir, not the caller's cwd.
+ *
+ * Pre-fix: `gbrain sync --repo <dir>` parsed the path but resolved the source
+ * from cwd, and the sync_brain op threaded only ctx.sourceId — so a repo
+ * pointing at source B's checkout synced under the WRONG source (wrong
+ * anchors, wrong page source_id, wrong `syncLockId(sourceId)` lock key).
+ *
+ * Coverage:
+ * 1. resolveSourceForRepoPath unit: local_path tier, dotfile tier, null.
+ * 2. sync_brain op: repo pointing at a registered source's checkout routes
+ * pages into THAT source; explicit source_id param wins; conflict with a
+ * non-default ctx.sourceId refuses with a structured OperationError.
+ * 3. CLI runSync: --repo routes to the repo's source even when the ambient
+ * chain would have picked 'default'.
+ */
+
+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 { runSources } from '../src/commands/sources.ts';
+import { resolveSourceForRepoPath } from '../src/core/source-resolver.ts';
+import { operationsByName, OperationError, type OperationContext } from '../src/core/operations.ts';
+
+const SRC_A = 'vault-a-3765';
+const SRC_B = 'vault-b-3765';
+
+let engine: PGLiteEngine;
+let repoA: string;
+let repoB: string;
+let unregistered: string;
+
+function makeGitRepo(prefix: string, slugStem: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ execSync('git init', { cwd: dir, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: dir, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: dir, stdio: 'pipe' });
+ mkdirSync(join(dir, 'topics'), { recursive: true });
+ writeFileSync(join(dir, `topics/${slugStem}.md`), [
+ '---',
+ 'type: concept',
+ `title: ${slugStem}`,
+ '---',
+ '',
+ `Body for ${slugStem}, long enough to import cleanly.`,
+ '',
+ ].join('\n'));
+ execSync('git add -A && git commit -m seed', { cwd: dir, stdio: 'pipe' });
+ return dir;
+}
+
+async function pagesIn(sourceId: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1`,
+ [sourceId],
+ );
+ return rows[0]!.n;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+
+ repoA = makeGitRepo('gbrain-3765-a-', 'alpha-note');
+ repoB = makeGitRepo('gbrain-3765-b-', 'beta-note');
+ unregistered = makeGitRepo('gbrain-3765-u-', 'unreg-note');
+
+ // TWO non-default sources so the sole_non_default convenience tier (5.5)
+ // can never mask the repo-derived routing under test.
+ await runSources(engine, ['add', SRC_A, '--path', repoA, '--no-federated']);
+ await runSources(engine, ['add', SRC_B, '--path', repoB, '--no-federated']);
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ for (const d of [repoA, repoB, unregistered]) {
+ if (d) rmSync(d, { recursive: true, force: true });
+ }
+}, 60_000);
+
+describe('#3765 resolveSourceForRepoPath (unit)', () => {
+ test('registered local_path containing the dir resolves (longest prefix)', async () => {
+ const hit = await resolveSourceForRepoPath(engine, repoA);
+ expect(hit).not.toBeNull();
+ expect(hit!.source_id).toBe(SRC_A);
+ expect(hit!.tier).toBe('local_path');
+
+ // A subdirectory of the checkout also resolves.
+ const sub = await resolveSourceForRepoPath(engine, join(repoA, 'topics'));
+ expect(sub?.source_id).toBe(SRC_A);
+ });
+
+ test('a .gbrain-source dotfile inside the repo dir wins over local_path', async () => {
+ // Plant a pin for SRC_B inside repoA's tree — dotfile tier fires first.
+ const pin = join(repoA, '.gbrain-source');
+ writeFileSync(pin, `${SRC_B}\n`, { mode: 0o644 });
+ try {
+ const hit = await resolveSourceForRepoPath(engine, repoA);
+ expect(hit?.source_id).toBe(SRC_B);
+ expect(hit?.tier).toBe('dotfile');
+ } finally {
+ rmSync(pin, { force: true });
+ }
+ });
+
+ test('an unregistered dir resolves to null (caller falls back to ambient)', async () => {
+ const hit = await resolveSourceForRepoPath(engine, unregistered);
+ expect(hit).toBeNull();
+ });
+});
+
+describe('#3765 sync_brain op routes repo to its source', () => {
+ const baseCtx = () =>
+ ({
+ engine,
+ config: {},
+ logger: { info() {}, warn() {}, error() {} },
+ dryRun: false,
+ remote: false,
+ }) as unknown as OperationContext;
+
+ test('repo param pointing at SRC_B checkout lands pages in SRC_B, not default', async () => {
+ const op = operationsByName['sync_brain']!;
+ const before = await pagesIn('default');
+ const result = await op.handler(baseCtx(), {
+ repo: repoB,
+ no_embed: true,
+ no_pull: true,
+ full: true,
+ });
+ expect(result).toBeDefined();
+ expect(await pagesIn(SRC_B)).toBeGreaterThan(0);
+ // Pre-fix: ctx.sourceId was undefined, so pages landed in 'default'.
+ expect(await pagesIn('default')).toBe(before);
+ }, 60_000);
+
+ test('explicit source_id param wins over the repo-derived source', async () => {
+ const op = operationsByName['sync_brain']!;
+ // Dry run — routing decision is the thing under test; explicit source_id
+ // must not be overridden by repo derivation (and must validate).
+ const result = await op.handler(baseCtx(), {
+ repo: repoB,
+ source_id: SRC_A,
+ dry_run: true,
+ no_embed: true,
+ no_pull: true,
+ });
+ expect(result).toBeDefined();
+ }, 60_000);
+
+ test('unknown explicit source_id refuses with invalid_params', async () => {
+ const op = operationsByName['sync_brain']!;
+ expect(
+ op.handler(baseCtx(), { repo: repoB, source_id: 'no-such-source', dry_run: true }),
+ ).rejects.toThrow(/not found|archived/i);
+ });
+
+ test('conflict: repo-derived source vs non-default ctx.sourceId refuses structurally', async () => {
+ const op = operationsByName['sync_brain']!;
+ const ctx = { ...baseCtx(), sourceId: SRC_A } as unknown as OperationContext;
+ let err: unknown;
+ try {
+ await op.handler(ctx, { repo: repoB, dry_run: true, no_pull: true });
+ } catch (e) {
+ err = e;
+ }
+ expect(err).toBeInstanceOf(OperationError);
+ const oe = err as OperationError;
+ expect(oe.code).toBe('invalid_params');
+ expect(oe.message).toContain(SRC_B);
+ expect(oe.message).toContain(SRC_A);
+ });
+
+ test('no conflict when ctx.sourceId matches the repo-derived source', async () => {
+ const op = operationsByName['sync_brain']!;
+ const ctx = { ...baseCtx(), sourceId: SRC_B } as unknown as OperationContext;
+ const result = await op.handler(ctx, {
+ repo: repoB,
+ dry_run: true,
+ no_embed: true,
+ no_pull: true,
+ });
+ expect(result).toBeDefined();
+ }, 60_000);
+});
+
+describe('#3765 CLI runSync --repo routing', () => {
+ test('--repo routes to the repo source when the ambient chain would pick default', async () => {
+ const { runSync } = await import('../src/commands/sync.ts');
+
+ const origExit = process.exit;
+ process.exit = ((_code?: number) => {
+ throw new Error('__exit__');
+ }) as typeof process.exit;
+ const before = await pagesIn('default');
+ try {
+ await runSync(engine, ['--full', '--no-embed', '--no-pull', '--repo', repoA]);
+ } catch (e) {
+ if ((e as Error).message !== '__exit__') throw e;
+ } finally {
+ process.exit = origExit;
+ }
+
+ // Two non-default sources exist, so tier 5.5 can't fire; pre-fix the cwd
+ // chain fell through to 'default' and repoA's pages landed there.
+ expect(await pagesIn(SRC_A)).toBeGreaterThan(0);
+ expect(await pagesIn('default')).toBe(before);
+ }, 60_000);
+});
diff --git a/test/sync-slug-root-mode-4342.test.ts b/test/sync-slug-root-mode-4342.test.ts
new file mode 100644
index 0000000000..a1901e4573
--- /dev/null
+++ b/test/sync-slug-root-mode-4342.test.ts
@@ -0,0 +1,188 @@
+/**
+ * #4342 — explicit + sticky slug namespacing (slug_root_mode).
+ *
+ * A source whose local_path is a SUBDIRECTORY of a bigger git repo used to
+ * get git-root-PREFIXED slugs implicitly (`notes/foo` instead of `foo`),
+ * diverging from `gbrain import <dir>` naming. The mode is now decided once
+ * and pinned per source:
+ *
+ * 1. fresh subdir source (no --src-subpath, no prefixed pages) →
+ * 'source-root': slugs are local_path-relative, on BOTH full and
+ * incremental syncs; the pin is persisted.
+ * 2. live install whose pages already carry the git-root prefix →
+ * auto-pins 'git-root' (no re-slug of existing brains).
+ * 3. explicit --src-subpath → 'git-root' (the #774 contract).
+ * 4. a stored pin wins over everything (sticky).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } 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 { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { performSync } from '../src/commands/sync.ts';
+import {
+ readSlugRootMode,
+ writeSlugRootMode,
+ resolveSlugRootMode,
+} from '../src/core/sync-anchor.ts';
+
+let engine: PGLiteEngine;
+let repoRoot: string;
+let subdir: string;
+
+function git(cmd: string) {
+ execSync(cmd, { cwd: repoRoot, stdio: 'pipe' });
+}
+
+function mdFile(rel: string, title: string) {
+ writeFileSync(join(repoRoot, rel), `---\ntype: concept\ntitle: ${title}\n---\n\nBody of ${title}.\n`);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ repoRoot = mkdtempSync(join(tmpdir(), 'gbrain-4342-'));
+ subdir = join(repoRoot, 'notes');
+ git('git init');
+ git('git config user.email "[email protected]"');
+ git('git config user.name "T"');
+ mkdirSync(subdir, { recursive: true });
+ mdFile('notes/alpha.md', 'Alpha');
+ mdFile('outside.md', 'Outside');
+ git('git add -A && git commit -m seed');
+});
+
+afterEach(() => {
+ if (repoRoot) rmSync(repoRoot, { recursive: true, force: true });
+});
+
+async function slugsIn(sourceId: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL ORDER BY slug`,
+ [sourceId],
+ );
+ return rows.map(r => r.slug);
+}
+
+describe('#4342 slug_root_mode', () => {
+ test('fresh subdir source pins source-root: local_path-relative slugs, full + incremental', async () => {
+ await runSources(engine, ['add', 'vault-sub', '--path', subdir, '--no-federated']);
+
+ const first = await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-sub', noEmbed: true, noPull: true,
+ });
+ expect(['first_sync', 'synced']).toContain(first.status);
+ expect(await slugsIn('vault-sub')).toEqual(['alpha']);
+ expect(await readSlugRootMode(engine, 'vault-sub')).toBe('source-root');
+
+ // Incremental add lands local_path-relative too.
+ mdFile('notes/beta.md', 'Beta');
+ git('git add -A && git commit -m add-beta');
+ const second = await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-sub', noEmbed: true, noPull: true,
+ });
+ expect(second.status).toBe('synced');
+ expect(await slugsIn('vault-sub')).toEqual(['alpha', 'beta']);
+
+ const third = await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-sub', noEmbed: true, noPull: true,
+ });
+ expect(third.status).toBe('up_to_date');
+
+ // Incremental delete resolves in the same namespace.
+ rmSync(join(repoRoot, 'notes/beta.md'));
+ git('git add -A && git commit -m del-beta');
+ const fourth = await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-sub', noEmbed: true, noPull: true,
+ });
+ expect(fourth.status).toBe('synced');
+ expect(await slugsIn('vault-sub')).toEqual(['alpha']);
+ }, 120_000);
+
+ test('live install with git-root-prefixed pages auto-pins git-root (no re-slug)', async () => {
+ await runSources(engine, ['add', 'vault-legacy', '--path', subdir, '--no-federated']);
+ // Simulate a pre-#4342 install: a page already carries the git-root prefix.
+ await engine.putPage('notes/legacy-note', {
+ type: 'concept' as never,
+ title: 'Legacy Note',
+ compiled_truth: 'Imported before #4342 under the git-root namespace.',
+ }, { sourceId: 'vault-legacy' });
+
+ const r = await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-legacy', noEmbed: true, noPull: true,
+ });
+ expect(['first_sync', 'synced']).toContain(r.status);
+ expect(await readSlugRootMode(engine, 'vault-legacy')).toBe('git-root');
+ // alpha imported under the PREFIXED namespace, matching the live install.
+ expect(await slugsIn('vault-legacy')).toContain('notes/alpha');
+ expect(await slugsIn('vault-legacy')).not.toContain('alpha');
+ }, 120_000);
+
+ test('explicit --src-subpath pins git-root (the #774 contract)', async () => {
+ const r = await performSync(engine, {
+ repoPath: repoRoot, srcSubpath: 'notes', sourceId: 'default', noEmbed: true, noPull: true,
+ });
+ expect(['first_sync', 'synced']).toContain(r.status);
+ expect(await readSlugRootMode(engine, 'default')).toBe('git-root');
+ expect(await slugsIn('default')).toContain('notes/alpha');
+ }, 120_000);
+
+ test('a stored pin is sticky — wins over the explicit flag and the heuristic', async () => {
+ await runSources(engine, ['add', 'vault-pin', '--path', subdir, '--no-federated']);
+ await writeSlugRootMode(engine, 'vault-pin', 'source-root');
+ const mode = await resolveSlugRootMode(engine, {
+ sourceId: 'vault-pin',
+ explicitGitRoot: true, // would say git-root — the pin must win
+ slugPrefix: 'notes',
+ });
+ expect(mode).toBe('source-root');
+ expect(await readSlugRootMode(engine, 'vault-pin')).toBe('source-root');
+ });
+
+ test('helpers: config-table storage for the legacy no-source path', async () => {
+ expect(await readSlugRootMode(engine, undefined)).toBeNull();
+ await writeSlugRootMode(engine, undefined, 'git-root');
+ expect(await readSlugRootMode(engine, undefined)).toBe('git-root');
+ });
+
+ test('--dry-run never persists the sticky pin (review fix: a preview must not mutate config)', async () => {
+ await runSources(engine, ['add', 'vault-dry', '--path', subdir, '--no-federated']);
+
+ // resolver-level: dryRun resolves the mode in-memory only.
+ const mode = await resolveSlugRootMode(engine, {
+ sourceId: 'vault-dry',
+ explicitGitRoot: false,
+ slugPrefix: 'notes',
+ dryRun: true,
+ });
+ expect(mode).toBe('source-root');
+ expect(await readSlugRootMode(engine, 'vault-dry')).toBeNull();
+
+ // end-to-end: a full `sync --dry-run` on a fresh scoped source leaves the
+ // pin unset — pre-fix it persisted slug_root_mode before the dry-run
+ // early-returned.
+ await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-dry', noEmbed: true, noPull: true, dryRun: true,
+ });
+ expect(await readSlugRootMode(engine, 'vault-dry')).toBeNull();
+
+ // The first REAL sync still pins it.
+ await performSync(engine, {
+ repoPath: subdir, sourceId: 'vault-dry', noEmbed: true, noPull: true,
+ });
+ expect(await readSlugRootMode(engine, 'vault-dry')).toBe('source-root');
+ }, 120_000);
+});
diff --git a/test/sync-sole-non-default-routing.test.ts b/test/sync-sole-non-default-routing.test.ts
index f3b3411b3e..c7a039bb5f 100644
--- a/test/sync-sole-non-default-routing.test.ts
+++ b/test/sync-sole-non-default-routing.test.ts
@@ -90,7 +90,10 @@ describe('#1434 — runSync auto-routes to sole_non_default source', () => {
// runSync takes (engine, args). With no --source it relies on the
// resolver to pick sole_non_default. --full to bypass git-diff
// bookmarking. --no-embed since we have no embedding provider.
- // --repo points at the synthetic vault.
+ // No --repo: since #3765 an explicit --repo routes via the repo-derived
+ // tier (dotfile/local_path anchored at the repo dir), which would
+ // short-circuit the sole_non_default tier this test pins. The anchor
+ // resolves from the source row's local_path instead.
// Note: runSync calls process.exit on some paths — guard accordingly.
const origExit = process.exit;
let exitCode: number | undefined;
@@ -100,7 +103,7 @@ describe('#1434 — runSync auto-routes to sole_non_default source', () => {
}) as typeof process.exit;
try {
- await runSync(engine, ['--full', '--no-embed', '--repo', repoPath]);
+ await runSync(engine, ['--full', '--no-embed']);
} catch (e) {
if ((e as Error).message !== '__exit__') throw e;
} finally {
@@ -168,7 +171,26 @@ describe('#1434 — runSync auto-routes to sole_non_default source', () => {
// irrelevant to what this test verifies (that 2+ non-default sources
// disable auto-routing); --force skips #2707's registration-time git
// validation, which is orthogonal to this test's assertion.
+ //
+ // #3765: --repo now routes via the repo-derived tier when the path
+ // belongs to a registered source, so this test's --repo must point at an
+ // UNREGISTERED repo — otherwise the repo tier (correctly) routes to
+ // studiovault and the seed_default fall-through under test never runs.
const secondRepo = mkdtempSync(join(tmpdir(), 'gbrain-snd-routing-second-'));
+ const unregisteredRepo = mkdtempSync(join(tmpdir(), 'gbrain-snd-routing-unreg-'));
+ execSync('git init', { cwd: unregisteredRepo, stdio: 'pipe' });
+ execSync('git config user.email "[email protected]"', { cwd: unregisteredRepo, stdio: 'pipe' });
+ execSync('git config user.name "T"', { cwd: unregisteredRepo, stdio: 'pipe' });
+ mkdirSync(join(unregisteredRepo, 'topics'), { recursive: true });
+ writeFileSync(join(unregisteredRepo, 'topics/bar.md'), [
+ '---',
+ 'type: concept',
+ 'title: Bar',
+ '---',
+ '',
+ 'fall-through body.',
+ ].join('\n'));
+ execSync('git add -A && git commit -m initial', { cwd: unregisteredRepo, stdio: 'pipe' });
await runSources(engine, ['add', 'studiovault', '--path', repoPath, '--no-federated']);
await runSources(engine, ['add', 'second-vault', '--path', secondRepo, '--no-federated', '--force']);
const { runSync } = await import('../src/commands/sync.ts');
@@ -188,7 +210,7 @@ describe('#1434 — runSync auto-routes to sole_non_default source', () => {
const origExit = process.exit;
process.exit = ((_code?: number) => { throw new Error('__exit__'); }) as typeof process.exit;
try {
- await runSync(engine, ['--full', '--no-embed', '--repo', repoPath]);
+ await runSync(engine, ['--full', '--no-embed', '--repo', unregisteredRepo]);
} catch (e) {
if ((e as Error).message !== '__exit__') throw e;
} finally {
diff --git a/test/take-proposals.test.ts b/test/take-proposals.test.ts
new file mode 100644
index 0000000000..ff2c24e6d4
--- /dev/null
+++ b/test/take-proposals.test.ts
@@ -0,0 +1,261 @@
+/**
+ * #2411 — take_proposals drain surface.
+ *
+ * The propose_takes cycle phase writes proposals to `take_proposals`, and the
+ * D17 posture says explicit operator accept is the ONLY queue→canonical path.
+ * Before this fix nothing implemented that path: `gbrain takes propose` fell
+ * through the dispatcher to the page-slug branch and printed
+ * "No takes on propose." (exit 0), so proposals accumulated forever and
+ * nothing ever wrote status='accepted'.
+ *
+ * Covers, against a real PGLite engine + temp markdown repo:
+ * - listPendingProposals: pending-only (tombstones/acted rows excluded),
+ * source-scoped
+ * - acceptProposal: fence write via addTakeToPage + status='accepted' +
+ * promoted_row_num/acted_at/acted_by stamps
+ * - rejectProposal: status='rejected' + stamps, no markdown write
+ * - double-accept refuses with not_pending
+ * - source scope: an out-of-scope id reads as not_found
+ * - CLI dispatcher: `takes propose` no longer falls through to the slug path
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ listPendingProposals,
+ acceptProposal,
+ rejectProposal,
+ coerceProposalKind,
+ TakeProposalError,
+} from '../src/core/take-proposals.ts';
+import { runTakes } from '../src/commands/takes.ts';
+import { parseTakesFence } from '../src/core/takes-fence.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+async function insertProposal(opts: {
+ slug: string;
+ claim: string;
+ sourceId?: string;
+ kind?: string;
+ holder?: string;
+ weight?: number;
+ status?: string;
+}): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO take_proposals
+ (source_id, page_slug, content_hash, prompt_version, proposal_run_id,
+ claim_text, kind, holder, weight, domain, model_id, status)
+ VALUES ($1, $2, md5($6), 'test-v1', 'run-test', $6, $3, $4, $5, NULL, 'test-model', $7)
+ RETURNING id`,
+ [
+ opts.sourceId ?? 'default',
+ opts.slug,
+ opts.kind ?? 'bet',
+ opts.holder ?? 'world',
+ opts.weight ?? 0.7,
+ opts.claim,
+ opts.status ?? 'pending',
+ ],
+ );
+ return rows[0].id;
+}
+
+async function proposalRow(id: number) {
+ const rows = await engine.executeRaw<{
+ status: string; promoted_row_num: number | null; acted_by: string | null; acted_at: string | null;
+ }>(`SELECT status, promoted_row_num, acted_by, acted_at FROM take_proposals WHERE id = $1`, [id]);
+ return rows[0];
+}
+
+async function captureStdout(fn: () => Promise<void>): Promise<string> {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try {
+ await fn();
+ } finally {
+ console.log = orig;
+ }
+ return lines.join('\n');
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-take-proposals-'));
+ await engine.setConfig('sync.repo_path', repo);
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('other', 'Other') ON CONFLICT (id) DO NOTHING`,
+ [],
+ );
+ for (const slug of ['companies/acme-example', 'companies/widget-co']) {
+ await engine.putPage(slug, { type: 'company', title: slug, compiled_truth: `about ${slug}` });
+ mkdirSync(join(repo, 'companies'), { recursive: true });
+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\nabout ${slug}\n`, 'utf-8');
+ }
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('listPendingProposals', () => {
+ test('lists pending rows only, excluding acted rows and other sources', async () => {
+ const pendingId = await insertProposal({ slug: 'companies/acme-example', claim: 'list: pending claim' });
+ const rejectedId = await insertProposal({
+ slug: 'companies/acme-example', claim: 'list: already rejected', status: 'rejected',
+ });
+ const otherSourceId = await insertProposal({
+ slug: 'companies/acme-example', claim: 'list: other-source claim', sourceId: 'other',
+ });
+
+ const rows = await listPendingProposals(engine, { sourceId: 'default', limit: 50 });
+ const ids = rows.map((r) => r.id);
+ expect(ids).toContain(pendingId);
+ expect(ids).not.toContain(rejectedId);
+ expect(ids).not.toContain(otherSourceId);
+ for (const r of rows) expect(r.status).toBe('pending');
+ });
+});
+
+describe('acceptProposal', () => {
+ test('promotes into the fence via addTakeToPage and stamps accepted + promoted_row_num', async () => {
+ const id = await insertProposal({
+ slug: 'companies/acme-example', claim: 'Acme ships the widget by Q3', kind: 'bet', weight: 0.8,
+ });
+ const { rowNum, proposal } = await acceptProposal(
+ { engine, brainDir: repo, sourceId: 'default', actedBy: 'people/tester' },
+ id,
+ );
+ expect(proposal.page_slug).toBe('companies/acme-example');
+ expect(rowNum).toBeGreaterThan(0);
+
+ // Markdown-canonical: the fence on disk holds the promoted claim.
+ const fence = parseTakesFence(readFileSync(join(repo, 'companies/acme-example.md'), 'utf-8'));
+ const promoted = fence.takes.find((t) => t.claim === 'Acme ships the widget by Q3');
+ expect(promoted).toBeDefined();
+ expect(promoted!.rowNum).toBe(rowNum);
+
+ // DB mirror carries the row too.
+ const takes = await engine.listTakes({ page_slug: 'companies/acme-example', active: true });
+ expect(takes.some((t) => t.claim === 'Acme ships the widget by Q3' && t.row_num === rowNum)).toBe(true);
+
+ // Queue row is stamped.
+ const row = await proposalRow(id);
+ expect(row.status).toBe('accepted');
+ expect(row.promoted_row_num).toBe(rowNum);
+ expect(row.acted_by).toBe('people/tester');
+ expect(row.acted_at).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);
+ try {
+ await acceptProposal({ engine, brainDir: repo, sourceId: 'default' }, id);
+ throw new Error('should have thrown');
+ } catch (err) {
+ expect((err as TakeProposalError).code).toBe('not_pending');
+ }
+ });
+
+ 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',
+ });
+ try {
+ await acceptProposal({ engine, brainDir: repo, sourceId: 'default' }, id);
+ throw new Error('should have thrown');
+ } catch (err) {
+ expect(err).toBeInstanceOf(TakeProposalError);
+ expect((err as TakeProposalError).code).toBe('not_found');
+ }
+ // Row untouched.
+ expect((await proposalRow(id)).status).toBe('pending');
+ });
+
+ test('unknown id → not_found', async () => {
+ try {
+ await acceptProposal({ engine, brainDir: repo, sourceId: 'default' }, 99999999);
+ throw new Error('should have thrown');
+ } catch (err) {
+ expect((err as TakeProposalError).code).toBe('not_found');
+ }
+ });
+});
+
+describe('rejectProposal', () => {
+ test('stamps rejected + acted_by without touching the fence', async () => {
+ const before = readFileSync(join(repo, 'companies/widget-co.md'), 'utf-8');
+ const id = await insertProposal({ slug: 'companies/widget-co', claim: 'reject: never promoted' });
+ const proposal = await rejectProposal({ engine, sourceId: 'default', actedBy: 'people/tester' }, id);
+ expect(proposal.claim_text).toBe('reject: never promoted');
+ const row = await proposalRow(id);
+ expect(row.status).toBe('rejected');
+ expect(row.acted_by).toBe('people/tester');
+ // No markdown write happened (reject is DB-only).
+ const after = readFileSync(join(repo, 'companies/widget-co.md'), 'utf-8');
+ expect(after.includes('reject: never promoted')).toBe(false);
+ expect(after.length >= before.length).toBe(true);
+ });
+
+ test('rejecting an acted row refuses with not_pending', async () => {
+ const id = await insertProposal({
+ slug: 'companies/widget-co', claim: 'reject: already accepted', status: 'accepted',
+ });
+ try {
+ await rejectProposal({ engine, sourceId: 'default' }, id);
+ throw new Error('should have thrown');
+ } catch (err) {
+ expect((err as TakeProposalError).code).toBe('not_pending');
+ }
+ });
+});
+
+describe('coerceProposalKind', () => {
+ test('canonical kinds pass through; prediction→bet; unknown→take', () => {
+ expect(coerceProposalKind('bet')).toBe('bet');
+ expect(coerceProposalKind('fact')).toBe('fact');
+ expect(coerceProposalKind('hunch')).toBe('hunch');
+ expect(coerceProposalKind('take')).toBe('take');
+ expect(coerceProposalKind('prediction')).toBe('bet');
+ expect(coerceProposalKind('garbage')).toBe('take');
+ });
+});
+
+describe('CLI dispatcher (#2411 no-fallthrough)', () => {
+ test('`takes propose` lists the queue instead of slug-ifying "propose"', async () => {
+ const id = await insertProposal({ slug: 'companies/acme-example', claim: 'cli: pending list claim' });
+ const out = await captureStdout(() => runTakes(engine, ['propose']));
+ expect(out).not.toContain('No takes on propose.');
+ expect(out).toContain('cli: pending list claim');
+ expect(out).toContain(`#${id}`);
+ });
+
+ test('`takes propose --json` returns rows', async () => {
+ const out = await captureStdout(() => runTakes(engine, ['propose', '--json', '--limit', '100']));
+ const parsed = JSON.parse(out);
+ expect(Array.isArray(parsed)).toBe(true);
+ expect(parsed.some((r: { claim_text: string }) => r.claim_text === 'cli: pending list claim')).toBe(true);
+ });
+
+ test('`takes propose --accept <id>` promotes and reports the fence row', async () => {
+ const id = await insertProposal({ slug: 'companies/acme-example', claim: 'cli: accept me' });
+ const out = await captureStdout(() => runTakes(engine, ['propose', '--accept', String(id)]));
+ expect(out).toContain(`Accepted proposal #${id}`);
+ expect((await proposalRow(id)).status).toBe('accepted');
+ });
+
+ test('`takes propose --reject <id>` rejects', async () => {
+ const id = await insertProposal({ slug: 'companies/acme-example', claim: 'cli: reject me' });
+ const out = await captureStdout(() => runTakes(engine, ['propose', '--reject', String(id)]));
+ expect(out).toContain(`Rejected proposal #${id}`);
+ expect((await proposalRow(id)).status).toBe('rejected');
+ });
+});
diff --git a/test/takes-fence.test.ts b/test/takes-fence.test.ts
index f1b6145a8e..81c44dc7c3 100644
--- a/test/takes-fence.test.ts
+++ b/test/takes-fence.test.ts
@@ -66,6 +66,29 @@ describe('parseTakesFence', () => {
expect(warnings).toEqual([]);
});
+ // #3769 — a fence written with the standard TWO-dash HTML comment form
+ // (`<!-- gbrain:takes:begin -->`) is a fence the author MEANT to write;
+ // pre-fix it parsed as "no fence at all" with zero warnings.
+ test('warns TAKES_FENCE_NEAR_MISS on the two-dash comment form', () => {
+ const body = `## Takes
+
+<!-- gbrain:takes:begin -->
+| # | claim | kind | who | weight | since | source |
+|---|-------|------|-----|--------|-------|--------|
+| 1 | Some claim | fact | world | 1.0 | 2026-01 | source |
+<!-- gbrain:takes:end -->
+`;
+ const { takes, warnings } = parseTakesFence(body);
+ expect(takes).toEqual([]);
+ expect(warnings.some(w => w.includes('TAKES_FENCE_NEAR_MISS'))).toBe(true);
+ });
+
+ test('no near-miss warning for prose that merely mentions takes', () => {
+ const { takes, warnings } = parseTakesFence('# Prose\n\nI have hot takes about fences.');
+ expect(takes).toEqual([]);
+ expect(warnings).toEqual([]);
+ });
+
test('warns on unbalanced fence (missing end)', () => {
const body = `## Takes\n\n${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n`;
const { takes, warnings } = parseTakesFence(body);
diff --git a/test/takes-propose-drain.test.ts b/test/takes-propose-drain.test.ts
new file mode 100644
index 0000000000..a170911d3e
--- /dev/null
+++ b/test/takes-propose-drain.test.ts
@@ -0,0 +1,128 @@
+/**
+ * #4102 — end-to-end drain of the take_proposals queue over a real PGLite
+ * engine: the propose_takes cycle phase PRODUCES pending proposals, and the
+ * new `gbrain takes propose` surface CONSUMES them (list → accept → fence).
+ *
+ * Before this wave the queue had a producer and no consumer: nothing in the
+ * codebase ever wrote status='accepted', so proposals accumulated forever
+ * and the phase's whole output was unreachable.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync, mkdirSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseProposeTakes, type ProposeTakesExtractor } from '../src/core/cycle/propose-takes.ts';
+import { runTakes } from '../src/commands/takes.ts';
+import { parseTakesFence } from '../src/core/takes-fence.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+const SLUG = 'companies/drain-example';
+const CLAIM = 'Drain-example doubles revenue within 12 months';
+
+function ctx(): OperationContext {
+ return {
+ engine,
+ config: {} as never,
+ logger: { info() {}, warn() {}, error() {} } as never,
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ };
+}
+
+async function captureStdout(fn: () => Promise<void>): Promise<string> {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try {
+ await fn();
+ } finally {
+ console.log = orig;
+ }
+ return lines.join('\n');
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-propose-drain-'));
+ await engine.setConfig('sync.repo_path', repo);
+ await engine.putPage(SLUG, {
+ type: 'company',
+ title: 'Drain Example',
+ compiled_truth: 'I bet drain-example doubles revenue within 12 months. They ship fast.',
+ });
+ mkdirSync(join(repo, 'companies'), { recursive: true });
+ writeFileSync(join(repo, `${SLUG}.md`), `# Drain Example\n\nprose body\n`, 'utf-8');
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('propose_takes → takes propose drain (#4102)', () => {
+ test('phase inserts a pending proposal; CLI lists, accepts, and stamps promoted_row_num', async () => {
+ // 1. Produce: run the phase with an injected extractor (no gateway).
+ const extractor: ProposeTakesExtractor = async () => [
+ { claim_text: CLAIM, kind: 'bet', holder: 'world', weight: 0.75, domain: 'revenue' },
+ ];
+ const phase = await runPhaseProposeTakes(ctx(), { extractor });
+ expect(phase.status).toBe('ok');
+ expect((phase.details as Record<string, unknown>).proposals_inserted).toBe(1);
+
+ const [pending] = await engine.executeRaw<{ id: number; status: string }>(
+ `SELECT id, status FROM take_proposals WHERE claim_text = $1`,
+ [CLAIM],
+ );
+ expect(pending.status).toBe('pending');
+
+ // 2. List: the CLI surfaces the pending proposal.
+ const listed = await captureStdout(() => runTakes(engine, ['propose']));
+ expect(listed).toContain(CLAIM);
+ expect(listed).toContain(`#${pending.id}`);
+
+ // 3. Accept: promotes into the markdown fence + DB mirror.
+ const accepted = await captureStdout(() =>
+ runTakes(engine, ['propose', '--accept', String(pending.id)]));
+ expect(accepted).toContain(`Accepted proposal #${pending.id}`);
+
+ const fence = parseTakesFence(readFileSync(join(repo, `${SLUG}.md`), 'utf-8'));
+ const row = fence.takes.find((t) => t.claim === CLAIM);
+ expect(row).toBeDefined();
+
+ const [acted] = await engine.executeRaw<{ status: string; promoted_row_num: number | null }>(
+ `SELECT status, promoted_row_num FROM take_proposals WHERE id = $1`,
+ [pending.id],
+ );
+ expect(acted.status).toBe('accepted');
+ expect(acted.promoted_row_num).toBe(row!.rowNum);
+
+ // 4. The queue is drained: nothing pending remains.
+ const after = await captureStdout(() => runTakes(engine, ['propose']));
+ expect(after).toContain('No pending take proposals');
+ });
+
+ test('config off switch stops the phase against a real engine; --once bypasses', async () => {
+ await engine.setConfig('cycle.propose_takes.enabled', 'false');
+ try {
+ let calls = 0;
+ const extractor: ProposeTakesExtractor = async () => { calls += 1; return []; };
+ const gated = await runPhaseProposeTakes(ctx(), { extractor });
+ expect(gated.status).toBe('skipped');
+ expect((gated.details as Record<string, unknown>).reason).toBe('disabled');
+ expect(calls).toBe(0);
+
+ const once = await runPhaseProposeTakes(ctx(), { extractor, once: true });
+ expect(once.status).not.toBe('skipped');
+ expect(calls).toBeGreaterThan(0);
+ } finally {
+ await engine.setConfig('cycle.propose_takes.enabled', 'true');
+ }
+ });
+});
diff --git a/test/test-reads-source-smell.test.ts b/test/test-reads-source-smell.test.ts
new file mode 100644
index 0000000000..80059889eb
--- /dev/null
+++ b/test/test-reads-source-smell.test.ts
@@ -0,0 +1,130 @@
+/**
+ * #3665 — source-text-assertion smell gate.
+ *
+ * A test whose assertions run over `readFileSync`'d src/ TEXT pins spelling,
+ * not behavior: it keeps passing when the behavior breaks in a way that
+ * preserves the grepped token, and it breaks when a harmless rename lands.
+ * Sometimes that is exactly the right tool (structural guards over generated
+ * files, comment-contract pins, guards for code that cannot run in a unit
+ * test) — but it must be a deliberate choice, not the default.
+ *
+ * Rule: a line in a test file that readFileSync's a literal src/ path needs a
+ * `test-reads-source-ok: <why>` comment on the line or within the 3 lines
+ * above. Files that predate the rule are in FROZEN_ALLOWLIST below; the list
+ * must only SHRINK (stale entries fail the suite so pruning is forced).
+ *
+ * Limitation (documented): only literal same-line `src/` paths are caught —
+ * a path built from variables slips through. That keeps false positives at
+ * zero, which is what lets this run in CI at all.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'fs';
+import { join, relative } from 'path';
+
+const TEST_DIR = import.meta.dir;
+
+/** Same-line literal read into src/ (or ../src/, or a URL/join ending there). */
+const READS_SRC = /readFileSync[^;\n]*['"`(/][^;\n]*\bsrc\//;
+const MARKER = 'test-reads-source-ok';
+
+/**
+ * Files with unannotated src-text reads that predate the rule. FROZEN:
+ * never add an entry — annotate the read with `test-reads-source-ok: <why>`
+ * (or assert runtime behavior instead). Prune entries as files get cleaned;
+ * a stale entry fails the suite.
+ */
+const FROZEN_ALLOWLIST = new Set([
+ 'admin-sse-eventsource.test.ts',
+ 'agent-register.test.ts',
+ 'apply-migrations.test.ts',
+ 'archived-source-scoping.test.ts',
+ 'autopilot-auto-drain-wiring.test.ts',
+ 'autopilot-install.test.ts',
+ 'autopilot-pause-marker.test.ts',
+ 'autopilot-self-upgrade.test.ts',
+ 'backlinks-job-default.test.ts',
+ 'cli-force-exit-teardown-arming.test.ts',
+ 'cli.test.ts',
+ 'connection-resilience.test.ts',
+ 'conversation-facts-type-allowlist-drift.test.ts',
+ 'cycle-abort.test.ts',
+ 'cycle-drain-renewal.test.ts',
+ 'cycle-patterns-deadline-budget.test.ts',
+ 'destructive-guard.test.ts',
+ 'doctor-orphan-ratio.test.ts',
+ 'dream-cli-flags.test.ts',
+ 'exit-classification.test.ts',
+ 'extract-atoms-drain.test.ts',
+ 'fence-extraction.test.ts',
+ 'fix-wave-structural.test.ts',
+ 'integrations.test.ts',
+ 'migrate-stdout-clean.test.ts',
+ 'migrate.test.ts',
+ 'migrations-v0_22_4.test.ts',
+ 'pglite-engine.test.ts',
+ 'pglite-wal-repair.serial.test.ts',
+ 'phantom-redirect-per-source-lock.test.ts',
+ 'register-client-source-normalize.test.ts',
+ 'regression-strict-source-id.test.ts',
+ 'reindex-code-recovery.test.ts',
+ 'schema-cli-contract.test.ts',
+ 'schema-pack-unify-types-handler.test.ts',
+ 'scripts/classify-tests.test.ts',
+ 'serve-http-github-webhook.test.ts',
+ 'serve-http-mcp-transport-cleanup.test.ts',
+ 'timing-safe.test.ts',
+ 'transcription-injection.test.ts',
+]);
+
+function* testFiles(dir: string): Generator<string> {
+ for (const entry of readdirSync(dir)) {
+ const p = join(dir, entry);
+ if (statSync(p).isDirectory()) yield* testFiles(p);
+ else if (p.endsWith('.test.ts')) yield p;
+ }
+}
+
+function offendingFiles(): Map<string, number[]> {
+ const out = new Map<string, number[]>();
+ for (const f of testFiles(TEST_DIR)) {
+ const rel = relative(TEST_DIR, f);
+ if (rel === 'test-reads-source-smell.test.ts') continue; // this file names the pattern in prose
+ const lines = readFileSync(f, 'utf-8').split('\n');
+ const hits: number[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (!READS_SRC.test(lines[i]!)) continue;
+ const context = lines.slice(Math.max(0, i - 3), i + 1).join('\n');
+ if (context.includes(MARKER)) continue;
+ hits.push(i + 1);
+ }
+ if (hits.length > 0) out.set(rel, hits);
+ }
+ return out;
+}
+
+describe('#3665 — tests that read src/ text need a justification', () => {
+ test('no NEW test file readFileSyncs src/* without a test-reads-source-ok comment', () => {
+ const offenders = offendingFiles();
+ const fresh = [...offenders.entries()].filter(([rel]) => !FROZEN_ALLOWLIST.has(rel));
+ const msg = fresh
+ .map(([rel, lines]) => `test/${rel}:${lines.join(',')}`)
+ .join('\n');
+ expect(
+ fresh.map(([rel]) => rel),
+ `New source-text reads in tests without justification:\n${msg}\n` +
+ `Either assert runtime behavior instead, or add a comment within 3 lines above the read:\n` +
+ ` // ${MARKER}: <why grepping source text is the right tool here>\n` +
+ `Do NOT add entries to FROZEN_ALLOWLIST — it only shrinks.`,
+ ).toEqual([]);
+ });
+
+ test('the frozen allowlist only shrinks (stale entries must be pruned)', () => {
+ const offenders = offendingFiles();
+ const stale = [...FROZEN_ALLOWLIST].filter((rel) => !offenders.has(rel));
+ expect(
+ stale,
+ `Allowlist entries whose files no longer have unannotated src reads (or were deleted) — prune them:\n${stale.join('\n')}`,
+ ).toEqual([]);
+ });
+});
diff --git a/test/think-ab.test.ts b/test/think-ab.test.ts
index c8e5fc49aa..56f2ad68ff 100644
--- a/test/think-ab.test.ts
+++ b/test/think-ab.test.ts
@@ -216,7 +216,10 @@ describe('formatAbReport', () => {
decisive_trials: 0,
}, 30);
expect(out).toContain('No data yet');
- expect(out).toContain('gbrain think --ab');
+ // #3697: the report must NOT advertise `gbrain think --ab` — think.ts never
+ // parses --ab (it would be swallowed into the question positional), so the
+ // old hint sent users to a silently-misparsed command.
+ expect(out).not.toContain('gbrain think --ab');
});
test('decisive-trials breakdown', () => {
diff --git a/test/think-persist-take.test.ts b/test/think-persist-take.test.ts
new file mode 100644
index 0000000000..30e76e90e0
--- /dev/null
+++ b/test/think-persist-take.test.ts
@@ -0,0 +1,139 @@
+/**
+ * #2556 — `gbrain think --take` actually persists a take row.
+ *
+ * The flag was documented + parsed + remote-gated since v0.28, but
+ * RunThinkOpts.take was never read: no think path called addTakeToPage, so
+ * `--take` silently persisted nothing. persistTakeFromSynthesis is the
+ * missing execution half; these tests pin:
+ *
+ * 1. claimFromAnswer: first substantive line, gaps stripped, markdown
+ * markers removed, fence-cell sanitization, bounded length.
+ * 2. Happy path on PGLite + a tmp brain repo: fence row lands on DISK
+ * (md-first) AND the DB mirror row exists; take_row returned.
+ * 3. Warning paths: synthesisOk=false, empty answer, no brain repo
+ * (TAKE_MIRROR_UNAVAILABLE), missing anchor page (TAKE_WRITE_FAILED).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ claimFromAnswer,
+ persistTakeFromSynthesis,
+ TAKE_CLAIM_MAX_CHARS,
+} from '../src/core/think/persist-take.ts';
+
+let engine: PGLiteEngine;
+let brainDir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-2556-'));
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+ if (brainDir) rmSync(brainDir, { recursive: true, force: true });
+}, 60_000);
+
+describe('#2556 claimFromAnswer (pure)', () => {
+ test('takes the first substantive line and strips markdown markers', () => {
+ expect(claimFromAnswer('## Verdict\n\n- Alice is the strongest founder in the batch.\nMore detail.'))
+ .toBe('Verdict');
+ expect(claimFromAnswer('\n\n- Alice is the strongest founder in the batch.\nMore.'))
+ .toBe('Alice is the strongest founder in the batch.');
+ });
+
+ test('strips the Gaps section before extracting', () => {
+ const answer = '## Gaps\n- missing data\n\n## Answer\nThe real claim.';
+ // stripGapsSection removes ONLY the gaps block; the next line wins.
+ expect(claimFromAnswer(answer)).toBe('Answer');
+ });
+
+ test('sanitizes fence-hostile content to a single safe cell', () => {
+ expect(claimFromAnswer('claim with\ttabs and gbrain:takes marker')).toBe('claim with tabs and marker');
+ // Wholly-strikethrough would round-trip inactive — unwrapped.
+ expect(claimFromAnswer('~~struck claim~~')).toBe('struck claim');
+ });
+
+ test('bounds the claim length', () => {
+ const long = 'x'.repeat(TAKE_CLAIM_MAX_CHARS * 2);
+ const claim = claimFromAnswer(long)!;
+ expect(claim.length).toBeLessThanOrEqual(TAKE_CLAIM_MAX_CHARS);
+ });
+
+ test('returns null for empty/whitespace answers', () => {
+ expect(claimFromAnswer('')).toBeNull();
+ expect(claimFromAnswer('\n\n \n')).toBeNull();
+ });
+});
+
+describe('#2556 persistTakeFromSynthesis (PGLite + tmp repo)', () => {
+ test('synthesisOk=false warn-skips (never mints a take from a stub)', async () => {
+ const r = await persistTakeFromSynthesis(engine, { answer: 'stub', synthesisOk: false }, { anchor: 'x' });
+ expect(r.take_row).toBeNull();
+ expect(r.warnings).toContain('TAKE_SKIPPED_SYNTHESIS_FAILED');
+ });
+
+ test('empty answer warn-skips', async () => {
+ const r = await persistTakeFromSynthesis(engine, { answer: ' ', synthesisOk: true }, { anchor: 'x' });
+ expect(r.take_row).toBeNull();
+ expect(r.warnings).toContain('TAKE_SKIPPED_EMPTY_ANSWER');
+ });
+
+ test('no brain repo → TAKE_MIRROR_UNAVAILABLE (md is canonical)', async () => {
+ // sync.repo_path unset at this point.
+ const r = await persistTakeFromSynthesis(engine, { answer: 'A real claim.', synthesisOk: true }, { anchor: 'x' });
+ expect(r.take_row).toBeNull();
+ expect(r.warnings).toContain('TAKE_MIRROR_UNAVAILABLE');
+ });
+
+ test('happy path: fence row on disk + DB mirror row + take_row', async () => {
+ await engine.setConfig('sync.repo_path', brainDir);
+ await engine.putPage('people/alice-example', {
+ type: 'person' as never,
+ title: 'Alice Example',
+ compiled_truth: 'A founder page.',
+ });
+
+ const r = await persistTakeFromSynthesis(
+ engine,
+ { answer: '- Alice is the strongest founder in the batch.\n\nDetail follows.', synthesisOk: true },
+ { anchor: 'people/alice-example' },
+ );
+ expect(r.warnings.filter(w => w.startsWith('TAKE_'))).toEqual([]);
+ expect(r.take_row).toBe(1);
+ expect(r.path).toBeDefined();
+
+ // md-first: the fence row is on disk.
+ expect(existsSync(r.path!)).toBe(true);
+ const body = readFileSync(r.path!, 'utf-8');
+ expect(body).toContain('gbrain:takes');
+ expect(body).toContain('Alice is the strongest founder in the batch.');
+
+ // DB mirror row exists with the owner holder + think source.
+ const rows = await engine.executeRaw<{ claim: string; holder: string; kind: string; source: string | null }>(
+ `SELECT t.claim, t.holder, t.kind, t.source
+ FROM takes t JOIN pages p ON p.id = t.page_id
+ WHERE p.slug = 'people/alice-example' AND p.source_id = 'default'`,
+ );
+ expect(rows.length).toBe(1);
+ expect(rows[0]!.claim).toBe('Alice is the strongest founder in the batch.');
+ expect(rows[0]!.kind).toBe('take');
+ expect(rows[0]!.source).toBe('think');
+ }, 60_000);
+
+ test('missing anchor page → TAKE_WRITE_FAILED warning, never a throw', async () => {
+ const r = await persistTakeFromSynthesis(
+ engine,
+ { answer: 'A claim.', synthesisOk: true },
+ { anchor: 'people/no-such-page' },
+ );
+ expect(r.take_row).toBeNull();
+ expect(r.warnings.some(w => w.startsWith('TAKE_WRITE_FAILED'))).toBe(true);
+ }, 60_000);
+});
diff --git a/test/timeline-dedup-repair.test.ts b/test/timeline-dedup-repair.test.ts
index bfacab68a4..96fd6df727 100644
--- a/test/timeline-dedup-repair.test.ts
+++ b/test/timeline-dedup-repair.test.ts
@@ -72,7 +72,7 @@ describe('#2038 idx_timeline_dedup drift repair', () => {
expect(status.needsRepair).toBe(true);
});
- test('rebuilds the 3-column index to 4 columns (no dupes to collapse)', async () => {
+ test('rebuilds the 3-column index to the md5-keyed 4-column shape (no dupes to collapse)', async () => {
await regressTo3Col();
await engine.executeRaw(
`INSERT INTO timeline_entries (page_id, date, summary, source, detail)
@@ -86,7 +86,8 @@ describe('#2038 idx_timeline_dedup drift repair', () => {
expect(res.collapsedDuplicates).toBe(0);
const after = await checkTimelineDedupIndex(engine);
- expect(after.columns).toEqual(['page_id', 'date', 'summary', 'source']);
+ // #3737: canonical shape keys md5(summary).
+ expect(after.columns).toEqual(['page_id', 'date', 'md5(summary)', 'source']);
expect(after.needsRepair).toBe(false);
});
@@ -102,7 +103,7 @@ describe('#2038 idx_timeline_dedup drift repair', () => {
expect(res.collapsedDuplicates).toBe(1); // one of the two 'meeting' rows removed
const after = await checkTimelineDedupIndex(engine);
- expect(after.columns).toEqual(['page_id', 'date', 'summary', 'source']);
+ expect(after.columns).toEqual(['page_id', 'date', 'md5(summary)', 'source']);
const rows = await engine.executeRaw<{ n: string }>(
`SELECT COUNT(*)::text AS n FROM timeline_entries`,
);
@@ -117,3 +118,225 @@ describe('#2038 idx_timeline_dedup drift repair', () => {
expect(second.reason).toBe('already_correct');
});
});
+
+// ─── #3737: raw-summary btree overflow → md5-keyed dedup tuple ──────────
+
+import { parseIndexColumns } from '../src/core/timeline-dedup-repair.ts';
+import { randomBytes } from 'crypto';
+
+/** Regress to the pre-#3737 raw-summary 4-column shape. */
+async function regressToRaw4Col() {
+ await engine.executeRaw(`DELETE FROM timeline_entries`);
+ await engine.executeRaw(`DROP INDEX IF EXISTS idx_timeline_dedup`);
+ await engine.executeRaw(
+ `CREATE UNIQUE INDEX idx_timeline_dedup ON timeline_entries(page_id, date, summary, source)`,
+ );
+}
+
+describe('#3737 md5-keyed dedup index', () => {
+ test('parseIndexColumns keeps md5(summary) whole (first-paren fix)', () => {
+ expect(parseIndexColumns(
+ 'CREATE UNIQUE INDEX idx_timeline_dedup ON public.timeline_entries USING btree (page_id, date, md5(summary), source)',
+ )).toEqual(['page_id', 'date', 'md5(summary)', 'source']);
+ // Raw shape still parses (drift detection input).
+ expect(parseIndexColumns(
+ 'CREATE UNIQUE INDEX idx_timeline_dedup ON public.timeline_entries USING btree (page_id, date, summary, source)',
+ )).toEqual(['page_id', 'date', 'summary', 'source']);
+ });
+
+ test('the pre-#3737 raw-summary shape reads as drift and rebuilds to md5', async () => {
+ await regressToRaw4Col();
+ const status = await checkTimelineDedupIndex(engine);
+ expect(status.needsRepair).toBe(true);
+ const res = await repairTimelineDedupIndex(engine);
+ expect(res.repaired).toBe(true);
+ const after = await checkTimelineDedupIndex(engine);
+ expect(after.columns).toEqual(['page_id', 'date', 'md5(summary)', 'source']);
+ expect(after.needsRepair).toBe(false);
+ });
+
+ test('healthy md5 index is NOT rebuilt on every pass (self-heal must not revert)', async () => {
+ await regressToRaw4Col();
+ await repairTimelineDedupIndex(engine);
+ const second = await repairTimelineDedupIndex(engine);
+ expect(second.repaired).toBe(false);
+ expect(second.reason).toBe('already_correct');
+ });
+
+ test('3100-char incompressible summary inserts and dedups (single + batch)', async () => {
+ await regressToRaw4Col();
+ await repairTimelineDedupIndex(engine);
+ const big = randomBytes(1550).toString('hex'); // 3100 chars, incompressible
+
+ // Pre-fix: "index row size 3128 exceeds btree version 4 maximum 2704".
+ const first = await engine.addTimelineEntry(
+ 'people/alice-example',
+ { date: '2026-01-05', source: 'meeting', summary: big, detail: '' },
+ );
+ expect(first).toBe(true);
+ // Same tuple again → deduped via the md5 conflict target, not an error.
+ const dup = await engine.addTimelineEntry(
+ 'people/alice-example',
+ { date: '2026-01-05', source: 'meeting', summary: big, detail: '' },
+ );
+ expect(dup).toBe(false);
+
+ const batchDup = await engine.addTimelineEntriesBatch([
+ { slug: 'people/alice-example', date: '2026-01-05', source: 'meeting', summary: big, detail: '', source_id: 'default' },
+ ]);
+ expect(batchDup).toBe(0);
+ const batchNew = await engine.addTimelineEntriesBatch([
+ { slug: 'people/alice-example', date: '2026-01-06', source: 'meeting', summary: big, detail: '', source_id: 'default' },
+ ]);
+ expect(batchNew).toBe(1);
+
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM timeline_entries`,
+ );
+ expect(parseInt(rows[0].n, 10)).toBe(2);
+ });
+});
+
+// ─── #3957: legacy (source='') row shape repair ──────────────────────────
+
+import { repairLegacyTimelineSourceRows } from '../src/core/timeline-dedup-repair.ts';
+import { MIGRATIONS } from '../src/core/migrate.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+
+describe("#3957 legacy-row (source='') shape repair", () => {
+ const PIPE_BULLET = '- **2026-01-05** | meeting — Discussed the wiki';
+ const DASH_BULLET = '- **2026-01-06** - moved to Berlin - permanently';
+
+ async function resetLegacyState() {
+ // Canonical md5 index back in place (earlier describe blocks regress it),
+ // then a clean slate for rows + repair-target pages.
+ await repairTimelineDedupIndex(engine);
+ await engine.executeRaw(`DELETE FROM timeline_entries`);
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'legacy/%'`);
+ }
+
+ async function seedLegacyPage(slug: string, content: string): Promise<string> {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
+ VALUES ($1, 'default', 'note', $1, $2, '')`,
+ [slug, content],
+ );
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id::text AS id FROM pages WHERE slug = $1 AND source_id = 'default'`,
+ [slug],
+ );
+ return rows[0]!.id;
+ }
+
+ async function timelineRowsFor(pid: string) {
+ return engine.executeRaw<{ source: string; summary: string }>(
+ `SELECT source, summary FROM timeline_entries WHERE page_id = $1 ORDER BY id`,
+ [pid],
+ );
+ }
+
+ test('THE review case: legacy pipe-bullet row + re-extract → exactly one split row after repair', async () => {
+ await resetLegacyState();
+ const pid = await seedLegacyPage('legacy/pipe', `# Pipe\n\n${PIPE_BULLET}\n`);
+ // Pre-#3957 DB-path shape: source='' + the UNSPLIT `Source — Summary`.
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES ($1, '2026-01-05', '', 'meeting — Discussed the wiki', '')`,
+ [pid],
+ );
+
+ const r = await repairLegacyTimelineSourceRows(engine);
+ expect(r.rowsRewritten).toBe(1);
+ expect(r.rowsDeleted).toBe(0);
+
+ // Rewritten in place to the split shape the new parser emits.
+ let rows = await timelineRowsFor(pid);
+ expect(rows).toEqual([{ source: 'meeting', summary: 'Discussed the wiki' }]);
+
+ // Re-extract (the stale sweep) now DEDUPS onto the repaired row instead
+ // of duplicating — pre-repair this left TWO rows.
+ await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ });
+ rows = await timelineRowsFor(pid);
+ expect(rows).toEqual([{ source: 'meeting', summary: 'Discussed the wiki' }]);
+ });
+
+ test('dash-bullet legacy row gets source=markdown and is NEVER split on interior dashes', async () => {
+ await resetLegacyState();
+ const pid = await seedLegacyPage('legacy/dash', `# Dash\n\n${DASH_BULLET}\n`);
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES ($1, '2026-01-06', '', 'moved to Berlin - permanently', '')`,
+ [pid],
+ );
+
+ const r = await repairLegacyTimelineSourceRows(engine);
+ expect(r.rowsRewritten).toBe(1);
+ const rows = await timelineRowsFor(pid);
+ // A blind split would have produced ('moved to Berlin', 'permanently').
+ expect(rows).toEqual([{ source: 'markdown', summary: 'moved to Berlin - permanently' }]);
+
+ await extractStaleFromDB(engine, {
+ dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
+ });
+ expect(await timelineRowsFor(pid)).toEqual([
+ { source: 'markdown', summary: 'moved to Berlin - permanently' },
+ ]);
+ });
+
+ test('legacy row whose new-shape duplicate already landed is deleted, not collided', async () => {
+ await resetLegacyState();
+ const pid = await seedLegacyPage('legacy/dupe', `# Dupe\n\n${PIPE_BULLET}\n`);
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES ($1, '2026-01-05', '', 'meeting — Discussed the wiki', ''),
+ ($1, '2026-01-05', 'meeting', 'Discussed the wiki', '')`,
+ [pid],
+ );
+
+ const r = await repairLegacyTimelineSourceRows(engine);
+ expect(r.rowsDeleted).toBe(1);
+ expect(r.rowsRewritten).toBe(0);
+ expect(await timelineRowsFor(pid)).toEqual([{ source: 'meeting', summary: 'Discussed the wiki' }]);
+ });
+
+ test('legacy row with no matching bullet in current content is left untouched', async () => {
+ await resetLegacyState();
+ const pid = await seedLegacyPage('legacy/stale-content', `# Edited\n\nNo timeline lines anymore.\n`);
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES ($1, '2026-01-05', '', 'meeting — Removed from content', '')`,
+ [pid],
+ );
+
+ const r = await repairLegacyTimelineSourceRows(engine);
+ expect(r.rowsSkipped).toBe(1);
+ expect(r.rowsRewritten).toBe(0);
+ expect(await timelineRowsFor(pid)).toEqual([
+ { source: '', summary: 'meeting — Removed from content' },
+ ]);
+ });
+
+ test('idempotent — a second repair pass finds nothing to do', async () => {
+ await resetLegacyState();
+ const pid = await seedLegacyPage('legacy/idem', `# Idem\n\n${PIPE_BULLET}\n`);
+ await engine.executeRaw(
+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES ($1, '2026-01-05', '', 'meeting — Discussed the wiki', '')`,
+ [pid],
+ );
+ await repairLegacyTimelineSourceRows(engine);
+ const second = await repairLegacyTimelineSourceRows(engine);
+ expect(second).toEqual({ pagesScanned: 0, rowsRewritten: 0, rowsDeleted: 0, rowsSkipped: 0 });
+ });
+
+ test('migration v139 ships the repair (handler-only, idempotent)', () => {
+ const m = MIGRATIONS.find(x => x.version === 139);
+ expect(m).toBeDefined();
+ expect(m!.name).toBe('timeline_legacy_source_split_repair');
+ expect(typeof m!.handler).toBe('function');
+ expect(m!.sql).toBe('');
+ expect(m!.idempotent).toBe(true);
+ });
+});
diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.ts
index 4d53c7b69f..7ece516e82 100644
--- a/test/truthful-catalog.e2e-lite.test.ts
+++ b/test/truthful-catalog.e2e-lite.test.ts
@@ -661,11 +661,17 @@ describe('E5 truthful catalog — OAuth-path cells (serve-http seams over dispat
await setGates(false);
const cell = makeCell('agent', ['agent'], 'full', false, false);
const listed = await oauthToolsList(cell);
- expect(sortedArray(listed)).toEqual(['get_agent_job', 'request_tools', 'submit_agent']);
+ // #4098: the generic queue ops (get/list/progress/cancel) are
+ // agentCallable with an owner-client fence, so the honest agent-lane
+ // row includes them alongside the submit_agent/get_agent_job pair.
+ expect(sortedArray(listed)).toEqual([
+ 'cancel_job', 'get_agent_job', 'get_job', 'get_job_progress',
+ 'list_jobs', 'request_tools', 'submit_agent',
+ ]);
// Probes: garbage args die at validation (proving the scope layer let
// them through), and discovery genuinely works for the agent class.
- for (const name of ['submit_agent', 'get_agent_job']) {
+ for (const name of ['submit_agent', 'get_agent_job', 'get_job', 'get_job_progress', 'cancel_job', 'list_jobs']) {
const op = operations.find(o => o.name === name)!;
const verdict = await oauthToolCall(cell, name, probeArgsFor(op));
expect(verdict.kind).toBe('invalid_params');
diff --git a/test/validate-params.test.ts b/test/validate-params.test.ts
index 90a0b28c20..29155dd800 100644
--- a/test/validate-params.test.ts
+++ b/test/validate-params.test.ts
@@ -44,6 +44,8 @@ function stubEngine(strictMode: 'warn' | 'reject' | null): BrainEngine {
resolveSlugs: async () => [],
getStats: async () => ({ pages: 0 }),
getTimeline: async () => [],
+ // #4352 gate surface: remote get_timeline probes for private-only slugs.
+ executeRaw: async () => [],
} as unknown as BrainEngine;
}
diff --git a/test/voice-gate.test.ts b/test/voice-gate.test.ts
index 61c2316c6f..3e6b7c5fef 100644
--- a/test/voice-gate.test.ts
+++ b/test/voice-gate.test.ts
@@ -282,7 +282,7 @@ describe('voice-gate templates', () => {
expect(out).toContain('Not enough resolved X calls yet');
});
- test('nudgeTemplate includes the hush command', () => {
+ test('nudgeTemplate names the auto-quiet pattern, not a fictional hush command (#3697)', () => {
const out = nudgeTemplate({
domain: 'macro',
conviction: 0.85,
@@ -290,7 +290,12 @@ describe('voice-gate templates', () => {
nRecentTotal: 3,
hushPattern: 'over-confident-macro',
});
- expect(out).toContain('gbrain takes nudge --hush over-confident-macro');
+ // `gbrain takes nudge --hush` never existed as a subcommand; the 14-day
+ // quiet period is automatic via take_nudge_log. The template must not
+ // advertise a command that exits "Unknown subcommand".
+ expect(out).not.toContain('gbrain takes nudge');
+ expect(out).toContain('over-confident-macro');
+ expect(out).toContain('14 days');
expect(out).toContain('0.85');
expect(out).toContain('2 of 3 missed');
});
diff --git a/tests/docker/bootstrap-e2e-inner.sh b/tests/docker/bootstrap-e2e-inner.sh
index d1dbddf750..d6a114cda4 100644
--- a/tests/docker/bootstrap-e2e-inner.sh
+++ b/tests/docker/bootstrap-e2e-inner.sh
@@ -162,8 +162,14 @@ cat > "$GBRAIN_HOME/.gbrain/config.json" <<EOF
EOF
# ── Workspace + scripted interview helper ───────────────────────────────────
+# $2 (optional) is the MCP_SCOPE answer; pass "none" to leave the consent
+# UNANSWERED (MCP_SCOPE is optional — confirm still closes). The opencode
+# workspace needs the unanswered form: its user-global default only holds
+# when no explicit scope was recorded, and recording one can't be undone
+# post-confirm without invalidating the read-back hash (A8).
run_interview() {
ws="$1"
+ scope="${2:-project}"
gbrain bootstrap interview --init --workspace "$ws" > /dev/null
gbrain bootstrap interview --set AGENT_NAME "Lanternfish" --workspace "$ws" > /dev/null
gbrain bootstrap interview --set PRINCIPAL_NAME "Pat Example" --workspace "$ws" > /dev/null
@@ -173,7 +179,9 @@ run_interview() {
- meeting prep" --workspace "$ws" > /dev/null
gbrain bootstrap interview --set PRINCIPAL_CONTEXT "Runs a small research group; builds internal tooling; values signal over noise." --workspace "$ws" > /dev/null
gbrain bootstrap interview --set VOICE_REGISTER "Direct: three options, the second one wins." --workspace "$ws" > /dev/null
- gbrain bootstrap interview --set MCP_SCOPE "project" --workspace "$ws" > /dev/null
+ if [ "$scope" != "none" ]; then
+ gbrain bootstrap interview --set MCP_SCOPE "$scope" --workspace "$ws" > /dev/null
+ fi
gbrain bootstrap interview --set HOOKS_CONSENT "no" --workspace "$ws" > /dev/null
gbrain bootstrap interview --set PERSIST_CRON "no" --workspace "$ws" > /dev/null
hash="$(gbrain bootstrap interview --status --workspace "$ws" | sed -n 's/.*read-back hash: \([0-9a-f][0-9a-f]*\).*/\1/p')"
@@ -206,10 +214,15 @@ origin="$(git -C "$WS" remote get-url origin)"
grep -Fq "$origin" "$WS/GITHUB.md" || fail "GITHUB.md not refreshed with the repo URL"
# ── ABORT_AFTER kill mid-render on a second workspace → status resumes ──────
+# WS2 doubles as the opencode workspace below, so its interview records NO
+# MCP_SCOPE answer — the opencode lane's user-global default only applies
+# when a human never explicitly chose a scope (#4293: pointing the opencode
+# step at WS, whose interview banked MCP_SCOPE=project, made the lane write
+# project scope and fail the user-global assertion).
step "ABORT_AFTER kill + status resume"
WS2="$SCRATCH/ws2"
mkdir -p "$WS2/brain"
-run_interview "$WS2"
+run_interview "$WS2" none
set +e
GBRAIN_BOOTSTRAP_ABORT_AFTER=render gbrain bootstrap render --workspace "$WS2"
rc=$?
@@ -245,13 +258,15 @@ grep -Fq "serve --surface full" "$GB_CODEX_STATE" || fail "codex registration di
# ── opencode door: direct-writer registration, NO binary at all ─────────────
# The opencode lane needs no CLI (the JSONC writer is the registration), so
# the offline container exercises it with nothing faked except the config
-# location (XDG_CONFIG_HOME → scratch). Asserts: user-global default scope
-# (no MCP_SCOPE answer recorded → the sharing-safe inversion), the entry
-# shape (absolute binary, GBRAIN_SOURCE bound, full surface), and no Claude
-# hooks written.
+# location (XDG_CONFIG_HOME → scratch). Runs against WS2 — the workspace
+# whose interview recorded NO MCP_SCOPE answer — because the assertions
+# below prove the sharing-safe inversion: user-global is the DEFAULT, not
+# an echo of a recorded 'project' choice (WS has one; #4293). Asserts:
+# user-global default scope, the entry shape (absolute binary,
+# GBRAIN_SOURCE bound, full surface), and no Claude hooks written.
step "opencode MCP registration (direct JSONC writer, no binary)"
export XDG_CONFIG_HOME="$SCRATCH/xdg-config"
-opencode_out="$(gbrain bootstrap hooks --workspace "$WS" --harness opencode --gbrain-bin "$FAKE_GBRAIN" 2>&1)"
+opencode_out="$(gbrain bootstrap hooks --workspace "$WS2" --harness opencode --gbrain-bin "$FAKE_GBRAIN" 2>&1)"
printf '%s\n' "$opencode_out"
printf '%s\n' "$opencode_out" | grep -Fq "scope: user-global" \
|| fail "opencode registration did not default to user-global scope"
@@ -260,6 +275,7 @@ OC_CFG="$XDG_CONFIG_HOME/opencode/opencode.jsonc"
grep -Fq '"GBRAIN_SOURCE"' "$OC_CFG" || fail "opencode registration did not bind GBRAIN_SOURCE"
grep -Fq '"--surface"' "$OC_CFG" || fail "opencode registration did not pin a surface"
grep -Fq "\"$FAKE_GBRAIN\"" "$OC_CFG" || fail "opencode user-global entry must carry the absolute binary path"
+[ -f "$WS2/.claude/settings.local.json" ] && fail "opencode path must not write Claude hooks"
printf '%s\n' "$opencode_out" | grep -Fq "AGENTS.md" \
|| fail "opencode wiring did not state the pull protocol plainly"
unset XDG_CONFIG_HOME
diff --git a/tests/heavy/_read_latency_workload.ts b/tests/heavy/_read_latency_workload.ts
index f638a5c2e4..6af4fcce0f 100644
--- a/tests/heavy/_read_latency_workload.ts
+++ b/tests/heavy/_read_latency_workload.ts
@@ -23,7 +23,10 @@
* on Darwin, more on Linux CI)
* NUM_QUERIES queries per phase (default 200)
* NUM_WRITERS parallel writer tasks during phase B (default 4)
- * WRITES_PER_WRITER pages each writer inserts during phase B (default 25)
+ * WRITES_PER_WRITER safety-cap sizing: each writer loops until the query
+ * loop finishes, capped at 4x this value (#4285; the
+ * fixed per-writer exit made phase B lie when writers
+ * finished before the queries did)
* STRICT 1 = exit non-zero on delta_pct > THRESHOLD_PCT (default 0)
* THRESHOLD_PCT regression threshold (default 50)
*
@@ -31,12 +34,18 @@
* {
* ok, platform, brain_page_count,
* phase_a: { p50_ms, p95_ms, p99_ms, queries_run },
- * phase_b: { p50_ms, p95_ms, p99_ms, queries_run, writes_completed, writes_failed },
+ * phase_b: { p50_ms, p95_ms, p99_ms, queries_run, writes_completed,
+ * writes_failed, writer_end_ms },
* delta_p50_pct, delta_p95_pct, delta_p99_pct,
+ * overlap_pct, // % of the phase B query window with >=1 live writer
* elapsed_ms, threshold_pct,
* verdict: 'pass' | 'fail' | 'informational',
* note?, error?
* }
+ *
+ * Honesty guard (#4285): a `pass` verdict requires overlap_pct >= 90 — if the
+ * writers stopped early (safety cap or crash) the numbers measured mostly
+ * uncontended reads, so `pass` degrades to `informational` with a note.
*/
import { platform } from 'node:os';
@@ -48,6 +57,8 @@ interface Phase {
queries_run: number;
writes_completed?: number;
writes_failed?: number;
+ /** ms from phase B query start until the LAST writer stopped (#4285). */
+ writer_end_ms?: number;
}
interface Result {
@@ -59,6 +70,8 @@ interface Result {
delta_p50_pct: number | null;
delta_p95_pct: number | null;
delta_p99_pct: number | null;
+ /** % of the phase B query window during which >=1 writer was live (#4285). */
+ overlap_pct: number | null;
elapsed_ms: number;
threshold_pct: number;
verdict: 'pass' | 'fail' | 'informational';
@@ -111,6 +124,7 @@ async function main(): Promise<void> {
delta_p50_pct: null,
delta_p95_pct: null,
delta_p99_pct: null,
+ overlap_pct: null,
elapsed_ms: 0,
threshold_pct: THRESHOLD_PCT,
verdict: 'informational',
@@ -165,41 +179,47 @@ async function main(): Promise<void> {
};
// ---- Phase B: under load (parallel writers)
+ // #4285: writers loop on a stop flag the query loop raises after
+ // NUM_QUERIES, instead of exiting after a fixed WRITES_PER_WRITER count.
+ // Pre-fix, fast writers finished early and the tail of phase B measured
+ // UNCONTENDED reads while still being reported as "under load". The 4x
+ // WRITES_PER_WRITER safety cap bounds a wedged query loop.
process.stderr.write(`[_read_latency] phase B: ${NUM_QUERIES} queries with ${NUM_WRITERS} writers...\n`);
let writesCompleted = 0;
let writesFailed = 0;
- let writersDone = 0;
+ let stopWriters = false;
+ const WRITER_SAFETY_CAP = 4 * WRITES_PER_WRITER;
+ const writerEndTimes: number[] = [];
+ const phaseBStart = Date.now();
const writers: Promise<void>[] = [];
for (let w = 0; w < NUM_WRITERS; w += 1) {
writers.push((async () => {
- const base = BRAIN_PAGES + w * WRITES_PER_WRITER;
- for (let i = 0; i < WRITES_PER_WRITER; i += 1) {
- const p = generatePage(base + i, `WriterW${w}`);
- try {
- await engine.putPage(p.slug, {
- type: 'note',
- title: p.title,
- compiled_truth: p.body,
- timeline: '',
- frontmatter: { writer: w, tags: ['writer-load'] },
- });
- writesCompleted += 1;
- } catch {
- writesFailed += 1;
+ const base = BRAIN_PAGES + w * WRITER_SAFETY_CAP;
+ try {
+ for (let i = 0; !stopWriters && i < WRITER_SAFETY_CAP; i += 1) {
+ const p = generatePage(base + i, `WriterW${w}`);
+ try {
+ await engine.putPage(p.slug, {
+ type: 'note',
+ title: p.title,
+ compiled_truth: p.body,
+ timeline: '',
+ frontmatter: { writer: w, tags: ['writer-load'] },
+ });
+ writesCompleted += 1;
+ } catch {
+ writesFailed += 1;
+ }
}
+ } finally {
+ writerEndTimes.push(Date.now());
}
- writersDone += 1;
})());
}
const phaseBMs: number[] = [];
- // Run queries until we hit NUM_QUERIES OR all writers finish, whichever
- // is LATER. Goal: every query in phase B is during sustained writer
- // pressure. If queries are too few and writers haven't finished, keep
- // going past NUM_QUERIES for fairness.
- let queryIdx = 0;
- while (queryIdx < NUM_QUERIES || writersDone < NUM_WRITERS) {
+ for (let queryIdx = 0; queryIdx < NUM_QUERIES; queryIdx += 1) {
const q = queries[queryIdx % queries.length]!;
const t = Date.now();
try {
@@ -207,14 +227,20 @@ async function main(): Promise<void> {
} catch {
/* tolerated */
}
- if (queryIdx < NUM_QUERIES) {
- phaseBMs.push(Date.now() - t);
- }
- queryIdx += 1;
- // Safety stop: don't blow past 4x NUM_QUERIES if writers are wedged
- if (queryIdx >= 4 * NUM_QUERIES) break;
+ phaseBMs.push(Date.now() - t);
}
+ const phaseBQueriesEnd = Date.now();
+ stopWriters = true;
await Promise.allSettled(writers);
+
+ // Overlap: fraction of the query window during which at least one writer
+ // was still running. With the stop-flag design this is ~100% unless the
+ // writers hit the safety cap (or crashed) before the queries finished.
+ const lastWriterEnd = writerEndTimes.length > 0 ? Math.max(...writerEndTimes) : phaseBStart;
+ const windowMs = Math.max(1, phaseBQueriesEnd - phaseBStart);
+ const coveredMs = Math.max(0, Math.min(lastWriterEnd, phaseBQueriesEnd) - phaseBStart);
+ result.overlap_pct = NUM_WRITERS > 0 ? Math.round((coveredMs / windowMs) * 100) : 0;
+
phaseBMs.sort((a, b) => a - b);
result.phase_b = {
p50_ms: percentile(phaseBMs, 50),
@@ -223,6 +249,7 @@ async function main(): Promise<void> {
queries_run: phaseBMs.length,
writes_completed: writesCompleted,
writes_failed: writesFailed,
+ writer_end_ms: Math.max(0, lastWriterEnd - phaseBStart),
};
// Delta math: ((B - A) / A) * 100, integer percent. Guard divide-by-zero.
@@ -250,6 +277,16 @@ async function main(): Promise<void> {
result.verdict = 'informational';
}
+ // #4285 honesty guard: a low-overlap phase B measured mostly uncontended
+ // reads. A `fail` under partial pressure is still valid evidence (full
+ // pressure is at least as bad); a `pass` is not — degrade it.
+ if ((result.overlap_pct ?? 0) < 90) {
+ result.note =
+ `writer pressure covered only ${result.overlap_pct ?? 0}% of the phase B query window (<90%); ` +
+ `under-load numbers are unreliable`;
+ if (result.verdict === 'pass') result.verdict = 'informational';
+ }
+
result.ok = true;
result.elapsed_ms = Date.now() - t0;
} catch (err) {