Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.14.0 fix: issue+PR fix wave — 13 verified fixes + 14 community adoptions with credit (#4226)

Garry Tan864dec4f199f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 878700204b..5813986243 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.13.0",
+ "version": "0.46.14.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 1796eff804..c7cddf6b34 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.13.0",
+ "version": "0.46.14.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index a85e2e98fa..f3f1e4e22c 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.13.0 -->
+<!-- gbrain-runbook-stamp: 0.46.14.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 2990b58d2b..0c6beddb30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,84 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.14.0] - 2026-08-16
+
+Fix wave: 13 verified issues fixed + 14 community PRs adopted with credit, from a
+triage of everything filed since the 2026-08-14 audit (42 new items, each verified
+against HEAD with an adversarial second pass before entering scope).
+
+### Fixed
+- **dream/cycle:** calibration-trio phases (propose_takes, grade_takes,
+ calibration_profile) now clamp their deadlines to the owning job's claim-time
+ timeout via shared `BasePhaseOpts.deadlineAtMs`, so long cycles bank partial
+ work and exit cleanly instead of dead-lettering at the worker kill switch (#4168).
+ extract_atoms distinguishes malformed model output from a real zero-yield
+ extraction (typed parse outcomes), writes atoms with a completion receipt so a
+ partial persist is retried instead of silently skipped forever, and tombstones a
+ page only after 3 consecutive same-content deterministic failures (#4148). The
+ nightly purge survives a RESTRICT-FK-held source (revoked oauth client) with a
+ structured `{purged, blocked}` report instead of aborting the whole sweep (#4115).
+ Dream `--input` on an already-synthesized transcript says why it skipped
+ (PR #4122 by @Masashi-Ono0611). The cycle lock-steal decision keys on the aborted
+ flag, not the droppable abort reason (#4140, PR #4141 by @Masashi-Ono0611).
+- **takes:** `eval suspected-contradictions` resolution commands are now
+ addressable and truthful — `--row` carries the per-page row number, commands
+ that need operator judgment say so instead of failing, and the unimplemented
+ mark-debate action is no longer minted (#4169).
+- **minions/claude-cli:** multi-turn claude-cli subagent jobs no longer
+ dead-letter when the provider reuses a tool_use_id — execution rows key on
+ (message_idx, tool_use_id) with migration v131 (#4155, PR #4156 by
+ @Masashi-Ono0611). claude-cli reports cachedInputTokens (PR #4120) and scrubs
+ ALL cloud-auth routing env vars so children always use the subscription auth the
+ recipe documents — intentional cloud routing belongs on the `anthropic` recipe
+ (PR #4111, both by @Masashi-Ono0611). `models doctor` honors slow-start
+ providers instead of a flat 5s probe abort (PR #4112 by @Masashi-Ono0611).
+- **recipes:** Google `supports_prompt_cache` is a per-model predicate — Gemini
+ 2.5+ caches implicitly and no longer reads as cache-less (#4158, PR #4159 by
+ @dovstern). OpenRouter embedding models carry verified per-model dims and
+ unlisted ids require explicit dims instead of inheriting a plausible-wrong 1536
+ (#4114). Qwen embedding ids match case-insensitively so correctly-cased provider
+ ids get their dimensions pinned (#4123). Recipe-declared thinking-by-default
+ models (DeepSeek v4) get reasoning-token headroom in `think` via the capability
+ layer (reimplements stale-fork PR #4172; thanks @Tonyli1010).
+- **doctor/health:** `get_health`'s islanded check applies endpoint liveness in
+ both directions so it agrees with `gbrain orphans` (#4153), and entity coverage
+ ratios report "too few to grade" below a small-N floor instead of a misleading
+ hard 0%/100% (#4147, also closing the #3945 class). JSON/MCP consumers:
+ `link_coverage` and `timeline_coverage` are now `number | null` — `null` means
+ "too few entity pages to grade" — and the payload adds `entity_page_count` so
+ you can render the floor yourself.
+- **transcripts:** sparse multiline sessions parse (PR #4163 by @richtheworld);
+ `--max-bytes` gives oversized stores a validated escape hatch while per-format
+ safety defaults stay in charge, with the cap folded into the `--since last`
+ checkpoint fingerprint (#4149; thanks @justemu).
+- **search/budget:** query-expansion LLM spend records to the budget tracker and
+ audit (#4121, PR #4124 by @Masashi-Ono0611).
+- **serve --http:** no-grant legacy bearer tokens get #3242's federated read
+ parity via a shared, fail-closed widening decision (PR #4132 by @kyle944).
+ Behavior change: SDK-transport sessions authenticated with such a token now
+ see the same federated read scope as the HTTP dispatch path — reads that
+ previously came back empty on one transport are consistent on both.
+- **Windows:** path containment uses the OS separator (PR #4103 by
+ @MohammedAlkindi, with CI-runnable win32 shape tests), and sync accepts Windows
+ path casing + indexes .astro/.svelte files (#4044, PR #4144 by @javieraldape).
+- **facts:** the conversation-type allowlist derives from one frozen module
+ instead of five hand-copied lists (PR #4135 by @Masashi-Ono0611).
+- **cli:** `sources --help` shows real usage instead of the circular stub
+ (PR #4133 by @Masashi-Ono0611).
+
+### To take advantage of v0.46.14.0
+- `gbrain upgrade` picks everything up; migration v131 runs automatically.
+ Multi-worker Postgres deployments: stop running `gbrain jobs work` daemons
+ BEFORE upgrading and restart them on the new binary — an old binary writing
+ tool executions against a migrated database errors on every persist until
+ restarted. Single-binary PGLite installs need nothing.
+- If claude-cli subagent jobs previously dead-lettered on
+ `uniq_subagent_tools_use_id`, re-run them — the class is fixed.
+- Hermes stores over the default cap: `gbrain transcripts ingest --max-bytes 4gb <store>`.
+- If you intentionally route claude-cli through a cloud backend, switch that
+ workload to the `anthropic` recipe with cloud credentials — claude-cli children
+ now always use subscription auth.
## [0.46.13.0] - 2026-08-16
**One brain can now safely serve many agents.** `gbrain agent register` mints
diff --git a/README.md b/README.md
index d8bb6caf7b..9e315c4ec6 100644
--- a/README.md
+++ b/README.md
@@ -250,6 +250,7 @@ re-runs are free — unchanged sessions skip on content hash:
gbrain transcripts ingest # discover importable session logs
gbrain transcripts ingest --all # import everything discovered
gbrain transcripts ingest ~/Downloads/conversations.json # consumer export (unzip first)
+gbrain transcripts ingest --max-bytes 4gb <store> # oversized store; omit to keep per-format caps
gbrain transcripts status # found vs imported, per harness
```
diff --git a/TODOS.md b/TODOS.md
index db29c99152..09a96cd20d 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,129 @@
# TODOS
+## chennai fix-wave follow-ups (filed 2026-08-16)
+
+- [ ] **P1 — read_latency_under_sync hangs from 6a905a1e (#4143); 6a905a1e's
+ read-path hunks are the revert candidate.** **What:** phase B of
+ `tests/heavy/read_latency_under_sync.sh` never returns; the workload's own
+ 600s timeout kills it (exit 124). **Investigation so far (chennai wave,
+ timeboxed):** reproduced 2/2 on darwin at wave HEAD with default params
+ (500/200/4); a stderr-instrumented copy of the SAME workload at the SAME
+ params passes cleanly (writers finish by query ~11), and small params
+ (50/20/4) pass — the per-iteration stderr writes act as load-bearing yield
+ points, consistent with the repo's known Bun timers-phase starvation class
+ (cf. GBRAIN_SYNC_YIELD_EVERY: `setTimeout(0)`, NOT `setImmediate` — "Bun
+ starves the timers phase under a tight loop"). Suspect surface: #4096's
+ hybrid.ts read-path rework (embedQueryBounded's AbortSignal.timeout pairs +
+ query-cache/mode changes) turning phase B into a microtask-dominated spin
+ that starves timers. Reporter's Linux bisect (100% reproducible, first bad
+ 6a905a1e) is in #4143. **Next:** either root-cause the starvation (try a
+ setTimeout(0) yield in the phase-B loop to confirm the class, then find
+ which #4096 await lost its macrotask boundary) or revert 6a905a1e's
+ hybrid.ts hunks and re-run the lane. Harness hardening also owed: count
+ swallowed query errors (all-fail should not read as latency data), bound
+ the `Promise.allSettled(writers)` wait, per #4143's own notes. **Also:**
+ the Heavy Tests lane comes back `skipped` on in-repo branches, so this
+ gates nothing upstream — fix the lane gating or this class stays invisible.
+ **Effort:** M. **Priority:** P1.
+
+- [ ] **P2 — Cache-MODE enum: implicit vs Anthropic-explicit prompt caching.**
+ **What:** replace `supports_prompt_cache`'s boolean/predicate with a mode
+ (`explicit-anthropic` | `implicit` | `none`) so the gateway's cache-marker
+ injection is driven by MODE, not by "caching exists". **Why:** the Google
+ predicate fix (#4158) is functionally safe today only because anthropic-
+ namespaced providerOptions are ignored on native-google — a transport-level
+ pin test (`recipe-google-prompt-cache.test.ts`) guards that; the semantic
+ conflation stays until modes exist. **Context:** cross-model review finding
+ on PR #4159; the pin test names this TODO. **Effort:** M (CC: S). **P2.**
+- [ ] **P2 — Abort-signal threading through BasePhaseOpts + dream generators.**
+ **What:** thread an AbortSignal from the job deadline into every calibration
+ phase's LLM calls so an in-flight hung request is CANCELLED, not just
+ observed at the next loop boundary. **Why:** #4168's clamp restores the
+ clean partial-exit but a wedged provider call still burns the reserve.
+ **Context:** adjacent to banked PR #4077 (cooperative abort through
+ synthesis) — the same seam should serve both. **Effort:** M. **P2.**
+- [ ] **P2 — transcripts parser: surface out-of-set speaker headings (#4136).**
+ **What:** optional ParseResult field (`suspect_heading_labels` + count) when
+ a heading-only anchor-shaped continuation line with an out-of-set label is
+ folded under a heading-anchored multi_line pattern; extract-conversation-
+ facts warns. **Why:** silent speaker misattribution is accepted parse today.
+ **Context:** reporter offered the PR (green-lit in the issue thread with the
+ three-label reproducer as tests); keep phase `regex_match`; a decline
+ threshold is a follow-on decision. **Effort:** M. **P2.**
+- [ ] **P2 — skillopt field-report items (#4119, all verified at HEAD).**
+ **What:** (a) in-loop runtime-deadline check (orchestrator.ts:440 is
+ step-granular); (b) output-size-aware cost estimate (preflight.ts fixed
+ 800-token constant); (c) validation-gate n-gram overlap detector vs judge
+ definitions; (d) stronger bootstrap judges; (e) opt-in `--hermetic-config`
+ (CLAUDE_CONFIG_DIR) for claude-cli children — default-on needs its own
+ security decision (the provider deliberately rides the operator's ~/.claude
+ OAuth session); (f) docs: rule judges as a gameable optimizer target, D13
+ limitation, cap sizing, human review of proposed.md is load-bearing.
+ **Context:** issue thread carries the full analysis; CLAUDE_CONFIG_DIR is
+ the documented interim mitigation. **Effort:** M spread. **P2.**
+- [ ] **P3 — orphans.exclude_domains (feature, #4157).** Third exclusion axis
+ on the shared orphan policy, matched on the derived domain; must thread the
+ orphans denominator query AND both engines' getHealth page-scope rows
+ (engine parity). **Effort:** S. **P3.**
+- [ ] **P3 — dream.synthesize flat/root output_root (feature, #4117).**
+ Per-family prefix shape (reflections/originals prefixes derived into prompts
+ AND the fail-closed allow-list; default preserves wiki/). No config-registry
+ drift to fix (`dream.` prefix already accepted). **Effort:** M. **P3.**
+- [ ] **P2 — test debt from the chennai wave's pre-landing review (deferred
+ with rationale, not skipped).** (a) `/mcp` SDK-transport integration test:
+ spin the serve-http surface with a legacy no-grant token end-to-end and
+ assert the federated source list matches `localFederatedSourceIds` — the
+ unit precedence test pins the resolver but not the transport wiring; also
+ pin `AuthInfo.hasSourceGrant` at the oauth-provider construction site.
+ (b) postgres `getHealth` parity e2e for the islanded/coverage changes —
+ unit coverage is PGLite-only; the DATABASE_URL-gated parity lane should
+ assert entity_page_count + null-coverage-below-floor on real Postgres.
+ (c) transcripts replay-reconcile tests for WITHIN-TURN duplicate
+ tool_use_id after migration v131 (same id, same message_idx — provider
+ emits the dup inside one message). **Effort:** M spread. **P2.**
+- [ ] **P2 — adversarial-review residuals on the chennai wave (verified real,
+ deferred with rationale).** (a) subagent tool-ledger zero-row settlement
+ observability: in the residual zombie race a pending INSERT can be swallowed
+ by ON CONFLICT DO NOTHING, the tool still executes, and the settle UPDATE
+ then matches 0 rows — the outcome is silently unrecorded and a non-idempotent
+ tool can re-execute on replay. Add a rowcount check + job-log warn (needs a
+ logging seam in the persist helpers). (b) extract-atoms tombstones cover
+ pages only: `recordPageFailureCount` returns null for `kind !== 'page'`, so
+ a transcript that deterministically yields malformed output re-spends LLM
+ budget every cycle forever — extend #4148's failure-count machinery to
+ transcript items. (c) getHealth coverage numerators are not liveness-
+ filtered while islanded now is (#4153): a page whose only inbound link is
+ from a soft-deleted page counts as covered AND orphaned simultaneously;
+ align the coverage EXISTS subqueries with the islanded liveness JOINs in
+ both engines (parity + bootstrap-probe update). **Effort:** M spread. **P2.**
+- [ ] **P3 — conversation-parser: corpus-level false-positive receipt for the
+ multi_line bold-name-date builtin (#4163 follow-on).** Flipping the builtin
+ to `multi_line` + score_continuations_as_body means non-conversation prose
+ with as few as two `**Name** (date):`-shaped lines can clear the 5% density
+ floor (every other line counts as a continuation) and parse as a
+ conversation, feeding facts extraction with garbage segments. Build a
+ small negative corpus (essays/notes with incidental bold-date lines) and
+ either raise the floor for this builtin or require a minimum SPEAKER count.
+ Adjacent to the #4136 suspect-heading work above. **Effort:** S. **P3.**
+- [ ] **P3 — gateway expand(): record spend for a generateObject call that
+ throws after consuming tokens (#4121 follow-on).** The schema-rejection →
+ viaText fallback is the double-billed shape; the first call's tokens go
+ unrecorded because usage is only read on success. If the SDK error carries
+ usage, record it before the fallback retry. **Effort:** S. **P3.**
+- [ ] **P3 — eval-contradictions: reject flag-shaped slugs at render time.**
+ A slug beginning with `-` renders into `takes supersede '<slug>'` as a
+ flag-shaped positional; the pasted command errors rather than executes, but
+ a render-time shape check (or `--` separator support in the takes CLI)
+ would make the generated command paste-safe for any slug a remote MCP
+ writer can mint. **Effort:** S. **P3.**
+- [ ] **P3 — DRY refactors flagged by the review army (correct today,
+ duplicated shape).** (a) hoist the settlement-status subquery duplicated
+ across grade-takes call sites into one helper; (b) extract the three-tier
+ resolution (per-call > config > default) repeated in pace-mode/search-mode/
+ probe-timeout into a shared `resolveTiered` helper; (c) `renderBlock`-style
+ functions taking 6+ positional args → params object; (d) the deadline-skip
+ preamble repeated at the top of each cycle phase → shared guard in
+ base-phase.ts. **Effort:** S each. **P3.**
## Multi-agent wave follow-ups (cathedral-6, `gbrain agent register`)
- [ ] **P2 — archived sources keep previously-granted federated reads until
diff --git a/VERSION b/VERSION
index 5465571245..981510d985 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.13.0
\ No newline at end of file
+0.46.14.0
\ No newline at end of file
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index 705ce6c717..4dd6dde104 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -66,16 +66,21 @@ stdin:
every call would boot the user's configured MCP servers — including
gbrain's own MCP, which would recurse and contend for the PGLite
single-writer lock.
-- The subprocess env is a copy of gbrain's own process env with exactly
- three keys deleted before spawn: `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`,
- `ANTHROPIC_BASE_URL`. Everything else in gbrain's environment is inherited
- as-is. The recipe's source comment states the intent (stop an
- `ANTHROPIC_API_KEY` present in gbrain's own env from being picked up by the
- subprocess), scoped to those three variables specifically — the doc does
- not claim this rules out every other way `claude` could end up billing
- through a non-subscription path (e.g. other env-based auth switches the CLI
- itself may support); that is between the installed `claude` binary and its
- own configuration, not something this recipe's code inspects.
+- The subprocess env is a copy of gbrain's own process env with the
+ cloud-auth routing variables scrubbed before spawn: the three direct-API
+ keys (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`)
+ plus every `CLAUDE_CODE_USE_*` backend-switch flag (a prefix wipe, not a
+ denylist — Bedrock, Vertex AI, and the other cloud backends are each gated
+ by one of these, take priority over subscription OAuth when set, and route
+ billing through a cloud account; clearing the switch is sufficient because
+ the provider-specific credentials are inert without it). Everything else in
+ gbrain's environment is inherited as-is. Subscription-only is the recipe's
+ contract: children always authenticate with the CLI's own login state. If
+ you intentionally route a workload through a cloud backend, use the
+ `anthropic` recipe with cloud credentials instead — the scrub means
+ claude-cli children will not inherit that routing. Whatever auth/billing
+ configuration the installed `claude` binary carries in its own config files
+ (not env) remains between it and its login state.
- Beyond that env-scrub, auth resolution is entirely up to the installed
`claude` binary — the recipe does not manage or forward credentials
itself. Whatever `claude` is already logged in / authenticated with on
@@ -106,37 +111,30 @@ above.
| Tool use | JSON emission via a system-prompt-injected protocol, not the CLI's native tool-call mechanism. Parallel tool calls in one turn round-trip correctly. |
| Multimodal | Not supported over the subprocess path. File/image message parts are rendered as a `[file <mediaType>]` text stub, not sent as actual content. |
| Prompt caching | The recipe declares `supports_prompt_cache: false`. The CLI manages its own caching internally but does not expose it through gbrain's `cache_control` control plane, so from the gateway's point of view this model does not support prompt caching. |
-| Usage / token counts | Reported `usage.input_tokens` / `usage.output_tokens` are read straight from the CLI's `--output-format json` envelope (`result.usage?.input_tokens` / `output_tokens`); gbrain does not independently count tokens for this path. |
+| Usage / token counts | Reported `usage.input_tokens` / `usage.output_tokens` are read straight from the CLI's `--output-format json` envelope (`result.usage?.input_tokens` / `output_tokens`); gbrain does not independently count tokens for this path. The envelope's `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens`, so cache reads no longer count as zero in gbrain's usage accounting; `cache_creation_input_tokens` is not surfaced (the AI SDK's usage shape has no corresponding field). |
| Cost figures | The recipe declares `cost_per_1m_input_usd: 3.0` / `cost_per_1m_output_usd: 15.0` — the same Sonnet-class figures the `anthropic` recipe declares (`price_last_verified: 2026-06-17`) — purely so gbrain's budget ledger has a number to attribute per call. Neither the recipe nor the adapter code checks what you're actually billed; treat these as the ledger's nominal per-call number, not a verified charge. |
| User-level CLAUDE.md | `~/.claude/CLAUDE.md` still loads on every call (see above) — only the working directory changes (see "What actually happens on a call" for exactly what that directory is and isn't). |
-## Known doctor caveat: cold-start subprocess vs the fixed 5s probe timeout
+## Doctor probe timeout: per-recipe, 30s for claude-cli
`gbrain models doctor`'s chat reachability probe (`probeModel` in
-`src/commands/models.ts`) wraps every chat call in a fixed 5-second
-`AbortController` timeout, independent of any per-recipe timeout the recipe
-itself declares (`claude-cli` does not declare a `default_timeout_ms`).
-Spawning the `claude` binary and letting it start up is generally fast, but
-is not instantaneous — a slow first invocation (cold process cache, slow
-disk, contended machine) can outrun that 5-second window.
-
-When that happens, the probe's `AbortController` fires, the subprocess is
-killed (`child.kill('SIGTERM')`), and the adapter's abort handler rejects
-with a fixed message (`claude-cli adapter aborted`). `classifyError` in
-`src/commands/models.ts` only maps a message to `status: network` if it
-matches `/timeout|network|econn|fetch failed|enotfound/`; `claude-cli
-adapter aborted` matches none of those, so it falls through to
-`status: unknown` — the classifier's catch-all — instead of `status:
-network`, which is what a plain slow/unreachable HTTP provider would map
-to on the same probe timeout. So a `status: unknown` result on a
-`claude-cli:` model is not necessarily a broken configuration on its own;
-a cold subprocess start outrunning the fixed 5s window is one thing that
-can produce it (the same class of first-call cold-start the embedding
-reachability probe's own code comment already calls out for local
-embedders), and re-running the probe is a reasonable first thing to try.
-`status: unknown` on its own doesn't distinguish that from any other
-unclassified failure, so if a re-run keeps producing it, treat it as an
-unclassified error worth investigating rather than assuming cold-start.
+`src/commands/models.ts`) resolves its timeout per model: the recipe
+touchpoint's declared `default_timeout_ms` when present, else a flat 5000ms
+default (the right number for a plain HTTP round-trip). The `claude-cli`
+recipe declares `default_timeout_ms: 30_000` because each call spawns a
+`claude -p` subprocess (CLI cold start + user-level CLAUDE.md load) that
+routinely takes 5-6 seconds even when the CLI and subscription are perfectly
+healthy — under the old flat 5s abort the probe false-failed on every run
+with `status: unknown` (`claude-cli adapter aborted`) while `chat()`
+succeeded fine at normal call sites.
+
+30 seconds gives the subprocess room to start without masking a truly
+dead or unauthenticated CLI for long. A probe that still outruns 30s kills
+the subprocess (`child.kill('SIGTERM')`) and reports `status: unknown` —
+the adapter's abort message doesn't match `classifyError`'s network
+patterns, so it lands in the catch-all. A persistent `unknown` is now worth
+investigating directly (run the same model via `gbrain models doctor
+--json` or call `claude` by hand) rather than assuming cold-start.
## Troubleshooting
@@ -146,5 +144,5 @@ unclassified error worth investigating rather than assuming cold-start.
| `claude-cli exited <code>: ...` | Non-zero exit from the `claude` subprocess itself; the message is whatever the CLI wrote to stderr/stdout | Run `claude` interactively with the same model to see the underlying CLI error directly (e.g. not logged in, model unavailable) |
| `claude-cli output not JSON: ...` | `JSON.parse(stdout)` threw (stdout wasn't valid JSON at all) | Confirm the installed `claude` CLI version still supports `--print --output-format json`; this adapter's JSON handling was verified against CLI 2.1.145 |
| `claude-cli JSON event array had no "result" event` | stdout parsed as a JSON array (the `"verbose": true` event-stream shape in `~/.claude/settings.json`) but none of the events had `type: "result"` | Check `~/.claude/settings.json` for `"verbose": true`; the adapter tolerates the array shape but still needs a `result` event in it |
-| `gbrain models doctor` reports `chat` as `status: unknown` for a `claude-cli:` model | See "Known doctor caveat" above — `classifyError` falls through to `unknown` for the adapter's abort message | Re-run the probe; if it persists, treat it as an unclassified failure and investigate directly (e.g. run the same model via `gbrain models doctor --json` or call `claude` by hand) |
-| A call bills through the Anthropic API instead of the local session | The adapter deletes `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_BASE_URL` from the subprocess env — this covers gbrain's own env leaking into the call. It does not inspect any other auth/billing switch the installed `claude` CLI itself may support | If billing looks wrong, check the `claude` CLI's own auth/billing configuration on this machine, not just gbrain's env |
+| `gbrain models doctor` reports `chat` as `status: unknown` for a `claude-cli:` model | The probe now allows 30s for the subprocess (see "Doctor probe timeout" above); a persistent `unknown` means the call genuinely failed or outran even that window — `classifyError` falls through to `unknown` for the adapter's abort message | Investigate directly: run the same model via `gbrain models doctor --json` or call `claude` by hand (e.g. not logged in, model unavailable) |
+| A call bills through the Anthropic API or a cloud backend instead of the local session | The adapter deletes `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_BASE_URL` and every `CLAUDE_CODE_USE_*` backend-switch flag from the subprocess env — this covers gbrain's own env leaking into the call. It does not inspect billing switches the installed `claude` CLI carries in its own config files | If billing looks wrong, check the `claude` CLI's own auth/billing configuration on this machine, not just gbrain's env. For intentional cloud routing, use the `anthropic` recipe instead |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 5bba7e6da4..2d1911670d 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -134,7 +134,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ai/gateway.ts` — unified seam for every AI call. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / ZeroEntropy / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `zeroEntropyCompatFetch` shim (sibling to `voyageCompatFetch`) handles ZE's non-OpenAI-compatible wire shape — rewrites the request URL `/embeddings → /models/embed`, injects `input_type` (default `'document'`; the threaded `'query'|'document'` crosses the SDK boundary via the module-level `__embedInputTypeStore` AsyncLocalStorage populated in `embedSubBatch()`, because the AI SDK's openai-compatible adapter strips `input_type` from `providerOptions` before building the wire body — #1400; `voyageCompatFetch` injects it opt-in the same way, and `openAICompatAsymmetricFetch` is the fallthrough shim for every other openai-compat recipe — llama-server/litellm/ollama — a strict pass-through when nothing was threaded) and explicit `encoding_format: 'float'`, and rewrites the response `{results: [{embedding}], usage: {total_bytes, total_tokens}}` → `{data: [{embedding, index}], usage: {prompt_tokens, total_tokens}}` so the SDK's openai-compatible Zod schema validates. Layer 1 (Content-Length) + Layer 2 (per-embedding) OOM caps via tagged `ZeroEntropyResponseTooLargeError` (kept separate from `VoyageResponseTooLargeError` because `test/voyage-response-cap.test.ts` does structural source-text greps pinning the Voyage name). Wired in `instantiateEmbedding()` via the `recipe.id === 'zeroentropyai'` branch. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the configured reranker via `getRerankerModel()`, posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/models/rerank`; Voyage declares `/rerank`) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `warnSunsetOnce(recipe, touchpoint)`: once-per-(recipe,touchpoint) stderr DEPRECATED warning for recipes carrying `sunset` metadata, fired on actual use (embedding resolution + the rerank path) so brains still riding a dying provider hear about it on every process, not only at upgrade time; prints the sunset date plus the migrate / `search.reranker.model` fix, never throws, `_resetSunsetWarningsForTest()` is the test seam. `RerankError.reason` classifier: `auth | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` accessor + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length at `:595`, Layer 2 per-embedding base64 at `:619`) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (regression assertion in `test/voyage-response-cap.test.ts` pins the `instanceof ⇒ throw err` line). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; new exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is the load-bearing fix for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion fix in `src/core/skillopt/rollout.ts`: the inline `paramsToSchema` dropped `items` on array params; it now uses the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default). Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions` — this REPLACED the old `user_provided_model_unset` guard, which was structurally unreachable (parseModelId throws on a bare provider) and only ever false-positived for `litellm:<model>`, silently disabling vector search. `configureGateway` no longer backfills `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport.
- `src/core/ai/recipes/zeroentropyai.ts` — ZeroEntropy openai-compatible recipe declaring BOTH `embedding` (`zembed-1`, 7 Matryoshka dims: 2560/1280/640/320/160/80/40) AND `reranker` (`zerank-2` flagship + `zerank-1` + `zerank-1-small`, 5MB payload cap) touchpoints. `implementation: 'openai-compatible'` (pinned by regression in `test/ai/zeroentropy-recipe.test.ts`). `base_url_default: 'https://api.zeroentropy.dev/v1'` already ends with `/v1`, so the `zeroEntropyCompatFetch` URL rewrite `/embeddings → /models/embed` produces `…/v1/models/embed` (NOT `…/v1/v1/…` — pinned by regression). `chars_per_token: 1` + `safety_factor: 0.5` match Voyage's dense-content hedge. Carries `sunset` metadata (`ZEROENTROPY_SUNSET_DATE` + replacement models from `ai/defaults.ts`) that drives init picker/auto-pick exclusion, the gateway's once-per-process warn-on-use, and every `gbrain providers` rendering via the shared `sunsetMarker` in `src/commands/providers.ts` (`list` status cell, ⚠ `explain` rows, and the `env` deprecation block that replaces the signup funnel); the recipe itself is deleted in the September removal release.
- `src/core/ai/recipes/llama-server-reranker.ts` — sibling of `llama-server` (the embedding recipe) for llama.cpp in `--reranking` mode. Distinct recipe rather than dual-touchpoint extension because `--reranking` and `--embeddings` are mutually exclusive at server-launch time, so the two backends need independent base URLs (default 8081 here vs 8080 there). Declares `reranker` touchpoint with `models: []` (user-provided id matching the `--alias` the user launched with), `path: '/rerank'` (leaf-only; consumes `RerankerTouchpoint.path` override; gateway concatenates with `base_url_default` which ends in `/v1`, producing `…/v1/rerank`), `default_timeout_ms: 30_000` (consumed by `src/core/search/mode.ts`'s reranker timeout chain — CPU-only first-call warmup headroom; the 5s mode-bundle default would fail-open as `timeout`), `cost_per_1m_tokens_usd: 0` (recognized by `FREE_LOCAL_RERANK_PROVIDERS` in `src/core/budget/budget-tracker.ts` so `--max-cost` callers don't hard-fail on local rerank). Setup hint emphasizes `--alias` because llama-server's `/v1/models` defaults model id to the gguf file path without it. Covers Qwen3-Reranker via llama.cpp AND self-hosted ZE weights via llama.cpp — same recipe, different `--model` at launch. Pinned by `test/ai/recipe-llama-server-reranker.test.ts`. Voyage / Cohere / vLLM rerankers stay out of scope (different wire shapes). Same wave adds: `path?: string` + `default_timeout_ms?: number` on `RerankerTouchpoint` in `src/core/ai/types.ts`; consumed by the URL build at `src/core/ai/gateway.ts:rerank()` and by mode-resolution at `src/core/search/mode.ts:resolveSearchMode` (precedence: per-call > config-key > recipe touchpoint default > mode bundle); `LLAMA_SERVER_RERANKER_BASE_URL` env passthrough in `src/cli.ts:buildGatewayConfig`; `FREE_LOCAL_RERANK_PROVIDERS` set in `src/core/budget/budget-tracker.ts:lookupPricing` (rerank-kind-only zero-pricing for the local provider prefix); doctor-fix at `src/commands/models.ts:probeRerankerConfig` reads `search.reranker.model` via `loadSearchModeConfig` + `resolveSearchMode` (closes file-plane / DB-plane divergence where doctor said "not configured" while live search was actively reranking — the field-plane `getRerankerModel()` read nothing writes); `probeRerankerReachability` reads the recipe's `default_timeout_ms` so CPU-only cold-start doesn't false-fail.
-- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: `openai/text-embedding-3-small` at 1536 dims with Matryoshka `dims_options: [512, 768, 1024, 1536]`; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is INFORMATIONAL — the real gate is `isAnthropicProvider()` in `src/core/model-config.ts` which hard-pins gbrain's subagent infra to Anthropic-direct. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
+- `src/core/ai/recipes/openrouter.ts` — OpenRouter openai-compatible recipe: single key, many providers via `openrouter:<provider>/<model>` strings. `base_url_default: 'https://openrouter.ai/api/v1'`. Embedding touchpoint: default model `openai/text-embedding-3-small`; per-model `model_dims` carries verified native widths (text-embedding-3-small 1536, text-embedding-3-large 3072, qwen/qwen3-embedding-8b 4096, bge-m3 + baai/bge-m3 1024) with `default_dims: 0` so an UNLISTED proxied id has NO silent default — it errors until the user supplies explicit dims (`--embedding-dimensions` / `embedding_dimensions`), which `trust_custom_dims: true` accepts (#4114; gemini-embedding-2-preview is deliberately unlisted — width unverified). Matryoshka `dims_options: [512, 768, 1024, 1536]` still governs the default model's shrink steps; `max_batch_tokens: 300_000` = OpenAI's aggregate-per-request token cap (NOT per-input). Chat touchpoint declares 8 curated entry points (gpt-5.2, gpt-5.2-chat, gpt-5.5, claude-haiku-4.5, claude-sonnet-4.6, claude-opus-4.7, gemini-3-flash-preview, deepseek-chat) but openai-compat tier accepts any model ID; deliberately no `max_context_tokens` because OR's catalog spans 128K to 1M+. `supports_subagent_loop: false` is INFORMATIONAL — the real gate is `isAnthropicProvider()` in `src/core/model-config.ts` which hard-pins gbrain's subagent infra to Anthropic-direct. Declares `resolveDefaultHeaders(env)` returning OR's three attribution headers: `HTTP-Referer` (required for OR app-attribution), `X-OpenRouter-Title` (preferred), `X-Title` (back-compat alias); defaults to `https://gbrain.ai` / `gbrain`; forks override via `OPENROUTER_REFERER` / `OPENROUTER_TITLE` env vars. Smoke-tested by `test/ai/recipe-openrouter.test.ts` (incl. the shape-test regression guard: every model in the chat list matches `^[a-z0-9-]+\/[a-z0-9._-]+$`).
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check reads `search.reranker.enabled` first so "no events in window" is interpreted correctly (disabled → ok; enabled → ok). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
- `src/core/search/embedding-column.ts` — single source of truth for "which `content_chunks.*` column does this query rank against?" Pure functions, no engine I/O: `loadRegistry(cfg)` walks the `embedding_columns` config (DB plane, JSON map keyed by column name with `{provider, dimensions, type}` entries), seeds the OpenAI `embedding` builtin when unset, validates everything before it lands (column-name regex, type ∈ `vector | halfvec`, dims in [1, 8192], provider format) using `Object.create(null)` + `Object.hasOwn` so a key like `constructor` rejects instead of resolving to `Object.prototype.constructor`. `resolveColumn(registry, override?, cfg)` is the boundary call: returns a frozen `ResolvedColumn` descriptor (`{name, provider, dimensions, type}`) honoring per-call override → `search_embedding_column` config → `'embedding'` default; throws `UnknownEmbeddingColumnError` with the list of registered names on miss. `isCacheSafe(resolved, cfg)` compares the full embedding SPACE (provider + dimensions + name) against cfg's default so a repointed `embedding` builtin doesn't serve OpenAI-shaped cache rows. `validateResolvedColumn(descriptor)` re-validates hand-rolled descriptors that bypass the registry (internal-SDK passthrough) so the SQL-injection escape hatch through the descriptor field is closed. Consumed by `hybridSearch`, `gateway.embedQuery(text, {embeddingModel, dimensions})`, `cosineReScore`, and the `query` MCP op (per-call `embedding_column` param). Pinned by `test/search/embedding-column.test.ts` (prototype-pollution, descriptor passthrough, env-only Postgres install, empty-brain coverage gate, cache-space comparison).
- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, sends to `gateway.rerank()`, reorders by `relevanceScore` desc, appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged. Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network.
@@ -152,7 +152,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Pinned by 13 unit cases.
- `src/core/model-config.ts` — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (`ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent'`) with `TIER_DEFAULTS` (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and `tier?: ModelTier` on `ResolveModelOpts`. 8-step resolution chain: cliFlag → deprecated key → config key → `models.default` → `models.tier.<tier>` → env var → `TIER_DEFAULTS[tier]` → caller fallback. `isAnthropicProvider(modelString)` checks `provider:model` prefix OR `claude-` bare-id pattern (routes through `splitProviderModelId` from `src/core/model-id.ts` so slash-form ids like `anthropic/claude-sonnet-4-6` classify correctly). `enforceSubagentAnthropic()` is the layer-2 runtime guard: when `tier === 'subagent'` resolves non-Anthropic, it emits a once-per-`(source, model)` stderr warn AND falls back to `TIER_DEFAULTS.subagent` (the Anthropic Messages API tool-loop can't run on OpenAI/Gemini). `_resetDeprecationWarningsForTest()` also clears `_subagentTierWarningsEmitted`. Pinned by `test/model-config.serial.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape.
-- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (13 `PER_TASK_KEYS`, now including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
+- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (13 `PER_TASK_KEYS`, now including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`). `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and used to false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
- `src/core/init-embed-check.ts` — embedding-key validation at `gbrain init`. `runInitEmbedCheck(opts)` runs a config-only `diagnoseEmbedding` (catches a missing key for ANY provider) plus a best-effort `liveTestEmbed` (1-token `gateway.embed(['probe'], {inputType:'query', abortSignal})`, 5s `AbortController` timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (`--no-embedding` is the deferred-setup escape; `--skip-embed-check` / `GBRAIN_INIT_SKIP_EMBED_CHECK=1` skip the check). Builds the effective env (`process.env` + every file-plane provider key `buildGatewayConfig` folds — openai/anthropic/voyage/zeroentropy/dashscope/google, #2662 — from `loadConfigFileOnly()` + `opts.apiKey`) and configures the gateway via `buildGatewayConfig` before diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names `--no-embedding` / `--skip-embed-check`, not the sync-flavored `--no-embed`. Wired into `initPGLite` + `initPostgres` in `src/commands/init.ts`, with the result added to the `--json` envelope as `embedding_check {ok, reason?, live_ok?}`. Pinned by `test/init-embed-check.test.ts` (hermetic via the gateway embed-transport seam + `withEnv`).
- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, extracted from `src/cli.ts` (which re-exports it for back-compat). Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Single owner of folding file-plane API keys (openai/anthropic/zeroentropy) into the gateway env and threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries, `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.
@@ -215,6 +215,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/conversation-parser/` — 17-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (17 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); and **`--background` via `maybeBackground`**. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, closing the "terminal audit row written after partial insertFacts failure" class. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`.
+- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — replacing five hand-copied lists that could drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` transitively attributed that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry (#4135). Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`.
- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. #2576: markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist survives only as the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (issue #972, default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter` (replaces the old `nullResolver` ternary). All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 (#1941) then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three new `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). Race fix: `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` gains `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` adds `'extract.stale'` to `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` adds `links_extraction_lag` to `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp regression + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite regression in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.
@@ -224,7 +225,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/sources.ts` — `gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit}`. `current [--json]` calls `resolveSourceWithTier()` and prints `source_id`, `tier` (`flag | env | dotfile | local_path | brain_default | seed_default`), and optional `detail` (decision table in `skills/conventions/brain-routing.md`). `status [--json]` — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around `buildSyncStatusReport` + `printSyncStatusReport` from `src/commands/sync.ts`; `--json` emits stable `{schema_version: 1, sources, ...}` on stdout; filters input to `local_path IS NOT NULL AND archived IS NOT TRUE`. `audit <id> [--json]` — read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walks `sources.local_path`, reads each markdown file, runs `assessContent()` from `src/core/content-sanity.ts`, aggregates by verdict (`ok | warn_oversize | hard_block_junk_pattern`). The live `runStatus` health table gains a `BACKFILL` column between `EMBED` and `FAILS` (`active(N)` beats `queued(N)` beats `idle`, from `SourceMetrics.backfill_active` / `backfill_queued` in `src/core/source-health.ts`) so operators see deferred `embed-backfill` minion work after `sync --all` exits 0; `jobCountsBySource` in `source-health.ts` widens its `minion_jobs` SQL with two `COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)` aggregates (best-effort, all-0 on pre-minions brains). `remove` pre-checks OAuth-client referents (guided refusal via `formatClientReferentsBlock` — the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (`unhardenBrainRepo`: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact. `purge` runs the same referents pre-check before its hard DELETE. Pinned by `test/content-sanity.test.ts`, `test/import-file-content-sanity.test.ts`, `test/source-health.test.ts`.
- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch (#1963); it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it) and timed out 100% of the time on PGLite. Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).
- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for historical non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.
-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'`, auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (14 cases), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`).
+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'`, auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (14 cases), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the #3242 widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases).
- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (#1941, opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (#2073, idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — NULL never matched a scoped `AND source_id = …` filter so scoped `code-callers`/`code-callees` returned 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (#4152, additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).
- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).
- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.
@@ -262,13 +263,13 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.
- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown'`). Single regression point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
- `src/core/minions/backpressure-audit.ts` — sibling of shell-audit.ts for `maxWaiting` AND `maxPending` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. One line per coalesce with `(queue, name, waiting_count/max_waiting OR pending_count/max_pending, returned_job_id, ts)`. `readRecentCoalesceCounts` feeds the `jobs stats` Backpressure line (reads current + previous ISO-week files so a 24h window survives week boundaries, filtered per queue). Closes the silent-drop vector the backpressure guards introduced. Pinned by `test/backpressure-audit-read.test.ts`.
-- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`.
+- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id` — providers like claude-cli legitimately re-mint the same short id every turn, and the collision dead-lettered the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
- `src/core/minions/handlers/subagent-audit.ts` — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback for `gbrain agent logs`.
- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms).
- `src/core/minions/handlers/contextual-reindex-per-chunk.ts` — per-page contextual re-embed handler. Resolves `models.contextual_synopsis` once and isolates cross-worker leases by the full resolved model id. `GBRAIN_CONTEXTUAL_SYNOPSIS_RPM` controls the cap; `GBRAIN_CONTEXTUAL_HAIKU_RPM` is the compatibility alias.
- `src/core/minions/wait-for-completion.ts` — poll-until-terminal helper for CLI callers. `TimeoutError` does NOT cancel the job; `AbortSignal` exits without throwing. Default `pollMs`: 1000 on Postgres, 250 on PGLite inline.
-- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `tool_use_id`. UTF-8-safe truncation; unknown block types fall through to fenced JSON.
+- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.
- `src/core/minions/plugin-loader.ts` — `GBRAIN_PLUGIN_PATH` discovery. Absolute paths only, left-wins collision, `gbrain.plugin.json` with `plugin_version: "gbrain-plugin-v1"`, plugins ship DEFS only (no new tools), `allowed_tools:` validated at load time against the derived registry.
- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trust comes from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitters set it. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param).
- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list` (WP3 amendment 14 unified the former inline mapper onto it), and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. Default emission is byte-identical to the pre-WP3 output; `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (D14.1 — schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.
@@ -317,7 +318,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — closes the PGLite CLI search/query/get-hang class where the IIFE raced disconnect and PGLite's WASM kept Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — closes the silent-false-success class where `--save` printed "Saved" unconditionally even when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown` (string `buildBrainstormFrontmatter` untouched). Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.
- `src/core/write-through.ts` — shared atomic disk write-through for the canonical ingestion path. `writePageThrough(engine, slug, {sourceId?, frontmatterOverrides?, logger?})` resolves the disk target from the ASSIGNED source's own working tree (`sources.local_path`), re-reads the just-written DB row (`getPage`), renders it via `serializePageToMarkdown`, and writes the `.md` under that tree's root so the brain has a committable artifact that round-trips through `gbrain sync`. A source with its own `local_path` writes there; a source WITHOUT one falls back to the global `sync.repo_path` ONLY when this is the sole source (then that path is unambiguously this source's tree) and otherwise skips with `source_has_no_local_path` rather than leak into a sibling source's git repo. Rendering FROM the row means file and row cannot diverge. ATOMIC: writes to a unique temp sibling (`<file>.tmp.<pid>.<rand>`) + `renameSync`, cleaning up temp on any failure, so a crash or concurrent `gbrain sync`/autopilot walking the live git tree never reads a half-written `.md` (matches the `.tmp + rename` convention in import-checkpoint.ts / op-checkpoint.ts). Never throws — returns `WriteThroughResult { written, path?, skipped?: 'no_repo_configured' | 'repo_not_found' | 'source_has_no_local_path' | 'page_not_found_after_write', error? }` so the caller decides messaging + exit codes. Trust gating (subagent sandbox, dry-run) stays at the CALLER. On a durability-hardened repo (`isDurabilityHardened` — the gbrain post-commit hook is installed, i.e. the user ran `gbrain sources harden`), a successful write is best-effort COMMITTED via `commitWriteThroughFile` (path-limited `git commit -- <file>`, never sweeps unrelated edits; the hook then background-pushes) so write-through content reaches git instead of accumulating uncommitted forever (#2426); result carries `committed?: boolean`. Unhardened repos keep write-only behavior. Consumers: `put_page` op and `gbrain brainstorm/lsd --save` via `persistSavedIdea`. Pinned by `test/write-through.test.ts` + `test/write-through-commit.serial.test.ts`.
- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/minions/batch-projection.ts` at two call sites, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.
-- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help).
+- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help).
- `src/core/transcripts/` (directory) — the cathedral-4 transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which gained the ADDITIVE full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is regression-pinned byte-identical), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message, assistant from `response_item` output_text; role user/developer response_items are injected preambles and never leak), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), ~300KB message-boundary splitting with 2-message overlap (under the embed-skip threshold), part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/e2e/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path — the BrainBench bypass closer).
- `src/commands/integrity.ts` — `gbrain integrity check|auto|review|extract`: bare-tweet detection, dead-link detection, three-bucket repair (auto-repair / review-queue / skip). `scanIntegrity()` is the shared library function called from `gbrain doctor` (sampled at limit=500) and `cmdCheck` (full scan). Batch-load fast path on Postgres uses a single SQL query (fixes the PgBouncer round-trip timeout, ~60s → ~6s), gated by `engine.kind === 'postgres'` at the call site so PGLite never enters batch; fallback `catch` logs at `GBRAIN_DEBUG=1`. Batch projection is `SELECT ... ORDER BY source_id, slug` (NOT `SELECT DISTINCT ON (slug)`, which collapsed same-slug-different-source pages into one scan) so multi-source brains scan each `(source, slug)` row independently. Sequential and auto-repair loops use `listAllPageRefs()` to enumerate `(slug, source_id)` pairs and thread `sourceId` to `getPage`; batch + sequential paths report the same page count on multi-source brains.
- `src/core/timeline-dedup-repair.ts` (#2038) — schema-drift self-heal for `idx_timeline_dedup`. The migration that widened the dedup index from `(page_id, date, summary)` to `(page_id, date, summary, source)` was renumbered during a master merge, so a brain that ran the old variant has its version counter stamped past the change while the index keeps the 3-column shape — and every `addTimelineEntry` batch then fails its 4-column `ON CONFLICT`, silently breaking timeline writes brain-wide. The version counter can't detect this, so the repair is keyed off the actual index SHAPE: `checkTimelineDedupIndex(engine)` returns `{tablePresent, indexPresent, columns, needsRepair}` (read-only; powers the `timeline_dedup_index` doctor check) and `repairTimelineDedupIndex(engine)` dedupes-then-rebuilds the index. `runMigrations` invokes the repair on every pass (including the no-pending early-return path); idempotent no-op when the index is already 4-column. `gbrain apply-migrations --force-schema` triggers it on demand. Pinned by `test/timeline-dedup-repair.test.ts`.
diff --git a/docs/contradictions.md b/docs/contradictions.md
index 46ca5012f0..0da06f12fb 100644
--- a/docs/contradictions.md
+++ b/docs/contradictions.md
@@ -106,15 +106,23 @@ Decision criteria for the bigger swing (chunk-level `revises` field):
## When to act on findings
-Each finding ships with a `resolution_command` field — paste-ready:
-
-- `gbrain takes supersede <slug> --row N` — newer take should replace
- the older chunk text on the same page (intra_page kind).
+Each finding ships with a `resolution_command` field — addressable and
+honest about what needs operator judgment:
+
+- `gbrain takes supersede <slug> --row N --claim '<replacement>'` — newer
+ take should replace the older one (intra_page kind). `--row` is the
+ per-page row number and `--claim` is required; when the winning side has
+ an unambiguous claim (temporal supersession where the newer side is
+ itself a take) the command is fully paste-ready, otherwise it carries an
+ explicit `<replacement claim>` placeholder for you to fill from the
+ report — the classifier picks an action, not a winner, and will not
+ fabricate a take from arbitrary chunk prose.
- `gbrain dream --phase synthesize --slug <slug>` — compiled_truth for
the curated entity needs an update (cross_slug curated-vs-bulk).
-- `gbrain takes mark-debate <slug> --row N` — intentional disagreement
- (e.g., two opinions you want to keep both of).
-- `# manual review: <a> vs <b>` — judge wasn't sure; operator decides.
+- `# manual review: ...` — intentional-disagreement (debate) findings and
+ judge-unsure findings render as a manual-review comment; a
+ mark-as-debate subcommand does not exist yet, so nothing is minted that
+ would fail when pasted.
Run `gbrain eval suspected-contradictions review --severity high` to
inspect findings without re-running the probe.
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 9e7cd1413d..ea08943adc 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -133,7 +133,10 @@ gbrain sources list [--json] List all sources with page counts + federation st
gbrain sources archive <id> Soft-delete: hide from search, keep data for a TTL
grace window. Prefer this over `remove`.
gbrain sources restore <id> Un-archive. `gbrain sources archived` lists expiries;
- `gbrain sources purge` permanently deletes expired archives.
+ `gbrain sources purge` permanently deletes expired archives —
+ except sources still referenced by a registered OAuth client
+ (reported as `Blocked:`, sweep continues); revoke or rescope
+ the client (`gbrain auth revoke-client <id>`) and re-run.
gbrain sources remove <id> [--confirm-destructive] [--dry-run]
Permanently cascade-delete a source (pages, chunks,
timeline). Shows an impact preview first.
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 553d09c911..abd5ce577e 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -25,7 +25,7 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
|---|---|---|---|---|---|
| `voyage` (**default** — `voyage-4` @ 1024d; `rerank-2.5` reranker on the same key) | `VOYAGE_API_KEY` | 1024 | 0.06 (`voyage-4`) | no | yes (`voyage-multimodal-3`) |
| `openai` | `OPENAI_API_KEY` | 1536 | 0.13 | no | no |
-| `openrouter` | `OPENROUTER_API_KEY` | 1536 | 0.02 | no | model-dependent |
+| `openrouter` | `OPENROUTER_API_KEY` | per-model (1536 for the default `openai/text-embedding-3-small`; unlisted ids require explicit dims) | 0.02 | no | model-dependent |
| `zeroentropyai` — **DEPRECATED** (hosted API **shuts down 2026-09-04**; replacement `voyage:voyage-4` — see note below) | `ZEROENTROPY_API_KEY` | 2560 (Matryoshka to 1280/640/320/...) | 0.05 | no | no |
| `google` | `GOOGLE_GENERATIVE_AI_API_KEY` | 768 | 0.025 | no | no |
| `azure-openai` | `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENT` | 1536 | 0.13 | no | no |
@@ -112,7 +112,7 @@ For GCP service-account / Vertex AI auth (production deployments), see the v0.32
Single OpenAI-compatible API for fan-out to OpenAI, Anthropic, Google, DeepSeek, Meta Llama, Qwen, and dozens of other hosted providers. One key, many models. Set `OPENROUTER_API_KEY` or `openrouter_api_key` in `~/.gbrain/config.json`, then use `openrouter:<provider>/<model>` (e.g. `openrouter:openai/gpt-5.2`, `openrouter:anthropic/claude-sonnet-4.6`).
-**Embedding**: `openai/text-embedding-3-small` (1536d default, Matryoshka shrink to 512/768/1024). OR's embedding catalog also includes `text-embedding-3-large`, `google/gemini-embedding-2-preview`, `qwen/qwen3-embedding-8b`, `bge-m3` — opt in via `--embedding-model openrouter:<id>`. Pricing matches the upstream provider (OR adds a small markup).
+**Embedding**: `openai/text-embedding-3-small` (1536d default, Matryoshka shrink to 512/768/1024). The recipe carries verified per-model native dims for its catalog — `openai/text-embedding-3-large` (3072), `qwen/qwen3-embedding-8b` (4096), `bge-m3` (1024) — so opting in via `--embedding-model openrouter:<id>` plans the right column width automatically. Any id NOT in that list (including `google/gemini-embedding-2-preview`, whose width is unverified) has no silent default: you must pass explicit dimensions (`--embedding-dimensions <N>` or `embedding_dimensions` config) or the command errors with the fix. Pricing matches the upstream provider (OR adds a small markup).
**Chat**: every chat model OR proxies works through `/v1/chat/completions`. The recipe lists 8 curated entry points (GPT-5.2 family, Claude 4.5/4.6/4.7, Gemini 3 Flash Preview, DeepSeek); any other OR catalog ID also works. Tool-calling envelope is supported by the OR endpoint, but per-model capability varies — check https://openrouter.ai/models before counting on tools for a specific slug.
diff --git a/llms-full.txt b/llms-full.txt
index 0d08b6a5ba..04da7c4c66 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1924,6 +1924,7 @@ re-runs are free — unchanged sessions skip on content hash:
gbrain transcripts ingest # discover importable session logs
gbrain transcripts ingest --all # import everything discovered
gbrain transcripts ingest ~/Downloads/conversations.json # consumer export (unzip first)
+gbrain transcripts ingest --max-bytes 4gb <store> # oversized store; omit to keep per-format caps
gbrain transcripts status # found vs imported, per harness
```
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index d4aad4abfb..e013c6abce 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.13.0",
+ "version": "0.46.14.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index e4c17944d2..58c4a34e28 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.13.0",
+ "version": "0.46.14.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index 0d321fe3f0..e0e698196f 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.13.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.14.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/conversation-archive/SKILL.md b/plugin/skills/conversation-archive/SKILL.md
index ebd1d09e34..c583330a20 100644
--- a/plugin/skills/conversation-archive/SKILL.md
+++ b/plugin/skills/conversation-archive/SKILL.md
@@ -71,9 +71,15 @@ procedure whenever the source is one of those six formats:
```
gbrain transcripts ingest ~/Downloads/conversations.json # unzip first
gbrain transcripts ingest # discover harness logs
+gbrain transcripts ingest --max-bytes 4gb <store> # oversized store (omit = per-format caps)
gbrain transcripts status # found vs imported gaps
```
+`--max-bytes` note: the cap is part of the `--since last` checkpoint
+fingerprint — running with a different cap (or dropping it) starts a fresh
+watermark scope, so a capped run's skipped tail is never mistaken for
+already-scanned.
+
Native-vs-manual delta to know: the native lane redacts SECRETS (key
patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and
counts agent-directed imperatives into frontmatter, but broad PII detection
diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.md
index 3ad249e400..9471bd9cb7 100644
--- a/plugin/skills/maintain/SKILL.md
+++ b/plugin/skills/maintain/SKILL.md
@@ -294,6 +294,9 @@ Populate them periodically or after major imports:
- `gbrain stats` — verify `link_count > 0` and `timeline_entry_count > 0` after extraction.
- `gbrain health` — review `link_coverage` and `timeline_coverage` percentages
on entity pages (person/company). Below 50% means more extraction is needed.
+ On brains with very few entity pages these report "too few to grade"
+ (`null` in JSON, with `entity_page_count` carrying the denominator) instead
+ of a misleading 0%/100% — grow the entity set before acting on coverage.
Available link types (use with `gbrain graph-query --type`):
`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, `source`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e0fde3a067..7463d6959c 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -9,10 +9,10 @@ src/core/postgres-engine.ts 5770 ratchet peel target: containment sprint C15; gr
src/core/pglite-engine.ts 5660 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wave
-src/core/ai/gateway.ts 4117 ratchet watchlist
-src/cli.ts 3433 ratchet watchlist; +21 gap-closure wave thin-client routing; +cathedral-6 agent-register pre-connect guards + `--`-aware help + shared thin-client message import
-src/core/cycle.ts 2933 ratchet
-src/commands/serve-http.ts 2962 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight)
+src/core/ai/gateway.ts 4168 ratchet watchlist
+src/cli.ts 3453 ratchet watchlist; +21 gap-closure wave thin-client routing; +cathedral-6 agent-register pre-connect guards + `--`-aware help + shared thin-client message import; +sources self-help (chennai wave)
+src/core/cycle.ts 3024 ratchet
+src/commands/serve-http.ts 2978 ratchet grown cathedral-6 multi-agent wave (admin register route composes registerScopedClient in one tx under the name advisory lock; ttl validation + brain_too_old preflight) + chennai no-grant federated scope
src/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wave
src/core/search/hybrid.ts 2479 ratchet
src/core/engine.ts 2345 ratchet
@@ -22,14 +22,14 @@ src/commands/extract-conversation-facts.ts 1968 ratchet
src/core/import-file.ts 2000 ratchet grown v0.46.11.0 five-issue wave
src/core/cycle/synthesize.ts 2685 ratchet grown v0.46.11.0 five-issue wave
src/commands/embed.ts 1963 ratchet
-src/core/types.ts 1829 ratchet
+src/core/types.ts 1851 ratchet
src/commands/skillpack.ts 1763 ratchet
src/core/minions/queue.ts 2130 ratchet grown v0.46.11.0 five-issue wave
src/commands/init.ts 1932 ratchet
src/commands/integrations.ts 1675 ratchet
-src/core/minions/handlers/subagent.ts 1643 ratchet
+src/core/minions/handlers/subagent.ts 1773 ratchet
src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 1500 cap on master)
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 1642 ratchet grown cathedral-6 fix wave (remove: in-tx referents re-check + DELETE commits before external teardown)
-src/core/bootstrap/harness.ts 1914 ratchet
+src/commands/sources.ts 1676 ratchet
+src/core/bootstrap/harness.ts 1947 ratchet
src/commands/hook.ts 1525 ratchet
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 33dce90cd1..b25c77c715 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -47,6 +47,7 @@ test/codex-plugin-manifest.test.ts curated tree membership + scanner guard 5 rea
test/config.test.ts config source correctness 2 readFileSync
test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync
test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync
+test/conversation-facts-type-allowlist-drift.test.ts (file-level) 17 readFileSync
test/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSync
test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 4 readFileSync
test/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync
diff --git a/skills/conversation-archive/SKILL.md b/skills/conversation-archive/SKILL.md
index ebd1d09e34..c583330a20 100644
--- a/skills/conversation-archive/SKILL.md
+++ b/skills/conversation-archive/SKILL.md
@@ -71,9 +71,15 @@ procedure whenever the source is one of those six formats:
```
gbrain transcripts ingest ~/Downloads/conversations.json # unzip first
gbrain transcripts ingest # discover harness logs
+gbrain transcripts ingest --max-bytes 4gb <store> # oversized store (omit = per-format caps)
gbrain transcripts status # found vs imported gaps
```
+`--max-bytes` note: the cap is part of the `--since last` checkpoint
+fingerprint — running with a different cap (or dropping it) starts a fresh
+watermark scope, so a capped run's skipped tail is never mistaken for
+already-scanned.
+
Native-vs-manual delta to know: the native lane redacts SECRETS (key
patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and
counts agent-directed imperatives into frontmatter, but broad PII detection
diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.md
index 3ad249e400..9471bd9cb7 100644
--- a/skills/maintain/SKILL.md
+++ b/skills/maintain/SKILL.md
@@ -294,6 +294,9 @@ Populate them periodically or after major imports:
- `gbrain stats` — verify `link_count > 0` and `timeline_entry_count > 0` after extraction.
- `gbrain health` — review `link_coverage` and `timeline_coverage` percentages
on entity pages (person/company). Below 50% means more extraction is needed.
+ On brains with very few entity pages these report "too few to grade"
+ (`null` in JSON, with `entity_page_count` carrying the denominator) instead
+ of a misleading 0%/100% — grow the entity set before acting on coverage.
Available link types (use with `gbrain graph-query --type`):
`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, `source`.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 5ae71ab23a..993bb859b0 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -58,7 +58,7 @@
"conventions/subagent-routing.md": "8b8830b815a9a8581a12b489f966c0b0a39eb9b5f66e905a691a03653eef348d",
"conventions/test-before-bulk.md": "6b2c52cda9e2cd5f04c15152b3d92aeb7187ab193a15082be0f8a3991a6a5725",
"conventions/untrusted-content.md": "259384d490892cd0e1e8e054decf752d7354f516c83aee57b332c1a96aac6a6e",
- "conversation-archive/SKILL.md": "4e1dea00f5e1e16e749a42f295fdccf556199d4400a2ba1b891aa91839e37214",
+ "conversation-archive/SKILL.md": "3c1d342c58444a8b2c7fd961dee1ff8c08bfa3487877f877699abd4d0582b003",
"conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca",
"correction-pipeline/SKILL.md": "caf1264b7afec46569d30f6d92b07f37ae375e3f4e6aeddd58866aec327053de",
"correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",
@@ -87,7 +87,7 @@
"idea-lineage/SKILL.md": "bbf37781d93b71ddc7909ecc5ab635872c874fb8591995dbf88b45ffeac6b1de",
"idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41",
"ingest/SKILL.md": "dc40ecc0072806fb8c7bb6ab9cf1f103842e05653eb55d67632d7e3ffc4dd7d2",
- "maintain/SKILL.md": "33e48e31baf89b6b257ad863cdb9de444777bc1272f5ed8c2b28be3a54cbaa14",
+ "maintain/SKILL.md": "89ace6ae686284fd4423416a3b80d8ad940fbcf5313523f690684afe52779788",
"manifest.json": "03471868cce05fa38af6f793da54e2fc11f77ef778271a596d75bc29f9ec4c73",
"measure-before-you-fix/SKILL.md": "1fd3b40ab65cbd08f50dea16107701859165469be3c85c57d779c7b4bbf92db8",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
diff --git a/src/cli.ts b/src/cli.ts
index ae21b076aa..43a4b317fa 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -175,6 +175,15 @@ const CLI_ONLY_SELF_HELP = new Set([
// would hide both — `gbrain dream retriage --help` printed the one-line
// dream stub instead of the retriage contract (outside-voice CX9).
'dream',
+ // sources ships its own printHelp() (sources.ts, wired to `case '--help'`)
+ // covering all ~28 subcommands, but was missing from this set — so
+ // `gbrain sources --help` hit the generic one-line stub, which itself says
+ // "run gbrain --help for the full command list", and the top-level help's
+ // own SOURCES block promises `sources --help` as the place to find the
+ // long tail (rename, default, attach, current, federate, set-cr-mode,
+ // webhook, harden, ...). That made the pointer circular and those
+ // subcommands undiscoverable from the CLI in either direction.
+ 'sources',
// ZE interim cleanup: the retired ze-switch shim ships truthful help
// (sunset refusal + canonical migration command); the generic stub hid it.
'ze-switch',
@@ -203,6 +212,11 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, arg
// runDream accepts BrainEngine | null; --help (and `retriage --help`) is
// answered before any engine-bearing work per the dream.ts IRON RULE.
dream: async () => (await import('./commands/dream.ts')).runDream as never,
+ // runSources's `--help`/`-h`/undefined-subcommand branch calls printHelp()
+ // without ever touching `engine` — safe to dispatch with no brain
+ // configured, matching the reader who runs `sources --help` because they
+ // have no brain yet.
+ sources: async () => (await import('./commands/sources.ts')).runSources as never,
// runAgent accepts BrainEngine | null; help (incl. `register --help`) is
// answered before any engine or job-queue work (cathedral-6).
agent: async () => (await import('./commands/agent.ts')).runAgent as never,
@@ -1522,11 +1536,17 @@ export function formatResult(
`Stale pages: ${h.stale_pages}`,
`Orphan pages: ${h.orphan_pages}`,
];
- if (h.link_coverage !== undefined) {
+ // gbrain#4147: null = below the small-N floor — say so instead of
+ // rendering a misleading hard 0%/100%.
+ if (h.link_coverage != null) {
lines.push(`Link coverage (entities): ${(h.link_coverage * 100).toFixed(1)}%`);
+ } else if (h.entity_page_count !== undefined) {
+ lines.push(`Link coverage (entities): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
}
- if (h.timeline_coverage !== undefined) {
+ if (h.timeline_coverage != null) {
lines.push(`Timeline coverage (entity pages): ${(h.timeline_coverage * 100).toFixed(1)}%`);
+ } else if (h.entity_page_count !== undefined) {
+ lines.push(`Timeline coverage (entity pages): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
}
if (h.timeline_coverage_score !== undefined) {
lines.push(`Timeline density (all pages): ${h.timeline_coverage_score}/15 (whole-brain brain-score component)`);
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 2221f0a18a..a630d75c58 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -1,4 +1,7 @@
import type { BrainEngine } from '../core/engine.ts';
+// Leaf module (no flag surface of its own) — see that file for why this
+// isn't imported from extract-conversation-facts.ts directly (#4135).
+import { ALLOWED_TYPES } from '../core/facts/conversation-types.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import * as db from '../core/db.ts';
import { LATEST_VERSION, getIdleBlockers } from '../core/migrate.ts';
@@ -1268,7 +1271,8 @@ export async function buildChecks(
try {
const { readConversationBodyForParsing } = await import('../core/conversation-parser/body.ts');
const { parseConversation } = await import('../core/conversation-parser/parse.ts');
- const allowedTypes = ['conversation', 'meeting', 'slack', 'email', 'imessage', 'imessage-daily'] as const;
+ // Single source of truth for the conversation-facts type allowlist (#4135).
+ const allowedTypes = ALLOWED_TYPES;
// PageFilters supports singular `type` only; iterate the allowed types
// and cap at ~50/each to land at ~200 total max.
const sample: import('../core/types.ts').Page[] = [];
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 86194032b7..e95660368f 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -6,6 +6,9 @@
*/
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
+// Leaf module (no flag surface of its own) — see that file for why this
+// isn't imported from extract-conversation-facts.ts directly (#4135).
+import { ALLOWED_TYPES } from '../../../core/facts/conversation-types.ts';
/**
* v0.32.3 [CDX-20]: surface mode + per-key override drift.
@@ -475,7 +478,9 @@ export async function computeConversationFactsBacklogCheck(
const typesRaw = await engine.getConfig(
'cycle.conversation_facts_backfill.types',
);
- let types = ['conversation', 'meeting', 'slack', 'email', 'imessage', 'imessage-daily'];
+ // Default mirrors ALLOWED_TYPES — the single source of truth for the
+ // conversation-facts type allowlist (#4135).
+ let types: string[] = [...ALLOWED_TYPES];
if (typesRaw) {
try {
const parsed = JSON.parse(typesRaw);
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index 46efbd91d1..ced0332a89 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -454,9 +454,29 @@ function printHuman(report: CycleReport) {
}
if (report.status === 'clean') {
+ // A 'clean' cycle can still carry a skip reason worth surfacing — e.g.
+ // synthesize's D8 legacy-key / D5 oversize-chunk skips leave
+ // transcripts_processed/synth_pages_written at 0 (so deriveStatus sees
+ // no activity) while `details.skips` names exactly why each transcript
+ // was passed over. Without this, `--input <already-handled-file>`
+ // prints only "Brain is healthy" with no indication anything was
+ // examined and skipped.
+ const skipLines: string[] = [];
+ for (const p of report.phases) {
+ const skips = (p.details as { skips?: Array<{ filePath: string; reason: string }> } | undefined)?.skips;
+ if (Array.isArray(skips)) {
+ for (const s of skips) {
+ skipLines.push(` - ${p.phase}: ${s.filePath} (${s.reason})`);
+ }
+ }
+ }
console.log(
`Brain is healthy. ${report.phases.length} phase(s) checked in ${(report.duration_ms / 1000).toFixed(1)}s.`,
);
+ if (skipLines.length > 0) {
+ console.log('Skipped:');
+ for (const line of skipLines) console.log(line);
+ }
return;
}
@@ -489,6 +509,14 @@ function printHuman(report: CycleReport) {
}
}
+// ── Test-only export ───────────────────────────────────────
+// `__testing` re-exports otherwise-private helpers so unit tests can pin
+// CLI output behavior without spawning a subprocess. Not part of the
+// runtime contract.
+export const __testing = {
+ printHuman,
+};
+
// ─── CLI entry ─────────────────────────────────────────────────────
/**
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index dba76ed78b..28acdeec50 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -93,6 +93,16 @@ import { withRefreshingLock, LockUnavailableError } from '../core/db-lock.ts';
import { assertFactsEmbeddingDimMatchesConfig } from '../core/embedding-dim-check.ts';
import { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';
import { upsertExtractRollup } from '../core/extract/rollup-writer.ts';
+import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';
+
+// Re-exported verbatim so existing importers (this file's own helpers below
+// and this file's tests) keep working unchanged; doctor.ts, jobs.ts,
+// sources.ts, and the cycle backfill phase import the leaf directly. Moved to
+// src/core/facts/conversation-types.ts (see that file for why) so a
+// consumer that only needs the six values doesn't also pull in this file's
+// own CLI flag surface.
+export { ALLOWED_TYPES };
+export type { AllowedType };
// ---------------------------------------------------------------------------
// Tunables (exported for tests).
@@ -135,21 +145,11 @@ export const MAX_PAGE_BODY_BYTES = 25 * 1024 * 1024;
/** Default cost cap when no tracker is passed explicitly. */
export const DEFAULT_MAX_COST_USD = 5.0;
-/**
- * Allowlist of page types this command operates on. Mirrors
- * cycle.conversation_facts_backfill.types config default. CLI's
- * `--types` flag is an explicit per-run override; cycle config is
- * the single source of truth.
- */
-export const ALLOWED_TYPES = [
- 'conversation',
- 'meeting',
- 'slack',
- 'email',
- 'imessage',
- 'imessage-daily',
-] as const;
-export type AllowedType = (typeof ALLOWED_TYPES)[number];
+// ALLOWED_TYPES / AllowedType now live in
+// ../core/facts/conversation-types.ts (imported + re-exported above).
+// Mirrors cycle.conversation_facts_backfill.types config default. CLI's
+// `--types` flag is an explicit per-run override; cycle config is the
+// single source of truth.
/**
* Granular collector page-types that alias into each canonical conversation
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index aa1df69e69..331149f822 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -4,6 +4,9 @@
*/
import type { BrainEngine } from '../core/engine.ts';
+// Leaf module (no flag surface of its own) — see that file for why this
+// isn't imported from extract-conversation-facts.ts directly (#4135).
+import { ALLOWED_TYPES, type AllowedType } from '../core/facts/conversation-types.ts';
import { MinionQueue, deriveWedgeSignal } from '../core/minions/queue.ts';
import { MinionWorker } from '../core/minions/worker.ts';
import {
@@ -2152,14 +2155,16 @@ export async function registerBuiltinHandlers(
// SHOULD pin to one source per call (job_id is per-call).
throw new Error('extract-conversation-facts Minion job requires data.sourceId');
}
+ // ALLOWED_TYPES is the single source of truth for the conversation-facts
+ // type allowlist (see src/core/facts/conversation-types.ts).
const types = Array.isArray(job.data.types)
- ? (job.data.types as string[]).filter((t) =>
- ['conversation', 'meeting', 'slack', 'email', 'imessage', 'imessage-daily'].includes(t),
+ ? (job.data.types as string[]).filter(
+ (t): t is AllowedType => (ALLOWED_TYPES as readonly string[]).includes(t),
)
: undefined;
const result = await runExtractConversationFactsCore(engine, {
sourceId,
- types: types as ('conversation' | 'meeting' | 'slack' | 'email')[] | undefined,
+ types,
slug: typeof job.data.slug === 'string' ? job.data.slug : undefined,
dryRun: !!job.data.dryRun,
limit: typeof job.data.limit === 'number' ? job.data.limit : undefined,
@@ -2653,14 +2658,17 @@ export async function registerBuiltinHandlers(
const result = await engine.purgeDeletedPages(olderThanHours);
pagesPurged = result.count;
}
+ let sourcesBlocked: Array<{ id: string; reason: string }> = [];
if (scope === 'sources' || scope === 'all') {
const { purgeExpiredSources } = await import('../core/destructive-guard.ts');
- sourcesPurged = await purgeExpiredSources(engine);
+ const purgeResult = await purgeExpiredSources(engine);
+ sourcesPurged = purgeResult.purged;
+ sourcesBlocked = purgeResult.blocked;
}
// GC stale op_checkpoints rows (folded scope item +C from review).
const { purgeStaleCheckpoints } = await import('../core/op-checkpoint.ts');
const checkpointsPurged = await purgeStaleCheckpoints(engine, 7);
- return { pagesPurged, sourcesPurged, checkpointsPurged, dryRun };
+ return { pagesPurged, sourcesPurged, sourcesBlocked, checkpointsPurged, dryRun };
});
// Phase-wrapper handlers — each delegates to runCycle({ phases: [name] }).
diff --git a/src/commands/models.ts b/src/commands/models.ts
index 9b54a82c2f..9b6832df2e 100644
--- a/src/commands/models.ts
+++ b/src/commands/models.ts
@@ -578,13 +578,43 @@ export async function probeEmbeddingReachability(deps: ProbeDeps = {}): Promise<
}
}
+/**
+ * Resolve the chat/expansion probe timeout: the recipe's declared
+ * `touchpoints.<kind>.default_timeout_ms` when set, else the probe's
+ * historical flat 5000ms.
+ *
+ * Pre-fix `probeModel` hardcoded 5000ms for every provider. That's fine for
+ * a plain network round-trip, but `claude-cli:` dispatches through a
+ * `claude -p (print mode)` subprocess (CLI cold start + user-level CLAUDE.md load),
+ * which routinely takes 5-6s even when healthy — so the probe aborted on
+ * every run and reported 'unknown — claude-cli adapter aborted', not
+ * because the model was actually unreachable. Mirrors the reranker probe's
+ * recipe-default fallback (`resolveLiveRerankerTimeoutMs` / mode.ts), but
+ * simpler: unlike `search.reranker.timeout_ms`, there's no config-key
+ * override for chat/expansion timeouts, so the chain is just per-call
+ * default (5000) unless the recipe overrides it.
+ */
+/** Historical flat probe timeout — right for fast HTTP providers; recipes override via default_timeout_ms. */
+const DEFAULT_PROBE_TIMEOUT_MS = 5000;
+
+export async function resolveChatProbeTimeoutMs(modelStr: string, touchpoint: 'chat' | 'expansion'): Promise<number> {
+ try {
+ const { resolveRecipe } = await import('../core/ai/model-resolver.ts');
+ const { recipe } = resolveRecipe(modelStr);
+ return recipe.touchpoints[touchpoint]?.default_timeout_ms ?? DEFAULT_PROBE_TIMEOUT_MS;
+ } catch {
+ return DEFAULT_PROBE_TIMEOUT_MS;
+ }
+}
+
export async function probeModel(modelStr: string, touchpoint: 'chat' | 'expansion', deps: ProbeDeps = {}): Promise<ProbeResult> {
const start = Date.now();
+ const probeTimeoutMs = await resolveChatProbeTimeoutMs(modelStr, touchpoint);
try {
const chat = deps.chat ?? (await import('../core/ai/gateway.ts')).chat;
- // Use AbortController so the 5s timeout doesn't hang on a stuck network.
+ // Use AbortController so the resolved timeout doesn't hang on a stuck network.
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(new Error('probe timed out after 5s')), 5000);
+ const timeoutId = setTimeout(() => controller.abort(new Error(`probe timed out after ${probeTimeoutMs}ms`)), probeTimeoutMs);
try {
await chat({
model: modelStr,
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 11273cee5b..433769963f 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -2358,6 +2358,21 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
// verifyAccessToken. The env-fallback is gone.
const tokenSourceId = authInfo.sourceId ?? 'default';
+ // #3242 parity: the legacy-transport and stdio dispatch sites widen a
+ // no-grant caller's unqualified reads across the federated source set
+ // (localFederatedSourceIds); this SDK-transport site never did, so the
+ // same token saw federated pages over /mcp on one serve mode and scalar
+ // 'default' on the other. hasSourceGrant === false is set ONLY for
+ // legacy bearer tokens with no operator source grant (oauth-provider);
+ // granted tokens and OAuth clients never widen. Best-effort: a resolver
+ // failure keeps the scalar scope.
+ const { noGrantFederatedScope } = await import('../core/source-resolver.ts');
+ const localFederated = await noGrantFederatedScope(
+ engine,
+ authInfo.hasSourceGrant,
+ tokenSourceId,
+ );
+
let toolResult: Awaited<ReturnType<typeof dispatchToolCall>>;
try {
toolResult = await dispatchToolCall(engine, name, params as Record<string, unknown> | undefined, {
@@ -2367,6 +2382,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
transport: 'http',
takesHoldersAllowList: tokenAllowList,
sourceId: tokenSourceId,
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
metaHook: getBrainHotMemoryMeta,
// MEMORY_VERBS v1: fail-closed surface enforcement + usage attribution.
...(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 959da41f71..de0a29b894 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -786,11 +786,16 @@ async function runPurge(engine: BrainEngine, args: string[]): Promise<void> {
}
// No id: purge all expired archives
- const purged = await purgeExpiredSources(engine);
- if (purged.length === 0) {
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ if (purged.length === 0 && blocked.length === 0) {
console.log('No expired archives to purge.');
} else {
- console.log(`Purged ${purged.length} expired archive(s): ${purged.join(', ')}`);
+ if (purged.length > 0) {
+ console.log(`Purged ${purged.length} expired archive(s): ${purged.join(', ')}`);
+ }
+ for (const b of blocked) {
+ console.log(`Blocked: ${b.id} — ${b.reason}`);
+ }
}
}
@@ -1030,6 +1035,17 @@ function formatLag(seconds: number): string {
}
// ── v0.40 sources webhook (D8) ──────────────────────────────
+// Hoisted so both runWebhook's `case '--help'` and the top-level nested-help
+// guard in runSources (`sources webhook --help`, `sources webhook <sub>
+// --help`) print the identical text without dispatching into runWebhook.
+const SOURCES_WEBHOOK_HELP = `Usage: gbrain sources webhook <subcommand> <source-id> [options]
+
+Subcommands:
+ set <id> [--secret VAL] [--github-repo owner/name] One-time reveal
+ show <id> Metadata only
+ rotate <id> New secret, reveal
+ clear <id> Remove webhook config`;
+
async function runWebhook(engine: BrainEngine, args: string[]): Promise<void> {
const sub = args[0];
const rest = args.slice(1);
@@ -1041,13 +1057,7 @@ async function runWebhook(engine: BrainEngine, args: string[]): Promise<void> {
case undefined:
case '--help':
case '-h':
- console.log(`Usage: gbrain sources webhook <subcommand> <source-id> [options]
-
-Subcommands:
- set <id> [--secret VAL] [--github-repo owner/name] One-time reveal
- show <id> Metadata only
- rotate <id> New secret, reveal
- clear <id> Remove webhook config`);
+ console.log(SOURCES_WEBHOOK_HELP);
return;
default:
console.error(`Unknown webhook subcommand: ${sub}`);
@@ -1369,14 +1379,8 @@ async function runAudit(engine: BrainEngine, args: string[]): Promise<void> {
// frontmatter.type and estimates per-page segment count from body
// bytes. Estimated per-segment Sonnet cost is a rough heuristic
// (~2000 in + 500 out tokens at $3/MTok in + $15/MTok out ≈ $0.013).
- const FACTS_BACKFILL_ALLOWED = [
- 'conversation',
- 'meeting',
- 'slack',
- 'email',
- 'imessage',
- 'imessage-daily',
- ];
+ // Single source of truth for the conversation-facts type allowlist.
+ const { ALLOWED_TYPES: FACTS_BACKFILL_ALLOWED } = await import('../core/facts/conversation-types.ts');
const FACTS_BACKFILL_CHARS_PER_SEGMENT = 6500; // matches SEGMENT_TEXT_CHAR_LIMIT
const FACTS_BACKFILL_USD_PER_SEGMENT = 0.013;
let factsBackfillPages = 0;
@@ -1420,7 +1424,7 @@ async function runAudit(engine: BrainEngine, args: string[]): Promise<void> {
}
// Facts-backfill estimator: counts pages matching allowed types.
const fmType = (parsed.frontmatter?.type as string | undefined) ?? null;
- if (fmType && FACTS_BACKFILL_ALLOWED.includes(fmType)) {
+ if (fmType && (FACTS_BACKFILL_ALLOWED as readonly string[]).includes(fmType)) {
factsBackfillPages++;
const totalBytes = sanity.bytes;
const segmentsEstimate = Math.max(
@@ -1519,6 +1523,36 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
const sub = args[0];
const rest = args.slice(1);
+ // Help guards run BEFORE the subcommand switch below (mirrors jobs.ts
+ // src/commands/jobs.ts:462-471 — help checked first-position, then any
+ // position, before any subcommand body runs). cli.ts routes bare `sources
+ // --help` here with a placeholder engine (SELF_HELP_WITHOUT_ENGINE): the
+ // second check is why that's safe — without it, `sources <sub> --help`
+ // would fall through to <sub>'s own handler instead of printing help,
+ // which crashes for engine-touching subcommands (the placeholder engine
+ // is not a real one) and, for engine-free subcommands like `detach`
+ // (unlinks .gbrain-source with no engine involved at all), would silently
+ // perform the destructive action instead of showing usage.
+ if (!sub || sub === '--help' || sub === '-h') {
+ printHelp();
+ return;
+ }
+ if (rest.includes('--help') || rest.includes('-h')) {
+ // webhook is the one sources subcommand that ships its own detailed
+ // --help (set/show/rotate/clear, in SOURCES_WEBHOOK_HELP) — print that
+ // instead of the general list so `sources webhook --help` and `sources
+ // webhook <sub> --help` reach it. Do NOT dispatch into runWebhook: that
+ // would let e.g. `sources webhook set x --help` fall through to
+ // runWebhookSet, the same destructive-dispatch class this guard exists
+ // to prevent for the rest of sources' subcommands.
+ if (sub === 'webhook') {
+ console.log(SOURCES_WEBHOOK_HELP);
+ return;
+ }
+ printHelp();
+ return;
+ }
+
switch (sub) {
case 'add': return runAdd(engine, rest);
case 'list': return runList(engine, rest);
@@ -1552,11 +1586,8 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
// agent-bootstrap: scan-gated workspace push
case 'push': return runPush(engine, rest);
case 'unharden': { const { runUnharden } = await import('./sources-harden.ts'); return runUnharden(engine, rest); }
- case undefined:
- case '--help':
- case '-h':
- printHelp();
- return;
+ // undefined / --help / -h are handled by the guards above, before this
+ // switch is ever reached — no case needed here.
default:
console.error(`Unknown sources subcommand: ${sub}`);
printHelp();
@@ -1604,6 +1635,9 @@ Subcommands:
override (v0.40.3.0). Pass "unset" or
"default" to clear (NULL falls through
to the global search.mode bundle).
+ webhook <set|show|rotate|clear> <id> [options]
+ v0.40 — per-source webhook secret management.
+ Run 'sources webhook --help' for subcommand detail.
harden <id|--all> [--pat-file <p>] [--branch <b>] [--no-cron] [--no-verify] [--dry-run] [--json]
v0.42.44 — make a brain repo durable: local
auto-push hook, committed commit-push helper,
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 753425406a..a7924b7131 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -67,13 +67,41 @@ interface IngestCliOpts {
source?: string;
facts?: boolean;
maxCostUsd?: number;
+ /** gbrain#4149: explicit per-format byte-cap override; undefined = adapter-native defaults. */
+ maxBytes?: number;
embed?: boolean;
all?: boolean;
json?: boolean;
quiet?: boolean;
}
-function parseIngestArgs(args: string[]): IngestCliOpts | { help: true } | { error: string } {
+/**
+ * gbrain#4149: the checkpoint fingerprint input, extracted so the cap
+ * dimension is unit-testable — a `--since last` watermark written under one
+ * cap must never be reused under another (or the auto defaults).
+ */
+export function ingestCheckpointFingerprintInput(args: {
+ sourceId: string;
+ pathspec: string | string[];
+ format: string;
+ version: string | number;
+ maxBytes?: number;
+}): Record<string, string | number | string[]> {
+ return {
+ sourceId: args.sourceId,
+ pathspec: args.pathspec,
+ format: args.format,
+ version: args.version,
+ // Key present ONLY for an explicit cap (review finding, multi-specialist
+ // confirmed): an unconditional `maxBytes: 'auto'` would re-hash EVERY
+ // pre-existing watermark at upgrade and silently force a one-time full
+ // rescan. Omitting the key keeps the default path on the legacy
+ // fingerprint; every explicit cap still gets its own scope.
+ ...(args.maxBytes != null ? { maxBytes: args.maxBytes } : {}),
+ };
+}
+
+export function parseIngestArgs(args: string[]): IngestCliOpts | { help: true } | { error: string } {
const opts: IngestCliOpts = { paths: [] };
for (let i = 0; i < args.length; i++) {
const a = args[i];
@@ -128,6 +156,20 @@ function parseIngestArgs(args: string[]): IngestCliOpts | { help: true } | { err
opts.maxCostUsd = n;
continue;
}
+ if (a === '--max-bytes') {
+ // gbrain#4149: optional VALIDATED override for the per-format byte
+ // caps (e.g. the Hermes store guard). Omission preserves each
+ // adapter's native default — one global cap must not replace
+ // format-specific safety limits. Accepts plain bytes or kb/mb/gb.
+ const raw = (args[++i] ?? '').toLowerCase();
+ const m = raw.match(/^(\d+(?:\.\d+)?)(kb|mb|gb)?$/);
+ if (!m) return { error: `max-bytes must be a positive size like 800000000, 512mb, or 4gb (got '${raw || ''}')` };
+ const mult = m[2] === 'kb' ? 1024 : m[2] === 'mb' ? 1024 ** 2 : m[2] === 'gb' ? 1024 ** 3 : 1;
+ const n = Math.floor(parseFloat(m[1]) * mult);
+ if (!Number.isFinite(n) || n <= 0) return { error: 'max-bytes must resolve to a positive byte count' };
+ opts.maxBytes = n;
+ continue;
+ }
if (a.startsWith('-')) return { error: `unknown flag ${a}` };
opts.paths.push(a);
}
@@ -158,6 +200,11 @@ skip). Embedding is OFF by default; run the embed backfill later or opt in.
--embed Embed pages at import (default: defer to embed backfill)
--facts Extract facts from imported pages (budget-capped)
--max-cost-usd F Facts budget cap (default 5)
+ --max-bytes N Override the per-format file/store byte caps (e.g. 4gb
+ for a multi-GB hermes store). Omit to keep each
+ format's native safety default. Changing it starts a
+ fresh --since last scope (caps are part of the
+ checkpoint fingerprint)
--json Machine-readable result
--quiet Suppress the human summary
@@ -347,12 +394,18 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {
const { TRANSCRIPT_IMPORT_VERSION } = await import('../core/transcripts/render.ts');
const checkpointKey = {
op: 'transcripts-ingest',
- fingerprint: fingerprint({
+ // gbrain#4149: the effective cap is part of scan coverage — a checkpoint
+ // written under a different cap (or the auto defaults) must not be
+ // silently reused, or a capped run's skipped tail reads as
+ // already-imported. The input builder distinguishes 'auto' from every
+ // explicit value.
+ fingerprint: fingerprint(ingestCheckpointFingerprintInput({
sourceId,
pathspec: checkpointSpec,
format: parsed.format ?? 'auto',
version: TRANSCRIPT_IMPORT_VERSION,
- }),
+ maxBytes: parsed.maxBytes,
+ })),
};
let sinceIso = parsed.since;
if (parsed.since === 'last') {
@@ -383,6 +436,7 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {
limit: parsed.limit,
sinceIso,
sourceId,
+ maxBytes: parsed.maxBytes,
embed: parsed.embed,
activePack,
onFileDone: () => reporter.tick(),
diff --git a/src/core/ai/capabilities.ts b/src/core/ai/capabilities.ts
index 535d23b9d4..7906bfc0c8 100644
--- a/src/core/ai/capabilities.ts
+++ b/src/core/ai/capabilities.ts
@@ -101,10 +101,12 @@ export function getProviderCapabilities(modelString: string): ProviderCapabiliti
// Subsequent waves can split this into its own recipe field if a provider
// ever supports tools without parallel dispatch.
supportsParallelTools: chat.supports_tools === true,
- // Not exposed by ChatTouchpoint today — defaults to false. Recipes can add
- // a `supports_thinking` field later without breaking this helper (it'll
- // just keep returning false until a recipe sets it).
- supportsThinking: false,
+ // Recipe-declared thinking-by-default (gbrain#4172): true when the model
+ // reasons without being asked and bills that reasoning as output tokens.
+ // Boolean or per-model predicate, mirroring supports_prompt_cache.
+ supportsThinking: typeof chat.thinking_by_default === 'function'
+ ? chat.thinking_by_default(parsed.modelId)
+ : chat.thinking_by_default === true,
maxContext: chat.max_context_tokens ?? 128_000,
};
}
diff --git a/src/core/ai/dims.ts b/src/core/ai/dims.ts
index adeaddd316..0d17b86b8e 100644
--- a/src/core/ai/dims.ts
+++ b/src/core/ai/dims.ts
@@ -288,7 +288,11 @@ export function dimsProviderOptions(
// configured for a smaller width (e.g. 1536) hard-fail at first embed.
// Azure/OpenAI-compat embeddings are symmetric — inputType ignored.
// v0.36.0.0 (D13): same range validation as native-openai path.
- const bareModelId = modelId.includes('/') ? modelId.split('/').pop()! : modelId;
+ // Lowercased for matching only — providers' model ids are case-sensitive
+ // (SiliconFlow serves `Qwen/Qwen3-Embedding-4B` and 500s on the
+ // lowercase form), so the ORIGINAL id goes on the wire while every
+ // literal compared here is already lowercase (gbrain#4123).
+ const bareModelId = (modelId.includes('/') ? modelId.split('/').pop()! : modelId).toLowerCase();
if (bareModelId.startsWith('text-embedding-3')) {
if (isOpenAITextEmbedding3Model(bareModelId) && !isValidOpenAITextEmbedding3Dim(bareModelId, dims)) {
const max = maxOpenAITextEmbedding3Dim(bareModelId)!;
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 4edaadc889..1dc2da3372 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -46,7 +46,7 @@ import type {
Recipe,
TouchpointKind,
} from './types.ts';
-import { resolveRecipe, assertTouchpoint, parseModelId } from './model-resolver.ts';
+import { resolveRecipe, assertTouchpoint, parseModelId, embeddingDimsForModel } from './model-resolver.ts';
import {
OPENROUTER_CACHE_HEADER,
openrouterRequiresExplicitPromptCache,
@@ -164,6 +164,11 @@ type EmbedManyFn = typeof embedMany;
let _embedTransport: EmbedManyFn = embedMany;
type GenerateTextFn = typeof generateText;
let _generateTextTransport: GenerateTextFn = generateText;
+// Test-only seam for expand()'s structured-output SDK call. Mirrors
+// _generateTextTransport (see __setGenerateObjectTransportForTests). Never
+// swapped in production — expand() always calls the real generateObject.
+type GenerateObjectFn = typeof generateObject;
+let _generateObjectTransport: GenerateObjectFn = generateObject;
// v0.41.6.0 D1: tests that install a transport stub also pass the
// embedding-creds preflight, matching the chat-transport fast-path
// pattern. Set when __setEmbedTransportForTests is called with a
@@ -619,6 +624,7 @@ function clearGatewayState(): void {
_shrinkState.clear();
_embedTransport = embedMany;
_generateTextTransport = generateText;
+ _generateObjectTransport = generateObject;
_embedTransportInstalled = false;
_chatTransport = null;
_warnedRecipes.clear();
@@ -676,6 +682,17 @@ export function __setGenerateTextTransportForTests(fn: GenerateTextFn | null): v
_generateTextTransport = fn ?? generateText;
}
+/**
+ * Test-only seam for expand()'s generateObject call (the structured-output
+ * path used for native providers and openai-compatible recipes that declare
+ * supportsStructuredOutputs). Same shape as __setGenerateTextTransportForTests.
+ *
+ * @internal exported for tests; not part of the public gateway API.
+ */
+export function __setGenerateObjectTransportForTests(fn: GenerateObjectFn | null): void {
+ _generateObjectTransport = fn ?? generateObject;
+}
+
/**
* Test-only seam mirroring `__setEmbedTransportForTests`. When set,
* `chat()` skips provider resolution and SDK invocation and calls the
@@ -831,8 +848,12 @@ export function diagnoseEmbedding(modelOverride?: string): EmbeddingDiagnosis {
// search. The genuine "picked a user-provided provider but no model" UX is
// handled at the config/init layer, where a bare provider string still exists.
const isUserProvided = (tp as any).user_provided_models === true;
- const recipeDefaultDims = tp.default_dims ?? 0;
- if ((isUserProvided || recipeDefaultDims === 0) && !_config!.embedding_dimensions) {
+ // Consult the per-model map, not just the recipe-wide default: a recipe
+ // with default_dims:0 (openrouter, #4114) still KNOWS the width of its
+ // listed models via model_dims, so those must not fail preflight when
+ // embedding_dimensions is unset — only genuinely unknown ids do.
+ const recipeDeclaredDims = embeddingDimsForModel(recipe, parsed.modelId);
+ if ((isUserProvided || recipeDeclaredDims === 0) && !_config!.embedding_dimensions) {
return {
ok: false,
reason: 'user_provided_dims_unset',
@@ -2202,13 +2223,14 @@ async function embedMultimodalOpenAICompat(
);
}
- // D12 — dim validation. Prefer recipe's declared default_dims when set;
- // fall back to the brain's configured embedding_dimensions. If neither
- // is known (LiteLLM recipe with default_dims=0 and no config override),
- // we skip the dim check rather than fabricate an expected value — the
- // engine's vector(N) column will reject mismatched rows at INSERT time
- // with a clearer error than anything we could throw here.
- const recipeDims = recipe.touchpoints.embedding?.default_dims ?? 0;
+ // D12 — dim validation. Prefer the recipe's declared dims for THIS model
+ // (per-model model_dims first, then default_dims — #4114); fall back to
+ // the brain's configured embedding_dimensions. If neither is known
+ // (LiteLLM recipe with default_dims=0 and no config override), we skip
+ // the dim check rather than fabricate an expected value — the engine's
+ // vector(N) column will reject mismatched rows at INSERT time with a
+ // clearer error than anything we could throw here.
+ const recipeDims = embeddingDimsForModel(recipe, modelId);
const expectedDims = recipeDims > 0
? recipeDims
: (cfg.embedding_dimensions ?? 0);
@@ -2531,8 +2553,34 @@ export async function expand(query: string): Promise<string[]> {
`Query: ${query}`,
].join('\n');
+ // #4121: expand() calls generateObject/generateText directly and never
+ // goes through chat()'s _recordBudget closure, so every expansion LLM
+ // call was invisible to BudgetTracker — spend happened but was never
+ // recorded, even inside a withBudgetTracker() scope. Resolve the ambient
+ // tracker once and record on every SUCCESSFUL call site below. Fail-open
+ // (no tracker → no-op) and swallow BudgetExhausted the same way chat()'s
+ // _recordBudget does — TX1 surfaces on the NEXT reserve(), not here.
+ const tracker = getCurrentBudgetTracker();
+ const recordExpansionUsage = (
+ modelLabel: string,
+ usage: { inputTokens?: number; outputTokens?: number } | undefined,
+ ): void => {
+ if (!tracker) return;
+ try {
+ tracker.record({
+ modelId: modelLabel,
+ inputTokens: Number(usage?.inputTokens ?? 0),
+ outputTokens: Number(usage?.outputTokens ?? 0),
+ label: 'gateway.expand',
+ });
+ } catch {
+ // BudgetExhausted (TX1) raised here; surfaced via the next reserve().
+ }
+ };
+
try {
const { model, recipe, modelId } = await resolveExpansionProvider(getExpansionModel());
+ const modelLabel = `${recipe.id}:${modelId}`;
let expansions: string[];
@@ -2541,35 +2589,38 @@ export async function expand(query: string): Promise<string[]> {
// there, so generateObject would warn and silently degrade. generateText + a
// tolerant parse recovers the queries instead. Fresh abortSignal per call.
const viaText = async (): Promise<string[]> => {
- const { text } = await generateText({
+ const { text, usage } = await _generateTextTransport({
model,
abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),
prompt: expansionPrompt,
});
+ recordExpansionUsage(modelLabel, usage);
return parseExpansionResponse(text) ?? [];
};
if (recipe.implementation !== 'openai-compatible') {
// Native providers (Anthropic, OpenAI, Google) support generateObject's
// structured output natively — unchanged path.
- const result = await generateObject({
+ const result = await _generateObjectTransport({
model,
schema: ExpansionSchema,
abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),
prompt: expansionPrompt,
});
+ recordExpansionUsage(modelLabel, result.usage);
expansions = result.object?.queries ?? [];
} else if (recipeSupportsStructuredOutputs(recipe)) {
// openai-compatible backend that honors strict json_schema: request the
// schema (strict validation), and fall back to the text path if it is
// rejected at call time so a mis-declared capability never drops expansion.
try {
- const result = await generateObject({
+ const result = await _generateObjectTransport({
model,
schema: ExpansionSchema,
abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),
prompt: expansionPrompt,
});
+ recordExpansionUsage(modelLabel, result.usage);
expansions = result.object?.queries ?? [];
} catch {
expansions = await viaText();
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 4ffaec0af4..00cdcf6e21 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -219,10 +219,24 @@ function runClaude(
// (subscription), never via an inherited API key. Without this, an
// ANTHROPIC_API_KEY in gbrain's env (the exact setup this recipe is meant
// to replace) silently flips billing to per-token API usage.
+ //
+ // Also scrub the CLAUDE_CODE_USE_* backend-switch flags: Bedrock, Vertex
+ // AI, Mantle, Microsoft Foundry, and Claude Platform on AWS are each
+ // gated by one of these, take priority over subscription OAuth when set,
+ // and route billing through a cloud account instead. Clearing the switch
+ // is sufficient — provider-specific creds (AWS_*, ANTHROPIC_VERTEX_*,
+ // ANTHROPIC_FOUNDRY_*, ANTHROPIC_AWS_*, ...) are inert without it.
const env = { ...process.env };
delete env.ANTHROPIC_API_KEY;
delete env.ANTHROPIC_AUTH_TOKEN;
delete env.ANTHROPIC_BASE_URL;
+ // Prefix wipe, not a denylist (review hardening): the backend-switch
+ // family grows one CLAUDE_CODE_USE_* flag per new cloud backend, and any
+ // future switch inherited from gbrain's env would silently re-route the
+ // child's billing. Subscription-only is the recipe's contract.
+ for (const k of Object.keys(env)) {
+ if (k.startsWith('CLAUDE_CODE_USE_')) delete env[k];
+ }
const child = spawn(claudeBin(), args, {
stdio: ['pipe', 'pipe', 'pipe'],
cwd: ensureCleanCwd(),
@@ -392,7 +406,12 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
async doGenerate(options: LanguageModelV2CallOptions): Promise<{
content: LanguageModelV2Content[];
finishReason: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown';
- usage: { inputTokens: number | undefined; outputTokens: number | undefined; totalTokens: number | undefined };
+ usage: {
+ inputTokens: number | undefined;
+ outputTokens: number | undefined;
+ totalTokens: number | undefined;
+ cachedInputTokens: number | undefined;
+ };
warnings: never[];
}> {
const { systemText, userPrompt } = renderPrompt(options.prompt);
@@ -422,6 +441,14 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
const inputTokens = result.usage?.input_tokens;
const outputTokens = result.usage?.output_tokens;
const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);
+ // `cache_creation_input_tokens` is deliberately NOT surfaced here — the AI
+ // SDK's LanguageModelV2Usage has no corresponding field, and folding it in
+ // would need a claude-cli-specific branch in the gateway's usage assembly
+ // (src/core/ai/gateway.ts). Out of scope for this fix.
+ const cachedInputTokens =
+ result.usage?.cache_read_input_tokens !== undefined
+ ? Number(result.usage.cache_read_input_tokens)
+ : undefined;
return {
content,
@@ -430,6 +457,7 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
inputTokens,
outputTokens,
totalTokens: inputTokens !== undefined && outputTokens !== undefined ? totalTokens : undefined,
+ cachedInputTokens,
},
warnings: [],
};
diff --git a/src/core/ai/recipes/claude-cli.ts b/src/core/ai/recipes/claude-cli.ts
index bb1a5db8c2..eb60e1f1c7 100644
--- a/src/core/ai/recipes/claude-cli.ts
+++ b/src/core/ai/recipes/claude-cli.ts
@@ -57,6 +57,15 @@ export const claudeCli: Recipe = {
cost_per_1m_input_usd: 3.0,
cost_per_1m_output_usd: 15.0,
price_last_verified: '2026-06-17',
+ // The gateway dispatches via a `claude -p (print mode)` subprocess (CLI cold
+ // start + user-level CLAUDE.md load), which routinely takes 5-6s even
+ // when the CLI and subscription are perfectly healthy. `gbrain models
+ // doctor`'s chat probe used to hardcode a flat 5000ms abort, so this
+ // recipe always false-failed the doctor check ('unknown — claude-cli
+ // adapter aborted') despite `chat()` succeeding fine at normal call
+ // sites. 30s gives the subprocess room to start without masking a truly
+ // dead/unauthenticated CLI for anywhere near that long.
+ default_timeout_ms: 30_000,
},
},
// Friendly aliases mirror the `anthropic` recipe so config strings stay
diff --git a/src/core/ai/recipes/deepseek.ts b/src/core/ai/recipes/deepseek.ts
index 5a70392fd6..888649fc85 100644
--- a/src/core/ai/recipes/deepseek.ts
+++ b/src/core/ai/recipes/deepseek.ts
@@ -96,6 +96,10 @@ export const deepseek: Recipe = {
supports_tools: true,
supports_subagent_loop: true,
supports_prompt_cache: false,
+ // Thinking mode is DEFAULT ON for both v4 models (see module docstring):
+ // reasoning bills as output and counts against max_tokens, so callers
+ // that size output caps must grant reasoning headroom (gbrain#4172).
+ thinking_by_default: true,
max_context_tokens: 1_000_000,
cost_per_1m_input_usd: 0.14, // deepseek-v4-flash cache-miss baseline
cost_per_1m_output_usd: 0.28,
diff --git a/src/core/ai/recipes/google.ts b/src/core/ai/recipes/google.ts
index 4f66fa9de3..3836ee5be8 100644
--- a/src/core/ai/recipes/google.ts
+++ b/src/core/ai/recipes/google.ts
@@ -1,5 +1,35 @@
import type { Recipe } from '../types.ts';
+/**
+ * Version-scoped prompt-cache capability.
+ *
+ * Gemini's *implicit* caching is the only kind that applies here: the gateway
+ * sends no cache directives on the Google path, and the explicit CachedContent
+ * API is never called. Implicit caching is on by default for Gemini 2.5 and
+ * newer, so those ids cache (and bill cached input at a discount) with no
+ * request mutation; 1.5 and 2.0 cache only through the explicit API and stay
+ * false. Ids this recipe can also serve but that never cache (Gemma) are out.
+ *
+ * The version digits sit in different positions across ids (`gemini-2.5-pro`,
+ * `gemini-3-flash-preview`, `gemini-3.6-flash`), so match the first numeric
+ * token rather than a fixed segment. A VERSIONED `-latest` alias
+ * (`gemini-1.5-pro-latest`) is judged by its version — 1.5 aliases cache only
+ * via the explicit API and must stay false. Only an UNVERSIONED `-latest`
+ * alias (no digits to judge by) passes on the alias alone, since it resolves
+ * to a current-generation model. Any other unversioned id reads false: a
+ * wrong `true` silently promises a discount the provider never applies.
+ */
+export function googleSupportsPromptCache(modelId: string): boolean {
+ const normalized = modelId.trim().toLowerCase();
+ if (!normalized.startsWith('gemini-')) return false;
+ // Version tokens are 1-2 digits (2, 2.5, 3, 3.6, 10…); a longer numeric run
+ // is a DATE/experiment suffix, not a version — `gemini-exp-1206` must not
+ // parse as version 1206 and read as caching (review hardening on #4159).
+ const version = normalized.match(/(?<!\d)\d{1,2}(?:\.\d+)?(?!\d)/);
+ if (version !== null) return Number.parseFloat(version[0]) >= 2.5;
+ return normalized.endsWith('-latest');
+}
+
export const google: Recipe = {
id: 'google',
name: 'Google Gemini',
@@ -40,7 +70,11 @@ export const google: Recipe = {
models: ['gemini-2.0-flash-exp', 'gemini-2.0-flash'],
supports_tools: true,
supports_subagent_loop: true,
- supports_prompt_cache: false,
+ // Per-model: implicit caching is a 2.5+ capability, and this recipe
+ // accepts off-list ids (the config plane does not pin model ids to the
+ // list above), so a recipe-wide boolean mislabels whichever side it
+ // picks.
+ supports_prompt_cache: googleSupportsPromptCache,
max_context_tokens: 1000000, // Gemini 2.0 Flash
cost_per_1m_input_usd: 0.30,
cost_per_1m_output_usd: 1.20,
diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.ts
index 221041727b..f6b44bf75b 100644
--- a/src/core/ai/recipes/openrouter.ts
+++ b/src/core/ai/recipes/openrouter.ts
@@ -168,7 +168,26 @@ export const openrouter: Recipe = {
touchpoints: {
embedding: {
models: ['openai/text-embedding-3-small'],
- default_dims: 1536,
+ // #4114: per-model native dims for the catalog the docs invite users to
+ // pick. The old recipe-wide `default_dims: 1536` was only right for
+ // text-embedding-3-small — `migrate embeddings --to openrouter:bge-m3`
+ // planned a 1536-wide column for a model that returns 1024. Slash-form
+ // ids are the lookup key (embeddingDimsForModel strips only a leading
+ // `provider:`, never the org slash). gemini-embedding-2-preview is
+ // deliberately NOT listed: its width is unverified, and a plausible
+ // guess is this exact bug class — unlisted ids resolve to 0, which
+ // forces an explicit --dim / embedding_dimensions with a clear error.
+ model_dims: {
+ 'openai/text-embedding-3-small': 1536,
+ 'openai/text-embedding-3-large': 3072,
+ 'qwen/qwen3-embedding-8b': 4096,
+ 'bge-m3': 1024,
+ 'baai/bge-m3': 1024,
+ },
+ // OpenRouter proxies arbitrary embedding models with widths we cannot
+ // know ahead of time; 0 = no silent default for unlisted ids.
+ default_dims: 0,
+ trust_custom_dims: true,
// text-embedding-3-small was trained at MRL breakpoints 512/1024/1536
// (Weaviate analysis); 768 is a practical intermediate. Users opt into
// a smaller dim via `gbrain config set embedding_dimensions <N>`.
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 7d825fa010..d7f134395a 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -202,6 +202,14 @@ export interface ExpansionTouchpoint {
models: string[];
cost_per_1m_tokens_usd?: number;
price_last_verified?: string;
+ /**
+ * Recipe-level timeout fallback for `gbrain models doctor`'s expansion
+ * reachability probe. Mirrors `RerankerTouchpoint.default_timeout_ms`: lets
+ * a slow-start provider (e.g. a subprocess-dispatched CLI with real cold-start
+ * latency) declare the headroom it needs instead of the probe's flat 5000ms
+ * default false-failing on every run.
+ */
+ default_timeout_ms?: number;
}
/**
@@ -274,6 +282,17 @@ export interface ChatTouchpoint {
* model family).
*/
supports_prompt_cache?: boolean | ((modelId: string) => boolean);
+ /**
+ * Model reasons/thinks BY DEFAULT, spending output-token budget on internal
+ * reasoning before any answer text (DeepSeek v4's thinking mode bills
+ * reasoning as output and counts it against `max_tokens`). Consumers that
+ * size output caps (e.g. `think`'s `maxOutputTokensFor`) grant these models
+ * the same headroom as thinking-by-default Claude 5 / OpenAI reasoning
+ * models. Boolean for recipe-wide behavior; predicate when only some routed
+ * model ids think by default. Distinct from "can be asked to think" —
+ * default-off reasoning modes should NOT set this (gbrain#4172).
+ */
+ thinking_by_default?: boolean | ((modelId: string) => boolean);
/**
* Backend honors OpenAI structured outputs (a strict `json_schema`
* response_format). Threaded into `createOpenAICompatible`'s
@@ -289,6 +308,14 @@ export interface ChatTouchpoint {
cost_per_1m_input_usd?: number;
cost_per_1m_output_usd?: number;
price_last_verified?: string;
+ /**
+ * Recipe-level timeout fallback for `gbrain models doctor`'s chat
+ * reachability probe. Mirrors `RerankerTouchpoint.default_timeout_ms`: lets
+ * a slow-start provider (e.g. a subprocess-dispatched CLI with real cold-start
+ * latency) declare the headroom it needs instead of the probe's flat 5000ms
+ * default false-failing on every run.
+ */
+ default_timeout_ms?: number;
}
export interface Recipe {
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index b2dbc4949b..b8bcdbe804 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -464,6 +464,7 @@ export function detectCodeLanguage(filePath: string, content?: string): Supporte
if (lower.endsWith('.sh') || lower.endsWith('.bash')) return 'bash';
if (lower.endsWith('.css')) return 'css';
if (lower.endsWith('.html') || lower.endsWith('.htm')) return 'html';
+ if (lower.endsWith('.astro') || lower.endsWith('.svelte')) return 'html';
if (lower.endsWith('.vue')) return 'vue';
if (lower.endsWith('.json')) return 'json';
if (lower.endsWith('.yaml') || lower.endsWith('.yml')) return 'yaml';
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 73ff779a0a..712b084095 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -108,7 +108,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'sync': ['--abbrev-ref', '--abi', '--abort', '--aliases', '--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', '--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', '--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-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', '--pattern', '--pending', '--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', '--resolve', '--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', '--status', '--stdin', '--strategy', '--supabase', '--supersessions', '--surface', '--target', '--target-score', '--thin', '--timeout', '--to', '--token-ttl', '--top-k', '--type', '--url', '--url-managed', '--verbose', '--verify', '--watch', '--window', '--workers', '--yes'],
'takes': ['--aliases', '--all', '--brain', '--bucket-size', '--by', '--claim', '--dir', '--domain', '--dry-run', '--evidence', '--expired', '--fast', '--federated', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--include-null-signature', '--json', '--kind', '--limit', '--max-pages', '--no-embedding', '--no-extract', '--no-federated', '--outcome', '--path', '--pattern', '--pending', '--quality', '--repo', '--reset', '--resolve', '--restore-only', '--row', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--supersessions', '--surface', '--thin', '--token-ttl', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--aliases', '--all', '--anchor', '--brain', '--calibration-holder', '--explain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-usd', '--mcp-only', '--model', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--rounds', '--save', '--since', '--source', '--stale', '--supersessions', '--surface', '--take', '--thin', '--timeout', '--token-ttl', '--until', '--with-calibration'],
- 'transcripts': ['--aliases', '--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', '--include-null-signature', '--json', '--limit', '--markdown', '--max-cost-usd', '--no-embedding', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
+ 'transcripts': ['--aliases', '--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', '--include-null-signature', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--supersessions', '--surface', '--thin', '--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', '--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': ['--aliases', '--all', '--brain', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--token-ttl', '--window-turns'],
'whoknows': ['--aliases', '--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', '--include-null-signature', '--json', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reset', '--resolve', '--restore-only', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
diff --git a/src/core/conversation-parser/builtins.ts b/src/core/conversation-parser/builtins.ts
index d23721ee41..7c19f0df1a 100644
--- a/src/core/conversation-parser/builtins.ts
+++ b/src/core/conversation-parser/builtins.ts
@@ -74,7 +74,13 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [
date_source: 'inline',
time_format: '12h_ampm',
timezone_policy: 'inline_utc',
- multi_line: false,
+ // Transcript imports preserve embedded newlines in each turn. Treat
+ // non-anchor lines as message continuations when scoring so a small
+ // number of long coding turns does not fall below the global 5% density
+ // floor and become unparseable. The continuation-aware scorer still
+ // requires an anchor on the first line or at least two valid anchors.
+ multi_line: true,
+ score_continuations_as_body: true,
quick_reject: /^\*\*/,
test_positive: [
'**Alice Example** (2024-03-15 9:00 AM): hello',
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 808357c90b..87017c72c4 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -604,6 +604,26 @@ export function cycleLockIdFor(sourceId?: string): string {
return `${LEGACY_CYCLE_LOCK_ID}:${sourceId}`;
}
+/**
+ * Non-throwing companion to `cycleLockIdFor`, for LOG LABELS only (the
+ * LockStolenError messages + the steal abort log line in runCycle).
+ *
+ * runCycle needs the label on paths that never validate `opts.sourceId`:
+ * lock-free phase selections acquire no lock at all (e.g.
+ * `gbrain dream --phase orphans --source __all__` — the `__all__` sentinel
+ * deliberately fails strict validation), and the engine-null file-lock path
+ * never routes the sourceId through `acquireDbCycleLock`. Throwing there
+ * would crash a run that never needed a lock id. NEVER use this for an
+ * actual lock acquisition — `cycleLockIdFor`'s throw IS the defense there.
+ */
+function cycleLockIdLabelFor(sourceId?: string): string {
+ try {
+ return cycleLockIdFor(sourceId);
+ } catch {
+ return `${LEGACY_CYCLE_LOCK_ID}:${String(sourceId)}`;
+ }
+}
+
/**
* Acquire the DB-backed cycle lock for a given source.
*
@@ -871,6 +891,41 @@ function resolveCycleLockRefreshMs(): number {
return CYCLE_LOCK_REFRESH_INTERVAL_MS;
}
+/**
+ * Did runCycle's private steal controller fire, and is this a steal rather than
+ * an external abort?
+ *
+ * Keyed on the ABORTED FLAG, not on `reason instanceof LockStolenError`. The
+ * `stolen` controller never leaves runCycle: the only two things that can abort
+ * it are startCycleLockRefresher (which passes `new LockStolenError(lockId)`)
+ * and the `onStolen` callback (typed to take a LockStolenError). So its aborted
+ * flag IS the steal signal, and re-deriving that answer from the reason only
+ * adds a way to get it wrong.
+ *
+ * It does get it wrong: the runtime can deliver `aborted === true` with
+ * `reason === undefined` when abort() runs in a microtask continuation
+ * scheduled from a timer callback — exactly startCycleLockRefresher's shape.
+ * Gating on the reason then INVERTS this branch, so a real steal rethrows
+ * instead of reporting the structured `lock_stolen` partial that exists to
+ * spare daemon callers that classification.
+ *
+ * The external-abort conjunct is preserved: a caller-initiated abort keeps the
+ * throw-out contract even if a steal races it.
+ *
+ * Takes minimal structural types rather than AbortSignal so it stays callable
+ * with the duck-typed stubs this file already documents (see anyAbortSignal)
+ * — and so the reason-dropped case is reachable in a test at all, since
+ * `abort()` / `abort(undefined)` both yield a DOMException, never `undefined`.
+ */
+export function isLockStolenAbort(
+ stolen: { aborted: boolean; reason?: unknown } | undefined,
+ external: { aborted: boolean } | undefined,
+): boolean {
+ if (stolen?.aborted !== true) return false;
+ if (external?.aborted === true) return false;
+ return true;
+}
+
// ─── Helpers ───────────────────────────────────────────────────────
function makeErrorFromException(e: unknown, fallbackClass = 'InternalError'): PhaseError {
@@ -1560,7 +1615,10 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas
};
}
const { purgeExpiredSources } = await import('./destructive-guard.ts');
- const purgedSources = await purgeExpiredSources(engine);
+ // gbrain#4115: {purged, blocked} — a RESTRICT-FK-held source (revoked
+ // oauth_client, v64) is reported and skipped instead of aborting the sweep.
+ const purgeResult = await purgeExpiredSources(engine);
+ const purgedSources = purgeResult.purged;
const purgedPages = await engine.purgeDeletedPages(SOFT_DELETE_TTL_HOURS_FOR_PURGE);
const purgedClones = await purgeOrphanClones(SOFT_DELETE_TTL_HOURS_FOR_PURGE);
// v0.36+ folded scope item +C: GC stale op_checkpoints rows.
@@ -1609,13 +1667,16 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas
status: 'ok',
duration_ms: 0,
summary:
- `purged ${purgedSources.length} source(s), ${purgedPages.count} page(s), ` +
+ `purged ${purgedSources.length} source(s)` +
+ (purgeResult.blocked.length > 0 ? ` (${purgeResult.blocked.length} FK-blocked, see details)` : '') +
+ `, ${purgedPages.count} page(s), ` +
`${purgedClones.count} orphan clone temp dir(s), ${purgedCheckpoints} stale op_checkpoint(s), ` +
`${purgedBrainstormCheckpoints} stale brainstorm checkpoint(s), ` +
`${purgedBatchRetryAuditFiles} stale batch-retry audit file(s), ` +
`and ${purgedVolunteerEvents} stale volunteer event(s)`,
details: {
purged_sources_count: purgedSources.length,
+ purged_sources_blocked: purgeResult.blocked,
purged_pages_count: purgedPages.count,
purged_orphan_clones_count: purgedClones.count,
purged_orphan_clone_names: purgedClones.names,
@@ -1896,17 +1957,26 @@ export async function runCycle(
const cycleSignal: AbortSignal | undefined = combinedSignal
? combinedSignal.signal
: (stolen?.signal ?? externalSignal);
+ // Label only — the non-throwing variant, because this line runs even for
+ // lock-free phase selections where opts.sourceId was never validated (a
+ // `cycleLockIdFor` throw here crashed `--source __all__` runs that never
+ // needed a lock id). Real acquisition validated above via acquireDbCycleLock.
+ const cycleLockId = cycleLockIdLabelFor(opts.sourceId);
const stopRefresher: (() => void) | undefined = lock && stolen
- ? startCycleLockRefresher(lock, stolen, cycleLockIdFor(opts.sourceId))
+ ? startCycleLockRefresher(lock, stolen, cycleLockId)
: undefined;
const onStolen = stolen ? (e: LockStolenError) => { if (!stolen.signal.aborted) stolen.abort(e); } : undefined;
+ // The reason can arrive as undefined (see isLockStolenAbort); rejecting a
+ // raced phase with `undefined` would hand the outer catch a valueless throw.
+ const stolenReason = () =>
+ (stolen!.signal.reason as unknown) ?? new LockStolenError(cycleLockId);
const raceStolen = !stolen
? <T,>(p: Promise<T>): Promise<T> => p
: <T,>(p: Promise<T>): Promise<T> => {
- if (stolen.signal.aborted) return Promise.reject(stolen.signal.reason);
+ if (stolen.signal.aborted) return Promise.reject(stolenReason());
let onAbort!: () => void;
const abortP = new Promise<never>((_, rej) => {
- onAbort = () => rej(stolen.signal.reason);
+ onAbort = () => rej(stolenReason());
stolen.signal.addEventListener('abort', onAbort, { once: true });
});
return Promise.race([p, abortP]).finally(() => {
@@ -2412,7 +2482,9 @@ export async function runCycle(
checkAborted(cycleSignal);
progress.start('cycle.propose_takes');
const { runPhaseProposeTakes } = await import('./cycle/propose-takes.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined }) as Promise<PhaseResult>);
+ // gbrain#4168: thread the job's absolute deadline so the phase's
+ // clean partial-exit fires before the worker's kill switch.
+ const { result, duration_ms } = await timePhase(() => runPhaseProposeTakes(calibrationCtx, { repoPath: brainDir ?? undefined, deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2423,7 +2495,7 @@ export async function runCycle(
checkAborted(cycleSignal);
progress.start('cycle.grade_takes');
const { runPhaseGradeTakes } = await import('./cycle/grade-takes.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, {}) as Promise<PhaseResult>);
+ const { result, duration_ms } = await timePhase(() => runPhaseGradeTakes(calibrationCtx, { deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2434,7 +2506,7 @@ export async function runCycle(
checkAborted(cycleSignal);
progress.start('cycle.calibration_profile');
const { runPhaseCalibrationProfile } = await import('./cycle/calibration-profile.ts');
- const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, {}) as Promise<PhaseResult>);
+ const { result, duration_ms } = await timePhase(() => runPhaseCalibrationProfile(calibrationCtx, { deadlineAtMs: opts.deadlineAtMs ?? null }) as Promise<PhaseResult>);
result.duration_ms = duration_ms;
phaseResults.push(result);
progress.finish();
@@ -2714,12 +2786,15 @@ export async function runCycle(
// per D5.6); report a structured partial instead of throwing so daemon
// callers (jobs.ts / autopilot) don't have to classify an exception.
// External aborts (cycleSignal) keep the existing throw-out contract.
- const stolenFired = stolen?.signal.aborted === true
- && stolen.signal.reason instanceof LockStolenError
- && externalSignal?.aborted !== true;
+ const stolenFired = isLockStolenAbort(stolen?.signal, externalSignal);
if (stolenFired) {
lockStolenAbort = true;
- console.error(`[cycle] aborting: ${stolen!.signal.reason.message} — ${phaseResults.length} phase(s) completed before the steal; their writes are durable`);
+ // The reason is the better message when it survived; it is not always
+ // there (see isLockStolenAbort), so never dereference it unguarded.
+ const why = stolen!.signal.reason instanceof LockStolenError
+ ? stolen!.signal.reason.message
+ : `lock '${cycleLockId}' was stolen out from under this holder`;
+ console.error(`[cycle] aborting: ${why} — ${phaseResults.length} phase(s) completed before the steal; their writes are durable`);
} else {
throw e;
}
@@ -2928,6 +3003,22 @@ function deriveStatus(phases: PhaseResult[], totals: CycleReport['totals']): Cyc
// (resolve_symbol_edges). Without these, an edges-only cycle reports 'clean'
// — indistinguishable from "nothing happened" even when N edges resolved.
totals.edges_resolved > 0 ||
- totals.edges_ambiguous > 0;
+ totals.edges_ambiguous > 0 ||
+ // `gbrain dream --input <file>` implies `--phase synthesize` (a
+ // synthesize-only cycle never touches sync/embed/etc, so those totals
+ // stay zero even on a genuinely productive run). Without these two, a
+ // real synthesize outcome — new pages written, or an already-completed
+ // transcript quietly reusing its prior job via the queue's
+ // idempotency_key dedupe — is indistinguishable from "nothing happened".
+ totals.transcripts_processed > 0 ||
+ totals.synth_pages_written > 0;
return anyWork ? 'ok' : 'clean';
}
+
+// ── Test-only export ───────────────────────────────────────
+// `__testing` re-exports otherwise-private helpers so unit tests can pin
+// behavior at function granularity without going through a full runCycle.
+// Not part of the runtime contract.
+export const __testing = {
+ deriveStatus,
+};
diff --git a/src/core/cycle/base-phase.ts b/src/core/cycle/base-phase.ts
index e255eb97aa..89f8ebd058 100644
--- a/src/core/cycle/base-phase.ts
+++ b/src/core/cycle/base-phase.ts
@@ -55,6 +55,43 @@ export interface BasePhaseOpts {
budgetUsd?: number;
/** Optional injected BudgetMeter (tests). When set, replaces the default constructed one. */
meter?: BudgetMeter;
+ /**
+ * Absolute wall-clock deadline (epoch ms) inherited from the owning job's
+ * claim-time `timeout_at` (gbrain#4168). Phases with their own relative
+ * deadline (e.g. propose_takes' 30-min cap) clamp it via
+ * `effectivePhaseDeadlineMs()` so the clean partial-exit path fires BEFORE
+ * the worker's kill switch — without this, a phase default equal to (or,
+ * since phases start mid-cycle, always trailing) the job timeout makes the
+ * clean exit unreachable and the job dead-letters instead of banking
+ * partial work. Null/undefined = no job deadline (interactive CLI runs).
+ */
+ deadlineAtMs?: number | null;
+}
+
+/**
+ * Stop-margin reserved under the job deadline when deriving a phase's
+ * effective relative deadline. Guarantees the phase's clean exit + result
+ * write unwind before the worker's abort fires: wait poll interval (5s) +
+ * worker force-evict grace (30s) + lock and DB cleanup headroom. Lives here
+ * (not patterns.ts) because every deadline-aware phase consumes it;
+ * patterns.ts re-exports for back-compat.
+ */
+export const CYCLE_DEADLINE_RESERVE_MS = 60 * 1000;
+
+/**
+ * Effective relative deadline for a phase: the phase's own default, clamped
+ * to the time remaining under the job's absolute deadline minus the reserve.
+ * Returns 0 when the job budget is already inside the reserve — callers
+ * treat that as "exit cleanly now with deadline_hit", never as unlimited.
+ */
+export function effectivePhaseDeadlineMs(
+ phaseDefaultMs: number,
+ deadlineAtMs: number | null | undefined,
+ nowMs: number,
+): number {
+ if (deadlineAtMs == null) return phaseDefaultMs;
+ const remaining = deadlineAtMs - CYCLE_DEADLINE_RESERVE_MS - nowMs;
+ return Math.max(0, Math.min(phaseDefaultMs, remaining));
}
export abstract class BaseCyclePhase {
diff --git a/src/core/cycle/calibration-profile.ts b/src/core/cycle/calibration-profile.ts
index 857ffeaa68..7d24a56443 100644
--- a/src/core/cycle/calibration-profile.ts
+++ b/src/core/cycle/calibration-profile.ts
@@ -25,7 +25,7 @@
* profiles per source for the same holder.
*/
-import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
+import { BaseCyclePhase, effectivePhaseDeadlineMs, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
import { gateVoice, type VoiceGateGenerator, type VoiceGateJudge } from '../calibration/voice-gate.ts';
@@ -257,6 +257,24 @@ class CalibrationProfilePhase extends BaseCyclePhase {
warnings: [],
};
+ // gbrain#4168: this phase runs last in the calibration trio and makes
+ // 1-2 LLM calls with no interior loop to break out of — so the deadline
+ // check is a pre-flight gate: if the job budget is already inside the
+ // reserve, skip cleanly (the next cycle regenerates from fresher data
+ // anyway) instead of starting an LLM call the worker will kill mid-write.
+ const remainingMs = effectivePhaseDeadlineMs(
+ Number.MAX_SAFE_INTEGER,
+ opts.deadlineAtMs,
+ Date.now(),
+ );
+ if (remainingMs <= 0) {
+ return {
+ summary: 'calibration_profile: skipped — job deadline inside the reserve window',
+ details: { ...result, deadline_hit: true },
+ status: 'warn',
+ };
+ }
+
// Load the holder's scorecard.
const scorecard = await engine.getScorecard({ holder }, undefined);
result.total_resolved = scorecard.resolved;
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index 4186cb4640..095db30e97 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -36,7 +36,7 @@
* cycle.conversation_facts_backfill.max_total_cost_usd (5.00)
* cycle.conversation_facts_backfill.max_walltime_min (20)
* cycle.conversation_facts_backfill.max_total_walltime_min (30)
- * cycle.conversation_facts_backfill.types (["conversation","meeting","slack","email"])
+ * cycle.conversation_facts_backfill.types (all of ALLOWED_TYPES — src/core/facts/conversation-types.ts)
*
* `.types` is the single source of truth for "enabled types" — the CLI
* default reads from the same key (Eng-v2 A2).
@@ -48,10 +48,12 @@ import { withBudgetTracker } from '../ai/gateway.ts';
import { listSources } from '../sources-ops.ts';
import {
runExtractConversationFactsCore,
- ALLOWED_TYPES,
- type AllowedType,
type ExtractConversationFactsResult,
} from '../../commands/extract-conversation-facts.ts';
+// The type allowlist comes straight from the canonical leaf module (same
+// binding extract-conversation-facts.ts re-exports) so this phase is part of
+// the drift-guarded set in test/conversation-facts-type-allowlist-drift.test.ts.
+import { ALLOWED_TYPES, type AllowedType } from '../facts/conversation-types.ts';
/** Per-phase wrapper opts. */
export interface ConversationFactsBackfillPhaseOpts {
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 12034fd50c..46d24ee667 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -65,6 +65,21 @@ import { slugifySegment } from '../sync.ts';
const DEFAULT_BUDGET_USD = 0.3;
const DEFAULT_EXTRACT_ATOMS_MODEL = 'anthropic:claude-haiku-4-5';
+/**
+ * gbrain#4148: consecutive same-content failures of a content-deterministic
+ * class (malformed model output) before the page is tombstoned so the
+ * backlog floor can clear. A content edit resets the streak.
+ */
+export const MAX_DETERMINISTIC_FAILURES = 3;
+
+/**
+ * Transient provider/infra failure shapes — retryable, never counted.
+ * Numeric codes are word-bounded so a 3-digit run inside prose or a larger
+ * number ("chunk 1500", "$1.512") doesn't read as an HTTP 5xx/429.
+ */
+const TRANSIENT_EXTRACT_ERROR_RE =
+ /timeout|timed out|\b429\b|rate.?limit|\b5\d\d\b|ECONN|ETIMEDOUT|EPIPE|ENOTFOUND|fetch failed|\bnetwork\b|socket|overloaded/i;
+
// v0.42+ TODO: read atom_type enum from active pack manifest at runtime.
const ATOM_TYPES = [
'insight', 'anecdote', 'quote', 'framework', 'statistic',
@@ -622,6 +637,49 @@ export async function runPhaseExtractAtoms(
}
}
+ // ── gbrain#4148 helpers ────────────────────────────────────────────
+ let malformedOutputs = 0;
+ const tombstonedForFailures: string[] = [];
+
+ /** Stamp the zero-yield/complete tombstone (hash-keyed; edits re-eligibilize). */
+ async function stampAtomsScanHash(item: { slug: string; contentHash: string }): Promise<void> {
+ try {
+ await engine.executeRaw(
+ `UPDATE pages
+ SET frontmatter = frontmatter || jsonb_build_object('atoms_scan_hash', $1::text)
+ WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL`,
+ [item.contentHash.slice(0, 16), sourceId, item.slug],
+ );
+ } catch { /* fail-soft: page stays rediscoverable */ }
+ }
+
+ /**
+ * Durable per-item failure count, keyed to the CURRENT content hash so a
+ * content edit resets the streak. Returns the new consecutive count, or
+ * null for transcripts / on write failure (never blocks the phase).
+ */
+ async function recordPageFailureCount(item: { kind: string; slug?: string; contentHash: string }): Promise<number | null> {
+ if (item.kind !== 'page' || !item.slug || opts.dryRun) return null;
+ try {
+ const rows = await engine.executeRaw<{ cnt: number | string }>(
+ `UPDATE pages
+ SET frontmatter = frontmatter
+ || jsonb_build_object('atoms_fail_hash', $1::text)
+ || jsonb_build_object('atoms_fail_count',
+ CASE WHEN COALESCE(frontmatter->>'atoms_fail_hash', '') = $1::text
+ THEN COALESCE((frontmatter->>'atoms_fail_count')::int, 0) + 1
+ ELSE 1 END)
+ WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL
+ RETURNING (frontmatter->>'atoms_fail_count')::int AS cnt`,
+ [item.contentHash.slice(0, 16), sourceId, item.slug],
+ );
+ const cnt = rows[0]?.cnt;
+ return cnt == null ? null : Number(cnt);
+ } catch {
+ return null;
+ }
+ }
+
await withBudgetTracker(budgetTracker, async () => {
for (const item of work) {
await maybeYield();
@@ -651,7 +709,29 @@ export async function runPhaseExtractAtoms(
estimatedSpendUsd = budgetTracker.totalSpent;
- const atoms = parseAtomsResponse(result.text);
+ // gbrain#4148: typed outcome — malformed output is a FAILURE (counted
+ // toward the bounded tombstone below), never a zero-yield success.
+ const parseOutcome = parseAtomsOutcome(result.text);
+ if (!parseOutcome.ok) {
+ malformedOutputs++;
+ const failCount = await recordPageFailureCount(item);
+ failures.push({
+ source: originLabel,
+ error: `malformed model output: ${parseOutcome.reason}` +
+ (failCount != null ? ` (consecutive failure ${failCount} on this content)` : ''),
+ });
+ // Content-deterministic class: the same prose reliably produces
+ // unparseable output. After N consecutive failures on the SAME
+ // content hash, tombstone so the backlog floor clears; a content
+ // edit re-eligibilizes (stamp is hash-keyed). Transient provider
+ // errors never reach here — they throw and take the catch path.
+ if (failCount != null && failCount >= MAX_DETERMINISTIC_FAILURES && !opts.dryRun && item.kind === 'page') {
+ await stampAtomsScanHash(item);
+ tombstonedForFailures.push(item.slug);
+ }
+ continue;
+ }
+ const atoms = parseOutcome.atoms;
if (atoms.length === 0) {
// #2144: tombstone zero-yield pages so they stop being rediscovered.
// Idempotency is keyed on atom rows — a page that yields no atoms
@@ -661,16 +741,10 @@ export async function runPhaseExtractAtoms(
// scanned; discovery skips the page only while its content is
// unchanged (edits re-eligibilize, mirroring atom-row staleness).
// Only stamped after a SUCCESSFUL chat call — LLM failures take the
- // catch path below and stay retryable.
+ // catch path below and stay retryable, and malformed output is
+ // counted above (gbrain#4148), never stamped as success.
if (!opts.dryRun && item.kind === 'page') {
- try {
- await engine.executeRaw(
- `UPDATE pages
- SET frontmatter = frontmatter || jsonb_build_object('atoms_scan_hash', $1::text)
- WHERE source_id = $2 AND slug = $3 AND deleted_at IS NULL`,
- [item.contentHash.slice(0, 16), sourceId, item.slug],
- );
- } catch { /* fail-soft: page stays rediscoverable */ }
+ await stampAtomsScanHash(item);
}
if (item.kind === 'transcript') transcriptsProcessed++;
else pagesProcessed++;
@@ -678,6 +752,17 @@ export async function runPhaseExtractAtoms(
}
if (!opts.dryRun) {
+ // gbrain#4148 completion receipt: atoms import with a PROVISIONAL
+ // source_hash (`pending:<hash>`) that discovery's NOT-EXISTS check
+ // can never match, then ONE flip UPDATE marks the whole item done
+ // after every atom persisted. Pre-fix, atom writes were per-atom
+ // while discovery treated any matching source_hash as complete — if
+ // atom 1 persisted and atom 2 failed, the next run skipped the item
+ // and atom 2 was permanently lost. On partial failure the pending
+ // rows stay invisible to doneness, the item re-runs, and the
+ // deterministic slugs upsert instead of duplicating.
+ const hash16 = item.contentHash.slice(0, 16);
+ const importedSlugs: string[] = [];
for (const atom of atoms) {
const srcRef = item.kind === 'transcript' ? item.filePath : item.slug;
const slug = atomSlug(atom.title, srcRef);
@@ -700,7 +785,8 @@ export async function runPhaseExtractAtoms(
{
atom_type: atom.atom_type,
...originFrontmatter,
- source_hash: item.contentHash.slice(0, 16),
+ // Provisional until the whole item's atoms persist (see above).
+ source_hash: `pending:${hash16}`,
...(atom.source_quote && { source_quote: atom.source_quote }),
...(atom.lesson && { lesson: atom.lesson }),
...(atom.concepts && atom.concepts.length > 0 && { concepts: atom.concepts }),
@@ -717,8 +803,21 @@ export async function runPhaseExtractAtoms(
sourceId,
noEmbed: !isAvailable('embedding'),
});
+ importedSlugs.push(slug);
totalAtomsExtracted++;
}
+ // Completion receipt: flip provisional → real in one statement, then
+ // stamp the source page. A crash between flip and stamp degrades to
+ // the legacy atom-rows-mean-done semantics — safe, not lossy.
+ await engine.executeRaw(
+ `UPDATE pages
+ SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)
+ WHERE source_id = $2 AND type = 'atom' AND slug = ANY($3::text[]) AND deleted_at IS NULL`,
+ [hash16, sourceId, importedSlugs],
+ );
+ if (item.kind === 'page') {
+ await stampAtomsScanHash(item);
+ }
} else {
totalAtomsExtracted += atoms.length; // count for dry-run reporting
}
@@ -734,9 +833,18 @@ export async function runPhaseExtractAtoms(
else pagesSkipped++;
continue;
}
+ // gbrain#4148: classify. Transient provider/infra errors (timeouts,
+ // rate limits, 5xx, network) stay retryable and are NOT counted toward
+ // any tombstone. Everything else gets a durable count for
+ // observability, but only the malformed-output class (handled above)
+ // ever tombstones — an unknown error class must never permanently
+ // suppress a page's atoms.
+ const message = err instanceof Error ? err.message : String(err);
+ const transient = TRANSIENT_EXTRACT_ERROR_RE.test(message);
+ if (!transient) await recordPageFailureCount(item);
failures.push({
source: originLabel,
- error: err instanceof Error ? err.message : String(err),
+ error: transient ? `${message} [transient — retried next run]` : message,
});
}
}
@@ -806,6 +914,8 @@ export async function runPhaseExtractAtoms(
pages_skipped_budget: pagesSkipped,
duplicates_skipped: duplicatesSkipped,
failures,
+ malformed_outputs: malformedOutputs,
+ tombstoned_for_failures: tombstonedForFailures,
estimated_spend_usd: estimatedSpendUsd,
budget_usd: budgetCap,
model: extractModel,
@@ -817,11 +927,19 @@ export async function runPhaseExtractAtoms(
}
/**
- * Parse the Haiku JSON response into ExtractedAtom[]. Tolerant of
- * common LLM mistakes: extra prose around the JSON, missing fields,
- * invalid atom_type values. Rejects (returns empty) on hard parse fail.
+ * gbrain#4148 — typed parse outcome. Malformed model output and a legitimate
+ * zero-yield extraction both used to collapse into `[]`, so malformed output
+ * was tombstoned as success (the page never retried, its atoms silently
+ * lost). `ok: false` means the response was not parseable as an atoms array
+ * AT ALL — a content-deterministic failure class the caller counts toward a
+ * bounded tombstone; `ok: true, atoms: []` means the model genuinely
+ * extracted nothing.
*/
-export function parseAtomsResponse(raw: string): ExtractedAtom[] {
+export type AtomsParseOutcome =
+ | { ok: true; atoms: ExtractedAtom[] }
+ | { ok: false; reason: string };
+
+export function parseAtomsOutcome(raw: string): AtomsParseOutcome {
// Strip markdown code fences if the LLM wrapped JSON in them.
let cleaned = raw.trim();
const fenceMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
@@ -829,7 +947,7 @@ export function parseAtomsResponse(raw: string): ExtractedAtom[] {
// Find the first JSON array bracket.
const arrayStart = cleaned.indexOf('[');
- if (arrayStart === -1) return [];
+ if (arrayStart === -1) return { ok: false, reason: 'no JSON array in response' };
cleaned = cleaned.slice(arrayStart);
let parsed: unknown;
@@ -838,15 +956,29 @@ export function parseAtomsResponse(raw: string): ExtractedAtom[] {
} catch {
// Try trimming back from the end to recover from trailing prose.
const arrayEnd = cleaned.lastIndexOf(']');
- if (arrayEnd === -1) return [];
+ if (arrayEnd === -1) return { ok: false, reason: 'unterminated JSON array' };
try {
parsed = JSON.parse(cleaned.slice(0, arrayEnd + 1));
} catch {
- return [];
+ return { ok: false, reason: 'unparseable JSON array' };
}
}
- if (!Array.isArray(parsed)) return [];
+ if (!Array.isArray(parsed)) return { ok: false, reason: 'JSON value is not an array' };
+ return { ok: true, atoms: atomsFromParsedArray(parsed) };
+}
+
+/**
+ * Back-compat wrapper: parse the response into ExtractedAtom[], returning []
+ * for BOTH malformed output and a legitimate zero-yield (legacy callers/tests
+ * that don't need the typed distinction — new code uses parseAtomsOutcome).
+ */
+export function parseAtomsResponse(raw: string): ExtractedAtom[] {
+ const outcome = parseAtomsOutcome(raw);
+ return outcome.ok ? outcome.atoms : [];
+}
+
+function atomsFromParsedArray(parsed: unknown[]): ExtractedAtom[] {
const atoms: ExtractedAtom[] = [];
for (const item of parsed) {
diff --git a/src/core/cycle/grade-takes.ts b/src/core/cycle/grade-takes.ts
index ac47e8826b..e7562bf950 100644
--- a/src/core/cycle/grade-takes.ts
+++ b/src/core/cycle/grade-takes.ts
@@ -35,7 +35,7 @@
*/
import { createHash } from 'node:crypto';
-import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
+import { BaseCyclePhase, effectivePhaseDeadlineMs, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
import { chat as gatewayChat, getChatModel } from '../ai/gateway.ts';
import { splitProviderModelId } from '../model-id.ts';
import { GBrainError } from '../types.ts';
@@ -177,6 +177,8 @@ export function aggregateEnsemble(
export type EvidenceRetrieverFn = (take: Take, scope: ScopedReadOpts) => Promise<string>;
export interface GradeTakesOpts extends BasePhaseOpts {
+ /** Override the phase wall-clock deadline (tests). Default: 30 min, clamped to the job deadline (gbrain#4168). */
+ deadlineMs?: number;
/** Minimum age in months before a take is eligible for grading. Default 6. */
minAgeMonths?: number;
/** Limit takes processed in this cycle. Default 50. */
@@ -252,6 +254,8 @@ export interface GradeTakesResult {
ensemble_invoked: number;
/** E2 ensemble (T5): count of takes where ensemble produced 3/3 unanimous. */
ensemble_unanimous: number;
+ /** gbrain#4168: true when the phase deadline fired mid-loop (partial result). */
+ deadline_hit: boolean;
}
/**
@@ -368,6 +372,14 @@ function verdictToResolution(verdict: JudgeVerdict, resolvedByLabel: string): Ta
};
}
+/**
+ * Hard wall-clock deadline for the grade_takes phase (gbrain#4168). Same
+ * clean-partial-exit contract as propose_takes: judge calls have long tails,
+ * and without a phase deadline the worker's job timeout killed the phase
+ * mid-write instead of letting it bank completed verdicts.
+ */
+const GRADE_TAKES_PHASE_DEADLINE_MS = 30 * 60 * 1000;
+
class GradeTakesPhase extends BaseCyclePhase {
readonly name = 'grade_takes' as CyclePhase;
protected readonly budgetUsdKey = 'cycle.grade_takes.budget_usd';
@@ -426,8 +438,29 @@ class GradeTakesPhase extends BaseCyclePhase {
warnings: [],
ensemble_invoked: 0,
ensemble_unanimous: 0,
+ deadline_hit: false,
};
+ // gbrain#4168: relative phase deadline clamped to the job's absolute
+ // deadline minus the reserve — same clean partial-exit contract as
+ // propose_takes (break, bank verdicts already written, report).
+ const phaseStartMs = Date.now();
+ const deadlineMs = effectivePhaseDeadlineMs(
+ opts.deadlineMs ?? GRADE_TAKES_PHASE_DEADLINE_MS,
+ opts.deadlineAtMs,
+ phaseStartMs,
+ );
+ if (deadlineMs <= 0) {
+ // Job budget already inside the reserve — exit before ANY judge call.
+ result.warnings.push('phase skipped: job deadline already inside the reserve window');
+ result.deadline_hit = true;
+ return {
+ summary: 'grade_takes: skipped — job deadline inside the reserve window',
+ details: { ...result, prompt_version: promptVersion, auto_resolve: autoResolve, auto_resolve_threshold: autoResolveThreshold },
+ status: 'warn',
+ };
+ }
+
// Load unresolved active takes, oldest-first.
const takes = await engine.listTakes({
resolved: false,
@@ -442,6 +475,19 @@ class GradeTakesPhase extends BaseCyclePhase {
const now = new Date();
for (const take of takes) {
+ // Phase deadline check (gbrain#4168). Break, not throw: verdicts
+ // already cached stay banked, and the phase reports partial cleanly
+ // before the worker's kill switch fires.
+ const elapsedMs = Date.now() - phaseStartMs;
+ if (elapsedMs > deadlineMs) {
+ result.warnings.push(
+ `phase deadline hit at take ${result.takes_scanned}/${takes.length} ` +
+ `after ${(elapsedMs / 1000).toFixed(0)}s (cap ${(deadlineMs / 1000).toFixed(0)}s); partial completion`,
+ );
+ result.deadline_hit = true;
+ break;
+ }
+
result.takes_scanned += 1;
this.tick(opts);
@@ -613,7 +659,8 @@ class GradeTakesPhase extends BaseCyclePhase {
const summary =
`grade_takes: scanned ${result.takes_scanned} takes ` +
`(${result.too_recent} too recent, ${result.cache_hits} cached, ` +
- `${result.verdicts_written} new verdicts, ${result.auto_applied} auto-applied)`;
+ `${result.verdicts_written} new verdicts, ${result.auto_applied} auto-applied)` +
+ (result.deadline_hit ? ' [deadline hit — partial]' : '');
return {
summary,
details: {
@@ -622,7 +669,7 @@ class GradeTakesPhase extends BaseCyclePhase {
auto_resolve: autoResolve,
auto_resolve_threshold: autoResolveThreshold,
},
- status: result.budget_exhausted ? 'warn' : 'ok',
+ status: result.budget_exhausted || result.deadline_hit ? 'warn' : 'ok',
};
}
}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 1b51b82ca0..bd1a930a3f 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -74,10 +74,11 @@ export interface PatternsPhaseOpts {
* budgets. NOT a promise that tail phases complete — the cycle is allowed
* to go partial and resume next tick. This only guarantees the phase's
* wait returns and the handler unwinds cleanly before the worker's abort
- * fires: wait poll interval (5s) + worker force-evict grace (30s) + lock
- * and DB cleanup headroom.
+ * fires. Canonical definition moved to base-phase.ts (gbrain#4168 made it
+ * a every-phase concern); re-exported here for existing importers.
*/
-export const CYCLE_DEADLINE_RESERVE_MS = 60 * 1000;
+export { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';
+import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';
/**
* Smallest remaining budget worth submitting a subagent for. Below this,
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index e62e958e35..ea23da385f 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -38,7 +38,7 @@
*/
import { randomUUID, createHash } from 'node:crypto';
-import { BaseCyclePhase, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
+import { BaseCyclePhase, effectivePhaseDeadlineMs, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';
import { chat as gatewayChat, getChatModel, probeChatModel } from '../ai/gateway.ts';
import { normalizeModelId } from '../model-id.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
@@ -436,8 +436,18 @@ class ProposeTakesPhase extends BaseCyclePhase {
const promptVersion = opts.promptVersion ?? PROPOSE_TAKES_PROMPT_VERSION;
const pageLimit = opts.pageLimit ?? 100;
const skipPagesWithFence = opts.skipPagesWithFence ?? false;
- const deadlineMs = opts.deadlineMs ?? ProposeTakesPhase.PHASE_DEADLINE_MS;
const phaseStartMs = Date.now();
+ // gbrain#4168: clamp the phase's relative deadline to the job's absolute
+ // deadline (minus reserve). At the default installed-daemon interval the
+ // job timeout floor EQUALS the old 30-min phase default, and since this
+ // phase starts after earlier phases, phase-elapsed always trailed
+ // job-elapsed — the clean partial-exit below was unreachable and cycles
+ // dead-lettered instead of banking work.
+ const deadlineMs = effectivePhaseDeadlineMs(
+ opts.deadlineMs ?? ProposeTakesPhase.PHASE_DEADLINE_MS,
+ opts.deadlineAtMs,
+ phaseStartMs,
+ );
const proposalRunId = `propose-${new Date().toISOString().slice(0, 19).replace(/[-:T]/g, '')}-${randomUUID().slice(0, 8)}`;
const modelId = opts.model ?? getChatModel();
@@ -476,8 +486,22 @@ class ProposeTakesPhase extends BaseCyclePhase {
tombstones_written: 0,
budget_exhausted: false,
warnings: [],
+ deadline_hit: false,
};
+ // gbrain#4168: job budget already inside the reserve window — exit
+ // cleanly before ANY work (the in-loop `elapsed > deadline` check can't
+ // fire on the first iteration when the effective deadline is 0).
+ if (deadlineMs <= 0) {
+ result.warnings.push('phase skipped: job deadline already inside the reserve window');
+ result.deadline_hit = true;
+ return {
+ summary: `propose_takes: skipped — job deadline inside the reserve window (run ${proposalRunId})`,
+ details: { ...result, proposal_run_id: proposalRunId, prompt_version: promptVersion },
+ status: 'warn' as PhaseStatus,
+ };
+ }
+
// Load pages eligible for proposal. Source-scoped per BaseCyclePhase.
const pages = await listCandidatePages(engine, scope, pageLimit);
diff --git a/src/core/destructive-guard.ts b/src/core/destructive-guard.ts
index b52f08ecb4..93de6a0960 100644
--- a/src/core/destructive-guard.ts
+++ b/src/core/destructive-guard.ts
@@ -416,60 +416,78 @@ export async function listArchivedSources(
}));
}
+/** Result of a purge sweep: what deleted, and what an FK deliberately held. */
+export interface PurgeExpiredResult {
+ /** Source ids permanently deleted this sweep. */
+ purged: string[];
+ /**
+ * Sources past TTL that could NOT be deleted because a RESTRICT FK still
+ * references them — today that is migration v64's oauth_clients.source_id
+ * ON DELETE RESTRICT, which intentionally refuses source deletion until
+ * every client is revoked-and-purged or re-scoped. Blocked is a policy
+ * outcome, not an error: the sweep reports it and moves on.
+ */
+ blocked: Array<{ id: string; reason: string }>;
+}
+
/**
* Permanently purge sources whose 72h TTL has expired. Cascades to pages
- * (and content_chunks via existing FKs). Returns the ids of purged sources.
- *
- * v0.26.5: moved from JSONB-driven iteration to a single set-based DELETE
- * with `archived = true AND archive_expires_at <= now()`. Server-side
- * filter; one round-trip; cascade-friendly.
+ * (and content_chunks via existing FKs).
*
- * PR6 D5b: sources still referenced by ANY oauth_clients row (including
- * soft-deleted ones — the FK is physical, ON DELETE RESTRICT ignores
- * deleted_at) are SKIPPED via NOT EXISTS instead of aborting the whole
- * set-based DELETE with an FK violation. Skips surface as ONE stderr warn
- * naming the skipped ids; the return contract stays string[] (purged ids
- * only) for the cycle.ts + jobs.ts callers.
+ * v0.26.5 used a single set-based DELETE; gbrain#4115 showed one FK-blocked
+ * source (a revoked-but-retained oauth_client under v64's ON DELETE RESTRICT)
+ * aborted the whole statement, wedging the nightly purge forever. The sweep is
+ * now per-source: each DELETE re-checks the expiry predicate (no
+ * select-then-delete race with a concurrent restore), ONLY the FK-restriction
+ * error class (SQLSTATE 23503) is treated as blocked-and-reported, and every
+ * other error re-raises. (Supersedes #4238's set-based NOT-EXISTS variant at
+ * merge: the 23503 catch covers ANY current or future RESTRICT FK — including
+ * soft-deleted oauth_clients, since the FK is physical — not just the one
+ * table an EXISTS prefilter names, and the structured {purged, blocked}
+ * return is what every caller + test in this tree consumes.)
*/
export async function purgeExpiredSources(
engine: BrainEngine,
-): Promise<string[]> {
- const expiredCond = `archived = true
+): Promise<PurgeExpiredResult> {
+ const candidates = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources
+ WHERE archived = true
AND archive_expires_at IS NOT NULL
- AND archive_expires_at <= now()`;
- const referencedCond = `EXISTS (SELECT 1 FROM oauth_clients c WHERE c.source_id = sources.id)`;
-
- // Query the skip set FIRST so the warn can name ids even though the DELETE
- // never touches them. Pre-oauth brains (no oauth_clients table) — and
- // pre-migration brains without the source_id column (no column ⇒ no FK) —
- // purge unconditionally. The EXISTS is deliberately PHYSICAL (no deleted_at
- // filter): the FK ignores soft-deletion.
- let skipped: Array<{ id: string }> = [];
- let hasOauthTable = true;
- try {
- skipped = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources WHERE ${expiredCond} AND ${referencedCond} ORDER BY id`,
- );
- } catch (e) {
- if (!isUndefinedTableError(e) && !isUndefinedColumnError(e, 'source_id')) throw e;
- hasOauthTable = false;
- }
-
- const rows = await engine.executeRaw<{ id: string }>(
- hasOauthTable
- ? `DELETE FROM sources WHERE ${expiredCond} AND NOT ${referencedCond} RETURNING id`
- : `DELETE FROM sources WHERE ${expiredCond} RETURNING id`,
+ AND archive_expires_at <= now()
+ ORDER BY id`,
);
-
- if (skipped.length > 0) {
- const ids = skipped.map((s) => s.id).join(', ');
- console.error(
- `[gbrain] purge skipped ${skipped.length} expired source(s) still referenced by OAuth clients: ${ids}. ` +
- `Revoke the referencing client(s) (gbrain auth revoke-client "<client-id>") and re-run the purge.`,
- );
+ const purged: string[] = [];
+ const blocked: PurgeExpiredResult['blocked'] = [];
+ for (const { id } of candidates) {
+ try {
+ const rows = await engine.executeRaw<{ id: string }>(
+ `DELETE FROM sources
+ WHERE id = $1
+ AND archived = true
+ AND archive_expires_at IS NOT NULL
+ AND archive_expires_at <= now()
+ RETURNING id`,
+ [id],
+ );
+ if (rows.length > 0) purged.push(id);
+ // 0 rows = restored/already gone between SELECT and DELETE; neither
+ // purged nor blocked.
+ } catch (err) {
+ // SQLSTATE 23503 foreign_key_violation — same detection idiom as
+ // oauth-provider.ts's delete path for this exact FK.
+ if ((err as { code?: string })?.code === '23503') {
+ blocked.push({
+ id,
+ reason:
+ 'still referenced by a RESTRICT foreign key (revoked oauth_client not yet purged? the FK is physical, so soft-deleted clients also block) — ' +
+ 'review with `gbrain auth clients`, revoke with `gbrain auth revoke-client "<client-id>"`, then retry',
+ });
+ continue;
+ }
+ throw err;
+ }
}
-
- return rows.map((r) => r.id);
+ return { purged, blocked };
}
// ── Display Helpers ─────────────────────────────────────────
diff --git a/src/core/eval-contradictions/auto-supersession.ts b/src/core/eval-contradictions/auto-supersession.ts
index 08ac887562..43c7a2427e 100644
--- a/src/core/eval-contradictions/auto-supersession.ts
+++ b/src/core/eval-contradictions/auto-supersession.ts
@@ -89,9 +89,17 @@ export function classifyResolution(
if (pair.a.take_id !== null) return 'takes_supersede';
return 'manual_review';
}
- if (judgeHint === 'dream_synthesize' || judgeHint === 'takes_mark_debate') {
+ if (judgeHint === 'dream_synthesize') {
return judgeHint;
}
+ // gbrain#4169: `takes mark-debate` is documented but NOT implemented (the
+ // CLI dispatch falls through to the list path and treats "mark-debate" as
+ // a slug — tracked with #4102). Minting the kind would lie to JSON
+ // consumers about an available action; route to manual_review until the
+ // subcommand exists. The enum member stays for legacy stored rows.
+ if (judgeHint === 'takes_mark_debate') {
+ return 'manual_review';
+ }
if (judgeHint === 'takes_supersede' || judgeHint === 'manual_review') {
return judgeHint;
}
@@ -101,6 +109,18 @@ export function classifyResolution(
return 'manual_review';
}
+/**
+ * POSIX single-quote escaping for untrusted text (claim text AND slugs)
+ * rendered into a paste-ready command (gbrain#4169): wrap in single quotes;
+ * embedded single quotes become the `'\''` splice. Newlines collapse to
+ * spaces — a resolution command is one line by contract. Slugs are quoted
+ * too: validateSlug leaves shell metacharacters unblocked and remote MCP
+ * writers can mint slugs, so an unquoted slug reaches the operator's shell.
+ */
+function shellQuote(s: string): string {
+ return `'${s.replace(/\s+/g, ' ').trim().replace(/'/g, `'\\''`)}'`;
+}
+
/**
* Render the paste-ready CLI command for the chosen resolution. Operator
* runs this verbatim; the command may itself prompt for confirmation.
@@ -111,21 +131,30 @@ export function renderResolutionCommand(
): string {
switch (kind) {
case 'takes_supersede': {
- // Prefer the slug of the take side (intra_page) or the curated side.
+ // gbrain#4169: --row takes the PER-PAGE row_num (take_id is the global
+ // PK and never resolves), and `takes supersede` REQUIRES --claim — the
+ // replacement text. classifyResolution picks an ACTION, not a winner:
+ // in a chunk-vs-take pair the chunk side is arbitrary prose, so
+ // auto-filling --claim from it would fabricate a take. Render the
+ // correctly-addressed command with an explicit placeholder the
+ // operator fills in.
const takeSide = pair.b.take_id !== null ? pair.b : (pair.a.take_id !== null ? pair.a : pair.a);
- const takeId = takeSide.take_id ?? '<row>';
- return `gbrain takes supersede ${takeSide.slug} --row ${takeId}`;
+ const rowNum = takeSide.take_row_num ?? '<row>';
+ return `gbrain takes supersede ${shellQuote(takeSide.slug)} --row ${rowNum} --claim '<replacement claim — see contradiction report>'`;
}
case 'dream_synthesize': {
const curatedSide = isCuratedEntitySlug(pair.a.slug)
? pair.a
: (isCuratedEntitySlug(pair.b.slug) ? pair.b : pair.a);
- return `gbrain dream --phase synthesize --slug ${curatedSide.slug}`;
+ return `gbrain dream --phase synthesize --slug ${shellQuote(curatedSide.slug)}`;
}
case 'takes_mark_debate': {
+ // gbrain#4169: this subcommand does not exist (tracked with #4102) —
+ // new classifications route to manual_review; this branch only renders
+ // for LEGACY stored rows, and must not emit a command that fails.
const takeSide = pair.b.take_id !== null ? pair.b : (pair.a.take_id !== null ? pair.a : pair.a);
- const takeId = takeSide.take_id ?? '<row>';
- return `gbrain takes mark-debate ${takeSide.slug} --row ${takeId}`;
+ const rowNum = takeSide.take_row_num ?? '<row>';
+ return `# manual review: mark-as-debate is not implemented yet (#4102); take at ${takeSide.slug} row ${rowNum}`;
}
case 'temporal_supersede': {
// v0.34 / Lane A2: pick the newer-dated side as the survivor; render a
@@ -136,10 +165,18 @@ export function renderResolutionCommand(
const bDate = pair.b.effective_date;
if (aDate && bDate) {
const olderSide = aDate < bDate ? pair.a : pair.b;
+ const newerSide = aDate < bDate ? pair.b : pair.a;
const newerDate = aDate < bDate ? bDate : aDate;
- const olderTakeId = olderSide.take_id;
- if (olderTakeId !== null) {
- return `gbrain takes supersede ${olderSide.slug} --row ${olderTakeId} --since ${newerDate}`;
+ if (olderSide.take_id !== null && olderSide.take_row_num !== null) {
+ // gbrain#4169: temporal supersession has a REAL winner (the
+ // newer-dated side). When that side is itself a take, its claim is
+ // the unambiguous replacement — paste-ready, shell-escaped. When
+ // the newer side is a chunk, its text is arbitrary prose:
+ // correctly-addressed command with an explicit placeholder.
+ const claim = newerSide.take_id !== null
+ ? shellQuote(newerSide.text)
+ : `'<replacement claim — see contradiction report>'`;
+ return `gbrain takes supersede ${shellQuote(olderSide.slug)} --row ${olderSide.take_row_num} --claim ${claim} --since ${newerDate}`;
}
return `# temporal_supersession: ${olderSide.slug} (${aDate < bDate ? aDate : bDate}) superseded by ${newerDate}`;
}
diff --git a/src/core/eval-contradictions/runner.ts b/src/core/eval-contradictions/runner.ts
index adee2c5ef7..df1ee0aa32 100644
--- a/src/core/eval-contradictions/runner.ts
+++ b/src/core/eval-contradictions/runner.ts
@@ -111,6 +111,7 @@ function searchResultToMember(r: SearchResult): PairMember {
slug: r.slug,
chunk_id: r.chunk_id,
take_id: null,
+ take_row_num: null,
source_tier: classifySlugTier(r.slug),
holder: null,
text: r.chunk_text,
@@ -130,7 +131,7 @@ function searchResultToMember(r: SearchResult): PairMember {
* `pages.effective_date` here — for v1 they share the same page anchor.
*/
function takeToMember(
- take: { id: number; page_slug: string; claim: string; holder: string },
+ take: { id: number; row_num: number; page_slug: string; claim: string; holder: string },
source_tier: ReturnType<typeof classifySlugTier>,
effective_date: string | null,
effective_date_source: string | null,
@@ -139,6 +140,10 @@ function takeToMember(
slug: take.page_slug,
chunk_id: null,
take_id: take.id,
+ // gbrain#4169: the per-page row number is what `takes supersede --row`
+ // addresses. listActiveTakesForPages already SELECTs t.* so it rides
+ // along for free; takeToMember just stopped dropping it.
+ take_row_num: take.row_num,
source_tier,
holder: take.holder,
text: take.claim,
diff --git a/src/core/eval-contradictions/types.ts b/src/core/eval-contradictions/types.ts
index 02d509609c..0610e1da6d 100644
--- a/src/core/eval-contradictions/types.ts
+++ b/src/core/eval-contradictions/types.ts
@@ -118,6 +118,13 @@ export interface PairMember {
chunk_id: number | null;
/** Present for intra_page_chunk_take when this end is a take. */
take_id: number | null;
+ /**
+ * gbrain#4169: the take's PER-PAGE row number — what the takes CLI's
+ * `--row` flag actually addresses. `take_id` is the global PK; rendering
+ * it into `--row` made every generated resolution command fail with
+ * "Row #N not found". Null when this end is a chunk.
+ */
+ take_row_num: number | null;
source_tier: SourceTier;
/** Takes-only: who holds the take (`garry`, `alice`, ...). */
holder: string | null;
diff --git a/src/core/facts/conversation-types.ts b/src/core/facts/conversation-types.ts
new file mode 100644
index 0000000000..38b2fbcaf3
--- /dev/null
+++ b/src/core/facts/conversation-types.ts
@@ -0,0 +1,37 @@
+/**
+ * Canonical allowlist of `pages.type` values the conversation-facts
+ * extraction pipeline operates on: conversation, meeting, slack, email,
+ * imessage, imessage-daily.
+ *
+ * Lives in `src/core/facts/` (not `src/commands/`) so a consumer that only
+ * needs these six values — doctor.ts's backlog-check default and its
+ * conversation_format_coverage sample scan, jobs.ts's extract-conversation-
+ * facts Minion job handler, sources.ts's facts-backfill audit estimator —
+ * can import just this leaf instead of pulling in
+ * `src/commands/extract-conversation-facts.ts`'s own CLI flag surface (that
+ * command's help text and its own command-line option parsing).
+ *
+ * That's not a hypothetical: this file exists BECAUSE `scripts/generate-
+ * flag-registry.ts` scans every command-line-option-shaped string literal in
+ * a module it finds via a relative import, one level deep. Importing the
+ * constant straight from extract-conversation-facts.ts (even just for this
+ * constant) transitively attributed that whole option surface to doctor,
+ * jobs, and sources — three commands that don't otherwise accept those
+ * options — in the generated CLI_ONLY registry (#4135).
+ *
+ * `src/commands/extract-conversation-facts.ts` imports from here and
+ * re-exports both names verbatim so its remaining existing importers (its
+ * own tests) keep working unchanged; the cycle backfill phase
+ * (`src/core/cycle/conversation-facts-backfill.ts`) imports this leaf
+ * directly and is part of the drift-guarded set.
+ */
+export const ALLOWED_TYPES = Object.freeze([
+ 'conversation',
+ 'meeting',
+ 'slack',
+ 'email',
+ 'imessage',
+ 'imessage-daily',
+] as const);
+
+export type AllowedType = (typeof ALLOWED_TYPES)[number];
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index c2a498f565..56445846a2 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -253,7 +253,7 @@ export interface CodeRef {
// The extension list is aligned with detectCodeLanguage in chunkers/code.ts.
// Paths NOT matching these extensions are ignored because they wouldn't
// have a code page to edge to anyway.
-const CODE_REF_REGEX = /\b((?:src|lib|app|test|tests|scripts|docs|packages|internal|cmd|examples)\/[\w\-./]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|rb|go|rs|java|cs|cpp|cc|hpp|c|h|php|swift|kt|scala|lua|ex|exs|elm|ml|dart|zig|sol|sh|bash|css|html|vue|json|yaml|yml|toml))(?::(\d+))?\b/g;
+const CODE_REF_REGEX = /\b((?:src|lib|app|test|tests|scripts|docs|packages|internal|cmd|examples)\/[\w\-./]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|rb|go|rs|java|cs|cpp|cc|hpp|c|h|php|swift|kt|scala|lua|ex|exs|elm|ml|dart|zig|sol|sh|bash|css|html|astro|svelte|vue|json|yaml|yml|toml))(?::(\d+))?\b/g;
/**
* Extract code-path references (e.g. 'src/core/sync.ts:42') from markdown
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index bff3fd224a..b6686e25f4 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -5853,6 +5853,35 @@ export const MIGRATIONS: Migration[] = [
ALTER TABLE minion_jobs ADD CONSTRAINT chk_lock_duration_positive CHECK (lock_duration_ms IS NULL OR (lock_duration_ms >= 5000 AND lock_duration_ms <= 3600000));
`,
},
+ {
+ version: 131,
+ name: 'drop_job_wide_subagent_tool_use_id_unique',
+ // #4155 — tool_use_id stores the RAW provider id, and some providers
+ // legitimately reuse the same short id on every turn (claude-cli spawns a
+ // fresh subprocess per turn from an id-stripped transcript, so the model
+ // re-invents ids like "toolu_01"). The job-wide UNIQUE (job_id,
+ // tool_use_id) constraint encoded the false assumption that provider ids
+ // are unique within a job; a reuse collided (this was never any INSERT's
+ // conflict target) and dead-lettered the job. Row identity is already
+ // carried by subagent_tool_executions_stable_id UNIQUE (job_id,
+ // message_idx, ordinal); readers resolve executions by (message_idx,
+ // tool_use_id). A narrower unique (e.g. adding message_idx) would still
+ // dead-letter a turn that reuses one id twice, so no replacement
+ // constraint is added. Same SQL on both engines; DROP CONSTRAINT IF
+ // EXISTS makes re-runs a no-op (v82 pglite precedent).
+ // (Authored as v129; renumbered to v131 after #4152 and #4145 landed
+ // 129/130 first — same renumber pattern as v130 itself.)
+ // Mixed-version fleets: an OLD binary still naming this constraint as an
+ // ON CONFLICT target errors (SQLSTATE 42P10) on every tool persist once
+ // the drop runs — fail-loud, not corrupting. Multi-worker Postgres
+ // deployments should stop `jobs work` daemons before upgrading and
+ // restart them on the new binary (release-noted in v0.46.14.0).
+ idempotent: true,
+ sql: `
+ ALTER TABLE subagent_tool_executions
+ DROP CONSTRAINT IF EXISTS uniq_subagent_tools_use_id;
+ `,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.ts
index 88de88578d..0d8d6b6125 100644
--- a/src/core/minions/handlers/subagent.ts
+++ b/src/core/minions/handlers/subagent.ts
@@ -165,6 +165,8 @@ interface PersistedMessage {
interface PersistedToolExec {
message_idx: number;
+ /** D11 stable ordinal (per-turn tool-call position). NULL on legacy rows. */
+ ordinal: number | null;
tool_use_id: string;
tool_name: string;
input: unknown;
@@ -367,7 +369,14 @@ export function makeSubagentHandler(deps: SubagentDeps) {
// ── Load prior state (replay) ───────────────────────────
const priorMessages = await loadPriorMessages(engine, ctx.id);
const priorTools = await loadPriorTools(engine, ctx.id);
- const priorToolByUseId = new Map(priorTools.map(t => [t.tool_use_id, t]));
+ // Keyed by (message_idx, tool_use_id) — raw provider tool_use_ids may
+ // repeat across turns (#4155), so tool_use_id alone could resolve a
+ // sibling turn's execution row. WITHIN a turn this legacy path relies on
+ // the Anthropic-direct invariant that ids are unique per message (the
+ // whole loop is Anthropic-pinned for exactly that stability — see
+ // src/core/ai/capabilities.ts); the gateway path carries D11 ordinals
+ // for providers without that guarantee.
+ const priorToolByUseId = new Map(priorTools.map(t => [`${t.message_idx}:${t.tool_use_id}`, t]));
// Rebuild the Anthropic messages array from persisted rows.
const anthroMessages: Anthropic.MessageParam[] = priorMessages.length > 0
@@ -437,8 +446,8 @@ export function makeSubagentHandler(deps: SubagentDeps) {
}
if (pendingToolUses.length > 0) {
const synthesizedResults: ContentBlock[] = [];
- for (const use of pendingToolUses) {
- const prior = priorToolByUseId.get(use.id);
+ for (const [useOrdinal, use] of pendingToolUses.entries()) {
+ const prior = priorToolByUseId.get(`${last.message_idx}:${use.id}`);
if (prior?.status === 'complete') {
synthesizedResults.push({
type: 'tool_result',
@@ -460,7 +469,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
const toolDef = toolDefs.find(t => t.name === use.name);
if (!toolDef) {
await persistToolExecFailed(
- engine, ctx.id, last.message_idx, use.id, use.name, use.input,
+ engine, ctx.id, last.message_idx, useOrdinal, use.id, use.name, use.input,
`tool "${use.name}" is not in the registry for this subagent`,
);
synthesizedResults.push({
@@ -472,19 +481,19 @@ export function makeSubagentHandler(deps: SubagentDeps) {
if (prior?.status === 'pending' && !toolDef.idempotent) {
throw new Error(`non-idempotent tool "${use.name}" pending on resume; cannot safely re-run`);
}
- await persistToolExecPending(engine, ctx.id, last.message_idx, use.id, use.name, use.input);
+ await persistToolExecPending(engine, ctx.id, last.message_idx, useOrdinal, use.id, use.name, use.input);
try {
const output = await toolDef.execute(use.input, {
engine, jobId: ctx.id, remote: true, signal: ctx.signal,
});
- await persistToolExecComplete(engine, ctx.id, use.id, output);
+ await persistToolExecComplete(engine, ctx.id, last.message_idx, useOrdinal, use.id, output);
synthesizedResults.push({
type: 'tool_result', tool_use_id: use.id,
content: asStringIfNotObject(output),
} as ContentBlock);
} catch (e) {
const errText = e instanceof Error ? (e.stack ?? e.message) : String(e);
- await persistToolExecFailed(engine, ctx.id, last.message_idx, use.id, use.name, use.input, errText);
+ await persistToolExecFailed(engine, ctx.id, last.message_idx, useOrdinal, use.id, use.name, use.input, errText);
synthesizedResults.push({
type: 'tool_result', tool_use_id: use.id,
content: errText, is_error: true,
@@ -726,7 +735,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
// 5. Dispatch each tool_use. Two-phase persist (pending → complete/failed).
const toolResults: ContentBlock[] = [];
- for (const use of toolUses) {
+ for (const [useOrdinal, use] of toolUses.entries()) {
if (ctx.signal.aborted || ctx.shutdownSignal.aborted) {
throw new Error('subagent aborted during tool dispatch');
}
@@ -737,7 +746,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
// Model called a tool we didn't expose. Mark execution failed
// with a clear error and feed the error back in the next turn.
await persistToolExecFailed(
- engine, ctx.id, assistantIdx, use.id, toolName, use.input,
+ engine, ctx.id, assistantIdx, useOrdinal, use.id, toolName, use.input,
`tool "${toolName}" is not in the registry for this subagent`,
);
toolResults.push({
@@ -756,9 +765,10 @@ export function makeSubagentHandler(deps: SubagentDeps) {
continue;
}
- // Replay: if we already have a row for this tool_use_id, trust it
- // unless status='pending' and the tool is idempotent (re-run).
- const prior = priorToolByUseId.get(use.id);
+ // Replay: if we already have a row for this turn's tool_use_id,
+ // trust it unless status='pending' and the tool is idempotent
+ // (re-run). Keyed by (message_idx, tool_use_id) — see #4155.
+ const prior = priorToolByUseId.get(`${assistantIdx}:${use.id}`);
if (prior && prior.status === 'complete') {
toolResults.push({
type: 'tool_result',
@@ -782,7 +792,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
}
// Fresh or idempotent-replay dispatch.
- await persistToolExecPending(engine, ctx.id, assistantIdx, use.id, toolName, use.input);
+ await persistToolExecPending(engine, ctx.id, assistantIdx, useOrdinal, use.id, toolName, use.input);
logSubagentHeartbeat({ job_id: ctx.id, event: 'tool_called', turn_idx: turnIdx, tool_name: toolName });
const toolStart = Date.now();
@@ -793,7 +803,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
remote: true,
signal: ctx.signal,
});
- await persistToolExecComplete(engine, ctx.id, use.id, output);
+ await persistToolExecComplete(engine, ctx.id, assistantIdx, useOrdinal, use.id, output);
logSubagentHeartbeat({
job_id: ctx.id,
event: 'tool_result',
@@ -810,7 +820,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {
const errText = e instanceof Error
? (e.stack ?? e.message)
: String(e);
- await persistToolExecFailed(engine, ctx.id, assistantIdx, use.id, toolName, use.input, errText);
+ await persistToolExecFailed(engine, ctx.id, assistantIdx, useOrdinal, use.id, toolName, use.input, errText);
logSubagentHeartbeat({
job_id: ctx.id,
event: 'tool_failed',
@@ -1073,6 +1083,20 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResu
// circuit silently breaks and the tool re-executes. Pinned by
// test/e2e/subagent-crash-replay-multi-provider.test.ts.
const candidateId = randomUUIDv7();
+ // #4155 — tool_use_id stores the RAW provider id, which is NOT unique
+ // per job: some providers (claude-cli) hand back short, repeating ids
+ // (e.g. "toolu_01" on every turn, since each `claude -p` (print mode)
+ // call is a fresh subprocess replayed from an id-stripped transcript).
+ // NOTE: spell it `-p`, not the long form — scripts/generate-flag-registry.ts
+ // harvests flag-shaped literals out of comments too, and the long form
+ // lands in the generated registry as a flag `jobs` does not accept.
+ // The former job-wide `uniq_subagent_tools_use_id UNIQUE (job_id,
+ // tool_use_id)` constraint encoded the false assumption that provider
+ // ids are job-unique; a reuse collided (it was never this INSERT's
+ // conflict target) and dead-lettered the job. Migration v131 dropped
+ // it — row identity is (job_id, message_idx, ordinal), and every
+ // reader resolves an execution by (message_idx, tool_use_id) or by
+ // gbrain_tool_use_id, never by tool_use_id alone.
const rows = await engine.executeRaw<{ gbrain_tool_use_id: string }>(
`INSERT INTO subagent_tool_executions
(job_id, message_idx, tool_use_id, tool_name, input, status, schema_version, ordinal, gbrain_tool_use_id, provider_id)
@@ -1199,15 +1223,29 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileRes
};
});
- // Settled executions, looked up by (assistant message_idx, provider
- // tool_use_id) with an ordinal-position fallback for legacy rows.
+ // Settled executions, three lookup structures:
+ // - execByOrdinal: rows keyed by their PERSISTED (message_idx, ordinal) —
+ // the true D11 row identity. The block position callIdx equals the
+ // ordinal stamped at first observation, so this survives both same-id
+ // repeats within a turn and slot shift when an earlier call never got
+ // a ledger row.
+ // - execByKey: (message_idx, tool_use_id) — exact whenever the turn's raw
+ // ids are unique (single-value: last-write-wins only for the same-id-
+ // twice shape, which execByOrdinal already resolves first).
+ // - legacyByMsg: ordinal=NULL rows (pre-stamping writes) in block order,
+ // for the positional fallback.
+ const execByOrdinal = new Map<string, PersistedToolExec>();
const execByKey = new Map<string, PersistedToolExec>();
- const execByMsg = new Map<number, PersistedToolExec[]>();
+ const legacyByMsg = new Map<number, PersistedToolExec[]>();
for (const t of priorTools) {
execByKey.set(`${t.message_idx}:${t.tool_use_id}`, t);
- const arr = execByMsg.get(t.message_idx) ?? [];
- arr.push(t);
- execByMsg.set(t.message_idx, arr);
+ if (t.ordinal != null) {
+ execByOrdinal.set(`${t.message_idx}:${t.ordinal}`, t);
+ } else {
+ const arr = legacyByMsg.get(t.message_idx) ?? [];
+ arr.push(t);
+ legacyByMsg.set(t.message_idx, arr);
+ }
}
let maxIdx = work.reduce((mx, w) => Math.max(mx, w.message_idx), -1);
@@ -1229,15 +1267,34 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileRes
const next = work[i + 1];
if (next && next.role === 'user' && next.blocks.some(b => b.type === 'tool-result')) continue;
+ // Ids that repeat WITHIN this turn are ambiguous as a lookup key — the
+ // single-value execByKey map is last-write-wins for them, so the exact-id
+ // fallback below is disabled for those ids (ordinal identity only).
+ const idCounts = new Map<string, number>();
+ for (const c of toolCalls) idCounts.set(c.toolCallId, (idCounts.get(c.toolCallId) ?? 0) + 1);
+
const results: ChatBlock[] = [];
for (let callIdx = 0; callIdx < toolCalls.length; callIdx++) {
const call = toolCalls[callIdx];
- // Prefer an exact (message_idx, provider tool_use_id) match. The
- // positional fallback is used only when the row at that ordinal is for
- // the SAME tool, so a missing row can't mis-attribute a sibling's output.
- const fallback = execByMsg.get(msg.message_idx)?.[callIdx];
- const exec = execByKey.get(`${msg.message_idx}:${call.toolCallId}`)
- ?? (fallback && fallback.tool_name === call.toolName ? fallback : undefined);
+ // Row resolution order:
+ // 1. The persisted-ordinal row at this block position when its raw id
+ // matches the call — exact D11 identity (#4155: raw ids may repeat
+ // within a turn, and an earlier call without a ledger row must not
+ // shift a later row into its slot).
+ // 2. The exact (message_idx, tool_use_id) key — only when this turn
+ // uses the id ONCE (a repeated id makes the key ambiguous and the
+ // call must resolve by ordinal or not at all, else one row's
+ // outcome would be served to every call sharing the id).
+ // 3. The legacy (ordinal=NULL) positional row, only when it is for
+ // the SAME tool, so a missing row can't mis-attribute a sibling's
+ // output.
+ const stamped = execByOrdinal.get(`${msg.message_idx}:${callIdx}`);
+ const idIsUniqueInTurn = (idCounts.get(call.toolCallId) ?? 0) <= 1;
+ const legacyPositional = legacyByMsg.get(msg.message_idx)?.[callIdx];
+ const exec = (stamped && stamped.tool_use_id === call.toolCallId)
+ ? stamped
+ : (idIsUniqueInTurn ? execByKey.get(`${msg.message_idx}:${call.toolCallId}`) : undefined)
+ ?? (legacyPositional && legacyPositional.tool_name === call.toolName ? legacyPositional : undefined);
if (exec?.status === 'complete') {
results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output: exec.output ?? null });
continue;
@@ -1248,21 +1305,21 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileRes
}
const toolDef = toolDefs.find(t => t.name === call.toolName);
if (!toolDef) {
- await persistToolExecFailed(engine, jobId, msg.message_idx, call.toolCallId, call.toolName, call.input, `tool "${call.toolName}" is not in the registry for this subagent`);
+ await persistToolExecFailed(engine, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName, call.input, `tool "${call.toolName}" is not in the registry for this subagent`);
results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output: `tool "${call.toolName}" is not available`, isError: true });
continue;
}
if (exec?.status === 'pending' && !toolDef.idempotent) {
throw new Error(`non-idempotent tool "${call.toolName}" pending on resume; cannot safely re-run`);
}
- await persistToolExecPending(engine, jobId, msg.message_idx, call.toolCallId, call.toolName, call.input);
+ await persistToolExecPending(engine, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName, call.input);
try {
const output = await toolDef.execute(call.input, { engine, jobId, remote: true, signal });
- await persistToolExecComplete(engine, jobId, call.toolCallId, output);
+ await persistToolExecComplete(engine, jobId, msg.message_idx, callIdx, call.toolCallId, output);
results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output });
} catch (e) {
const errText = e instanceof Error ? (e.stack ?? e.message) : String(e);
- await persistToolExecFailed(engine, jobId, msg.message_idx, call.toolCallId, call.toolName, call.input, errText);
+ await persistToolExecFailed(engine, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName, call.input, errText);
results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output: errText, isError: true });
}
}
@@ -1451,7 +1508,7 @@ async function loadPriorMessages(engine: BrainEngine, jobId: number): Promise<Pe
async function loadPriorTools(engine: BrainEngine, jobId: number): Promise<PersistedToolExec[]> {
const rows = await engine.executeRaw<Record<string, unknown>>(
- `SELECT message_idx, tool_use_id, tool_name, input, status, output, error
+ `SELECT message_idx, ordinal, tool_use_id, tool_name, input, status, output, error
FROM subagent_tool_executions
WHERE job_id = $1
ORDER BY message_idx, COALESCE(ordinal, 0), id`,
@@ -1459,6 +1516,7 @@ async function loadPriorTools(engine: BrainEngine, jobId: number): Promise<Persi
);
return rows.map(r => ({
message_idx: r.message_idx as number,
+ ordinal: (r.ordinal as number | null) ?? null,
tool_use_id: r.tool_use_id as string,
tool_name: r.tool_name as string,
input: typeof r.input === 'string' ? JSON.parse(r.input) : r.input,
@@ -1494,6 +1552,8 @@ async function persistToolExecPending(
engine: BrainEngine,
jobId: number,
messageIdx: number,
+ /** 0-based tool_use block position within the turn — the D11 ordinal. */
+ ordinal: number,
toolUseId: string,
toolName: string,
input: unknown,
@@ -1504,25 +1564,61 @@ async function persistToolExecPending(
// postgres.js .unsafe() (#2339 class; PGLite hides it). The ::text cast makes
// the text→jsonb parse produce a real jsonb object.
const jsonStr = typeof input === 'string' ? input : JSON.stringify(input);
+ // Two guards replace the former job-wide ON CONFLICT (job_id, tool_use_id)
+ // DO NOTHING (that constraint was dropped in migration v131, #4155 — raw
+ // provider ids may repeat across turns):
+ // 1. NOT EXISTS, restricted to LEGACY ordinal=NULL rows, preserves the
+ // DO NOTHING semantics against rows that predate ordinal stamping
+ // (they never trip a conflict target). Stamped rows are governed by
+ // guard 2 alone, so two distinct same-turn calls that share a raw id
+ // each keep their own row.
+ // 2. ON CONFLICT on the stable-id constraint (job_id, message_idx,
+ // ordinal) is the constraint-backed backstop for the residual race —
+ // a lease bounds honest workers to one owner per job, but an expired
+ // job can be reclaimed while a partitioned old worker still writes.
await engine.executeRaw(
- `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status)
- VALUES ($1, $2, $3, $4, $5::text::jsonb, 'pending')
- ON CONFLICT (job_id, tool_use_id) DO NOTHING`,
- [jobId, messageIdx, toolUseId, toolName, jsonStr],
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, ordinal)
+ SELECT $1, $2, $3, $4, $5::text::jsonb, 'pending', $6
+ WHERE NOT EXISTS (
+ SELECT 1 FROM subagent_tool_executions
+ WHERE job_id = $1 AND message_idx = $2 AND tool_use_id = $3
+ AND ordinal IS NULL
+ )
+ ON CONFLICT (job_id, message_idx, ordinal) DO NOTHING`,
+ [jobId, messageIdx, toolUseId, toolName, jsonStr, ordinal],
);
}
async function persistToolExecComplete(
engine: BrainEngine,
jobId: number,
+ messageIdx: number,
+ /** 0-based tool_use block position within the turn — the D11 ordinal. */
+ ordinal: number,
toolUseId: string,
output: unknown,
): Promise<void> {
+ // Scoped by message_idx: raw provider tool_use_ids may repeat across turns
+ // (#4155), so (job_id, tool_use_id) alone could also update a sibling
+ // turn's row. Targets exactly ONE row: the call's own ordinal first, then a
+ // legacy ordinal=NULL row — never an already-COMPLETE row (the ordinal IS
+ // NULL disjunct would otherwise let a legacy settled sibling's output be
+ // silently overwritten), and never a same-id SIBLING at another ordinal: a
+ // call's own row is always reachable via its ordinal (persistToolExecPending
+ // stamps the same value) or via the legacy NULL, so a broader status-based
+ // disjunct could only ever capture a sibling's row.
await engine.executeRaw(
`UPDATE subagent_tool_executions
- SET status = 'complete', output = $3::text::jsonb, ended_at = now()
- WHERE job_id = $1 AND tool_use_id = $2`,
- [jobId, toolUseId, typeof output === 'string' ? output : JSON.stringify(output)],
+ SET status = 'complete', output = $4::text::jsonb, ended_at = now()
+ WHERE id = (
+ SELECT id FROM subagent_tool_executions
+ WHERE job_id = $1 AND message_idx = $2 AND tool_use_id = $3
+ AND (ordinal = $5 OR ordinal IS NULL)
+ AND status <> 'complete'
+ ORDER BY CASE WHEN ordinal = $5 THEN 0 ELSE 1 END, id
+ LIMIT 1
+ )`,
+ [jobId, messageIdx, toolUseId, typeof output === 'string' ? output : JSON.stringify(output), ordinal],
);
}
@@ -1530,6 +1626,8 @@ async function persistToolExecFailed(
engine: BrainEngine,
jobId: number,
messageIdx: number,
+ /** 0-based tool_use block position within the turn — the D11 ordinal. */
+ ordinal: number,
toolUseId: string,
toolName: string,
input: unknown,
@@ -1537,13 +1635,45 @@ async function persistToolExecFailed(
): Promise<void> {
// INSERT-or-UPDATE to failed — covers both "no pending row yet" (tool
// rejected upfront) and "pending row exists" (tool threw mid-execute).
- await engine.executeRaw(
- `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, error, ended_at)
- VALUES ($1, $2, $3, $4, $5::text::jsonb, 'failed', $6, now())
- ON CONFLICT (job_id, tool_use_id) DO UPDATE
- SET status = 'failed', error = EXCLUDED.error, ended_at = now()`,
- [jobId, messageIdx, toolUseId, toolName, typeof input === 'string' ? input : JSON.stringify(input), error],
+ // UPDATE-then-INSERT replaces the former ON CONFLICT (job_id, tool_use_id)
+ // upsert (that job-wide unique was dropped in migration v131, #4155).
+ // The UPDATE targets exactly ONE row (own ordinal first, then legacy
+ // ordinal=NULL) and NEVER a row that already settled complete — without the
+ // status guard the ordinal IS NULL disjunct would let a late failure
+ // downgrade a legacy settled row, corrupting the ledger replay trusts. No
+ // status-based disjunct: a call's own row is always reachable via its
+ // ordinal or the legacy NULL, so an `OR status = 'pending'` arm could only
+ // ever capture a same-id SIBLING's pending row at another ordinal (e.g. an
+ // unregistered-tool failure with no own row stealing the sibling's slot).
+ // The INSERT leg carries the stable-id ON CONFLICT backstop for the
+ // residual zombie-worker race, mirroring persistToolExecPending; its
+ // conflict update is predicated on the SAME tool_use_id and a non-complete
+ // row for the same reason.
+ const updated = await engine.executeRaw<{ id: number }>(
+ `UPDATE subagent_tool_executions
+ SET status = 'failed', error = $4, ended_at = now()
+ WHERE id = (
+ SELECT id FROM subagent_tool_executions
+ WHERE job_id = $1 AND message_idx = $2 AND tool_use_id = $3
+ AND (ordinal = $5 OR ordinal IS NULL)
+ AND status <> 'complete'
+ ORDER BY CASE WHEN ordinal = $5 THEN 0 ELSE 1 END, id
+ LIMIT 1
+ )
+ RETURNING id`,
+ [jobId, messageIdx, toolUseId, error, ordinal],
);
+ if (updated.length === 0) {
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, error, ended_at, ordinal)
+ VALUES ($1, $2, $3, $4, $5::text::jsonb, 'failed', $6, now(), $7)
+ ON CONFLICT (job_id, message_idx, ordinal) DO UPDATE
+ SET status = 'failed', error = EXCLUDED.error, ended_at = now()
+ WHERE subagent_tool_executions.tool_use_id = EXCLUDED.tool_use_id
+ AND subagent_tool_executions.status <> 'complete'`,
+ [jobId, messageIdx, toolUseId, toolName, typeof input === 'string' ? input : JSON.stringify(input), error, ordinal],
+ );
+ }
}
// ── Internal: helpers ───────────────────────────────────────
diff --git a/src/core/minions/transcript.ts b/src/core/minions/transcript.ts
index fee76e3800..0083bddd5b 100644
--- a/src/core/minions/transcript.ts
+++ b/src/core/minions/transcript.ts
@@ -36,6 +36,8 @@ export interface SubagentToolExecRow {
id: number;
job_id: number;
message_idx: number;
+ /** D11 stable ordinal (per-turn tool-call position). NULL on legacy rows. */
+ ordinal: number | null;
tool_use_id: string;
tool_name: string;
input: unknown;
@@ -58,7 +60,7 @@ export async function loadTranscriptRows(
[jobId],
);
const toolRows = await engine.executeRaw<Record<string, unknown>>(
- `SELECT id, job_id, message_idx, tool_use_id, tool_name, input, status, output, error
+ `SELECT id, job_id, message_idx, ordinal, tool_use_id, tool_name, input, status, output, error
FROM subagent_tool_executions
WHERE job_id = $1
ORDER BY id ASC`,
@@ -99,6 +101,7 @@ function normalizeTool(row: Record<string, unknown>): SubagentToolExecRow {
id: row.id as number,
job_id: row.job_id as number,
message_idx: row.message_idx as number,
+ ordinal: (row.ordinal as number | null) ?? null,
tool_use_id: row.tool_use_id as string,
tool_name: row.tool_name as string,
input,
@@ -116,7 +119,7 @@ export interface RenderTranscriptOpts {
/**
* Render messages + tool executions to markdown. Message order is
* authoritative; tool rows are spliced under their owning assistant message
- * by tool_use_id.
+ * by (message_idx, tool_use_id) — raw provider ids may repeat across turns.
*/
export function renderTranscript(
messages: SubagentMessageRow[],
@@ -124,9 +127,21 @@ export function renderTranscript(
opts: RenderTranscriptOpts = {},
): string {
const maxOut = opts.maxOutputBytes ?? 4096;
- const toolById = new Map<string, SubagentToolExecRow>(
- tools.map(t => [t.tool_use_id, t]),
+ // Keyed by (message_idx, tool_use_id) — raw provider tool_use_ids may
+ // repeat across turns (#4155: replay-style providers like claude-cli reuse
+ // the same short id on every turn), so tool_use_id alone would collapse
+ // distinct executions onto one row and mis-attribute status/output.
+ const toolByMsgAndId = new Map<string, SubagentToolExecRow>(
+ tools.map(t => [`${t.message_idx}:${t.tool_use_id}`, t]),
);
+ // Ordinal-first resolution for stamped rows: within one turn a raw id can
+ // even repeat (the composite id map is last-write-wins for that shape);
+ // the persisted D11 ordinal equals the tool_use block position, which is
+ // exact.
+ const toolByMsgAndOrdinal = new Map<string, SubagentToolExecRow>();
+ for (const t of tools) {
+ if (t.ordinal != null) toolByMsgAndOrdinal.set(`${t.message_idx}:${t.ordinal}`, t);
+ }
const out: string[] = [];
out.push('# Subagent transcript', '');
@@ -141,6 +156,13 @@ export function renderTranscript(
if (first.model) out.push(`- model: ${first.model}`);
out.push('');
+ // tool_result blocks live in the user message FOLLOWING the owning
+ // assistant message; track the nearest preceding assistant idx so their
+ // ownership check uses that turn's composite key (a job-wide id set would
+ // wrongly suppress a result whose own turn has no execution row when a
+ // DIFFERENT turn reused the id).
+ let prevAssistantIdx: number | null = null;
+
for (const msg of messages) {
out.push(`## Message ${msg.message_idx} — ${msg.role}`);
if (msg.tokens_in != null || msg.tokens_out != null) {
@@ -153,10 +175,23 @@ export function renderTranscript(
}
out.push('');
+ // Ids repeated WITHIN this message make the (message_idx, raw id) key
+ // ambiguous — resolution for those falls to the stamped ordinal only.
+ const idCounts = new Map<string, number>();
+ for (const b of msg.content_blocks) {
+ if (b.type === 'tool_use' && typeof b.id === 'string') {
+ idCounts.set(b.id, (idCounts.get(b.id) ?? 0) + 1);
+ }
+ }
+ let toolUseOrdinal = 0; // tool_use block position within this message
for (const block of msg.content_blocks) {
- renderBlock(block, toolById, maxOut, out);
+ const blockOrdinal = block.type === 'tool_use' ? toolUseOrdinal++ : -1;
+ const idIsUniqueInMsg = !(block.type === 'tool_use' && typeof block.id === 'string'
+ && (idCounts.get(block.id) ?? 0) > 1);
+ renderBlock(block, msg.message_idx, blockOrdinal, idIsUniqueInMsg, prevAssistantIdx, toolByMsgAndId, toolByMsgAndOrdinal, maxOut, out);
}
out.push('');
+ if (msg.role === 'assistant') prevAssistantIdx = msg.message_idx;
}
return out.join('\n').replace(/\n{3,}/g, '\n\n');
@@ -164,7 +199,14 @@ export function renderTranscript(
function renderBlock(
block: ContentBlock,
- toolById: Map<string, SubagentToolExecRow>,
+ messageIdx: number,
+ /** tool_use block position within the message (-1 for non-tool_use blocks). */
+ blockOrdinal: number,
+ /** false when this tool_use block's id repeats within the message. */
+ idIsUniqueInMsg: boolean,
+ prevAssistantIdx: number | null,
+ toolByMsgAndId: Map<string, SubagentToolExecRow>,
+ toolByMsgAndOrdinal: Map<string, SubagentToolExecRow>,
maxOutputBytes: number,
out: string[],
): void {
@@ -179,7 +221,15 @@ function renderBlock(
const inputStr = safeJson(block.input, 2);
out.push(`**tool_use** \`${name}\` (id=\`${block.id ?? '?'}\`)`);
out.push('```json', inputStr, '```');
- const toolRow = block.id && typeof block.id === 'string' ? toolById.get(block.id) : undefined;
+ // Execution rows are written with the OWNING assistant message's idx.
+ // Resolve by the stamped (message_idx, ordinal) first — validated by the
+ // raw id — then by (message_idx, raw id) for legacy rows.
+ const stamped = toolByMsgAndOrdinal.get(`${messageIdx}:${blockOrdinal}`);
+ const toolRow = (stamped && typeof block.id === 'string' && stamped.tool_use_id === block.id)
+ ? stamped
+ : (idIsUniqueInMsg && block.id && typeof block.id === 'string'
+ ? toolByMsgAndId.get(`${messageIdx}:${block.id}`)
+ : undefined);
if (toolRow) {
out.push(`→ status: **${toolRow.status}**`);
if (toolRow.status === 'complete') {
@@ -197,9 +247,14 @@ function renderBlock(
if (block.type === 'tool_result') {
// Most tool_result blocks live inside user messages echoing back the
// assistant's tool_use. We skip them here because the owning tool_use
- // block already rendered the execution row. If the user message carries
- // a raw tool_result with no matching tool_use (rare), dump it raw.
- if (!block.tool_use_id || !toolById.has(block.tool_use_id as string)) {
+ // block already rendered the execution row. Ownership is checked against
+ // the nearest PRECEDING assistant turn's key — raw ids may repeat across
+ // turns, so a job-wide id match could suppress a result whose own turn
+ // has no execution row. If no owning row exists (rare), dump it raw.
+ const owned = prevAssistantIdx !== null
+ && typeof block.tool_use_id === 'string'
+ && toolByMsgAndId.has(`${prevAssistantIdx}:${block.tool_use_id}`);
+ if (!owned) {
out.push('**tool_result** (no matching tool_use in this transcript)');
out.push('```json', truncate(safeJson(block.content, 2), maxOutputBytes), '```');
out.push('');
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index 156f661015..b6bea82f31 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -964,6 +964,9 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// allowedSources for federated reads, matching legacy HTTP transport.
sourceId,
allowedSources,
+ // #3242 parity with src/mcp/http-transport.ts: only the historical
+ // no-grant floor may widen unqualified reads to the federated set.
+ hasSourceGrant: permissions?.source_id != null,
takesHoldersAllowList,
} as CoreAuthInfo as SdkAuthInfo;
}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 742000c33d..652e1d9b3d 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -165,6 +165,15 @@ export interface AuthInfo {
* `gbrain auth scope-client`.
*/
sourceId?: string;
+ /**
+ * #3242 (serve --http parity): distinguishes an operator-set source scope
+ * from the historical no-grant 'default' floor. `false` ONLY for a legacy
+ * bearer token whose `access_tokens.permissions.source_id` is absent —
+ * the one case whose unqualified reads may widen to the federated set.
+ * `true` (or undefined, e.g. OAuth clients) never widens. Mirrors
+ * `AuthResult.hasSourceGrant` in `src/mcp/http-transport.ts`.
+ */
+ hasSourceGrant?: boolean;
/**
* v0.34.1 (#876): array of source ids this OAuth client may READ
* from (federation). Sourced from `oauth_clients.federated_read`.
diff --git a/src/core/path-confine.ts b/src/core/path-confine.ts
index 9f7eced919..b6f3374c13 100644
--- a/src/core/path-confine.ts
+++ b/src/core/path-confine.ts
@@ -20,7 +20,7 @@
*/
import { realpathSync, existsSync, type Stats } from 'fs';
-import { resolve as resolvePath, relative, isAbsolute, dirname, basename, join } from 'path';
+import { resolve as resolvePath, relative, isAbsolute, dirname, basename, join, sep } from 'path';
/**
* Symlink-safe path confinement: realpath BOTH sides, then a separator-aware
@@ -41,8 +41,26 @@ export function isPathContained(child: string, parent: string): boolean {
} catch {
return false; // missing / unresolvable path → not contained
}
- // Append a separator so /foo doesn't match /foobar.
- const parentWithSep = resolvedParent.endsWith('/') ? resolvedParent : resolvedParent + '/';
+ return resolvedPrefixContained(resolvedChild, resolvedParent, sep);
+}
+
+/**
+ * Pure separator-aware prefix check over ALREADY-RESOLVED paths — the exact
+ * logic that regressed on Windows (#3643/#4103: a hardcoded '/' suffix made
+ * every real backslash subdirectory fail the prefix test). Exported so the
+ * win32 shapes (drive-letter roots, backslash subtrees, UNC shares) are
+ * testable on POSIX CI, where realpathSync can never produce them
+ * (gbrain#4103 review requirement — no Windows runner exists).
+ */
+export function resolvedPrefixContained(
+ resolvedChild: string,
+ resolvedParent: string,
+ sepChar: string,
+): boolean {
+ // Append the OS separator so /foo doesn't match /foobar. `sep`, not a
+ // hardcoded '/': realpathSync returns backslash paths on Windows, so a '/'
+ // suffix would make the prefix test fail for every real subdirectory.
+ const parentWithSep = resolvedParent.endsWith(sepChar) ? resolvedParent : resolvedParent + sepChar;
return resolvedChild === resolvedParent || resolvedChild.startsWith(parentWithSep);
}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index d38e158e7c..27438b5fa4 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -78,7 +78,7 @@ import type {
import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { executeRawJsonb, type SqlValue } from './sql-query.ts';
import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
-import { PAGE_SORT_SQL } from './types.ts';
+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 } from './search/sql-ranking.ts';
@@ -5149,8 +5149,16 @@ export class PGLiteEngine implements BrainEngine {
AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
) as missing_embeddings,
(SELECT count(*) FROM links) as link_count,
+ (SELECT count(*) FROM entity_pages) as entity_page_count,
+ -- gbrain#4153 consistency: an inbound link counts toward coverage
+ -- only when its SOURCE page is live — the same endpoint-liveness rule
+ -- the islanded predicate below applies, so an entity whose only
+ -- inbound link comes from a soft-deleted page can't read as covered
+ -- AND islanded in one payload.
(SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id))::float /
+ WHERE EXISTS (SELECT 1 FROM links l
+ JOIN pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = e.id AND src.deleted_at IS NULL))::float /
GREATEST((SELECT count(*) FROM entity_pages), 1)::float as link_coverage,
(SELECT count(*) FROM entity_pages e
WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
@@ -5175,10 +5183,20 @@ export class PGLiteEngine implements BrainEngine {
// Archive (raw/), generated, and daily-log pages are not expected to
// participate in the curated graph. Filtered in TS because the policy
// includes per-brain config overrides.
+ // gbrain#4153: endpoint liveness in BOTH directions — an inbound link
+ // only counts when its SOURCE page is live (the invariant
+ // findOrphanPages documents), and an outbound link only counts when its
+ // TARGET is live. Without this, get_health's orphan_pages disagreed with
+ // `gbrain orphans` whenever a soft-deleted page still linked to (or was
+ // linked from) a live one.
const { rows: pageScopeRows } = await this.db.query(`
SELECT p.slug,
- (NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
- AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)) as islanded,
+ (NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = p.id AND src.deleted_at IS NULL)
+ AND NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages tgt ON tgt.id = l.to_page_id
+ WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL)) as islanded,
EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
FROM pages p
WHERE p.deleted_at IS NULL
@@ -5230,8 +5248,12 @@ export class PGLiteEngine implements BrainEngine {
missing_embeddings: Number(r.missing_embeddings),
brain_score: brainScore,
dead_links: deadLinks,
- link_coverage: Number(r.link_coverage),
- timeline_coverage: Number(r.timeline_coverage),
+ entity_page_count: Number(r.entity_page_count),
+ // gbrain#4147: below the small-N floor the ratio is statistically
+ // meaningless (0/0 used to read as a hard 0%), so it reports null and
+ // consumers suppress both the percentage and its remediation actions.
+ link_coverage: Number(r.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(r.link_coverage) : null,
+ timeline_coverage: Number(r.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(r.timeline_coverage) : null,
most_connected: (connected as { slug: string; link_count: number }[]).map(c => ({
slug: c.slug,
link_count: Number(c.link_count),
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index e20f11eddb..c4ecbd6703 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -559,6 +559,11 @@ CREATE TABLE IF NOT EXISTS subagent_messages (
CREATE INDEX IF NOT EXISTS idx_subagent_messages_job ON subagent_messages (job_id, message_idx);
CREATE INDEX IF NOT EXISTS idx_subagent_messages_provider ON subagent_messages (job_id, provider_id);
+-- tool_use_id holds the RAW provider id and is deliberately NOT unique per
+-- job (#4155): replay-style providers reuse the same short id on every turn.
+-- Row identity is (job_id, message_idx, ordinal); readers key executions by
+-- (message_idx, tool_use_id), never by tool_use_id alone. The former job-wide
+-- unique constraint uniq_subagent_tools_use_id was dropped in migration v131.
CREATE TABLE IF NOT EXISTS subagent_tool_executions (
id BIGSERIAL PRIMARY KEY,
job_id BIGINT NOT NULL REFERENCES minion_jobs(id) ON DELETE CASCADE,
@@ -579,7 +584,6 @@ CREATE TABLE IF NOT EXISTS subagent_tool_executions (
gbrain_tool_use_id UUID,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
ended_at TIMESTAMPTZ,
- CONSTRAINT uniq_subagent_tools_use_id UNIQUE (job_id, tool_use_id),
CONSTRAINT subagent_tool_executions_stable_id UNIQUE (job_id, message_idx, ordinal),
CONSTRAINT chk_subagent_tools_status CHECK (status IN ('pending','complete','failed'))
);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index db9039aed6..d44fce9f0f 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -73,7 +73,7 @@ import type {
EmotionalWeightInputRow, EmotionalWeightWriteRow,
EnrichCandidatesOpts, EnrichCandidate,
} from './types.ts';
-import { GBrainError, PAGE_SORT_SQL } from './types.ts';
+import { GBrainError, PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
import * as db from './db.ts';
import { ConnectionManager, DEFAULT_DIRECT_POOL_SIZE } from './connection-manager.ts';
@@ -5066,8 +5066,16 @@ export class PostgresEngine implements BrainEngine {
AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
) as missing_embeddings,
(SELECT count(*) FROM links) as link_count,
+ (SELECT count(*) FROM entity_pages) as entity_page_count,
+ -- gbrain#4153 consistency: an inbound link counts toward coverage
+ -- only when its SOURCE page is live — the same endpoint-liveness rule
+ -- the islanded predicate below applies, so an entity whose only
+ -- inbound link comes from a soft-deleted page can't read as covered
+ -- AND islanded in one payload.
(SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id))::float /
+ WHERE EXISTS (SELECT 1 FROM links l
+ JOIN pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = e.id AND src.deleted_at IS NULL))::float /
GREATEST((SELECT count(*) FROM entity_pages), 1)::float as link_coverage,
(SELECT count(*) FROM entity_pages e
WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
@@ -5091,10 +5099,20 @@ export class PostgresEngine implements BrainEngine {
// Archive (raw/), generated, and daily-log pages are not expected to
// participate in the curated graph. Filtered in TS because the policy
// includes per-brain config overrides. PGLite path has the same logic.
+ // gbrain#4153: endpoint liveness in BOTH directions — an inbound link
+ // only counts when its SOURCE page is live (the invariant
+ // findOrphanPages documents), and an outbound link only counts when its
+ // TARGET is live. Without this, get_health's orphan_pages disagreed with
+ // `gbrain orphans` whenever a soft-deleted page still linked to (or was
+ // linked from) a live one.
const pageScopeRows = await sql<{ slug: string; islanded: boolean; has_timeline: boolean }[]>`
SELECT p.slug,
- (NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
- AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)) as islanded,
+ (NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = p.id AND src.deleted_at IS NULL)
+ AND NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages tgt ON tgt.id = l.to_page_id
+ WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL)) as islanded,
EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
FROM pages p
WHERE p.deleted_at IS NULL
@@ -5144,8 +5162,12 @@ export class PostgresEngine implements BrainEngine {
missing_embeddings: Number(h.missing_embeddings),
brain_score: brainScore,
dead_links: deadLinks,
- link_coverage: Number(h.link_coverage),
- timeline_coverage: Number(h.timeline_coverage),
+ entity_page_count: Number(h.entity_page_count),
+ // gbrain#4147: below the small-N floor the ratio is statistically
+ // meaningless (0/0 used to read as a hard 0%), so it reports null and
+ // consumers suppress both the percentage and its remediation actions.
+ link_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.link_coverage) : null,
+ timeline_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.timeline_coverage) : null,
most_connected: (connected as unknown as { slug: string; link_count: number }[]).map(c => ({
slug: c.slug,
link_count: Number(c.link_count),
diff --git a/src/core/schema-embedded.ts b/src/core/schema-embedded.ts
index ea70a13101..e82e932b52 100644
--- a/src/core/schema-embedded.ts
+++ b/src/core/schema-embedded.ts
@@ -1066,6 +1066,14 @@ CREATE INDEX IF NOT EXISTS idx_subagent_messages_provider ON subagent_messages (
-- Two-phase tool execution ledger. Before tool call: INSERT status='pending'.
-- After success: UPDATE to 'complete' + output. On failure: 'failed' + error.
-- Replay re-runs 'pending' rows only if the tool is idempotent.
+--
+-- tool_use_id holds the RAW provider id and is deliberately NOT unique per
+-- job (#4155): replay-style providers (claude-cli spawns a fresh subprocess
+-- per turn from an id-stripped transcript) reuse the same short id on every
+-- turn. Row identity is (job_id, message_idx, ordinal); readers that resolve
+-- a tool_use block to its execution row must key by (message_idx, tool_use_id),
+-- never by tool_use_id alone. The former job-wide unique constraint
+-- uniq_subagent_tools_use_id was dropped in migration v131.
CREATE TABLE IF NOT EXISTS subagent_tool_executions (
id BIGSERIAL PRIMARY KEY,
job_id BIGINT NOT NULL REFERENCES minion_jobs(id) ON DELETE CASCADE,
@@ -1088,7 +1096,6 @@ CREATE TABLE IF NOT EXISTS subagent_tool_executions (
gbrain_tool_use_id UUID,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
ended_at TIMESTAMPTZ,
- CONSTRAINT uniq_subagent_tools_use_id UNIQUE (job_id, tool_use_id),
CONSTRAINT subagent_tool_executions_stable_id UNIQUE (job_id, message_idx, ordinal),
CONSTRAINT chk_subagent_tools_status CHECK (status IN ('pending','complete','failed'))
);
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index b022427a2e..18596b9ad6 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -403,6 +403,35 @@ export async function resolveSourceWithTier(
return { source_id: 'default', tier: 'seed_default' };
}
+/**
+ * #3242 parity: the widening set a TRANSPORT should attach for a caller that
+ * carries no operator source grant, or `undefined` when the caller must keep
+ * its scalar scope.
+ *
+ * The gate is deliberately `hasSourceGrant === false` rather than falsy.
+ * `false` is set only for a legacy bearer token whose
+ * `access_tokens.permissions.source_id` is absent — the historical no-grant
+ * floor. `true` is an operator-set scope and `undefined` is an OAuth client,
+ * and neither may widen, so a falsy check would hand OAuth clients the
+ * federated set.
+ *
+ * Resolution is best-effort by design: a source table that cannot be read
+ * leaves the scalar scope standing rather than failing the request, matching
+ * the surrounding transport behaviour.
+ */
+export async function noGrantFederatedScope(
+ engine: BrainEngine,
+ hasSourceGrant: boolean | undefined,
+ sourceId: string | undefined,
+): Promise<string[] | undefined> {
+ if (hasSourceGrant !== false || !sourceId) return undefined;
+ try {
+ return await localFederatedSourceIds(engine, sourceId, 'seed_default');
+ } catch {
+ return undefined;
+ }
+}
+
/**
* #2561 — compute the federated read scope for an UNQUALIFIED local CLI call.
*
@@ -422,8 +451,12 @@ export async function resolveSourceWithTier(
*
* Archived sources are excluded (same rationale as pickSoleNonDefaultSource);
* the archived column is v34+, so fall back to the un-archived query on older
- * brains. Callers put the result on `OperationContext.localFederatedSourceIds`
- * — consumed only by `federatedSearchScope` and only when `remote === false`.
+ * brains. Callers put the result on `OperationContext.localFederatedSourceIds`,
+ * consumed by `federatedSearchScope`. Two caller classes exist: local CLI/MCP
+ * stdio (`remote === false`, the original #2561 path) and — via
+ * `noGrantFederatedScope` below — remote transports for a legacy no-grant
+ * bearer token (#3242 parity), where the transport itself decides the caller
+ * may see the federated floor.
*/
export async function localFederatedSourceIds(
engine: BrainEngine,
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
index 175c82088d..7a3a89c241 100644
--- a/src/core/sync-git.ts
+++ b/src/core/sync-git.ts
@@ -388,11 +388,28 @@ export function createSyncBaselineCommit(repoPath: string): void {
* returns backslash paths there, and a literal `rootReal + '/'` prefix can
* never match one. A sibling (`root-evil`) is rejected because `relative`
* yields `../root-evil`, and a cross-drive path because it yields an absolute.
+ * On Windows this intentionally follows the platform path semantics exposed by
+ * `win32.relative`, including case-insensitive segment matching; detecting rare
+ * per-directory case-sensitive NTFS siblings would require filesystem identity
+ * checks rather than a pure path check. (#4044/#4144)
*/
-export function isWithinRoot(childReal: string, rootReal: string): boolean {
+interface PathContainmentOps {
+ relative(from: string, to: string): string;
+ isAbsolute(path: string): boolean;
+ sep: string;
+}
+
+const nativePathContainmentOps: PathContainmentOps = { relative, isAbsolute, sep };
+
+export function isWithinRoot(
+ childReal: string,
+ rootReal: string,
+ pathOps: PathContainmentOps = nativePathContainmentOps,
+): boolean {
if (childReal === rootReal) return true;
- const rel = relative(rootReal, childReal);
- return rel !== '' && rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
+ const rel = pathOps.relative(rootReal, childReal);
+ if (rel === '') return true;
+ return rel !== '..' && !rel.startsWith('..' + pathOps.sep) && !pathOps.isAbsolute(rel);
}
/**
diff --git a/src/core/sync.ts b/src/core/sync.ts
index d6aa5c5d6b..a142c1a496 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -76,6 +76,7 @@ const CODE_EXTENSIONS = new Set<string>([
'.sh', '.bash',
'.css',
'.html', '.htm',
+ '.astro', '.svelte',
'.vue',
'.json',
'.yaml', '.yml',
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 905a3b0c8e..c05020e636 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -27,6 +27,7 @@ import { resolveCitations, type ParsedCitation } from './cite-render.ts';
import { resolveOwnerHolder } from '../owner-holder.ts';
import { resolveModel } from '../model-config.ts';
import { chat as gatewayChat, probeChatModel, type ChatResult } from '../ai/gateway.ts';
+import { getProviderCapabilities } from '../ai/capabilities.ts';
import { AIConfigError } from '../ai/errors.ts';
import { normalizeModelId } from '../model-id.ts';
import { hasAnthropicKey } from '../ai/anthropic-key.ts';
@@ -227,9 +228,22 @@ const OPENAI_CHAT_SNAPSHOT_RE = /-chat(?:-|$)/i; // gpt-5-chat-latest, gpt-5.2-c
export function maxOutputTokensFor(modelStr: string): number {
const openaiReasoning =
OPENAI_REASONING_MODEL_RE.test(modelStr) && !OPENAI_CHAT_SNAPSHOT_RE.test(modelStr);
- return THINKING_BY_DEFAULT_MODEL_RE.test(modelStr) || openaiReasoning
- ? THINKING_DEFAULT_MAX_OUTPUT_TOKENS
- : DEFAULT_MAX_OUTPUT_TOKENS;
+ if (THINKING_BY_DEFAULT_MODEL_RE.test(modelStr) || openaiReasoning) {
+ return THINKING_DEFAULT_MAX_OUTPUT_TOKENS;
+ }
+ // Recipe-declared thinking-by-default (gbrain#4172, e.g. DeepSeek v4):
+ // keyed on the capability, not a model-name regex, so a provider's model
+ // renames don't silently drop the headroom. Reasoning bills as output and
+ // counts against max_tokens; without headroom the 4000 cap is spent on
+ // reasoning and think returns truncated/empty JSON.
+ try {
+ if (getProviderCapabilities(modelStr).supportsThinking) {
+ return THINKING_DEFAULT_MAX_OUTPUT_TOKENS;
+ }
+ } catch {
+ // Unknown provider / chat-less recipe — keep the conservative default.
+ }
+ return DEFAULT_MAX_OUTPUT_TOKENS;
}
function inferIntent(question: string, anchor?: string): string {
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index 7d0cf77ec0..103c232563 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -55,6 +55,13 @@ export interface TranscriptsIngestOpts {
sourceId: string;
/** Embedding opt-in (default OFF: bulk imports defer to the embed backfill). */
embed?: boolean;
+ /**
+ * gbrain#4149: explicit byte-cap OVERRIDE threaded to every adapter's
+ * parse. Undefined = each adapter keeps its own format-specific default
+ * (Hermes 512MB store guard, 50MB jsonl cap, ...) — the override exists
+ * for legitimate oversized stores, not to replace the defaults.
+ */
+ maxBytes?: number;
activePack?: IngestActivePack;
/** Test seam for the redaction user-pattern file. */
userPatternsPath?: string;
@@ -194,7 +201,11 @@ export async function runTranscriptsIngest(
}
fileOutcome.format = detected.adapter.format;
- const gen = detected.adapter.parse(path);
+ // gbrain#4149: thread the explicit cap override; omit the opts object
+ // entirely when unset so adapters keep their native defaults.
+ const gen = opts.maxBytes != null
+ ? detected.adapter.parse(path, { maxBytes: opts.maxBytes })
+ : detected.adapter.parse(path);
try {
let step = await gen.next();
while (!step.done) {
diff --git a/src/core/types.ts b/src/core/types.ts
index 88b0cc50cd..bb8f2e639b 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1487,6 +1487,14 @@ export interface BrainStats {
pages_by_type: Record<string, number>;
}
+/**
+ * gbrain#4147: minimum entity pages before the entity-scoped coverage ratios
+ * (link_coverage / timeline_coverage) are statistically worth reporting.
+ * Behavior: 0 entities → null (0/0 used to read as a hard 0%); 1..4 → null
+ * (a one-page "100% ± 0.0%" is noise, cf. #3945); >= 5 → the real ratio.
+ */
+export const MIN_ENTITY_PAGES_FOR_COVERAGE = 5;
+
export interface BrainHealth {
page_count: number;
/**
@@ -1523,10 +1531,24 @@ export interface BrainHealth {
* DELETEs can produce dangling references.
*/
dead_links: number;
- /** Fraction of entity pages (person/company) with >= 1 inbound link. */
- link_coverage: number;
- /** Fraction of entity pages (person/company) with >= 1 structured timeline entry. */
- timeline_coverage: number;
+ /**
+ * gbrain#4147: entity pages in the coverage denominator. Surfaced so
+ * consumers can tell "0% coverage" from "no entities to grade".
+ */
+ entity_page_count: number;
+ /**
+ * Entity link coverage, or null when entity_page_count is below
+ * MIN_ENTITY_PAGES_FOR_COVERAGE — a 0/0 or single-page ratio is
+ * statistically meaningless and used to read as a hard 0%/100%
+ * (gbrain#4147). Null means "not enough entity pages to grade"; consumers
+ * suppress the percentage AND its remediation actions.
+ */
+ link_coverage: number | null;
+ /**
+ * Fraction of entity pages (person/company) with >= 1 structured timeline
+ * entry, or null below the same small-N floor as link_coverage (#4147).
+ */
+ timeline_coverage: number | null;
/** Top 5 entities by total link count (in + out). */
most_connected: Array<{ slug: string; link_count: number }>;
/**
diff --git a/src/schema.sql b/src/schema.sql
index d4d08775a3..c5a65e41c0 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1062,6 +1062,14 @@ CREATE INDEX IF NOT EXISTS idx_subagent_messages_provider ON subagent_messages (
-- Two-phase tool execution ledger. Before tool call: INSERT status='pending'.
-- After success: UPDATE to 'complete' + output. On failure: 'failed' + error.
-- Replay re-runs 'pending' rows only if the tool is idempotent.
+--
+-- tool_use_id holds the RAW provider id and is deliberately NOT unique per
+-- job (#4155): replay-style providers (claude-cli spawns a fresh subprocess
+-- per turn from an id-stripped transcript) reuse the same short id on every
+-- turn. Row identity is (job_id, message_idx, ordinal); readers that resolve
+-- a tool_use block to its execution row must key by (message_idx, tool_use_id),
+-- never by tool_use_id alone. The former job-wide unique constraint
+-- uniq_subagent_tools_use_id was dropped in migration v131.
CREATE TABLE IF NOT EXISTS subagent_tool_executions (
id BIGSERIAL PRIMARY KEY,
job_id BIGINT NOT NULL REFERENCES minion_jobs(id) ON DELETE CASCADE,
@@ -1084,7 +1092,6 @@ CREATE TABLE IF NOT EXISTS subagent_tool_executions (
gbrain_tool_use_id UUID,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
ended_at TIMESTAMPTZ,
- CONSTRAINT uniq_subagent_tools_use_id UNIQUE (job_id, tool_use_id),
CONSTRAINT subagent_tool_executions_stable_id UNIQUE (job_id, message_idx, ordinal),
CONSTRAINT chk_subagent_tools_status CHECK (status IN ('pending','complete','failed'))
);
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 87df993fa4..bb1575f12b 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.13.0 -->
+<!-- gbrain-template-stamp: 0.46.14.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/advisor-ranking-eval.test.ts b/test/advisor-ranking-eval.test.ts
index 219f33a7f2..e819d740c5 100644
--- a/test/advisor-ranking-eval.test.ts
+++ b/test/advisor-ranking-eval.test.ts
@@ -36,7 +36,7 @@ const HEALTHY_STATS = {
}),
getHealth: async () => ({
page_count: 500, linkable_page_count: 500, embed_coverage: 0.99, stale_pages: 0, orphan_pages: 0, missing_embeddings: 0,
- brain_score: 95, dead_links: 0, link_coverage: 1, timeline_coverage: 1, most_connected: [],
+ entity_page_count: 10, brain_score: 95, dead_links: 0, link_coverage: 1, timeline_coverage: 1, most_connected: [],
embed_coverage_score: 35, link_density_score: 25, timeline_coverage_score: 15, no_orphans_score: 15, no_dead_links_score: 10,
}),
getConfig: async () => null,
@@ -56,7 +56,7 @@ const FIXTURES: Fixture[] = [
...HEALTHY_STATS,
getHealth: async () => ({
page_count: 500, linkable_page_count: 500, embed_coverage: 0.3, stale_pages: 0, orphan_pages: 12, missing_embeddings: 350,
- brain_score: 40, dead_links: 2, link_coverage: 0.2, timeline_coverage: 0.2, most_connected: [],
+ entity_page_count: 10, brain_score: 40, dead_links: 2, link_coverage: 0.2, timeline_coverage: 0.2, most_connected: [],
embed_coverage_score: 10, link_density_score: 5, timeline_coverage_score: 3, no_orphans_score: 2, no_dead_links_score: 8,
}),
},
diff --git a/test/ai/dims-qwen3-native.test.ts b/test/ai/dims-qwen3-native.test.ts
index 0c7bae4882..cd2837b261 100644
--- a/test/ai/dims-qwen3-native.test.ts
+++ b/test/ai/dims-qwen3-native.test.ts
@@ -63,3 +63,24 @@ describe('qwen3-embedding hyphenated hub-form ids (OpenRouter et al.)', () => {
.toEqual({ openaiCompatible: { dimensions: 1024 } });
});
});
+
+describe('gbrain#4123 — correctly-cased provider ids must match (providers are case-sensitive, our matching must not be)', () => {
+ test('HF/SiliconFlow-cased org-prefixed id pins dimensions at non-native dim', () => {
+ // The provider REQUIRES this exact casing (lowercase gets HTTP 500), so
+ // lowercasing the config is not a workaround — matching must normalize.
+ expect(dimsProviderOptions('openai-compatible', 'Qwen/Qwen3-Embedding-4B', 1536))
+ .toEqual({ openaiCompatible: { dimensions: 1536 } });
+ expect(dimsProviderOptions('openai-compatible', 'Qwen/Qwen3-Embedding-8B', 1536))
+ .toEqual({ openaiCompatible: { dimensions: 1536 } });
+ });
+
+ test('correctly-cased id at native width still suppresses the dimensions param', () => {
+ expect(dimsProviderOptions('openai-compatible', 'Qwen/Qwen3-Embedding-4B', 2560)).toBeUndefined();
+ expect(dimsProviderOptions('openai-compatible', 'Qwen/Qwen3-Embedding-0.6B', 1024)).toBeUndefined();
+ });
+
+ test('mixed-case ollama tag form also matches', () => {
+ expect(dimsProviderOptions('openai-compatible', 'Qwen3-Embedding:4B', 1024))
+ .toEqual({ openaiCompatible: { dimensions: 1024 } });
+ });
+});
diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts
index 549f7af237..1992bb8c27 100644
--- a/test/ai/gateway-chat.test.ts
+++ b/test/ai/gateway-chat.test.ts
@@ -45,14 +45,15 @@ describe('chat touchpoint — recipe registry', () => {
}
});
- test('only Anthropic and model-family-gated OpenRouter claim supports_prompt_cache', () => {
+ test('only Anthropic claims supports_prompt_cache outright; others gate per model', () => {
for (const r of listRecipes()) {
if (!r.touchpoints.chat) continue;
if (r.id === 'anthropic') {
expect(r.touchpoints.chat.supports_prompt_cache).toBe(true);
- } else if (r.id === 'openrouter') {
- // Family-scoped predicate (openai/* + anthropic/claude-*), never a
- // blanket true — see recipe-openrouter.test.ts for the model matrix.
+ } else if (r.id === 'openrouter' || r.id === 'google') {
+ // Scoped predicates, never a blanket true: OpenRouter by routed model
+ // family (openai/* + anthropic/claude-*), Google by Gemini version
+ // (implicit caching is 2.5+). Matrices live in each recipe's test.
expect(typeof r.touchpoints.chat.supports_prompt_cache).toBe('function');
} else {
expect(r.touchpoints.chat.supports_prompt_cache ?? false).toBe(false);
diff --git a/test/ai/recipe-google-prompt-cache.test.ts b/test/ai/recipe-google-prompt-cache.test.ts
new file mode 100644
index 0000000000..de5f35e56b
--- /dev/null
+++ b/test/ai/recipe-google-prompt-cache.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Google/Gemini prompt-cache capability is a per-model predicate, not a flat
+ * boolean: Gemini's implicit caching (the only kind the gateway can benefit
+ * from — it sends no cache directives on the Google path) is default-on for
+ * 2.5 and newer, and absent on 1.5/2.0.
+ */
+
+import { afterAll, describe, expect, test } from 'bun:test';
+import { getRecipe } from '../../src/core/ai/recipes/index.ts';
+import { googleSupportsPromptCache } from '../../src/core/ai/recipes/google.ts';
+import { getProviderCapabilities } from '../../src/core/ai/capabilities.ts';
+import {
+ chat,
+ configureGateway,
+ resetGateway,
+ __setGenerateTextTransportForTests,
+} from '../../src/core/ai/gateway.ts';
+
+afterAll(() => {
+ resetGateway();
+ __setGenerateTextTransportForTests(null);
+});
+
+describe('recipe: google prompt cache', () => {
+ test('chat touchpoint wires the predicate, not a boolean', () => {
+ const chat = getRecipe('google')!.touchpoints.chat!;
+ expect(chat.supports_prompt_cache).toBe(googleSupportsPromptCache);
+ });
+
+ test('2.5 and newer cache; older families and non-Gemini ids do not', () => {
+ expect(googleSupportsPromptCache('gemini-2.5-flash')).toBe(true);
+ expect(googleSupportsPromptCache('gemini-2.5-pro')).toBe(true);
+ expect(googleSupportsPromptCache('gemini-3-flash-preview')).toBe(true);
+ // Version digits trail the family name on this one — position varies.
+ expect(googleSupportsPromptCache('gemini-3.6-flash')).toBe(true);
+ // UNVERSIONED `-latest` aliases carry no digits but always point at
+ // current models.
+ expect(googleSupportsPromptCache('gemini-flash-latest')).toBe(true);
+ expect(googleSupportsPromptCache('gemini-pro-latest')).toBe(true);
+ // VERSIONED `-latest` aliases are judged by their version, not the alias:
+ // the real gemini-1.5-*-latest ids cache only via the explicit API
+ // (adversarial-review fix — the alias shortcut used to run first).
+ expect(googleSupportsPromptCache('gemini-1.5-pro-latest')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-1.5-flash-latest')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-2.5-pro-latest')).toBe(true);
+
+ expect(googleSupportsPromptCache('gemini-2.0-flash')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-2.0-flash-exp')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-1.5-pro')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-embedding-001')).toBe(false);
+ expect(googleSupportsPromptCache('gemma-3-27b-it')).toBe(false);
+ // Date/experiment suffixes are NOT versions: parseFloat('1206') >= 2.5
+ // must never promise a discount a 1.x-era experimental model lacked.
+ expect(googleSupportsPromptCache('gemini-exp-1206')).toBe(false);
+ expect(googleSupportsPromptCache('gemini-exp-0827')).toBe(false);
+ });
+
+ test('off-list passthrough ids resolve through the capability layer', () => {
+ // The recipe's `models` list is not enforced for native Google ids at the
+ // config plane, so a newer Gemini the list has not caught up to still has
+ // to be classified correctly.
+ expect(getProviderCapabilities('google:gemini-2.5-flash').supportsPromptCaching).toBe(true);
+ expect(getProviderCapabilities('google:gemini-1.5-pro').supportsPromptCaching).toBe(false);
+ });
+
+ test('cacheSystem on a caching Gemini injects ONLY anthropic-namespaced markers — nothing the google adapter acts on', async () => {
+ // The flip is functionally safe because Gemini caching is implicit: the
+ // gateway must not start sending Google-visible cache directives just
+ // because supports_prompt_cache is now true. Everything cache-shaped in
+ // the transport args has to stay in the `anthropic` namespace (which
+ // @ai-sdk/google ignores at every level) — no `providerOptions.google`
+ // cache keys, no cachedContent field. If this test starts failing, a
+ // change made the predicate drive REAL request mutation on the Google
+ // path; that needs the cache-MODE design (implicit vs explicit), not a
+ // silent flip.
+ resetGateway();
+ let captured: any;
+ __setGenerateTextTransportForTests(async (args: any) => {
+ captured = args;
+ return {
+ content: [{ type: 'text', text: 'ok' }],
+ finishReason: 'stop',
+ usage: { inputTokens: 1, outputTokens: 1 },
+ } as any;
+ });
+ configureGateway({
+ chat_model: 'google:gemini-2.5-flash',
+ env: { GOOGLE_GENERATIVE_AI_API_KEY: 'fake' },
+ });
+ await chat({
+ model: 'google:gemini-2.5-flash',
+ system: 'stable system prompt',
+ messages: [{ role: 'user', content: 'hello' }],
+ cacheSystem: true,
+ tools: [{ name: 'search', description: 'search', inputSchema: { type: 'object', properties: {} } }],
+ });
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+
+ // Cache markers exist (shared code path) but only under `anthropic`.
+ const po = captured.providerOptions ?? {};
+ const googleKeys = Object.keys(po.google ?? {});
+ expect(googleKeys.filter(k => /cache/i.test(k))).toEqual([]);
+ expect(JSON.stringify(po.google ?? {})).not.toMatch(/cache/i);
+ // System block marker stays anthropic-namespaced.
+ if (typeof captured.system === 'object' && captured.system?.providerOptions) {
+ expect(Object.keys(captured.system.providerOptions)).toEqual(['anthropic']);
+ }
+ // Tool-def marker stays anthropic-namespaced.
+ for (const tool of Object.values<any>(captured.tools ?? {})) {
+ if (tool?.providerOptions) {
+ expect(Object.keys(tool.providerOptions)).toEqual(['anthropic']);
+ }
+ }
+ // No Gemini explicit-cache surface is touched.
+ expect(captured.cachedContent).toBeUndefined();
+ });
+});
diff --git a/test/ai/recipe-openrouter.test.ts b/test/ai/recipe-openrouter.test.ts
index 1793a49653..2d77591d20 100644
--- a/test/ai/recipe-openrouter.test.ts
+++ b/test/ai/recipe-openrouter.test.ts
@@ -18,7 +18,7 @@ import {
openrouterSupportsPromptCache,
} from '../../src/core/ai/recipes/openrouter.ts';
import { defaultResolveAuth } from '../../src/core/ai/gateway.ts';
-import { assertTouchpoint } from '../../src/core/ai/model-resolver.ts';
+import { assertTouchpoint, embeddingDimsForModel } from '../../src/core/ai/model-resolver.ts';
import { AIConfigError } from '../../src/core/ai/errors.ts';
// D5 shape regex: provider/model slug, allowing letters, digits, dots, hyphens,
@@ -45,11 +45,26 @@ describe('recipe: openrouter', () => {
expect(r.touchpoints.embedding).toBeDefined();
const e = r.touchpoints.embedding!;
expect(e.models[0]).toBe('openai/text-embedding-3-small');
- expect(e.default_dims).toBe(1536);
expect(e.dims_options).toEqual([512, 768, 1024, 1536]);
expect(e.max_batch_tokens).toBe(300_000);
});
+ test('2b. #4114 — per-model dims for the documented catalog; unlisted ids resolve to 0 (explicit dims required)', () => {
+ const r = getRecipe('openrouter')!;
+ // Known catalog ids resolve to their live native width.
+ expect(embeddingDimsForModel(r, 'openrouter:openai/text-embedding-3-small')).toBe(1536);
+ expect(embeddingDimsForModel(r, 'openrouter:openai/text-embedding-3-large')).toBe(3072);
+ expect(embeddingDimsForModel(r, 'openrouter:qwen/qwen3-embedding-8b')).toBe(4096);
+ expect(embeddingDimsForModel(r, 'openrouter:bge-m3')).toBe(1024);
+ expect(embeddingDimsForModel(r, 'openrouter:baai/bge-m3')).toBe(1024);
+ // Unknown ids must NOT inherit a plausible-wrong 1536: 0 forces the
+ // explicit --dim path (migrate embeddings throws its actionable error).
+ expect(embeddingDimsForModel(r, 'openrouter:some/unknown-embedder')).toBe(0);
+ expect(embeddingDimsForModel(r, 'openrouter:google/gemini-embedding-2-preview')).toBe(0);
+ // Explicit override stays trusted for unlisted models.
+ expect(r.touchpoints.embedding!.trust_custom_dims).toBe(true);
+ });
+
test('3. chat touchpoint accepts arbitrary provider/model IDs (openai-compat tier)', () => {
const r = getRecipe('openrouter')!;
expect(r.touchpoints.chat).toBeDefined();
diff --git a/test/brain-score-recommendations.test.ts b/test/brain-score-recommendations.test.ts
index d4687e6595..c3ebc191b5 100644
--- a/test/brain-score-recommendations.test.ts
+++ b/test/brain-score-recommendations.test.ts
@@ -134,6 +134,7 @@ function makeHealth(overrides: Partial<BrainHealth> = {}): BrainHealth {
brain_score: 100,
dead_links: 0,
link_coverage: 1.0,
+ entity_page_count: 10,
timeline_coverage: 1.0,
most_connected: [],
embed_coverage_score: 35,
diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.ts
index 2580ff94ea..fb3f46f2fb 100644
--- a/test/chunkers/code.test.ts
+++ b/test/chunkers/code.test.ts
@@ -16,7 +16,7 @@ describe('CHUNKER_VERSION', () => {
});
describe('detectCodeLanguage', () => {
- test('recognizes all 30 supported extensions', () => {
+ test('recognizes supported extensions', () => {
const cases: Record<string, string> = {
'foo.ts': 'typescript', 'foo.tsx': 'tsx', 'foo.mts': 'typescript', 'foo.cts': 'typescript',
'foo.js': 'javascript', 'foo.jsx': 'javascript', 'foo.mjs': 'javascript', 'foo.cjs': 'javascript',
@@ -28,7 +28,7 @@ describe('detectCodeLanguage', () => {
'foo.scala': 'scala', 'foo.lua': 'lua', 'foo.ex': 'elixir',
'foo.elm': 'elm', 'foo.ml': 'ocaml', 'foo.dart': 'dart',
'foo.zig': 'zig', 'foo.sol': 'solidity', 'foo.sh': 'bash',
- 'foo.css': 'css', 'foo.html': 'html', 'foo.vue': 'vue',
+ 'foo.css': 'css', 'foo.html': 'html', 'foo.astro': 'html', 'foo.svelte': 'html', 'foo.vue': 'vue',
'foo.json': 'json', 'foo.yaml': 'yaml', 'foo.toml': 'toml',
// v0.41 D2 wave: SQL via DerekStride/tree-sitter-sql.
'foo.sql': 'sql', 'migrations/001_init.sql': 'sql',
diff --git a/test/claude-cli-recipe.test.ts b/test/claude-cli-recipe.test.ts
index 429a6b028b..de11ba7de4 100644
--- a/test/claude-cli-recipe.test.ts
+++ b/test/claude-cli-recipe.test.ts
@@ -120,6 +120,54 @@ describe('claude-cli LanguageModel — text-only round trip', () => {
expect(result.content[0]).toEqual({ type: 'text', text: 'hello world' });
expect(result.usage.inputTokens).toBe(12);
expect(result.usage.outputTokens).toBe(34);
+ // baseEnvelope's default cache_read_input_tokens is 0 (present, not
+ // omitted) — pins "present zero" as distinct from the omitted/undefined
+ // case covered below.
+ expect(result.usage.cachedInputTokens).toBe(0);
+ });
+ });
+
+ test('maps cache_read_input_tokens onto usage.cachedInputTokens', async () => {
+ await withStubEnv(async () => {
+ stageResponse(
+ baseEnvelope('hello world', {
+ usage: {
+ input_tokens: 12,
+ output_tokens: 34,
+ cache_read_input_tokens: 9001,
+ cache_creation_input_tokens: 0,
+ },
+ }),
+ );
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('hi')],
+ } as LanguageModelV2CallOptions);
+
+ expect(result.usage.cachedInputTokens).toBe(9001);
+ });
+ });
+
+ test('leaves usage.cachedInputTokens undefined when the CLI omits cache_read_input_tokens', async () => {
+ await withStubEnv(async () => {
+ stageResponse({
+ type: 'result',
+ subtype: 'success',
+ is_error: false,
+ result: 'hello world',
+ stop_reason: 'end_turn',
+ session_id: 'test-session',
+ num_turns: 1,
+ usage: { input_tokens: 12, output_tokens: 34 },
+ });
+ const { ClaudeCliLanguageModel } = await import('../src/core/ai/providers/claude-cli-language-model.ts');
+ const model = new ClaudeCliLanguageModel('claude-sonnet-4-6');
+ const result = await model.doGenerate({
+ prompt: [userMessage('hi')],
+ } as LanguageModelV2CallOptions);
+
+ expect(result.usage.cachedInputTokens).toBeUndefined();
});
});
@@ -377,19 +425,24 @@ describe('claude-cli LanguageModel — context isolation', () => {
});
});
- test('scrubs ANTHROPIC_* credentials from the child env (subscription-only auth)', async () => {
+ test('scrubs ANTHROPIC_* credentials and cloud-auth backend switches from the child env (subscription-only auth)', async () => {
await withStubEnv(async () => {
await withEnv(
{
ANTHROPIC_API_KEY: 'sk-should-never-leak',
ANTHROPIC_AUTH_TOKEN: 'tok-should-never-leak',
ANTHROPIC_BASE_URL: 'https://proxy.should.never.leak',
+ CLAUDE_CODE_USE_BEDROCK: '1',
+ CLAUDE_CODE_USE_VERTEX: '1',
+ CLAUDE_CODE_USE_MANTLE: '1',
+ CLAUDE_CODE_USE_FOUNDRY: '1',
+ CLAUDE_CODE_USE_ANTHROPIC_AWS: '1',
},
async () => {
const envLog = join(stubDir, 'env.log');
const envStub = [
'#!/bin/sh',
- `printf "key=%s\\ntoken=%s\\nbase=%s\\n" "\${ANTHROPIC_API_KEY:-UNSET}" "\${ANTHROPIC_AUTH_TOKEN:-UNSET}" "\${ANTHROPIC_BASE_URL:-UNSET}" > "${envLog}"`,
+ `printf "key=%s\\ntoken=%s\\nbase=%s\\nbedrock=%s\\nvertex=%s\\nmantle=%s\\nfoundry=%s\\nanthropicAws=%s\\n" "\${ANTHROPIC_API_KEY:-UNSET}" "\${ANTHROPIC_AUTH_TOKEN:-UNSET}" "\${ANTHROPIC_BASE_URL:-UNSET}" "\${CLAUDE_CODE_USE_BEDROCK:-UNSET}" "\${CLAUDE_CODE_USE_VERTEX:-UNSET}" "\${CLAUDE_CODE_USE_MANTLE:-UNSET}" "\${CLAUDE_CODE_USE_FOUNDRY:-UNSET}" "\${CLAUDE_CODE_USE_ANTHROPIC_AWS:-UNSET}" > "${envLog}"`,
'cat > /dev/null',
`cat "${stubResponsePath}"`,
].join('\n');
@@ -409,6 +462,11 @@ describe('claude-cli LanguageModel — context isolation', () => {
expect(seen).toContain('key=UNSET');
expect(seen).toContain('token=UNSET');
expect(seen).toContain('base=UNSET');
+ expect(seen).toContain('bedrock=UNSET');
+ expect(seen).toContain('vertex=UNSET');
+ expect(seen).toContain('mantle=UNSET');
+ expect(seen).toContain('foundry=UNSET');
+ expect(seen).toContain('anthropicAws=UNSET');
} finally {
const fastStub = [
'#!/bin/sh',
diff --git a/test/cli-help-discoverability.test.ts b/test/cli-help-discoverability.test.ts
index 8769642a76..b49f9749b5 100644
--- a/test/cli-help-discoverability.test.ts
+++ b/test/cli-help-discoverability.test.ts
@@ -17,12 +17,33 @@
import { describe, test, expect } from 'bun:test';
import { spawnSync } from 'node:child_process';
+import { mkdtempSync, writeFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
-function runCli(args: string[]): { stdout: string; stderr: string; status: number } {
- const result = spawnSync('bun', ['run', 'src/cli.ts', ...args], {
- cwd: process.cwd(),
+// Absolute path to the CLI entrypoint so `cwd` can be overridden (needed for
+// the `sources detach --help` regression test below, which must run with the
+// spawned process's cwd pointed at a scratch directory).
+const CLI_ENTRY = join(process.cwd(), 'src/cli.ts');
+
+function runCli(args: string[], opts: { cwd?: string } = {}): { stdout: string; stderr: string; status: number } {
+ // Hermetic no-brain environment, matching cli-help-without-brain.serial.test.ts:
+ // GBRAIN_HOME alone is not enough — loadConfig also honours GBRAIN_DATABASE_URL
+ // and DATABASE_URL, so a developer or CI runner exporting either would let the
+ // CLI connect anyway and these assertions would go inert.
+ const env: Record<string, string | undefined> = {
+ ...process.env,
+ GBRAIN_HOME: '/tmp/gbrain-test-help-nonexistent',
+ };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ // --no-env-file: bun auto-loads .env from cwd, and GBRAIN_DATABASE_URL is
+ // honored unconditionally, so a local .env would put back exactly what the
+ // deletes above removed.
+ const result = spawnSync('bun', ['--no-env-file', 'run', CLI_ENTRY, ...args], {
+ cwd: opts.cwd ?? process.cwd(),
encoding: 'utf8',
- env: { ...process.env, GBRAIN_HOME: '/tmp/gbrain-test-help-nonexistent' },
+ env,
});
return {
stdout: result.stdout ?? '',
@@ -183,3 +204,97 @@ describe('#3834 — extract flags are discoverable from both help surfaces', ()
for (const flag of implementedFlags) expect(extractHelp).toContain(flag);
});
});
+
+describe('sources --help reaches its own usage block instead of the circular generic stub', () => {
+ test('`gbrain sources --help` reaches detailed command help without a configured brain', () => {
+ const { stdout, stderr, status } = runCli(['sources', '--help']);
+ expect(status).toBe(0);
+ expect(stderr).toBe('');
+ expect(stdout).toContain('Subcommands:');
+ // Pre-fix output was the generic short-circuit, which itself points back
+ // at `gbrain --help` — a circular pointer, since the top-level help's own
+ // SOURCES block promises `sources --help` as the place to find these.
+ expect(stdout).not.toContain('run gbrain --help for the full command list');
+ // Subcommands the top-level `gbrain --help` SOURCES block does NOT list
+ // (it only lists list/add/remove/archive/restore/archived/purge/status)
+ // and instead defers to `sources --help` for.
+ expect(stdout).toContain('rename');
+ expect(stdout).toContain('set-cr-mode');
+ expect(stdout).toContain('federate');
+ expect(stdout).toContain('attach');
+ expect(stdout).toContain('harden');
+ });
+
+ test('`gbrain sources -h` reaches the same detailed command help', () => {
+ const { stdout, status } = runCli(['sources', '-h']);
+ expect(status).toBe(0);
+ expect(stdout).toContain('set-cr-mode');
+ expect(stdout).not.toContain('run gbrain --help for the full command list');
+ });
+});
+
+describe('regression: nested `sources <sub> --help` must print help, not dispatch to <sub>', () => {
+ // `hasHelpFlag` in src/cli.ts matches --help/-h in ANY position, which is
+ // what routes `sources list --help` into SELF_HELP_WITHOUT_ENGINE with a
+ // placeholder null engine. Before the sources.ts guard, runSources's
+ // switch dispatched on args[0] only ('list'), so the '--help' in position
+ // 1 was silently dropped and runList(nullEngine, ['--help']) actually ran
+ // — crashing on the placeholder engine. Some subcommands (`detach`) don't
+ // even touch the engine and would perform their real, destructive action
+ // instead of crashing.
+ test('`sources list --help` prints help and does not dispatch into runList (no null-engine crash)', () => {
+ const { stdout, stderr, status } = runCli(['sources', 'list', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).toContain('Subcommands:');
+ expect(stdout).not.toContain('run gbrain --help for the full command list');
+ // Pre-fix this crashed inside runList with something like
+ // "null is not an object (evaluating 'engine.executeRaw')".
+ expect(stderr).not.toContain('executeRaw');
+ expect(stderr).not.toContain('TypeError');
+ });
+
+ test('`sources detach --help` prints help and does NOT delete .gbrain-source', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sources-detach-help-'));
+ const dotfile = join(dir, '.gbrain-source');
+ writeFileSync(dotfile, 'example-source\n');
+ try {
+ const { stdout, status } = runCli(['sources', 'detach', '--help'], { cwd: dir });
+ expect(status).toBe(0);
+ expect(stdout).toContain('Subcommands:');
+ // The regression: runDetach() takes no engine and unconditionally
+ // unlinks .gbrain-source — with no guard, `detach --help` silently
+ // deletes the caller's dotfile instead of showing usage.
+ expect(existsSync(dotfile)).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('`sources webhook --help` reaches its own detailed help, not the general block or runWebhook*', () => {
+ test('`sources webhook --help` prints the webhook-specific usage (set/show/rotate/clear), not the general SOURCES block', () => {
+ const { stdout, status } = runCli(['sources', 'webhook', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).toContain('Usage: gbrain sources webhook');
+ expect(stdout).toContain('rotate <id>');
+ expect(stdout).toContain('clear <id>');
+ expect(stdout).toContain('One-time reveal');
+ // The general block's opening line + a subcommand only it lists —
+ // absence of both confirms this reached SOURCES_WEBHOOK_HELP, not
+ // printHelp().
+ expect(stdout).not.toContain('gbrain sources — manage multi-source brain configuration');
+ expect(stdout).not.toContain('add <id> --path');
+ });
+
+ test('`sources webhook set x --help` prints webhook help and does NOT reach runWebhookSet', () => {
+ const { stdout, stderr, status } = runCli(['sources', 'webhook', 'set', 'x', '--help']);
+ expect(status).toBe(0);
+ expect(stdout).toContain('Usage: gbrain sources webhook');
+ // runWebhookSet's own usage-error / not-found text must never appear —
+ // its presence would mean the guard let dispatch fall through to it.
+ expect(stdout).not.toContain('Source "x" not found');
+ expect(stderr).not.toContain('Source "x" not found');
+ expect(stderr).not.toContain('--github-repo');
+ expect(stderr).not.toContain('TypeError');
+ });
+});
diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.ts
index 010e530247..4042e0e908 100644
--- a/test/cli-help-without-brain.serial.test.ts
+++ b/test/cli-help-without-brain.serial.test.ts
@@ -29,6 +29,7 @@ const HELP_WITHOUT_BRAIN = [
'jobs',
// #4152: dream answers --help (and the retriage subverb help) engine-free.
'dream',
+ 'sources',
// cathedral-6: agent answers --help (incl. `register --help`) engine-free.
'agent',
// ZE interim cleanup: the retired ze-switch shim answers --help engine-free
diff --git a/test/conversation-facts-type-allowlist-drift.test.ts b/test/conversation-facts-type-allowlist-drift.test.ts
new file mode 100644
index 0000000000..d21e09dd69
--- /dev/null
+++ b/test/conversation-facts-type-allowlist-drift.test.ts
@@ -0,0 +1,347 @@
+/**
+ * conversation-facts type allowlist — single source of truth + drift guard.
+ *
+ * The conversation-facts type allowlist (`conversation`, `meeting`, `slack`,
+ * `email`, `imessage`, `imessage-daily`) used to be hand-copied into five
+ * places across four files:
+ * 1. extract-conversation-facts.ts's ALLOWED_TYPES (canonical)
+ * 2. doctor.ts's conversation_facts_backlog config default
+ * 3. doctor.ts's conversation_format_coverage sample scan
+ * 4. jobs.ts's extract-conversation-facts Minion job handler filter
+ * 5. sources.ts's facts-backfill audit estimator
+ *
+ * It had already drifted: jobs.ts's runExtractConversationFactsCore call cast
+ * `types` to `('conversation' | 'meeting' | 'slack' | 'email')[] | undefined`
+ * — the pre-#2756 four-element set, missing `imessage` and `imessage-daily`
+ * that the runtime filter one line above it already accepted. Same class of
+ * bug CLAUDE.md calls out for pricing tables: "One canonical ... table ...
+ * Every other table is a DERIVED view, never a hand-copied duplicate — so
+ * cross-table ... drift is structurally impossible."
+ *
+ * ALLOWED_TYPES/AllowedType now live in a leaf module,
+ * src/core/facts/conversation-types.ts, NOT in extract-conversation-facts.ts
+ * (which re-exports both verbatim). That's a second-order fix: sites 2-5
+ * originally imported the constant straight from extract-conversation-
+ * facts.ts, and scripts/generate-flag-registry.ts scans every relative
+ * import of a command module for `--flag`-shaped string literals — so
+ * importing anything from that command module (even just this constant)
+ * transitively attributed its whole CLI flag surface (`--background`,
+ * `--concurrency`, `--limit`, ... about ten flags) to doctor/repos/sources
+ * in the generated registry, silently widening what those three commands'
+ * strict unknown-flag validation (#2185) accepts (#4135 CI failure). The
+ * leaf module has no flags of its own, so importing it doesn't leak
+ * anything, regardless of whether the importer uses a static or dynamic
+ * import (generate-flag-registry.ts's one-level relative-import scan
+ * matches both forms identically).
+ *
+ * Guards below, mirroring test/model-pricing.test.ts:
+ * - identity/behavioral assertions where a site's resolved list is
+ * reachable at runtime (doctor.ts's backlog-check `details.types`);
+ * - a SEMANTIC hand-copy detector (set-membership over array literals and
+ * string-literal union chains, order- and length-insensitive) for sites
+ * whose list isn't independently reachable/exported. An earlier version
+ * used byte-exact canonical-order regexes, which mutation testing showed
+ * only tripped on an exact canonical-order re-add — permuted re-adds,
+ * subset re-adds (the harmful direction: silently dropping types), and a
+ * narrowed jobs.ts runtime filter all passed. The detector fails on ANY
+ * re-hardcoded conversation-type list (>=2 canonical members, code or
+ * comment) and on pointing a site back at extract-conversation-facts.ts
+ * instead of the leaf. The guarded set includes the cycle backfill phase
+ * (src/core/cycle/conversation-facts-backfill.ts), where the detector
+ * immediately caught a stale pre-#2756 four-element default in the
+ * header comment;
+ * - ALLOWED_TYPES itself is Object.frozen, so runtime mutation throws
+ * instead of silently drifting every derived consumer at once;
+ * - a flag-registry regression guard pinning the exact bug this file's
+ * history hit: doctor/repos/sources must never carry
+ * extract-conversation-facts.ts's own flags.
+ */
+import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { ALLOWED_TYPES } from '../src/core/facts/conversation-types.ts';
+import { computeConversationFactsBacklogCheck } from '../src/commands/doctor.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { buildFlagRegistry } from '../scripts/generate-flag-registry.ts';
+
+const EXPECTED_TYPES = [
+ 'conversation',
+ 'meeting',
+ 'slack',
+ 'email',
+ 'imessage',
+ 'imessage-daily',
+] as const;
+
+function readSrc(relPath: string): string {
+ return readFileSync(fileURLToPath(new URL(`../src/${relPath}`, import.meta.url)), 'utf8');
+}
+
+// Semantic hand-copy detector (replaces the earlier byte-exact literal/order
+// matchers, which only tripped on a canonical-order re-add — a permuted
+// re-add, a subset re-add (the harmful direction: silently dropping types),
+// and a narrowed runtime filter all sailed past them). Finds EVERY
+// conversation-type list shape regardless of order or length:
+// - array literals of >=2 string elements (`['meeting', 'slack', ...]`)
+// - string-literal union chains of >=2 members (`'meeting' | 'slack' | ...`)
+// and flags any whose elements intersect the canonical set in >=2 places.
+// Set-membership, not sequence match — so permutations, subsets, and
+// supersets all trip it. It deliberately scans comments too: a hand-copied
+// list in a doc comment goes stale the same way code does (adding this
+// detector immediately caught a pre-#2756 four-element default documented in
+// conversation-facts-backfill.ts's header while the code default was six).
+// The >=2 threshold keeps single-membership arrays like extract-conversation-
+// facts.ts's ALLOWED_TYPE_ALIASES values (`['slack', 'slack-dm-day', ...]`,
+// one canonical member each) from false-positiving.
+const CANONICAL_SET: ReadonlySet<string> = new Set(EXPECTED_TYPES);
+const STRING_LIT = `(?:'[^'\\n]*'|"[^"\\n]*")`;
+const ARRAY_LIST_RE = new RegExp(
+ `\\[\\s*${STRING_LIT}(?:\\s*,\\s*${STRING_LIT})+\\s*,?\\s*\\]`,
+ 'g',
+);
+const UNION_LIST_RE = new RegExp(`${STRING_LIT}(?:\\s*\\|\\s*${STRING_LIT})+`, 'g');
+
+function stringElements(listText: string): string[] {
+ return [...listText.matchAll(/['"]([^'"\n]*)['"]/g)].map((m) => m[1]);
+}
+
+function findSuspectTypeLists(src: string): Array<{ snippet: string; elements: string[] }> {
+ const suspects: Array<{ snippet: string; elements: string[] }> = [];
+ for (const re of [ARRAY_LIST_RE, UNION_LIST_RE]) {
+ for (const m of src.matchAll(re)) {
+ const elements = stringElements(m[0]);
+ const canonicalHits = elements.filter((e) => CANONICAL_SET.has(e));
+ if (canonicalHits.length >= 2) suspects.push({ snippet: m[0], elements });
+ }
+ }
+ return suspects;
+}
+
+// Any import (static `from '...'` or dynamic `import('...')`) of
+// ALLOWED_TYPES (optionally aliased) from the given relative module path.
+function countAllowedTypesImportsFrom(src: string, modulePathEscaped: string): number {
+ const staticRe = new RegExp(
+ `import\\s*\\{[^}]*\\bALLOWED_TYPES\\b[^}]*\\}\\s*from\\s*['"]${modulePathEscaped}['"]`,
+ 'g',
+ );
+ const dynamicRe = new RegExp(
+ `\\{\\s*[^}]*\\bALLOWED_TYPES\\b[^}]*\\}\\s*=\\s*await\\s+import\\(\\s*['"]${modulePathEscaped}['"]\\s*\\)`,
+ 'g',
+ );
+ return [...src.matchAll(staticRe)].length + [...src.matchAll(dynamicRe)].length;
+}
+
+// A site still pointed at extract-conversation-facts.ts for ALLOWED_TYPES
+// (the exact regression this file's history hit) rather than the leaf.
+function countAllowedTypesImportsFromCommandModule(src: string): number {
+ return countAllowedTypesImportsFrom(src, '\\.\\/extract-conversation-facts\\.ts');
+}
+
+describe('ALLOWED_TYPES — canonical source of truth (leaf module)', () => {
+ test('has exactly the 6 expected types, in order', () => {
+ expect([...ALLOWED_TYPES]).toEqual([...EXPECTED_TYPES]);
+ });
+
+ test('is Object.frozen — runtime mutation throws instead of silently drifting every consumer', () => {
+ expect(Object.isFrozen(ALLOWED_TYPES)).toBe(true);
+ // Module code runs in strict mode, so a frozen-array write throws
+ // (it would be a silent no-op in sloppy mode — assert the throw so the
+ // guard is about behavior, not just the flag).
+ expect(() => {
+ (ALLOWED_TYPES as unknown as string[]).push('sms');
+ }).toThrow();
+ expect(ALLOWED_TYPES.length).toBe(6);
+ });
+
+ test('exactly one conversation-type list exists in the leaf module, and it is set-equal to the canonical 6', () => {
+ const src = readSrc('core/facts/conversation-types.ts');
+ const suspects = findSuspectTypeLists(src);
+ expect(suspects.length).toBe(1);
+ expect([...suspects[0].elements].sort()).toEqual([...EXPECTED_TYPES].sort());
+ });
+
+ test('the leaf module carries no CLI-flag-shaped literals of its own', () => {
+ // This is the actual invariant the leaf module exists to guarantee: it
+ // must never gain a `--flag`-shaped string (e.g. from a comment example
+ // or a hand-added constant), or generate-flag-registry.ts's relative-
+ // import scan would once again attribute flags to every consumer that
+ // imports ALLOWED_TYPES from here — reopening #4135.
+ const src = readSrc('core/facts/conversation-types.ts');
+ expect([...src.matchAll(/--[a-z0-9][a-z0-9-]*/g)]).toEqual([]);
+ });
+
+ test('extract-conversation-facts.ts no longer hand-copies any type list; re-exports from the leaf', () => {
+ const src = readSrc('commands/extract-conversation-facts.ts');
+ expect(findSuspectTypeLists(src)).toEqual([]);
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(1);
+ expect(src).toContain('export { ALLOWED_TYPES }');
+ expect(src).toContain('export type { AllowedType }');
+ });
+});
+
+describe('DRIFT GUARD — consumer sites derive from the leaf module (re-hardcode + wrong-import trip-wire)', () => {
+ for (const [label, relPath] of [
+ ['doctor.ts', 'commands/doctor.ts'],
+ ['jobs.ts', 'commands/jobs.ts'],
+ ['sources.ts', 'commands/sources.ts'],
+ ['conversation-facts-backfill.ts', 'core/cycle/conversation-facts-backfill.ts'],
+ ] as const) {
+ test(`${label}: no hand-copied conversation-type list remains (any order, any length >= 2)`, () => {
+ // Set-membership detector, NOT a canonical-order literal match: a
+ // permuted re-add, a subset re-add (dropping a type), and a widened
+ // re-add all fail here. Code and comments alike.
+ const src = readSrc(relPath);
+ expect(findSuspectTypeLists(src)).toEqual([]);
+ });
+
+ test(`${label}: does not import ALLOWED_TYPES from extract-conversation-facts.ts`, () => {
+ const src = readSrc(relPath);
+ expect(
+ countAllowedTypesImportsFrom(src, '\\.\\.?(?:/\\.\\.)?/commands/extract-conversation-facts\\.ts') +
+ countAllowedTypesImportsFromCommandModule(src),
+ ).toBe(0);
+ });
+ }
+
+ test('conversation-facts-backfill.ts: imports ALLOWED_TYPES from the leaf exactly once', () => {
+ const src = readSrc('core/cycle/conversation-facts-backfill.ts');
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./facts/conversation-types\\.ts')).toBe(1);
+ });
+
+ test('doctor.ts: imports ALLOWED_TYPES from the leaf exactly once', () => {
+ // Post-peel (v0.46.9.1 containment sprint) doctor.ts keeps ONE call site
+ // (the buildChecks parser sample); the backlog check moved to
+ // doctor/checks/search-eval.ts and is guarded separately below.
+ const src = readSrc('commands/doctor.ts');
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(1);
+ expect((src.match(/\bALLOWED_TYPES\b/g) ?? []).length).toBeGreaterThanOrEqual(2); // import + 1 usage
+ });
+
+ test('doctor/checks/search-eval.ts: the peeled backlog check derives from the leaf too', () => {
+ const src = readSrc('commands/doctor/checks/search-eval.ts');
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./\\.\\./\\.\\./core/facts/conversation-types\\.ts')).toBe(1);
+ expect((src.match(/\bALLOWED_TYPES\b/g) ?? []).length).toBeGreaterThanOrEqual(2); // import + 1 usage
+ });
+
+ test('jobs.ts: the extract-conversation-facts handler filters job.data.types against ALLOWED_TYPES', () => {
+ // Closes the narrowed-runtime-filter hole: the `job.data.types` filter
+ // must reference the canonical ALLOWED_TYPES binding. Together with the
+ // hand-copy detector above (no shadow list may exist anywhere in
+ // jobs.ts) and the single-leaf-import guard below, narrowing the filter
+ // requires either dropping this reference (fails here) or re-adding a
+ // hand-copied list (fails the detector). The old guard was a byte-exact
+ // match on the stale 4-element union cast, which a 4-element runtime
+ // filter re-add sailed straight past.
+ const src = readSrc('commands/jobs.ts');
+ expect(src).toMatch(/job\.data\.types[\s\S]{0,400}?\bALLOWED_TYPES\b/);
+ });
+
+ test('jobs.ts: imports ALLOWED_TYPES + AllowedType from the leaf exactly once', () => {
+ const src = readSrc('commands/jobs.ts');
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(1);
+ expect(src).toContain("type AllowedType } from '../core/facts/conversation-types.ts'");
+ });
+
+ test('sources.ts: FACTS_BACKFILL_ALLOWED imports ALLOWED_TYPES from the leaf', () => {
+ const src = readSrc('commands/sources.ts');
+ expect(countAllowedTypesImportsFrom(src, '\\.\\./core/facts/conversation-types\\.ts')).toBe(1);
+ });
+});
+
+describe('DRIFT GUARD — jobs.ts filter accepts all 6 canonical types at runtime', () => {
+ // jobs.ts's filter is `(t): t is AllowedType => (ALLOWED_TYPES as readonly
+ // string[]).includes(t)` — the same predicate shape as
+ // extract-conversation-facts.ts's own resolveTypesFromConfig filter. Since
+ // the source-text guard above proves jobs.ts's filter is wired to the
+ // canonical ALLOWED_TYPES (not a hand-copied duplicate), proving
+ // ALLOWED_TYPES itself accepts every canonical type closes the loop:
+ // jobs.ts accepts all 6, including `imessage`/`imessage-daily`, which the
+ // stale cast's *type* (but not its runtime behavior — see the commit
+ // message) used to exclude.
+ test('ALLOWED_TYPES accepts every canonical type via .includes()', () => {
+ for (const t of EXPECTED_TYPES) {
+ expect((ALLOWED_TYPES as readonly string[]).includes(t)).toBe(true);
+ }
+ });
+});
+
+describe('DRIFT GUARD — doctor.ts conversation_facts_backlog default is reachable + correct', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ test('with no cycle.conversation_facts_backfill.types override, the resolved default equals ALLOWED_TYPES', async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('cycle.conversation_facts_backfill.enabled', 'true');
+ // No pages of any conversation type exist, so backlog === 0 and the
+ // check takes the 'ok' branch, which reports the resolved `types` it
+ // used in `details.types` — the actual default this code path runs
+ // with, not a value we're asserting in isolation.
+ const check = await computeConversationFactsBacklogCheck(engine);
+ expect(check.status).toBe('ok');
+ const resolvedTypes = (check.details as { types?: string[] } | undefined)?.types;
+ expect(resolvedTypes).toBeDefined();
+ expect([...(resolvedTypes ?? [])].sort()).toEqual([...EXPECTED_TYPES].sort());
+ });
+});
+
+describe('DRIFT GUARD — #4135 regression: doctor.ts/sources.ts never relative-import extract-conversation-facts.ts', () => {
+ // The exact bug: doctor.ts (both sites) and sources.ts each imported
+ // ALLOWED_TYPES straight from extract-conversation-facts.ts.
+ // generate-flag-registry.ts's one-level relative-import scan
+ // (`from '...'` AND `import('...')`, matched identically) then read that
+ // whole command module's text for `--flag`-shaped literals and folded
+ // them into doctor/repos/sources's registry entries — silently widening
+ // what those commands' #2185 strict unknown-flag validation accepts.
+ // Reproduces the generator's own relative-import regex (scripts/
+ // generate-flag-registry.ts:relativeImports) rather than guessing which
+ // flag names are "foreign": other legitimately-imported modules can
+ // independently contribute overlapping flag names, so a flag-allowlist
+ // test would be both wrong and fragile. jobs.ts is deliberately excluded:
+ // it independently, legitimately imports extract-conversation-facts.ts
+ // for runExtractConversationFactsCore, so its registry entry already (and
+ // correctly) carries that command's flag surface — see the "no #2756-
+ // drift-class" jobs.ts guards above for what DOES need to hold there.
+ const RELATIVE_IMPORT_RE = /(?:from\s+'(\.\.?\/[^']+\.ts)'|import\('(\.\.?\/[^']+\.ts)'\))/g;
+
+ function relativeImportPaths(src: string): string[] {
+ return [...src.matchAll(RELATIVE_IMPORT_RE)].map((m) => m[1] ?? m[2]);
+ }
+
+ for (const [label, relPath] of [
+ ['doctor.ts', 'commands/doctor.ts'],
+ ['sources.ts', 'commands/sources.ts'],
+ ] as const) {
+ test(`${label}: source contains no relative import path ending in extract-conversation-facts.ts`, () => {
+ const src = readSrc(relPath);
+ const hits = relativeImportPaths(src).filter((p) => p.endsWith('extract-conversation-facts.ts'));
+ expect(hits).toEqual([]);
+ });
+ }
+
+ test('flag-registry freshness: rebuilding the registry now produces the exact same doctor/repos/sources/jobs entries as committed', () => {
+ // Narrow, targeted companion to test/cli-flag-validation.test.ts's
+ // whole-registry freshness guard (#2185) — pinned specifically to the
+ // four command names this bug touched (or, for jobs, deliberately did
+ // NOT touch), so a regression here fails right next to its cause.
+ const registry = buildFlagRegistry();
+ const committedSrc = readSrc('core/cli-flag-registry.generated.ts');
+ for (const command of ['doctor', 'repos', 'sources', 'jobs']) {
+ const entryMatch = committedSrc.match(
+ new RegExp(`'${command}': \\[([^\\]]*)\\]`),
+ );
+ expect(entryMatch, `no committed registry entry found for '${command}'`).not.toBeNull();
+ const committedFlags = [...(entryMatch![1].matchAll(/'([^']+)'/g))].map((m) => m[1]).sort();
+ expect(registry[command]).toEqual(committedFlags);
+ }
+ });
+});
diff --git a/test/conversation-parser/parse.test.ts b/test/conversation-parser/parse.test.ts
index 6a1ec436f9..3d2dd7d405 100644
--- a/test/conversation-parser/parse.test.ts
+++ b/test/conversation-parser/parse.test.ts
@@ -469,7 +469,7 @@ describe('scorePatternFull — full-body scoring (v0.41.18+ Codex P1 #1)', () =>
const im = BUILTIN_PATTERNS.find((p) => p.id === 'imessage-slack')!;
expect(scorePatternFull('', im)).toBe(0);
});
- test('preamble + 20 matching lines scores 20/(preamble + 20)', () => {
+ test('multi-line format ignores preamble after multiple anchors establish a transcript', () => {
const im = BUILTIN_PATTERNS.find((p) => p.id === 'imessage-slack')!;
const preamble = ['## Summary', 'Three sentences.', '> Source: ref', '## Transcript'];
const matches = Array.from(
@@ -477,8 +477,9 @@ describe('scorePatternFull — full-body scoring (v0.41.18+ Codex P1 #1)', () =>
(_, i) => `**Garry Tan** (2026-01-29 12:00 PM): message ${i}`,
);
const body = [...preamble, ...matches].join('\n');
- // 24 total non-blank, 20 match → 20/24 ≈ 0.833
- expect(scorePatternFull(body, im)).toBeCloseTo(20 / 24, 5);
+ // Once two anchors establish a real multi-line transcript, unrelated
+ // preamble/continuation lines no longer dilute the format score.
+ expect(scorePatternFull(body, im)).toBe(1);
});
test('preamble-only-no-match scores 0', () => {
const im = BUILTIN_PATTERNS.find((p) => p.id === 'imessage-slack')!;
diff --git a/test/core/budget/expand-records-budget.test.ts b/test/core/budget/expand-records-budget.test.ts
new file mode 100644
index 0000000000..2ae13e7d2a
--- /dev/null
+++ b/test/core/budget/expand-records-budget.test.ts
@@ -0,0 +1,259 @@
+/**
+ * #4121 — expand() (query expansion) calls generateObject/generateText
+ * directly and never went through chat()'s `_recordBudget` closure, so
+ * expansion LLM spend was invisible to BudgetTracker even inside a
+ * `withBudgetTracker()` scope.
+ *
+ * Pins the fix's public contract:
+ * - Every SUCCESSFUL expand() call site (native generateObject path,
+ * openai-compatible structured-output generateObject path, and the
+ * schemaless generateText fallback path) records usage on the ambient
+ * BudgetTracker with a distinct `sub_label: 'gateway.expand'` — never
+ * conflated with chat()'s `gateway.chat` audit rows.
+ * - expand() outside any withBudgetTracker scope stays a budget no-op
+ * (back-compat, mirrors gateway-budget-composition.test.ts).
+ * - record() throwing BudgetExhausted (TX1, over-cap) is swallowed —
+ * expand() still returns its best-effort result, matching chat()'s
+ * fail-open posture.
+ *
+ * Hermetic: routes through __setGenerateObjectTransportForTests /
+ * __setGenerateTextTransportForTests so no network / provider / env
+ * variable is touched.
+ */
+
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ expand,
+ configureGateway,
+ resetGateway,
+ withBudgetTracker,
+ getCurrentBudgetTracker,
+ __setGenerateObjectTransportForTests,
+ __setGenerateTextTransportForTests,
+} from '../../../src/core/ai/gateway.ts';
+import {
+ BudgetTracker,
+ _resetBudgetTrackerWarningsForTest,
+} from '../../../src/core/budget/budget-tracker.ts';
+import { getRecipe, __setTestRecipesForTests } from '../../../src/core/ai/recipes/index.ts';
+import type { Recipe } from '../../../src/core/ai/types.ts';
+
+let tmp: string;
+let auditPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-expand-budget-'));
+ auditPath = join(tmp, 'budget.jsonl');
+ _resetBudgetTrackerWarningsForTest();
+});
+
+afterEach(() => {
+ __setGenerateObjectTransportForTests(null);
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+/** Read + parse every JSONL line in the tracker's audit file. */
+function readAudit(): any[] {
+ return readFileSync(auditPath, 'utf-8')
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map(line => JSON.parse(line));
+}
+
+describe('expand() budget accounting — native generateObject path', () => {
+ beforeEach(() => {
+ configureGateway({
+ expansion_model: 'anthropic:claude-haiku-4-5-20251001',
+ env: { ANTHROPIC_API_KEY: 'sk-test-fake' },
+ });
+ });
+
+ test('a successful expansion records usage under the ambient tracker', async () => {
+ __setGenerateObjectTransportForTests(async () => ({
+ object: { queries: ['alt one', 'alt two'] },
+ usage: { inputTokens: 120, outputTokens: 40 },
+ }) as any);
+
+ const tracker = new BudgetTracker({ maxCostUsd: 1.0, label: 'test-expand', auditPath });
+
+ let result: string[] = [];
+ await withBudgetTracker(tracker, async () => {
+ result = await expand('original query');
+ });
+
+ expect(result).toContain('original query');
+ expect(result).toContain('alt one');
+ expect(tracker.snapshot().callsRecorded).toBe(1);
+ // Haiku pricing is non-zero, so a priced call must move totalSpent.
+ expect(tracker.totalSpent).toBeGreaterThan(0);
+
+ const rows = readAudit();
+ const recordRow = rows.find(r => r.event === 'record');
+ expect(recordRow).toBeTruthy();
+ // The core of #4121: expansion spend must carry its own sub_label, never
+ // the chat() one — that conflation is exactly what made it invisible.
+ expect(recordRow.sub_label).toBe('gateway.expand');
+ expect(recordRow.sub_label).not.toBe('gateway.chat');
+ expect(recordRow.model).toBe('anthropic:claude-haiku-4-5-20251001');
+ expect(recordRow.input_tokens).toBe(120);
+ expect(recordRow.output_tokens).toBe(40);
+ });
+
+ test('outside any withBudgetTracker scope, expand() is a budget no-op (back-compat)', async () => {
+ __setGenerateObjectTransportForTests(async () => ({
+ object: { queries: ['alt one'] },
+ usage: { inputTokens: 120, outputTokens: 40 },
+ }) as any);
+
+ expect(getCurrentBudgetTracker()).toBeNull();
+ const result = await expand('original query');
+ expect(result).toContain('original query');
+ expect(result).toContain('alt one');
+ // No tracker was ever installed — nothing to assert beyond "no throw".
+ expect(getCurrentBudgetTracker()).toBeNull();
+ });
+
+ test('BudgetExhausted from record() (TX1) is swallowed — expand() still returns its result', async () => {
+ // Tiny cap: reserve() has no pre-flight for expand() (only chat() calls
+ // reserve()), so the first record() itself pushes cumulative > cap and
+ // throws internally. recordExpansionUsage must swallow it.
+ __setGenerateObjectTransportForTests(async () => ({
+ object: { queries: ['alt one'] },
+ usage: { inputTokens: 1_000_000, outputTokens: 1_000_000 },
+ }) as any);
+
+ const tracker = new BudgetTracker({ maxCostUsd: 0.0001, label: 'tight-expand', auditPath });
+
+ let result: string[] = [];
+ let threw: unknown = null;
+ await withBudgetTracker(tracker, async () => {
+ try {
+ result = await expand('original query');
+ } catch (err) {
+ threw = err;
+ }
+ });
+
+ expect(threw).toBeNull();
+ expect(result).toContain('original query');
+ expect(tracker.totalSpent).toBeGreaterThan(0.0001);
+ });
+});
+
+describe('expand() budget accounting — openai-compatible schemaless (viaText) path', () => {
+ beforeEach(() => {
+ // litellm: requires no auth env and declares no chat.supports_structured_outputs,
+ // so recipeSupportsStructuredOutputs() is false and expand() routes straight
+ // to viaText() — the generateText fallback path, not generateObject.
+ configureGateway({
+ expansion_model: 'litellm:my-proxied-model',
+ env: {},
+ });
+ });
+
+ test('a successful viaText() expansion records usage with the same sub_label', async () => {
+ __setGenerateTextTransportForTests(async () => ({
+ text: '{"queries": ["alt one", "alt two"]}',
+ usage: { inputTokens: 80, outputTokens: 30 },
+ }) as any);
+
+ const tracker = new BudgetTracker({ label: 'test-expand-viatext', auditPath });
+
+ let result: string[] = [];
+ await withBudgetTracker(tracker, async () => {
+ result = await expand('original query');
+ });
+
+ expect(result).toContain('original query');
+ expect(result).toContain('alt one');
+ expect(tracker.snapshot().callsRecorded).toBe(1);
+
+ const rows = readAudit();
+ // litellm has no pricing entry, so this lands as record_unpriced — still
+ // proves the call site fired (this is the exact code path #4121 reported
+ // as never reaching the tracker at all).
+ const recordRow = rows.find(r => r.event === 'record' || r.event === 'record_unpriced');
+ expect(recordRow).toBeTruthy();
+ expect(recordRow.sub_label).toBe('gateway.expand');
+ expect(recordRow.model).toBe('litellm:my-proxied-model');
+ expect(recordRow.input_tokens).toBe(80);
+ expect(recordRow.output_tokens).toBe(30);
+ });
+});
+
+describe('expand() budget accounting — openai-compatible structured-output (generateObject) path', () => {
+ // No built-in recipe currently opts into supports_structured_outputs (it's
+ // an opt-in per-backend capability declared in ChatTouchpoint — see
+ // recipeSupportsStructuredOutputs()'s own unit test in gateway-chat.test.ts
+ // for the same "no shipped recipe exercises this today" situation). Rather
+ // than mutating a shipped recipe singleton, use the established synthetic-
+ // recipe seam (__setTestRecipesForTests, already used by
+ // no-batch-cap-suppression.serial.test.ts / adaptive-embed-batch.test.ts):
+ // clone litellm under a test-only id with supports_structured_outputs
+ // flipped on, so expand() takes the SECOND generateObject call site (the
+ // one guarded by recipeSupportsStructuredOutputs(recipe)) through the real
+ // resolution path instead of the native-provider branch already covered
+ // above — without touching the real `litellm` recipe object at all.
+ const baseLitellm = getRecipe('litellm')!;
+ const structuredLitellm: Recipe = {
+ ...baseLitellm,
+ id: 'synthetic-structured-litellm',
+ touchpoints: {
+ ...baseLitellm.touchpoints,
+ chat: { ...baseLitellm.touchpoints.chat!, supports_structured_outputs: true },
+ },
+ };
+
+ beforeEach(() => {
+ __setTestRecipesForTests([structuredLitellm]);
+ configureGateway({
+ expansion_model: 'synthetic-structured-litellm:my-proxied-model',
+ env: {},
+ });
+ });
+
+ afterEach(() => {
+ __setTestRecipesForTests([]);
+ });
+
+ test('a successful structured-output expansion records usage — NOT via viaText()', async () => {
+ __setGenerateObjectTransportForTests(async () => ({
+ object: { queries: ['alt one', 'alt two'] },
+ usage: { inputTokens: 55, outputTokens: 22 },
+ }) as any);
+ // If the code regresses to falling through to viaText() (e.g. the
+ // try/catch around the structured call swallows a non-error condition),
+ // this transport must NOT be reached — assert it never fires.
+ let viaTextCalled = false;
+ __setGenerateTextTransportForTests(async () => {
+ viaTextCalled = true;
+ return { text: '{"queries": ["fallback"]}', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+
+ const tracker = new BudgetTracker({ label: 'test-expand-structured', auditPath });
+
+ let result: string[] = [];
+ await withBudgetTracker(tracker, async () => {
+ result = await expand('original query');
+ });
+
+ expect(viaTextCalled).toBe(false);
+ expect(result).toContain('original query');
+ expect(result).toContain('alt one');
+ expect(tracker.snapshot().callsRecorded).toBe(1);
+
+ const rows = readAudit();
+ const recordRow = rows.find(r => r.event === 'record' || r.event === 'record_unpriced');
+ expect(recordRow).toBeTruthy();
+ expect(recordRow.sub_label).toBe('gateway.expand');
+ expect(recordRow.model).toBe('synthetic-structured-litellm:my-proxied-model');
+ expect(recordRow.input_tokens).toBe(55);
+ expect(recordRow.output_tokens).toBe(22);
+ });
+});
diff --git a/test/cycle-lock-steal.serial.test.ts b/test/cycle-lock-steal.serial.test.ts
index e885dc7e65..cf89b9318c 100644
--- a/test/cycle-lock-steal.serial.test.ts
+++ b/test/cycle-lock-steal.serial.test.ts
@@ -105,3 +105,19 @@ test('steal-free cycle still completes and releases normally (regression guard)'
);
expect(rows.length).toBe(0);
});
+
+test("source '__all__' on a lock-free phase selection does not throw (regression guard)", async () => {
+ // `__all__` is the span-every-source sentinel and deliberately FAILS strict
+ // source-id validation (source-id.ts) so it can never leak into lock ids.
+ // A lock-free selection acquires no lock at all, so runCycle must never
+ // evaluate cycleLockIdFor(opts.sourceId) for it — an unconditional
+ // evaluation crashed `gbrain dream --phase orphans --source __all__` with
+ // an uncaught `Invalid source_id`.
+ const report = await runCycle(engine, {
+ brainDir,
+ sourceId: '__all__',
+ phases: ['orphans'],
+ });
+ expect(report.phases.map(p => p.phase)).toEqual(['orphans']);
+ expect(report.reason).not.toBe('lock_stolen');
+});
diff --git a/test/cycle-phase-deadline.test.ts b/test/cycle-phase-deadline.test.ts
new file mode 100644
index 0000000000..89884fb4a4
--- /dev/null
+++ b/test/cycle-phase-deadline.test.ts
@@ -0,0 +1,183 @@
+/**
+ * gbrain#4168 — phase deadlines must clamp to the owning job's absolute
+ * deadline (claim-time timeout_at), or the clean partial-exit path is dead
+ * code: at the default installed-daemon interval the autopilot-cycle timeout
+ * floor (1_800_000ms) EQUALS propose_takes' 30-min phase default, and since
+ * the phase starts after earlier phases, phase-elapsed always trailed
+ * job-elapsed — cycles dead-lettered instead of banking partial work.
+ *
+ * Red-on-master proof: on pre-fix code `deadlineAtMs` is an unknown option
+ * (silently ignored), so the phase runs the full page/take loop and the
+ * deadline_hit assertions below fail AT THE ASSERTION.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ effectivePhaseDeadlineMs,
+ CYCLE_DEADLINE_RESERVE_MS,
+} from '../src/core/cycle/base-phase.ts';
+import { CYCLE_DEADLINE_RESERVE_MS as RESERVE_VIA_PATTERNS } from '../src/core/cycle/patterns.ts';
+import { runPhaseProposeTakes, type ProposeTakesExtractor } from '../src/core/cycle/propose-takes.ts';
+import { runPhaseGradeTakes } from '../src/core/cycle/grade-takes.ts';
+import { runPhaseCalibrationProfile } from '../src/core/cycle/calibration-profile.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+function buildCtx(engine: BrainEngine): OperationContext {
+ return {
+ engine,
+ config: {} as never,
+ logger: { info() {}, warn() {}, error() {} } as never,
+ dryRun: false,
+ remote: false,
+ sourceId: 'default',
+ };
+}
+
+const PAGE_SQL_MARKER = 'SELECT slug, source_id, compiled_truth';
+
+function proposeEngine(pageCount: number): BrainEngine {
+ const pages = Array.from({ length: pageCount }, (_, i) => ({
+ slug: `wiki/p${i}`,
+ source_id: 'default',
+ compiled_truth: `page ${i} prose long enough to be processed by the loop.`,
+ }));
+ return {
+ kind: 'pglite',
+ async executeRaw<T>(sql: string): Promise<T[]> {
+ if (sql.includes(PAGE_SQL_MARKER)) return pages as T[];
+ return [] as T[];
+ },
+ async getConfig() { return null; },
+ } as unknown as BrainEngine;
+}
+
+describe('effectivePhaseDeadlineMs (gbrain#4168)', () => {
+ const NOW = 1_755_300_000_000;
+ const DEFAULT = 30 * 60 * 1000;
+
+ test('no job deadline → phase default', () => {
+ expect(effectivePhaseDeadlineMs(DEFAULT, null, NOW)).toBe(DEFAULT);
+ expect(effectivePhaseDeadlineMs(DEFAULT, undefined, NOW)).toBe(DEFAULT);
+ });
+
+ test('far job deadline → phase default (clamp is a no-op)', () => {
+ const deadlineAt = NOW + 2 * 60 * 60 * 1000; // 2h out
+ expect(effectivePhaseDeadlineMs(DEFAULT, deadlineAt, NOW)).toBe(DEFAULT);
+ });
+
+ test('near job deadline → clamped strictly below remaining budget by the reserve', () => {
+ const deadlineAt = NOW + 10 * 60 * 1000; // 10 min of job budget left
+ const effective = effectivePhaseDeadlineMs(DEFAULT, deadlineAt, NOW);
+ expect(effective).toBe(10 * 60 * 1000 - CYCLE_DEADLINE_RESERVE_MS);
+ // The property the bug violated: effective phase deadline < remaining job budget.
+ expect(effective).toBeLessThan(deadlineAt - NOW);
+ });
+
+ test('the exact pre-fix trap: job floor == phase default still clamps below the floor', () => {
+ const deadlineAt = NOW + 1_800_000; // autopilot-cycle timeout floor
+ const effective = effectivePhaseDeadlineMs(DEFAULT, deadlineAt, NOW);
+ expect(effective).toBe(1_800_000 - CYCLE_DEADLINE_RESERVE_MS);
+ expect(effective).toBeLessThan(1_800_000);
+ });
+
+ test('job budget already inside the reserve → 0, never negative or unlimited', () => {
+ expect(effectivePhaseDeadlineMs(DEFAULT, NOW + CYCLE_DEADLINE_RESERVE_MS - 1, NOW)).toBe(0);
+ expect(effectivePhaseDeadlineMs(DEFAULT, NOW - 1000, NOW)).toBe(0);
+ });
+
+ test('patterns.ts re-export stays the same constant (back-compat)', () => {
+ expect(RESERVE_VIA_PATTERNS).toBe(CYCLE_DEADLINE_RESERVE_MS);
+ });
+});
+
+describe('phases consume deadlineAtMs (red on master: option was ignored)', () => {
+ test('propose_takes with the job budget inside the reserve exits with deadline_hit before any page', async () => {
+ let extractorCalls = 0;
+ const extractor: ProposeTakesExtractor = async () => { extractorCalls++; return []; };
+ const result = await runPhaseProposeTakes(buildCtx(proposeEngine(3)), {
+ extractor,
+ deadlineAtMs: Date.now() - 1, // already past — worst case
+ });
+ const details = result.details as Record<string, unknown>;
+ expect(details.deadline_hit).toBe(true);
+ expect(details.pages_scanned).toBe(0);
+ expect(extractorCalls).toBe(0);
+ });
+
+ test('grade_takes with the job budget inside the reserve exits with deadline_hit before any take', async () => {
+ let judgeCalls = 0;
+ const engine = {
+ kind: 'pglite',
+ async listTakes() {
+ return [{ id: 't1', claim_text: 'c', since_date: '2020-01-01', holder: 'h', weight: 0.5 }];
+ },
+ async executeRaw<T>(): Promise<T[]> { return [] as T[]; },
+ async getConfig() { return null; },
+ } as unknown as BrainEngine;
+ const result = await runPhaseGradeTakes(buildCtx(engine), {
+ judge: (async () => { judgeCalls++; return { verdict: 'right', confidence: 0.9, rationale: 'r' }; }) as never,
+ deadlineAtMs: Date.now() - 1,
+ });
+ const details = result.details as Record<string, unknown>;
+ expect(details.deadline_hit).toBe(true);
+ expect(details.takes_scanned).toBe(0);
+ expect(judgeCalls).toBe(0);
+ expect(result.status).toBe('warn');
+ });
+
+ test('calibration_profile with the job budget inside the reserve skips cleanly (warn + deadline_hit)', async () => {
+ const engine = {
+ kind: 'pglite',
+ async executeRaw<T>(): Promise<T[]> { return [] as T[]; },
+ async getConfig() { return null; },
+ } as unknown as BrainEngine;
+ const result = await runPhaseCalibrationProfile(buildCtx(engine), {
+ deadlineAtMs: Date.now() - 1,
+ });
+ const details = result.details as Record<string, unknown>;
+ expect(details.deadline_hit).toBe(true);
+ expect(result.status).toBe('warn');
+ expect(details.profile_written).toBe(false);
+ });
+
+ test('grade_takes breaks MID-LOOP on the deadline: partial banked, warn status (review gap G5)', async () => {
+ let judgeCalls = 0;
+ const inserts: string[] = [];
+ const engine = {
+ kind: 'pglite',
+ async listTakes() {
+ return [1, 2, 3].map(i => ({ id: i, row_num: i, page_slug: `p/${i}`, claim: `c${i}`, holder: 'h', weight: 0.5, since_date: '2020-01-01' }));
+ },
+ async executeRaw<T>(sql: string): Promise<T[]> {
+ if (sql.includes('INSERT')) inserts.push(sql);
+ return [] as T[];
+ },
+ async getConfig() { return null; },
+ } as unknown as BrainEngine;
+ const result = await runPhaseGradeTakes(buildCtx(engine), {
+ judge: (async () => {
+ judgeCalls++;
+ await new Promise(r => setTimeout(r, 40));
+ return { verdict: 'right', confidence: 0.9, rationale: 'r' };
+ }) as never,
+ evidenceRetriever: (async () => 'some evidence') as never,
+ deadlineMs: 15, // fires after the first (slow) take, before the second
+ });
+ const details = result.details as Record<string, unknown>;
+ expect(details.deadline_hit).toBe(true);
+ expect(Number(details.takes_scanned)).toBeLessThan(3);
+ expect(judgeCalls).toBeLessThan(3); // did NOT run the full list
+ expect(judgeCalls).toBeGreaterThan(0); // …but banked real work first
+ expect(result.status).toBe('warn');
+ expect(result.summary).toContain('[deadline hit — partial]');
+ });
+
+ test('no deadlineAtMs → phases run normally (interactive CLI unaffected)', async () => {
+ const extractor: ProposeTakesExtractor = async () => [];
+ const result = await runPhaseProposeTakes(buildCtx(proposeEngine(2)), { extractor });
+ const details = result.details as Record<string, unknown>;
+ expect(details.deadline_hit).toBe(false);
+ expect(details.pages_scanned).toBe(2);
+ });
+});
diff --git a/test/db-lock-fencing.test.ts b/test/db-lock-fencing.test.ts
index 42c034e74f..79a5e815ab 100644
--- a/test/db-lock-fencing.test.ts
+++ b/test/db-lock-fencing.test.ts
@@ -12,7 +12,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { tryAcquireDbLock, LockStolenError } from '../src/core/db-lock.ts';
-import { startCycleLockRefresher, buildYieldDuringPhase, type LockHandle } from '../src/core/cycle.ts';
+import { startCycleLockRefresher, buildYieldDuringPhase, isLockStolenAbort, type LockHandle } from '../src/core/cycle.ts';
let engine: PGLiteEngine;
@@ -196,3 +196,34 @@ describe('buildYieldDuringPhase steal reporting', () => {
expect(stolen).toBe(false);
});
});
+
+describe('isLockStolenAbort — the steal decision does not depend on the reason (#4140)', () => {
+ // Duck-typed signals on purpose: `abort()` and `abort(undefined)` BOTH yield a
+ // DOMException, so `reason: undefined` — the state the runtime actually
+ // delivers — is unreachable through AbortController. This is the only way to
+ // pin it deterministically instead of waiting for the ~1-in-20 flake.
+
+ test('a steal with the reason DROPPED still classifies as a steal', () => {
+ expect(isLockStolenAbort({ aborted: true, reason: undefined }, undefined)).toBe(true);
+ });
+
+ test('a steal with the reason intact classifies as a steal (unchanged)', () => {
+ expect(isLockStolenAbort({ aborted: true, reason: new LockStolenError('x') }, undefined)).toBe(true);
+ });
+
+ test('no steal when the controller never fired', () => {
+ expect(isLockStolenAbort({ aborted: false }, undefined)).toBe(false);
+ expect(isLockStolenAbort(undefined, undefined)).toBe(false);
+ });
+
+ test('an external abort still wins — it keeps the throw-out contract', () => {
+ // Both with and without a surviving reason, so the external conjunct is
+ // pinned independently of the reason.
+ expect(isLockStolenAbort({ aborted: true, reason: new LockStolenError('x') }, { aborted: true })).toBe(false);
+ expect(isLockStolenAbort({ aborted: true, reason: undefined }, { aborted: true })).toBe(false);
+ });
+
+ test('a non-aborted external signal does not suppress the steal', () => {
+ expect(isLockStolenAbort({ aborted: true, reason: undefined }, { aborted: false })).toBe(true);
+ });
+});
diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.ts
index ddf2f28bc7..3b787c4d33 100644
--- a/test/destructive-guard.test.ts
+++ b/test/destructive-guard.test.ts
@@ -379,9 +379,10 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
`UPDATE sources SET archive_expires_at = now() - INTERVAL '1 hour' WHERE id = $1`,
[expiredId],
);
- const purged = await purgeExpiredSources(engine);
+ const { purged, blocked } = await purgeExpiredSources(engine);
expect(purged).toContain(expiredId);
expect(purged).not.toContain(recoverableId);
+ expect(blocked).toEqual([]);
const remainingPages = await engine.executeRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1`,
[expiredId],
@@ -389,6 +390,41 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
expect(remainingPages[0].n).toBe(0);
});
+ test('gbrain#4115 — an FK-blocked source is reported and skipped; the deletable one still purges', async () => {
+ const blockedId = 'pe-fk-blocked';
+ const deletableId = 'pe-fk-deletable';
+ await seedSource(engine, blockedId, { withPages: 1 });
+ await seedSource(engine, deletableId, { withPages: 1 });
+ await softDeleteSource(engine, blockedId);
+ await softDeleteSource(engine, deletableId);
+ await engine.executeRaw(
+ `UPDATE sources SET archive_expires_at = now() - INTERVAL '1 hour' WHERE id IN ($1, $2)`,
+ [blockedId, deletableId],
+ );
+ // A revoked-but-retained oauth client (soft-deleted via deleted_at) under
+ // v64's ON DELETE RESTRICT — the exact production shape from the report.
+ await engine.executeRaw(
+ `INSERT INTO oauth_clients (client_id, client_name, source_id, deleted_at)
+ VALUES ('cl-4115-test', 'test client', $1, now())`,
+ [blockedId],
+ );
+ const { purged, blocked } = await purgeExpiredSources(engine);
+ expect(purged).toContain(deletableId);
+ expect(purged).not.toContain(blockedId);
+ expect(blocked.map((b) => b.id)).toEqual([blockedId]);
+ expect(blocked[0].reason).toContain('RESTRICT');
+ // The blocked source is untouched (still archived, still expired) — the
+ // next sweep retries it after the operator clears the client.
+ const still = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM sources WHERE id = $1 AND archived = true`,
+ [blockedId],
+ );
+ expect(still[0].n).toBe(1);
+ // Cleanup so later tests are unaffected.
+ await engine.executeRaw(`DELETE FROM oauth_clients WHERE client_id = 'cl-4115-test'`);
+ await engine.executeRaw(`DELETE FROM sources WHERE id = $1`, [blockedId]);
+ });
+
test('purgeExpiredSources is no-op when nothing is past TTL', async () => {
// After all earlier tests, there may still be archived rows whose
// archive_expires_at is in the future. Force-update any leftover-past
@@ -397,8 +433,33 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
await engine.executeRaw(
`UPDATE sources SET archive_expires_at = now() + INTERVAL '72 hours' WHERE archived = true`,
);
- const purged = await purgeExpiredSources(engine);
+ const result = await purgeExpiredSources(engine);
+ expect(result.purged).toEqual([]);
+ expect(result.blocked).toEqual([]);
+ });
+
+ test('gbrain#4115 — a NON-FK error re-raises instead of reading as blocked (review gap G8)', async () => {
+ const stub = {
+ async executeRaw(sql: string): Promise<Array<{ id: string }>> {
+ if (sql.trimStart().startsWith('SELECT')) return [{ id: 'boom' }];
+ const err = new Error('canceling statement due to statement timeout') as Error & { code: string };
+ err.code = '57014'; // query_canceled — NOT the FK class
+ throw err;
+ },
+ } as never;
+ await expect(purgeExpiredSources(stub)).rejects.toThrow('statement timeout');
+ });
+
+ test('gbrain#4115 — a source restored between SELECT and DELETE is neither purged nor blocked (review gap G8)', async () => {
+ const stub = {
+ async executeRaw(sql: string): Promise<Array<{ id: string }>> {
+ if (sql.trimStart().startsWith('SELECT')) return [{ id: 'restored-mid-sweep' }];
+ return []; // per-id DELETE re-checks the expiry predicate → 0 rows
+ },
+ } as never;
+ const { purged, blocked } = await purgeExpiredSources(stub);
expect(purged).toEqual([]);
+ expect(blocked).toEqual([]);
});
});
@@ -493,7 +554,11 @@ describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () =>
expect(formatImpact(impact!)).not.toContain('OAuth client');
});
- test('purgeExpiredSources purges only the unreferenced expired source and warns naming the skipped id', async () => {
+ test('purgeExpiredSources purges only the unreferenced expired source and reports the FK-held one as blocked', async () => {
+ // Ported from #4238's string[]-contract version at merge: the sweep now
+ // returns {purged, blocked} (chennai #4115 fix) — the skipped id and its
+ // revoke guidance live in the structured result, not a stderr warn
+ // (callers render it).
await seedSource(engine, 'fk-purge-ref', { withPages: 1 });
await seedSource(engine, 'fk-purge-free', { withPages: 1 });
await seedClient('cl-purge-ref', 'fk-purge-ref');
@@ -504,37 +569,21 @@ describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () =>
[['fk-purge-ref', 'fk-purge-free']],
);
- const errSpy = spyOn(console, 'error').mockImplementation(() => {});
- let purged: string[];
- let errCalls: string[];
- try {
- purged = await purgeExpiredSources(engine);
- } finally {
- // Snapshot BEFORE restore — mockRestore() clears mock.calls.
- errCalls = errSpy.mock.calls.map((c) => String(c[0]));
- errSpy.mockRestore();
- }
-
- // Return contract preserved: string[] of purged ids ONLY — exactly the
- // unreferenced one.
+ const { purged, blocked } = await purgeExpiredSources(engine);
+
expect(purged).toEqual(['fk-purge-free']);
+ expect(blocked.map((b) => b.id)).toEqual(['fk-purge-ref']);
+ expect(blocked[0].reason).toContain('revoke-client');
- // Referenced source survives (skipped, not FK-crashed).
+ // Referenced source survives (blocked, not FK-crashed).
const remaining = await engine.executeRaw<{ id: string }>(
`SELECT id FROM sources WHERE id = ANY($1::text[])`,
[['fk-purge-ref', 'fk-purge-free']],
);
expect(remaining.map((r) => r.id)).toEqual(['fk-purge-ref']);
-
- // ONE stderr warn naming the skipped id + revoke guidance.
- const warns = errCalls.filter((m) => m.includes('purge skipped'));
- expect(warns.length).toBe(1);
- expect(warns[0]).toContain('fk-purge-ref');
- expect(warns[0]).toContain('revoke-client');
- expect(warns[0]).not.toContain('fk-purge-free');
});
- test('purge skip is PHYSICAL: a soft-deleted client row still blocks (FK ignores deleted_at)', async () => {
+ test('purge block is PHYSICAL: a soft-deleted client row still blocks (FK ignores deleted_at)', async () => {
await seedSource(engine, 'fk-purge-dead', { withPages: 1 });
await seedClient('cl-purge-dead', 'fk-purge-dead', { deleted: true });
await softDeleteSource(engine, 'fk-purge-dead');
@@ -543,15 +592,10 @@ describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () =>
['fk-purge-dead'],
);
- const errSpy = spyOn(console, 'error').mockImplementation(() => {});
- let purged: string[];
- try {
- purged = await purgeExpiredSources(engine);
- } finally {
- errSpy.mockRestore();
- }
+ const { purged, blocked } = await purgeExpiredSources(engine);
expect(purged).not.toContain('fk-purge-dead');
+ expect(blocked.map((b) => b.id)).toContain('fk-purge-dead');
const rows = await engine.executeRaw<{ id: string }>(
`SELECT id FROM sources WHERE id = $1`, ['fk-purge-dead'],
);
@@ -617,20 +661,19 @@ describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () =>
} as any;
expect(await clientsReferencingSource(noSourceId, 'x')).toEqual([]);
- // Same brain shape must not break the purge path either: the skip-set
- // query 42703s, and the purge falls back to the unconditional DELETE.
- let sawUnconditionalDelete = false;
+ // Same brain shape must not break the purge path either. The per-source
+ // sweep (chennai #4115) never queries oauth_clients at all — the FK, if
+ // present, surfaces as SQLSTATE 23503 on the DELETE — so a pre-v61 brain
+ // shape purges through the exact same code path.
+ let sawOauthQuery = false;
const purgeStub = {
executeRaw: async (sql: string) => {
- if (sql.includes('oauth_clients')) {
- throw Object.assign(new Error('column "source_id" does not exist'), { code: '42703' });
- }
- if (sql.startsWith('DELETE FROM sources')) sawUnconditionalDelete = true;
+ if (sql.includes('oauth_clients')) sawOauthQuery = true;
return [];
},
} as any;
- expect(await purgeExpiredSources(purgeStub)).toEqual([]);
- expect(sawUnconditionalDelete).toBe(true);
+ expect(await purgeExpiredSources(purgeStub)).toEqual({ purged: [], blocked: [] });
+ expect(sawOauthQuery).toBe(false);
});
});
diff --git a/test/doctor-timeline-metric-labels-2298.test.ts b/test/doctor-timeline-metric-labels-2298.test.ts
index 96c7420c27..eb4a1065e4 100644
--- a/test/doctor-timeline-metric-labels-2298.test.ts
+++ b/test/doctor-timeline-metric-labels-2298.test.ts
@@ -13,7 +13,7 @@
* explicitly and keeps BOTH the entity CLI line and the whole-brain line.
*
* Tests (no private EriadorMu data, no production/home DB, no network):
- * - numeric denominator assertions (Metric A = 50%, Metric B = 4/15)
+ * - numeric denominator assertions (Metric A = 50%, Metric B = 6/15)
* - doctor rendered-message assertions (exact labels, no ambiguous old label)
* - CLI rendered-output assertions (exact lines, guard matrix)
* - red/green: same assertions FAIL on origin/master, PASS on this branch
@@ -32,19 +32,29 @@ let engine: PGLiteEngine;
async function seedFourPages(eng: PGLiteEngine): Promise<void> {
const sql = sqlQueryForEngine(eng);
- // 2 eligible entity pages, 2 technical/non-entity pages.
- // Only ONE entity page has a timeline entry; only ONE total page does.
+ // 6 eligible entity pages (>= the gbrain#4147 small-N floor of 5, so the
+ // entity ratio is a real percentage rather than the below-floor null),
+ // 2 technical/non-entity pages. THREE entity pages carry timeline entries:
+ // Metric A (entity-scoped): 3/6 = 50% (same 50% the contract pins)
+ // Metric B (whole-brain): 3/8 -> round(15 * 0.375) = 6/15
+ // The two stay provably distinct (50% vs 40%).
await sql`
INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
VALUES
('acme-example', 'default', 'company', 'Acme', '', '{}', 'h1', now(), now()),
('alice-example', 'default', 'person', 'Alice', '', '{}', 'h2', now(), now()),
+ ('bob-example', 'default', 'person', 'Bob', '', '{}', 'h5', now(), now()),
+ ('carol-example', 'default', 'person', 'Carol', '', '{}', 'h6', now(), now()),
+ ('widget-co-example', 'default', 'company', 'Widget Co', '', '{}', 'h7', now(), now()),
+ ('dana-example', 'default', 'person', 'Dana', '', '{}', 'h8', now(), now()),
('technical-a', 'default', 'note', 'Tech A', '', '{}', 'h3', now(), now()),
('technical-b', 'default', 'note', 'Tech B', '', '{}', 'h4', now(), now())
`;
- const companyId = (await sql`SELECT id FROM pages WHERE slug='acme-example'`)[0].id as number;
- await sql`INSERT INTO timeline_entries (page_id, date, source, summary, detail)
- VALUES (${companyId}, CURRENT_DATE, 'test', 'milestone', '{}')`;
+ for (const slug of ['acme-example', 'alice-example', 'bob-example']) {
+ const pid = (await sql`SELECT id FROM pages WHERE slug=${slug}`)[0].id as number;
+ await sql`INSERT INTO timeline_entries (page_id, date, source, summary, detail)
+ VALUES (${pid}, CURRENT_DATE, 'test', 'milestone', '{}')`;
+ }
}
beforeAll(async () => {
@@ -62,26 +72,26 @@ beforeEach(async () => {
});
describe('issue #2298 — numeric denominator semantics', () => {
- test('entity timeline coverage = 1/2 = 50% (2 eligible entities, 1 with timeline)', async () => {
+ test('entity timeline coverage = 3/6 = 50% (6 eligible entities, 3 with timeline)', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(health.timeline_coverage).toBeDefined();
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
});
- test('whole-brain timeline density = 1/4 -> score 4/15 (4 total pages, 1 with timeline)', async () => {
+ test('whole-brain timeline density = 3/8 -> score 6/15 (8 total pages, 3 with timeline)', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(health.timeline_coverage_score).toBeDefined();
- expect(health.timeline_coverage_score).toBe(4);
+ expect(health.timeline_coverage_score).toBe(6);
});
test('the two metrics use independent denominators', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
- expect(health.timeline_coverage_score ?? 0).toBe(4);
- // 50% (entity, /2) != 26.7% (whole-brain, /4). Provably distinct.
+ expect(health.timeline_coverage_score ?? 0).toBe(6);
+ // 50% (entity, /6) != 40% (whole-brain, 6/15). Provably distinct.
expect(Math.round(((health.timeline_coverage_score ?? 0) / 15) * 100)).not.toBe(50);
});
});
@@ -98,17 +108,17 @@ describe('issue #2298 — doctor rendered-message contract', () => {
expect(graph!.message).not.toMatch(/timeline \(entity, brain score\)/);
});
- test('brain_score renders whole-brain density label 4/15', async () => {
+ test('brain_score renders whole-brain density label 6/15', async () => {
await seedFourPages(engine);
const checks = await buildChecks(engine, [], null);
const brain = checks.find((c) => c.name === 'brain_score');
expect(brain, 'brain_score check must be present').toBeDefined();
- expect(brain!.message).toContain('timeline density (all pages) 4/15');
+ expect(brain!.message).toContain('timeline density (all pages) 6/15');
// wrong labels must NOT be present
- expect(brain!.message).not.toMatch(/timeline 4\/15/);
+ expect(brain!.message).not.toMatch(/timeline 6\/15/);
expect(brain!.message).not.toMatch(/timeline \(entity, brain score\)/);
// brain-score component must NOT carry the word "entity" (it is whole-brain)
- const timelinePart = brain!.message.split('timeline density (all pages) 4/15')[0] + 'timeline density (all pages) 4/15';
+ const timelinePart = brain!.message.split('timeline density (all pages) 6/15')[0] + 'timeline density (all pages) 6/15';
expect(timelinePart).not.toMatch(/entity/);
});
});
@@ -129,7 +139,7 @@ describe('issue #2298 — CLI get_health rendered-output contract', () => {
expect(out).not.toContain('undefined/15');
expect(out).not.toContain('Timeline coverage (entities)');
expect(out).not.toMatch(/timeline \(entity, brain score\)/);
- expect(out).not.toMatch(/bare "timeline 4\/15"/);
+ expect(out).not.toMatch(/bare "timeline 6\/15"/);
});
test('guard matrix: entity present, whole-brain absent -> only entity line', () => {
diff --git a/test/dream-clean-status-skip-visibility.test.ts b/test/dream-clean-status-skip-visibility.test.ts
new file mode 100644
index 0000000000..7619b9b3fb
--- /dev/null
+++ b/test/dream-clean-status-skip-visibility.test.ts
@@ -0,0 +1,172 @@
+/**
+ * Regression coverage for the `gbrain dream --input <file>` diagnostic gap:
+ * an already-synthesized transcript used to report status='clean' with a
+ * bare "Brain is healthy" line and NO indication that anything was
+ * examined and skipped (or that the queue's idempotency_key dedupe
+ * silently reused a prior job instead of doing new work).
+ *
+ * Two independent fixes, pinned at function granularity (no DB needed —
+ * both `deriveStatus` and `printHuman` are pure functions of a CycleReport):
+ *
+ * 1. `deriveStatus` (src/core/cycle.ts) now folds
+ * totals.transcripts_processed / totals.synth_pages_written into
+ * `anyWork`. A synthesize-only cycle (which --input implies) never
+ * touches sync/embed/lint/etc, so those totals staying zero used to
+ * force status='clean' even when synthesize genuinely processed a
+ * transcript or wrote pages.
+ * 2. `printHuman` (src/commands/dream.ts) no longer short-circuits a
+ * 'clean' report before checking each phase's `details.skips` — the
+ * synthesize phase's D8 (legacy-key) / D5 (oversize-chunk) skip
+ * reasons are now printed even when overall status stays 'clean'
+ * (e.g. every worth-processing transcript was skipped, so
+ * transcripts_processed/synth_pages_written are also 0).
+ *
+ * Run: bun test test/dream-clean-status-skip-visibility.test.ts
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { __testing as cycleTesting, type CycleReport, type PhaseResult } from '../src/core/cycle.ts';
+import { __testing as dreamTesting } from '../src/commands/dream.ts';
+
+const { deriveStatus } = cycleTesting;
+const { printHuman } = dreamTesting;
+
+function emptyTotals(): CycleReport['totals'] {
+ return {
+ lint_fixes: 0,
+ backlinks_added: 0,
+ pages_synced: 0,
+ pages_extracted: 0,
+ pages_embedded: 0,
+ orphans_found: 0,
+ transcripts_processed: 0,
+ synth_pages_written: 0,
+ patterns_written: 0,
+ pages_emotional_weight_recomputed: 0,
+ edges_resolved: 0,
+ edges_ambiguous: 0,
+ purged_sources_count: 0,
+ purged_pages_count: 0,
+ facts_consolidated: 0,
+ consolidate_takes_written: 0,
+ phantoms_redirected: 0,
+ phantoms_ambiguous: 0,
+ phantoms_skipped_drift: 0,
+ };
+}
+
+function synthesizePhase(details: Record<string, unknown>, summary = 'synthesize ran'): PhaseResult {
+ return {
+ phase: 'synthesize',
+ status: 'ok',
+ duration_ms: 200,
+ summary,
+ details,
+ };
+}
+
+function report(phases: PhaseResult[], totals: CycleReport['totals']): CycleReport {
+ return {
+ schema_version: '1',
+ timestamp: new Date().toISOString(),
+ duration_ms: 200,
+ status: deriveStatus(phases, totals),
+ brain_dir: '/tmp/brain',
+ phases,
+ totals,
+ };
+}
+
+/** Capture everything printHuman writes to console.log during `body()`. */
+function captureLog(body: () => void): string[] {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ body();
+ } finally {
+ console.log = original;
+ }
+ return lines;
+}
+
+describe('deriveStatus — synthesize-only activity is not invisible', () => {
+ test('transcripts_processed > 0 (queue idempotency_key reuse: no pages, no lint/sync/embed) → ok, not clean', () => {
+ const totals = emptyTotals();
+ totals.transcripts_processed = 1; // reused an already-completed v2 job
+ const phases = [synthesizePhase({ transcripts_processed: 1, pages_written: 0, skips: [] })];
+ expect(deriveStatus(phases, totals)).toBe('ok');
+ });
+
+ test('synth_pages_written > 0 alone (transcripts_processed miscounted 0) → ok, not clean', () => {
+ const totals = emptyTotals();
+ totals.synth_pages_written = 2;
+ const phases = [synthesizePhase({ pages_written: 2 })];
+ expect(deriveStatus(phases, totals)).toBe('ok');
+ });
+
+ test('genuinely idle synthesize (0 transcripts, 0 pages) still reports clean', () => {
+ const totals = emptyTotals();
+ const phases = [synthesizePhase({ transcripts_processed: 0, pages_written: 0 }, 'no transcripts to process')];
+ expect(deriveStatus(phases, totals)).toBe('clean');
+ });
+
+ test('D8/D5 skip-only run (worth-processing transcript fully skipped) still reports clean', () => {
+ // Mirrors runPhaseSynthesize's D8 legacy-key branch: worthProcessing had
+ // 1 entry, skipReports absorbed it, so submittedTranscripts=0 and no
+ // pages were written — deriveStatus correctly stays 'clean' here; it's
+ // printHuman's job (below) to surface *why*.
+ const totals = emptyTotals();
+ const phases = [synthesizePhase({
+ transcripts_processed: 0,
+ pages_written: 0,
+ skips: [{ filePath: '/tmp/corpus/2026-08-15.txt', reason: 'already_synthesized_legacy_chunked' }],
+ }, '0 transcript(s) synthesized in 0.0s')];
+ expect(deriveStatus(phases, totals)).toBe('clean');
+ });
+});
+
+describe('printHuman — a clean cycle still surfaces skip reasons', () => {
+ test('clean + non-empty details.skips prints the skip reason, not just "Brain is healthy"', () => {
+ const totals = emptyTotals();
+ const phases = [synthesizePhase({
+ transcripts_processed: 0,
+ pages_written: 0,
+ skips: [{ filePath: '/tmp/corpus/2026-08-15.txt', reason: 'already_synthesized_legacy_chunked' }],
+ }, '0 transcript(s) synthesized in 0.0s')];
+ const r = report(phases, totals);
+ expect(r.status).toBe('clean');
+
+ const lines = captureLog(() => printHuman(r));
+ expect(lines[0]).toContain('Brain is healthy');
+ const skipLine = lines.find(l => l.includes('already_synthesized_legacy_chunked'));
+ expect(skipLine).toBeDefined();
+ expect(skipLine).toContain('/tmp/corpus/2026-08-15.txt');
+ });
+
+ test('clean + empty skips prints only the healthy line (no regression for the idle case)', () => {
+ const totals = emptyTotals();
+ const phases = [synthesizePhase({ transcripts_processed: 0, pages_written: 0 }, 'no transcripts to process')];
+ const r = report(phases, totals);
+ expect(r.status).toBe('clean');
+
+ const lines = captureLog(() => printHuman(r));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('Brain is healthy');
+ });
+
+ test('ok status (transcripts_processed>0 via deriveStatus fix) prints the per-phase summary + totals line', () => {
+ const totals = emptyTotals();
+ totals.transcripts_processed = 1;
+ const phases = [synthesizePhase(
+ { transcripts_processed: 1, pages_written: 0, skips: [] },
+ '1 transcript(s) synthesized in 0.0s',
+ )];
+ const r = report(phases, totals);
+ expect(r.status).toBe('ok');
+
+ const lines = captureLog(() => printHuman(r));
+ expect(lines.some(l => l.includes('synthesize') && l.includes('1 transcript(s) synthesized'))).toBe(true);
+ expect(lines.some(l => l.includes('synth_transcripts=1'))).toBe(true);
+ });
+});
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index 86c3346136..6e952c5db5 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -321,21 +321,20 @@ describe.skipIf(!DATABASE_URL)('Postgres bootstrap verify (real Postgres)', () =
const magic = res.checks.find((c) => c.id === 'magic_moment');
expect(magic?.ok).toBe(true);
- // Probe cleanup [G13] must hold on the Postgres DDL path too. Verify
- // cleans up through the real delete_page op, which is a SOFT delete
- // (deleted_at stamp) — so assert no ACTIVE probe rows remain, and pin
- // that the probes went through the soft-delete path rather than never
- // being cleaned at all.
+ // Probe cleanup [G13] must hold on the Postgres DDL path too. Since
+ // v0.46.6.0 (#4170, closing #4142) verify's probe cleanup HARD-deletes
+ // via the trusted engine primitive — probes are not user content and
+ // verify is a trusted local caller; the old soft-delete path left
+ // tombstones in user brains until the 72h purge. Assert NO probe rows
+ // remain at all, active or tombstoned. (This hunk shipped in #4171
+ // still asserting the pre-#4170 soft-delete contract — the merge-base
+ // collision flagged in that PR's review thread — and broke the Postgres
+ // e2e lane on master; repaired here.)
const probePages = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3) AND deleted_at IS NULL`,
+ `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3)`,
['workspace', VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],
);
expect(probePages[0].n).toBe(0);
- const probeTombstones = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1 AND slug IN ($2, $3) AND deleted_at IS NOT NULL`,
- ['workspace', VERIFY_PROBE_SLUG, VERIFY_PROBE_ENTITY_SLUG],
- );
- expect(probeTombstones[0].n).toBe(2);
const probeFacts = await engine.executeRaw<{ n: number }>(
`SELECT COUNT(*)::int AS n FROM facts WHERE source_id = $1 AND source_markdown_slug = $2`,
['workspace', VERIFY_PROBE_SLUG],
diff --git a/test/e2e/eval-contradictions-postgres.test.ts b/test/e2e/eval-contradictions-postgres.test.ts
index 6da325fe99..974d2cad12 100644
--- a/test/e2e/eval-contradictions-postgres.test.ts
+++ b/test/e2e/eval-contradictions-postgres.test.ts
@@ -273,8 +273,8 @@ describe('E2E: find_contradictions MCP op on Postgres', () => {
contradictions: [
{
kind: 'cross_slug_chunks',
- a: { slug: 'companies/acme-example', chunk_id: 1, take_id: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
- b: { slug: 'openclaw/chat/x', chunk_id: 2, take_id: null, source_tier: 'bulk', holder: null, text: 'b', effective_date: null, effective_date_source: null },
+ a: { slug: 'companies/acme-example', chunk_id: 1, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
+ b: { slug: 'openclaw/chat/x', chunk_id: 2, take_id: null, take_row_num: null, source_tier: 'bulk', holder: null, text: 'b', effective_date: null, effective_date_source: null },
combined_score: 1.5,
verdict: 'contradiction',
severity: 'high',
@@ -285,8 +285,8 @@ describe('E2E: find_contradictions MCP op on Postgres', () => {
},
{
kind: 'cross_slug_chunks',
- a: { slug: 'people/alice-example', chunk_id: 3, take_id: null, source_tier: 'curated', holder: null, text: 'c', effective_date: null, effective_date_source: null },
- b: { slug: 'people/alice-smith-example', chunk_id: 4, take_id: null, source_tier: 'curated', holder: null, text: 'd', effective_date: null, effective_date_source: null },
+ a: { slug: 'people/alice-example', chunk_id: 3, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'c', effective_date: null, effective_date_source: null },
+ b: { slug: 'people/alice-smith-example', chunk_id: 4, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'd', effective_date: null, effective_date_source: null },
combined_score: 1.2,
verdict: 'contradiction',
severity: 'low',
diff --git a/test/e2e/subagent-gateway-path.test.ts b/test/e2e/subagent-gateway-path.test.ts
index 98fdfdb070..b46cc93b59 100644
--- a/test/e2e/subagent-gateway-path.test.ts
+++ b/test/e2e/subagent-gateway-path.test.ts
@@ -252,13 +252,91 @@ describe('runSubagentViaGateway (v0.38 Slice 1 — full handler path through gat
expect(toolRows[0].ordinal).toBe(0);
expect(toolRows[0].schema_version).toBe(2); // v0.38 write
expect(String(toolRows[0].gbrain_tool_use_id)).toMatch(/^[0-9a-f-]{36}$/); // UUID v7
- expect(toolRows[0].tool_use_id).toBe('provider-tc-1'); // provider id preserved
+ expect(toolRows[0].tool_use_id).toBe('provider-tc-1'); // raw provider id preserved (#4155)
// Token accumulation across both turns.
expect(result.tokens.in).toBe(45); // 20 + 25
expect(result.tokens.out).toBe(12); // 8 + 4
});
+ it('#4155 regression: two different tool calls sharing the SAME provider id persist as two rows with the raw id intact', async () => {
+ // Real-world shape: claude-cli replays a fresh subprocess per turn from
+ // an id-stripped transcript, so the model invents the SAME short id
+ // ("toolu_01") for the first tool call of every turn. Pre-fix, the second
+ // turn's INSERT collided on the former job-wide `uniq_subagent_tools_use_id
+ // UNIQUE (job_id, tool_use_id)` constraint (a DIFFERENT constraint than
+ // this INSERT's own conflict target `(job_id, message_idx, ordinal)`) and
+ // threw, dead-lettering the job after 3 attempts. Migration v131 dropped
+ // that constraint; the raw provider id is stored as-is and row identity
+ // is (job_id, message_idx, ordinal).
+ let turn = 0;
+ __setChatTransportForTests(async () => {
+ turn++;
+ if (turn === 1) {
+ return {
+ text: '',
+ blocks: [{ type: 'tool-call', toolCallId: 'toolu_01', toolName: 'search', input: { q: 'first' } }] as ChatBlock[],
+ stopReason: 'tool_calls',
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ } satisfies ChatResult;
+ }
+ if (turn === 2) {
+ return {
+ text: '',
+ blocks: [{ type: 'tool-call', toolCallId: 'toolu_01', toolName: 'put_page', input: { slug: 'x' } }] as ChatBlock[],
+ stopReason: 'tool_calls',
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ } satisfies ChatResult;
+ }
+ return {
+ text: 'both done',
+ blocks: [{ type: 'text', text: 'both done' }] as ChatBlock[],
+ stopReason: 'end',
+ usage: { input_tokens: 5, output_tokens: 3, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6',
+ providerId: 'anthropic',
+ } satisfies ChatResult;
+ });
+
+ const executions: Array<{ name: string; input: unknown; ts: number }> = [];
+ const tools = makeStubTools(executions);
+ const handler = buildHandler(tools);
+ const { jobId, ctx } = await makeFakeJob({
+ prompt: 'do two things',
+ model: 'anthropic:claude-sonnet-4-6',
+ allowed_tools: ['search', 'put_page'],
+ });
+
+ const result = await handler(ctx);
+
+ expect(result.result).toBe('both done');
+ expect(result.stop_reason).toBe('end_turn');
+ expect(executions.map(e => e.name)).toEqual(['search', 'put_page']);
+
+ const toolRows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT message_idx, tool_use_id, tool_name, status
+ FROM subagent_tool_executions
+ WHERE job_id = $1
+ ORDER BY message_idx`,
+ [jobId],
+ );
+ // Both rows persisted — the collision never threw.
+ expect(toolRows.length).toBe(2);
+ expect(toolRows[0].tool_name).toBe('search');
+ expect(toolRows[1].tool_name).toBe('put_page');
+ expect(toolRows[0].status).toBe('complete');
+ expect(toolRows[1].status).toBe('complete');
+ // The RAW provider id is stored on both rows — readers disambiguate by
+ // message_idx, which must differ across the two turns.
+ expect(toolRows[0].tool_use_id).toBe('toolu_01');
+ expect(toolRows[1].tool_use_id).toBe('toolu_01');
+ expect(toolRows[0].message_idx).not.toBe(toolRows[1].message_idx);
+ });
+
it('tool error path: handler persists status=failed, loop continues with error feedback', async () => {
let turn = 0;
__setChatTransportForTests(async () => {
diff --git a/test/eval-contradictions-auto-supersession.test.ts b/test/eval-contradictions-auto-supersession.test.ts
index 44a248998f..1c13458f9a 100644
--- a/test/eval-contradictions-auto-supersession.test.ts
+++ b/test/eval-contradictions-auto-supersession.test.ts
@@ -17,17 +17,17 @@ import type {
function mkCrossSlugPair(slugA: string, slugB: string): ContradictionPair {
return {
kind: 'cross_slug_chunks',
- a: { slug: slugA, chunk_id: 1, take_id: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
- b: { slug: slugB, chunk_id: 2, take_id: null, source_tier: 'bulk', holder: null, text: 'b', effective_date: null, effective_date_source: null },
+ a: { slug: slugA, chunk_id: 1, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
+ b: { slug: slugB, chunk_id: 2, take_id: null, take_row_num: null, source_tier: 'bulk', holder: null, text: 'b', effective_date: null, effective_date_source: null },
combined_score: 1,
};
}
-function mkIntraPagePair(pageSlug: string, takeId: number): ContradictionPair {
+function mkIntraPagePair(pageSlug: string, takeId: number, takeRowNum: number | null = 2): ContradictionPair {
return {
kind: 'intra_page_chunk_take',
- a: { slug: pageSlug, chunk_id: 5, take_id: null, source_tier: 'curated', holder: null, text: 'chunk text', effective_date: null, effective_date_source: null },
- b: { slug: pageSlug, chunk_id: null, take_id: takeId, source_tier: 'curated', holder: 'garry', text: 'take claim', effective_date: null, effective_date_source: null },
+ a: { slug: pageSlug, chunk_id: 5, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'chunk text', effective_date: null, effective_date_source: null },
+ b: { slug: pageSlug, chunk_id: null, take_id: takeId, take_row_num: takeRowNum, source_tier: 'curated', holder: 'garry', text: 'take claim', effective_date: null, effective_date_source: null },
combined_score: 1,
};
}
@@ -43,9 +43,9 @@ describe('classifyResolution', () => {
expect(classifyResolution(pair, 'dream_synthesize')).toBe('dream_synthesize');
});
- test('cross_slug + judge hint takes_mark_debate → honored', () => {
+ test('cross_slug + judge hint takes_mark_debate → manual_review (gbrain#4169: the subcommand does not exist, tracked in #4102)', () => {
const pair = mkCrossSlugPair('originals/talk', 'writing/essay');
- expect(classifyResolution(pair, 'takes_mark_debate')).toBe('takes_mark_debate');
+ expect(classifyResolution(pair, 'takes_mark_debate')).toBe('manual_review');
});
test('cross_slug + no judge hint + curated entity → dream_synthesize fallback', () => {
@@ -67,22 +67,58 @@ describe('classifyResolution', () => {
});
describe('renderResolutionCommand', () => {
- test('takes_supersede emits gbrain takes supersede with row id', () => {
- const pair = mkIntraPagePair('people/alice', 7);
+ test('gbrain#4169 — takes_supersede addresses --row with the PER-PAGE row_num, not the global take id', () => {
+ // take_id 7 (global PK) vs row_num 2 (what the CLI resolves): the pre-fix
+ // command `--row 7` errored "Row #7 not found" on every generated
+ // resolution. --claim is required by cmdSupersede; a chunk-vs-take pair
+ // has no unambiguous winner claim, so an explicit placeholder renders.
+ const pair = mkIntraPagePair('people/alice', 7, 2);
const cmd = renderResolutionCommand(pair, 'takes_supersede');
- expect(cmd).toBe('gbrain takes supersede people/alice --row 7');
+ expect(cmd).toBe(`gbrain takes supersede 'people/alice' --row 2 --claim '<replacement claim — see contradiction report>'`);
+ expect(cmd).not.toContain('--row 7');
});
test('dream_synthesize targets the curated entity side', () => {
const pair = mkCrossSlugPair('openclaw/chat/x', 'companies/acme');
const cmd = renderResolutionCommand(pair, 'dream_synthesize');
- expect(cmd).toBe('gbrain dream --phase synthesize --slug companies/acme');
+ expect(cmd).toBe(`gbrain dream --phase synthesize --slug 'companies/acme'`);
});
- test('takes_mark_debate emits mark-debate with row id', () => {
- const pair = mkIntraPagePair('people/alice', 12);
+ test('gbrain#4169 — legacy takes_mark_debate rows render a truthful manual-review hint (subcommand does not exist)', () => {
+ const pair = mkIntraPagePair('people/alice', 12, 3);
const cmd = renderResolutionCommand(pair, 'takes_mark_debate');
- expect(cmd).toBe('gbrain takes mark-debate people/alice --row 12');
+ expect(cmd).toContain('# manual review');
+ expect(cmd).toContain('#4102');
+ expect(cmd).toContain('row 3');
+ expect(cmd).not.toContain('gbrain takes mark-debate');
+ });
+
+ test('gbrain#4169 — temporal_supersede with a take winner renders paste-ready with the shell-escaped winning claim', () => {
+ const pair: ContradictionPair = {
+ kind: 'intra_page_chunk_take',
+ a: { slug: 'people/alice', chunk_id: null, take_id: 40, take_row_num: 1, source_tier: 'curated', holder: 'garry', text: "old take: it's the CFO's call", effective_date: '2025-01-01', effective_date_source: 'frontmatter' },
+ b: { slug: 'people/alice', chunk_id: null, take_id: 41, take_row_num: 4, source_tier: 'curated', holder: 'garry', text: "newer take: it's the CEO's call", effective_date: '2026-02-02', effective_date_source: 'frontmatter' },
+ combined_score: 1,
+ };
+ const cmd = renderResolutionCommand(pair, 'temporal_supersede');
+ // Older side (row 1) superseded; the newer take's claim is the winner —
+ // single-quoted with embedded apostrophes spliced ('\'').
+ expect(cmd).toContain(`gbrain takes supersede 'people/alice' --row 1 --claim `);
+ expect(cmd).toContain('--since 2026-02-02');
+ expect(cmd).toContain(`newer take: it'\\''s the CEO'\\''s call`);
+ });
+
+ test('gbrain#4169 — temporal_supersede with a chunk winner keeps the claim placeholder (no fabricated take)', () => {
+ const pair: ContradictionPair = {
+ kind: 'intra_page_chunk_take',
+ a: { slug: 'people/alice', chunk_id: null, take_id: 40, take_row_num: 1, source_tier: 'curated', holder: 'garry', text: 'old take', effective_date: '2025-01-01', effective_date_source: 'frontmatter' },
+ b: { slug: 'people/alice', chunk_id: 9, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'arbitrary chunk prose', effective_date: '2026-02-02', effective_date_source: 'frontmatter' },
+ combined_score: 1,
+ };
+ const cmd = renderResolutionCommand(pair, 'temporal_supersede');
+ expect(cmd).toContain('--row 1');
+ expect(cmd).toContain('<replacement claim');
+ expect(cmd).not.toContain('arbitrary chunk prose');
});
test('manual_review emits a no-op comment naming both slugs', () => {
@@ -101,18 +137,18 @@ describe('renderResolutionCommand', () => {
});
describe('proposeResolution (classify + render combined)', () => {
- test('intra_page → takes_supersede with paste-ready command', () => {
- const pair = mkIntraPagePair('people/alice', 42);
+ test('intra_page → takes_supersede addressed by row_num with an explicit claim placeholder (gbrain#4169)', () => {
+ const pair = mkIntraPagePair('people/alice', 42, 5);
const p = proposeResolution(pair, null);
expect(p.resolution_kind).toBe('takes_supersede');
- expect(p.resolution_command).toBe('gbrain takes supersede people/alice --row 42');
+ expect(p.resolution_command).toBe(`gbrain takes supersede 'people/alice' --row 5 --claim '<replacement claim — see contradiction report>'`);
});
test('cross_slug curated → dream_synthesize on curated slug', () => {
const pair = mkCrossSlugPair('openclaw/chat/foo', 'companies/acme');
const p = proposeResolution(pair, null);
expect(p.resolution_kind).toBe('dream_synthesize');
- expect(p.resolution_command).toBe('gbrain dream --phase synthesize --slug companies/acme');
+ expect(p.resolution_command).toBe(`gbrain dream --phase synthesize --slug 'companies/acme'`);
});
});
diff --git a/test/eval-contradictions-calibration-join.test.ts b/test/eval-contradictions-calibration-join.test.ts
index 34c591a0f4..ed18518777 100644
--- a/test/eval-contradictions-calibration-join.test.ts
+++ b/test/eval-contradictions-calibration-join.test.ts
@@ -26,7 +26,7 @@ function buildMember(slug: string, holder: string | null = 'garry'): PairMember
return {
slug,
chunk_id: 1,
- take_id: null,
+ take_id: null, take_row_num: null,
source_tier: 'curated',
holder,
text: 'some text',
diff --git a/test/eval-contradictions-cross-source.test.ts b/test/eval-contradictions-cross-source.test.ts
index 85980b01b8..f26d7d2a11 100644
--- a/test/eval-contradictions-cross-source.test.ts
+++ b/test/eval-contradictions-cross-source.test.ts
@@ -12,8 +12,8 @@ import type { ContradictionPair } from '../src/core/eval-contradictions/types.ts
function mkPair(slugA: string, slugB: string): ContradictionPair {
return {
kind: 'cross_slug_chunks',
- a: { slug: slugA, chunk_id: 1, take_id: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
- b: { slug: slugB, chunk_id: 2, take_id: null, source_tier: 'curated', holder: null, text: 'b', effective_date: null, effective_date_source: null },
+ a: { slug: slugA, chunk_id: 1, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'a', effective_date: null, effective_date_source: null },
+ b: { slug: slugB, chunk_id: 2, take_id: null, take_row_num: null, source_tier: 'curated', holder: null, text: 'b', effective_date: null, effective_date_source: null },
combined_score: 1,
};
}
diff --git a/test/eval-contradictions-integrations.test.ts b/test/eval-contradictions-integrations.test.ts
index c00b4cc72d..6601ba3408 100644
--- a/test/eval-contradictions-integrations.test.ts
+++ b/test/eval-contradictions-integrations.test.ts
@@ -85,8 +85,8 @@ function mkReport(opts: Partial<ProbeReport> & {
pairs_judged: findings.length,
contradictions: findings.map((f, i) => ({
kind: 'cross_slug_chunks' as const,
- a: { slug: f.slugA, chunk_id: i + 1, take_id: null, source_tier: 'curated' as const, holder: null, text: 'a', effective_date: null, effective_date_source: null },
- b: { slug: f.slugB, chunk_id: i + 100, take_id: null, source_tier: 'bulk' as const, holder: null, text: 'b', effective_date: null, effective_date_source: null },
+ a: { slug: f.slugA, chunk_id: i + 1, take_id: null, take_row_num: null, source_tier: 'curated' as const, holder: null, text: 'a', effective_date: null, effective_date_source: null },
+ b: { slug: f.slugB, chunk_id: i + 100, take_id: null, take_row_num: null, source_tier: 'bulk' as const, holder: null, text: 'b', effective_date: null, effective_date_source: null },
combined_score: 1.0,
verdict: 'contradiction' as const,
severity: f.severity,
diff --git a/test/eval-contradictions-severity.test.ts b/test/eval-contradictions-severity.test.ts
index d6c37d4950..653cf8c438 100644
--- a/test/eval-contradictions-severity.test.ts
+++ b/test/eval-contradictions-severity.test.ts
@@ -21,7 +21,7 @@ function mkFinding(opts: {
a: {
slug: opts.slugA,
chunk_id: 1,
- take_id: null,
+ take_id: null, take_row_num: null,
source_tier: 'curated',
holder: null,
text: 'A',
@@ -31,7 +31,7 @@ function mkFinding(opts: {
b: {
slug: opts.slugB,
chunk_id: 2,
- take_id: null,
+ take_id: null, take_row_num: null,
source_tier: 'bulk',
holder: null,
text: 'B',
diff --git a/test/extract-atoms-failure-classes.test.ts b/test/extract-atoms-failure-classes.test.ts
new file mode 100644
index 0000000000..87bbf49e94
--- /dev/null
+++ b/test/extract-atoms-failure-classes.test.ts
@@ -0,0 +1,218 @@
+/**
+ * gbrain#4148 — extract_atoms failure classes, bounded tombstone, and the
+ * partial-persist completion receipt.
+ *
+ * Pre-fix defects these pin (each red on master at the assertion):
+ * 1. Malformed model output and legit zero-yield both parsed to `[]`, so
+ * malformed output was TOMBSTONED AS SUCCESS — the page never retried
+ * and its atoms were silently lost.
+ * 2. No durable failure count existed — a deterministically-failing page
+ * re-entered discovery forever (the --drain backlog floor never cleared).
+ * 3. Atom writes were per-atom while discovery treated ANY atom row with a
+ * matching source_hash as item-complete — a partial persist (atom 1
+ * written, atom 2 failed) skipped the item on every later run.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import {
+ runPhaseExtractAtoms,
+ discoverExtractablePages,
+ parseAtomsOutcome,
+ MAX_DETERMINISTIC_FAILURES,
+} from '../src/core/cycle/extract-atoms.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+function okChatResult(text: string): ChatResult {
+ return {
+ text,
+ blocks: [{ type: 'text', text }],
+ stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5',
+ providerId: 'anthropic',
+ } as ChatResult;
+}
+
+const HASH_A = 'a'.repeat(16);
+const ATOM_JSON = JSON.stringify([
+ { title: 'A durable insight', atom_type: 'insight', body: 'The insight body prose.' },
+]);
+
+async function seedPage(slug: string): Promise<void> {
+ await engine.putPage(slug, {
+ title: slug,
+ type: 'note',
+ compiled_truth: 'seed body prose',
+ } as never, { sourceId: 'default' });
+}
+
+async function frontmatterOf(slug: string): Promise<Record<string, unknown>> {
+ const rows = await engine.executeRaw<{ frontmatter: Record<string, unknown> | string | null }>(
+ `SELECT frontmatter FROM pages WHERE source_id = 'default' AND slug = $1`,
+ [slug],
+ );
+ const fm = rows[0]?.frontmatter;
+ if (fm == null) return {};
+ return typeof fm === 'string' ? JSON.parse(fm) : fm;
+}
+
+describe('parseAtomsOutcome — typed parse (gbrain#4148)', () => {
+ test('malformed shapes are ok:false, never an empty success', () => {
+ expect(parseAtomsOutcome('sorry, I cannot help with that')).toEqual({ ok: false, reason: 'no JSON array in response' });
+ expect(parseAtomsOutcome('[ {"title": "broken"')).toEqual({ ok: false, reason: 'unterminated JSON array' });
+ expect(parseAtomsOutcome('[ %%% ] trailing')).toMatchObject({ ok: false });
+ });
+
+ test('legit zero-yield and valid extractions stay ok:true', () => {
+ expect(parseAtomsOutcome('[]')).toEqual({ ok: true, atoms: [] });
+ const out = parseAtomsOutcome(ATOM_JSON);
+ expect(out.ok).toBe(true);
+ if (out.ok) expect(out.atoms).toHaveLength(1);
+ });
+});
+
+describe('runPhaseExtractAtoms — failure classes (gbrain#4148)', () => {
+ test('malformed output is a counted failure, NOT a zero-yield tombstone', async () => {
+ await seedPage('note/m1');
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'note/m1', content: 'prose', contentHash: HASH_A }],
+ _chat: async (_o: ChatOpts) => okChatResult('no json in sight'),
+ });
+ expect(result.details.malformed_outputs).toBe(1);
+ expect((result.details.failures as Array<{ error: string }>)[0].error).toContain('malformed model output');
+ expect(result.details.pages_processed).toBe(0);
+ const fm = await frontmatterOf('note/m1');
+ expect(fm.atoms_scan_hash).toBeUndefined(); // the pre-fix bug: this was stamped
+ expect(Number(fm.atoms_fail_count)).toBe(1);
+ expect(fm.atoms_fail_hash).toBe(HASH_A);
+ });
+
+ test(`tombstones only after ${MAX_DETERMINISTIC_FAILURES} consecutive same-content malformed failures`, async () => {
+ await seedPage('note/m2');
+ const opts = {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'note/m2', content: 'prose', contentHash: HASH_A }],
+ _chat: async (_o: ChatOpts) => okChatResult('still not json'),
+ };
+ for (let i = 1; i < MAX_DETERMINISTIC_FAILURES; i++) {
+ const r = await runPhaseExtractAtoms(engine, opts);
+ expect(r.details.tombstoned_for_failures).toEqual([]);
+ const fm = await frontmatterOf('note/m2');
+ expect(Number(fm.atoms_fail_count)).toBe(i);
+ expect(fm.atoms_scan_hash).toBeUndefined();
+ }
+ const final = await runPhaseExtractAtoms(engine, opts);
+ expect(final.details.tombstoned_for_failures).toEqual(['note/m2']);
+ const fm = await frontmatterOf('note/m2');
+ expect(Number(fm.atoms_fail_count)).toBe(MAX_DETERMINISTIC_FAILURES);
+ expect(fm.atoms_scan_hash).toBe(HASH_A); // backlog floor clears
+ });
+
+ test('a content edit resets the failure streak (count is hash-keyed)', async () => {
+ await seedPage('note/m3');
+ const mk = (hash: string) => ({
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'note/m3', content: 'prose', contentHash: hash }],
+ _chat: async (_o: ChatOpts) => okChatResult('nope'),
+ });
+ await runPhaseExtractAtoms(engine, mk(HASH_A));
+ await runPhaseExtractAtoms(engine, mk(HASH_A));
+ expect(Number((await frontmatterOf('note/m3')).atoms_fail_count)).toBe(2);
+ await runPhaseExtractAtoms(engine, mk('b'.repeat(16))); // edited content
+ const fm = await frontmatterOf('note/m3');
+ expect(Number(fm.atoms_fail_count)).toBe(1);
+ expect(fm.atoms_fail_hash).toBe('b'.repeat(16));
+ });
+
+ test('transient provider errors are retryable: no count, no tombstone', async () => {
+ await seedPage('note/t1');
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'note/t1', content: 'prose', contentHash: HASH_A }],
+ _chat: async (_o: ChatOpts) => { throw new Error('fetch failed: 503 upstream timeout'); },
+ });
+ const failures = result.details.failures as Array<{ error: string }>;
+ expect(failures[0].error).toContain('[transient — retried next run]');
+ const fm = await frontmatterOf('note/t1');
+ expect(fm.atoms_fail_count).toBeUndefined();
+ expect(fm.atoms_scan_hash).toBeUndefined();
+ });
+});
+
+describe('runPhaseExtractAtoms — completion receipt (gbrain#4148)', () => {
+ test('full success flips atoms to the real source_hash and stamps the page', async () => {
+ await seedPage('note/ok1');
+ const result = await runPhaseExtractAtoms(engine, {
+ sourceId: 'default',
+ _transcripts: [],
+ _pages: [{ slug: 'note/ok1', content: 'prose', contentHash: HASH_A }],
+ _chat: async (_o: ChatOpts) => okChatResult(ATOM_JSON),
+ });
+ expect(result.details.atoms_extracted).toBe(1);
+ const atoms = await engine.executeRaw<{ slug: string; frontmatter: Record<string, unknown> | string }>(
+ `SELECT slug, frontmatter FROM pages WHERE type = 'atom' AND source_id = 'default'`,
+ );
+ expect(atoms).toHaveLength(1);
+ const afm = typeof atoms[0].frontmatter === 'string' ? JSON.parse(atoms[0].frontmatter) : atoms[0].frontmatter;
+ expect(afm.source_hash).toBe(HASH_A); // flipped, not pending:
+ expect(String(afm.source_hash)).not.toContain('pending');
+ expect((await frontmatterOf('note/ok1')).atoms_scan_hash).toBe(HASH_A);
+ });
+
+ test('a pending (partial-persist) atom row does NOT mark the source page done for discovery', async () => {
+ // Seed a discovery-eligible source page: extractable type + >=500 chars.
+ const longBody = 'meeting prose. '.repeat(60);
+ await engine.putPage('meetings/2026-04-03', {
+ title: 'meetings/2026-04-03',
+ type: 'meeting',
+ compiled_truth: longBody,
+ } as never, { sourceId: 'default' });
+ const pageRow = await engine.executeRaw<{ content_hash: string }>(
+ `SELECT content_hash FROM pages WHERE slug = 'meetings/2026-04-03' AND source_id = 'default'`,
+ );
+ const hash16 = pageRow[0].content_hash.slice(0, 16);
+
+ // An atom left behind by a crashed partial run: provisional hash.
+ await engine.putPage('atoms/2026-04-03/partial-atom-abc123', {
+ title: 'partial atom',
+ type: 'atom',
+ compiled_truth: 'atom body',
+ frontmatter: { source_hash: `pending:${hash16}` },
+ } as never, { sourceId: 'default' });
+
+ const pending = await discoverExtractablePages(engine, 'default');
+ expect(pending.map(p => p.slug)).toContain('meetings/2026-04-03'); // still pending → retried
+
+ // After the flip (completed run) the same page is done.
+ await engine.executeRaw(
+ `UPDATE pages SET frontmatter = frontmatter || jsonb_build_object('source_hash', $1::text)
+ WHERE slug = 'atoms/2026-04-03/partial-atom-abc123' AND source_id = 'default'`,
+ [hash16],
+ );
+ const done = await discoverExtractablePages(engine, 'default');
+ expect(done.map(p => p.slug)).not.toContain('meetings/2026-04-03');
+ });
+});
diff --git a/test/health-islanded-liveness.test.ts b/test/health-islanded-liveness.test.ts
new file mode 100644
index 0000000000..967d2a31e2
--- /dev/null
+++ b/test/health-islanded-liveness.test.ts
@@ -0,0 +1,120 @@
+/**
+ * gbrain#4153 + gbrain#4147 — getHealth accounting fixes.
+ *
+ * #4153: the islanded (orphan_pages) predicate must apply endpoint liveness
+ * in BOTH directions — an inbound link from a soft-deleted page (the
+ * invariant findOrphanPages documents) and an outbound link to a
+ * soft-deleted target must NOT rescue a page from islanded status. Pre-fix,
+ * get_health.orphan_pages disagreed with `gbrain orphans` whenever a
+ * soft-deleted page still touched a live one.
+ *
+ * #4147: entity-scoped link_coverage / timeline_coverage report null below
+ * MIN_ENTITY_PAGES_FOR_COVERAGE (0/0 used to read as a hard 0%), with
+ * entity_page_count surfaced so consumers can tell 0% from vacuous.
+ *
+ * Red on master at the assertions: orphan_pages was 0 in both #4153 cases
+ * (the dead link rescued the page), and coverage was 0 (not null) at N=0.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MIN_ENTITY_PAGES_FOR_COVERAGE } 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 () => {
+ for (const t of ['links', 'content_chunks', 'timeline_entries', 'raw_data', 'tags', 'page_versions', 'ingest_log', 'pages']) {
+ await (engine as any).db.exec(`DELETE FROM ${t}`);
+ }
+});
+
+async function pageId(slug: string): Promise<number> {
+ return (await (engine as any).db.query(`SELECT id FROM pages WHERE slug=$1`, [slug])).rows[0].id;
+}
+
+async function link(fromSlug: string, toSlug: string): Promise<void> {
+ await (engine as any).db.query(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
+ [await pageId(fromSlug), await pageId(toSlug)],
+ );
+}
+
+async function softDelete(slug: string): Promise<void> {
+ await (engine as any).db.query(`UPDATE pages SET deleted_at = now() WHERE slug = $1`, [slug]);
+}
+
+describe('gbrain#4153 — islanded endpoint liveness (both directions)', () => {
+ test('an inbound link from a soft-deleted page does NOT rescue a page from islanded', async () => {
+ await engine.putPage('live-target', { type: 'note', title: 'T', compiled_truth: 'body', frontmatter: {} });
+ await engine.putPage('dead-source', { type: 'note', title: 'S', compiled_truth: 'body', frontmatter: {} });
+ await link('dead-source', 'live-target');
+ await softDelete('dead-source');
+ const h = await engine.getHealth();
+ // live-target's only inbound link comes from a soft-deleted page — the
+ // same situation `gbrain orphans` already reports as an orphan.
+ expect(h.orphan_pages).toBe(1);
+ });
+
+ test('an outbound link to a soft-deleted target does NOT rescue a page from islanded', async () => {
+ await engine.putPage('live-source', { type: 'note', title: 'S', compiled_truth: 'body', frontmatter: {} });
+ await engine.putPage('dead-target', { type: 'note', title: 'T', compiled_truth: 'body', frontmatter: {} });
+ await link('live-source', 'dead-target');
+ await softDelete('dead-target');
+ const h = await engine.getHealth();
+ expect(h.orphan_pages).toBe(1);
+ });
+
+ test('live endpoints still rescue: linked live pages are not islanded', async () => {
+ await engine.putPage('a', { type: 'note', title: 'A', compiled_truth: 'body', frontmatter: {} });
+ await engine.putPage('b', { type: 'note', title: 'B', compiled_truth: 'body', frontmatter: {} });
+ await link('a', 'b');
+ const h = await engine.getHealth();
+ expect(h.orphan_pages).toBe(0);
+ });
+});
+
+describe('gbrain#4147 — entity coverage small-N guard', () => {
+ async function seedEntities(n: number, linked: boolean): Promise<void> {
+ for (let i = 0; i < n; i++) {
+ await engine.putPage(`people/p${i}`, { type: 'person', title: `P${i}`, compiled_truth: 'bio', frontmatter: {} });
+ }
+ if (linked && n > 0) {
+ await engine.putPage('hub', { type: 'note', title: 'Hub', compiled_truth: 'idx', frontmatter: {} });
+ for (let i = 0; i < n; i++) await link('hub', `people/p${i}`);
+ }
+ }
+
+ test('0 entity pages → coverage is null (not a hard 0%), entity_page_count 0', async () => {
+ await engine.putPage('note/x', { type: 'note', title: 'X', compiled_truth: 'body', frontmatter: {} });
+ const h = await engine.getHealth();
+ expect(h.entity_page_count).toBe(0);
+ expect(h.link_coverage).toBeNull();
+ expect(h.timeline_coverage).toBeNull();
+ });
+
+ test('threshold-1 entity pages → still null (single-page 100% is noise too)', async () => {
+ await seedEntities(MIN_ENTITY_PAGES_FOR_COVERAGE - 1, true);
+ const h = await engine.getHealth();
+ expect(h.entity_page_count).toBe(MIN_ENTITY_PAGES_FOR_COVERAGE - 1);
+ expect(h.link_coverage).toBeNull();
+ expect(h.timeline_coverage).toBeNull();
+ });
+
+ test('at the threshold → the real ratio is reported', async () => {
+ await seedEntities(MIN_ENTITY_PAGES_FOR_COVERAGE, true);
+ const h = await engine.getHealth();
+ expect(h.entity_page_count).toBe(MIN_ENTITY_PAGES_FOR_COVERAGE);
+ expect(h.link_coverage).toBe(1);
+ expect(h.timeline_coverage).toBe(0); // no timeline entries seeded
+ });
+});
diff --git a/test/health-soft-delete.test.ts b/test/health-soft-delete.test.ts
index b4991a6c3d..424e2d87f9 100644
--- a/test/health-soft-delete.test.ts
+++ b/test/health-soft-delete.test.ts
@@ -80,30 +80,71 @@ describe('#1305 — getHealth excludes soft-deleted pages', () => {
});
test('entity coverage denominators and most_connected exclude deleted entities', async () => {
- // Live entity: inbound link + timeline entry → full coverage.
- await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: 'a person', frontmatter: {} });
+ // FIVE live entities (>= the gbrain#4147 small-N floor, so the ratios
+ // are real percentages, not the below-floor null), each with an inbound
+ // link + timeline entry → full coverage. Bob is the sixth, soft-deleted.
+ const liveSlugs = ['people/alice-example', 'people/carol-example', 'people/dana-example', 'companies/acme-example', 'companies/widget-co'];
+ for (const slug of liveSlugs) {
+ await engine.putPage(slug, { type: slug.startsWith('companies/') ? 'company' : 'person', title: slug, compiled_truth: 'an entity', frontmatter: {} });
+ }
await engine.putPage('people/bob-example', { type: 'person', title: 'Bob', compiled_truth: 'another person', frontmatter: {} });
- await seedNote('wiki/mentions-alice');
- const aliceId = await pageId('people/alice-example');
- await (engine as any).db.query(
- `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
- [await pageId('wiki/mentions-alice'), aliceId],
- );
- await (engine as any).db.query(
- `INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', 'met alice')`,
- [aliceId],
- );
+ await seedNote('wiki/mentions-all');
+ const hubId = await pageId('wiki/mentions-all');
+ for (const slug of liveSlugs) {
+ const pid = await pageId(slug);
+ await (engine as any).db.query(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
+ [hubId, pid],
+ );
+ await (engine as any).db.query(
+ `INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-01-01', 'seen')`,
+ [pid],
+ );
+ }
await engine.softDeletePage('people/bob-example');
const h = await engine.getHealth();
- // Pre-fix: bob stayed in the entity_pages CTE → coverage 0.5 each,
+ // Pre-fix: bob stayed in the entity_pages CTE → coverage 5/6 each,
// and bob appeared in most_connected.
+ expect(h.entity_page_count).toBe(5);
expect(h.link_coverage).toBe(1);
expect(h.timeline_coverage).toBe(1);
expect(h.most_connected.map((c) => c.slug)).not.toContain('people/bob-example');
});
+ test('link_coverage does not count inbound links whose SOURCE page is soft-deleted (red-team consistency with islanded)', async () => {
+ // Five entities (at the #4147 floor). Four get live inbound links; the
+ // fifth's ONLY inbound link comes from a page that is then soft-deleted.
+ // The islanded predicate (#4153) calls that entity islanded; coverage
+ // must agree it is uncovered — 4/5, not 5/5.
+ const slugs = ['people/alice-example', 'people/carol-example', 'people/dana-example', 'companies/acme-example', 'companies/widget-co'];
+ for (const slug of slugs) {
+ await engine.putPage(slug, { type: slug.startsWith('companies/') ? 'company' : 'person', title: slug, compiled_truth: 'an entity', frontmatter: {} });
+ }
+ await seedNote('wiki/live-hub');
+ await seedNote('wiki/doomed-hub');
+ const liveHub = await pageId('wiki/live-hub');
+ const doomedHub = await pageId('wiki/doomed-hub');
+ for (const slug of slugs.slice(0, 4)) {
+ await (engine as any).db.query(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
+ [liveHub, await pageId(slug)],
+ );
+ }
+ await (engine as any).db.query(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`,
+ [doomedHub, await pageId('companies/widget-co')],
+ );
+
+ await engine.softDeletePage('wiki/doomed-hub');
+ const h = await engine.getHealth();
+
+ expect(h.entity_page_count).toBe(5);
+ // Pre-fix: 1 (the dead inbound link still counted widget-co as covered).
+ expect(h.link_coverage).toBeCloseTo(0.8, 5);
+ });
+
test('chunk storage counts stay raw (the deliberate boundary)', async () => {
await seedNote('wiki/kept');
await seedNote('wiki/gone');
diff --git a/test/link-extraction-code-refs.test.ts b/test/link-extraction-code-refs.test.ts
index dc86b81c9d..47b061eb3a 100644
--- a/test/link-extraction-code-refs.test.ts
+++ b/test/link-extraction-code-refs.test.ts
@@ -43,7 +43,7 @@ describe('extractCodeRefs — basic patterns', () => {
'cpp', 'cc', 'hpp', 'c', 'h',
'php', 'swift', 'kt', 'scala', 'lua',
'ex', 'exs', 'elm', 'ml', 'dart', 'zig', 'sol',
- 'sh', 'bash', 'css', 'html', 'vue',
+ 'sh', 'bash', 'css', 'html', 'astro', 'svelte', 'vue',
'json', 'yaml', 'yml', 'toml',
];
for (const ext of exts) {
diff --git a/test/migrations-v131.test.ts b/test/migrations-v131.test.ts
new file mode 100644
index 0000000000..eb8e650207
--- /dev/null
+++ b/test/migrations-v131.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Migration v131 (drop_job_wide_subagent_tool_use_id_unique) — #4155.
+ *
+ * tool_use_id stores the RAW provider id, and replay-style providers
+ * (claude-cli spawns a fresh subprocess per turn from an id-stripped
+ * transcript) reuse the same short id on every turn. The job-wide
+ * UNIQUE (job_id, tool_use_id) constraint encoded the false assumption that
+ * provider ids are job-unique; a reuse collided and dead-lettered the job.
+ * Row identity is (job_id, message_idx, ordinal).
+ *
+ * Pinned contracts:
+ * 1. v131 exists in MIGRATIONS with the canonical name, idempotent flag, and
+ * one engine-agnostic sql block (no sqlFor split).
+ * 2. Fresh init: the schema no longer declares uniq_subagent_tools_use_id and
+ * two rows sharing (job_id, tool_use_id) can coexist.
+ * 3. Upgrade: on a brain where the constraint still exists (positive control:
+ * the duplicate insert THROWS before the migration), a ledger rewind to
+ * 130 → runMigrations applies v131, the constraint is gone, and the same
+ * duplicate insert succeeds. Re-run applies nothing, and re-executing the
+ * v131 SQL directly is a no-op (DROP CONSTRAINT IF EXISTS).
+ */
+
+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 { MIGRATIONS, LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+let jobId: number;
+
+const V131_SQL = MIGRATIONS.find(m => m.version === 131)?.sql ?? '';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' }); // in-memory
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM subagent_tool_executions');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const j = await queue.add('subagent', { prompt: 'x' }, {}, { allowProtectedSubmit: true });
+ jobId = j.id;
+});
+
+/** Insert an execution row with an explicit (message_idx, ordinal) identity. */
+async function insertExec(msgIdx: number, toolUseId: string, ordinal: number): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions
+ (job_id, message_idx, tool_use_id, tool_name, input, status, ordinal)
+ VALUES ($1, $2, $3, 'search', '{}'::jsonb, 'pending', $4)`,
+ [jobId, msgIdx, toolUseId, ordinal],
+ );
+}
+
+async function constraintExists(): Promise<boolean> {
+ const rows = await engine.executeRaw<{ conname: string }>(
+ `SELECT conname FROM pg_constraint WHERE conname = 'uniq_subagent_tools_use_id'`,
+ );
+ return rows.length > 0;
+}
+
+describe('migration v131 — structure', () => {
+ test('exists with canonical name, idempotent flag, engine-agnostic sql', () => {
+ const v131 = MIGRATIONS.find(m => m.version === 131);
+ expect(v131).toBeDefined();
+ expect(v131?.name).toBe('drop_job_wide_subagent_tool_use_id_unique');
+ expect(v131?.idempotent).toBe(true);
+ expect(v131?.sqlFor).toBeUndefined();
+ expect(V131_SQL).toContain('DROP CONSTRAINT IF EXISTS uniq_subagent_tools_use_id');
+ expect(LATEST_VERSION).toBeGreaterThanOrEqual(131);
+ });
+});
+
+describe('migration v131 — fresh init (PGLite)', () => {
+ test('fresh schema has no job-wide unique; duplicate raw ids across turns coexist', async () => {
+ expect(await constraintExists()).toBe(false);
+ await insertExec(1, 'toolu_01', 0);
+ await insertExec(3, 'toolu_01', 0); // same (job_id, tool_use_id), different turn
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM subagent_tool_executions WHERE job_id = $1 AND tool_use_id = 'toolu_01'`,
+ [jobId],
+ );
+ expect(Number(rows[0].n)).toBe(2);
+ });
+});
+
+describe('migration v131 — upgrade from a pre-v131 brain (PGLite)', () => {
+ test('drops the constraint; duplicate insert throws before (positive control) and succeeds after', async () => {
+ // Simulate a pre-v131 brain: re-add the job-wide constraint.
+ await engine.executeRaw(
+ `ALTER TABLE subagent_tool_executions
+ ADD CONSTRAINT uniq_subagent_tools_use_id UNIQUE (job_id, tool_use_id)`,
+ );
+ expect(await constraintExists()).toBe(true);
+
+ // Positive control: the guard actually fires pre-migration — this is the
+ // exact #4155 dead-letter shape.
+ await insertExec(1, 'toolu_01', 0);
+ await expect(insertExec(3, 'toolu_01', 0)).rejects.toThrow();
+
+ // Apply v131 via the real migration runner (ledger rewind).
+ await engine.setConfig('version', '130');
+ const res = await runMigrations(engine);
+ expect(res.applied).toBeGreaterThanOrEqual(1);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ expect(await constraintExists()).toBe(false);
+
+ // The same duplicate now persists.
+ await insertExec(3, 'toolu_01', 0);
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM subagent_tool_executions WHERE job_id = $1 AND tool_use_id = 'toolu_01'`,
+ [jobId],
+ );
+ expect(Number(rows[0].n)).toBe(2);
+
+ // Ledger idempotency: re-run applies nothing.
+ const rerun = await runMigrations(engine);
+ expect(rerun.applied).toBe(0);
+
+ // SQL-level idempotency: DROP CONSTRAINT IF EXISTS on an absent
+ // constraint is a no-op, not an error.
+ await engine.executeRaw(V131_SQL);
+ expect(await constraintExists()).toBe(false);
+ });
+});
diff --git a/test/models-doctor-chat-probe-timeout.slow.test.ts b/test/models-doctor-chat-probe-timeout.slow.test.ts
new file mode 100644
index 0000000000..bf16db45b5
--- /dev/null
+++ b/test/models-doctor-chat-probe-timeout.slow.test.ts
@@ -0,0 +1,56 @@
+/**
+ * `gbrain models doctor` chat probe timeout — end-to-end wall-clock proof.
+ *
+ * Companion to `models-doctor-chat-probe-timeout.test.ts` (the fast,
+ * zero-wait unit tests for `resolveChatProbeTimeoutMs`). These two tests
+ * each inject a `deps.chat` mock that stalls ~5.5s — comfortably past the
+ * old hardcoded 5000ms probe budget — to prove `probeModel()` actually
+ * wires the resolved timeout through end-to-end, not just that the
+ * resolver function returns the right number in isolation:
+ *
+ * - claude-cli: now succeeds (its recipe declares 30_000ms).
+ * - every other provider: UNCHANGED, still aborts at the historical
+ * 5000ms (pinned by asserting the exact abort message).
+ *
+ * Per `docs/TESTING.md`, real multi-second waits belong in `*.slow.test.ts`
+ * (run via `bun run test:slow`), not the fast unit loop that
+ * `scripts/run-unit-shard.sh` fans out on every inner-loop run.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { probeModel } from '../src/commands/models.ts';
+
+type ChatFn = typeof import('../src/core/ai/gateway.ts').chat;
+
+function stallingChat(ms: number): ChatFn {
+ return (async (opts: { abortSignal?: AbortSignal }) => {
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(resolve, ms);
+ opts.abortSignal?.addEventListener('abort', () => {
+ clearTimeout(timer);
+ reject(opts.abortSignal!.reason ?? new Error('aborted'));
+ });
+ });
+ return {} as Awaited<ReturnType<ChatFn>>;
+ }) as unknown as ChatFn;
+}
+
+describe('probeModel — honors the resolved timeout end-to-end', () => {
+ // Explicit per-test timeout: empirically, a bare `bun test <file>` (no
+ // --timeout flag) enforces bun's built-in 5000ms per-test default even
+ // though bunfig.toml declares `[test].timeout = 60_000` — verified
+ // locally (a standalone 5.5s-wait test times out at 5005ms without this
+ // override). scripts/run-unit-*.sh pass --timeout=60000 explicitly, but
+ // pin it here too so this test doesn't depend on invocation method.
+ test('claude-cli: a >5s chat call (realistic subprocess cold start) succeeds instead of false-failing at the old 5s budget', async () => {
+ const r = await probeModel('claude-cli:claude-sonnet-5', 'chat', { chat: stallingChat(5500) });
+ expect(r.status).toBe('ok');
+ expect(r.message).toBe('reachable');
+ }, 15_000);
+
+ test('non-claude-cli provider: a >5s stall still aborts at the unchanged 5000ms budget', async () => {
+ const r = await probeModel('anthropic:claude-sonnet-4-6', 'chat', { chat: stallingChat(5500) });
+ expect(r.status).not.toBe('ok');
+ expect(r.message).toBe('probe timed out after 5000ms');
+ }, 15_000);
+});
diff --git a/test/models-doctor-chat-probe-timeout.test.ts b/test/models-doctor-chat-probe-timeout.test.ts
new file mode 100644
index 0000000000..87b6f9d0e3
--- /dev/null
+++ b/test/models-doctor-chat-probe-timeout.test.ts
@@ -0,0 +1,48 @@
+/**
+ * `gbrain models doctor` chat/expansion probe timeout — defect fix.
+ *
+ * Pre-fix, `probeModel()` hardcoded a flat 5000ms abort for every provider.
+ * `claude-cli:` dispatches through a `claude --print` subprocess (CLI cold
+ * start + user-level CLAUDE.md load), which routinely takes 5-6s even when
+ * the CLI and subscription are perfectly healthy — so the doctor probe
+ * always aborted and reported `'unknown — claude-cli adapter aborted'`,
+ * not because anything was actually broken. `chat()` itself succeeds fine
+ * at normal call sites; only the probe's flat 5s budget was too tight.
+ *
+ * `resolveChatProbeTimeoutMs()` now reads `touchpoints.<kind>.default_timeout_ms`
+ * off the resolved recipe (mirrors the reranker probe's recipe-default
+ * fallback in `resolveLiveRerankerTimeoutMs` / mode.ts) before falling back
+ * to the historical 5000ms. These fast, zero-wait tests pin the resolution
+ * logic: (1) claude-cli's declared 30s override, (2) every other provider
+ * keeps the unchanged 5000ms default, (3) an unresolvable model string
+ * still degrades to 5000ms rather than throwing. The end-to-end wall-clock
+ * proof that `probeModel` actually honors the resolved timeout lives in
+ * `models-doctor-chat-probe-timeout.slow.test.ts` (per `docs/TESTING.md`,
+ * tests with real multi-second waits belong in `*.slow.test.ts`, not the
+ * fast unit loop).
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { resolveChatProbeTimeoutMs } from '../src/commands/models.ts';
+
+describe('resolveChatProbeTimeoutMs', () => {
+ test('claude-cli chat touchpoint resolves to its declared 30s override', async () => {
+ const ms = await resolveChatProbeTimeoutMs('claude-cli:claude-sonnet-5', 'chat');
+ expect(ms).toBe(30_000);
+ });
+
+ test('a provider without a declared default_timeout_ms keeps the historical 5000ms', async () => {
+ const ms = await resolveChatProbeTimeoutMs('anthropic:claude-sonnet-4-6', 'chat');
+ expect(ms).toBe(5000);
+ });
+
+ test('expansion touchpoint on a provider with no override keeps 5000ms', async () => {
+ const ms = await resolveChatProbeTimeoutMs('openai:gpt-5-mini', 'expansion');
+ expect(ms).toBe(5000);
+ });
+
+ test('an unresolvable model string degrades to 5000ms instead of throwing', async () => {
+ const ms = await resolveChatProbeTimeoutMs('not-a-real-provider:nope', 'chat');
+ expect(ms).toBe(5000);
+ });
+});
diff --git a/test/no-grant-federated-scope.test.ts b/test/no-grant-federated-scope.test.ts
new file mode 100644
index 0000000000..90b80b35a4
--- /dev/null
+++ b/test/no-grant-federated-scope.test.ts
@@ -0,0 +1,75 @@
+/**
+ * #3242 parity for the SDK HTTP transport (`serve --http`).
+ *
+ * The legacy HTTP transport and the stdio dispatch site both widen an
+ * UNQUALIFIED read to the federated source set when the caller carries no
+ * operator source grant. The SDK transport in `src/commands/serve-http.ts`
+ * never did, so one legacy bearer token saw federated pages over `/mcp` on one
+ * serve mode and scalar 'default' on the other — a brain whose code lives in a
+ * non-default source answered `code_def` on one and came back empty on the
+ * other.
+ *
+ * `noGrantFederatedScope` is the decision that transport now shares. These
+ * tests pin the part that is easy to get wrong: WHICH callers may widen. The
+ * gate is `hasSourceGrant === false`, not a falsy check, because `undefined`
+ * means an OAuth client and must NOT widen — a falsy gate would quietly hand
+ * every OAuth client the whole federated set.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ // Seeded 'default' is federated. 'wiki' joins it; 'private' opted out and
+ // must never appear in a widened scope.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ('wiki', 'wiki', '/tmp/wiki', '{"federated": true}'::jsonb)`,
+ );
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ('private', 'private', '/tmp/private', '{}'::jsonb)`,
+ );
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+describe('noGrantFederatedScope — which callers may widen', () => {
+ test('no-grant legacy bearer token widens to the federated set', async () => {
+ expect(await noGrantFederatedScope(engine, false, 'default')).toEqual(['default', 'wiki']);
+ });
+
+ test('operator-granted token keeps its scalar scope', async () => {
+ expect(await noGrantFederatedScope(engine, true, 'default')).toBeUndefined();
+ });
+
+ test('OAuth client (flag undefined) keeps its scalar scope', async () => {
+ // The regression a falsy gate would introduce: undefined is not "no grant".
+ expect(await noGrantFederatedScope(engine, undefined, 'default')).toBeUndefined();
+ });
+
+ test('no resolved source id: nothing to widen from', async () => {
+ expect(await noGrantFederatedScope(engine, false, undefined)).toBeUndefined();
+ expect(await noGrantFederatedScope(engine, false, '')).toBeUndefined();
+ });
+
+ test('a non-default anchor widens from itself, excluding the unfederated source', async () => {
+ const scope = await noGrantFederatedScope(engine, false, 'wiki');
+ expect(scope).toEqual(['wiki', 'default']);
+ expect(scope).not.toContain('private');
+ });
+
+ test('an unreadable sources table leaves the scalar scope standing', async () => {
+ const broken = {
+ executeRaw: async () => {
+ throw new Error('sources table unavailable');
+ },
+ } as any;
+ expect(await noGrantFederatedScope(broken, false, 'default')).toBeUndefined();
+ });
+});
diff --git a/test/path-confine.test.ts b/test/path-confine.test.ts
index 960d2f8618..762d7b8b92 100644
--- a/test/path-confine.test.ts
+++ b/test/path-confine.test.ts
@@ -19,6 +19,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import {
isTrustedDotfile, isPathContained, realpathOrResolve, isWriteTargetContained,
+ resolvedPrefixContained,
} from '../src/core/path-confine.ts';
import { validateSlug } from '../src/core/utils.ts';
import { resolveSourceId } from '../src/core/source-resolver.ts';
@@ -122,6 +123,22 @@ describe('isPathContained', () => {
mkdirSync(sub);
expect(isPathContained(sub, dir)).toBe(true);
});
+ test('containment uses the OS separator, not a hardcoded "/"', () => {
+ // The boundary check appended '/' unconditionally. realpathSync returns
+ // backslash paths on Windows, so no real child ever matched the
+ // 'C:\\...\\parent/' prefix and every containment check returned false —
+ // which made the skills-dir auto-detector miss a skills/ directory that
+ // was present. Exercised through the public API with OS-native paths.
+ const dir = scratch();
+ const nested = join(dir, 'a', 'b');
+ mkdirSync(nested, { recursive: true });
+ expect(isPathContained(nested, dir)).toBe(true);
+ expect(isPathContained(nested, join(dir, 'a'))).toBe(true);
+ // The separator must remain a real boundary, not a bare string prefix.
+ const sibling = join(dir, 'a-sibling');
+ mkdirSync(sibling);
+ expect(isPathContained(sibling, join(dir, 'a'))).toBe(false);
+ });
test('symlink escaping the parent is NOT contained', () => {
const dir = scratch();
const outside = scratch('pc-outside-');
@@ -317,3 +334,35 @@ describe('autoDetectSkillsDir — skills/ symlink confinement', () => {
expect(found.dir).toBe(join(ws, 'skills'));
});
});
+
+// gbrain#4103 — win32 shapes for the pure prefix core, runnable on POSIX CI
+// (no Windows runner exists; realpathSync can never produce backslash paths
+// here, so the extracted resolvedPrefixContained is the testable seam).
+describe('resolvedPrefixContained — win32 shapes (gbrain#4103)', () => {
+ const BS = '\\';
+
+ test('backslash subtree is contained (the exact pre-fix regression)', () => {
+ // Pre-fix, a hardcoded "/" suffix made this false for EVERY real
+ // Windows subdirectory.
+ expect(resolvedPrefixContained('C:\\brain\\pages\\note.md', 'C:\\brain', BS)).toBe(true);
+ expect(resolvedPrefixContained('C:\\brain', 'C:\\brain', BS)).toBe(true);
+ });
+
+ test('sibling-prefix directories do not leak (C:\\brain vs C:\\brainstorm)', () => {
+ expect(resolvedPrefixContained('C:\\brainstorm\\x.md', 'C:\\brain', BS)).toBe(false);
+ });
+
+ test('drive-letter boundaries hold', () => {
+ expect(resolvedPrefixContained('D:\\brain\\x.md', 'C:\\brain', BS)).toBe(false);
+ });
+
+ test('UNC shares: contained subtree true, sibling share false', () => {
+ expect(resolvedPrefixContained('\\\\server\\share\\brain\\a.md', '\\\\server\\share\\brain', BS)).toBe(true);
+ expect(resolvedPrefixContained('\\\\server\\share2\\brain\\a.md', '\\\\server\\share\\brain', BS)).toBe(false);
+ });
+
+ test('POSIX shapes still hold through the same core', () => {
+ expect(resolvedPrefixContained('/brain/pages/a.md', '/brain', '/')).toBe(true);
+ expect(resolvedPrefixContained('/brainstorm/a.md', '/brain', '/')).toBe(false);
+ });
+});
diff --git a/test/pglite-engine.test.ts b/test/pglite-engine.test.ts
index e41b3c4f8d..120e658d86 100644
--- a/test/pglite-engine.test.ts
+++ b/test/pglite-engine.test.ts
@@ -1431,29 +1431,42 @@ describe('PGLiteEngine: traverseGraph cycle prevention', () => {
describe('PGLiteEngine: getHealth graph metrics', () => {
beforeEach(async () => {
await truncateAll();
+ // Five entity pages — at MIN_ENTITY_PAGES_FOR_COVERAGE (gbrain#4147), so
+ // the ratio tests below exercise real percentages, not the small-N null.
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
+ await engine.putPage('people/carol', { ...testPage, type: 'person', title: 'Carol' });
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
await engine.putPage('entities/project-x', { ...testPage, type: 'entity', title: 'Project X' });
});
- test('link_coverage = 0 when no links exist', async () => {
+ test('link_coverage = 0 when no links exist (at/above the small-N floor)', async () => {
const h = await engine.getHealth();
+ expect(h.entity_page_count).toBe(5);
expect(h.link_coverage).toBe(0);
});
test('link_coverage = % of entity pages with >= 1 inbound link', async () => {
- // Acme gets 1 inbound link (from Alice); Alice/Bob/Project X get 0 inbound.
- // 1 of 4 entity pages has inbound links -> 25%.
+ // Acme gets 1 inbound link (from Alice); the other 4 get 0 inbound.
+ // 1 of 5 entity pages has inbound links -> 20%.
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
const h = await engine.getHealth();
- expect(h.link_coverage).toBeCloseTo(1 / 4, 2);
+ expect(h.link_coverage).toBeCloseTo(1 / 5, 2);
});
test('timeline_coverage = % with >= 1 timeline entry', async () => {
await engine.addTimelineEntry('people/alice', { date: '2026-01-15', summary: 'Joined' });
const h = await engine.getHealth();
- expect(h.timeline_coverage).toBeCloseTo(1 / 4, 2);
+ expect(h.timeline_coverage).toBeCloseTo(1 / 5, 2);
+ });
+
+ test('below the small-N floor the ratios are null, never a hard 0% (gbrain#4147)', async () => {
+ await truncateAll();
+ await engine.putPage('people/solo', { ...testPage, type: 'person', title: 'Solo' });
+ const h = await engine.getHealth();
+ expect(h.entity_page_count).toBe(1);
+ expect(h.link_coverage).toBeNull();
+ expect(h.timeline_coverage).toBeNull();
});
test('most_connected lists top entities by link count', async () => {
@@ -1466,16 +1479,17 @@ describe('PGLiteEngine: getHealth graph metrics', () => {
});
test('orphan_pages: pages with neither inbound nor outbound links', async () => {
- // All 4 pages start with no links, but entities/project-x is excluded
+ // All 5 pages start with no links, but entities/project-x is excluded
// from orphan reporting by the shared orphan policy ('entities' is a
- // first-segment exclusion in orphan-policy.ts). Expect 3 orphans.
+ // first-segment exclusion in orphan-policy.ts). Expect 4 orphans.
const h = await engine.getHealth();
- expect(h.orphan_pages).toBe(3);
+ expect(h.orphan_pages).toBe(4);
- // Add alice -> acme. Alice has outbound, acme has inbound, only Bob is orphan.
+ // Add alice -> acme. Alice has outbound, acme has inbound; Bob and Carol
+ // stay orphaned.
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
const h2 = await engine.getHealth();
- expect(h2.orphan_pages).toBe(1);
+ expect(h2.orphan_pages).toBe(2);
});
});
diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.ts
index 0d565d0115..7f66abab11 100644
--- a/test/propose-takes.test.ts
+++ b/test/propose-takes.test.ts
@@ -508,7 +508,9 @@ New prose appended here.`;
const extractor: ProposeTakesExtractor = async () => [];
const result = await runPhaseProposeTakes(buildCtx(engine), { extractor });
const details = result.details as Record<string, unknown>;
- expect(details.deadline_hit).toBeUndefined();
+ // gbrain#4168: deadline_hit is now explicitly initialized false (was
+ // undefined-when-unhit); the behavior pinned here is unchanged.
+ expect(details.deadline_hit).toBe(false);
expect(details.pages_scanned).toBe(1);
});
diff --git a/test/regressions/v0.36.1.0-iron-rule.test.ts b/test/regressions/v0.36.1.0-iron-rule.test.ts
index 30b541d6fc..b056629cff 100644
--- a/test/regressions/v0.36.1.0-iron-rule.test.ts
+++ b/test/regressions/v0.36.1.0-iron-rule.test.ts
@@ -57,7 +57,7 @@ describe('R2: contradictions probe UNCHANGED when no calibration profile', () =>
a: {
slug: 'wiki/companies/x',
chunk_id: 1,
- take_id: null,
+ take_id: null, take_row_num: null,
source_tier: 'curated' as const,
holder: 'garry',
text: 't',
@@ -67,7 +67,7 @@ describe('R2: contradictions probe UNCHANGED when no calibration profile', () =>
b: {
slug: 'wiki/companies/y',
chunk_id: 1,
- take_id: null,
+ take_id: null, take_row_num: null,
source_tier: 'curated' as const,
holder: 'garry',
text: 't',
diff --git a/test/remediation-run-loop.serial.test.ts b/test/remediation-run-loop.serial.test.ts
index 1b444d9b4d..7837ac17fc 100644
--- a/test/remediation-run-loop.serial.test.ts
+++ b/test/remediation-run-loop.serial.test.ts
@@ -47,6 +47,7 @@ function makeHealth(): BrainHealth {
brain_score: 80,
dead_links: 1,
link_coverage: 1,
+ entity_page_count: 10,
timeline_coverage: 1,
most_connected: [],
embed_coverage_score: 35,
diff --git a/test/subagent-tool-ledger.test.ts b/test/subagent-tool-ledger.test.ts
new file mode 100644
index 0000000000..9d6efb02b3
--- /dev/null
+++ b/test/subagent-tool-ledger.test.ts
@@ -0,0 +1,192 @@
+/**
+ * Two-phase tool ledger helpers (persistToolExecPending/Complete/Failed) —
+ * #4155 raw-id semantics.
+ *
+ * After migration v131 dropped the job-wide UNIQUE (job_id, tool_use_id),
+ * tool_use_id stores the RAW provider id and may repeat both across turns and
+ * (defensively) within one turn. Pinned contracts:
+ *
+ * 1. Same-turn duplicate raw ids: each call keeps its own row (distinct
+ * ordinals), and complete/failed settlement lands on the call's OWN row —
+ * never a settled same-id sibling.
+ * 2. Zombie-race downgrade guard: persistToolExecFailed's stable-id conflict
+ * update never downgrades an already-complete row, and never touches a
+ * conflicting row that belongs to a DIFFERENT tool_use_id.
+ * 3. Legacy compatibility: a pre-existing ordinal=NULL row for the same
+ * (job_id, message_idx, tool_use_id) suppresses a re-insert (the old
+ * ON CONFLICT DO NOTHING semantics), and settlement still finds it.
+ */
+
+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 { __testing } from '../src/core/minions/handlers/subagent.ts';
+
+const { persistToolExecPending, persistToolExecComplete, persistToolExecFailed } = __testing;
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+let jobId: number;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM subagent_tool_executions');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const j = await queue.add('subagent', { prompt: 'x' }, {}, { allowProtectedSubmit: true });
+ jobId = j.id;
+});
+
+async function rows(): Promise<Array<Record<string, unknown>>> {
+ return engine.executeRaw<Record<string, unknown>>(
+ `SELECT message_idx, ordinal, tool_use_id, tool_name, status, output, error
+ FROM subagent_tool_executions
+ WHERE job_id = $1
+ ORDER BY message_idx, COALESCE(ordinal, 0), id`,
+ [jobId],
+ );
+}
+
+describe('persistToolExec* — same-turn duplicate raw ids (#4155)', () => {
+ test('two calls sharing one raw id keep separate rows and settle on their own ordinal', async () => {
+ await persistToolExecPending(engine, jobId, 1, 0, 'dup', 'search', { q: 'a' });
+ await persistToolExecPending(engine, jobId, 1, 1, 'dup', 'put_page', { slug: 'b' });
+
+ let r = await rows();
+ expect(r.length).toBe(2); // the NOT EXISTS guard must not collapse stamped rows
+
+ // Settle call 0 complete, then call 1 failed — each on its own row.
+ await persistToolExecComplete(engine, jobId, 1, 0, 'dup', { hit: 'zero' });
+ await persistToolExecFailed(engine, jobId, 1, 1, 'dup', 'put_page', { slug: 'b' }, 'one-broke');
+
+ r = await rows();
+ expect(r.length).toBe(2);
+ expect(r[0].ordinal).toBe(0);
+ expect(r[0].status).toBe('complete');
+ expect(r[1].ordinal).toBe(1);
+ expect(r[1].status).toBe('failed');
+ expect(r[1].error).toBe('one-broke');
+ });
+
+ test('a late failure for one call never overwrites the settled same-id sibling', async () => {
+ // Call 0 fully settled; call 1 (same raw id) fails without a pending row.
+ await persistToolExecPending(engine, jobId, 1, 0, 'dup', 'search', { q: 'a' });
+ await persistToolExecComplete(engine, jobId, 1, 0, 'dup', { hit: 'keep-me' });
+ await persistToolExecFailed(engine, jobId, 1, 1, 'dup', 'search', { q: 'a' }, 'late-error');
+
+ const r = await rows();
+ expect(r.length).toBe(2);
+ expect(r[0].status).toBe('complete'); // untouched
+ expect(r[1].status).toBe('failed');
+ });
+
+ test('a failure for a call with no own row never captures a same-id sibling STILL-PENDING row', async () => {
+ // Red-team finding: an `OR status = 'pending'` disjunct in the failed
+ // UPDATE selected the sibling's in-flight row (different ordinal, same raw
+ // id) when the failing call had no row of its own (e.g. unregistered
+ // tool), marking the sibling failed with the wrong call's error and
+ // skipping the INSERT leg.
+ await persistToolExecPending(engine, jobId, 1, 0, 'dup', 'search', { q: 'a' });
+ // Call 1 (same raw id, ordinal 1) is rejected upfront — no pending row.
+ await persistToolExecFailed(engine, jobId, 1, 1, 'dup', 'bad_tool', {}, 'not in registry');
+
+ const r = await rows();
+ expect(r.length).toBe(2);
+ expect(r[0].ordinal).toBe(0);
+ expect(r[0].status).toBe('pending'); // sibling stays in flight, error-free
+ expect(r[0].error).toBeNull();
+ expect(r[1].ordinal).toBe(1);
+ expect(r[1].status).toBe('failed'); // failure lands on its OWN row
+ expect(r[1].error).toBe('not in registry');
+ });
+});
+
+describe('persistToolExecFailed — stable-id conflict downgrade guard', () => {
+ test('does not downgrade a complete row owned by a DIFFERENT tool_use_id at the same ordinal', async () => {
+ // Winner: settled complete at (msg 1, ordinal 0) under id "winner".
+ await persistToolExecPending(engine, jobId, 1, 0, 'winner', 'search', { q: 'w' });
+ await persistToolExecComplete(engine, jobId, 1, 0, 'winner', { hit: 'won' });
+
+ // Loser (zombie writer): same ordinal slot, different id, reports failed.
+ // The UPDATE leg finds nothing (different id, nothing pending), and the
+ // INSERT leg's conflict-update predicate must refuse the downgrade.
+ await persistToolExecFailed(engine, jobId, 1, 0, 'loser', 'search', { q: 'l' }, 'zombie-error');
+
+ const r = await rows();
+ expect(r.length).toBe(1);
+ expect(r[0].tool_use_id).toBe('winner');
+ expect(r[0].status).toBe('complete'); // NOT downgraded to failed
+ expect(r[0].error).toBeNull();
+ });
+});
+
+describe('persistToolExec* — legacy ordinal=NULL row compatibility', () => {
+ test('a legacy row suppresses re-insert and still receives settlement', async () => {
+ // Simulate a pre-upgrade pending row (no ordinal stamped).
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status)
+ VALUES ($1, 2, 'legacy-id', 'search', '{}'::jsonb, 'pending')`,
+ [jobId],
+ );
+
+ // Replay re-persists pending (now with an ordinal): must be a no-op.
+ await persistToolExecPending(engine, jobId, 2, 0, 'legacy-id', 'search', {});
+ let r = await rows();
+ expect(r.length).toBe(1);
+ expect(r[0].ordinal).toBeNull();
+
+ // Settlement finds the legacy row.
+ await persistToolExecComplete(engine, jobId, 2, 0, 'legacy-id', { hit: 'legacy' });
+ r = await rows();
+ expect(r.length).toBe(1);
+ expect(r[0].status).toBe('complete');
+ });
+
+ test('a late failure never downgrades a legacy row that already settled complete', async () => {
+ // Adversarial-review finding: the ordinal IS NULL disjunct in the failed
+ // UPDATE's inner SELECT matched a legacy COMPLETE row (CASE priority 2)
+ // when no own-ordinal/pending row existed, silently overwriting a settled
+ // outcome with 'failed'.
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output)
+ VALUES ($1, 3, 'legacy-done', 'search', '{}'::jsonb, 'complete', '{"hit":"keep"}'::jsonb)`,
+ [jobId],
+ );
+
+ await persistToolExecFailed(engine, jobId, 3, 1, 'legacy-done', 'search', {}, 'late-zombie-error');
+
+ const r = await rows();
+ const legacy = r.find(x => x.ordinal === null);
+ expect(legacy?.status).toBe('complete'); // NOT downgraded
+ expect(legacy?.error).toBeNull();
+ // The failure lands as its own stamped row instead of clobbering.
+ const stamped = r.find(x => x.ordinal === 1);
+ expect(stamped?.status).toBe('failed');
+ });
+
+ test('a late completion never overwrites a legacy row that already settled complete', async () => {
+ // Same class on the complete side: a settled legacy sibling's output must
+ // not be replaced by a different call's completion.
+ await engine.executeRaw(
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output)
+ VALUES ($1, 4, 'legacy-done2', 'search', '{}'::jsonb, 'complete', '{"hit":"original"}'::jsonb)`,
+ [jobId],
+ );
+
+ await persistToolExecComplete(engine, jobId, 4, 1, 'legacy-done2', { hit: 'other-call' });
+
+ const r = await rows();
+ const legacy = r.find(x => x.message_idx === 4 && x.ordinal === null);
+ const out = typeof legacy?.output === 'string' ? JSON.parse(legacy.output as string) : legacy?.output;
+ expect((out as Record<string, unknown>)?.hit).toBe('original'); // untouched
+ });
+});
diff --git a/test/subagent-transcript.test.ts b/test/subagent-transcript.test.ts
index 781ec3e837..440692595c 100644
--- a/test/subagent-transcript.test.ts
+++ b/test/subagent-transcript.test.ts
@@ -62,11 +62,12 @@ async function insertTool(
status: 'pending' | 'complete' | 'failed',
output: unknown = null,
error: string | null = null,
+ ordinal: number | null = null,
) {
await engine.executeRaw(
- `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output, error)
- VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7::jsonb, $8)`,
- [jobId, idx, toolUseId, toolName, JSON.stringify(input), status, output == null ? null : JSON.stringify(output), error],
+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, status, output, error, ordinal)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7::jsonb, $8, $9)`,
+ [jobId, idx, toolUseId, toolName, JSON.stringify(input), status, output == null ? null : JSON.stringify(output), error, ordinal],
);
}
@@ -145,6 +146,83 @@ describe('renderTranscript', () => {
expect(md).toContain('pending (no resolution recorded yet)');
});
+ test('#4155 regression: the same raw tool_use_id across two turns resolves each tool_use to ITS OWN execution row', async () => {
+ // claude-cli replays a fresh subprocess per turn from an id-stripped
+ // transcript, so the model reuses the same short id ("toolu_01") on every
+ // turn. Rows must resolve by (message_idx, tool_use_id): an id-only map
+ // is last-write-wins and mis-attributes turn 1's status/output to turn 2's
+ // row (and vice versa).
+ await insertMessage(0, 'user', [{ type: 'text', text: 'do two things' }]);
+ await insertMessage(1, 'assistant', [
+ { type: 'tool_use', id: 'toolu_01', name: 'brain_search', input: { q: 'first' } },
+ ]);
+ await insertMessage(2, 'user', [
+ { type: 'tool_result', tool_use_id: 'toolu_01', content: 'first-turn-output' },
+ ]);
+ await insertMessage(3, 'assistant', [
+ { type: 'tool_use', id: 'toolu_01', name: 'brain_put_page', input: { slug: 'x' } },
+ ]);
+ await insertMessage(4, 'user', [
+ { type: 'tool_result', tool_use_id: 'toolu_01', content: 'second-turn-error', is_error: true },
+ ]);
+ // Same raw id on both rows — legal now that the job-wide unique on
+ // (job_id, tool_use_id) is gone from the schema (v131).
+ await insertTool(1, 'toolu_01', 'brain_search', { q: 'first' }, 'complete', { hit: 'first-turn-output' });
+ await insertTool(3, 'toolu_01', 'brain_put_page', { slug: 'x' }, 'failed', null, 'second-turn-error');
+
+ const { messages, tools } = await loadTranscriptRows(engine, jobId);
+ expect(tools.length).toBe(2); // both rows persisted despite the shared raw id
+ const md = renderTranscript(messages, tools);
+
+ // Attribution: turn 1 (before the "## Message 3" header) shows ITS
+ // complete output; turn 2 (after) shows ITS failure. Pre-fix, the
+ // id-only map served the LAST row for both lookups, so turn 1 rendered
+ // as failed.
+ const splitAt = md.indexOf('## Message 3');
+ expect(splitAt).toBeGreaterThan(-1);
+ const turn1 = md.slice(0, splitAt);
+ const turn2 = md.slice(splitAt);
+ expect(turn1).toContain('status: **complete**');
+ expect(turn1).toContain('first-turn-output');
+ expect(turn1).not.toContain('status: **failed**');
+ expect(turn2).toContain('status: **failed**');
+ expect(turn2).toContain('second-turn-error');
+ expect(turn2).not.toContain('status: **complete**');
+
+ // The echoed tool_result blocks are still recognized as owned (skipped),
+ // not dumped as orphans.
+ expect(md).not.toContain('no matching tool_use in this transcript');
+ });
+
+ test('#4155 corner: the same raw id repeated WITHIN one turn resolves per-call by the stamped ordinal', async () => {
+ // A provider should never repeat an id inside a single response, but the
+ // ledger tolerates it: rows carry the D11 ordinal and rendering resolves
+ // ordinal-first, disabling the ambiguous raw-id map for repeated ids.
+ await insertMessage(0, 'assistant', [
+ { type: 'tool_use', id: 'dup', name: 'brain_search', input: { q: 'a' } },
+ { type: 'tool_use', id: 'dup', name: 'brain_put_page', input: { slug: 'b' } },
+ ]);
+ await insertTool(0, 'dup', 'brain_search', { q: 'a' }, 'complete', { hit: 'ordinal-zero-output' }, null, 0);
+ await insertTool(0, 'dup', 'brain_put_page', { slug: 'b' }, 'failed', null, 'ordinal-one-error', 1);
+
+ const { messages, tools } = await loadTranscriptRows(engine, jobId);
+ expect(tools.length).toBe(2);
+ const md = renderTranscript(messages, tools);
+
+ const firstBlockAt = md.indexOf('**tool_use** `brain_search`');
+ const secondBlockAt = md.indexOf('**tool_use** `brain_put_page`');
+ expect(firstBlockAt).toBeGreaterThan(-1);
+ expect(secondBlockAt).toBeGreaterThan(firstBlockAt);
+ const firstBlock = md.slice(firstBlockAt, secondBlockAt);
+ const secondBlock = md.slice(secondBlockAt);
+ expect(firstBlock).toContain('status: **complete**');
+ expect(firstBlock).toContain('ordinal-zero-output');
+ expect(firstBlock).not.toContain('ordinal-one-error');
+ expect(secondBlock).toContain('status: **failed**');
+ expect(secondBlock).toContain('ordinal-one-error');
+ expect(secondBlock).not.toContain('ordinal-zero-output');
+ });
+
test('truncates huge tool outputs per maxOutputBytes', async () => {
await insertMessage(0, 'assistant', [
{ type: 'tool_use', id: 'tu_big', name: 'brain_search', input: {} },
diff --git a/test/sync-classifier-widening.test.ts b/test/sync-classifier-widening.test.ts
index f7a1a5adf3..0022f74699 100644
--- a/test/sync-classifier-widening.test.ts
+++ b/test/sync-classifier-widening.test.ts
@@ -66,9 +66,11 @@ describe('Layer 2 — isCodeFilePath widening', () => {
expect(isCodeFilePath('contracts/Token.sol')).toBe(true);
});
- test('Web + config extensions (CSS, HTML, Vue, JSON, YAML, TOML)', () => {
+ test('Web + config extensions (CSS, HTML, Astro, Svelte, Vue, JSON, YAML, TOML)', () => {
expect(isCodeFilePath('src/app.css')).toBe(true);
expect(isCodeFilePath('public/index.html')).toBe(true);
+ expect(isCodeFilePath('src/pages/index.astro')).toBe(true);
+ expect(isCodeFilePath('src/routes/App.svelte')).toBe(true);
expect(isCodeFilePath('src/App.vue')).toBe(true);
expect(isCodeFilePath('package.json')).toBe(true);
expect(isCodeFilePath('config.yaml')).toBe(true);
diff --git a/test/sync-path-containment.test.ts b/test/sync-path-containment.test.ts
index 0824ae8a4c..8914a671a8 100644
--- a/test/sync-path-containment.test.ts
+++ b/test/sync-path-containment.test.ts
@@ -17,7 +17,7 @@
*/
import { describe, test, expect } from 'bun:test';
-import { join, sep, parse } from 'path';
+import { join, sep, parse, win32 } from 'path';
import { isWithinRoot } from '../src/commands/sync.ts';
describe('isWithinRoot path containment (#774 NAV-1/NAV-2)', () => {
@@ -31,6 +31,10 @@ describe('isWithinRoot path containment (#774 NAV-1/NAV-2)', () => {
expect(isWithinRoot(join(root, 'page.md'), root)).toBe(true);
});
+ test('accepts the root with a trailing separator', () => {
+ expect(isWithinRoot(root + sep, root)).toBe(true);
+ });
+
test('accepts a nested descendant (the case a hardcoded "/" broke on win32)', () => {
expect(isWithinRoot(join(root, 'wiki', 'notes', 'page.md'), root)).toBe(true);
});
@@ -58,4 +62,12 @@ describe('isWithinRoot path containment (#774 NAV-1/NAV-2)', () => {
const child = `${root}${sep}sub${sep}page.md`;
expect(isWithinRoot(child, root)).toBe(true);
});
+
+ test('accepts Windows paths that differ only by directory casing', () => {
+ const winRoot = 'C:\\Users\\person\\Projects\\Tally';
+
+ expect(isWithinRoot('C:\\Users\\person\\projects\\Tally', winRoot, win32)).toBe(true);
+ expect(isWithinRoot('C:\\Users\\person\\projects\\Tally\\wiki\\page.md', winRoot, win32)).toBe(true);
+ expect(isWithinRoot('C:\\Users\\person\\projects\\Tally-evil\\page.md', winRoot, win32)).toBe(false);
+ });
});
diff --git a/test/think-max-output-tokens.test.ts b/test/think-max-output-tokens.test.ts
index dc060ef5cc..36e6642685 100644
--- a/test/think-max-output-tokens.test.ts
+++ b/test/think-max-output-tokens.test.ts
@@ -47,13 +47,27 @@ describe('maxOutputTokensFor — thinking-default headroom', () => {
// Version/name boundaries: `gpt-50` and `o3foo` are not gpt-5 / o3.
expect(maxOutputTokensFor('openai:gpt-50')).toBe(4000);
expect(maxOutputTokensFor('openai:o3foo')).toBe(4000);
- // Other providers' reasoning models are out of scope here — the routed
- // provider recipe, not this budget, is what changes for them.
- expect(maxOutputTokensFor('deepseek:deepseek-reasoner')).toBe(4000);
// Prefix must be the openai provider — a bare model name or another
// provider's gpt-5 spelling doesn't match.
expect(maxOutputTokensFor('o3')).toBe(4000);
expect(maxOutputTokensFor('gpt-5.2')).toBe(4000);
expect(maxOutputTokensFor('openrouter:openai/gpt-5.2')).toBe(4000);
});
+
+ test('gbrain#4172 — recipe-declared thinking-by-default models (DeepSeek v4) get 16000 via the capability layer', () => {
+ // DeepSeek v4 thinks by default and bills reasoning against max_tokens:
+ // at 4000 the whole budget is spent reasoning and think returns
+ // truncated/empty JSON. Keyed on thinking_by_default (capability), not a
+ // model-name regex, so provider renames keep the headroom.
+ expect(maxOutputTokensFor('deepseek:deepseek-v4-flash')).toBe(16000);
+ expect(maxOutputTokensFor('deepseek:deepseek-v4-pro')).toBe(16000);
+ // Retired alias still routes to a thinking v4 model at the provider.
+ expect(maxOutputTokensFor('deepseek:deepseek-reasoner')).toBe(16000);
+ // Recipes without the capability keep the conservative default.
+ expect(maxOutputTokensFor('ollama:llama3.3')).toBe(4000);
+ expect(maxOutputTokensFor('groq:llama-3.3-70b-versatile')).toBe(4000);
+ // Unknown provider strings fail open to the default, never throw.
+ expect(maxOutputTokensFor('nonexistent-provider:whatever')).toBe(4000);
+ expect(maxOutputTokensFor('voyage:voyage-4')).toBe(4000); // chat-less recipe
+ });
});
diff --git a/test/transcript-render.test.ts b/test/transcript-render.test.ts
index 7f6e73ea20..9e41bf05b5 100644
--- a/test/transcript-render.test.ts
+++ b/test/transcript-render.test.ts
@@ -62,6 +62,25 @@ describe('render round-trip through the SHARED imessage-slack pattern', () => {
expect(body).toContain('(2026-08-02 9:30 PM)');
});
+ test('multi-line coding turns remain parseable below the ordinary density floor', () => {
+ const longUserTurn = Array.from({ length: 40 }, (_, i) => `user line ${i}`).join('\n');
+ const longAssistantTurn = Array.from({ length: 40 }, (_, i) => `assistant line ${i}`).join('\n');
+ const sparse = session([
+ { role: 'user', timestamp: '2026-08-02T09:00:03.000Z', text: longUserTurn },
+ { role: 'assistant', timestamp: '2026-08-02T09:00:04.000Z', text: longAssistantTurn },
+ ]);
+
+ const rendered = renderSessionParts(
+ redactSession(sparse, { userPatternsPath: '/nonexistent' }),
+ );
+ const parsed = parseConversation(splitBody(rendered.parts[0].content));
+
+ expect(parsed.matched_pattern_id).toBe('imessage-slack');
+ expect(parsed.messages).toHaveLength(2);
+ expect(parsed.messages[0].text).toContain('user line 39');
+ expect(parsed.messages[1].text).toContain('assistant line 39');
+ });
+
test('frontmatter is mandatory-complete: type, date, unique per-part id, marker', () => {
const r = renderSessionParts(redactSession(BASIC, { userPatternsPath: '/nonexistent' }));
const fm = frontmatter(r.parts[0].content);
diff --git a/test/transcripts-max-bytes.test.ts b/test/transcripts-max-bytes.test.ts
new file mode 100644
index 0000000000..3866150b1d
--- /dev/null
+++ b/test/transcripts-max-bytes.test.ts
@@ -0,0 +1,118 @@
+/**
+ * gbrain#4149 — the per-format byte caps get a validated, checkpoint-aware
+ * escape hatch instead of being unreachable from the CLI.
+ *
+ * Pre-fix (red on master at the assertions): ParseSessionsOpts.maxBytes
+ * existed but ingest.ts never threaded it, so `gbrain transcripts ingest`
+ * users hit the Hermes 512MB store guard with no recourse; --max-bytes was
+ * an unknown flag; and a --since last checkpoint carried no cap dimension.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+import { parseIngestArgs, ingestCheckpointFingerprintInput } from '../src/commands/transcripts.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+import { fingerprint } from '../src/core/op-checkpoint.ts';
+import type { TranscriptAdapter, ParseSessionsOpts } from '../src/core/transcripts/types.ts';
+import { mkdtempSync, writeFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+describe('--max-bytes CLI validation (gbrain#4149)', () => {
+ test('accepts plain bytes and kb/mb/gb forms', () => {
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '800000000']) as any).maxBytes).toBe(800_000_000);
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '512mb']) as any).maxBytes).toBe(512 * 1024 ** 2);
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '4gb']) as any).maxBytes).toBe(4 * 1024 ** 3);
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '1.5gb']) as any).maxBytes).toBe(Math.floor(1.5 * 1024 ** 3));
+ });
+
+ test('rejects garbage, zero, and negatives loudly', () => {
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', 'lots']) as any).error).toContain('max-bytes');
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '0']) as any).error).toContain('positive');
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes', '-5']) as any).error).toContain('max-bytes');
+ expect((parseIngestArgs(['a.jsonl', '--max-bytes']) as any).error).toContain('max-bytes');
+ });
+
+ test('omission leaves maxBytes undefined (adapter-native defaults stay in charge)', () => {
+ expect((parseIngestArgs(['a.jsonl']) as any).maxBytes).toBeUndefined();
+ });
+});
+
+describe('cap threading to adapters (gbrain#4149)', () => {
+ function stubAdapter(seen: Array<ParseSessionsOpts | undefined>): TranscriptAdapter {
+ return {
+ format: 'claude-code' as never,
+ specTarget: 'claude-code' as never,
+ detect: () => true,
+ // eslint-disable-next-line require-yield
+ parse: async function* (_path: string, opts?: ParseSessionsOpts) {
+ seen.push(opts);
+ return { truncated: false } as never;
+ },
+ };
+ }
+
+ const scratchDirs: string[] = [];
+ afterEach(() => {
+ for (const d of scratchDirs.splice(0)) rmSync(d, { recursive: true, force: true });
+ });
+
+ async function runWith(maxBytes: number | undefined, seen: Array<ParseSessionsOpts | undefined>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gb4149-'));
+ scratchDirs.push(dir);
+ const f = join(dir, 's.jsonl');
+ writeFileSync(f, '{"x":1}\n');
+ await runTranscriptsIngest({} as never, {
+ paths: [f],
+ dryRun: true,
+ sourceId: 'default',
+ maxBytes,
+ adapters: [stubAdapter(seen)],
+ });
+ }
+
+ test('an explicit cap reaches adapter.parse', async () => {
+ const seen: Array<ParseSessionsOpts | undefined> = [];
+ await runWith(123_456, seen);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]?.maxBytes).toBe(123_456);
+ });
+
+ test('omission passes NO opts — each adapter keeps its format-specific default', async () => {
+ const seen: Array<ParseSessionsOpts | undefined> = [];
+ await runWith(undefined, seen);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]).toBeUndefined();
+ });
+});
+
+describe('checkpoint fingerprint carries the cap (gbrain#4149)', () => {
+ const base = { sourceId: 'default', pathspec: '~/.hermes/state.db', format: 'hermes', version: 'v3' };
+
+ test('auto vs explicit caps produce different fingerprints (no silent watermark reuse)', () => {
+ const auto = fingerprint(ingestCheckpointFingerprintInput(base));
+ const capped = fingerprint(ingestCheckpointFingerprintInput({ ...base, maxBytes: 4 * 1024 ** 3 }));
+ const cappedOther = fingerprint(ingestCheckpointFingerprintInput({ ...base, maxBytes: 512 * 1024 ** 2 }));
+ expect(auto).not.toBe(capped);
+ expect(capped).not.toBe(cappedOther);
+ });
+
+ test('the default (no-cap) path keeps the LEGACY 4-key fingerprint — existing watermarks stay valid at upgrade', () => {
+ // Review finding (multi-specialist confirmed): an unconditional
+ // maxBytes:'auto' key would orphan every pre-#4149 checkpoint and force
+ // a silent one-time full rescan on the first post-upgrade --since last.
+ const auto = fingerprint(ingestCheckpointFingerprintInput(base));
+ const legacy = fingerprint({
+ sourceId: base.sourceId,
+ pathspec: base.pathspec,
+ format: base.format,
+ version: base.version,
+ });
+ expect(auto).toBe(legacy);
+ });
+
+ test('the same cap is stable (checkpoint resume still works within one cap)', () => {
+ const a = fingerprint(ingestCheckpointFingerprintInput({ ...base, maxBytes: 1024 }));
+ const b = fingerprint(ingestCheckpointFingerprintInput({ ...base, maxBytes: 1024 }));
+ expect(a).toBe(b);
+ });
+});