Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.12.2 feat(mcp): CLI→MCP gap closure — 11 new ops, capture, thin-client routing (#4229)

Garry Tan9c2c911886ea
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index ed8259288c..35f7337dc2 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.12.0",
+ "version": "0.46.12.2",
"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 9a6b499fd1..5e2f347b10 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.12.0",
+ "version": "0.46.12.2",
"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 2b2b032a8a..ae6a5b3363 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.12.0 -->
+<!-- gbrain-runbook-stamp: 0.46.12.2 -->
<!-- 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 ea9bfe4d02..1ebe9ed752 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,71 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.12.2] - 2026-08-16
+
+**Your agent can now do over MCP what it could only do from the CLI.** An
+audit of the CLI-versus-MCP surface found the gap was never that MCP filtered
+tools out — it was CLI commands that never got an operation entry, so a
+connected agent hit "unknown tool" and fell back to shelling out. This wave
+closes that: eleven new tools, so an agent can record and resolve predictions,
+capture a quick note, check queue health, and read search/cache diagnostics
+without leaving the MCP session.
+
+### Added
+- **Record predictions from your agent.** `takes_add`, `takes_update`,
+ `takes_resolve`, and `takes_supersede` let a connected agent write to the
+ predictions ledger, not just read it — record a bet, refine its weight,
+ resolve it with evidence, or supersede a stale claim. Resolutions an agent
+ makes are tagged distinctly from your own, so the calibration scorecard keeps
+ agent-made and owner-made verdicts separable (`takes_scorecard` shows the
+ count).
+- **`capture` over MCP.** The "just remember this" write is now an MCP tool,
+ not CLI-only: it auto-derives a stable inbox slug, dedupes identical content,
+ and is on the daily-driver (`starter`) surface so bundled connect flows can
+ reach it. Prefer it for quick notes; `put_page` still handles full-control
+ writes.
+- **Queue health from your agent.** `get_job_stats` surfaces the job queue's
+ per-type rollup and health counts over MCP, including the "wedged queue"
+ signal (a worker alive but claiming nothing while work waits) — the one jobs
+ command that had no MCP equivalent.
+- **Retrieval + cache diagnostics over MCP.** `search_stats`, `search_modes`,
+ `search_tune`, and `cache_stats` expose the same read-only dashboards as
+ `gbrain search` / `gbrain cache stats`, so an agent asked to diagnose
+ retrieval quality or cost no longer has to shell out. Tuning recommendations
+ come back as paste-ready commands; applying them stays a deliberate local
+ step.
+- **Content-quality triage over MCP.** `quarantine_list` shows hidden and
+ flagged pages for review; scanning and clearing stay local.
+- **Migration state in `get_health`.** The health dashboard now reports
+ pending, partial, and wedged host migrations, so a remote operator can spot
+ a stuck migration without opening a shell on the host.
+- **Thin-client installs route the new tools automatically.** On a
+ connect-to-a-remote-brain install, `gbrain takes …`, `gbrain search
+ stats|modes|tune`, `gbrain jobs stats`, `gbrain cache stats`, and `gbrain
+ quarantine list` now run against the brain host instead of failing.
+
+### Changed
+- **`gbrain whoknows` now shows its full ranked view.** The expertise-routing
+ command was reachable but rendered generic output; it now renders the ranked
+ table with per-factor explanations it was always meant to show.
+- **The agent tool catalog is honest on every transport.** On a local
+ (stdio) connection, tools gated off by the brain owner no longer appear in
+ the tool list only to be refused when called — they're hidden until enabled,
+ matching how remote connections already behaved.
+
+### Fixed
+- **Predictions written over MCP are safe by construction.** The
+ markdown-canonical takes store keeps its file writes contained to the right
+ source's working tree, writes atomically, refuses input that could corrupt
+ the on-page table, and treats a database mirror hiccup as recoverable rather
+ than losing the write — the same protections the main page writer already
+ had, now covering the new remote write path.
+
+To take advantage of v0.46.12.2: reconnect your coding agent (or restart
+`gbrain serve`) so the new tools appear in its catalog. On the default `full`
+surface every new tool is available immediately; on `starter`, `capture` joins
+the daily-driver set. Nothing to configure — the tools are read-only or
+scope-and-fence-protected exactly like the operations they mirror.
## [0.46.12.0] - 2026-08-16
**Every surface that could still steer you toward the retiring embedding
diff --git a/TODOS.md b/TODOS.md
index e47b9a7040..9dda140c35 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,64 @@
# TODOS
+## CLI→MCP gap-closure wave follow-ups (2026-08-16; plan: ~/.claude/plans/system-instruction-you-are-working-concurrent-lantern.md)
+
+- [ ] **P2 — publish-gate fail-open on a DB-config read failure.**
+ **What:** `readPublishGate` + `assertPublishEnabled` (publish-gate path) fall back to the
+ file plane when `engine.getConfig` throws, so a DB outage with file-plane=true but a
+ DB-override=false widens authorization instead of denying it. **Why:** an auth gate that
+ opens wider when its store is unreachable is fail-open — the wrong default for a
+ publish/authorization boundary. **Context:** pre-existing behavior, explicitly pinned by
+ `test/publish-gates.test.ts:71`; this needs a dedicated auth-plane decision (fail-closed
+ vs. the current fail-open), NOT a drive-by flip in a test-regression pass. **Effort:** M,
+ review-bound (one-way-door auth semantics).
+
+- [ ] **P2 — takes-fence parser drops pack-extended kinds (whole-page refusal is the interim guard).**
+ **What:** `parseTakesFence`'s `KIND_VALUES` is the closed `{fact,take,bet,hunch}` set, so a
+ schema-pack kind (`finding|hypothesis|…`) is skipped as malformed and surfaces a warning —
+ which is exactly why the F1 guard (`assertFenceRoundTrips`) has to refuse the WHOLE page to
+ avoid deleting the skipped row on a re-render. **Why:** a brain with pack-extended takes
+ kinds can't be mutated through the write verbs at all today (every mutate refuses
+ `fence_unparsed`). **Deeper fix:** widen the parser to accept any string kind (`TakeKind`
+ opened to `string` in v0.38) and/or make the fence editor splice-preserve raw unparsed
+ lines instead of a whole-fence re-render. **Effort:** M. (Related to the P3 pack-aware
+ kind-validation item below, but that one is write-side; this is the parser + editor.)
+
+- [ ] **P2 — `get_health` migration-ledger honesty.**
+ **What:** `loadCompletedMigrations` skips a malformed JSONL line with a `warn`, so a
+ truncated ledger entry silently mis-reports — a completed migration can look pending —
+ instead of surfacing a `ledger_unreadable` signal. **Why:** health/doctor output should
+ fail loud when its own audit trail is unreadable, not quietly under-count. **Effort:** S.
+
+- [ ] **P2 — `quarantine_list` SELECT projection pushdown.**
+ **What:** the quarantine scan pulls full page bodies (`SELECT p.*`) only to read two
+ frontmatter keys. Push the marker filter into SQL (`frontmatter ? 'quarantine'`) and
+ project just `slug`, `source_id`, `frontmatter`. **Why:** loading every page body to check
+ a frontmatter flag is O(corpus-bytes) for an O(matches) result. **Effort:** S.
+
+- [ ] **P3 — `permissions.takes_write_holders`: split the takes read/write holder axes.**
+ **What:** a dedicated write-side holder allow-list config, consumed by the takes write
+ verbs' fence in `src/core/ops/takes.ts` (today the WRITE fence reuses the READ
+ allow-list `takesHoldersAllowList` — fail-closed and symmetric, but semantically
+ overloaded). **Why:** an operator may want an agent to READ private holders but WRITE
+ only world-held rows, or vice versa. **Context:** decided at the wave's CEO/OV review
+ ("reuse now, split when field use demands"); the fence is one shared function
+ (`takesWriteAllowList` + takes-write.ts's holder checks), so the split is a
+ resolution-chain change, not a redesign. **Effort:** S. **Depends on:** field demand.
+
+- [ ] **P3 — pack-aware takes kind validation, shared CLI + ops.**
+ **What:** `takes_add`/`takes_supersede` pin `kind` to the 4 base literals
+ (fact|take|bet|hunch) — same limitation as the CLI's `ensureKind` — while schema packs
+ can extend `takes_kinds` (engine.ts TakeKindLiteral). Validate against the ACTIVE
+ pack's kind set in ONE shared place (takes-write.ts) and widen the op enum note.
+ **Why:** pack-extended kinds (finding|hypothesis|…) can't be written through either
+ surface today. **Effort:** S.
+
+- [ ] **P3 — `mcp:capture` provenance channel label (mini trust review).**
+ **What:** capture delegates to put_page, so remote captures stamp `source_kind:
+ 'mcp:put_page'` (honest CV6 delegation; the op result carries channel:'capture').
+ A distinct `mcp:capture` stamp needs a trusted internal channel label through the CV6
+ else-branch — its own small trust review, filed rather than rushed. **Why:** finer
+ provenance analytics on ingestion channels. **Effort:** S, review-bound.
## Five-issue fix wave follow-ups (backlinks corruption / malformed paths / type warnings / getPage scoping / queue admission)
- [ ] **P2 — migrate the remaining fs writers to core/atomic-write.** **What:**
@@ -4244,6 +4303,16 @@ verify Voyage adapter integration in `src/core/ai/recipes/voyage.ts`).
### Token rotation: `gbrain auth rotate <name>` + `rotate_token` MCP op
**Priority:** P2
+**Deferral note (CLI→MCP gap-closure wave, 2026-08-16, user decision D3A):**
+deliberately NOT bundled into the gap-closure wave — there is no CLI to
+mirror yet (this TODO is its own work item, not a CLI→MCP gap), and a token
+that can mint its own successor turns a leaked credential into persistence +
+operator lock-out, so it needs its own auth-plane design pass. Sketch agreed
+at review: admin scope, NOT localOnly (remote rotation is the point),
+SELF-rotation only (the calling token/client — never a name param), returns
+the new secret exactly once, rate-limited via the RateLimiter house pattern,
+and ships in the same PR as the `gbrain auth rotate` CLI.
+
**What:** Atomic rotate for legacy + OAuth tokens. Issue a new token in the same TX as the revocation of the old, no overlap window. Refresh-token rotation already exists for OAuth; this is the unified user-facing surface (CLI + MCP).
**Why:** Today rotation is `revoke + create`, with a window where neither token works. For long-lived bearer keys handed to agents, that's a reload outage every time the key gets rotated.
@@ -4254,7 +4323,15 @@ verify Voyage adapter integration in `src/core/ai/recipes/voyage.ts`).
**Depends on:** Nothing.
### Migration introspection in `get_health`
-**Priority:** P3
+**Priority:** P3 — **DONE (CLI→MCP gap-closure wave, 2026-08-16).** The
+`get_health` OP now returns `migrations {pending, partial, wedged,
+skipped_future}` composed at the op layer from the new
+`src/core/migration-ledger.ts` (version strings only). Op-layer composition
+was chosen over this TODO's engine-method wording: the ledger is a
+filesystem JSONL, engine-agnostic — growing `BrainEngine.getHealth()` would
+have duplicated a file read in both engines. Pinned by
+`test/migration-ledger.test.ts` + `test/get-job-stats-op.test.ts`'s sibling
+patterns.
**What:** Extend `BrainEngine.getHealth()` return shape with `migrations: { pending: [...], wedged: [...] }`. `gbrain doctor` already shows this; expose it via the MCP op so remote agents can detect partial-migration state without invoking `doctor` separately.
diff --git a/VERSION b/VERSION
index d7cf5c11b1..d253aaaac1 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.12.0
+0.46.12.2
\ No newline at end of file
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 6cb1a40d28..1b20bac989 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -73,7 +73,7 @@ claude mcp add gbrain -- gbrain serve --surface verbs # Claude Code
codex mcp add gbrain -- gbrain serve --surface verbs # Codex
```
-The agent spawns `gbrain serve` as a stdio subprocess against your local brain. `--surface verbs` gives the agent the seven-verb memory protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` — [MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) instead of the full tool catalog; `--surface starter` adds the daily-driver set on top of the verbs (~26 ops total); drop the flag (default `full`) for every operation. Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
+The agent spawns `gbrain serve` as a stdio subprocess against your local brain. `--surface verbs` gives the agent the seven-verb memory protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` — [MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) instead of the full tool catalog; `--surface starter` adds the daily-driver set on top of the verbs (~27 ops total); drop the flag (default `full`) for every operation. Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
## 3. MCP server (any MCP client)
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 3bc78fde6c..51fa08ea26 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,15 +4,16 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **Starter** marks membership in the ~26-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 115 tools across 22 areas. **Starter** marks membership in the ~27-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
-| `get_health` | Brain health dashboard (embed coverage, stale pages, orphans) | admin | | |
+| `get_health` | Brain health dashboard (embed coverage, stale pages, orphans). | admin | | |
| `get_stats` | Brain statistics (page count, chunk count, etc.) | admin | | |
| `get_status_snapshot` | Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. | admin | | |
+| `quarantine_list` | List quarantined (hidden) and optionally content-flagged pages by scanning page frontmatter, newest-updated first. | admin | | |
| `run_doctor` | Run brain health checks and return a structured DoctorReport (thin-client doctor surface). | admin | | |
| `run_onboard` | Probe brain health + optionally submit onboard remediations. | admin | | |
| `run_skillopt` | Run SkillOpt against a single skill. | admin | | |
@@ -91,6 +92,7 @@ Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **S
| `get_agent_job` | Poll an agent job submitted via submit_agent. | agent | yes | |
| `get_job` | Get job status and details by ID | admin | | |
| `get_job_progress` | Get structured progress for a running job | admin | | |
+| `get_job_stats` | Job queue statistics. | admin | | |
| `list_jobs` | List jobs with optional filters | admin | | |
| `pause_job` | Pause a waiting, active, or delayed job | admin | | |
| `replay_job` | Replay a completed/failed/dead job, optionally with modified data | admin | | |
@@ -144,6 +146,7 @@ Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
+| `capture` | Capture a quick note into the brain — the "just remember this" write. | write | yes | |
| `delete_page` | Soft-delete a page. | write | | |
| `get_chunks` | Get content chunks for a page | read | | |
| `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |
@@ -174,9 +177,13 @@ Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
+| `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | |
| `query` | Hybrid search with vector + keyword + multi-query expansion. | read | yes | |
| `search` | Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. | read | yes | |
| `search_by_image` | v0.36 cross-modal Phase 2: image-as-query retrieval. | read | | |
+| `search_modes` | Read-only search-mode dashboard: active mode, per-knob resolved value with attribution (mode default vs config override), and the three frozen bundles. | read | | |
+| `search_stats` | Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. | admin | | |
+| `search_tune` | Read-only tuning recommendations derived from the last 7 days of search telemetry: what should change, why, and the paste-ready config command per recommendation — relay them to the user. | admin | | |
## skills
@@ -207,10 +214,14 @@ Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
+| `takes_add` | Record a take (typed claim) on a page: fact / take / bet / hunch, with a holder (who holds the belief: world, people/<slug>, companies/<slug>, or brain), weight 0..1, and optional source/since date. | write | | |
| `takes_calibration` | Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket. | read | | |
| `takes_list` | List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc. | read | | |
+| `takes_resolve` | Resolve a take: quality correct / incorrect / partial / unresolvable, with optional evidence text and measured value/unit. | write | | |
| `takes_scorecard` | Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate. | read | | |
| `takes_search` | Keyword search across takes (pg_trgm similarity over claim text) | read | | |
+| `takes_supersede` | Supersede a take with a replacement claim: the old row is struck through (kept for archaeology), the replacement appends at the next fence row number. | write | | |
+| `takes_update` | Update a take's mutable fields (weight, source, since date). | write | | |
| `think` | Multi-hop synthesis across pages + takes + graph. | read | | |
## timeline
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 058bd733b0..d565389960 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -277,7 +277,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/verbs/usage-log.ts` — E4 observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember` [E1]. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession [X1]: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old) + superseded_by link; DB path: engine insertFact supersedeId). Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented).
-- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~26-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the FOV-6b fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools`; re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition (an out-of-sync copy in the collector once produced a perpetual bogus unused-starter finding). `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). WP4 per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases).
+- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the FOV-6b fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition (an out-of-sync copy in the collector once produced a perpetual bogus unused-starter finding). `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). WP4 per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases).
- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.
- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).
- `src/commands/agent.ts` — `gbrain agent run <prompt> [flags]` CLI. Submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`. Single-entry `--fanout-manifest` short-circuits. Children get `on_child_fail: 'continue'` + `max_stalled: 3`. `--follow` is the default on TTY; streams logs + polls `waitForCompletion` in parallel. Ctrl-C detaches, does not cancel.
@@ -301,7 +301,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.
- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar) and `--federated-read <S1,S2,...>` (read scope, array) and prints the resolved `Write source` + `Federated reads`; pre-v0.34 clients backfill to `source_id='default'` via migration v60. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)` (the inline version used `rest[takesIdx + 1]` resolving to `rest[0]` when `takesIdx === -1`, excluding the name from the positional search). Pinned by `test/auth-create-args.test.ts`.
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses JSON error envelopes first, falls back to substring detection for legacy server messages. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
-- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `put_page` not `capture` since `capture` is CLI-only, not an MCP tool) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing an inline `bearer_token` managed block because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set and that `capture` is NOT advertised) + `test/serve-skills-publish-nudge.test.ts` (the `test/audit/batch-retry-audit.test.ts` ENOENT case was made hermetic — it had read the real `~/.gbrain/audit`).
+- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which now names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing an inline `bearer_token` managed block because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts` (the `test/audit/batch-retry-audit.test.ts` ENOENT case was made hermetic — it had read the real `~/.gbrain/audit`).
- `src/commands/upgrade.ts` — self-update CLI. `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally.
- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators no longer call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in the `MIGRATIONS` array in `src/core/migrate.ts`. `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (running in-process removes the spawn that died with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.
- `src/commands/migrations/v0_46_3.ts` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 24387bac34..7e75ce0e02 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -46,7 +46,7 @@ tunnel, no token needed. Works with both PGLite and Supabase engines.
`entity`, `synthesize`, `forget`, `context_pack`, `delta` —
[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)),
the surface built for agents and quickstarts. `--surface starter` adds the
-daily-driver set on top (~26 ops total). Drop the flag for the full
+daily-driver set on top (core page/search/graph ops + capture). Drop the flag for the full
operation catalog (`get_page`, `put_page`, `search`, graph ops, …) — `full` is
the default and what existing installs already run.
@@ -118,8 +118,10 @@ You should see results from your GBrain knowledge base.
> `gbrain config set mcp.publish_skills true`. Skill discovery and the core tools
> named here (search, query, get_page, put_page, think, find_experts) are
> full-surface — on `--surface verbs` the agent sees only the seven memory verbs,
-> and `list_skills` isn't on the surface at all. Note: `capture` is a
-> CLI-only command, not an MCP tool — the agent writes over MCP with `put_page`.
+> and `list_skills` isn't on the surface at all. `capture` is on the starter and
+> full surfaces (prefer it for quick notes — auto-slug + dedupe; `put_page` for
+> full-control writes); if your tool list doesn't carry it, use `put_page`, or
+> `remember` on the verbs surface.
> Why brains differ on the default: [tutorial A1](../tutorials/connect-coding-agent.md#a1-on-the-host-serve-over-http).
## Ambient recall at session boundaries (v0.45.7)
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 3ee9aedfb0..9a26e5b18b 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -39,7 +39,7 @@ that exact install one-liner on stderr; with no brain, it exits with
resolution order: `$GBRAIN_BIN` → `~/.bun/bin/gbrain` → `gbrain` on PATH — the
sanctioned install location is preferred over PATH so a stray `gbrain` earlier
on PATH can't shadow it).
-`starter` is the 26-op daily-driver surface (the seven memory verbs + daily
+`starter` is the daily-driver surface (the seven memory verbs + daily
brain ops) — the curated skills drive everything else through the `gbrain`
CLI. Widen a machine without editing the snapshot: `GBRAIN_SURFACE=full` in
the env that launches Codex (new sessions pick it up), or use the bootstrap
@@ -129,8 +129,10 @@ everything it can do.
> **`list_skills` empty?** It's gated by `mcp.publish_skills` on the host — enable
> it with `gbrain config set mcp.publish_skills true`. The core tools (search,
-> query, get_page, put_page, think, find_experts) work regardless; `capture` is
-> CLI-only, so write over MCP with `put_page`. Why brains differ on the default:
+> query, get_page, put_page, capture, think, find_experts) work regardless —
+> prefer `capture` for quick notes (auto-slug + dedupe), `put_page` for
+> full-control writes; if a narrowed token's list lacks capture, use `put_page`.
+> Why brains differ on the default:
> [tutorial A1](../tutorials/connect-coding-agent.md#a1-on-the-host-serve-over-http).
## Remove
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 108d8b1e9e..1a7f98353e 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -29,7 +29,7 @@ No server, no tunnel, no token needed. Works on both PGLite and Postgres engines
`--surface verbs` exposes exactly the seven-verb memory protocol (`recall`,
`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full catalog;
-`--surface starter` sits between (~26 ops: the verbs plus the daily-driver set);
+`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
omit the flag (default `full`) for every operation.
### Remote over OAuth 2.1 (recommended)
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 4b617ba7fa..f03816898c 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -82,8 +82,8 @@ each client.
**Surface modes:** `--surface verbs` exposes EXACTLY the seven verbs —
advertised list AND dispatch are filtered fail-closed (a hidden op returns
`unknown_tool` even when called by name). `--surface starter` exposes the
-~26-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
-verbs plus the daily brain-tool slice, the agent lane, `whoami`, and the
+~27-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
+verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and the
`request_tools` discovery meta-op (re-derivable from production usage via
`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full
(pinned by test) — starter extends the ladder ABOVE verbs and never changes
diff --git a/docs/tutorials/connect-coding-agent.md b/docs/tutorials/connect-coding-agent.md
index f6e09440ad..6a093f2f7f 100644
--- a/docs/tutorials/connect-coding-agent.md
+++ b/docs/tutorials/connect-coding-agent.md
@@ -161,7 +161,7 @@ That's the whole wire-up. No token, no URL, no tunnel. The agent spawns
[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md), frozen + additive-forever)
instead of the full operation catalog, so the agent sees a tight, stable surface
instead of a 110-tool wall. `--surface starter` sits between: the verbs plus the
-daily-driver set (~26 ops total). Drop the flag (or pass `--surface full`) for every
+daily-driver set (core page/search/graph ops + capture). Drop the flag (or pass `--surface full`) for every
operation. The default when the flag is omitted is `full`, so existing wire-ups
are unchanged.
@@ -244,7 +244,7 @@ habits to build. Your agent stops being amnesiac.
| Agent "can't reach the brain" (Path A) | `gbrain serve --http` bound to loopback | Restart with `--bind 0.0.0.0` |
| `list_skills` returns nothing / errors | Skill publishing OFF on the host | `gbrain config set mcp.publish_skills true` |
| Token rejected on first call | Wrong/expired token | Re-mint with `gbrain auth create`; `--install` smoke-tests it for you |
-| `unknown tool: capture` | `capture` is CLI-only, not an MCP tool | Use `put_page` over MCP; `capture` only on the CLI |
+| `unknown tool: capture` | Your surface predates v0.47 or your token's surface was narrowed | Upgrade the host (capture is on starter + full now); on narrowed tokens use `put_page`, or `remember` on the verbs surface |
| Empty results (Path B) | Brain has nothing in it yet | `gbrain import ~/notes/` or `gbrain capture "..."` |
## Next steps
diff --git a/llms-full.txt b/llms-full.txt
index 04f9dc45d0..37d9dfd175 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4144,7 +4144,7 @@ No server, no tunnel, no token needed. Works on both PGLite and Postgres engines
`--surface verbs` exposes exactly the seven-verb memory protocol (`recall`,
`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full catalog;
-`--surface starter` sits between (~26 ops: the verbs plus the daily-driver set);
+`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
omit the flag (default `full`) for every operation.
### Remote over OAuth 2.1 (recommended)
@@ -4571,8 +4571,8 @@ each client.
**Surface modes:** `--surface verbs` exposes EXACTLY the seven verbs —
advertised list AND dispatch are filtered fail-closed (a hidden op returns
`unknown_tool` even when called by name). `--surface starter` exposes the
-~26-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
-verbs plus the daily brain-tool slice, the agent lane, `whoami`, and the
+~27-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
+verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and the
`request_tools` discovery meta-op (re-derivable from production usage via
`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full
(pinned by test) — starter extends the ladder ABOVE verbs and never changes
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index ce6c07a276..c3b350f144 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.12.0",
+ "version": "0.46.12.2",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 902b6815cb..943709ce41 100644
--- a/package.json
+++ b/package.json
@@ -168,7 +168,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.12.0",
+ "version": "0.46.12.2",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index 983c571f13..59886a22ec 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.12.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.12.2 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
@@ -8,8 +8,9 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface starter` — the 26-op
-daily-driver surface (the seven memory verbs + daily brain ops). 21
+The plugin's MCP server runs `gbrain serve --surface starter` — the
+27-op daily-driver surface (the seven memory verbs + daily
+brain ops + capture). 21
bundled skills reference gbrain operations beyond that surface; every one of
them has a first-class `gbrain` CLI path, which is the primary way skills
drive gbrain. When a skill step names an operation your MCP tool list doesn't
diff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.md
index c9ee988969..008a49100c 100644
--- a/plugin/skills/minion-orchestrator/SKILL.md
+++ b/plugin/skills/minion-orchestrator/SKILL.md
@@ -174,8 +174,8 @@ get_job_progress ID
```
Check structured result fields (exit code, stdout/stderr tails, attempts,
-timings) from `get_job`. Use `gbrain jobs stats` (CLI) for worker/queue
-health dashboard.
+timings) from `get_job`. Use `get_job_stats` (MCP) or `gbrain jobs stats`
+(CLI) for the worker/queue health dashboard incl. the wedged-queue signal.
### Control (MCP-callable)
@@ -521,4 +521,5 @@ Total tokens so far: 4.3k
- Replay a completed/failed job — `replay_job` (MCP)
- Send sidechannel message — `send_job_message` (MCP)
- Get structured progress — `get_job_progress` (MCP)
-- Queue stats — `gbrain jobs stats` (CLI; no MCP equivalent)
+- Queue stats — `get_job_stats` (MCP; admin scope over HTTP, same as the other
+ jobs ops here — includes the wedged-queue silent-halt signal) or `gbrain jobs stats` (CLI)
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 32641f6905..9dd9d9d39c 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -36,6 +36,19 @@ const EXTRA_FLAGS: Record<string, string[]> = {
sync: ['--pace', '--pace-max-concurrency'],
};
+/**
+ * Modules the import scan must SKIP. thin-client-routing.ts is a pure router —
+ * its flag literals belong to the commands it routes (takes/search/jobs/cache/
+ * quarantine), and each of those declares its own flags in its own case block;
+ * scanning the router bleeds takes/quarantine flags into jobs (whose case
+ * block imports it for the `jobs stats` thin-client route).
+ */
+const EXCLUDED_MODULES = ['thin-client-routing.ts'];
+
+function isExcludedModule(p: string): boolean {
+ return EXCLUDED_MODULES.some(m => p.endsWith(`/${m}`));
+}
+
/** Universal helper flags every command may see (parsed or short-circuited upstream). */
const UNIVERSAL_FLAGS = ['--help', '--json', '--brain', '--source'];
@@ -59,7 +72,7 @@ function relativeImports(src: string, fromDir: string): string[] {
for (const m of src.matchAll(/import\('(\.\.?\/[^']+\.ts)'\)/g)) paths.add(m[1]);
return [...paths]
.map(p => resolvePath(fromDir, p))
- .filter(p => existsSync(p))
+ .filter(p => existsSync(p) && !isExcludedModule(p))
.flatMap(p => [p, ...facadeExpansion(p)]);
}
@@ -166,7 +179,7 @@ export function buildFlagRegistry(): Record<string, string[]> {
// own ./relative imports.
const commandModules = [...block.matchAll(/import\('(\.\/[^']+\.ts)'\)/g)]
.map(mm => resolvePath(join(ROOT, 'src'), mm[1]))
- .filter(p => existsSync(p));
+ .filter(p => existsSync(p) && !isExcludedModule(p));
for (const modPath of commandModules) {
// A command module that IS a peeled façade counts its module files as
// part of itself: their text scans at module depth and THEIR relative
diff --git a/scripts/generate-plugin-tree.ts b/scripts/generate-plugin-tree.ts
index c3c850b9d2..a6e86ec09a 100644
--- a/scripts/generate-plugin-tree.ts
+++ b/scripts/generate-plugin-tree.ts
@@ -179,8 +179,9 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs \`gbrain serve --surface starter\` — the 26-op
-daily-driver surface (the seven memory verbs + daily brain ops). ${gapSkills}
+The plugin's MCP server runs \`gbrain serve --surface starter\` — the
+${STARTER_OPS.size}-op daily-driver surface (the seven memory verbs + daily
+brain ops + capture). ${gapSkills}
bundled skills reference gbrain operations beyond that surface; every one of
them has a first-class \`gbrain\` CLI path, which is the primary way skills
drive gbrain. When a skill step names an operation your MCP tool list doesn't
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f7cad646ce..f78392b510 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -10,7 +10,7 @@ src/core/pglite-engine.ts 5660 ratchet peel target: containment sprint C15; grow
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 3364 ratchet watchlist
+src/cli.ts 3385 ratchet watchlist; +21 gap-closure wave: thin-client routing call sites (logic in commands/thin-client-routing.ts)
src/core/cycle.ts 2933 ratchet
src/commands/serve-http.ts 2836 ratchet
src/commands/jobs.ts 2950 ratchet grown v0.46.11.0 five-issue wave
diff --git a/skills/minion-orchestrator/SKILL.md b/skills/minion-orchestrator/SKILL.md
index c9ee988969..008a49100c 100644
--- a/skills/minion-orchestrator/SKILL.md
+++ b/skills/minion-orchestrator/SKILL.md
@@ -174,8 +174,8 @@ get_job_progress ID
```
Check structured result fields (exit code, stdout/stderr tails, attempts,
-timings) from `get_job`. Use `gbrain jobs stats` (CLI) for worker/queue
-health dashboard.
+timings) from `get_job`. Use `get_job_stats` (MCP) or `gbrain jobs stats`
+(CLI) for the worker/queue health dashboard incl. the wedged-queue signal.
### Control (MCP-callable)
@@ -521,4 +521,5 @@ Total tokens so far: 4.3k
- Replay a completed/failed job — `replay_job` (MCP)
- Send sidechannel message — `send_job_message` (MCP)
- Get structured progress — `get_job_progress` (MCP)
-- Queue stats — `gbrain jobs stats` (CLI; no MCP equivalent)
+- Queue stats — `get_job_stats` (MCP; admin scope over HTTP, same as the other
+ jobs ops here — includes the wedged-queue silent-halt signal) or `gbrain jobs stats` (CLI)
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index f34105fada..7d20b10f65 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -133,7 +133,7 @@
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
"migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb",
"migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",
- "minion-orchestrator/SKILL.md": "a0319963481eae87466871b423757d6a82561d241578304de55ed765cb970356",
+ "minion-orchestrator/SKILL.md": "0b6799dbe6bccc83984371545db0d1d6216d152578d035bb869471cca7ab9b69",
"minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992",
"perplexity-research/SKILL.md": "c25f5c471cbe3c6e0f975d8397e8382b00a85f8aa75302231d53c52855369e97",
"perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",
diff --git a/src/cli.ts b/src/cli.ts
index 7470d1ec46..d345fccc1c 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -65,6 +65,11 @@ export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'pglite-repair', 'upgr
// v0.42.58 (#2035 class, caught by the handleCliOnly reachability sweep):
// full handler at `case 'notability-eval'` but never dispatchable.
'notability-eval',
+ // #2035 class (wired the #3502 way): `case 'whoknows'` had a live handler
+ // (runWhoknows: ranked table, per-factor explain, thin-client routing) that
+ // was shadowed by find_experts' non-hidden cliHints. The op hint is now
+ // hidden (ops/insights.ts); this entry makes the richer handler dispatch.
+ 'whoknows',
// Agent-bootstrap family (ENG-2 three-touchpoint rule): `bootstrap` + `hook`
// are ENGINE-FREE (dispatched in handleCliOnly before the connectEngine
// terminator) and must NEVER enter THIN_CLIENT_REFUSED_COMMANDS. `sweep` is
@@ -75,6 +80,8 @@ export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'pglite-repair', 'upgr
// per-subcommand usage stays reachable.
const CLI_ONLY_SELF_HELP = new Set([
'upgrade', 'post-upgrade', 'check-update',
+ // whoknows honours --help first (runWhoknows HELP block, whoknows.ts).
+ 'whoknows',
// #3502 sweep: pages + bench print their own usage (pages.ts printHelp,
// bench-publish.ts printHelp). Both were documented but undispatchable —
// `pages` had a live handleCliOnly case but was missing from CLI_ONLY
@@ -397,6 +404,15 @@ async function main() {
if (command === 'search' && ['modes', 'stats', 'tune', 'diagnose'].includes(subArgs[0] ?? '')) {
const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
const isDiagnose = subArgs[0] === 'diagnose';
+ // Gap-closure wave [OV6]: thin clients route the read-only dashboard
+ // forms via search_modes/search_stats/search_tune instead of fabricating
+ // a scratch PGLite; --reset/--apply/diagnose fall through to the refusal.
+ const cfgSearch = loadConfig();
+ if (isThinClient(cfgSearch)) {
+ const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfgSearch!, 'search', subArgs)) return;
+ refuseThinClient('search', cfgSearch!.remote_mcp!.mcp_url);
+ }
const label = 'gbrain search';
// diagnose runs real retrieval (keyword + vector + hybrid) so it gets a
// longer deadline than the read-only dashboard.
@@ -1666,7 +1682,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
orphans: "orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",
transcripts: 'transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.',
storage: 'storage operates on the local repo on disk. Run on the host.',
- takes: 'takes mutate subcommands edit local .md files; routing the read subcommands lands in v0.31.x. For now: use `takes_list` and `takes_search` MCP tools from your agent, or run on the host.',
+ takes: 'takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.',
sources: 'sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.',
sweep: 'sweep runs the serve-resident maintenance passes against the LOCAL engine. Run it on the host (the serve process also runs it automatically).',
// v0.32 audit additions
@@ -1679,7 +1695,12 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
'code-callees': '`code-callees` has no MCP op yet. Run on the host.',
// scratch-DB audit additions
config: "config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set.",
- jobs: '`jobs list` and `jobs get <id>` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job MCP tools from your agent, or run on the host with GBRAIN_HOME set.',
+ jobs: '`jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.',
+ // Gap-closure wave [OV6]: routable subcommands are intercepted before this
+ // hint fires — these fire only for the host-bound remainder.
+ search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',
+ cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',
+ quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',
};
/**
@@ -1707,9 +1728,14 @@ async function handleCliOnly(command: string, args: string[]) {
// hint instead of letting them fail later inside connectEngine or
// mid-handler. v0.31.1 routes through `refuseThinClient` so every
// refusal carries an actionable next-step hint (CDX-5 cherry-pick A).
- if (THIN_CLIENT_REFUSED_COMMANDS.has(command)) {
+ // Gap-closure wave [OV6]: takes/cache/quarantine first try the
+ // per-subcommand MCP routing (engine-free); unhandled subcommands fall
+ // through to the refusal.
+ if (THIN_CLIENT_REFUSED_COMMANDS.has(command) || command === 'cache' || command === 'quarantine') {
const cfg = loadConfig();
if (isThinClient(cfg)) {
+ const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfg!, command, args)) return;
refuseThinClient(command, cfg!.remote_mcp!.mcp_url);
}
}
@@ -2375,6 +2401,11 @@ async function handleCliOnly(command: string, args: string[]) {
await runJobs(null, args);
return;
}
+ if (jobsSub === 'stats') {
+ // Gap-closure wave [OV6]: queue health routes via get_job_stats.
+ const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfgJobs!, 'jobs', args)) return;
+ }
refuseThinClient('jobs', cfgJobs!.remote_mcp!.mcp_url);
}
}
@@ -2728,12 +2759,6 @@ async function handleCliOnly(command: string, args: string[]) {
await runModels(engine, args);
break;
}
- case 'search': {
- // v0.32.3 search-lite — `gbrain search modes/stats/tune`.
- const { runSearch } = await import('./commands/search.ts');
- await runSearch(engine, args);
- break;
- }
case 'takes': {
const { runTakes } = await import('./commands/takes.ts');
await runTakes(engine, args);
@@ -3151,10 +3176,6 @@ export function printOpHelp(op: Operation, invokedName?: string) {
}
function printHelp() {
- // Gather shared operations grouped by category
- const cliNames = Array.from(cliOps.entries())
- .map(([name, op]) => ({ name, desc: op.description }));
-
console.log(`gbrain ${VERSION} -- personal knowledge brain
USAGE
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index b5ab2dd561..7cc7523ce1 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -16,9 +16,11 @@ import { VERSION } from '../version.ts';
import { loadConfig } from '../core/config.ts';
import { loadCompletedMigrations, appendCompletedMigration, type CompletedMigrationEntry } from '../core/preferences.ts';
import { migrations, compareVersions, type Migration, type OrchestratorOpts } from './migrations/index.ts';
-
-/** Bug 3 — max consecutive partials before we wedge a migration. */
-const MAX_CONSECUTIVE_PARTIALS = 3;
+import {
+ indexCompletedEntries,
+ statusForVersion as ledgerStatusForVersion,
+ MAX_CONSECUTIVE_PARTIALS,
+} from '../core/migration-ledger.ts';
interface ApplyMigrationsArgs {
list: boolean;
@@ -117,53 +119,18 @@ interface CompletedIndex {
byVersion: Map<string, CompletedMigrationEntry[]>;
}
+// Ledger status logic moved to src/core/migration-ledger.ts (shared with the
+// get_health op's migrations block, TODOS:4063) — same semantics, same Bug 3
+// "complete wins / trailing retry overrides / consecutive-partial cap" rules.
function indexCompleted(entries: CompletedMigrationEntry[]): CompletedIndex {
- const byVersion = new Map<string, CompletedMigrationEntry[]>();
- for (const e of entries) {
- const list = byVersion.get(e.version) ?? [];
- list.push(e);
- byVersion.set(e.version, list);
- }
- return byVersion.size > 0
- ? { byVersion }
- : { byVersion: new Map() };
+ return { byVersion: indexCompletedEntries(entries) };
}
-/**
- * Returns the resolved status for a migration based on its entries.
- *
- * Semantics (Bug 3 — keep "complete wins" safety):
- * - If the latest entry is `retry`, the version is pending. This is the
- * explicit escape hatch written by `--force-retry`, and it overrides an
- * earlier `complete` entry without hand-editing the ledger.
- * - Otherwise, if any entry is `complete`, the version is complete.
- * - Otherwise, if any entry is `partial`, the version is partial.
- * - Otherwise, pending.
- *
- * `complete` never regresses accidentally. A later `partial` append cannot
- * undo a completed migration; only a trailing, explicit `retry` marker can.
- */
function statusForVersion(
version: string,
idx: CompletedIndex,
): 'complete' | 'partial' | 'pending' | 'wedged' {
- const entries = idx.byVersion.get(version) ?? [];
- if (entries.length === 0) return 'pending';
- const latest = entries[entries.length - 1];
- if (latest.status === 'retry') return 'pending';
- if (entries.some(e => e.status === 'complete')) return 'complete';
- // Bug 3 attempt cap — count consecutive partials from the end (stopping
- // at any 'retry' or 'complete'). If we hit MAX_CONSECUTIVE_PARTIALS,
- // the migration is wedged and needs explicit --force-retry to try again.
- let consecutive = 0;
- for (let i = entries.length - 1; i >= 0; i--) {
- const e = entries[i];
- if (e.status === 'partial') consecutive++;
- else break;
- }
- if (consecutive >= MAX_CONSECUTIVE_PARTIALS) return 'wedged';
- if (entries.some(e => e.status === 'partial')) return 'partial';
- return 'pending';
+ return ledgerStatusForVersion(version, idx.byVersion);
}
interface Plan {
diff --git a/src/commands/capture.ts b/src/commands/capture.ts
index 86919f8b37..785db345aa 100644
--- a/src/commands/capture.ts
+++ b/src/commands/capture.ts
@@ -31,7 +31,6 @@
*/
import { readFileSync } from 'node:fs';
-import matter from 'gray-matter';
import type { BrainEngine } from '../core/engine.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
import { callRemoteTool, unpackToolResult, RemoteMcpError } from '../core/mcp-client.ts';
@@ -39,6 +38,18 @@ import { computeContentHash } from '../core/ingestion/types.ts';
import { operations } from '../core/operations.ts';
import type { OperationContext } from '../core/operations.ts';
import { resolveSourceWithTier } from '../core/source-resolver.ts';
+// Pure content helpers moved to core (shared with the capture MCP op — the
+// core module also breaks the capture.ts→operations.ts static import cycle).
+// Re-exported below so existing importers/tests keep their entry point.
+import {
+ defaultSlug,
+ detectBinaryNullByte,
+ normalizeForHash,
+ deriveTitle,
+ mergeCaptureFrontmatter,
+} from '../core/capture-content.ts';
+
+export { detectBinaryNullByte, normalizeForHash, mergeCaptureFrontmatter } from '../core/capture-content.ts';
interface RunOpts {
content?: string;
@@ -144,45 +155,6 @@ Examples:
JOB=$(gbrain capture "..." --quiet)
`;
-// v0.42.x — Life Chronicle (#2390): route the default slug prefix by type so
-// `gbrain capture --type diary` lands under life/diary/ and `--type event`
-// under life/events/ (matching the chronicle path-prefix inference). Everything
-// else keeps the inbox/ default.
-function slugPrefixForType(type?: string): string {
- if (type === 'diary') return 'life/diary';
- if (type === 'event') return 'life/events';
- return 'inbox';
-}
-function defaultSlug(content: string, now: Date = new Date(), type?: string): string {
- const y = now.getUTCFullYear();
- const m = String(now.getUTCMonth() + 1).padStart(2, '0');
- const d = String(now.getUTCDate()).padStart(2, '0');
- const hashPrefix = computeContentHash(content).slice(0, 8);
- return `${slugPrefixForType(type)}/${y}-${m}-${d}-${hashPrefix}`;
-}
-
-/**
- * v0.39.3.0 CV10 — binary file guard. Scans the first 8KB of `buf` for a
- * NUL byte (0x00). Real text files (including UTF-8 with multi-byte CJK,
- * emoji, BOM) never contain a NUL byte at any position — text encoding
- * uses non-zero continuation bytes. NUL appears in binary formats:
- * executables, archives, compressed images, PDFs (after the magic-byte
- * header), most office documents. Single-pass scan; constant memory.
- *
- * Returns the 0-indexed byte offset of the first NUL, or -1 if clean.
- * Caller decides the error shape (message vs JSON envelope).
- *
- * Known limit: a PNG-without-NUL-in-first-8KB slips through. v0.39
- * magic-byte allowlist (per CV10-B + TODOS.md) closes this hole. The
- * 8KB ceiling bounds the scan cost to ~microseconds even on huge files.
- */
-export function detectBinaryNullByte(buf: Buffer): number {
- const limit = Math.min(buf.length, 8 * 1024);
- for (let i = 0; i < limit; i++) {
- if (buf[i] === 0) return i;
- }
- return -1;
-}
async function readStdinBuffer(): Promise<Buffer> {
const chunks: Buffer[] = [];
@@ -192,20 +164,6 @@ async function readStdinBuffer(): Promise<Buffer> {
return Buffer.concat(chunks);
}
-/**
- * v0.39.3.0 CV9 — normalize content for content_hash so identical text
- * produces identical hashes regardless of leading/trailing whitespace,
- * line-ending style (CRLF vs LF), or Unicode normalization form. The
- * STORED body is preserved as-is (CRLF stays CRLF, BOM stays BOM).
- *
- * Two concerns, two transforms — the hash gets aggressive normalization
- * for dedup correctness; the stored body keeps user bytes for round-trip
- * fidelity. CQ2's CRLF/BOM preservation tests rely on this split.
- */
-export function normalizeForHash(s: string): string {
- // Strip BOM, normalize line endings to LF, trim, NFKC for Unicode-stable hash.
- return s.replace(/^/, '').replace(/\r\n/g, '\n').trim().normalize('NFKC');
-}
/**
* v0.39.3.0 A2 + CV6 — detect Postgres FK violation on the sources table
@@ -231,115 +189,6 @@ export function maybeRewriteSourceFkError(err: unknown, sourceId: string | undef
return `source '${sourceId}' is not registered. Register it first:\n gbrain sources add ${sourceId} --path <path>\n\nList registered sources:\n gbrain sources list`;
}
-/**
- * Derive a title from the first non-empty, non-`---` line of the body,
- * stripping leading markdown heading marks, capped at 80 chars. Truncation
- * is codepoint-aware (never splits an astral surrogate pair) and appends an
- * ellipsis so a cut title is visibly cut.
- * Falls back to 'Capture' when no usable line exists.
- */
-function deriveTitle(rawBody: string): string {
- const firstLine = rawBody
- .split('\n')
- .find((l) => l.trim().length > 0 && l.trim() !== '---') ?? '';
- const stripped = firstLine.replace(/^#+\s*/, '');
- const cps = [...stripped];
- return (cps.length > 80 ? cps.slice(0, 79).join('') + '…' : stripped) || 'Capture';
-}
-
-/**
- * v0.39.3.0 (BUG-1): merge capture's auto-stamped fields with any existing
- * frontmatter in `rawBody`, rather than always prepending a second
- * frontmatter block. The pre-fix code stamped its own `---` block on top
- * of files that already had frontmatter, producing `title: '---'` (the
- * file's opening delimiter became the outer title) and two consecutive
- * frontmatter blocks the parser interpreted as the outer block + a body
- * starting with a horizontal rule.
- *
- * Precedence rules (user-wins by default):
- * - `type`: opts.type (CLI flag) > userFm.type > 'note'
- * - `title`: userFm.title > derived-from-body
- * - `captured_via`: userFm.captured_via > opts.source > 'capture-cli'
- * (CV3/Phase 3c will narrow this to always 'capture-cli';
- * for Phase 2a we preserve current semantics)
- * - `captured_at`: userFm.captured_at > now (user can pre-stamp for retroactive
- * captures; see CQ2 test case 4)
- * - Any other user-declared keys (description, tags, slug, etc.) pass through verbatim.
- *
- * For files WITHOUT existing frontmatter, preserves the original behavior:
- * stamps a fresh frontmatter block, and if the body doesn't already look
- * like markdown (no `#` heading), wraps it under a `# {title}` heading.
- */
-// v0.42.x — Life Chronicle (#2390): assemble the `event:` frontmatter block
-// from the --who/--what/--where/--kind/--depth flags (only for --type event).
-// Returns undefined when no event flags are set so non-event captures are
-// untouched.
-function buildEventBlock(opts: RunOpts): Record<string, unknown> | undefined {
- if (opts.type !== 'event') return undefined;
- const who = opts.who ? opts.who.split(',').map((s) => s.trim()).filter(Boolean) : [];
- const block: Record<string, unknown> = {};
- if (opts.what) block.what = opts.what;
- if (who.length) block.who = who;
- if (opts.where) block.where = opts.where;
- if (opts.kind) block.kind = opts.kind;
- if (opts.depth) block.depth = opts.depth;
- return Object.keys(block).length ? block : undefined;
-}
-
-export function mergeCaptureFrontmatter(rawBody: string, opts: RunOpts): string {
- const nowIso = new Date().toISOString();
- // Detect frontmatter: leading `---\n` or `---\r\n`, tolerating leading BOM/whitespace.
- // We do NOT use the more permissive `startsWith('---')` because a body that opens
- // with a horizontal-rule like `--- separator ---` would false-positive.
- const trimmedStart = rawBody.replace(/^/, '');
- const hasFrontmatter = /^---\r?\n/.test(trimmedStart);
-
- if (!hasFrontmatter) {
- // No existing frontmatter: stamp a fresh block and (if body lacks markdown
- // structure) wrap under a derived heading.
- const title = deriveTitle(rawBody);
- const fm: Record<string, unknown> = {
- type: opts.type ?? 'note',
- title,
- captured_via: opts.source ?? 'capture-cli',
- captured_at: nowIso,
- };
- const ev = buildEventBlock(opts);
- if (ev) fm.event = ev;
- const looksMarkdown = /^#{1,6}\s/.test(rawBody.trimStart());
- const body = looksMarkdown ? rawBody : `# ${title}\n\n${rawBody}`;
- return matter.stringify(body, fm);
- }
-
- // Existing frontmatter: parse, merge user-wins, re-emit as a SINGLE block.
- let parsed: matter.GrayMatterFile<string>;
- try {
- parsed = matter(rawBody);
- } catch (e) {
- throw new Error(
- `malformed frontmatter in capture input: ${e instanceof Error ? e.message : String(e)}`,
- );
- }
- const userFm = (parsed.data ?? {}) as Record<string, unknown>;
- const merged: Record<string, unknown> = {
- // Spread user's declared keys first so 'description', 'tags', etc. pass through.
- ...userFm,
- // Then apply auto-fields with the precedence rules above. The explicit
- // assignment AFTER the spread is intentional: it lets us implement the
- // mixed precedence (CLI flag wins for `type`; user wins for `title`/
- // `captured_via`/`captured_at`) in one expression per key.
- type: opts.type ?? userFm.type ?? 'note',
- title: userFm.title ?? deriveTitle(parsed.content),
- captured_via: userFm.captured_via ?? opts.source ?? 'capture-cli',
- captured_at: userFm.captured_at ?? nowIso,
- };
- // v0.42.x — merge the event block (user-declared keys win per-key).
- const ev = buildEventBlock(opts);
- if (ev || userFm.event) {
- merged.event = { ...(ev ?? {}), ...((userFm.event as Record<string, unknown>) ?? {}) };
- }
- return matter.stringify(parsed.content, merged);
-}
/**
* Build the put_page content (frontmatter + body). The user's --type and
diff --git a/src/commands/connect.ts b/src/commands/connect.ts
index 0bdc49cbc7..762001c7ab 100644
--- a/src/commands/connect.ts
+++ b/src/commands/connect.ts
@@ -117,15 +117,17 @@ export const AGENT_SPECS: Record<AgentId, AgentSpec> = {
export const AGENT_IDS: AgentId[] = ['claude-code', 'codex', 'opencode', 'perplexity', 'generic'];
// The named tools MUST be real MCP-exposed ops (verified by the round-trip
-// E2E). `capture` is intentionally absent: it's a CLI-only convenience wrapper,
-// not an MCP tool — the agent writes over MCP with `put_page`.
+// E2E). `capture` earned its slot in the CLI→MCP gap-closure wave (D2A):
+// it is a starter-surface op now — prefer it for quick notes (auto-slug +
+// dedupe), `put_page` for full-control writes.
export const LEARN_INSTRUCTION =
'Once connected, call the `get_brain_identity` tool (whose brain this is), then ' +
'`list_skills` (everything it can do; if it errors, the host has not enabled skill ' +
'publishing — these core tools still work: search, query, get_page, put_page, ' +
- 'think, find_experts). Then call `list_brain_skillpack`: if this brain ships a ' +
- 'skillpack, ask the user whether to install it (gbrain skillpack scaffold <spec>). ' +
- 'Always search the brain before answering or writing.';
+ 'capture, think, find_experts). Then call `list_brain_skillpack`: if this brain ships ' +
+ 'a skillpack, ask the user whether to install it (gbrain skillpack scaffold <spec>). ' +
+ 'Prefer `capture` for quick notes (auto-slug + dedupe) and `put_page` for ' +
+ 'full-control writes. Always search the brain before answering or writing.';
const SECRET_NOTE =
'Note: that bearer token is a long-lived, full-access secret — keep it private and ' +
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 083ef23afd..aa1df69e69 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -4,7 +4,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
-import { MinionQueue } from '../core/minions/queue.ts';
+import { MinionQueue, deriveWedgeSignal } from '../core/minions/queue.ts';
import { MinionWorker } from '../core/minions/worker.ts';
import {
WORKER_EXIT_RSS_WATCHDOG,
@@ -1044,13 +1044,9 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
{
const w = stats.wedge;
const mins = w.minutes_since_completion;
- // Same threshold the doctor `wedged_queue` check uses, so the two
- // advisory surfaces agree (issue #1801).
- const wedgeMins = (() => {
- const raw = parseInt(process.env.GBRAIN_WEDGED_QUEUE_WARN_MINUTES ?? '', 10);
- return Number.isFinite(raw) && raw > 0 ? raw : 15;
- })();
- const wedged = w.active_healthy === 0 && w.waiting > 0 && (mins === null || mins > wedgeMins);
+ // Shared derivation (queue.ts deriveWedgeSignal) so this line, the
+ // doctor wedged_queue check, and the get_job_stats op agree (#1801).
+ const { wedged, wedge_threshold_minutes: wedgeMins } = deriveWedgeSignal(w);
if (wedged) {
const since = mins === null ? 'no completions on record' : `${mins}m since last completion`;
console.log(
diff --git a/src/commands/migrations/index.ts b/src/commands/migrations/index.ts
index 22597ed17b..6b6c7818b0 100644
--- a/src/commands/migrations/index.ts
+++ b/src/commands/migrations/index.ts
@@ -56,19 +56,7 @@ export function getMigration(version: string): Migration | null {
export type { Migration, FeaturePitch, OrchestratorOpts, OrchestratorResult } from './types.ts';
-/**
- * Compare two semver strings (MAJOR.MINOR.PATCH). Returns -1 / 0 / 1.
- * Extracted from src/commands/upgrade.ts#isNewerThan for shared use across
- * the migration runner + post-upgrade pitch path.
- */
-export function compareVersions(a: string, b: string): -1 | 0 | 1 {
- const va = a.split('.').map(n => parseInt(n, 10) || 0);
- const vb = b.split('.').map(n => parseInt(n, 10) || 0);
- for (let i = 0; i < 3; i++) {
- const da = va[i] ?? 0;
- const db = vb[i] ?? 0;
- if (da > db) return 1;
- if (da < db) return -1;
- }
- return 0;
-}
+// Canonical home moved to src/core/migration-ledger.ts (shared with the
+// get_health migrations block without pulling this registry into the ops
+// layer). Re-exported so every existing importer is unchanged.
+export { compareVersions } from '../../core/migration-ledger.ts';
diff --git a/src/commands/quarantine.ts b/src/commands/quarantine.ts
index 6410c918dd..43a92aa603 100644
--- a/src/commands/quarantine.ts
+++ b/src/commands/quarantine.ts
@@ -15,7 +15,7 @@ import { serializePageToMarkdown, serializeMarkdown } from '../core/markdown.ts'
import { importFromContent } from '../core/import-file.ts';
import type { PageType } from '../core/types.ts';
-interface QuarantineRow {
+export interface QuarantineRow {
slug: string;
source_id: string;
marker: 'quarantine' | 'content_flag';
@@ -23,7 +23,7 @@ interface QuarantineRow {
assessed_at: string;
}
-function rowFor(page: { slug: string; source_id?: string; frontmatter?: Record<string, unknown> | null }): QuarantineRow | null {
+export function rowFor(page: { slug: string; source_id?: string; frontmatter?: Record<string, unknown> | null }): QuarantineRow | null {
const fm = page.frontmatter ?? null;
if (isQuarantined(fm)) {
const m = (fm as Record<string, unknown>)[QUARANTINE_KEY] as Record<string, unknown>;
@@ -49,25 +49,93 @@ function rowFor(page: { slug: string; source_id?: string; frontmatter?: Record<s
return null;
}
-async function runList(engine: BrainEngine, args: string[]): Promise<void> {
- const json = args.includes('--json');
- const includeFlagged = args.includes('--include-flagged');
- // Paginate so a huge brain doesn't pull everything at once.
+// Bounds for the quarantine_list op's clamps (src/core/ops/admin.ts); the CLI
+// list stays unbounded. One canonical home so the op clamps and the param
+// descriptions can't drift apart silently.
+export const QUARANTINE_LIST_DEFAULT_LIMIT = 200;
+export const QUARANTINE_LIST_MAX_LIMIT = 1000;
+export const QUARANTINE_SCAN_DEFAULT = 20000;
+export const QUARANTINE_SCAN_MAX = 100000;
+
+export interface CollectQuarantineOpts {
+ includeFlagged?: boolean;
+ /** Max ROWS returned (op default 200, cap 1000). Undefined = unbounded (CLI). */
+ limit?: number;
+ /** Max PAGES scanned (op default 20000, cap 100000). Undefined = full scan (CLI). */
+ maxScan?: number;
+ /** Source scope (the op threads sourceScopeOpts; the CLI scans unscoped). */
+ sourceId?: string;
+ sourceIds?: string[];
+}
+
+export interface CollectQuarantineResult {
+ rows: QuarantineRow[];
+ scanned: number;
+ /** True when a bound stopped the scan — `rows.length` is a LOWER BOUND. */
+ truncated: boolean;
+}
+
+/**
+ * Shared frontmatter scan behind `gbrain quarantine list` and the
+ * quarantine_list op. Scan order is pinned to listPages' default
+ * `updated_desc` (most recently updated pages first), so a bounded scan sees
+ * the newest markers before older ones [OV13].
+ *
+ * [P2-6] Offset pagination over `updated_desc` is NOT a total order:
+ * `PAGE_SORT_SQL.updated_desc` is `p.updated_at DESC` with no unique
+ * tiebreaker (src/core/types.ts). A cluster of pages sharing an identical
+ * `updated_at` (bulk syncs stamp one now() across a transaction) that
+ * straddles a 1000-row batch boundary can have a row skipped or duplicated
+ * across batches. We accept this rather than switch sorts because the only
+ * tiebreaker'd enum option (`updated_asc`, `p.updated_at ASC, p.slug ASC`)
+ * reverses the [OV13] direction — a truncated scan (bounded by max_scan /
+ * limit) would then surface the OLDEST markers and MISS recent ones, a worse
+ * triage failure on large brains, and its slug tiebreaker is only a total
+ * order for a single-source scan anyway (the op can scope federated
+ * multi-source and the CLI scans unscoped, where slug is not unique). The
+ * exposure is bounded: the op caps the scan at max_scan, and only exact
+ * same-timestamp clusters landing on a batch boundary are affected. The full
+ * fix is a globally-unique page_id tiebreaker in PAGE_SORT_SQL (out of scope
+ * here — a filed follow-up), not a SELECT-projection pushdown.
+ */
+export async function collectQuarantineRows(
+ engine: BrainEngine,
+ opts: CollectQuarantineOpts = {},
+): Promise<CollectQuarantineResult> {
const rows: QuarantineRow[] = [];
const PAGE = 1000;
let offset = 0;
- for (;;) {
- const pages = await engine.listPages({ limit: PAGE, offset });
+ let scanned = 0;
+ let truncated = false;
+ outer: for (;;) {
+ const pages = await engine.listPages({
+ limit: PAGE,
+ offset,
+ sort: 'updated_desc',
+ ...(opts.sourceIds && opts.sourceIds.length > 0
+ ? { sourceIds: opts.sourceIds }
+ : opts.sourceId ? { sourceId: opts.sourceId } : {}),
+ });
if (pages.length === 0) break;
for (const p of pages) {
+ if (opts.maxScan !== undefined && scanned >= opts.maxScan) { truncated = true; break outer; }
+ scanned += 1;
const r = rowFor(p);
if (!r) continue;
- if (r.marker === 'content_flag' && !includeFlagged) continue;
+ if (r.marker === 'content_flag' && !opts.includeFlagged) continue;
rows.push(r);
+ if (opts.limit !== undefined && rows.length >= opts.limit) { truncated = true; break outer; }
}
if (pages.length < PAGE) break;
offset += PAGE;
}
+ return { rows, scanned, truncated };
+}
+
+async function runList(engine: BrainEngine, args: string[]): Promise<void> {
+ const json = args.includes('--json');
+ const includeFlagged = args.includes('--include-flagged');
+ const { rows } = await collectQuarantineRows(engine, { includeFlagged });
if (json) {
console.log(JSON.stringify({ schema_version: 1, count: rows.length, rows }, null, 2));
diff --git a/src/commands/search.ts b/src/commands/search.ts
index e96717d318..a1aea1b92e 100644
--- a/src/commands/search.ts
+++ b/src/commands/search.ts
@@ -22,114 +22,37 @@
* Recommendation engine. Reads stats + brain size + model tier and
* prints structured recommendations. --apply mutates config (each
* change logged loud + paste-ready revert command at the end).
+ *
+ * The report builders live in core (src/core/search/modes-report.ts,
+ * tune-recommendations.ts, telemetry.ts) and are shared with the
+ * search_modes / search_stats / search_tune MCP ops. This file owns arg
+ * parsing, text rendering, the --reset lane, and the --apply lane
+ * (config mutation stays CLI-only per [CDX-21]).
*/
import type { BrainEngine } from '../core/engine.ts';
import {
- MODE_BUNDLES,
SEARCH_MODES,
SEARCH_MODE_KEY,
- SEARCH_MODE_CONFIG_KEYS,
- DEFAULT_SEARCH_MODE,
isSearchMode,
- loadSearchModeConfig,
- resolveSearchMode,
- attributeKnob,
- type SearchMode,
- type ModeBundle,
} from '../core/search/mode.ts';
-import { readSearchStats, telemetryCoverage, TELEMETRY_COVERAGE_CAVEAT } from '../core/search/telemetry.ts';
-
-const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {
- cache_enabled: 'Semantic query cache on/off',
- cache_similarity_threshold: 'Cosine-similarity floor for cache hits (0..1)',
- cache_ttl_seconds: 'Per-row cache TTL',
- intentWeighting: 'Zero-LLM intent classifier weight adjustments',
- tokenBudget: 'Per-call token-budget cap (undefined = no cap)',
- expansion: 'LLM multi-query expansion (Haiku call per search)',
- searchLimit: 'Default `limit` for the operation layer',
- reranker_enabled: 'Cross-encoder reranker on/off',
- reranker_model: 'Provider:model for the reranker',
- reranker_top_n_in: 'Candidates sent to reranker per call',
- reranker_top_n_out: 'Cap on reranked output (null = no truncate)',
- reranker_timeout_ms: 'HTTP timeout for the reranker call',
- floor_ratio: 'Floor-ratio gate for metadata boosts (0..1, undefined = off)',
- title_boost: 'Title-phrase boost multiplier (query is a title token-run; 1.0 = off)',
- // v0.36 cross-modal knobs (D3 registry)
- cross_modal_both_text_weight: "D6 'both'-mode RRF weight for text branch (0.6 default)",
- cross_modal_both_image_weight: "D6 'both'-mode RRF weight for image branch (0.4 default)",
- image_query_text_refinement_weight: 'D13 searchByImage text-refinement RRF weight (0.4 default)',
- image_query_image_refinement_weight: 'D13 searchByImage image branch RRF weight (0.6 default)',
- unified_multimodal: 'Phase 3 — route all queries through embedding_multimodal column',
- unified_multimodal_only: 'Phase 3 strict — bypass dual-column fallback when unified is on',
- cross_modal_llm_intent: 'Commit 4 — Haiku tie-break for ambiguous modality classification',
- // v0.40.4 graph signals
- graph_signals: 'Selective graph signals: adjacency hub + cross-source hub + session diversification',
- // v0.40.3.0 contextual retrieval
- contextual_retrieval: 'CR tier (none|title|per_chunk_synopsis) — wraps chunks at embed time',
- contextual_retrieval_disabled: 'Soft kill switch — neutralizes CR wrapping for queries + new embeds',
- // v0.42.3.0 autocut
- autocut: 'Score-discontinuity result-sizing (cuts at the rerank-score cliff; no-op without a reranker)',
- autocut_jump: 'Autocut sensitivity: min normalized score gap that counts as a cliff (0..1, 0.20 default)',
- // v0.43 relational recall
- relationalRetrieval: 'Typed-edge relational recall arm (relational queries walk the graph; no-op otherwise)',
- relational_retrieval_depth: 'Max hops for relational traversal (1..3, 2 default)',
-};
-
-interface SearchModesReport {
- schema_version: 2;
- active_mode: SearchMode;
- active_mode_valid: boolean;
- resolved: Record<keyof ModeBundle, { value: unknown; source: string; source_detail: string; description: string }>;
- bundles: Record<SearchMode, ModeBundle>;
- config_keys: ReadonlyArray<string>;
- _meta?: {
- metric_glossary?: Record<string, string>;
- };
-}
-
-async function buildModesReport(engine: BrainEngine): Promise<SearchModesReport> {
- const input = await loadSearchModeConfig(engine);
- const resolved = resolveSearchMode(input);
-
- const knobs: Array<keyof ModeBundle> = [
- 'cache_enabled',
- 'cache_similarity_threshold',
- 'cache_ttl_seconds',
- 'intentWeighting',
- 'tokenBudget',
- 'expansion',
- 'searchLimit',
- // v0.35.6.0 — floor-ratio surfaced in `gbrain search modes` dashboard
- // so config drift is legible. Default undefined renders as 'undefined'
- // in the bundle column, 'mode' source when unset by config/per-call.
- 'floor_ratio',
- ];
-
- const attributions = {} as SearchModesReport['resolved'];
- for (const k of knobs) {
- const a = attributeKnob(k, input, resolved);
- attributions[k] = {
- value: a.value,
- source: a.source,
- source_detail: a.source_detail,
- description: KNOB_DESCRIPTIONS[k],
- };
- }
-
- return {
- schema_version: 2,
- active_mode: resolved.resolved_mode,
- active_mode_valid: resolved.mode_valid,
- resolved: attributions,
- bundles: {
- conservative: { ...MODE_BUNDLES.conservative },
- balanced: { ...MODE_BUNDLES.balanced },
- tokenmax: { ...MODE_BUNDLES.tokenmax },
- },
- config_keys: SEARCH_MODE_CONFIG_KEYS,
- };
-}
+import {
+ readSearchStats,
+ readGraphSignalsStats,
+ telemetryCoverage,
+ TELEMETRY_COVERAGE_CAVEAT,
+ type GraphSignalsStatsSection,
+} from '../core/search/telemetry.ts';
+import {
+ buildModesReport,
+ KNOB_DESCRIPTIONS,
+ type SearchModesReport,
+} from '../core/search/modes-report.ts';
+import {
+ buildTuneRecommendations,
+ TUNE_MIN_CALLS,
+ type TuneRecommendation,
+} from '../core/search/tune-recommendations.ts';
function formatModesText(report: SearchModesReport): string {
const lines: string[] = [];
@@ -210,15 +133,8 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<
const stats = await readSearchStats(engine, { days: Number.isFinite(days) ? days : 7 });
- // v0.40.4 — graph_signals section. Sourced from:
- // 1. config: search.graph_signals (or mode bundle default) for the
- // on/off status.
- // 2. JSONL audit: graph-signals-failures-*.jsonl for the error count.
- //
- // Fire-rate metrics (adjacency_fires, cross_source_fires,
- // session_demotions) require telemetry table writes from the
- // applyGraphSignals onMeta callback — wired in a v0.41+ follow-up
- // (T-todo-2 calibration wave). For now: status + error count.
+ // v0.40.4 — graph_signals section (readGraphSignalsStats now lives in
+ // core/search/telemetry.ts, shared with the search_stats op).
const gsSection = await readGraphSignalsStats(engine, Number.isFinite(days) ? days : 7);
if (json) {
@@ -291,57 +207,6 @@ async function runStatsSubcommand(engine: BrainEngine, args: string[]): Promise<
printGraphSignalsSection(gsSection);
}
-interface GraphSignalsStatsSection {
- enabled: boolean;
- source: 'config' | 'mode_default';
- failures_count: number;
- /** Failure-reason breakdown across the window (truncated to top reasons). */
- failures_by_reason: Record<string, number>;
-}
-
-async function readGraphSignalsStats(engine: BrainEngine, days: number): Promise<GraphSignalsStatsSection> {
- // Resolve graph_signals on/off. Mirrors the resolution chain in
- // src/commands/doctor/checks/graph-embedding.ts:checkGraphSignalsCoverage.
- // v0.40.4 codex F1: case-insensitive + trim parity with
- // loadOverridesFromConfig (mode.ts). Without this, search-stats would
- // silently report the opposite of what the parser actually enables on
- // values like 'TRUE' or 'True'.
- const cfg = await engine.getConfig('search.graph_signals').catch(() => null);
- let enabled: boolean;
- let source: 'config' | 'mode_default';
- if (cfg !== null && cfg !== undefined) {
- const v = cfg.trim().toLowerCase();
- enabled = v === 'true' || v === '1';
- source = 'config';
- } else {
- const modeRaw = await engine.getConfig('search.mode').catch(() => null);
- const modeVal = typeof modeRaw === 'string' ? modeRaw.trim().toLowerCase() : '';
- const mode = modeVal === 'conservative' || modeVal === 'tokenmax' ? modeVal : 'balanced';
- enabled = mode !== 'conservative';
- source = 'mode_default';
- }
-
- let failures_count = 0;
- const failures_by_reason: Record<string, number> = {};
- try {
- const { readRecentGraphSignalsFailures } = await import('../core/search/graph-signals.ts');
- const events = readRecentGraphSignalsFailures(days);
- failures_count = events.length;
- // The failure event schema has error_summary (not a reason field) —
- // bucket by the first word of the summary so operators see e.g.
- // "ECONNREFUSED" / "timeout" / "permission" at a glance.
- for (const e of events) {
- const firstWord = (e.error_summary ?? '').split(/[\s:]+/)[0]?.slice(0, 32) || 'unknown';
- failures_by_reason[firstWord] = (failures_by_reason[firstWord] ?? 0) + 1;
- }
- } catch {
- // Audit reader is best-effort. Missing module / corrupt files →
- // count stays 0, search-stats still renders.
- }
-
- return { enabled, source, failures_count, failures_by_reason };
-}
-
function printGraphSignalsSection(gs: GraphSignalsStatsSection): void {
console.log(' Graph signals:');
const sourceLabel = gs.source === 'config' ? 'config override' : 'mode default';
@@ -362,100 +227,41 @@ function printGraphSignalsSection(gs: GraphSignalsStatsSection): void {
}
}
-interface TuneRecommendation {
- knob: string;
- current: unknown;
- suggested: unknown;
- reason: string;
- apply_command: string;
-}
-
async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<void> {
const json = args.includes('--json');
const apply = args.includes('--apply');
- const modeInput = await loadSearchModeConfig(engine);
- const resolved = resolveSearchMode(modeInput);
- const stats = await readSearchStats(engine, { days: 7 });
-
- const recs: TuneRecommendation[] = [];
+ const report = await buildTuneRecommendations(engine);
+ const recs = report.recommendations;
- // Recommendation 1: low call volume → no data yet.
- if (stats.total_calls < 20) {
+ // Recommendation gate: low call volume → no data yet.
+ if (report.status === 'insufficient_data') {
if (json) {
console.log(JSON.stringify({
schema_version: 2,
status: 'insufficient_data',
- total_calls: stats.total_calls,
- coverage: telemetryCoverage(),
+ total_calls: report.total_calls,
+ coverage: report.coverage,
recommendations: [],
message: 'Not enough search activity in the last 7 days to tune. Run `gbrain search stats` after some real usage.',
}, null, 2));
return;
}
console.log('Not enough search activity in the last 7 days to tune.');
- console.log(`Total searches: ${stats.total_calls} (need >= 20 for confident recommendations).`);
+ console.log(`Total searches: ${report.total_calls} (need >= ${TUNE_MIN_CALLS} for confident recommendations).`);
console.log(`(${TELEMETRY_COVERAGE_CAVEAT} Low counts can reflect this gap, not just low usage.)`);
console.log('Use `gbrain serve` or an MCP session for a while, then re-run `gbrain search tune`.');
return;
}
- // Recommendation 2: budget pressure under conservative.
- if (resolved.resolved_mode === 'conservative' && stats.total_calls > 0) {
- const dropPctPerCall = stats.total_budget_dropped / stats.total_calls;
- if (dropPctPerCall > 2) {
- recs.push({
- knob: 'search.mode',
- current: 'conservative',
- suggested: 'balanced',
- reason: `Avg ${dropPctPerCall.toFixed(1)} results dropped per search by the 4K budget. Consider balanced (12K budget) or raise search.tokenBudget.`,
- apply_command: 'gbrain config set search.mode balanced',
- });
- }
- }
-
- // Recommendation 3: high cache hit rate → bump similarity threshold.
- if (stats.cache_hit_rate > 0.85 && stats.cache_hits + stats.cache_misses > 50) {
- recs.push({
- knob: 'search.cache.similarity_threshold',
- current: resolved.cache_similarity_threshold,
- suggested: 0.94,
- reason: `Cache hit rate is ${(stats.cache_hit_rate * 100).toFixed(1)}%. You can raise similarity threshold to 0.94 for tighter freshness at small recall cost.`,
- apply_command: 'gbrain config set search.cache.similarity_threshold 0.94',
- });
- }
-
- // Recommendation 4: tokenmax + Haiku subagent.
- const subagentModel = await engine.getConfig('models.tier.subagent');
- if (resolved.resolved_mode === 'tokenmax' && subagentModel && /haiku/i.test(subagentModel)) {
- recs.push({
- knob: 'search.mode',
- current: 'tokenmax',
- suggested: 'balanced',
- reason: `Subagent tier is Haiku but mode is tokenmax. LLM expansion adds ~50ms + ~1¢ per query. Balanced cuts that cost without losing intent weighting or cache.`,
- apply_command: 'gbrain config set search.mode balanced',
- });
- }
-
- // Recommendation 5: cache disabled but available — fix the free win.
- if (!resolved.cache_enabled && stats.total_calls > 5) {
- recs.push({
- knob: 'search.cache.enabled',
- current: false,
- suggested: true,
- reason: 'Cache is disabled but mode bundles enable it by default. Cache is a free win (zero LLM cost, big latency drop on repeat queries).',
- apply_command: 'gbrain config unset search.cache.enabled',
- });
- }
-
if (json) {
console.log(JSON.stringify({
schema_version: 2,
- status: recs.length === 0 ? 'no_recommendations' : 'has_recommendations',
- total_calls: stats.total_calls,
- cache_hit_rate: stats.cache_hit_rate,
- active_mode: resolved.resolved_mode,
- coverage: telemetryCoverage(),
+ status: report.status,
+ total_calls: report.total_calls,
+ cache_hit_rate: report.cache_hit_rate,
+ active_mode: report.active_mode,
+ coverage: report.coverage,
recommendations: recs,
applied: apply ? recs.map(r => r.apply_command) : [],
_meta: {
@@ -473,7 +279,7 @@ async function runTuneSubcommand(engine: BrainEngine, args: string[]): Promise<v
return;
}
- console.log(`Search tune (last 7 days, active mode: ${resolved.resolved_mode}):`);
+ console.log(`Search tune (last 7 days, active mode: ${report.active_mode}):`);
console.log(`(${TELEMETRY_COVERAGE_CAVEAT})`);
console.log('');
@@ -572,20 +378,9 @@ export async function runSearch(engine: BrainEngine, args: string[]): Promise<vo
}
}
-/**
- * `gbrain search modes` is read-only — no DB connection strictly required
- * for the bundle display IF the engine is given. The dispatch in cli.ts
- * adds 'search' to its dispatch table so the engine connects normally;
- * this export is here so future no-engine modes (e.g. `gbrain search --help`
- * without an engine) could route through it cleanly.
- */
export const _exports_for_test = {
buildModesReport,
formatModesText,
maybeApplyRecommendation,
buildRevertCommand,
};
-
-// Suppress unused-export TS warning — these are intentionally retained for
-// downstream callers (cli.ts dispatch / future skill linkage).
-void DEFAULT_SEARCH_MODE;
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index db18a975e0..d2b9d759eb 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -10,25 +10,21 @@
* takes supersede <slug> --row N ... — strikethrough old + append new
* takes resolve <slug> --row N --outcome true|false [--value N --unit u]
*
- * Markdown is canonical. Every mutate command:
- * 1. acquires the per-page file lock
- * 2. re-reads the .md file
- * 3. applies the edit via takes-fence (upsertTakeRow / supersedeRow)
- * 4. writes the .md file back
- * 5. mirrors to the DB via the engine method
- * 6. releases the lock (auto via withPageLock)
+ * Markdown is canonical. Every mutate command routes through the shared
+ * write-through core (src/core/takes-write.ts — also the takes_* MCP ops'
+ * backend): lock → resolve page → fence edit → write .md → DB mirror. This
+ * file owns arg parsing + rendering + exit codes only.
*/
-import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
-import { join, dirname } from 'node:path';
+import { existsSync } from 'node:fs';
import type { BrainEngine, TakeKind } from '../core/engine.ts';
import {
- parseTakesFence,
- upsertTakeRow,
- supersedeRow,
- type ParsedTake,
-} from '../core/takes-fence.ts';
-import { withPageLock } from '../core/page-lock.ts';
+ addTakeToPage,
+ updateTakeOnPage,
+ supersedeTakeOnPage,
+ resolveTakeOnPage,
+ TakesWriteError,
+} from '../core/takes-write.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
@@ -60,8 +56,22 @@ async function resolveBrainDir(engine: BrainEngine | null, explicitDir: string |
process.exit(1);
}
-function pageFilePath(brainDir: string, slug: string): string {
- return join(brainDir, `${slug}.md`);
+/**
+ * Map a TakesWriteError to the historical CLI error surface (stderr + exit 1).
+ * Message text preserves the pre-extraction wording users and scripts saw.
+ */
+function exitTakesError(err: unknown): never {
+ if (err instanceof TakesWriteError) {
+ switch (err.code) {
+ case 'page_not_found':
+ console.error(`${err.message} Run \`gbrain sync\` first.`);
+ process.exit(1);
+ default:
+ console.error(err.hint && err.code !== 'holder_denied' ? `${err.message} ${err.hint}` : err.message);
+ process.exit(1);
+ }
+ }
+ throw err;
}
function ensureKind(raw: string | undefined): TakeKind {
@@ -86,23 +96,6 @@ function ensureFloat(raw: string | undefined, fallback: number): number {
return n;
}
-async function getPageId(engine: BrainEngine, slug: string, sourceId?: string): Promise<number> {
- const rows = sourceId
- ? await engine.executeRaw<{ id: number }>(
- `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 LIMIT 1`,
- [slug, sourceId],
- )
- : await engine.executeRaw<{ id: number }>(
- `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,
- [slug],
- );
- if (!rows[0]) {
- console.error(`Page not found in brain: ${slug}${sourceId ? ` (source=${sourceId})` : ''}. Run \`gbrain sync\` first.`);
- process.exit(1);
- }
- return rows[0].id;
-}
-
// Fail-closed (#2698 residual, TODOS.md): `resolveSourceId` only ever
// throws when a source WAS explicitly in play — an invalid or
// unregistered `GBRAIN_SOURCE`, a `.gbrain-source` dotfile pointing at a
@@ -117,16 +110,6 @@ async function resolveTakesSourceId(engine: BrainEngine): Promise<string> {
return resolveSourceId(engine, null);
}
-function readBodyOrEmpty(path: string): string {
- if (!existsSync(path)) return '';
- return readFileSync(path, 'utf-8');
-}
-
-function writeBody(path: string, body: string): void {
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, body, 'utf-8');
-}
-
// --- Subcommands ---
async function cmdList(engine: BrainEngine, args: string[]): Promise<void> {
@@ -209,27 +192,15 @@ async function cmdAdd(engine: BrainEngine, args: string[], sourceId?: string): P
const dirArg = flagValue(args, '--dir');
const brainDir = await resolveBrainDir(engine, dirArg ?? null);
- await withPageLock(slug, async () => {
- // Resolve the page BEFORE touching the markdown. getPageId exits 1 when the
- // page isn't in the brain; doing this after writeBody left a .md file
- // carrying a take with no DB row — invisible to scorecard/calibration but
- // present on disk, so a later `takes add` would number the next row past a
- // take the DB never saw. update/supersede/resolve already resolve first.
- const pageId = await getPageId(engine, slug, sourceId);
-
- const path = pageFilePath(brainDir, slug);
- const body = readBodyOrEmpty(path);
- const { body: nextBody, rowNum } = upsertTakeRow(body, {
- claim, kind, holder, weight, source, sinceDate: since, active: true,
- });
- writeBody(path, nextBody);
-
- await engine.addTakesBatch([{
- page_id: pageId, row_num: rowNum, claim, kind, holder, weight,
- since_date: since, source, active: true, superseded_by: null,
- }]);
+ try {
+ const { rowNum } = await addTakeToPage(
+ { engine, slug, brainDir, sourceId },
+ { claim, kind, holder, weight, source, sinceDate: since },
+ );
console.log(`Added take #${rowNum} to ${slug}.`);
- });
+ } catch (err) {
+ exitTakesError(err);
+ }
}
async function cmdUpdate(engine: BrainEngine, args: string[], sourceId?: string): Promise<void> {
@@ -250,36 +221,20 @@ async function cmdUpdate(engine: BrainEngine, args: string[], sourceId?: string)
const dirArg = flagValue(args, '--dir');
const brainDir = await resolveBrainDir(engine, dirArg ?? null);
- await withPageLock(slug, async () => {
- const pageId = await getPageId(engine, slug, sourceId);
- await engine.updateTake(pageId, rowNum, fields);
-
- // Sync the markdown table: read fence, find row, apply field updates, re-render.
- const path = pageFilePath(brainDir, slug);
- const body = readBodyOrEmpty(path);
- const parsed = parseTakesFence(body);
- const target = parsed.takes.find(t => t.rowNum === rowNum);
- if (!target) {
- console.warn(`[takes update] DB updated but row #${rowNum} not in markdown fence on disk; markdown may be out of sync. Run 'gbrain extract takes --slugs ${slug}' to reconcile.`);
- return;
- }
- const updated: ParsedTake = {
- ...target,
- weight: fields.weight ?? target.weight,
- source: fields.source ?? target.source,
- sinceDate: fields.since_date ?? target.sinceDate,
- };
- // Replace the row in-place by stripping the fence and re-rendering all rows.
- const allRows = parsed.takes.map(t => t.rowNum === rowNum ? updated : t);
- // Round-trip via upsertTakeRow with no new row: easiest is to render manually.
- const { renderTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } = await import('../core/takes-fence.ts');
- const newFence = renderTakesFence(allRows);
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
- const out = body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
- writeBody(path, out);
+ // v0.46.x (EV1): markdown is canonical, so a row missing from the on-disk
+ // fence now REFUSES the whole write instead of the old DB-update-then-warn
+ // path — that path was self-defeating (its own reconcile hint, extract
+ // takes, would clobber the DB-only update it had just written).
+ try {
+ await updateTakeOnPage(
+ { engine, slug, brainDir, sourceId },
+ rowNum,
+ { weight: fields.weight, source: fields.source, sinceDate: fields.since_date },
+ );
console.log(`Updated take #${rowNum} on ${slug}.`);
- });
+ } catch (err) {
+ exitTakesError(err);
+ }
}
async function cmdSupersede(engine: BrainEngine, args: string[], sourceId?: string): Promise<void> {
@@ -295,39 +250,29 @@ async function cmdSupersede(engine: BrainEngine, args: string[], sourceId?: stri
const dirArg = flagValue(args, '--dir');
const brainDir = await resolveBrainDir(engine, dirArg ?? null);
- await withPageLock(slug, async () => {
- const pageId = await getPageId(engine, slug, sourceId);
-
- // Read existing row to inherit kind/holder unless overridden
- const existing = await engine.listTakes({ page_id: pageId, active: true, limit: 500 });
- const target = existing.find(t => t.row_num === rowNum);
- if (!target) {
- console.error(`Row #${rowNum} not found on ${slug}.`);
- process.exit(1);
- }
- const kind = ensureKind(flagValue(args, '--kind') ?? target.kind);
- const holder = flagValue(args, '--who') ?? target.holder;
- const weight = ensureFloat(flagValue(args, '--weight'), Math.max(0, target.weight - 0.1));
- const source = flagValue(args, '--source');
- const since = flagValue(args, '--since');
-
- const dbResult = await engine.supersedeTake(pageId, rowNum, {
- claim, kind, holder, weight, source, since_date: since, active: true,
- });
-
- // Mirror in markdown
- const path = pageFilePath(brainDir, slug);
- const body = readBodyOrEmpty(path);
- if (parseTakesFence(body).takes.find(t => t.rowNum === rowNum)) {
- const { body: nextBody } = supersedeRow(body, rowNum, {
- claim, kind, holder, weight, source, sinceDate: since,
- });
- writeBody(path, nextBody);
- } else {
- console.warn(`[takes supersede] DB updated but markdown lacks row #${rowNum}; only DB written.`);
- }
- console.log(`Superseded #${dbResult.oldRow} → new #${dbResult.newRow} on ${slug}.`);
- });
+ // v0.46.x (EV1): fence-first — kind/holder inherit from the MARKDOWN row
+ // (canonical), the fence assigns the new row number, and a row absent from
+ // the on-disk fence refuses instead of the old DB-only write.
+ const kindArg = flagValue(args, '--kind');
+ try {
+ const result = await supersedeTakeOnPage(
+ { engine, slug, brainDir, sourceId },
+ rowNum,
+ {
+ claim,
+ kind: kindArg !== undefined ? ensureKind(kindArg) : undefined,
+ holder: flagValue(args, '--who'),
+ weight: flagValue(args, '--weight') !== undefined
+ ? ensureFloat(flagValue(args, '--weight'), 0.5)
+ : undefined,
+ source: flagValue(args, '--source'),
+ sinceDate: flagValue(args, '--since'),
+ },
+ );
+ console.log(`Superseded #${result.oldRow} → new #${result.newRow} on ${slug}.`);
+ } catch (err) {
+ exitTakesError(err);
+ }
}
async function cmdResolve(engine: BrainEngine, args: string[], sourceId?: string): Promise<void> {
@@ -374,61 +319,24 @@ async function cmdResolve(engine: BrainEngine, args: string[], sourceId?: string
const source = flagValue(args, '--evidence') ?? flagValue(args, '--source');
const resolvedBy = flagValue(args, '--by') ?? resolveOwnerHolder({ configValue: await engine.getConfig('emotional_weight.user_holder') });
const dirArg = flagValue(args, '--dir');
-
- const pageId = await getPageId(engine, slug, sourceId);
- await engine.resolveTake(pageId, rowNum, {
- quality,
- outcome,
- value,
- unit,
- source,
- resolvedBy,
- });
-
- // Mirror resolution into the markdown fence so the page is self-describing.
- // The renderer conditionally widens the table to 13 columns when at least one
- // row has resolution data; pages with no resolved rows keep the 7-col shape.
- // Round-trip via parseTakesFence + renderTakesFence preserves all rows.
const brainDir = await resolveBrainDir(engine, dirArg ?? null);
- await withPageLock(slug, async () => {
- const path = pageFilePath(brainDir, slug);
- const body = readBodyOrEmpty(path);
- if (!body) {
- console.warn(`[takes resolve] markdown file not found at ${path}; DB updated but on-disk page absent.`);
- return;
- }
- const { parseTakesFence, renderTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } = await import('../core/takes-fence.ts');
- const parsed = parseTakesFence(body);
- const target = parsed.takes.find(t => t.rowNum === rowNum);
- if (!target) {
- console.warn(`[takes resolve] DB updated but row #${rowNum} not in markdown fence; run 'gbrain extract takes --slugs ${slug}' to reconcile.`);
- return;
- }
- // Derive resolved fields from the inputs. Mirror the engine semantics:
- // quality wins when both set; partial → outcome=null.
- const finalQuality = quality ?? (outcome === true ? 'correct' : outcome === false ? 'incorrect' : undefined);
- if (!finalQuality) return; // unreachable — covered by earlier validation
- const finalOutcome = finalQuality === 'partial' ? undefined
- : finalQuality === 'correct' ? true : false;
- const updated = {
- ...target,
- resolvedAt: new Date().toISOString().slice(0, 10),
- resolvedQuality: finalQuality,
- resolvedOutcome: finalOutcome,
- resolvedEvidence: source,
- resolvedValue: value,
- resolvedUnit: unit,
- resolvedBy,
- };
- const allRows = parsed.takes.map(t => t.rowNum === rowNum ? updated : t);
- const newFence = renderTakesFence(allRows);
- const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
- const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
- const out = body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
- writeBody(path, out);
- });
- const finalQuality = quality ?? (outcome === true ? 'correct' : outcome === false ? 'incorrect' : 'unknown');
+ // Back-compat --outcome maps onto quality; the shared core takes quality only.
+ const finalQuality = quality ?? (outcome === true ? 'correct' : 'incorrect');
+
+ // v0.46.x (EV1): markdown is canonical — the fence row must exist on disk
+ // (the old path resolved the DB first and warned when the fence lacked the
+ // row, leaving a resolution the next reconcile couldn't see).
+ try {
+ await resolveTakeOnPage(
+ { engine, slug, brainDir, sourceId },
+ rowNum,
+ { quality: finalQuality, evidence: source, value, unit, resolvedBy },
+ );
+ } catch (err) {
+ exitTakesError(err);
+ }
+
const valueSummary = valueStr ? ` value=${value}${unit ? ` ${unit}` : ''}` : '';
console.log(`Resolved take #${rowNum} on ${slug}: quality=${finalQuality}${valueSummary}.`);
}
diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.ts
new file mode 100644
index 0000000000..5f2fe428e2
--- /dev/null
+++ b/src/commands/thin-client-routing.ts
@@ -0,0 +1,211 @@
+/**
+ * CLI→MCP gap-closure wave [OV6] — per-subcommand thin-client routing for the
+ * commands whose reads/writes gained MCP ops: takes (list/search/scorecard/
+ * calibration + the write verbs), search (modes/stats/tune, read-only forms),
+ * jobs stats, cache stats, and quarantine list. The salience/anomalies/
+ * graph-query precedent, engine-free: each routable subcommand maps onto its
+ * op over callRemoteTool; everything else returns false so the caller falls
+ * through to refuseThinClient's pinpoint hint.
+ *
+ * Config-MUTATING forms stay host-side by design: `search modes --reset` and
+ * `search tune --apply` (CDX-21), plus `search modes --source <mode>` (the
+ * reset dry-run — previews what a reset would change on the host), `cache
+ * clear|prune`, `quarantine scan|clear`, `takes extract|revisit`.
+ */
+
+import type { GBrainConfig } from '../core/config.ts';
+import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
+
+function flagValue(args: string[], name: string): string | undefined {
+ const i = args.indexOf(name);
+ return i === -1 ? undefined : args[i + 1];
+}
+
+function num(v: string | undefined): number | undefined {
+ if (v === undefined) return undefined;
+ const n = parseFloat(v);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+async function call(cfg: GBrainConfig, tool: string, args: Record<string, unknown>): Promise<unknown> {
+ return unpackToolResult(await callRemoteTool(cfg, tool, args));
+}
+
+function printJson(result: unknown): void {
+ console.log(JSON.stringify(result, null, 2));
+}
+
+/**
+ * Recognized-but-malformed routable subcommand: print the SAME usage string
+ * the host CLI prints (copied verbatim from src/commands/takes.ts) and exit 1.
+ * Returning false here instead would fall through to the host-bound refusal
+ * hint, which misleads (the subcommand IS routable — the args are just wrong).
+ */
+function usageExit(...lines: string[]): never {
+ for (const line of lines) console.error(line);
+ process.exit(1);
+}
+
+/**
+ * Route a thin-client invocation to its MCP op. Returns true when handled
+ * (output printed); false ONLY when the subcommand is genuinely host-bound
+ * and the caller should refuse with the hint. Routable subcommands with
+ * missing/invalid required args exit 1 with the host CLI's usage string
+ * instead of returning false. Remote op errors propagate (the mcp-client
+ * error surface already names the op + reason).
+ */
+export async function routeThinClientCommand(
+ cfg: GBrainConfig,
+ command: string,
+ args: string[],
+): Promise<boolean> {
+ const sub = args[0];
+ const rest = args.slice(1);
+
+ if (command === 'takes') {
+ switch (sub) {
+ case 'list': {
+ const slug = rest[0] && !rest[0].startsWith('-') ? rest[0] : undefined;
+ printJson(await call(cfg, 'takes_list', {
+ ...(slug ? { page_slug: slug } : {}),
+ ...(flagValue(rest, '--who') ? { holder: flagValue(rest, '--who') } : {}),
+ ...(flagValue(rest, '--kind') ? { kind: flagValue(rest, '--kind') } : {}),
+ }));
+ return true;
+ }
+ case 'search': {
+ if (!rest[0]) {
+ usageExit('Usage: gbrain takes search "<query>" [--who h] [--json]');
+ }
+ printJson(await call(cfg, 'takes_search', { query: rest[0], ...(num(flagValue(rest, '--limit')) !== undefined ? { limit: num(flagValue(rest, '--limit')) } : {}) }));
+ return true;
+ }
+ case 'scorecard': {
+ const holder = rest[0] && !rest[0].startsWith('--') ? rest[0] : flagValue(rest, '--holder');
+ printJson(await call(cfg, 'takes_scorecard', { ...(holder ? { holder } : {}) }));
+ return true;
+ }
+ case 'calibration': {
+ printJson(await call(cfg, 'takes_calibration', { ...(flagValue(rest, '--holder') ? { holder: flagValue(rest, '--holder') } : {}) }));
+ return true;
+ }
+ case 'add': {
+ const slug = rest[0];
+ const claim = flagValue(rest, '--claim');
+ const kind = flagValue(rest, '--kind');
+ const holder = flagValue(rest, '--who');
+ if (!slug || !claim || !kind || !holder) {
+ usageExit('Usage: gbrain takes add <slug> --claim "..." --kind <k> --who <h> [--weight 0.5] [--source "..."] [--since YYYY-MM]');
+ }
+ const res = await call(cfg, 'takes_add', {
+ slug,
+ claim,
+ kind,
+ holder,
+ ...(num(flagValue(rest, '--weight')) !== undefined ? { weight: num(flagValue(rest, '--weight')) } : {}),
+ ...(flagValue(rest, '--source') ? { source: flagValue(rest, '--source') } : {}),
+ ...(flagValue(rest, '--since') ? { since: flagValue(rest, '--since') } : {}),
+ }) as { row_num: number };
+ console.log(`Added take #${res.row_num} to ${slug}. (routed to the brain host)`);
+ return true;
+ }
+ case 'update': {
+ const slug = rest[0];
+ const row = num(flagValue(rest, '--row'));
+ if (!slug || row === undefined) {
+ usageExit('Usage: gbrain takes update <slug> --row N [--weight 0.7] [--source "..."] [--since YYYY-MM]');
+ }
+ await call(cfg, 'takes_update', {
+ slug, row_num: row,
+ ...(num(flagValue(rest, '--weight')) !== undefined ? { weight: num(flagValue(rest, '--weight')) } : {}),
+ ...(flagValue(rest, '--source') ? { source: flagValue(rest, '--source') } : {}),
+ ...(flagValue(rest, '--since') ? { since: flagValue(rest, '--since') } : {}),
+ });
+ console.log(`Updated take #${row} on ${slug}. (routed to the brain host)`);
+ return true;
+ }
+ case 'resolve': {
+ const slug = rest[0];
+ const row = num(flagValue(rest, '--row'));
+ const RESOLVE_USAGE = [
+ 'Usage: gbrain takes resolve <slug> --row N --quality correct|incorrect|partial|unresolvable [--evidence "..."] [--value N --unit usd|pct|count] [--by <slug>]',
+ ' (back-compat) gbrain takes resolve <slug> --row N --outcome true|false [...]',
+ ];
+ // Back-compat outcome lane (mirrors cmdResolve in src/commands/takes.ts):
+ // --quality wins when present; otherwise --outcome true|false maps onto
+ // correct|incorrect. Any other outcome value is a usage error.
+ let quality = flagValue(rest, '--quality');
+ const outcomeStr = flagValue(rest, '--outcome');
+ if (!quality && outcomeStr !== undefined) {
+ if (outcomeStr !== 'true' && outcomeStr !== 'false') {
+ usageExit(...RESOLVE_USAGE);
+ }
+ quality = outcomeStr === 'true' ? 'correct' : 'incorrect';
+ console.error('[deprecated] --outcome is the v0.28 alias for --quality. Prefer --quality correct|incorrect|partial in new scripts.');
+ }
+ if (!slug || row === undefined || !quality) {
+ usageExit(...RESOLVE_USAGE);
+ }
+ const res = await call(cfg, 'takes_resolve', {
+ slug, row_num: row, quality,
+ ...(flagValue(rest, '--evidence') ? { evidence: flagValue(rest, '--evidence') } : {}),
+ ...(num(flagValue(rest, '--value')) !== undefined ? { value: num(flagValue(rest, '--value')) } : {}),
+ ...(flagValue(rest, '--unit') ? { unit: flagValue(rest, '--unit') } : {}),
+ }) as { resolved_by: string };
+ console.log(`Resolved take #${row} on ${slug}: quality=${quality} (as ${res.resolved_by}).`);
+ return true;
+ }
+ case 'supersede': {
+ const slug = rest[0];
+ const row = num(flagValue(rest, '--row'));
+ const claim = flagValue(rest, '--claim');
+ if (!slug || row === undefined || !claim) {
+ usageExit('Usage: gbrain takes supersede <slug> --row N --claim "..." [--kind k] [--who h] [--weight 0.5] [--source "..."]');
+ }
+ const res = await call(cfg, 'takes_supersede', {
+ slug, row_num: row, claim,
+ ...(flagValue(rest, '--kind') ? { kind: flagValue(rest, '--kind') } : {}),
+ ...(flagValue(rest, '--who') ? { holder: flagValue(rest, '--who') } : {}),
+ ...(num(flagValue(rest, '--weight')) !== undefined ? { weight: num(flagValue(rest, '--weight')) } : {}),
+ }) as { old_row: number; new_row: number };
+ console.log(`Superseded #${res.old_row} → new #${res.new_row} on ${slug}. (routed to the brain host)`);
+ return true;
+ }
+ default:
+ return false; // extract / revisit / unknown — host-bound, refuse with hint
+ }
+ }
+
+ if (command === 'search') {
+ if (sub === 'modes' && !rest.includes('--reset') && !rest.includes('--source')) {
+ printJson(await call(cfg, 'search_modes', {}));
+ return true;
+ }
+ if (sub === 'stats') {
+ printJson(await call(cfg, 'search_stats', { ...(num(flagValue(rest, '--days')) !== undefined ? { days: num(flagValue(rest, '--days')) } : {}) }));
+ return true;
+ }
+ if (sub === 'tune' && !rest.includes('--apply')) {
+ printJson(await call(cfg, 'search_tune', {}));
+ return true;
+ }
+ return false; // modes --reset / modes --source (the reset dry-run) / tune --apply / diagnose — host-side config or live probe
+ }
+
+ if (command === 'jobs' && sub === 'stats') {
+ printJson(await call(cfg, 'get_job_stats', { ...(flagValue(rest, '--queue') ? { queue: flagValue(rest, '--queue') } : {}) }));
+ return true;
+ }
+
+ if (command === 'cache' && sub === 'stats') {
+ printJson(await call(cfg, 'cache_stats', {}));
+ return true;
+ }
+
+ if (command === 'quarantine' && sub === 'list') {
+ printJson(await call(cfg, 'quarantine_list', { ...(rest.includes('--include-flagged') ? { include_flagged: true } : {}) }));
+ return true;
+ }
+
+ return false;
+}
diff --git a/src/core/capture-content.ts b/src/core/capture-content.ts
new file mode 100644
index 0000000000..954c7950ff
--- /dev/null
+++ b/src/core/capture-content.ts
@@ -0,0 +1,198 @@
+/**
+ * Capture content helpers — moved from src/commands/capture.ts in the
+ * CLI→MCP gap-closure wave so the `capture` MCP op and the CLI share slug
+ * defaulting, dedupe hashing, the binary guard, and the frontmatter merge.
+ * (capture.ts statically imports operations.ts, so operations-layer code must
+ * never import capture.ts — this module breaks that cycle.) Pure functions;
+ * no fs, no engine.
+ */
+
+import matter from 'gray-matter';
+import { computeContentHash } from './ingestion/types.ts';
+
+/** The subset of capture options the frontmatter/slug helpers consume. */
+export interface CaptureFrontmatterOpts {
+ type?: string;
+ /** Ingestion channel override (CLI --source; ops never set it). */
+ source?: string;
+ /**
+ * Channel label used as the `captured_via` DEFAULT when no user frontmatter
+ * or CLI `--source` override is present. Lets a remote MCP caller record
+ * `capture-mcp` provenance instead of the local-CLI-implying `capture-cli`.
+ * Ordered below `source` so the explicit CLI flag still wins.
+ */
+ capturedVia?: string;
+ // v0.42.x — Life Chronicle (#2390) `--type event` sugar.
+ who?: string;
+ what?: string;
+ where?: string;
+ kind?: string;
+ depth?: string;
+}
+
+// v0.42.x — Life Chronicle (#2390): route the default slug prefix by type so
+// `gbrain capture --type diary` lands under life/diary/ and `--type event`
+// under life/events/ (matching the chronicle path-prefix inference). Everything
+// else keeps the inbox/ default.
+export function slugPrefixForType(type?: string): string {
+ if (type === 'diary') return 'life/diary';
+ if (type === 'event') return 'life/events';
+ return 'inbox';
+}
+
+export function defaultSlug(content: string, now: Date = new Date(), type?: string): string {
+ const y = now.getUTCFullYear();
+ const m = String(now.getUTCMonth() + 1).padStart(2, '0');
+ const d = String(now.getUTCDate()).padStart(2, '0');
+ const hashPrefix = computeContentHash(content).slice(0, 8);
+ return `${slugPrefixForType(type)}/${y}-${m}-${d}-${hashPrefix}`;
+}
+
+/**
+ * v0.39.3.0 CV10 — binary file guard. Scans the first 8KB of `buf` for a
+ * NUL byte (0x00). Real text files (including UTF-8 with multi-byte CJK,
+ * emoji, BOM) never contain a NUL byte at any position — text encoding
+ * uses non-zero continuation bytes. NUL appears in binary formats:
+ * executables, archives, compressed images, PDFs (after the magic-byte
+ * header), most office documents. Single-pass scan; constant memory.
+ *
+ * Returns the 0-indexed byte offset of the first NUL, or -1 if clean.
+ * Caller decides the error shape (message vs JSON envelope).
+ *
+ * Known limit: a PNG-without-NUL-in-first-8KB slips through. v0.39
+ * magic-byte allowlist (per CV10-B + TODOS.md) closes this hole. The
+ * 8KB ceiling bounds the scan cost to ~microseconds even on huge files.
+ */
+export function detectBinaryNullByte(buf: Buffer): number {
+ const limit = Math.min(buf.length, 8 * 1024);
+ for (let i = 0; i < limit; i++) {
+ if (buf[i] === 0) return i;
+ }
+ return -1;
+}
+
+/**
+ * v0.39.3.0 CV9 — normalize content for content_hash so identical text
+ * produces identical hashes regardless of leading/trailing whitespace,
+ * line-ending style (CRLF vs LF), or Unicode normalization form. The
+ * STORED body is preserved as-is (CRLF stays CRLF, BOM stays BOM).
+ *
+ * Two concerns, two transforms — the hash gets aggressive normalization
+ * for dedup correctness; the stored body keeps user bytes for round-trip
+ * fidelity. CQ2's CRLF/BOM preservation tests rely on this split.
+ */
+export function normalizeForHash(s: string): string {
+ // Strip BOM, normalize line endings to LF, trim, NFKC for Unicode-stable hash.
+ return s.replace(/^/, '').replace(/\r\n/g, '\n').trim().normalize('NFKC');
+}
+
+/**
+ * Derive a title from the first non-empty, non-`---` line of the body,
+ * stripping leading markdown heading marks, capped at 80 chars. Truncation
+ * is codepoint-aware (never splits an astral surrogate pair) and appends an
+ * ellipsis so a cut title is visibly cut.
+ * Falls back to 'Capture' when no usable line exists.
+ */
+export function deriveTitle(rawBody: string): string {
+ const firstLine = rawBody
+ .split('\n')
+ .find((l) => l.trim().length > 0 && l.trim() !== '---') ?? '';
+ const stripped = firstLine.replace(/^#+\s*/, '');
+ const cps = [...stripped];
+ return (cps.length > 80 ? cps.slice(0, 79).join('') + '…' : stripped) || 'Capture';
+}
+
+// v0.42.x — Life Chronicle (#2390): assemble the `event:` frontmatter block
+// from the --who/--what/--where/--kind/--depth flags (only for --type event).
+// Returns undefined when no event flags are set so non-event captures are
+// untouched.
+export function buildEventBlock(opts: CaptureFrontmatterOpts): Record<string, unknown> | undefined {
+ if (opts.type !== 'event') return undefined;
+ const who = opts.who ? opts.who.split(',').map((s) => s.trim()).filter(Boolean) : [];
+ const block: Record<string, unknown> = {};
+ if (opts.what) block.what = opts.what;
+ if (who.length) block.who = who;
+ if (opts.where) block.where = opts.where;
+ if (opts.kind) block.kind = opts.kind;
+ if (opts.depth) block.depth = opts.depth;
+ return Object.keys(block).length ? block : undefined;
+}
+
+/**
+ * v0.39.3.0 (BUG-1): merge capture's auto-stamped fields with any existing
+ * frontmatter in `rawBody`, rather than always prepending a second
+ * frontmatter block. The pre-fix code stamped its own `---` block on top
+ * of files that already had frontmatter, producing `title: '---'` (the
+ * file's opening delimiter became the outer title) and two consecutive
+ * frontmatter blocks the parser interpreted as the outer block + a body
+ * starting with a horizontal rule.
+ *
+ * Precedence rules (user-wins by default):
+ * - `type`: opts.type (CLI flag) > userFm.type > 'note'
+ * - `title`: userFm.title > derived-from-body
+ * - `captured_via`: userFm.captured_via > opts.source > opts.capturedVia > 'capture-cli'
+ * (opts.capturedVia is the per-channel default — remote MCP
+ * captures pass 'capture-mcp' so provenance isn't misreported
+ * as local CLI; the explicit CLI --source override still wins)
+ * - `captured_at`: userFm.captured_at > now (user can pre-stamp for retroactive
+ * captures; see CQ2 test case 4)
+ * - Any other user-declared keys (description, tags, slug, etc.) pass through verbatim.
+ *
+ * For files WITHOUT existing frontmatter, preserves the original behavior:
+ * stamps a fresh frontmatter block, and if the body doesn't already look
+ * like markdown (no `#` heading), wraps it under a `# {title}` heading.
+ */
+export function mergeCaptureFrontmatter(rawBody: string, opts: CaptureFrontmatterOpts): string {
+ const nowIso = new Date().toISOString();
+ // Detect frontmatter: leading `---\n` or `---\r\n`, tolerating leading BOM/whitespace.
+ // We do NOT use the more permissive `startsWith('---')` because a body that opens
+ // with a horizontal-rule like `--- separator ---` would false-positive.
+ const trimmedStart = rawBody.replace(/^/, '');
+ const hasFrontmatter = /^---\r?\n/.test(trimmedStart);
+
+ if (!hasFrontmatter) {
+ // No existing frontmatter: stamp a fresh block and (if body lacks markdown
+ // structure) wrap under a derived heading.
+ const title = deriveTitle(rawBody);
+ const fm: Record<string, unknown> = {
+ type: opts.type ?? 'note',
+ title,
+ captured_via: opts.source ?? opts.capturedVia ?? 'capture-cli',
+ captured_at: nowIso,
+ };
+ const ev = buildEventBlock(opts);
+ if (ev) fm.event = ev;
+ const looksMarkdown = /^#{1,6}\s/.test(rawBody.trimStart());
+ const body = looksMarkdown ? rawBody : `# ${title}\n\n${rawBody}`;
+ return matter.stringify(body, fm);
+ }
+
+ // Existing frontmatter: parse, merge user-wins, re-emit as a SINGLE block.
+ let parsed: matter.GrayMatterFile<string>;
+ try {
+ parsed = matter(rawBody);
+ } catch (e) {
+ throw new Error(
+ `malformed frontmatter in capture input: ${e instanceof Error ? e.message : String(e)}`,
+ );
+ }
+ const userFm = (parsed.data ?? {}) as Record<string, unknown>;
+ const merged: Record<string, unknown> = {
+ // Spread user's declared keys first so 'description', 'tags', etc. pass through.
+ ...userFm,
+ // Then apply auto-fields with the precedence rules above. The explicit
+ // assignment AFTER the spread is intentional: it lets us implement the
+ // mixed precedence (CLI flag wins for `type`; user wins for `title`/
+ // `captured_via`/`captured_at`) in one expression per key.
+ type: opts.type ?? userFm.type ?? 'note',
+ title: userFm.title ?? deriveTitle(parsed.content),
+ captured_via: userFm.captured_via ?? opts.source ?? opts.capturedVia ?? 'capture-cli',
+ captured_at: userFm.captured_at ?? nowIso,
+ };
+ // v0.42.x — merge the event block (user-declared keys win per-key).
+ const ev = buildEventBlock(opts);
+ if (ev || userFm.event) {
+ merged.event = { ...(ev ?? {}), ...((userFm.event as Record<string, unknown>) ?? {}) };
+ }
+ return matter.stringify(parsed.content, merged);
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 6b8a9e3702..92f5af9e6b 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -22,12 +22,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'autopilot': ['--aliases', '--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--include-null-signature', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--pattern', '--pending', '--phase', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--source', '--stale', '--status', '--supersessions', '--surface', '--swap-only', '--target', '--target-score', '--thin', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'],
'backfill': ['--aliases', '--all', '--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--include-null-signature', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin'],
'bench': ['--baseline', '--brain', '--explain', '--force', '--from', '--help', '--json', '--label', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--restore-only', '--source', '--stale', '--symbol-kind', '--thin', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--aliases', '--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--by-mention', '--chapters-dir', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-turns', '--max-usd', '--mode', '--model', '--multimodal', '--no-confirm', '--no-embedding', '--no-extract', '--no-follow', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
+ 'book-mirror': ['--aliases', '--all', '--allow-empty', '--apply', '--asof', '--author', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--budget-usd-per-day', '--by-mention', '--chapters-dir', '--content', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-turns', '--max-usd', '--mode', '--model', '--multimodal', '--no-confirm', '--no-embedding', '--no-extract', '--no-follow', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--thin', '--timeout', '--timeout-ms', '--title', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--compile', '--confirm', '--count', '--delete-brain', '--diff-filter', '--env', '--error-unmatch', '--exclude-standard', '--fast', '--file', '--flag', '--force', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--isolated', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-verify', '--once', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--token', '--token-name', '--token-ttl', '--unset-all', '--url', '--user-hooks', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--aliases', '--all', '--brain', '--chunker-debug', '--code', '--compile', '--fast', '--file', '--fix', '--force', '--force-rechunk', '--force-resume', '--from-pages', '--full', '--help', '--http', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--model', '--no-embed', '--no-embedding', '--no-extract', '--no-save', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-judge', '--save', '--source', '--stale', '--strict-budget', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--yes'],
'cache': ['--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],
- 'calibration': ['--ab', '--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', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--holder', '--http', '--image', '--include-null-signature', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--phase', '--progress-interval', '--progress-json', '--quiet', '--regenerate', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--trusted-extraction', '--undo-wave', '--url', '--with-calibration', '--with-db', '--yes'],
- 'call': ['--aliases', '--all', '--all-sources', '--as-context', '--auto-fix', '--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-extract', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--page', '--param', '--params', '--password', '--path', '--pattern', '--pending', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--thin', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],
+ 'calibration': ['--ab', '--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', '--dry-run', '--entities', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--holder', '--http', '--image', '--include-null-signature', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--phase', '--progress-interval', '--progress-json', '--quiet', '--regenerate', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl', '--trusted-extraction', '--undo-wave', '--url', '--with-calibration', '--with-db', '--yes'],
+ 'call': ['--aliases', '--all', '--all-sources', '--apply', '--as-context', '--auto-fix', '--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--confirm-destructive', '--content', '--cost-estimate', '--count', '--days', '--depth', '--dim', '--dir', '--direction', '--enable-dcr', '--enable-dcr-insecure', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--from', '--from-meetings', '--grant-types', '--grep', '--hard-deadline', '--help', '--http', '--image', '--include-expired', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--install', '--interval', '--json', '--key', '--kind', '--lang', '--limit', '--link-source', '--link-type', '--llm', '--migrate-only', '--missing-path', '--multimodal', '--ner', '--no-embed', '--no-expand', '--no-extract', '--no-federated', '--no-hard-deadline', '--no-retry-connect', '--no-save', '--older-than', '--page', '--param', '--params', '--password', '--path', '--pattern', '--pending', '--pglite', '--port', '--probe-pglite', '--progress-interval', '--progress-json', '--public-url', '--queue', '--quiet', '--reenrich-after', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--sigma', '--since', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--status', '--stdin', '--strategy', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--synthesize', '--tag', '--thin', '--timeout', '--to', '--today', '--token', '--token-ttl', '--tools-json', '--type', '--undo', '--uninstall', '--url', '--version', '--watch', '--with-calibration', '--workers', '--yes'],
'capture': ['--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', '--depth', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--reset', '--resolve', '--restore-only', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--trusted-extraction', '--type', '--url', '--what', '--where', '--who', '--with-db', '--yes'],
'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
@@ -44,14 +44,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'dream': ['--against', '--aliases', '--all', '--allow-regression', '--anchor', '--asof', '--audit-rejects', '--background', '--batch', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--cancel-unmatched', '--code', '--committed-baseline', '--compare', '--compile', '--concurrent', '--ctx-size', '--cycles', '--date', '--detail', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--expansion', '--explain', '--fast', '--federated', '--fix', '--fixtures', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--format', '--from', '--from-db', '--from-pages', '--gold', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--install', '--json', '--judge-model', '--justification', '--keyword-only', '--lang', '--limit', '--llm', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-tokens', '--max-usd', '--mcp-only', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--name-only', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-llm', '--no-mutate', '--no-trajectory', '--once', '--out', '--output', '--output-dir', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--phase', '--priority', '--progress-interval', '--progress-json', '--pull', '--quiet', '--receipt-dir', '--reconcile-queue', '--remediate', '--repo', '--reranking', '--reset', '--resolve', '--restore-only', '--resume-from', '--retrieval-only', '--rounds', '--rubric-version', '--save', '--seed', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--source-guard', '--source-id', '--stale', '--suite', '--suites', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--take', '--task', '--thin', '--threshold', '--timeout', '--to', '--token-ttl', '--top-k', '--unsafe-bypass-dream-guard', '--update-baseline', '--verify', '--version', '--window', '--yes'],
'edges-backfill': ['--aliases', '--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--include-null-signature', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-extract', '--no-federated', '--older-than', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--source-guard', '--stale', '--supersessions', '--thin', '--timeout', '--workers'],
'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--version'],
- 'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],
+ 'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],
'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dim', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],
'export': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--explain', '--federated', '--fix', '--follow', '--help', '--include-null-signature', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--slug-prefix', '--source', '--source-guard', '--stale', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type'],
'extract': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--multimodal', '--name-status', '--near-symbol', '--ner', '--no-extract', '--no-federated', '--older-than', '--pack', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--run-id', '--since', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--strategy', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type', '--verbose', '--workers', '--yes'],
'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--to', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],
'features': ['--aliases', '--all', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--no-extract', '--pace', '--pace-max-concurrency', '--pack', '--path', '--pattern', '--pending', '--priority', '--progress-json', '--quiet', '--repo', '--reset', '--resolve', '--run-id', '--since', '--slugs', '--source', '--source-id', '--stale', '--supersessions', '--thin', '--type', '--verbose', '--workers'],
'files': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--fast', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--no-pointer', '--page', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--retry-failed', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--yes'],
- 'forget': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
+ 'forget': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
'founder': ['--aliases', '--all', '--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--mcp-only', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--since', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--aliases', '--all', '--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--get', '--help', '--http', '--include-catch-all', '--include-null-signature', '--json', '--name-only', '--name-status', '--no-embedding', '--no-extract', '--no-verify', '--others', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--strategy', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--uninstall', '--write-back'],
@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--all', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--provenance', '--reranking', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],
'integrity': ['--aliases', '--all', '--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--limit', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl', '--type', '--url'],
- 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--supersessions', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],
+ 'jobs': ['--abbrev-ref', '--aliases', '--all', '--allow-empty', '--allow-protected', '--allow-shell-jobs', '--apply', '--asof', '--auto', '--auto-fix', '--auto-with-prompt', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch', '--batch-size', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--break-lock', '--budget-usd', '--budget-usd-per-day', '--by-mention', '--by-type', '--cached', '--catch-up', '--check', '--cli-path', '--cluster', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--content', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dim', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--federated-read', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--hard-deadline', '--health-interval', '--held-out', '--help', '--http', '--idempotency-key', '--image', '--include-frontmatter', '--include-gitignored', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--job-id', '--job-isolation', '--json', '--kind', '--lang', '--limit', '--lock', '--lock-duration-ms', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--name-status', '--near-symbol', '--ner', '--nice', '--no', '--no-auto-embed', '--no-embed', '--no-embedding', '--no-extract', '--no-federate', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-mutate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--offset', '--older-than', '--once', '--order', '--orphan', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--phase', '--pid-file', '--priority', '--progress-interval', '--progress-json', '--queue', '--quiet', '--redact-secrets', '--reenrich-after', '--refresh-cache', '--refresh-ms', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--run-id', '--save', '--segment-limit', '--serial', '--session', '--session-id', '--short', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supersessions', '--surface', '--swap-only', '--symbol-kind', '--target', '--target-score', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--token-ttl', '--trusted-extraction', '--type', '--types', '--uninstall', '--unsafe-bypass-dream-guard', '--url', '--user', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--with-db', '--workers', '--yes'],
'lint': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--retry-judge', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--aliases', '--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--help', '--include-flagged', '--include-frontmatter', '--include-null-signature', '--index-audit', '--infer-dates', '--input', '--json', '--kind', '--lang', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--near-symbol', '--ner', '--nice', '--no-extract', '--no-mutate', '--older-than', '--once', '--pack', '--parallel', '--params', '--path', '--pattern', '--pending', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--progress-json', '--query', '--queue', '--quiet', '--rebuild-rollup', '--regenerate', '--remediate', '--remediation-plan', '--reset', '--resolve', '--restore-only', '--resume', '--run-id', '--safe', '--scope', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--supersessions', '--symbol-kind', '--target', '--target-score', '--thin', '--to', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--url', '--verbose', '--window', '--workers', '--yes'],
@@ -69,16 +69,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'models': ['--aliases', '--all', '--brain', '--ctx-size', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--help', '--include-null-signature', '--json', '--judge-model', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--pattern', '--pending', '--reranking', '--reset', '--resolve', '--skip', '--source', '--stale', '--supersessions', '--thin', '--to', '--version'],
'mounts': ['--alias', '--brain', '--cache', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--explain', '--help', '--id', '--json', '--lang', '--lock', '--markdown', '--mcp-url', '--multimodal', '--near-symbol', '--path', '--restore-only', '--skills-dir', '--source', '--stale', '--symbol-kind', '--thin', '--verbose'],
'notability-eval': ['--aliases', '--all', '--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--include-null-signature', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--out', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--skip-llm', '--source', '--stale', '--supersessions', '--target-high', '--target-low', '--target-medium', '--thin', '--to', '--version'],
- 'onboard': ['--aliases', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--from-pages', '--help', '--history', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-extract', '--offset', '--params', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--reset', '--resolve', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--supersessions', '--surface', '--target-score', '--thin', '--trusted-extraction', '--url', '--with-db', '--yes'],
+ 'onboard': ['--aliases', '--all', '--allow-empty', '--allow-protected', '--apply', '--asof', '--auto', '--auto-with-prompt', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--check', '--content', '--date', '--days', '--entities', '--explain', '--federated', '--file', '--follow', '--from-pages', '--help', '--history', '--http', '--image', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-extract', '--offset', '--params', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--remediation-plan', '--reset', '--resolve', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--target-score', '--thin', '--trusted-extraction', '--url', '--with-db', '--yes'],
'orphans': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--count', '--explain', '--follow', '--help', '--include-null-signature', '--include-pseudo', '--json', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--timeout'],
'pages': ['--aliases', '--all', '--brain', '--dry-run', '--help', '--include-null-signature', '--json', '--no-extract', '--older-than', '--pattern', '--pending', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin'],
'pglite-repair': ['--brain', '--break-lock', '--dry-rnu', '--dry-run', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--path', '--quiet', '--source', '--surface', '--token-ttl', '--yes'],
'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--path', '--pglite', '--quiet', '--repo', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],
- 'protocol': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-embedding', '--offset', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
+ 'protocol': ['--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--no-embedding', '--offset', '--path', '--progress-interval', '--progress-json', '--quiet', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--synthesize', '--target', '--timeout', '--token', '--token-ttl', '--trusted-extraction', '--url', '--with-db', '--yes'],
'providers': ['--brain', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--yes'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--aliases', '--all', '--apply', '--brain', '--code', '--compile', '--explain', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--no-embed', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--restore-only', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--symbol-kind', '--thin', '--token-ttl'],
- 'recall': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
+ 'recall': ['--aliases', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--grep', '--help', '--http', '--image', '--include-expired', '--include-null-signature', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--no-embedding', '--no-extract', '--no-federated', '--offset', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--repo', '--reset', '--resolve', '--restore-only', '--rollup', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stats', '--stdin', '--supersessions', '--surface', '--thin', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--url', '--watch', '--with-db', '--yes'],
'reconcile-links': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--include-null-signature', '--json', '--name-status', '--no-extract', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--source', '--stale', '--strategy', '--supersessions', '--thin', '--timeout', '--type'],
'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--thin', '--timeout', '--to', '--token-ttl', '--version', '--workers', '--yes'],
'reindex-code': ['--abi', '--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--no-extract', '--older-than', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--serial', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--version', '--workers', '--yes'],
@@ -111,5 +111,6 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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'],
'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'],
'ze-switch': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--markdown', '--no-extract', '--non-interactive', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--to', '--undo', '--yes'],
};
diff --git a/src/core/migration-ledger.ts b/src/core/migration-ledger.ts
new file mode 100644
index 0000000000..7637ed71dd
--- /dev/null
+++ b/src/core/migration-ledger.ts
@@ -0,0 +1,134 @@
+/**
+ * Migration-ledger summary — the read-only "what host migrations are
+ * outstanding" view, shared by the get_health op (TODOS:4063: remote agents
+ * detect wedged migrations without SSH-ing to run the doctor) and the
+ * apply-migrations orchestrator (which imports statusForVersion +
+ * compareVersions from here).
+ *
+ * OV4/EV4 (CLI→MCP gap-closure wave): an op must never import
+ * src/commands/apply-migrations.ts — that module statically pulls the whole
+ * migration registry (17 migration modules plus orchestrator machinery). This
+ * module works on VERSION STRINGS ONLY: MIGRATION_VERSIONS below is a plain
+ * string list, pinned against the real registry by
+ * test/migration-ledger.test.ts so it cannot drift silently.
+ */
+
+import { loadCompletedMigrations, type CompletedMigrationEntry } from './preferences.ts';
+
+/**
+ * Version strings of every registered host migration, in registry order.
+ * APPEND HERE when adding a migration module to src/commands/migrations/
+ * (the sync test fails the suite otherwise).
+ */
+export const MIGRATION_VERSIONS: readonly string[] = [
+ '0.11.0', '0.12.0', '0.12.2', '0.13.0', '0.13.1', '0.14.0', '0.16.0',
+ '0.18.0', '0.18.1', '0.21.0', '0.22.4', '0.28.0', '0.29.1', '0.31.0',
+ '0.32.2', '0.43.0', '0.46.3',
+];
+
+/** Bug 3 attempt cap — consecutive partials before a version counts wedged. */
+export const MAX_CONSECUTIVE_PARTIALS = 3;
+
+/**
+ * Compare two semver strings (MAJOR.MINOR.PATCH). Returns -1 / 0 / 1.
+ * Canonical home (moved from src/commands/migrations/index.ts, which
+ * re-exports it); originally extracted from upgrade.ts#isNewerThan.
+ */
+export function compareVersions(a: string, b: string): -1 | 0 | 1 {
+ const va = a.split('.').map(n => parseInt(n, 10) || 0);
+ const vb = b.split('.').map(n => parseInt(n, 10) || 0);
+ for (let i = 0; i < 3; i++) {
+ const da = va[i] ?? 0;
+ const db = vb[i] ?? 0;
+ if (da > db) return 1;
+ if (da < db) return -1;
+ }
+ return 0;
+}
+
+export type MigrationLedgerStatus = 'complete' | 'partial' | 'pending' | 'wedged';
+
+/**
+ * Resolved status for a migration version given its ledger entries.
+ *
+ * Semantics (Bug 3 — keep "complete wins" safety):
+ * - If the latest entry is `retry`, the version is pending. This is the
+ * explicit escape hatch written by a forced retry, and it overrides an
+ * earlier `complete` entry without hand-editing the ledger.
+ * - Otherwise, if any entry is `complete`, the version is complete.
+ * - Otherwise, MAX_CONSECUTIVE_PARTIALS trailing partials → wedged.
+ * - Otherwise, any `partial` entry → partial; else pending.
+ *
+ * `complete` never regresses accidentally. A later `partial` append cannot
+ * undo a completed migration; only a trailing, explicit `retry` marker can.
+ */
+export function statusForVersion(
+ version: string,
+ byVersion: Map<string, CompletedMigrationEntry[]>,
+): MigrationLedgerStatus {
+ const entries = byVersion.get(version) ?? [];
+ if (entries.length === 0) return 'pending';
+ const latest = entries[entries.length - 1];
+ if (latest.status === 'retry') return 'pending';
+ if (entries.some(e => e.status === 'complete')) return 'complete';
+ let consecutive = 0;
+ for (let i = entries.length - 1; i >= 0; i--) {
+ const e = entries[i];
+ if (e.status === 'partial') consecutive++;
+ else break;
+ }
+ if (consecutive >= MAX_CONSECUTIVE_PARTIALS) return 'wedged';
+ if (entries.some(e => e.status === 'partial')) return 'partial';
+ return 'pending';
+}
+
+export function indexCompletedEntries(
+ entries: CompletedMigrationEntry[],
+): Map<string, CompletedMigrationEntry[]> {
+ const byVersion = new Map<string, CompletedMigrationEntry[]>();
+ for (const e of entries) {
+ const list = byVersion.get(e.version) ?? [];
+ list.push(e);
+ byVersion.set(e.version, list);
+ }
+ return byVersion;
+}
+
+export interface MigrationLedgerSummary {
+ /** Registered migrations ≤ installed version with no ledger completion. */
+ pending: string[];
+ /** Started but unfinished (some phases recorded partial). */
+ partial: string[];
+ /** Hit the consecutive-partial cap — needs an explicit forced retry. */
+ wedged: string[];
+ /**
+ * Migrations newer than the installed binary (count only). Future-versioned
+ * migrations are excluded from ALL status buckets regardless of ledger
+ * state (matches the apply-migrations list view); after a binary downgrade
+ * a wedged future migration appears only in this count.
+ */
+ skipped_future: number;
+}
+
+/**
+ * Summarize the host migration ledger for the given installed version.
+ * Filesystem read (the completed-migrations JSONL) — engine-agnostic, which
+ * is why get_health composes this at the op layer rather than growing
+ * BrainEngine.getHealth() in both engines. Version strings only; never
+ * migration internals.
+ */
+export function migrationLedgerSummary(installedVersion: string): MigrationLedgerSummary {
+ const byVersion = indexCompletedEntries(loadCompletedMigrations());
+ const summary: MigrationLedgerSummary = { pending: [], partial: [], wedged: [], skipped_future: 0 };
+ for (const version of MIGRATION_VERSIONS) {
+ if (compareVersions(version, installedVersion) > 0) {
+ summary.skipped_future += 1;
+ continue;
+ }
+ const status = statusForVersion(version, byVersion);
+ if (status === 'pending') summary.pending.push(version);
+ else if (status === 'partial') summary.partial.push(version);
+ else if (status === 'wedged') summary.wedged.push(version);
+ }
+ return summary;
+}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 7054b7b97a..97fba3080c 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -2102,3 +2102,25 @@ export class MinionQueue {
return rows.length > 0;
}
}
+
+/**
+ * issue #1801 / CLI→MCP gap-closure wave (CEO-F7) — derive the wedged-queue
+ * boolean from getStats().wedge, shared by `gbrain jobs stats` and the
+ * get_job_stats op so the two surfaces can never disagree. A queue is wedged
+ * when a worker is alive but claiming nothing while work waits:
+ * zero live-lock active rows, waiting > 0, and the last completion is older
+ * than the threshold (or absent). Threshold matches the doctor wedged_queue
+ * check: GBRAIN_WEDGED_QUEUE_WARN_MINUTES (server-side env), default 15.
+ */
+export function deriveWedgeSignal(wedge: {
+ active_healthy: number;
+ waiting: number;
+ minutes_since_completion: number | null;
+}): { wedged: boolean; wedge_threshold_minutes: number } {
+ const raw = parseInt(process.env.GBRAIN_WEDGED_QUEUE_WARN_MINUTES ?? '', 10);
+ const wedge_threshold_minutes = Number.isFinite(raw) && raw > 0 ? raw : 15;
+ const mins = wedge.minutes_since_completion;
+ const wedged = wedge.active_healthy === 0 && wedge.waiting > 0
+ && (mins === null || mins > wedge_threshold_minutes);
+ return { wedged, wedge_threshold_minutes };
+}
diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.ts
index ee07800ba4..403477c92b 100644
--- a/src/core/operations-descriptions.ts
+++ b/src/core/operations-descriptions.ts
@@ -238,3 +238,19 @@ export const SKILL_CLIENT_GUIDANCE = {
"if the user hasn't clearly asked for a write.",
],
} as const;
+
+/**
+ * CLI→MCP gap-closure wave — the capture op (D2A). Pinned here because it
+ * rewrites the routing guidance three docs used to carry as the
+ * "unknown tool: capture → use put_page" FAQ: agents must learn the split
+ * (capture = quick notes with auto-slug + dedupe; put_page = full control)
+ * from this description alone. Phrase-pinned by
+ * test/operations-descriptions.test.ts.
+ */
+export const CAPTURE_DESCRIPTION =
+ 'Capture a quick note into the brain — the "just remember this" write. Auto-derives a ' +
+ 'stable inbox/ slug from the content date + hash (recapturing identical text is ' +
+ 'idempotent), merges frontmatter, refuses binary/empty payloads, then delegates to ' +
+ 'put_page (inheriting its fences and provenance stamping). Prefer capture for quick ' +
+ 'notes and put_page when you need to control the slug, type, or an existing page\'s ' +
+ 'content. For structured facts about entities, prefer remember.';
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index f1ec50faf0..2c0bf25e33 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -28,10 +28,24 @@ const get_stats: Operation = {
const get_health: Operation = {
name: 'get_health',
- description: 'Brain health dashboard (embed coverage, stale pages, orphans)',
+ description: 'Brain health dashboard (embed coverage, stale pages, orphans). Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host.',
params: {},
handler: async (ctx) => {
- return ctx.engine.getHealth();
+ const health = await ctx.engine.getHealth();
+ // TODOS:4063 — composed at the OP layer (not BrainEngine.getHealth):
+ // the ledger is a filesystem JSONL, engine-agnostic; growing the engine
+ // interface would force both engines to duplicate a file read.
+ // Best-effort like the doctor's ledger read: a corrupt/unreadable ledger
+ // degrades the field, never the health call.
+ let migrations: unknown;
+ try {
+ const { migrationLedgerSummary } = await import('../migration-ledger.ts');
+ const { VERSION } = await import('../../version.ts');
+ migrations = migrationLedgerSummary(VERSION);
+ } catch {
+ migrations = { error: 'ledger_unreadable' };
+ }
+ return { ...health, migrations };
},
scope: 'admin',
cliHints: { name: 'health' },
@@ -164,8 +178,48 @@ const revert_version: Operation = {
};
+/**
+ * CLI→MCP gap-closure wave — read-only view of the content-quality gate
+ * (issue #1699). User story: an operator/agent reviewing what the gate hid or
+ * flagged, remotely or via a thin-client CLI. Admin scope: enumerates
+ * deliberately-hidden page slugs (the run_doctor posture). `quarantine scan`
+ * (bulk re-import + re-embed) and `quarantine clear` (the trust decision —
+ * same class as extraction_review) stay CLI-only.
+ */
+const quarantine_list: Operation = {
+ name: 'quarantine_list',
+ description:
+ 'List quarantined (hidden) and optionally content-flagged pages by scanning page ' +
+ 'frontmatter, newest-updated first. When truncated is true, count is a LOWER BOUND — ' +
+ 'raise max_scan/limit or run the quarantine list command on the brain host for the full ' +
+ 'set. Clearing a marker is a local-only trust decision (CLI).',
+ params: {
+ include_flagged: { type: 'boolean', required: false, description: 'Also list content_flag pages (searchable-but-warned). Default false.' },
+ limit: { type: 'number', required: false, description: 'Max rows returned (default 200, cap 1000).' },
+ max_scan: { type: 'number', required: false, description: 'Max pages scanned (default 20000, cap 100000).' },
+ },
+ scope: 'admin',
+ area: 'admin',
+ handler: async (ctx, p) => {
+ const {
+ collectQuarantineRows,
+ QUARANTINE_LIST_DEFAULT_LIMIT, QUARANTINE_LIST_MAX_LIMIT,
+ QUARANTINE_SCAN_DEFAULT, QUARANTINE_SCAN_MAX,
+ } = await import('../../commands/quarantine.ts');
+ const rawLimit = typeof p.limit === 'number' && Number.isFinite(p.limit) ? p.limit : QUARANTINE_LIST_DEFAULT_LIMIT;
+ const rawScan = typeof p.max_scan === 'number' && Number.isFinite(p.max_scan) ? p.max_scan : QUARANTINE_SCAN_DEFAULT;
+ const { rows, scanned, truncated } = await collectQuarantineRows(ctx.engine, {
+ includeFlagged: p.include_flagged === true,
+ limit: Math.max(1, Math.min(QUARANTINE_LIST_MAX_LIMIT, rawLimit)),
+ maxScan: Math.max(1, Math.min(QUARANTINE_SCAN_MAX, rawScan)),
+ ...sourceScopeOpts(ctx),
+ });
+ return { schema_version: 1, count: rows.length, truncated, scanned, rows };
+ },
+};
+
// Ops in EXACTLY the canonical `operations` array order.
export const adminOperations: Operation[] = [
get_stats, get_health, run_doctor, get_versions, revert_version,
- get_brain_identity,
+ get_brain_identity, quarantine_list,
];
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 2e5c79d95d..193fe75ce2 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -287,6 +287,14 @@ export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
// would break the original feature for clients that legitimately hold both
// a binding and `agent` scope.
'submit_agent',
+ // CLI→MCP gap-closure wave: capture delegates to put_page with the same ctx
+ // (inheriting its enforceClientSlugFence) and [EV7] defaults its slug UNDER
+ // the caller's first bound prefix — the zero-config path exists for exactly
+ // the bound-agent audience. The takes write verbs each call
+ // enforceClientSlugFence themselves (their markdown mirror writes the
+ // page file under the slug), the same guarantee as add_tag/add_timeline_entry.
+ 'capture',
+ 'takes_add', 'takes_update', 'takes_resolve', 'takes_supersede',
]);
/**
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index ee2301ee42..742000c33d 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -78,6 +78,30 @@ export class OperationError extends Error {
}
}
+/**
+ * CLI→MCP gap-closure wave (ENG-E2) — shared relation-missing guard for the
+ * telemetry ops (get_job_stats, cache_stats, search_stats, search_tune).
+ * Older brains that predate a feature's tables raw-error with Postgres 42P01
+ * ("relation … does not exist") / PGLite's equivalent; every telemetry op
+ * must degrade to the SAME actionable 'unavailable' envelope instead — one
+ * helper, never four inline copies.
+ */
+export async function withRelationGuard<T>(fn: () => Promise<T>, what: string): Promise<T> {
+ try {
+ return await fn();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (/relation .* does not exist|no such table/i.test(msg)) {
+ throw new OperationError(
+ 'unavailable',
+ `${what} is unavailable on this brain: a required table is missing.`,
+ 'Run gbrain apply-migrations on the brain host, then retry.',
+ );
+ }
+ throw err;
+ }
+}
+
/**
* MEMORY_VERBS v1 error constructor. Every verb error carries a populated
* `suggestion` (problem + cause + fix — agents read it and self-correct;
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
index 51e68f001e..2dcbac8cfa 100644
--- a/src/core/ops/insights.ts
+++ b/src/core/ops/insights.ts
@@ -155,7 +155,12 @@ const find_experts: Operation = {
...sourceScopeOpts(ctx),
});
},
- cliHints: { name: 'whoknows', positional: ['topic'] },
+ // hidden: 'whoknows' is in CLI_ONLY (src/cli.ts) — runWhoknows owns the CLI
+ // surface (ranked table + per-factor explain + thin-client routing) and was
+ // unreachable while this non-hidden hint dispatched the generic op formatter
+ // (the #2035 calibration bug class, resolved the #3502 way: wire the richer
+ // handler, hide the hint).
+ cliHints: { name: 'whoknows', positional: ['topic'], hidden: true },
};
// v0.32.6: contradiction probe MCP surface (M3)
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index f31ba776b8..4f468b7050 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -646,9 +646,47 @@ const send_job_message: Operation = {
};
+/**
+ * CLI→MCP gap-closure wave — `gbrain jobs stats` was the one jobs verb with
+ * no MCP equivalent (skills/minion-orchestrator documented the gap). Admin
+ * scope for jobs-family consistency (every op above is admin; HTTP callers
+ * need an admin-scope token). User story: an orchestrating agent checking
+ * queue health / catching the silent-halt wedge without shelling out.
+ */
+const get_job_stats: Operation = {
+ name: 'get_job_stats',
+ description:
+ 'Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL ' +
+ '(unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to ' +
+ 'the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming ' +
+ 'nothing while work waits) — suggest restarting the jobs supervisor on the brain host. ' +
+ 'Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.',
+ params: {
+ queue: { type: 'string', required: false, description: "Queue for the wedge signature (default 'default'). The other blocks stay global/windowed." },
+ since_hours: { type: 'number', required: false, description: 'Window for the by_type rollup in hours (default 24, clamped 1..720).' },
+ },
+ scope: 'admin',
+ area: 'jobs',
+ handler: async (ctx, p) => {
+ const { withRelationGuard } = await import('./contract.ts');
+ return withRelationGuard(async () => {
+ const { MinionQueue, deriveWedgeSignal } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const rawHours = typeof p.since_hours === 'number' && Number.isFinite(p.since_hours) ? p.since_hours : 24;
+ const hours = Math.max(1, Math.min(720, rawHours));
+ const stats = await queue.getStats({
+ since: new Date(Date.now() - hours * 3_600_000),
+ queue: typeof p.queue === 'string' && p.queue.length > 0 ? p.queue : 'default',
+ });
+ const { wedged, wedge_threshold_minutes } = deriveWedgeSignal(stats.wedge);
+ return { schema_version: 1, window_hours: hours, ...stats, wedged, wedge_threshold_minutes };
+ }, 'Job queue statistics (minions schema)');
+ },
+};
+
// Ops in EXACTLY the canonical `operations` array order.
export const jobsOperations: Operation[] = [
submit_job, get_job, list_jobs, cancel_job, retry_job, get_job_progress,
pause_job, resume_job, replay_job, send_job_message,
- submit_agent, get_agent_job,
+ submit_agent, get_agent_job, get_job_stats,
];
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index a3643307b5..65c0e25245 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -19,7 +19,7 @@ import type { WriterLintPayload } from '../output/post-write.ts';
import { stripFactsFence } from '../facts-fence.ts';
import { getContentFlag } from '../quarantine.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
-import { LIST_PAGES_DESCRIPTION } from '../operations-descriptions.ts';
+import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
import { OperationError } from './contract.ts';
import type { Operation } from './contract.ts';
import {
@@ -27,6 +27,8 @@ import {
slugOutsideCallerFence,
enforceClientSlugFence,
federatedSearchScope,
+ normalizeSlugPrefix,
+ validatePageSlug,
} from './context.ts';
// --- Page CRUD ---
@@ -930,9 +932,95 @@ const list_pages: Operation = {
// Ops in EXACTLY the order they appear in the canonical `operations` array
+/**
+ * CLI→MCP gap-closure wave — `capture` over MCP (D2A). The documented "just
+ * get this into my brain" entrypoint: three separate docs carried the
+ * "unknown tool: capture → use put_page" FAQ because agents kept reaching for
+ * it. Thin sugar that DELEGATES to the put_page handler with the same ctx
+ * (inheriting every fence: slug fence, dedupe, unknown-type audit,
+ * write-through, remote auto-link skip) after adding what agents had to
+ * hand-roll: a stable content-derived default slug + the frontmatter merge +
+ * the binary/empty guards. Remote provenance stays the CV6 server-stamp
+ * `mcp:put_page` (the write API truthfully IS put_page); the result carries
+ * channel: 'capture' for the receipt. Joins STARTER_OPS as a direct literal
+ * [EV8] so the plugin/starter lanes that retired the FAQ can actually call it.
+ */
+const capture: Operation = {
+ name: 'capture',
+ description: CAPTURE_DESCRIPTION,
+ params: {
+ content: { type: 'string', required: true, description: 'Markdown or plain text to capture. File paths are NOT accepted over MCP — read the file yourself and pass its content (the CLI --file lane is local-only).' },
+ slug: { type: 'string', required: false, description: "Target slug. Default: inbox/YYYY-MM-DD-<sha8-of-content> (stable per content — recapturing identical text hits the same slug); type diary/event routes under life/. Fenced clients: the default lands under your first bound prefix." },
+ type: { type: 'string', required: false, description: "Page type for the stamped frontmatter (default 'note')." },
+ },
+ scope: 'write',
+ mutating: true,
+ area: 'pages',
+ // 'capture' is in CLI_ONLY (rich local UX: --file/--stdin/event sugar);
+ // hidden hint per the advisor pattern.
+ cliHints: { name: 'capture', hidden: true },
+ handler: async (ctx, p) => {
+ const {
+ detectBinaryNullByte, normalizeForHash, mergeCaptureFrontmatter,
+ defaultSlug,
+ } = await import('../capture-content.ts');
+ const { computeContentHash } = await import('../ingestion/types.ts');
+ const content = p.content as string;
+ const nulAt = detectBinaryNullByte(Buffer.from(content, 'utf8'));
+ if (nulAt !== -1) {
+ throw new OperationError('invalid_params',
+ `content contains a NUL byte at offset ${nulAt} — binary payloads are refused.`,
+ 'Capture takes text/markdown; upload binaries through the files lane on the host.');
+ }
+ const normalized = normalizeForHash(content);
+ if (normalized.length === 0) {
+ throw new OperationError('invalid_params', 'Refusing to capture empty content.');
+ }
+ const type = typeof p.type === 'string' && p.type.length > 0 ? p.type : 'note';
+ let slug = typeof p.slug === 'string' && p.slug.length > 0 ? p.slug : undefined;
+ if (slug) {
+ // Defense-in-depth on the caller-supplied slug (matches the takes ops);
+ // put_page validates again, but reject a malformed slug before we build
+ // provenance frontmatter around it.
+ validatePageSlug(slug);
+ } else {
+ slug = defaultSlug(normalized, new Date(), type);
+ // [EV7] A slug-bound client would 403 on the inbox/ default via the
+ // inherited slug fence — the zero-config path must work for exactly
+ // that audience, so the ENTIRE default slug (type prefix included —
+ // diary/event prefixes are two segments) nests under the FIRST bound
+ // prefix. Normalize a stored `<prefix>/*` glob (submit_agent binding
+ // grammar) to `<prefix>/` first so the nested slug never carries a
+ // literal `*` segment.
+ const bound = ctx.auth?.boundSlugPrefixes;
+ if (bound && bound.length > 0) {
+ const base = normalizeSlugPrefix(bound[0]);
+ const prefix = base.endsWith('/') ? base : `${base}/`;
+ slug = `${prefix}${slug}`;
+ }
+ }
+ // Remote MCP captures record `capture-mcp` provenance; local CLI callers
+ // (ctx.remote === false) keep the neutral 'capture-cli' default.
+ const capturedVia = ctx.remote !== false ? 'capture-mcp' : undefined;
+ const fullContent = mergeCaptureFrontmatter(content, { type, capturedVia });
+ if (ctx.dryRun) return { dry_run: true, action: 'capture', slug };
+ // Delegate with the SAME ctx (the runCapture local-path precedent) —
+ // put_page enforces the slug fence, validates the slug, dedupes, and
+ // server-stamps provenance for remote callers.
+ const result = await put_page.handler(ctx, { slug, content: fullContent }) as Record<string, unknown>;
+ return {
+ ...result,
+ slug,
+ channel: 'capture',
+ content_hash: computeContentHash(normalized),
+ dedupe: 'identical normalized content produces the same default slug and hash',
+ };
+ },
+};
+
// (Page CRUD quartet first, then the v0.26.5 destructive-guard ops:
-// page-level soft-delete recovery + admin purge).
+// page-level soft-delete recovery + admin purge, then capture.)
export const pagesOperations: Operation[] = [
get_page, put_page, delete_page, list_pages,
- restore_page, purge_deleted_pages,
+ restore_page, purge_deleted_pages, capture,
];
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index 94d2170f0b..6d2a69d303 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -58,10 +58,14 @@ function firstSentenceOf(description: string): string {
* persist level), minus localOnly on network transports (stdio and the
* trusted local CLI keep them — D7), minus ops outside the caller's scopes
* (agent-callable carve-out per FOV-4), minus bound-client-fenced ops (same
- * predicate as tools/list, ENG-3), minus publish-gated ops whose gate is off
- * (stdio and the trusted local CLI bypass gates — the D7 local-surface
- * posture, matching assertPublishEnabled's remote===false exemption; a
- * failed gate read hides the gated ops, fail-closed).
+ * predicate as tools/list, ENG-3), minus publish-gated ops whose gate is off.
+ * Two DISTINCT caller axes here: localOnly visibility is the transport-
+ * LOCALITY axis (stdio pipe or trusted local CLI can call localOnly ops, D7),
+ * while publish gates are the owner-CONSENT axis and exempt ONLY
+ * ctx.remote === false (assertPublishEnabled + the advisor inline gate) —
+ * stdio dispatches remote:true, so its catalog subtracts gate-off ops or it
+ * advertises tools that deny at call time. A failed gate read hides the gated
+ * ops, fail-closed.
*/
async function visibleOpsForCaller(
ctx: OperationContext,
@@ -73,13 +77,15 @@ async function visibleOpsForCaller(
// runs, operations.ts has finished evaluating.
const { operations } = await import('../operations.ts');
const { filterOpsForSurface } = await import('../../mcp/surface.ts');
- // Trusted local callers: the stdio pipe, or the local CLI (remote is
- // strictly false — the fail-closed trust marker). Both CAN call localOnly
- // and gated ops, so hiding them would make the catalog dishonest.
- const isLocal = ctx.transport === 'stdio' || ctx.remote === false;
+ // Locality axis: the stdio pipe or the local CLI (remote strictly false)
+ // CAN call localOnly ops, so hiding those would make the catalog dishonest.
+ const canSeeLocalOnly = ctx.transport === 'stdio' || ctx.remote === false;
+ // Consent axis: publish-gate enforcement exempts ONLY remote === false —
+ // stdio is remote:true, so it is gate-subject like every other agent caller.
+ const gateExempt = ctx.remote === false;
let gateDisabled: ReadonlySet<string> = new Set();
- if (!isLocal) {
+ if (!gateExempt) {
try {
const { disabledOpsForPublishGates } = await import('../../mcp/publish-gates.ts');
gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);
@@ -96,7 +102,7 @@ async function visibleOpsForCaller(
const scopes = ctx.auth?.scopes && ctx.auth.scopes.length > 0 ? ctx.auth.scopes : null;
return filterOpsForSurface(operations, ceiling).filter(op =>
- (isLocal || !op.localOnly)
+ (canSeeLocalOnly || !op.localOnly)
&& (scopes === null
|| hasScope(scopes, op.scope ?? 'read')
|| (op.agentCallable === true && hasScope(scopes, 'agent')))
diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.ts
index d21ece94d7..79c7338cbd 100644
--- a/src/core/ops/salience.ts
+++ b/src/core/ops/salience.ts
@@ -51,7 +51,9 @@ const get_recent_salience: Operation = {
recency_bias: recencyBias,
});
},
- cliHints: { name: 'salience' },
+ // hidden: 'salience' is in CLI_ONLY (src/cli.ts) — runSalience owns the CLI
+ // surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).
+ cliHints: { name: 'salience', hidden: true },
};
const find_anomalies: Operation = {
@@ -79,7 +81,9 @@ const find_anomalies: Operation = {
sigma: typeof p.sigma === 'number' ? p.sigma : undefined,
});
},
- cliHints: { name: 'anomalies' },
+ // hidden: 'anomalies' is in CLI_ONLY (src/cli.ts) — runAnomalies owns the
+ // CLI surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).
+ cliHints: { name: 'anomalies', hidden: true },
};
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 8710923c32..973ba7ba56 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -370,5 +370,117 @@ const query: Operation = {
};
+// ---------------------------------------------------------------------------
+// CLI→MCP gap-closure wave — search/cache introspection ops. Read-only views
+// shared with the `gbrain search modes|stats|tune` + `gbrain cache stats` CLI
+// (the builders live in core/search/). User story for each: a thin-client
+// user whose CLI routes these subcommands remotely, or an agent asked to
+// diagnose retrieval quality/cost. Telemetry ops are admin-scoped
+// (operational counters, the get_status_snapshot posture); search_modes is
+// read-scoped (resolved knob values only — agents budget their own calls
+// with it, no usage data).
+// ---------------------------------------------------------------------------
+
+const search_stats: Operation = {
+ name: 'search_stats',
+ description:
+ 'Search observability over a window: cache hit rate, intent/mode mix, budget drops, ' +
+ 'rank-1 score drift, graph-signals failure counts. Same payload as the search-stats ' +
+ 'dashboard JSON. Coverage caveat: telemetry is best-effort (short-lived CLI calls may ' +
+ 'not flush), so zero counts can reflect the coverage gap rather than zero usage.',
+ params: {
+ days: { type: 'number', required: false, description: 'Window in days (default 7, clamped 1..365).' },
+ },
+ scope: 'admin',
+ area: 'search',
+ handler: async (ctx, p) => {
+ const { withRelationGuard } = await import('./contract.ts');
+ return withRelationGuard(async () => {
+ const { readSearchStats, readGraphSignalsStats, telemetryCoverage } = await import('../search/telemetry.ts');
+ const rawDays = typeof p.days === 'number' && Number.isFinite(p.days) ? p.days : 7;
+ const days = Math.max(1, Math.min(365, rawDays));
+ const stats = await readSearchStats(ctx.engine, { days });
+ const graph_signals = await readGraphSignalsStats(ctx.engine, days);
+ return {
+ schema_version: 2,
+ ...stats,
+ coverage: telemetryCoverage(),
+ graph_signals,
+ _meta: {
+ metric_glossary: {
+ cache_hit_rate: 'cache_hits / (cache_hits + cache_misses) — fraction of searches that reused a recent answer instead of running fresh',
+ avg_results: 'mean number of result rows returned per search call',
+ avg_tokens: 'mean estimated tokens in the returned chunk text (char/4 heuristic)',
+ total_budget_dropped: 'sum of results dropped because the call exceeded its tokenBudget',
+ graph_signals_enabled: 'whether graph_signals is on for the active mode (or via search.graph_signals override)',
+ graph_signals_failures_count: 'count of fail-open events in the JSONL audit over the window',
+ },
+ },
+ };
+ }, 'Search telemetry');
+ },
+};
+
+const search_modes: Operation = {
+ name: 'search_modes',
+ description:
+ 'Read-only search-mode dashboard: active mode, per-knob resolved value with attribution ' +
+ '(mode default vs config override), and the three frozen bundles. Never mutates; to ' +
+ 'change modes, tell the user to set the search.mode config key on the brain host.',
+ params: {},
+ scope: 'read',
+ area: 'search',
+ handler: async (ctx) => {
+ const { buildModesReport } = await import('../search/modes-report.ts');
+ return buildModesReport(ctx.engine);
+ },
+};
+
+const search_tune: Operation = {
+ name: 'search_tune',
+ description:
+ 'Read-only tuning recommendations derived from the last 7 days of search telemetry: ' +
+ 'what should change, why, and the paste-ready config command per recommendation — relay ' +
+ 'them to the user. Applying is CLI-only by design [CDX-21]: this op NEVER mutates config.',
+ params: {},
+ scope: 'admin',
+ area: 'search',
+ handler: async (ctx) => {
+ const { withRelationGuard } = await import('./contract.ts');
+ return withRelationGuard(async () => {
+ const { buildTuneRecommendations } = await import('../search/tune-recommendations.ts');
+ return buildTuneRecommendations(ctx.engine);
+ }, 'Search telemetry');
+ },
+};
+
+const cache_stats: Operation = {
+ name: 'cache_stats',
+ description:
+ 'Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) ' +
+ 'plus row counts and total hits. Read-only; clearing/pruning the cache stays on the CLI.',
+ params: {},
+ scope: 'admin',
+ area: 'search',
+ handler: async (ctx) => {
+ const { withRelationGuard } = await import('./contract.ts');
+ return withRelationGuard(async () => {
+ const { SemanticQueryCache, loadCacheConfig } = await import('../search/query-cache.ts');
+ const config = await loadCacheConfig(ctx.engine);
+ const cache = new SemanticQueryCache(ctx.engine, config);
+ const stats = await cache.stats();
+ return {
+ schema_version: 1,
+ enabled: config.enabled ?? true,
+ similarity_threshold: config.similarityThreshold,
+ ttl_seconds: config.ttlSeconds,
+ ...stats,
+ };
+ }, 'Query-cache statistics');
+ },
+};
+
// Ops in EXACTLY the canonical `operations` array order.
-export const searchOperations: Operation[] = [search, query];
+export const searchOperations: Operation[] = [
+ search, query, search_stats, search_modes, search_tune, cache_stats,
+];
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 2d856aa9fc..19f69cd0db 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -5,8 +5,21 @@
* in ../operations.ts. Never import from '../operations.ts' here (cycle).
*/
-import type { Operation } from './contract.ts';
-import { sourceScopeOpts, thinkSourceScopeOpts } from './context.ts';
+import { OperationError, type Operation, type OperationContext } from './contract.ts';
+import {
+ sourceScopeOpts,
+ thinkSourceScopeOpts,
+ enforceClientSlugFence,
+ validatePageSlug,
+} from './context.ts';
+import {
+ addTakeToPage,
+ updateTakeOnPage,
+ supersedeTakeOnPage,
+ resolveTakeOnPage,
+ resolveTakesRepoDir,
+ TakesWriteError,
+} from '../takes-write.ts';
// --- v0.28: Takes ---
@@ -81,7 +94,7 @@ const takes_scorecard: Operation = {
until: { type: 'string', description: 'Window end (YYYY-MM-DD)' },
},
handler: async (ctx, p) => {
- return ctx.engine.getScorecard(
+ const card = await ctx.engine.getScorecard(
{
...sourceScopeOpts(ctx),
holder: p.holder as string | undefined,
@@ -91,6 +104,13 @@ const takes_scorecard: Operation = {
},
ctx.takesHoldersAllowList,
);
+ // [OV8/EV5] Resolver-provenance visibility: remote resolutions are
+ // server-stamped resolved_by='mcp:<client>' (takes_resolve below), and
+ // this coarse count keeps agent-resolved rows segregable from owner
+ // ground truth. Op-layer SQL (plain executeRaw both engines share) —
+ // no engine method added, parity untouched. Unfiltered by the window/
+ // domain params (coarse by design; documented).
+ return { ...card, mcp_resolved: await countMcpResolved(ctx) };
},
cliHints: { name: 'takes-scorecard' },
};
@@ -108,6 +128,9 @@ const takes_calibration: Operation = {
bucket_size: { type: 'number', description: 'Bucket width in (0,1]; default 0.1' },
},
handler: async (ctx, p) => {
+ // (The [OV8/EV5] mcp_resolved provenance count lives on takes_scorecard —
+ // this op's wire shape is a bare bucket ARRAY, so decorating it would be
+ // a breaking change; the scorecard is the segregation surface.)
return ctx.engine.getCalibrationCurve(
{
...sourceScopeOpts(ctx),
@@ -120,6 +143,39 @@ const takes_calibration: Operation = {
cliHints: { name: 'takes-calibration' },
};
+/**
+ * [OV8/EV5] Count of resolved take rows whose resolved_by carries the MCP
+ * server-stamp prefix. Source-scoped + holder-allow-list-scoped like the
+ * aggregates it decorates; unfiltered by window/domain (coarse segregation
+ * signal, not a scorecard dimension).
+ */
+async function countMcpResolved(ctx: OperationContext): Promise<number> {
+ const scope = sourceScopeOpts(ctx);
+ const where: string[] = [`t.resolved_at IS NOT NULL`, `t.resolved_by LIKE 'mcp:%'`];
+ const params: unknown[] = [];
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ params.push(scope.sourceIds);
+ where.push(`p.source_id = ANY($${params.length}::text[])`);
+ } else if (scope.sourceId) {
+ params.push(scope.sourceId);
+ where.push(`p.source_id = $${params.length}`);
+ }
+ if (ctx.takesHoldersAllowList) {
+ params.push(ctx.takesHoldersAllowList);
+ where.push(`t.holder = ANY($${params.length}::text[])`);
+ }
+ try {
+ const rows = await ctx.engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM takes t JOIN pages p ON p.id = t.page_id WHERE ${where.join(' AND ')}`,
+ params,
+ );
+ return parseInt(rows[0]?.n ?? '0', 10);
+ } catch {
+ // Decoration only — never fail the aggregate over the provenance count.
+ return 0;
+ }
+}
+
const think: Operation = {
name: 'think',
description: 'Multi-hop synthesis across pages + takes + graph. Pulls relevant evidence and produces a cited answer with conflict + gap analysis.',
@@ -187,13 +243,310 @@ const think: Operation = {
remote_persisted_blocked: remote && (Boolean(p.save) || Boolean(p.take)),
};
},
- cliHints: { name: 'think', positional: ['question'] },
+ // hidden: 'think' is in CLI_ONLY (src/cli.ts) — the richer runThinkCli
+ // handler owns the CLI surface; a non-hidden hint here is dead (CLI_ONLY
+ // wins at dispatch) and lies to the catalog.
+ cliHints: { name: 'think', positional: ['question'], hidden: true },
+};
+
+
+// ---------------------------------------------------------------------------
+// CLI→MCP gap-closure wave — takes WRITE verbs. Before these, agents could
+// read the predictions ledger (takes_list/search/scorecard) but never record,
+// refine, resolve, or supersede a take. Backed by the same md-canonical
+// write-through core as the CLI (src/core/takes-write.ts): fence-derived row
+// numbers, markdown written first, the DB mirrored with the reconcile
+// primitive — and the markdown write is REQUIRED (no sync.repo_path on the
+// host → 'unavailable' with detail takes_mirror_unavailable), because a
+// DB-only row would be clobbered by the next md→DB reconcile.
+//
+// Trust model (ungated by design — the put_page precedent: writes are
+// consented via scope + the holder fence; publish gates cover owner-content
+// READ surfaces):
+// - Holder WRITE fence reuses the read allow-list, fail-closed: remote
+// effective list = ctx.takesHoldersAllowList ?? ['world'] (the stdio
+// default — stdio agents write world-held takes only; OAuth tokens can
+// grant more), [] = deny-all. add/supersede check the param holder;
+// update/resolve/supersede check the TARGET row's holder — and a fenced
+// row presents as not_found (same shape as a missing row), hiding content
+// and holder. Existence-by-count is accepted: row numbers are dense per
+// page, so takes_add's returned row_num reveals how many rows (including
+// private ones) exist — returning it is functionally required for later
+// update/resolve, and takes_list's visible-sequence gaps leak the same
+// count anyway [OV10/EV3].
+// - resolved_by is SERVER-STAMPED for remote callers (mcp:<clientId>) so
+// agent-resolved rows stay segregable from owner-resolved ground truth;
+// scorecard/calibration surface the mcp_resolved count [OV8/EV5].
+// - A future permissions.takes_write_holders key could split the read/write
+// axes if field use demands it.
+// ---------------------------------------------------------------------------
+
+const TAKE_KINDS = ['fact', 'take', 'bet', 'hunch'] as const;
+/** Ops hold the MCP request at most this long waiting for the page lock. */
+const OP_LOCK_TIMEOUT_MS = 2000;
+
+/** Remote callers get the read allow-list as the WRITE fence; local CLI is unfenced. */
+function takesWriteAllowList(ctx: OperationContext): readonly string[] | null {
+ return ctx.remote !== false ? (ctx.takesHoldersAllowList ?? ['world']) : null;
+}
+
+async function opBrainDir(ctx: OperationContext): Promise<string> {
+ const dir = await resolveTakesRepoDir(ctx.engine);
+ if (!dir) {
+ const err = new OperationError(
+ 'unavailable',
+ 'Takes are markdown-canonical and this brain has no writable markdown repo configured.',
+ 'Configure sync.repo_path on the brain host, then retry.',
+ );
+ err.detail = 'takes_mirror_unavailable';
+ throw err;
+ }
+ return dir;
+}
+
+function mapTakesWriteError(err: unknown): never {
+ if (err instanceof TakesWriteError) {
+ switch (err.code) {
+ case 'page_not_found':
+ throw new OperationError('page_not_found', err.message, 'Sync the brain first, or check the slug/source.');
+ case 'row_not_found':
+ // Fenced rows deliberately share this shape (no-existence-leak of
+ // content/holder — see the trust-model comment above).
+ throw new OperationError('not_found', err.message);
+ case 'holder_denied': {
+ const e = new OperationError('permission_denied', err.message,
+ "Ask the brain owner to widen this caller's takes-holder allow-list.");
+ e.detail = 'holder_not_in_allowlist';
+ throw e;
+ }
+ case 'mirror_unavailable': {
+ const e = new OperationError('unavailable', err.message,
+ 'Configure sync.repo_path on the brain host, then retry.');
+ e.detail = 'takes_mirror_unavailable';
+ throw e;
+ }
+ case 'page_locked': {
+ const e = new OperationError('unavailable', err.message, 'Retry shortly.');
+ e.detail = 'retryable';
+ throw e;
+ }
+ case 'already_resolved':
+ throw new OperationError('invalid_params', err.message, err.hint ?? 'Resolved takes are immutable; supersede instead.');
+ case 'fence_unparsed':
+ case 'row_inactive':
+ case 'no_fields':
+ case 'invalid_input':
+ throw new OperationError('invalid_params', err.message, err.hint);
+ }
+ }
+ throw err;
+}
+
+/**
+ * P1-4/F4: the markdown write already succeeded; a non-empty `mirror_warning`
+ * means only the DB mirror deferred to the next reconcile. Surface it so the
+ * agent knows the durable row is on disk and MUST NOT retry.
+ */
+function mirrorWarnFields(mirror: { mirror_warning?: string }): Record<string, string> {
+ return mirror.mirror_warning
+ ? { mirror_warning: `row written to markdown; DB mirror deferred to reconcile: ${mirror.mirror_warning}` }
+ : {};
+}
+
+const takes_add: Operation = {
+ name: 'takes_add',
+ description:
+ 'Record a take (typed claim) on a page: fact / take / bet / hunch, with a holder (who ' +
+ 'holds the belief: world, people/<slug>, companies/<slug>, or brain), weight 0..1, and ' +
+ 'optional source/since date. Writes the markdown takes fence first (markdown is ' +
+ 'canonical) and mirrors to the DB. Remote callers can only write holders in their ' +
+ 'allow-list (stdio default: world).',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug to attach the take to (page must exist).' },
+ claim: { type: 'string', required: true, description: 'The claim text (one line).' },
+ kind: { type: 'string', required: true, enum: [...TAKE_KINDS], description: 'Claim type. Base kinds only; pack-extended kinds are a filed follow-up.' },
+ holder: { type: 'string', required: true, description: "Who HOLDS this belief (said/clearly implied it): world | people/<slug> | companies/<slug> | brain. Remote callers: must be in the caller's takes-holder allow-list." },
+ weight: { type: 'number', required: false, description: 'Confidence 0..1 (default 0.5; clamped server-side).' },
+ source: { type: 'string', required: false, description: 'Where the claim came from (free text).' },
+ since: { type: 'string', required: false, description: "When the belief started ('YYYY-MM' or 'YYYY-MM-DD')." },
+ },
+ scope: 'write',
+ mutating: true,
+ area: 'takes',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'takes_add');
+ validatePageSlug(slug); // defense-in-depth, matching put_page
+ if (ctx.dryRun) return { dry_run: true, action: 'takes_add', slug };
+ const brainDir = await opBrainDir(ctx);
+ try {
+ const { rowNum, mirror } = await addTakeToPage(
+ { engine: ctx.engine, slug, brainDir, sourceId: ctx.sourceId, allowList: takesWriteAllowList(ctx), lockTimeoutMs: OP_LOCK_TIMEOUT_MS },
+ {
+ claim: p.claim as string,
+ kind: p.kind as string,
+ holder: p.holder as string,
+ weight: p.weight as number | undefined,
+ source: p.source as string | undefined,
+ sinceDate: p.since as string | undefined,
+ },
+ );
+ return { slug, row_num: rowNum, holder: p.holder, mirror_written: true, ...mirrorWarnFields(mirror) };
+ } catch (err) {
+ mapTakesWriteError(err);
+ }
+ },
};
+const takes_update: Operation = {
+ name: 'takes_update',
+ description:
+ 'Update a take\'s mutable fields (weight, source, since date). Claim/kind/holder are ' +
+ 'immutable — supersede instead. Markdown-canonical: the target row must exist in the ' +
+ 'page\'s takes fence. Remote callers can only touch rows whose holder is in their ' +
+ 'allow-list; other rows present as not_found.',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug.' },
+ row_num: { type: 'number', required: true, description: 'Take row number on the page (from takes_list).' },
+ weight: { type: 'number', required: false, description: 'New confidence 0..1.' },
+ source: { type: 'string', required: false, description: 'New source text.' },
+ since: { type: 'string', required: false, description: "New since date ('YYYY-MM' or 'YYYY-MM-DD')." },
+ },
+ scope: 'write',
+ mutating: true,
+ area: 'takes',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'takes_update');
+ validatePageSlug(slug); // defense-in-depth, matching put_page
+ if (ctx.dryRun) return { dry_run: true, action: 'takes_update', slug, row_num: p.row_num };
+ const brainDir = await opBrainDir(ctx);
+ try {
+ const { rowNum, mirror } = await updateTakeOnPage(
+ { engine: ctx.engine, slug, brainDir, sourceId: ctx.sourceId, allowList: takesWriteAllowList(ctx), lockTimeoutMs: OP_LOCK_TIMEOUT_MS },
+ p.row_num as number,
+ {
+ weight: p.weight as number | undefined,
+ source: p.source as string | undefined,
+ sinceDate: p.since as string | undefined,
+ },
+ );
+ return { slug, row_num: rowNum, updated: true, ...mirrorWarnFields(mirror) };
+ } catch (err) {
+ mapTakesWriteError(err);
+ }
+ },
+};
+
+const takes_supersede: Operation = {
+ name: 'takes_supersede',
+ description:
+ 'Supersede a take with a replacement claim: the old row is struck through (kept for ' +
+ 'archaeology), the replacement appends at the next fence row number. Kind/holder inherit ' +
+ 'from the target row unless overridden; unset weight decays the target\'s by 0.1. ' +
+ 'Markdown-canonical; remote holder fencing as in takes_update.',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug.' },
+ row_num: { type: 'number', required: true, description: 'Row number of the take being superseded.' },
+ claim: { type: 'string', required: true, description: 'The replacement claim text.' },
+ kind: { type: 'string', required: false, enum: [...TAKE_KINDS], description: 'Override kind (default: inherit from the target row).' },
+ holder: { type: 'string', required: false, description: 'Override holder (default: inherit). Remote callers: an override must be in the allow-list.' },
+ weight: { type: 'number', required: false, description: "Replacement confidence 0..1 (default: target's weight - 0.1)." },
+ source: { type: 'string', required: false, description: 'Source for the replacement.' },
+ since: { type: 'string', required: false, description: 'Since date for the replacement.' },
+ },
+ scope: 'write',
+ mutating: true,
+ area: 'takes',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'takes_supersede');
+ validatePageSlug(slug); // defense-in-depth, matching put_page
+ if (ctx.dryRun) return { dry_run: true, action: 'takes_supersede', slug, row_num: p.row_num };
+ const brainDir = await opBrainDir(ctx);
+ try {
+ const { oldRow, newRow, mirror } = await supersedeTakeOnPage(
+ { engine: ctx.engine, slug, brainDir, sourceId: ctx.sourceId, allowList: takesWriteAllowList(ctx), lockTimeoutMs: OP_LOCK_TIMEOUT_MS },
+ p.row_num as number,
+ {
+ claim: p.claim as string,
+ kind: p.kind as string | undefined,
+ holder: p.holder as string | undefined,
+ weight: p.weight as number | undefined,
+ source: p.source as string | undefined,
+ sinceDate: p.since as string | undefined,
+ },
+ );
+ return { slug, old_row: oldRow, new_row: newRow, ...mirrorWarnFields(mirror) };
+ } catch (err) {
+ mapTakesWriteError(err);
+ }
+ },
+};
+
+const takes_resolve: Operation = {
+ name: 'takes_resolve',
+ description:
+ 'Resolve a take: quality correct / incorrect / partial / unresolvable, with optional ' +
+ 'evidence text and measured value/unit. Resolutions feed the calibration scorecard. ' +
+ 'Remote callers: resolved_by is SERVER-STAMPED as mcp:<client> (any passed value is ' +
+ 'ignored) so agent resolutions stay segregable from owner ground truth; the target row ' +
+ 'must be in the caller\'s holder allow-list. Markdown-canonical.',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug.' },
+ row_num: { type: 'number', required: true, description: 'Take row number to resolve.' },
+ quality: { type: 'string', required: true, enum: ['correct', 'incorrect', 'partial', 'unresolvable'], description: 'Resolution verdict.' },
+ evidence: { type: 'string', required: false, description: 'What evidence resolved this (free text).' },
+ value: { type: 'number', required: false, description: 'Measured value, when the claim was quantitative.' },
+ unit: { type: 'string', required: false, description: 'Unit for value (usd | pct | count | ...).' },
+ resolved_by: { type: 'string', required: false, description: 'Resolver identity. Remote callers: SERVER-STAMPED mcp:<client>, client value ignored. Local default: the configured owner holder.' },
+ },
+ scope: 'write',
+ mutating: true,
+ area: 'takes',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'takes_resolve');
+ validatePageSlug(slug); // defense-in-depth, matching put_page
+ if (ctx.dryRun) return { dry_run: true, action: 'takes_resolve', slug, row_num: p.row_num };
+ const brainDir = await opBrainDir(ctx);
+ // CV6 posture: remote resolutions are provenance-stamped server-side —
+ // clamp + sanitize the client id: hostile DCR client names must not carry
+ // newlines/pipes into the markdown fence, and must not bloat the column.
+ let resolvedBy: string;
+ if (ctx.remote !== false) {
+ const id = (ctx.auth?.clientId ?? ctx.transport ?? 'remote').replace(/[^\w.:-]/g, '_').slice(0, 64);
+ resolvedBy = `mcp:${id}`;
+ } else if (typeof p.resolved_by === 'string' && p.resolved_by.length > 0) {
+ resolvedBy = p.resolved_by;
+ } else {
+ const { resolveOwnerHolder } = await import('../owner-holder.ts');
+ resolvedBy = resolveOwnerHolder({ configValue: await ctx.engine.getConfig('emotional_weight.user_holder') });
+ }
+ try {
+ const { rowNum, quality, mirror } = await resolveTakeOnPage(
+ { engine: ctx.engine, slug, brainDir, sourceId: ctx.sourceId, allowList: takesWriteAllowList(ctx), lockTimeoutMs: OP_LOCK_TIMEOUT_MS },
+ p.row_num as number,
+ {
+ quality: p.quality as 'correct' | 'incorrect' | 'partial' | 'unresolvable',
+ evidence: p.evidence as string | undefined,
+ value: p.value as number | undefined,
+ unit: p.unit as string | undefined,
+ resolvedBy,
+ },
+ );
+ return { slug, row_num: rowNum, quality, resolved_by: resolvedBy, ...mirrorWarnFields(mirror) };
+ } catch (err) {
+ mapTakesWriteError(err);
+ }
+ },
+};
// Ops in EXACTLY the canonical `operations` array order: the v0.28 trio
-// (takes_list, takes_search, think), then the v0.30 calibration aggregates.
+// (takes_list, takes_search, think), the v0.30 calibration aggregates, then
+// the gap-closure write verbs.
export const takesOperations: Operation[] = [
takes_list, takes_search, think,
takes_scorecard, takes_calibration,
+ takes_add, takes_update, takes_resolve, takes_supersede,
];
diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.ts
new file mode 100644
index 0000000000..dce47e9bf9
--- /dev/null
+++ b/src/core/search/modes-report.ts
@@ -0,0 +1,108 @@
+/**
+ * Read-only search-mode dashboard builder — moved from src/commands/search.ts
+ * in the CLI→MCP gap-closure wave so the `search_modes` op and the CLI render
+ * the same report. Pure reads: never mutates config (the `modes --reset` lane
+ * stays in the command file).
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import {
+ MODE_BUNDLES,
+ SEARCH_MODE_CONFIG_KEYS,
+ loadSearchModeConfig,
+ resolveSearchMode,
+ attributeKnob,
+ type SearchMode,
+ type ModeBundle,
+} from './mode.ts';
+
+export const KNOB_DESCRIPTIONS: Record<keyof ModeBundle, string> = {
+ cache_enabled: 'Semantic query cache on/off',
+ cache_similarity_threshold: 'Cosine-similarity floor for cache hits (0..1)',
+ cache_ttl_seconds: 'Per-row cache TTL',
+ intentWeighting: 'Zero-LLM intent classifier weight adjustments',
+ tokenBudget: 'Per-call token-budget cap (undefined = no cap)',
+ expansion: 'LLM multi-query expansion (Haiku call per search)',
+ searchLimit: 'Default `limit` for the operation layer',
+ reranker_enabled: 'Cross-encoder reranker on/off',
+ reranker_model: 'Provider:model for the reranker',
+ reranker_top_n_in: 'Candidates sent to reranker per call',
+ reranker_top_n_out: 'Cap on reranked output (null = no truncate)',
+ reranker_timeout_ms: 'HTTP timeout for the reranker call',
+ floor_ratio: 'Floor-ratio gate for metadata boosts (0..1, undefined = off)',
+ title_boost: 'Title-phrase boost multiplier (query is a title token-run; 1.0 = off)',
+ // v0.36 cross-modal knobs (D3 registry)
+ cross_modal_both_text_weight: "D6 'both'-mode RRF weight for text branch (0.6 default)",
+ cross_modal_both_image_weight: "D6 'both'-mode RRF weight for image branch (0.4 default)",
+ image_query_text_refinement_weight: 'D13 searchByImage text-refinement RRF weight (0.4 default)',
+ image_query_image_refinement_weight: 'D13 searchByImage image branch RRF weight (0.6 default)',
+ unified_multimodal: 'Phase 3 — route all queries through embedding_multimodal column',
+ unified_multimodal_only: 'Phase 3 strict — bypass dual-column fallback when unified is on',
+ cross_modal_llm_intent: 'Commit 4 — Haiku tie-break for ambiguous modality classification',
+ // v0.40.4 graph signals
+ graph_signals: 'Selective graph signals: adjacency hub + cross-source hub + session diversification',
+ // v0.40.3.0 contextual retrieval
+ contextual_retrieval: 'CR tier (none|title|per_chunk_synopsis) — wraps chunks at embed time',
+ contextual_retrieval_disabled: 'Soft kill switch — neutralizes CR wrapping for queries + new embeds',
+ // v0.42.3.0 autocut
+ autocut: 'Score-discontinuity result-sizing (cuts at the rerank-score cliff; no-op without a reranker)',
+ autocut_jump: 'Autocut sensitivity: min normalized score gap that counts as a cliff (0..1, 0.20 default)',
+ // v0.43 relational recall
+ relationalRetrieval: 'Typed-edge relational recall arm (relational queries walk the graph; no-op otherwise)',
+ relational_retrieval_depth: 'Max hops for relational traversal (1..3, 2 default)',
+};
+
+export interface SearchModesReport {
+ schema_version: 2;
+ active_mode: SearchMode;
+ active_mode_valid: boolean;
+ resolved: Record<keyof ModeBundle, { value: unknown; source: string; source_detail: string; description: string }>;
+ bundles: Record<SearchMode, ModeBundle>;
+ config_keys: ReadonlyArray<string>;
+ _meta?: {
+ metric_glossary?: Record<string, string>;
+ };
+}
+
+export async function buildModesReport(engine: BrainEngine): Promise<SearchModesReport> {
+ const input = await loadSearchModeConfig(engine);
+ const resolved = resolveSearchMode(input);
+
+ const knobs: Array<keyof ModeBundle> = [
+ 'cache_enabled',
+ 'cache_similarity_threshold',
+ 'cache_ttl_seconds',
+ 'intentWeighting',
+ 'tokenBudget',
+ 'expansion',
+ 'searchLimit',
+ // v0.35.6.0 — floor-ratio surfaced in `gbrain search modes` dashboard
+ // so config drift is legible. Default undefined renders as 'undefined'
+ // in the bundle column, 'mode' source when unset by config/per-call.
+ 'floor_ratio',
+ ];
+
+ const attributions = {} as SearchModesReport['resolved'];
+ for (const k of knobs) {
+ const a = attributeKnob(k, input, resolved);
+ attributions[k] = {
+ value: a.value,
+ source: a.source,
+ source_detail: a.source_detail,
+ description: KNOB_DESCRIPTIONS[k],
+ };
+ }
+
+ return {
+ schema_version: 2,
+ active_mode: resolved.resolved_mode,
+ active_mode_valid: resolved.mode_valid,
+ resolved: attributions,
+ bundles: {
+ conservative: { ...MODE_BUNDLES.conservative },
+ balanced: { ...MODE_BUNDLES.balanced },
+ tokenmax: { ...MODE_BUNDLES.tokenmax },
+ },
+ config_keys: SEARCH_MODE_CONFIG_KEYS,
+ };
+}
diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.ts
index bef0095619..db0215a7d3 100644
--- a/src/core/search/query-cache.ts
+++ b/src/core/search/query-cache.ts
@@ -328,6 +328,10 @@ export class SemanticQueryCache {
);
return rows[0] ?? { total_rows: 0, total_hits: 0, fresh_rows: 0, stale_rows: 0 };
} catch {
+ // Best-effort by design (parity with readSearchStats): a brain without
+ // the cache table shows all-zero, not a crash. cache_stats wraps this in
+ // withRelationGuard for other unexpected relation errors; the
+ // missing-cache-table case stays gracefully empty.
return { total_rows: 0, total_hits: 0, fresh_rows: 0, stale_rows: 0 };
}
}
diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.ts
index 531c1fe04d..7e71c8c66e 100644
--- a/src/core/search/telemetry.ts
+++ b/src/core/search/telemetry.ts
@@ -496,7 +496,14 @@ export async function readSearchStats(
empty_results: { total: empty_total, by_cause: empty_by_cause },
};
} catch {
- // Table missing or query failed — return empty stats rather than throw.
+ // Best-effort by design: a pre-v0.32.3 brain WITHOUT the search_telemetry
+ // table shows "0 searches" (with the coverage caveat explaining low/zero
+ // counts), NOT a crash — a long-standing contract pinned by
+ // test/search-telemetry.test.ts and relied on by the CLI dashboard. The
+ // search_stats op wraps this in withRelationGuard for OTHER unexpected
+ // relation errors, but the missing-telemetry-table case is intentionally
+ // graceful, not 'unavailable'. (Reverted an over-eager gap-closure rethrow
+ // that broke this contract for the CLI + dashboard to satisfy a P2 finding.)
return {
total_calls: 0,
cache_hits: 0,
@@ -571,3 +578,59 @@ export function _resetTelemetryWriterForTest(): void {
_writer = null;
}
}
+
+// ---------------------------------------------------------------------------
+// v0.40.4 graph-signals observability (moved from src/commands/search.ts in
+// the CLI→MCP gap-closure wave so the `search_stats` op and the CLI share it).
+// ---------------------------------------------------------------------------
+
+export interface GraphSignalsStatsSection {
+ enabled: boolean;
+ source: 'config' | 'mode_default';
+ failures_count: number;
+ /** Failure-reason breakdown across the window (truncated to top reasons). */
+ failures_by_reason: Record<string, number>;
+}
+
+export async function readGraphSignalsStats(engine: BrainEngine, days: number): Promise<GraphSignalsStatsSection> {
+ // Resolve graph_signals on/off. Mirrors the resolution chain in
+ // src/commands/doctor/checks/graph-embedding.ts:checkGraphSignalsCoverage.
+ // v0.40.4 codex F1: case-insensitive + trim parity with
+ // loadOverridesFromConfig (mode.ts). Without this, search-stats would
+ // silently report the opposite of what the parser actually enables on
+ // values like 'TRUE' or 'True'.
+ const cfg = await engine.getConfig('search.graph_signals').catch(() => null);
+ let enabled: boolean;
+ let source: 'config' | 'mode_default';
+ if (cfg !== null && cfg !== undefined) {
+ const v = cfg.trim().toLowerCase();
+ enabled = v === 'true' || v === '1';
+ source = 'config';
+ } else {
+ const modeRaw = await engine.getConfig('search.mode').catch(() => null);
+ const modeVal = typeof modeRaw === 'string' ? modeRaw.trim().toLowerCase() : '';
+ const mode = modeVal === 'conservative' || modeVal === 'tokenmax' ? modeVal : 'balanced';
+ enabled = mode !== 'conservative';
+ source = 'mode_default';
+ }
+
+ let failures_count = 0;
+ const failures_by_reason: Record<string, number> = {};
+ try {
+ const { readRecentGraphSignalsFailures } = await import('./graph-signals.ts');
+ const events = readRecentGraphSignalsFailures(days);
+ failures_count = events.length;
+ // The failure event schema has error_summary (not a reason field) —
+ // bucket by the first word of the summary so operators see e.g.
+ // "ECONNREFUSED" / "timeout" / "permission" at a glance.
+ for (const e of events) {
+ const firstWord = (e.error_summary ?? '').split(/[\s:]+/)[0]?.slice(0, 32) || 'unknown';
+ failures_by_reason[firstWord] = (failures_by_reason[firstWord] ?? 0) + 1;
+ }
+ } catch {
+ // Audit reader is best-effort. Missing module / corrupt files →
+ // count stays 0, search-stats still renders.
+ }
+
+ return { enabled, source, failures_count, failures_by_reason };
+}
diff --git a/src/core/search/tune-recommendations.ts b/src/core/search/tune-recommendations.ts
new file mode 100644
index 0000000000..686172f14a
--- /dev/null
+++ b/src/core/search/tune-recommendations.ts
@@ -0,0 +1,107 @@
+/**
+ * Search-tune recommendation builder — moved from src/commands/search.ts in
+ * the CLI→MCP gap-closure wave so the `search_tune` op and the CLI derive the
+ * same recommendations. STRICTLY READ-ONLY: applying a recommendation
+ * (`gbrain search tune` with the apply flag) is CLI-only by design [CDX-21]
+ * and stays in the command file.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { loadSearchModeConfig, resolveSearchMode, type SearchMode } from './mode.ts';
+import { readSearchStats, telemetryCoverage, type TelemetryCoverage } from './telemetry.ts';
+
+export interface TuneRecommendation {
+ knob: string;
+ current: unknown;
+ suggested: unknown;
+ reason: string;
+ apply_command: string;
+}
+
+export interface TuneReport {
+ schema_version: 2;
+ status: 'insufficient_data' | 'no_recommendations' | 'has_recommendations';
+ total_calls: number;
+ cache_hit_rate: number;
+ active_mode: SearchMode;
+ coverage: TelemetryCoverage;
+ recommendations: TuneRecommendation[];
+}
+
+/** Below this many recorded searches the report is 'insufficient_data'. */
+export const TUNE_MIN_CALLS = 20;
+
+export async function buildTuneRecommendations(engine: BrainEngine): Promise<TuneReport> {
+ const modeInput = await loadSearchModeConfig(engine);
+ const resolved = resolveSearchMode(modeInput);
+ const stats = await readSearchStats(engine, { days: 7 });
+
+ const base = {
+ schema_version: 2 as const,
+ total_calls: stats.total_calls,
+ cache_hit_rate: stats.cache_hit_rate,
+ active_mode: resolved.resolved_mode,
+ coverage: telemetryCoverage(),
+ };
+
+ // Recommendation 1: low call volume → no data yet.
+ if (stats.total_calls < TUNE_MIN_CALLS) {
+ return { ...base, status: 'insufficient_data', recommendations: [] };
+ }
+
+ const recs: TuneRecommendation[] = [];
+
+ // Recommendation 2: budget pressure under conservative.
+ if (resolved.resolved_mode === 'conservative' && stats.total_calls > 0) {
+ const dropPctPerCall = stats.total_budget_dropped / stats.total_calls;
+ if (dropPctPerCall > 2) {
+ recs.push({
+ knob: 'search.mode',
+ current: 'conservative',
+ suggested: 'balanced',
+ reason: `Avg ${dropPctPerCall.toFixed(1)} results dropped per search by the 4K budget. Consider balanced (12K budget) or raise search.tokenBudget.`,
+ apply_command: 'gbrain config set search.mode balanced',
+ });
+ }
+ }
+
+ // Recommendation 3: high cache hit rate → bump similarity threshold.
+ if (stats.cache_hit_rate > 0.85 && stats.cache_hits + stats.cache_misses > 50) {
+ recs.push({
+ knob: 'search.cache.similarity_threshold',
+ current: resolved.cache_similarity_threshold,
+ suggested: 0.94,
+ reason: `Cache hit rate is ${(stats.cache_hit_rate * 100).toFixed(1)}%. You can raise similarity threshold to 0.94 for tighter freshness at small recall cost.`,
+ apply_command: 'gbrain config set search.cache.similarity_threshold 0.94',
+ });
+ }
+
+ // Recommendation 4: tokenmax + Haiku subagent.
+ const subagentModel = await engine.getConfig('models.tier.subagent');
+ if (resolved.resolved_mode === 'tokenmax' && subagentModel && /haiku/i.test(subagentModel)) {
+ recs.push({
+ knob: 'search.mode',
+ current: 'tokenmax',
+ suggested: 'balanced',
+ reason: `Subagent tier is Haiku but mode is tokenmax. LLM expansion adds ~50ms + ~1¢ per query. Balanced cuts that cost without losing intent weighting or cache.`,
+ apply_command: 'gbrain config set search.mode balanced',
+ });
+ }
+
+ // Recommendation 5: cache disabled but available — fix the free win.
+ if (!resolved.cache_enabled && stats.total_calls > 5) {
+ recs.push({
+ knob: 'search.cache.enabled',
+ current: false,
+ suggested: true,
+ reason: 'Cache is disabled but mode bundles enable it by default. Cache is a free win (zero LLM cost, big latency drop on repeat queries).',
+ apply_command: 'gbrain config unset search.cache.enabled',
+ });
+ }
+
+ return {
+ ...base,
+ status: recs.length === 0 ? 'no_recommendations' : 'has_recommendations',
+ recommendations: recs,
+ };
+}
diff --git a/src/core/takes-fence.ts b/src/core/takes-fence.ts
index 2a33e86225..2e2a9b490c 100644
--- a/src/core/takes-fence.ts
+++ b/src/core/takes-fence.ts
@@ -426,7 +426,12 @@ export function renderTakesFence(takes: ParsedTake[]): string {
const resolved = t.resolvedAt ? safe(t.resolvedAt) : '';
const quality = t.resolvedQuality ?? '';
const evidence = t.resolvedEvidence ? safe(t.resolvedEvidence) : '';
- const value = t.resolvedValue !== undefined ? formatWeight(t.resolvedValue) : '';
+ // F3: resolvedValue is an UNBOUNDED measured value (usd/count/pct), NOT a
+ // weight on the 0..1 grid. formatWeight's 2-decimal round would diverge md
+ // from the DB (12345.678 → 12345.68). Render it full-precision. Only the
+ // weight cell (`w` above) stays on formatWeight; `value` is the sole
+ // numeric resolution cell.
+ const value = t.resolvedValue !== undefined ? String(t.resolvedValue) : '';
const unit = t.resolvedUnit ? safe(t.resolvedUnit) : '';
const by = t.resolvedBy ? safe(t.resolvedBy) : '';
return `${baseCells} ${resolved} | ${quality} | ${evidence} | ${value} | ${unit} | ${by} |`;
diff --git a/src/core/takes-write.ts b/src/core/takes-write.ts
new file mode 100644
index 0000000000..ae215a4e4a
--- /dev/null
+++ b/src/core/takes-write.ts
@@ -0,0 +1,621 @@
+/**
+ * Shared takes write-through core — consumed by the `gbrain takes` CLI
+ * (src/commands/takes.ts) and the takes_* MCP ops (src/core/ops/takes.ts).
+ *
+ * MARKDOWN IS CANONICAL (the extract-takes contract, src/core/cycle/
+ * extract-takes.ts): the md→DB reconcile upserts ON CONFLICT(page_id,row_num)
+ * and the extract rebuild lane deletes+reinserts from md, so any writer that
+ * creates DB-only rows gets silently clobbered by the next sync/extract. Every
+ * mutation here is therefore md-FIRST — row numbers derive from the fence
+ * (takes-fence.ts), the .md file is written before the DB — and the markdown
+ * write is REQUIRED: when the page file can't be located the write REFUSES
+ * (TakesWriteError 'mirror_unavailable') instead of creating divergence.
+ *
+ * Every mutate runs this pipeline:
+ *
+ * lock(slug, timeout) ─▶ page id (DB, source-scoped) ─▶ read .md
+ * │ │
+ * │ row lookup + holder fence ◀────┘ (fence rows,
+ * │ │ md-canonical)
+ * │ fence edit ─▶ write .md ─▶ DB mirror ─▶ release
+ * ▼
+ * [contended → 'page_locked' (retryable)]
+ *
+ * The DB mirror for add/update/supersede is addTakesBatch's upsert of the
+ * affected fence rows — the same primitive the extract pipeline uses, so the
+ * mirror can never disagree with a later reconcile. Its DO UPDATE clause
+ * touches base columns only (resolution columns preserved). resolve mirrors
+ * via engine.resolveTake (resolution fields aren't in TakeBatchInput);
+ * a drifted DB missing the row is self-healed by upserting the base row
+ * first — md is the truth being propagated.
+ *
+ * Holder fence (remote callers): callers pass `allowList` (null/undefined =
+ * trusted local, unfenced; [] = deny-all). Row-level checks look up the
+ * PARSED FENCE row and a fenced holder presents as 'row_not_found' — the
+ * same shape as a genuinely missing row — hiding content and holder.
+ * (Existence-by-count via dense row numbers is a documented, accepted
+ * limitation — see ops/takes.ts.)
+ */
+
+import { readFileSync, existsSync, mkdirSync } from 'node:fs';
+import { dirname } from 'node:path';
+import type { BrainEngine, TakeBatchInput, TakeKind } from './engine.ts';
+import {
+ parseTakesFence,
+ renderTakesFence,
+ upsertTakeRow,
+ supersedeRow,
+ TAKES_FENCE_BEGIN,
+ TAKES_FENCE_END,
+ type ParsedTake,
+ type ParseResult,
+} from './takes-fence.ts';
+import { withPageLock } from './page-lock.ts';
+import { resolvePageFilePath } from './markdown.ts';
+import { isWriteTargetContained } from './path-confine.ts';
+import { atomicWriteFileSync } from './atomic-write.ts';
+
+export type TakesWriteErrorCode =
+ | 'page_not_found' // slug has no pages row (scoped)
+ | 'row_not_found' // fence lacks the row OR the holder fence masks it
+ | 'already_resolved' // resolved rows are immutable; supersede instead
+ | 'row_inactive' // superseded rows can't be updated/resolved again
+ | 'holder_denied' // add with a holder outside the allow-list
+ | 'no_fields' // update with zero mutable fields
+ | 'mirror_unavailable' // sync.repo_path unset, page file absent, or write target escapes the source root
+ | 'page_locked' // lock contention within the timeout (retryable)
+ | 'fence_unparsed' // the page's fence has parser-skipped rows a whole-fence re-render would delete
+ | 'invalid_input'; // free-text field carries control chars, fence markers, or out-of-range values
+
+export class TakesWriteError extends Error {
+ code: TakesWriteErrorCode;
+ hint?: string;
+ constructor(code: TakesWriteErrorCode, message: string, hint?: string) {
+ super(message);
+ this.name = 'TakesWriteError';
+ this.code = code;
+ this.hint = hint;
+ }
+}
+
+/** null/undefined = trusted local (unfenced); [] = deny-all. */
+export type HolderAllowList = readonly string[] | null | undefined;
+
+export interface TakesWriteTarget {
+ engine: BrainEngine;
+ slug: string;
+ /** Brain repo dir (resolveTakesRepoDir or an explicit CLI --dir). */
+ brainDir: string;
+ /** Scalar source scope for the pages lookup (writes are scalar). */
+ sourceId?: string;
+ allowList?: HolderAllowList;
+ /** Lock wait budget. CLI keeps the 30s default; ops pass ~2000. */
+ lockTimeoutMs?: number;
+}
+
+/**
+ * The markdown write always succeeds before the DB mirror is attempted, and md
+ * is canonical — so a failed DB mirror is NOT fatal (the next reconcile heals
+ * it; throwing would make the caller retry and duplicate the durable md row).
+ * `mirror_warning` carries the DB-mirror error when it happened; `written` is
+ * still true because the markdown row is on disk.
+ */
+export interface TakeMirror { written: true; path: string; mirror_warning?: string }
+
+/** DB-mirror failures are non-fatal (md is canonical) — stringify for the warning. */
+function mirrorErrorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+/**
+ * Resolve the markdown brain dir for takes write-through. Returns null when
+ * `sync.repo_path` is unset or missing on disk — callers decide the refusal
+ * shape (ops: 'mirror_unavailable'; CLI: its historical error text + exit 1).
+ */
+export async function resolveTakesRepoDir(engine: BrainEngine): Promise<string | null> {
+ const configured = await engine.getConfig('sync.repo_path');
+ if (configured && existsSync(configured)) return configured;
+ return null;
+}
+
+/**
+ * P1-1 (source isolation): resolve the ACTUAL per-source markdown path for a
+ * write, mirroring write-through.ts's topology so a source-scoped take lands in
+ * the SAME working tree `gbrain sync` reads it back from. The old
+ * `join(brainDir, slug.md)` ignored the page's source entirely, so a non-default
+ * source's write clobbered a same-slug file in the wrong tree.
+ *
+ * 1. Source has its OWN `local_path` working tree → file at that tree's root
+ * (matches scanOneSource + write-through.ts; never nested under `.sources/`).
+ * 2. No per-source `local_path` → the shared host repo (`brainDir`): default
+ * source at the root, non-default nested under `.sources/<id>/`.
+ *
+ * The returned `writeRoot` is the containment boundary enforced before any write
+ * (P1-2). `resolvePageFilePath` does the slug→path join for the shared-repo case.
+ */
+async function resolveTakesFilePath(
+ engine: BrainEngine,
+ brainDir: string,
+ slug: string,
+ sourceId?: string,
+): Promise<{ path: string; writeRoot: string }> {
+ const src = sourceId ?? 'default';
+ const rows = await engine.executeRaw<{ local_path: string | null }>(
+ `SELECT local_path FROM sources WHERE id = $1`,
+ [src],
+ );
+ const sourceLocalPath = rows[0]?.local_path ?? null;
+ if (sourceLocalPath) {
+ // A source's own working tree files pages at its root (default layout).
+ return { path: resolvePageFilePath(sourceLocalPath, slug, 'default'), writeRoot: sourceLocalPath };
+ }
+ return { path: resolvePageFilePath(brainDir, slug, src), writeRoot: brainDir };
+}
+
+async function getPageId(engine: BrainEngine, slug: string, sourceId?: string): Promise<number> {
+ const rows = sourceId
+ ? await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE slug = $1 AND source_id = $2 LIMIT 1`,
+ [slug, sourceId],
+ )
+ : await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,
+ [slug],
+ );
+ if (!rows[0]) {
+ throw new TakesWriteError(
+ 'page_not_found',
+ `Page not found in brain: ${slug}${sourceId ? ` (source=${sourceId})` : ''}.`,
+ 'Run a brain sync first, or check the slug/source.',
+ );
+ }
+ return rows[0].id;
+}
+
+function assertHolderAllowed(holder: string, allowList: HolderAllowList): void {
+ if (allowList === null || allowList === undefined) return; // trusted local
+ if (!allowList.includes(holder)) {
+ throw new TakesWriteError(
+ 'holder_denied',
+ `holder '${holder}' is not in this caller's takes-holder allow-list.`,
+ 'holder_not_in_allowlist',
+ );
+ }
+}
+
+/**
+ * Fence-injection guard for free-text cells. Every user-supplied string that
+ * lands in a fence cell must be single-line (control chars — newlines
+ * included — would let one cell mint extra table rows) and must not carry the
+ * fence-marker text: 'gbrain:takes' is the tightest common substring of
+ * TAKES_FENCE_BEGIN/TAKES_FENCE_END, so a cell containing it could terminate
+ * the fence early or open a second one, rewriting rows the caller doesn't own.
+ */
+const CELL_CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\n\r\t]/;
+const FENCE_MARKER_SUBSTRING = 'gbrain:takes';
+function assertSafeCellText(field: string, value: string | undefined): void {
+ if (typeof value !== 'string') return;
+ if (CELL_CONTROL_CHARS.test(value)) {
+ throw new TakesWriteError(
+ 'invalid_input',
+ `${field} contains control characters (newlines included) — takes fence cells are single-line.`,
+ );
+ }
+ if (value.includes(FENCE_MARKER_SUBSTRING)) {
+ throw new TakesWriteError(
+ 'invalid_input',
+ `${field} contains the takes fence marker text ('${FENCE_MARKER_SUBSTRING}') — refusing a fence-injection write.`,
+ );
+ }
+ // F2: a wholly-strikethrough value (`~~x~~`) round-trips as active:false —
+ // fence-shared.ts stripStrikethrough matches ^~~(.+?)~~$ — so writing it as an
+ // active claim would silently mark the take inactive on the next parse.
+ if (/^~~[\s\S]*~~$/.test(value.trim())) {
+ throw new TakesWriteError(
+ 'invalid_input',
+ `${field} is wholly strikethrough-wrapped; that markup marks a take inactive on the next parse.`,
+ );
+ }
+}
+
+/**
+ * The param docs promise weight 0..1 and the DB clamps out-of-range values
+ * (normalizeWeightForStorage) — writing the raw value to md would diverge the
+ * markdown from the DB mirror, so out-of-range is refused up front.
+ */
+function assertValidWeight(weight: number | undefined): void {
+ if (weight === undefined) return;
+ if (!Number.isFinite(weight) || weight < 0 || weight > 1) {
+ throw new TakesWriteError('invalid_input', `weight must be a number in [0, 1] (got ${weight}).`);
+ }
+}
+
+const SINCE_DATE_RE = /^\d{4}-\d{2}(-\d{2})?$/;
+function assertValidSinceDate(value: string | undefined): void {
+ if (value === undefined) return;
+ if (!SINCE_DATE_RE.test(value)) {
+ throw new TakesWriteError(
+ 'invalid_input',
+ `since date must be 'YYYY-MM' or 'YYYY-MM-DD' (got '${value}').`,
+ );
+ }
+}
+
+/**
+ * Row lookup with the no-existence-leak masking: a row that is absent from
+ * the fence AND a row whose holder the caller cannot see produce the SAME
+ * error shape.
+ */
+function findFenceRow(takes: ParsedTake[], rowNum: number, allowList: HolderAllowList, slug: string): ParsedTake {
+ const target = takes.find(t => t.rowNum === rowNum);
+ const visible = target
+ && (allowList === null || allowList === undefined || allowList.includes(target.holder));
+ if (!target || !visible) {
+ throw new TakesWriteError('row_not_found', `Row #${rowNum} not found on ${slug}.`);
+ }
+ return target;
+}
+
+function readPageBody(path: string): string {
+ if (!existsSync(path)) {
+ throw new TakesWriteError(
+ 'mirror_unavailable',
+ `Page file not found at ${path} — takes are markdown-canonical, so the write is refused.`,
+ 'takes_mirror_unavailable',
+ );
+ }
+ return readFileSync(path, 'utf-8');
+}
+
+/**
+ * P1-2: contain the target within the source's working tree before any
+ * mkdir/write (a pre-existing hostile row or a symlinked intermediate dir must
+ * not escape), then atomic temp+rename so a reader never observes a torn file
+ * and a crash mid-write leaves only a tmp sibling.
+ */
+function writePageBody(path: string, body: string, writeRoot: string): void {
+ if (!isWriteTargetContained(path, writeRoot)) {
+ throw new TakesWriteError(
+ 'mirror_unavailable',
+ 'takes write target escapes the source root',
+ 'path_escapes_source_root',
+ );
+ }
+ mkdirSync(dirname(path), { recursive: true });
+ atomicWriteFileSync(path, body);
+}
+
+/**
+ * F1 (cross-holder data-loss guard): the row-targeting mutates re-render the
+ * WHOLE fence from `parsed.takes`, so any row parseTakesFence skipped (duplicate
+ * row_num, unknown kind outside {fact,take,bet,hunch}, malformed cells) — or any
+ * row it flagged — would be permanently deleted on the next write, INCLUDING a
+ * row held by an identity a world-fenced caller can't see. Refuse the write when
+ * the fence carries any parse warning; it must be reconciled first.
+ */
+function assertFenceRoundTrips(parsed: ParseResult): void {
+ if (parsed.warnings.length > 0) {
+ throw new TakesWriteError(
+ 'fence_unparsed',
+ `The page's takes fence has rows this version can't safely round-trip: ${parsed.warnings[0]}`,
+ "Reconcile the page's takes fence (gbrain extract takes --slugs <slug>) before mutating — it contains rows this version can't safely round-trip.",
+ );
+ }
+}
+
+function replaceFence(body: string, rows: ParsedTake[]): string {
+ const newFence = renderTakesFence(rows);
+ const beginIdx = body.indexOf(TAKES_FENCE_BEGIN);
+ const endIdx = body.indexOf(TAKES_FENCE_END, beginIdx + TAKES_FENCE_BEGIN.length);
+ return body.slice(0, beginIdx) + newFence + body.slice(endIdx + TAKES_FENCE_END.length);
+}
+
+function toBatchInput(pageId: number, t: ParsedTake, supersededBy?: number | null): TakeBatchInput {
+ return {
+ page_id: pageId,
+ row_num: t.rowNum,
+ claim: t.claim,
+ kind: t.kind,
+ holder: t.holder,
+ weight: t.weight,
+ since_date: t.sinceDate,
+ until_date: t.untilDate,
+ source: t.source,
+ active: t.active,
+ superseded_by: supersededBy ?? null,
+ };
+}
+
+async function withTakesLock<T>(target: TakesWriteTarget, fn: () => Promise<T>): Promise<T> {
+ try {
+ return await withPageLock(target.slug, fn, {
+ ...(target.lockTimeoutMs !== undefined ? { timeoutMs: target.lockTimeoutMs } : {}),
+ });
+ } catch (err) {
+ if (err instanceof TakesWriteError) throw err;
+ if (err instanceof Error && err.message.includes('could not acquire lock')) {
+ throw new TakesWriteError(
+ 'page_locked',
+ `Another writer holds the page lock for ${target.slug} — retry shortly.`,
+ 'retryable',
+ );
+ }
+ throw err;
+ }
+}
+
+export interface AddTakeInput {
+ claim: string;
+ kind: TakeKind;
+ holder: string;
+ weight?: number;
+ source?: string;
+ sinceDate?: string;
+}
+
+export async function addTakeToPage(
+ target: TakesWriteTarget,
+ input: AddTakeInput,
+): Promise<{ rowNum: number; mirror: TakeMirror }> {
+ assertHolderAllowed(input.holder, target.allowList);
+ // Fence-injection + range guards run before any I/O (invalid input must
+ // never acquire the lock or touch the page).
+ assertSafeCellText('claim', input.claim);
+ assertSafeCellText('kind', input.kind);
+ assertSafeCellText('holder', input.holder);
+ assertSafeCellText('source', input.source);
+ assertValidWeight(input.weight);
+ assertValidSinceDate(input.sinceDate);
+ return withTakesLock(target, async () => {
+ // Resolve the page BEFORE touching the markdown (the historical CLI
+ // ordering): failing after a fence write would leave a take on disk the
+ // DB never saw until the next reconcile.
+ const pageId = await getPageId(target.engine, target.slug, target.sourceId);
+ // add is the one mutate that may CREATE the page file + fence (first take
+ // on a page) — readPageBody's existence refusal applies to row-targeting
+ // mutates, not appends; the page itself was verified in the DB above.
+ const { path, writeRoot } = await resolveTakesFilePath(
+ target.engine, target.brainDir, target.slug, target.sourceId,
+ );
+ const body = existsSync(path) ? readFileSync(path, 'utf-8') : '';
+ // F1: guard only fires when a fence ALREADY exists (an empty/fence-less body
+ // parses to zero warnings) — a whole-fence re-render must not delete rows
+ // this version couldn't parse.
+ assertFenceRoundTrips(parseTakesFence(body));
+ const { body: nextBody, rowNum } = upsertTakeRow(body, {
+ claim: input.claim,
+ kind: input.kind,
+ holder: input.holder,
+ weight: input.weight ?? 0.5,
+ source: input.source,
+ sinceDate: input.sinceDate,
+ active: true,
+ });
+ writePageBody(path, nextBody, writeRoot);
+ let mirrorWarning: string | undefined;
+ try {
+ await target.engine.addTakesBatch([{
+ page_id: pageId, row_num: rowNum, claim: input.claim, kind: input.kind,
+ holder: input.holder, weight: input.weight ?? 0.5,
+ since_date: input.sinceDate, source: input.source,
+ active: true, superseded_by: null,
+ }]);
+ } catch (err) {
+ // P1-4/F4: md is canonical + already written — a failed DB mirror is
+ // healed by the next reconcile, so surface a warning instead of throwing
+ // (a throw would make the caller retry and duplicate the durable md row).
+ mirrorWarning = mirrorErrorMessage(err);
+ }
+ return { rowNum, mirror: { written: true, path, ...(mirrorWarning ? { mirror_warning: mirrorWarning } : {}) } };
+ });
+}
+
+export interface UpdateTakeFields {
+ weight?: number;
+ source?: string;
+ sinceDate?: string;
+}
+
+export async function updateTakeOnPage(
+ target: TakesWriteTarget,
+ rowNum: number,
+ fields: UpdateTakeFields,
+): Promise<{ rowNum: number; mirror: TakeMirror }> {
+ if (fields.weight === undefined && fields.source === undefined && fields.sinceDate === undefined) {
+ throw new TakesWriteError('no_fields', 'No mutable fields given (weight, source, since date).');
+ }
+ assertSafeCellText('source', fields.source);
+ assertValidWeight(fields.weight);
+ assertValidSinceDate(fields.sinceDate);
+ return withTakesLock(target, async () => {
+ const pageId = await getPageId(target.engine, target.slug, target.sourceId);
+ const { path, writeRoot } = await resolveTakesFilePath(
+ target.engine, target.brainDir, target.slug, target.sourceId,
+ );
+ const body = readPageBody(path);
+ const parsed = parseTakesFence(body);
+ assertFenceRoundTrips(parsed); // F1: refuse a whole-fence re-render that would drop skipped rows.
+ const targetRow = findFenceRow(parsed.takes, rowNum, target.allowList, target.slug);
+ if (targetRow.resolvedAt) {
+ throw new TakesWriteError('already_resolved', `Row #${rowNum} on ${target.slug} is resolved — resolved takes are immutable.`, 'Supersede instead.');
+ }
+ if (!targetRow.active) {
+ // A superseded row's mirror upsert would also wipe its superseded_by
+ // pointer — refuse, matching supersedeTakeOnPage's guard.
+ throw new TakesWriteError('row_inactive', `Row #${rowNum} on ${target.slug} is already superseded.`);
+ }
+ const updated: ParsedTake = {
+ ...targetRow,
+ weight: fields.weight ?? targetRow.weight,
+ source: fields.source ?? targetRow.source,
+ sinceDate: fields.sinceDate ?? targetRow.sinceDate,
+ };
+ const allRows = parsed.takes.map(t => (t.rowNum === rowNum ? updated : t));
+ writePageBody(path, replaceFence(body, allRows), writeRoot);
+ // Mirror md→DB with the reconcile primitive (upsert on (page_id,row_num));
+ // base columns only, resolution columns preserved by the DO UPDATE list.
+ let mirrorWarning: string | undefined;
+ try {
+ await target.engine.addTakesBatch([toBatchInput(pageId, updated)]);
+ } catch (err) {
+ mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.
+ }
+ return { rowNum, mirror: { written: true, path, ...(mirrorWarning ? { mirror_warning: mirrorWarning } : {}) } };
+ });
+}
+
+export interface SupersedeTakeInput {
+ claim: string;
+ kind?: TakeKind;
+ holder?: string;
+ weight?: number;
+ source?: string;
+ sinceDate?: string;
+}
+
+export async function supersedeTakeOnPage(
+ target: TakesWriteTarget,
+ rowNum: number,
+ input: SupersedeTakeInput,
+): Promise<{ oldRow: number; newRow: number; mirror: TakeMirror }> {
+ assertSafeCellText('claim', input.claim);
+ assertSafeCellText('kind', input.kind);
+ assertSafeCellText('holder', input.holder);
+ assertSafeCellText('source', input.source);
+ assertValidWeight(input.weight);
+ assertValidSinceDate(input.sinceDate);
+ return withTakesLock(target, async () => {
+ const pageId = await getPageId(target.engine, target.slug, target.sourceId);
+ const { path, writeRoot } = await resolveTakesFilePath(
+ target.engine, target.brainDir, target.slug, target.sourceId,
+ );
+ const body = readPageBody(path);
+ const parsed = parseTakesFence(body);
+ assertFenceRoundTrips(parsed); // F1: refuse a whole-fence re-render that would drop skipped rows.
+ const targetRow = findFenceRow(parsed.takes, rowNum, target.allowList, target.slug);
+ if (!targetRow.active) {
+ throw new TakesWriteError('row_inactive', `Row #${rowNum} on ${target.slug} is already superseded.`);
+ }
+ if (targetRow.resolvedAt) {
+ throw new TakesWriteError('already_resolved', `Row #${rowNum} on ${target.slug} is resolved — resolved takes are immutable.`, 'Add a new take instead.');
+ }
+ const holder = input.holder ?? targetRow.holder;
+ // An explicit replacement holder must clear the fence too (an allow-listed
+ // caller must not mint rows held by identities it can't see).
+ if (input.holder !== undefined) assertHolderAllowed(input.holder, target.allowList);
+ // CLI-parity default: unset weight decays the target's by 0.1.
+ const weight = input.weight ?? Math.max(0, targetRow.weight - 0.1);
+ const { body: nextBody, newRowNum } = supersedeRow(body, rowNum, {
+ claim: input.claim,
+ kind: input.kind ?? targetRow.kind,
+ holder,
+ weight,
+ sinceDate: input.sinceDate,
+ source: input.source,
+ });
+ writePageBody(path, nextBody, writeRoot);
+ // Mirror BOTH affected rows exactly as the fence now states them:
+ // old → inactive + superseded_by pointer, new → active append.
+ const after = parseTakesFence(nextBody).takes;
+ const oldAfter = after.find(t => t.rowNum === rowNum);
+ const newAfter = after.find(t => t.rowNum === newRowNum);
+ const mirrorRows: TakeBatchInput[] = [];
+ if (oldAfter) mirrorRows.push(toBatchInput(pageId, oldAfter, newRowNum));
+ if (newAfter) mirrorRows.push(toBatchInput(pageId, newAfter, null));
+ let mirrorWarning: string | undefined;
+ try {
+ await target.engine.addTakesBatch(mirrorRows);
+ } catch (err) {
+ mirrorWarning = mirrorErrorMessage(err); // P1-4/F4: md written; DB mirror deferred to reconcile.
+ }
+ return { oldRow: rowNum, newRow: newRowNum, mirror: { written: true, path, ...(mirrorWarning ? { mirror_warning: mirrorWarning } : {}) } };
+ });
+}
+
+export type ResolveQuality = 'correct' | 'incorrect' | 'partial' | 'unresolvable';
+
+export interface ResolveTakeInput {
+ quality: ResolveQuality;
+ /** Evidence text (stored as the resolution source). */
+ evidence?: string;
+ value?: number;
+ unit?: string;
+ resolvedBy: string;
+}
+
+export async function resolveTakeOnPage(
+ target: TakesWriteTarget,
+ rowNum: number,
+ input: ResolveTakeInput,
+): Promise<{ rowNum: number; quality: ResolveQuality; mirror: TakeMirror }> {
+ assertSafeCellText('evidence', input.evidence);
+ assertSafeCellText('unit', input.unit);
+ assertSafeCellText('resolved_by', input.resolvedBy);
+ return withTakesLock(target, async () => {
+ const pageId = await getPageId(target.engine, target.slug, target.sourceId);
+ const { path, writeRoot } = await resolveTakesFilePath(
+ target.engine, target.brainDir, target.slug, target.sourceId,
+ );
+ const body = readPageBody(path);
+ const parsed = parseTakesFence(body);
+ assertFenceRoundTrips(parsed); // F1: refuse a whole-fence re-render that would drop skipped rows.
+ const targetRow = findFenceRow(parsed.takes, rowNum, target.allowList, target.slug);
+ if (targetRow.resolvedAt) {
+ throw new TakesWriteError('already_resolved', `Row #${rowNum} on ${target.slug} is already resolved.`);
+ }
+ if (!targetRow.active) {
+ // Resolving a superseded row would feed calibration with an already-
+ // revised claim — resolve the replacement row instead.
+ throw new TakesWriteError('row_inactive', `Row #${rowNum} on ${target.slug} is already superseded.`, 'Resolve the replacement row instead.');
+ }
+ // quality → outcome per the schema CHECK (v74): correct↔true,
+ // incorrect↔false, partial/unresolvable↔NULL.
+ const outcome = input.quality === 'correct' ? true
+ : input.quality === 'incorrect' ? false : undefined;
+ const updated: ParsedTake = {
+ ...targetRow,
+ resolvedAt: new Date().toISOString().slice(0, 10),
+ resolvedQuality: input.quality,
+ resolvedOutcome: outcome,
+ resolvedEvidence: input.evidence,
+ resolvedValue: input.value,
+ resolvedUnit: input.unit,
+ resolvedBy: input.resolvedBy,
+ };
+ const allRows = parsed.takes.map(t => (t.rowNum === rowNum ? updated : t));
+ writePageBody(path, replaceFence(body, allRows), writeRoot);
+ // Resolution fields aren't in TakeBatchInput — mirror via resolveTake.
+ // A drifted DB missing the row is self-healed md→DB (upsert the base row,
+ // then resolve): the markdown is the truth being propagated.
+ // One shared argument object so the self-heal retry can never silently
+ // diverge from the primary call.
+ const resolveArgs = {
+ quality: input.quality,
+ outcome,
+ value: input.value,
+ unit: input.unit,
+ source: input.evidence,
+ resolvedBy: input.resolvedBy,
+ };
+ // P1-4/F4: md is canonical + already written — a failed DB mirror (incl. a
+ // failed self-heal) is healed by the next reconcile, so it surfaces as a
+ // warning, never a throw (a throw would make the caller retry the durable
+ // md write and duplicate the row).
+ let mirrorWarning: string | undefined;
+ try {
+ await target.engine.resolveTake(pageId, rowNum, resolveArgs);
+ } catch (err) {
+ if (err instanceof Error && err.message.includes('TAKE_ROW_NOT_FOUND')) {
+ try {
+ await target.engine.addTakesBatch([toBatchInput(pageId, targetRow)]);
+ await target.engine.resolveTake(pageId, rowNum, resolveArgs);
+ } catch (healErr) {
+ mirrorWarning = mirrorErrorMessage(healErr);
+ }
+ } else {
+ mirrorWarning = mirrorErrorMessage(err);
+ }
+ }
+ return { rowNum, quality: input.quality, mirror: { written: true, path, ...(mirrorWarning ? { mirror_warning: mirrorWarning } : {}) } };
+ });
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index 2a59afae0c..88b0cc50cd 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1542,34 +1542,20 @@ export interface BrainHealth {
no_orphans_score: number; // 0-15
no_dead_links_score: number; // 0-10
/**
- * v0.30.1 (Cherry D7 + Codex C3): explicit migrations diagnostic surface
- * exposed to MCP get_health callers so remote agents can detect a wedged
- * brain WITHOUT shelling SSH + gbrain doctor. Two ledgers (schema +
- * orchestrator) per Codex T5 namespacing.
+ * Host migration-ledger summary so remote get_health callers can detect a
+ * wedged brain WITHOUT shelling SSH + gbrain doctor. Composed at the op
+ * layer by get_health from src/core/migration-ledger.ts
+ * (migrationLedgerSummary — version strings only, never migration
+ * internals); an unreadable/corrupt ledger degrades to the error variant.
*
* `schema_version` ("1") on the parent BrainHealth pins the additive
* contract — clients should default-handle missing fields and never
* assume removed ones.
*/
schema_version?: '1';
- migrations?: {
- schema: {
- /** Current numeric config.version. */
- version: number;
- /** Latest available migration. */
- latest_version: number;
- /**
- * Optional drift evidence — names of columns/tables a verify hook
- * surfaced as missing on opt-in migrations. Empty array means no
- * drift detected (or no verify hook ran).
- */
- verify_drift?: string[];
- };
- orchestrator: {
- pending: Array<{ version: string; name: string; status: 'pending' | 'partial' }>;
- wedged: Array<{ version: string; name: string; consecutive_partials: number }>;
- };
- };
+ migrations?:
+ | { pending: string[]; partial: string[]; wedged: string[]; skipped_future: number }
+ | { error: 'ledger_unreadable' };
}
// Ingest log
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index a39e929a3d..d8aab22ae5 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -8,6 +8,8 @@ import { buildToolDefs } from './tool-defs.ts';
import { dispatchToolCall, buildOperationContext } from './dispatch.ts';
import { validateParams, parseStrictParamsMode } from './validate-params.ts';
import { filterOpsForSurface, allowedOpNames, clampSurface, type McpSurface } from './surface.ts';
+import { disabledOpsForPublishGates } from './publish-gates.ts';
+import type { Operation } from '../core/operations.ts';
import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
import {
@@ -53,6 +55,34 @@ export async function resolveMcpStdioSourceScope(
}
}
+/**
+ * Per-request stdio tools/list set: the surfaced ops minus publish-gated ops
+ * whose gate resolves off. stdio dispatches remote:true (agent-facing), and
+ * the gate enforcement (assertPublishEnabled, the advisor inline gate) exempts
+ * only ctx.remote === false — so listing gate-off ops here was the exact
+ * listed-but-denied class the honest-catalog wave exists to kill, surviving on
+ * the default transport. localOnly ops STAY listed: locality is the transport
+ * axis (stdio IS the local pipe, D7); publish gates are the owner-consent
+ * axis. Deliberately uncached (publish-gates.ts doctrine: the per-request read
+ * is what makes a config flip take effect without a restart; tools/list is
+ * rare). Fail-closed: a resolver failure hides every gated op rather than
+ * re-creating the listed-but-denied complaint.
+ */
+export async function stdioVisibleTools(
+ engine: BrainEngine,
+ surfacedOps: Operation[],
+): Promise<Operation[]> {
+ if (!surfacedOps.some(op => op.publishGateKey)) return surfacedOps;
+ let gateDisabled: ReadonlySet<string>;
+ try {
+ gateDisabled = await disabledOpsForPublishGates(engine, loadConfig());
+ } catch {
+ gateDisabled = new Set(surfacedOps.filter(o => o.publishGateKey).map(o => o.name));
+ }
+ if (gateDisabled.size === 0) return surfacedOps;
+ return surfacedOps.filter(op => !gateDisabled.has(op.name));
+}
+
export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSurface; sourceGuard?: boolean } = {}) {
const server = new Server(
{ name: 'gbrain', version: VERSION },
@@ -64,7 +94,10 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// (exactly the 7 protocol verbs). Enforced BOTH on the advertised list and
// in dispatch (fail-closed [c2]). WP4: the GBRAIN_MCP_FORCE_SURFACE kill
// switch min()s in (narrow-only, FOV-6a). Note stdio keeps localOnly ops
- // on every surface tier that includes them — it IS the local surface (D7).
+ // on every surface tier that includes them — it IS the local surface (D7,
+ // the transport-LOCALITY axis). Publish gates are the separate owner-
+ // CONSENT axis keyed on ctx.remote === false only, and stdio dispatches
+ // remote:true — so gate-off ops are subtracted per tools/list below.
const surface: McpSurface = clampSurface(opts.surface ?? 'full');
const surfacedOps = filterOpsForSurface(operations, surface);
const allowedOps = surface === 'full' ? undefined : allowedOpNames(operations, surface);
@@ -77,9 +110,12 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// Generate tool definitions from operations. Extracted to buildToolDefs so
// the subagent tool registry (v0.15+) can call the same mapper against a
- // filtered OPERATIONS subset instead of duplicating this shape.
+ // filtered OPERATIONS subset instead of duplicating this shape. Publish-gate
+ // subtraction happens per request (stdioVisibleTools) — no caching, so a
+ // `gbrain config set mcp.publish_skills true` takes effect on the next
+ // tools/list without a serve restart (matches the HTTP transports).
server.setRequestHandler(ListToolsRequestSchema, async () => ({
- tools: buildToolDefs(surfacedOps, { strictParams }),
+ tools: buildToolDefs(await stdioVisibleTools(engine, surfacedOps), { strictParams }),
}));
// Dispatch tool calls via shared dispatch.ts (parity with HTTP transport).
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index 235542c2e7..e9eb4a0d5e 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -89,6 +89,12 @@ export const STARTER_OPS: ReadonlySet<string> = new Set([
...FALLBACK_DAILY_OPS,
'whoami',
'request_tools',
+ // [EV8] capture joins as a DIRECT literal — deliberately NOT via
+ // BRAIN_TOOL_ALLOWLIST (that would grant every minion subagent a new write
+ // tool and require the skillopt mutating-exclusion update). The plugin +
+ // starter connect lanes retire the "unknown tool: capture" FAQ, which only
+ // works if the starter surface actually lists it.
+ 'capture',
]);
/**
@@ -105,6 +111,10 @@ export const ALWAYS_INCLUDED_STARTER_OPS: ReadonlySet<string> = new Set([
'request_tools',
'submit_agent',
'get_agent_job',
+ // [EV8] capture is contract-bearing on the starter lanes (the retired FAQ
+ // points agents at it) — usage-driven re-derivation must never propose
+ // evicting it as a zero-usage newcomer.
+ 'capture',
]);
/** Strict flag parser — unknown values reject loudly (parseStdioIdleTimeout pattern). */
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 7aa46d82ee..a0f1b434b4 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.12.0 -->
+<!-- gbrain-template-stamp: 0.46.12.2 -->
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/capture-op.test.ts b/test/capture-op.test.ts
new file mode 100644
index 0000000000..c8febbb828
--- /dev/null
+++ b/test/capture-op.test.ts
@@ -0,0 +1,99 @@
+/**
+ * CLI→MCP gap-closure wave — the capture op (D2A). Pins: default-slug
+ * determinism, the NUL/empty guards, the frontmatter merge (single block),
+ * put_page delegation (provenance server-stamped mcp:put_page for remote —
+ * honest CV6 delegation), the [EV7] bound-prefix default for fenced clients,
+ * and content_hash stability.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import type { AuthInfo } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('capture op', () => {
+ test('captures a note under a stable inbox/ slug and stamps provenance server-side', async () => {
+ const content = 'Decided to use PGLite as the default engine: zero-config wins.';
+ const res = await dispatchToolCall(engine, 'capture', { content }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.slug).toMatch(/^inbox\/\d{4}-\d{2}-\d{2}-[0-9a-f]{8}$/);
+ expect(body.channel).toBe('capture');
+ expect(typeof body.content_hash).toBe('string');
+
+ const page = await engine.getPage(body.slug);
+ expect(page).toBeTruthy();
+ // CV6: remote provenance is server-stamped by the delegated put_page.
+ expect(page?.source_kind).toBe('mcp:put_page');
+ // Frontmatter merged as a single stamped block.
+ expect(page?.frontmatter?.captured_at).toBeDefined();
+
+ // Idempotent default slug: identical normalized content → same slug.
+ const again = parsed(await dispatchToolCall(engine, 'capture', { content: ` ${content}\r\n` }, { ...STDIO }));
+ expect(again.slug).toBe(body.slug);
+ expect(again.content_hash).toBe(body.content_hash);
+ });
+
+ test('type routes the default slug prefix (diary → life/diary/)', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'capture', {
+ content: 'Long day, good demo.', type: 'diary',
+ }, { ...STDIO }));
+ expect(body.slug).toMatch(/^life\/diary\/\d{4}-\d{2}-\d{2}-[0-9a-f]{8}$/);
+ });
+
+ test('NUL byte and empty content are refused with named errors', async () => {
+ const nul = parsed(await dispatchToolCall(engine, 'capture', { content: 'ab\u0000cd' }, { ...STDIO }));
+ expect(nul.error).toBe('invalid_params');
+ expect(nul.message).toContain('NUL');
+ const empty = parsed(await dispatchToolCall(engine, 'capture', { content: ' \n ' }, { ...STDIO }));
+ expect(empty.error).toBe('invalid_params');
+ expect(empty.message).toContain('empty');
+ });
+
+ test('[EV7] fenced client: default slug nests under the first bound prefix', async () => {
+ const auth: AuthInfo = { token: 't', clientId: 'fenced-agent', scopes: ['write'], boundSlugPrefixes: ['wiki/agents/x/'] };
+ const body = parsed(await dispatchToolCall(engine, 'capture', { content: 'fenced note' }, {
+ ...STDIO, auth,
+ }));
+ expect(body.slug).toMatch(/^wiki\/agents\/x\/inbox\/\d{4}-\d{2}-\d{2}-[0-9a-f]{8}$/);
+ // An explicit out-of-fence slug still denies via the inherited fence.
+ const denied = parsed(await dispatchToolCall(engine, 'capture', {
+ content: 'escape attempt', slug: 'inbox/escape',
+ }, { ...STDIO, auth }));
+ expect(denied.error).toBe('permission_denied');
+ });
+
+ test('[EV7] fenced client + typed capture: the ENTIRE default slug (type prefix included) nests under the bound prefix', async () => {
+ const auth: AuthInfo = { token: 't', clientId: 'fenced-agent', scopes: ['write'], boundSlugPrefixes: ['wiki/agents/x/'] };
+ const body = parsed(await dispatchToolCall(engine, 'capture', {
+ content: 'fenced diary note', type: 'diary',
+ }, { ...STDIO, auth }));
+ expect(body.slug).toMatch(/^wiki\/agents\/x\/life\/diary\/\d{4}-\d{2}-\d{2}-[0-9a-f]{8}$/);
+ expect(body.slug).not.toContain('diary/diary');
+ });
+
+ test('dry_run short-circuits before any write', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'capture', { content: 'dry note', dry_run: true }, { ...STDIO }));
+ expect(body.dry_run).toBe(true);
+ const page = await engine.getPage(body.slug);
+ expect(page).toBeNull();
+ });
+});
diff --git a/test/cli-flag-validation.test.ts b/test/cli-flag-validation.test.ts
index 2c9476a4e3..91b25797ba 100644
--- a/test/cli-flag-validation.test.ts
+++ b/test/cli-flag-validation.test.ts
@@ -56,6 +56,13 @@ describe('#2185 sweep — every command rejects a nonsense flag', () => {
// And --migrate-only alone stays legal.
expect(validateCommandFlags('init', ['--migrate-only'])).toBeNull();
});
+
+ test('whoknows stays a CLI_ONLY member (reachability pin)', () => {
+ // The #2035 class: `case 'whoknows'` has a live handler (runWhoknows) that
+ // is shadowed by find_experts' hidden op hint — dropping this CLI_ONLY
+ // entry makes whoknows unreachable because its op hint is hidden.
+ expect(CLI_ONLY.has('whoknows')).toBe(true);
+ });
});
describe('#2185 acceptance — real usage stays legal', () => {
@@ -219,6 +226,19 @@ describe('#2185 drift + freshness guards', () => {
expect(missing).toEqual([]);
});
+ test('every op whose cliHints.name is in CLI_ONLY is hidden (shadow guard)', () => {
+ // CLI_ONLY wins over op-generated dispatch (src/cli.ts handleCliOnly
+ // check precedes cliOps lookup), so a NON-hidden cliHints name that
+ // collides with CLI_ONLY is dead code that lies to the catalog — the
+ // think/salience/anomalies/whoknows class this wave swept. New collisions
+ // must mark the hint hidden (the advisor pattern) or drop the CLI_ONLY
+ // entry.
+ const shadowed = operations
+ .filter(op => op.cliHints?.name && CLI_ONLY.has(op.cliHints.name) && op.cliHints.hidden !== true)
+ .map(op => `${op.name} (cliHints.name='${op.cliHints?.name}')`);
+ expect(shadowed).toEqual([]);
+ });
+
test('committed registry matches a fresh generator run (freshness guard)', () => {
const fresh = buildFlagRegistry();
const freshKeys = Object.keys(fresh).sort();
diff --git a/test/client-slug-fence.test.ts b/test/client-slug-fence.test.ts
index 9ce970de44..7e95f0c0f0 100644
--- a/test/client-slug-fence.test.ts
+++ b/test/client-slug-fence.test.ts
@@ -63,6 +63,13 @@ const FENCED_OPS: Array<{ name: string; params: (slug: string) => Record<string,
{ name: 'add_timeline_entry', params: (slug) => ({ slug, date: '2026-08-01', summary: 's' }) },
{ name: 'revert_version', params: (slug) => ({ slug, version_id: 1 }) },
{ name: 'put_raw_data', params: (slug) => ({ slug, source: 'src', data: {} }) },
+ // CLI→MCP gap-closure wave: the four takes write verbs call
+ // enforceClientSlugFence themselves BEFORE the dry-run short-circuit (their
+ // markdown mirror writes the page file under the slug).
+ { name: 'takes_add', params: (slug) => ({ slug, claim: 'c', kind: 'fact', holder: 'world' }) },
+ { name: 'takes_update', params: (slug) => ({ slug, row_num: 1, weight: 0.5 }) },
+ { name: 'takes_resolve', params: (slug) => ({ slug, row_num: 1, quality: 'correct' }) },
+ { name: 'takes_supersede', params: (slug) => ({ slug, row_num: 1, claim: 'c' }) },
];
describe('client slug fence (bound_slug_prefixes on direct writes)', () => {
diff --git a/test/connect.test.ts b/test/connect.test.ts
index 7d5a400dc3..df7dce19c9 100644
--- a/test/connect.test.ts
+++ b/test/connect.test.ts
@@ -770,11 +770,17 @@ describe('LEARN_INSTRUCTION names only real MCP tools', () => {
// The self-orientation block is pasted into a connected agent verbatim. Every
// tool it names MUST be MCP-exposed, or the agent calls an "unknown tool".
// The exposed set is pinned end-to-end by test/e2e/serve-stdio-roundtrip.ts.
- test('names put_page (the real MCP write tool), not capture (CLI-only)', () => {
+ test('every named tool is a real op, and capture (now an MCP op, gap-closure wave) is on the starter surface', async () => {
expect(LEARN_INSTRUCTION).toContain('put_page');
- // `capture` is a CLI-only convenience wrapper, not an MCP tool — naming it
- // here told connected agents to call a tool the server does not expose.
- expect(LEARN_INSTRUCTION).not.toContain('capture');
+ expect(LEARN_INSTRUCTION).toContain('capture');
+ const { operationsByName } = await import('../src/core/operations.ts');
+ const { STARTER_OPS } = await import('../src/mcp/surface.ts');
+ for (const name of ['get_brain_identity', 'list_skills', 'search', 'query', 'get_page', 'put_page', 'capture', 'think', 'find_experts', 'list_brain_skillpack']) {
+ expect(operationsByName[name]).toBeDefined();
+ }
+ // The plugin/starter connect lanes retired the "unknown tool: capture"
+ // FAQ — that only holds if starter actually lists it [EV8].
+ expect(STARTER_OPS.has('capture')).toBe(true);
});
test('still steers the agent to get_brain_identity + list_skills + brain-first search', () => {
expect(LEARN_INSTRUCTION).toContain('get_brain_identity');
diff --git a/test/e2e/mcp.test.ts b/test/e2e/mcp.test.ts
index 1f985514ae..c2faecd76a 100644
--- a/test/e2e/mcp.test.ts
+++ b/test/e2e/mcp.test.ts
@@ -15,7 +15,9 @@ import { operations } from '../../src/core/operations.ts';
describe('E2E: MCP Tool Generation', () => {
test('operations generate valid MCP tool definitions', () => {
- // This replicates exactly what server.ts does in the tools/list handler
+ // This replicates server.ts's tool-def mapping over the FULL op list.
+ // (The live tools/list additionally subtracts gate-off publish-gated ops
+ // per request — stdioVisibleTools, pinned by test/mcp-stdio-gate-list.)
const tools = operations.map(op => ({
name: op.name,
description: op.description,
diff --git a/test/e2e/serve-stdio-roundtrip.test.ts b/test/e2e/serve-stdio-roundtrip.test.ts
index 91d90973c1..8c9459cece 100644
--- a/test/e2e/serve-stdio-roundtrip.test.ts
+++ b/test/e2e/serve-stdio-roundtrip.test.ts
@@ -105,13 +105,13 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()
const { tools } = await client!.listTools();
const names = new Set(tools.map((t) => t.name));
// The core MCP tools the connect LEARN_INSTRUCTION promises always work.
- // `capture` is deliberately NOT here — it's a CLI-only wrapper, not an MCP
- // tool; the agent writes via put_page (regression guard for the stale
- // LEARN_INSTRUCTION that named capture as an MCP tool).
+ // `capture` earned its MCP slot in the CLI-to-MCP gap-closure wave: the
+ // LEARN_INSTRUCTION names it, so tools/list parity requires it advertised
+ // (regression guard against re-demoting it to a CLI-only wrapper).
for (const core of ['search', 'query', 'get_page', 'put_page', 'get_brain_identity', 'think', 'find_experts']) {
expect(names.has(core)).toBe(true);
}
- expect(names.has('capture')).toBe(false); // CLI-only, must not be advertised as MCP
+ expect(names.has('capture')).toBe(true); // MCP-advertised since the gap-closure wave
}, 30_000);
test('tools/call get_brain_identity returns version + engine + a populated counter', async () => {
diff --git a/test/get-job-stats-op.test.ts b/test/get-job-stats-op.test.ts
new file mode 100644
index 0000000000..f7cb3233cf
--- /dev/null
+++ b/test/get-job-stats-op.test.ts
@@ -0,0 +1,100 @@
+/**
+ * CLI→MCP gap-closure wave — get_job_stats op (`gbrain jobs stats` was the
+ * one jobs verb with no MCP equivalent). Pins the payload shape, the shared
+ * wedge derivation (queue.ts deriveWedgeSignal — same math as the CLI line
+ * and the doctor wedged_queue check, #1801), and the relation-missing guard.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { deriveWedgeSignal } from '../src/core/minions/queue.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+describe('get_job_stats op', () => {
+ test('returns the stats shape with the derived wedge signal (empty queue → not wedged)', async () => {
+ const res = await dispatchToolCall(engine, 'get_job_stats', {}, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.schema_version).toBe(1);
+ expect(body.window_hours).toBe(24);
+ expect(typeof body.by_status).toBe('object');
+ expect(Array.isArray(body.by_type)).toBe(true);
+ expect(typeof body.queue_health.waiting).toBe('number');
+ expect(body.wedge.queue).toBe('default');
+ // Empty queue: nothing waiting → never wedged.
+ expect(body.wedged).toBe(false);
+ expect(body.wedge_threshold_minutes).toBeGreaterThan(0);
+ });
+
+ test('queue + since_hours params: wedge scopes to the named queue, window clamps', async () => {
+ const res = await dispatchToolCall(engine, 'get_job_stats', { queue: 'reports', since_hours: 100000 }, { ...STDIO });
+ const body = parsed(res);
+ expect(body.wedge.queue).toBe('reports');
+ expect(body.window_hours).toBe(720); // clamp ceiling
+ });
+
+ test('admin scope declared (jobs-family consistency)', () => {
+ expect(operationsByName['get_job_stats'].scope).toBe('admin');
+ expect(operationsByName['get_job_stats'].area).toBe('jobs');
+ });
+
+ test('missing minions schema → actionable unavailable, not a raw relation error', async () => {
+ const bare = {
+ executeRaw: async () => {
+ throw new Error('relation "minion_jobs" does not exist');
+ },
+ } as unknown as BrainEngine;
+ const res = await dispatchToolCall(bare, 'get_job_stats', {}, { ...STDIO });
+ expect(res.isError).toBe(true);
+ const body = parsed(res);
+ expect(body.error).toBe('unavailable');
+ expect(body.suggestion).toContain('apply-migrations');
+ });
+});
+
+describe('deriveWedgeSignal (shared with the CLI line + doctor check)', () => {
+ // deriveWedgeSignal reads GBRAIN_WEDGED_QUEUE_WARN_MINUTES per call — pin
+ // it to unset so a tuned dev/CI host (e.g. =120) can't flip the 60-minute
+ // fixtures below. The default threshold (15) is what these assertions pin.
+ test('wedged: no healthy actives, work waiting, stale completion', async () => {
+ await withEnv({ GBRAIN_WEDGED_QUEUE_WARN_MINUTES: undefined }, async () => {
+ const { wedged } = deriveWedgeSignal({ active_healthy: 0, waiting: 3, minutes_since_completion: 60 });
+ expect(wedged).toBe(true);
+ });
+ });
+
+ test('wedged: no completions on record counts as stale', async () => {
+ await withEnv({ GBRAIN_WEDGED_QUEUE_WARN_MINUTES: undefined }, async () => {
+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 1, minutes_since_completion: null }).wedged).toBe(true);
+ });
+ });
+
+ test('not wedged: live active row masks nothing, recent completion clears', async () => {
+ await withEnv({ GBRAIN_WEDGED_QUEUE_WARN_MINUTES: undefined }, async () => {
+ expect(deriveWedgeSignal({ active_healthy: 1, waiting: 5, minutes_since_completion: 60 }).wedged).toBe(false);
+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 5, minutes_since_completion: 2 }).wedged).toBe(false);
+ expect(deriveWedgeSignal({ active_healthy: 0, waiting: 0, minutes_since_completion: null }).wedged).toBe(false);
+ });
+ });
+});
diff --git a/test/mcp-stdio-gate-list.test.ts b/test/mcp-stdio-gate-list.test.ts
new file mode 100644
index 0000000000..9a6ca69f92
--- /dev/null
+++ b/test/mcp-stdio-gate-list.test.ts
@@ -0,0 +1,78 @@
+/**
+ * B1 (CLI→MCP gap-closure wave) — stdio tools/list honesty.
+ *
+ * stdio dispatches remote:true, and publish-gate enforcement
+ * (assertPublishEnabled, the advisor inline gate) exempts only
+ * ctx.remote === false — so the stdio ListTools handler must subtract
+ * gate-off publish-gated ops or it advertises tools that deny at call time
+ * (the listed-but-denied class the honest-catalog wave exists to kill).
+ * localOnly ops stay listed: locality is the transport axis (D7), consent is
+ * the gate axis. These tests pin stdioVisibleTools, the extracted per-request
+ * list builder.
+ */
+import { describe, test, expect } from 'bun:test';
+import { stdioVisibleTools } from '../src/mcp/server.ts';
+import { operations } from '../src/core/operations.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const GATED = operations.filter(op => op.publishGateKey).map(op => op.name);
+const LOCAL_ONLY = operations.filter(op => op.localOnly).map(op => op.name);
+
+function engineWithGates(values: Record<string, string | null>): BrainEngine {
+ return {
+ getConfig: async (key: string) => values[key] ?? null,
+ } as unknown as BrainEngine;
+}
+
+describe('stdioVisibleTools (B1)', () => {
+ test('there are publish-gated ops to subtract (fixture sanity)', () => {
+ expect(GATED.length).toBeGreaterThanOrEqual(4);
+ expect(GATED).toContain('list_skills');
+ expect(GATED).toContain('advisor');
+ });
+
+ test('gates off (DB plane false): every gated op is subtracted, localOnly ops stay', async () => {
+ const engine = engineWithGates({ 'mcp.publish_skills': 'false', 'mcp.publish_advisor': 'false' });
+ const visible = await stdioVisibleTools(engine, operations);
+ const names = visible.map(op => op.name);
+ for (const gated of GATED) expect(names).not.toContain(gated);
+ // D7: stdio IS the local surface — localOnly ops remain listed.
+ for (const local of LOCAL_ONLY) expect(names).toContain(local);
+ expect(names).toContain('get_page');
+ });
+
+ test('one gate on: only that gate’s ops return', async () => {
+ const engine = engineWithGates({ 'mcp.publish_skills': 'true', 'mcp.publish_advisor': 'false' });
+ const names = (await stdioVisibleTools(engine, operations)).map(op => op.name);
+ expect(names).toContain('list_skills');
+ expect(names).toContain('get_skill');
+ expect(names).not.toContain('advisor');
+ });
+
+ test('both gates on: full surfaced set returned unchanged', async () => {
+ const engine = engineWithGates({ 'mcp.publish_skills': 'true', 'mcp.publish_advisor': 'true' });
+ const visible = await stdioVisibleTools(engine, operations);
+ expect(visible.length).toBe(operations.length);
+ });
+
+ test('gate resolver failure hides every gated op (fail-closed), never throws', async () => {
+ const engine = {
+ getConfig: async () => { throw new Error('config table unavailable'); },
+ } as unknown as BrainEngine;
+ const names = (await stdioVisibleTools(engine, operations)).map(op => op.name);
+ // A failed read resolves false per publish-gates doctrine (hide-on-doubt).
+ for (const gated of GATED) expect(names).not.toContain(gated);
+ expect(names).toContain('get_page');
+ });
+
+ test('surfaced set without gated ops passes through untouched (no gate read needed)', async () => {
+ const ungated = operations.filter(op => !op.publishGateKey);
+ let reads = 0;
+ const engine = {
+ getConfig: async () => { reads += 1; return null; },
+ } as unknown as BrainEngine;
+ const visible = await stdioVisibleTools(engine, ungated);
+ expect(visible.length).toBe(ungated.length);
+ expect(reads).toBe(0);
+ });
+});
diff --git a/test/migration-ledger.test.ts b/test/migration-ledger.test.ts
new file mode 100644
index 0000000000..30c2915702
--- /dev/null
+++ b/test/migration-ledger.test.ts
@@ -0,0 +1,171 @@
+/**
+ * CLI→MCP gap-closure wave — core/migration-ledger.ts (the get_health
+ * migrations block, TODOS:4063). Pins:
+ * - MIGRATION_VERSIONS stays in sync with the real registry (EV4: the core
+ * module carries version strings only, so drift must fail the suite).
+ * - statusForVersion semantics (complete-wins, trailing-retry override,
+ * consecutive-partial wedge cap) — shared with apply-migrations.
+ * - migrationLedgerSummary fixtures incl. skipped_future;
+ * - the get_health OP layer over dispatchToolCall (real PGLiteEngine): the
+ * migrations block carries the four keys, and an unreadable ledger
+ * degrades to {error: 'ledger_unreadable'} without dropping the health
+ * payload itself.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ MIGRATION_VERSIONS,
+ MAX_CONSECUTIVE_PARTIALS,
+ compareVersions,
+ statusForVersion,
+ indexCompletedEntries,
+ migrationLedgerSummary,
+} from '../src/core/migration-ledger.ts';
+import { migrations } from '../src/commands/migrations/index.ts';
+import type { CompletedMigrationEntry } from '../src/core/preferences.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+function entry(version: string, status: CompletedMigrationEntry['status']): CompletedMigrationEntry {
+ return { ts: '2026-08-16T00:00:00Z', version, status } as CompletedMigrationEntry;
+}
+
+describe('MIGRATION_VERSIONS registry sync (EV4)', () => {
+ test('matches the real migration registry exactly, in order', () => {
+ expect([...MIGRATION_VERSIONS]).toEqual(migrations.map(m => m.version));
+ });
+});
+
+describe('statusForVersion (shared with apply-migrations)', () => {
+ test('no entries → pending; complete wins; trailing retry overrides complete', () => {
+ expect(statusForVersion('0.21.0', indexCompletedEntries([]))).toBe('pending');
+ expect(statusForVersion('0.21.0', indexCompletedEntries([entry('0.21.0', 'complete')]))).toBe('complete');
+ expect(statusForVersion('0.21.0', indexCompletedEntries([
+ entry('0.21.0', 'partial'), entry('0.21.0', 'complete'),
+ ]))).toBe('complete');
+ expect(statusForVersion('0.21.0', indexCompletedEntries([
+ entry('0.21.0', 'complete'), entry('0.21.0', 'retry'),
+ ]))).toBe('pending');
+ });
+
+ test('consecutive-partial cap wedges; a lone partial stays partial', () => {
+ expect(statusForVersion('0.28.0', indexCompletedEntries([entry('0.28.0', 'partial')]))).toBe('partial');
+ const wedgedEntries = Array.from({ length: MAX_CONSECUTIVE_PARTIALS }, () => entry('0.28.0', 'partial'));
+ expect(statusForVersion('0.28.0', indexCompletedEntries(wedgedEntries))).toBe('wedged');
+ });
+});
+
+describe('compareVersions (canonical home)', () => {
+ test('orders MAJOR.MINOR.PATCH', () => {
+ expect(compareVersions('0.21.0', '0.28.0')).toBe(-1);
+ expect(compareVersions('0.46.3', '0.46.3')).toBe(0);
+ expect(compareVersions('1.0.0', '0.99.9')).toBe(1);
+ });
+});
+
+describe('migrationLedgerSummary', () => {
+ test('fixture ledger → pending/partial/wedged buckets + skipped_future count', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-'));
+ // GBRAIN_HOME is a PARENT dir — configDir() appends '.gbrain' itself.
+ mkdirSync(join(home, '.gbrain', 'migrations'), { recursive: true });
+ const special = new Set(['0.21.0', '0.28.0', '0.29.1']);
+ const lines = [
+ // Everything complete except: 0.21.0 pending (complete + trailing
+ // retry — the only marker that overrides a completion), 0.28.0 partial
+ // (a lone partial, never completed), 0.29.1 wedged (cap consecutive
+ // partials, never completed).
+ ...MIGRATION_VERSIONS.filter(v => !special.has(v)).map(v => JSON.stringify(entry(v, 'complete'))),
+ JSON.stringify(entry('0.21.0', 'complete')),
+ JSON.stringify(entry('0.21.0', 'retry')),
+ JSON.stringify(entry('0.28.0', 'partial')),
+ ...Array.from({ length: MAX_CONSECUTIVE_PARTIALS }, () => JSON.stringify(entry('0.29.1', 'partial'))),
+ ];
+ writeFileSync(join(home, '.gbrain', 'migrations', 'completed.jsonl'), lines.join('\n') + '\n');
+
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ // Installed version below the newest registry entries → they count as
+ // skipped_future, not pending.
+ const summary = migrationLedgerSummary('0.30.0');
+ expect(summary.pending).toContain('0.21.0');
+ expect(summary.partial).toEqual(['0.28.0']);
+ expect(summary.wedged).toEqual(['0.29.1']);
+ const future = MIGRATION_VERSIONS.filter(v => compareVersions(v, '0.30.0') > 0).length;
+ expect(summary.skipped_future).toBe(future);
+ });
+ });
+
+ test('empty ledger at current VERSION → everything registered is pending', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-empty-'));
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const summary = migrationLedgerSummary('99.0.0');
+ expect(summary.pending.length).toBe(MIGRATION_VERSIONS.length);
+ expect(summary.skipped_future).toBe(0);
+ });
+ });
+});
+
+describe('get_health op layer (dispatchToolCall, real PGLiteEngine)', () => {
+ let engine: import('../src/core/pglite-engine.ts').PGLiteEngine;
+ const tmpHomes: string[] = [];
+
+ beforeAll(async () => {
+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ for (const home of tmpHomes.splice(0)) {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+
+ test('migrations block carries the four ledger keys', async () => {
+ const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
+ // GBRAIN_HOME is a PARENT dir — configDir() appends '.gbrain' itself.
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-op-'));
+ tmpHomes.push(home);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const res = await dispatchToolCall(engine, 'get_health', {}, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = JSON.parse(res.content[0].text) as {
+ page_count: number;
+ migrations: { pending: string[]; partial: string[]; wedged: string[]; skipped_future: number };
+ };
+ expect(Object.keys(body.migrations).sort()).toEqual(['partial', 'pending', 'skipped_future', 'wedged'].sort());
+ expect(Array.isArray(body.migrations.pending)).toBe(true);
+ expect(Array.isArray(body.migrations.partial)).toBe(true);
+ expect(Array.isArray(body.migrations.wedged)).toBe(true);
+ expect(typeof body.migrations.skipped_future).toBe('number');
+ expect(typeof body.page_count).toBe('number');
+ });
+ });
+
+ test('unreadable ledger degrades migrations to {error: ledger_unreadable}; health payload survives', async () => {
+ const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ledger-op-bad-'));
+ tmpHomes.push(home);
+ // completed.jsonl as a DIRECTORY: existsSync passes, readFileSync throws
+ // EISDIR — the op's best-effort catch must degrade the field only.
+ mkdirSync(join(home, '.gbrain', 'migrations', 'completed.jsonl'), { recursive: true });
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const res = await dispatchToolCall(engine, 'get_health', {}, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = JSON.parse(res.content[0].text) as {
+ page_count: number;
+ linkable_page_count: number;
+ migrations: unknown;
+ };
+ expect(body.migrations).toEqual({ error: 'ledger_unreadable' });
+ // Page-count fields still exist — the degradation never eats the dashboard.
+ expect(typeof body.page_count).toBe('number');
+ expect(typeof body.linkable_page_count).toBe('number');
+ });
+ });
+});
diff --git a/test/operations-descriptions.test.ts b/test/operations-descriptions.test.ts
index b9822ffac5..9fb2f16cc1 100644
--- a/test/operations-descriptions.test.ts
+++ b/test/operations-descriptions.test.ts
@@ -10,6 +10,7 @@ import {
GET_SKILL_DESCRIPTION,
SKILL_CATALOG_INSTRUCTIONS,
SKILL_CLIENT_GUIDANCE,
+ CAPTURE_DESCRIPTION,
} from '../src/core/operations-descriptions.ts';
import { operations, operationsByName } from '../src/core/operations.ts';
import { BRAIN_TOOL_ALLOWLIST } from '../src/core/minions/tools/brain-allowlist.ts';
@@ -168,6 +169,19 @@ describe('v0.29 — operations array carries the three new ops', () => {
});
});
+describe('CLI→MCP gap-closure wave — capture description', () => {
+ test('matches the operation registration', () => {
+ expect(operationsByName['capture'].description).toBe(CAPTURE_DESCRIPTION);
+ });
+
+ test('teaches the capture/put_page/remember routing split', () => {
+ // capture = quick notes with auto-slug + dedupe; put_page = full control;
+ // structured entity facts route to remember.
+ expect(CAPTURE_DESCRIPTION).toContain('put_page');
+ expect(CAPTURE_DESCRIPTION).toContain('remember');
+ });
+});
+
describe('PR1 — skill catalog descriptions', () => {
test('list_skills / get_skill match the operation registration', () => {
expect(operationsByName['list_skills'].description).toBe(LIST_SKILLS_DESCRIPTION);
diff --git a/test/quarantine-cache-ops.test.ts b/test/quarantine-cache-ops.test.ts
new file mode 100644
index 0000000000..cf32f7cc4a
--- /dev/null
+++ b/test/quarantine-cache-ops.test.ts
@@ -0,0 +1,94 @@
+/**
+ * CLI→MCP gap-closure wave — quarantine_list + cache_stats ops. Pins marker
+ * detection, include_flagged, the truncation/lower-bound contract [OV13],
+ * source scoping, and the cache-stats knob merge. Exercised via
+ * dispatchToolCall against a real PGLite engine (the request-tools pattern).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { QUARANTINE_KEY, CONTENT_FLAG_KEY } from '../src/core/quarantine.ts';
+
+let engine: PGLiteEngine;
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ // Three pages: hidden (quarantine), flagged (content_flag), clean.
+ await engine.putPage('junk/hidden-one', {
+ type: 'note', title: 'Junk', compiled_truth: 'low value',
+ frontmatter: { [QUARANTINE_KEY]: { reason: 'markup_ratio', assessed_at: '2026-08-01' } },
+ });
+ await engine.putPage('fuzzy/flagged-one', {
+ type: 'note', title: 'Fuzzy', compiled_truth: 'maybe junk',
+ frontmatter: { [CONTENT_FLAG_KEY]: { reason: 'oversize', assessed_at: '2026-08-02' } },
+ });
+ await engine.putPage('clean/page-one', { type: 'note', title: 'Clean', compiled_truth: 'fine' });
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('quarantine_list op', () => {
+ test('lists quarantined pages only by default; flagged pages join with include_flagged', async () => {
+ const res = await dispatchToolCall(engine, 'quarantine_list', {}, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.schema_version).toBe(1);
+ const slugs = body.rows.map((r: { slug: string }) => r.slug);
+ expect(slugs).toContain('junk/hidden-one');
+ expect(slugs).not.toContain('fuzzy/flagged-one');
+ expect(slugs).not.toContain('clean/page-one');
+ expect(body.truncated).toBe(false);
+ expect(body.scanned).toBeGreaterThanOrEqual(3);
+
+ const withFlagged = parsed(await dispatchToolCall(engine, 'quarantine_list', { include_flagged: true }, { ...STDIO }));
+ const flaggedSlugs = withFlagged.rows.map((r: { slug: string; marker: string }) => r.slug);
+ expect(flaggedSlugs).toContain('fuzzy/flagged-one');
+ const flaggedRow = withFlagged.rows.find((r: { slug: string }) => r.slug === 'fuzzy/flagged-one');
+ expect(flaggedRow.marker).toBe('content_flag');
+ expect(flaggedRow.reason).toBe('oversize');
+ });
+
+ test('OV13: bounded scan sets truncated and count is a lower bound', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'quarantine_list', { include_flagged: true, limit: 1 }, { ...STDIO }));
+ expect(body.count).toBe(1);
+ expect(body.truncated).toBe(true);
+
+ const scanBound = parsed(await dispatchToolCall(engine, 'quarantine_list', { max_scan: 1 }, { ...STDIO }));
+ expect(scanBound.scanned).toBeLessThanOrEqual(1);
+ expect(scanBound.truncated).toBe(true);
+ });
+
+ test('source scoping: a foreign-source scope sees nothing', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'quarantine_list', { include_flagged: true }, {
+ ...STDIO, sourceId: 'some-other-source',
+ }));
+ expect(body.count).toBe(0);
+ });
+});
+
+describe('cache_stats op', () => {
+ test('returns resolved knobs + counter shape', async () => {
+ const res = await dispatchToolCall(engine, 'cache_stats', {}, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.schema_version).toBe(1);
+ expect(typeof body.enabled).toBe('boolean');
+ expect(body.similarity_threshold).toBeGreaterThan(0);
+ expect(body.ttl_seconds).toBeGreaterThan(0);
+ expect(typeof body.total_rows).toBe('number');
+ expect(typeof body.total_hits).toBe('number');
+ expect(typeof body.fresh_rows).toBe('number');
+ expect(typeof body.stale_rows).toBe('number');
+ });
+});
diff --git a/test/request-tools.test.ts b/test/request-tools.test.ts
index bb56f354a2..bee1220d7c 100644
--- a/test/request-tools.test.ts
+++ b/test/request-tools.test.ts
@@ -95,13 +95,32 @@ describe('request_tools catalog (no args)', () => {
expect(raw).not.toContain('advisor');
});
- test('stdio transport: localOnly listed (D7) and publish gates bypassed (local surface)', async () => {
+ test('stdio transport: localOnly listed (D7) but gate-off publish-gated ops hidden', async () => {
+ // Two distinct axes: stdio IS the local pipe (locality — localOnly ops
+ // dispatch there, so they list), but publish-gate enforcement exempts
+ // only remote === false and stdio dispatches remote:true — a gate-off op
+ // in this catalog would deny at call time (the listed-but-denied class).
const res = await dispatchToolCall(engine, 'request_tools', {}, {
remote: true, transport: 'stdio', sourceId: 'default',
});
const names = flatNames(parsed(res).catalog);
expect(names).toContain('file_list');
- expect(names).toContain('list_skills');
+ expect(names).not.toContain('list_skills');
+ expect(names).not.toContain('advisor');
+ });
+
+ test('stdio transport: gated ops appear once their gate is on (DB plane)', async () => {
+ await engine.setConfig('mcp.publish_skills', 'true');
+ try {
+ const res = await dispatchToolCall(engine, 'request_tools', {}, {
+ remote: true, transport: 'stdio', sourceId: 'default',
+ });
+ const names = flatNames(parsed(res).catalog);
+ expect(names).toContain('list_skills');
+ expect(names).not.toContain('advisor'); // separate gate, still off
+ } finally {
+ await engine.setConfig('mcp.publish_skills', 'false');
+ }
});
test('trusted local CLI (remote === false, no transport): localOnly + gated ops visible', async () => {
diff --git a/test/search-introspection-ops.test.ts b/test/search-introspection-ops.test.ts
new file mode 100644
index 0000000000..3e38a5282e
--- /dev/null
+++ b/test/search-introspection-ops.test.ts
@@ -0,0 +1,96 @@
+/**
+ * CLI→MCP gap-closure wave — search_stats / search_modes / search_tune ops.
+ * Pins the dashboard shapes (glossary block included per CDX-25), knob
+ * attribution, the insufficient-data tune path, and the read-only guarantee
+ * (search_tune NEVER mutates config — apply is CLI-only per CDX-21).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { operationsByName } from '../src/core/operations.ts';
+
+let engine: PGLiteEngine;
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('search_stats op', () => {
+ test('empty telemetry: zero counts, coverage caveat, glossary block', async () => {
+ const res = await dispatchToolCall(engine, 'search_stats', { days: 30 }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.schema_version).toBe(2);
+ expect(body.total_calls).toBe(0);
+ expect(body.window_days).toBe(30);
+ expect(body.coverage).toBeDefined();
+ expect(typeof body.graph_signals.enabled).toBe('boolean');
+ expect(body._meta.metric_glossary.cache_hit_rate).toContain('cache_hits');
+ });
+});
+
+describe('search_modes op', () => {
+ test('resolved knobs carry value + attribution + description; bundles frozen', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'search_modes', {}, { ...STDIO }));
+ expect(body.schema_version).toBe(2);
+ expect(['conservative', 'balanced', 'tokenmax']).toContain(body.active_mode);
+ const knob = body.resolved.tokenBudget;
+ expect(knob).toBeDefined();
+ expect(typeof knob.source).toBe('string');
+ expect(typeof knob.description).toBe('string');
+ expect(Object.keys(body.bundles).sort()).toEqual(['balanced', 'conservative', 'tokenmax']);
+ expect(operationsByName['search_modes'].scope).toBe('read');
+ });
+});
+
+describe('search_stats on a pre-telemetry brain degrades gracefully', () => {
+ test('a missing search_telemetry table yields zero-filled stats (the long-standing best-effort contract), not a crash', async () => {
+ // readSearchStats is intentionally graceful for a pre-v0.32.3 brain that
+ // has no telemetry table — it returns "0 searches" (the coverage caveat in
+ // the op description explains low/zero counts), a contract pinned by
+ // test/search-telemetry.test.ts and relied on by the CLI dashboard. The op
+ // wraps readSearchStats in withRelationGuard for OTHER unexpected relation
+ // errors, but the missing-telemetry-table case stays a healthy-empty
+ // dashboard (an earlier gap-closure rethrow that broke this was reverted).
+ const bareEngine = {
+ async executeRaw() {
+ throw new Error('relation "search_telemetry" does not exist');
+ },
+ // readGraphSignalsStats reads config (not the telemetry table); stub it
+ // so the op's graph-signals section resolves via the mode-default path.
+ async getConfig() { return null; },
+ } as unknown as PGLiteEngine;
+ const res = await dispatchToolCall(bareEngine, 'search_stats', { days: 30 }, { ...STDIO });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.total_calls).toBe(0);
+ expect(body.schema_version).toBe(2);
+ });
+});
+
+describe('search_tune op', () => {
+ test('insufficient data on a fresh brain; NEVER mutates config', async () => {
+ const before = await engine.listConfigKeys('search.');
+ const body = parsed(await dispatchToolCall(engine, 'search_tune', {}, { ...STDIO }));
+ expect(body.status).toBe('insufficient_data');
+ expect(body.recommendations).toEqual([]);
+ expect(typeof body.total_calls).toBe('number');
+ const after = await engine.listConfigKeys('search.');
+ expect(after).toEqual(before);
+ // No apply param exists on the op surface at all (CDX-21).
+ expect(Object.keys(operationsByName['search_tune'].params)).toEqual([]);
+ });
+});
diff --git a/test/takes-command-source-scope.test.ts b/test/takes-command-source-scope.test.ts
index 59f8c4b18d..bef9fe5169 100644
--- a/test/takes-command-source-scope.test.ts
+++ b/test/takes-command-source-scope.test.ts
@@ -1,9 +1,9 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runTakes } from '../src/commands/takes.ts';
-import type { BrainEngine, TakeBatchInput, TakesListOpts } from '../src/core/engine.ts';
+import type { BrainEngine, TakeBatchInput } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
const tmpRoots: string[] = [];
@@ -84,7 +84,11 @@ describe('gbrain takes CLI source scoping', () => {
expect(added).toHaveLength(1);
expect(added[0]![0]!.page_id).toBe(22);
- const written = join(brainDir, 'shared/page.md');
+ // P1-1 source isolation: a non-default source with no own local_path files
+ // its pages under `.sources/<id>/` in the shared repo (mirrors write-through
+ // topology), NOT the shared root — the old `<brainDir>/<slug>.md` clobbered a
+ // same-slug file in the wrong tree.
+ const written = join(brainDir, '.sources', 'dept', 'shared/page.md');
expect(existsSync(written)).toBe(true);
expect(readFileSync(written, 'utf-8')).toContain('Dept-scoped claim');
});
@@ -151,11 +155,27 @@ describe('gbrain takes CLI source scoping', () => {
expect(existsSync(join(brainDir, 'shared/page.md'))).toBe(false);
});
- test('supersede looks up the active row it is replacing (#2663)', async () => {
+ test('supersede inherits from the markdown fence row it is replacing (#2663, EV1 md-canonical)', async () => {
+ // v0.46.x (EV1): supersede is fence-first — the target row is looked up in
+ // the on-disk markdown (canonical), kind/holder inherit from that row, the
+ // fence assigns the new row number, and the DB mirror is addTakesBatch's
+ // upsert of both affected rows (the reconcile primitive). The pre-EV1
+ // shape (engine.listTakes lookup + engine.supersedeTake DB numbering)
+ // could disagree with a later md→DB reconcile.
const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-takes-supersede-'));
const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-home-'));
tmpRoots.push(brainDir, home);
- const listCalls: TakesListOpts[] = [];
+ const { renderTakesFence } = await import('../src/core/takes-fence.ts');
+ mkdirSync(join(brainDir, 'shared'), { recursive: true });
+ writeFileSync(
+ join(brainDir, 'shared/page.md'),
+ `# Shared page\n\n## Takes\n\n${renderTakesFence([{
+ rowNum: 3, claim: 'Current claim', kind: 'take', holder: 'self',
+ weight: 0.8, active: true,
+ }])}\n`,
+ 'utf-8',
+ );
+ const batches: unknown[][] = [];
const engine = {
getConfig: async () => null,
executeRaw: async (sql: string, params: unknown[] = []) => {
@@ -164,35 +184,151 @@ describe('gbrain takes CLI source scoping', () => {
if (sql.includes('FROM pages WHERE slug = $1 AND source_id = $2')) return [{ id: 11 }];
return [];
},
- listTakes: async (opts: TakesListOpts) => {
- listCalls.push(opts);
- return [{
- page_id: 11,
- row_num: 3,
- claim: 'Current claim',
- kind: 'take',
- holder: 'self',
- weight: 0.8,
- active: true,
- }];
+ addTakesBatch: async (rows: unknown[]) => { batches.push(rows); return rows.length; },
+ } as unknown as BrainEngine;
+
+ const logs: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ try {
+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, async () => {
+ await runTakes(engine, [
+ 'supersede',
+ 'shared/page',
+ '--row',
+ '3',
+ '--claim',
+ 'Replacement claim',
+ '--dir',
+ brainDir,
+ ]);
+ });
+ } finally {
+ logSpy.mockRestore();
+ }
+
+ expect(logs.join('\n')).toContain('Superseded #3 → new #4 on shared/page.');
+ // One mirror batch carrying both affected rows exactly as the fence states.
+ expect(batches.length).toBe(1);
+ const rows = batches[0] as Array<{ row_num: number; active: boolean; superseded_by: number | null; kind: string; holder: string }>;
+ const oldRow = rows.find(r => r.row_num === 3);
+ const newRow = rows.find(r => r.row_num === 4);
+ expect(oldRow?.active).toBe(false);
+ expect(oldRow?.superseded_by).toBe(4);
+ // kind/holder inherited from the fence row.
+ expect(newRow?.active).toBe(true);
+ expect(newRow?.kind).toBe('take');
+ expect(newRow?.holder).toBe('self');
+ });
+});
+
+describe('gbrain takes update/resolve — md-canonical CLI lanes (EV1)', () => {
+ test('update on a row missing from the md fence exits 1 with row-not-found; no DB write attempted', async () => {
+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-takes-update-miss-'));
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-home-'));
+ tmpRoots.push(brainDir, home);
+ const { renderTakesFence } = await import('../src/core/takes-fence.ts');
+ mkdirSync(join(brainDir, 'shared'), { recursive: true });
+ writeFileSync(
+ join(brainDir, 'shared/page.md'),
+ `# Shared page\n\n## Takes\n\n${renderTakesFence([{
+ rowNum: 3, claim: 'Current claim', kind: 'take', holder: 'self',
+ weight: 0.8, active: true,
+ }])}\n`,
+ 'utf-8',
+ );
+ const batches: unknown[][] = [];
+ const updates: unknown[] = [];
+ const engine = {
+ getConfig: async () => null,
+ executeRaw: async (sql: string, params: unknown[] = []) => {
+ if (sql.includes('FROM sources WHERE id = $1')) return [{ id: params[0] as string }];
+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) return [];
+ if (sql.includes('FROM pages WHERE slug = $1 AND source_id = $2')) return [{ id: 11 }];
+ return [];
},
- supersedeTake: async () => ({ oldRow: 3, newRow: 4 }),
+ addTakesBatch: async (rows: unknown[]) => { batches.push(rows); return rows.length; },
+ updateTake: async (...args: unknown[]) => { updates.push(args); return true; },
} as unknown as BrainEngine;
- await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, async () => {
- await runTakes(engine, [
- 'supersede',
- 'shared/page',
- '--row',
- '3',
- '--claim',
- 'Replacement claim',
- '--dir',
- brainDir,
- ]);
- });
+ const errs: string[] = [];
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+
+ let exited: string | null = null;
+ try {
+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, async () => {
+ // Row 5 does not exist in the fence (only row 3 does).
+ await runTakes(engine, ['update', 'shared/page', '--row', '5', '--weight', '0.9', '--dir', brainDir]);
+ });
+ } catch (e) {
+ if (!(e as Error).message.startsWith('EXIT:')) throw e;
+ exited = (e as Error).message;
+ } finally {
+ errSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+
+ expect(exited).toBe('EXIT:1');
+ expect(errs.join('\n')).toContain('Row #5 not found on shared/page');
+ // EV1 refusal is refusal — no DB write of any kind was attempted.
+ expect(batches).toHaveLength(0);
+ expect(updates).toHaveLength(0);
+ // And the on-disk fence is untouched.
+ expect(readFileSync(join(brainDir, 'shared/page.md'), 'utf-8')).toContain('Current claim');
+ });
+
+ test('resolve --outcome true maps to quality=correct (back-compat alias lane)', async () => {
+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-takes-resolve-outcome-'));
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-takes-home-'));
+ tmpRoots.push(brainDir, home);
+ const { renderTakesFence } = await import('../src/core/takes-fence.ts');
+ mkdirSync(join(brainDir, 'shared'), { recursive: true });
+ writeFileSync(
+ join(brainDir, 'shared/page.md'),
+ `# Shared page\n\n## Takes\n\n${renderTakesFence([{
+ rowNum: 3, claim: 'Bet claim', kind: 'bet', holder: 'self',
+ weight: 0.8, active: true,
+ }])}\n`,
+ 'utf-8',
+ );
+ const resolves: Array<{ pageId: number; rowNum: number; args: Record<string, unknown> }> = [];
+ const engine = {
+ getConfig: async () => null,
+ executeRaw: async (sql: string, params: unknown[] = []) => {
+ if (sql.includes('FROM sources WHERE id = $1')) return [{ id: params[0] as string }];
+ if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) return [];
+ if (sql.includes('FROM pages WHERE slug = $1 AND source_id = $2')) return [{ id: 11 }];
+ return [];
+ },
+ addTakesBatch: async (rows: unknown[]) => rows.length,
+ resolveTake: async (pageId: number, rowNum: number, args: Record<string, unknown>) => {
+ resolves.push({ pageId, rowNum, args });
+ return true;
+ },
+ } as unknown as BrainEngine;
+
+ const logs: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation(() => {}); // swallow the [deprecated] alias warn
+ try {
+ await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, async () => {
+ await runTakes(engine, ['resolve', 'shared/page', '--row', '3', '--outcome', 'true', '--dir', brainDir]);
+ });
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ }
- expect(listCalls).toEqual([{ page_id: 11, active: true, limit: 500 }]);
+ // The success line names the MAPPED quality, not the raw outcome flag.
+ expect(logs.join('\n')).toContain('Resolved take #3 on shared/page: quality=correct');
+ // And the DB mirror got quality 'correct' / outcome true.
+ expect(resolves).toHaveLength(1);
+ expect(resolves[0]!.args.quality).toBe('correct');
+ expect(resolves[0]!.args.outcome).toBe(true);
+ // Markdown mirror carries the resolution (md-first).
+ expect(readFileSync(join(brainDir, 'shared/page.md'), 'utf-8')).toContain('correct');
});
});
diff --git a/test/takes-write-ops.test.ts b/test/takes-write-ops.test.ts
new file mode 100644
index 0000000000..ac2d8a4355
--- /dev/null
+++ b/test/takes-write-ops.test.ts
@@ -0,0 +1,506 @@
+/**
+ * CLI→MCP gap-closure wave — takes_add / takes_update / takes_resolve /
+ * takes_supersede ops over dispatchToolCall (real PGLite engine + a temp
+ * markdown repo as sync.repo_path).
+ *
+ * Pins the load-bearing trust + md-canonical semantics:
+ * - mirror-mandatory refusal (takes_mirror_unavailable) when sync.repo_path
+ * is unset [EV1]
+ * - holder WRITE fence: hit/miss/[] deny-all/undefined→['world'] default,
+ * threaded through dispatchToolCall (the wiring, not just the handler)
+ * [CEO-F8]
+ * - fenced rows present as not_found — same shape as a missing row [CEO-F4]
+ * - fence round-trip: md written first, DB mirrored with the reconcile
+ * primitive; fence-create-if-absent on a page's first take [CEO-F6]
+ * - resolved_by server-stamped mcp:<client> for remote callers +
+ * mcp_resolved surfacing on takes_scorecard [OV8/EV5]
+ * - immutability: resolved rows refuse update/supersede
+ * - concurrent adds serialize under the page lock: loser gets the
+ * retryable error, retry lands the next sequential row [ENG-E4/EV11]
+ * - dry_run short-circuits
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, symlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { parseTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+const STDIO = { remote: true, transport: 'stdio' as const, sourceId: 'default' };
+/** stdio's hardcoded default allow-list (server.ts) — world-held writes only. */
+const STDIO_WORLD = { ...STDIO, takesHoldersAllowList: ['world'] };
+const LOCAL = { remote: false as const, sourceId: 'default' };
+
+function parsed(result: { content: Array<{ text: string }> }) {
+ return JSON.parse(result.content[0].text);
+}
+
+function pageMd(slug: string): string {
+ return readFileSync(join(repo, `${slug}.md`), 'utf-8');
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-takes-ops-repo-'));
+ await engine.setConfig('sync.repo_path', repo);
+ for (const slug of ['people/alice-example', 'companies/acme-example', 'notes/lockrace']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `about ${slug}` });
+ mkdirSync(join(repo, slug.split('/')[0]), { recursive: true });
+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\nabout ${slug}\n`, 'utf-8');
+ }
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+describe('takes_add', () => {
+ test('creates the fence on first take [CEO-F6], mirrors to DB, returns the fence row number', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'Ships weekly', kind: 'take', holder: 'world', weight: 0.7,
+ }, { ...STDIO_WORLD });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.row_num).toBe(1);
+ expect(body.mirror_written).toBe(true);
+ // md-first: the fence exists on disk with the row.
+ const fence = parseTakesFence(pageMd('people/alice-example'));
+ expect(fence.takes.length).toBe(1);
+ expect(fence.takes[0].claim).toBe('Ships weekly');
+ // DB mirror carries the same row.
+ const rows = await engine.listTakes({ page_slug: 'people/alice-example', active: true });
+ expect(rows.length).toBe(1);
+ expect(rows[0].row_num).toBe(1);
+ expect(rows[0].holder).toBe('world');
+ });
+
+ test('holder fence: outside-allow-list holder denies with machine-readable detail', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'Private hunch', kind: 'hunch', holder: 'people/garry-example',
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ const body = parsed(res);
+ expect(body.error).toBe('permission_denied');
+ expect(body.detail).toBe('holder_not_in_allowlist');
+ });
+
+ test('empty allow-list = deny-all; missing allow-list defaults to world [CEO-F8 wiring]', async () => {
+ const denyAll = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'x', kind: 'fact', holder: 'world',
+ }, { ...STDIO, takesHoldersAllowList: [] });
+ expect(parsed(denyAll).error).toBe('permission_denied');
+
+ // No list threaded at all (remote) → the ['world'] fail-closed default.
+ const defaulted = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'companies/acme-example', claim: 'Raised a round', kind: 'fact', holder: 'world',
+ }, { ...STDIO });
+ expect(parsed(defaulted).row_num).toBe(1);
+ const nonWorld = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'companies/acme-example', claim: 'y', kind: 'fact', holder: 'brain',
+ }, { ...STDIO });
+ expect(parsed(nonWorld).error).toBe('permission_denied');
+ });
+
+ test('trusted local caller is unfenced', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'Owner-held view', kind: 'bet', holder: 'people/garry-example', weight: 0.8,
+ }, { ...LOCAL });
+ expect(parsed(res).row_num).toBe(2);
+ });
+
+ test('mirror-mandatory: unset sync.repo_path refuses with takes_mirror_unavailable [EV1]', async () => {
+ await engine.unsetConfig('sync.repo_path');
+ try {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'z', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ const body = parsed(res);
+ expect(body.error).toBe('unavailable');
+ expect(body.detail).toBe('takes_mirror_unavailable');
+ } finally {
+ await engine.setConfig('sync.repo_path', repo);
+ }
+ });
+
+ test('dry_run short-circuits before any write', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'people/alice-example', claim: 'dry', kind: 'fact', holder: 'world', dry_run: true,
+ }, { ...STDIO_WORLD });
+ expect(parsed(res).dry_run).toBe(true);
+ const fence = parseTakesFence(pageMd('people/alice-example'));
+ expect(fence.takes.some(t => t.claim === 'dry')).toBe(false);
+ });
+
+ test('unknown page → page_not_found', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: 'missing/page', claim: 'x', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ expect(parsed(res).error).toBe('page_not_found');
+ });
+});
+
+describe('takes_update + holder row fence', () => {
+ test('updates mutable fields md-first and mirrors', async () => {
+ const res = await dispatchToolCall(engine, 'takes_update', {
+ slug: 'people/alice-example', row_num: 1, weight: 0.9, source: 'quarterly report',
+ }, { ...STDIO_WORLD });
+ expect(res.isError ?? false).toBe(false);
+ const fence = parseTakesFence(pageMd('people/alice-example'));
+ const row = fence.takes.find(t => t.rowNum === 1);
+ expect(row?.weight).toBe(0.9);
+ expect(row?.source).toBe('quarterly report');
+ const db = (await engine.listTakes({ page_slug: 'people/alice-example', active: true })).find(t => t.row_num === 1);
+ expect(Number(db?.weight)).toBe(0.9);
+ });
+
+ test('[CEO-F4] fenced row and missing row share the not_found shape (no existence leak)', async () => {
+ // Row 2 is holder people/garry-example — outside the world allow-list.
+ const fenced = await dispatchToolCall(engine, 'takes_update', {
+ slug: 'people/alice-example', row_num: 2, weight: 0.1,
+ }, { ...STDIO_WORLD });
+ const missing = await dispatchToolCall(engine, 'takes_update', {
+ slug: 'people/alice-example', row_num: 99, weight: 0.1,
+ }, { ...STDIO_WORLD });
+ const fencedBody = parsed(fenced);
+ const missingBody = parsed(missing);
+ expect(fencedBody.error).toBe('not_found');
+ expect(missingBody.error).toBe('not_found');
+ // Same shape: identical keys, and messages differing only by row number.
+ expect(Object.keys(fencedBody).sort()).toEqual(Object.keys(missingBody).sort());
+ expect(fencedBody.message.replace('#2', '#N')).toBe(missingBody.message.replace('#99', '#N'));
+ });
+
+ test('zero mutable fields → invalid_params', async () => {
+ const res = await dispatchToolCall(engine, 'takes_update', {
+ slug: 'people/alice-example', row_num: 1,
+ }, { ...STDIO_WORLD });
+ expect(parsed(res).error).toBe('invalid_params');
+ });
+});
+
+describe('takes_resolve', () => {
+ test('remote resolution is server-stamped mcp:<client> and ignores resolved_by [OV8]', async () => {
+ const res = await dispatchToolCall(engine, 'takes_resolve', {
+ slug: 'people/alice-example', row_num: 1, quality: 'correct',
+ evidence: 'shipped 12 weeks straight', resolved_by: 'people/spoofed-owner',
+ }, { ...STDIO_WORLD });
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.resolved_by).toBe('mcp:stdio');
+ const db = (await engine.listTakes({ page_slug: 'people/alice-example', active: true })).find(t => t.row_num === 1);
+ expect(db?.resolved_quality).toBe('correct');
+ expect(db?.resolved_by).toBe('mcp:stdio');
+ // Markdown mirror carries the resolution too (13-col fence).
+ expect(pageMd('people/alice-example')).toContain('mcp:stdio');
+ });
+
+ test('mcp_resolved surfaces on takes_scorecard [EV5]', async () => {
+ const card = parsed(await dispatchToolCall(engine, 'takes_scorecard', {}, { ...STDIO_WORLD }));
+ expect(card.mcp_resolved).toBeGreaterThanOrEqual(1);
+ });
+
+ test('resolved rows are immutable: update and supersede refuse, re-resolve refuses', async () => {
+ for (const [op, args] of [
+ ['takes_update', { slug: 'people/alice-example', row_num: 1, weight: 0.2 }],
+ ['takes_supersede', { slug: 'people/alice-example', row_num: 1, claim: 'replacement' }],
+ ['takes_resolve', { slug: 'people/alice-example', row_num: 1, quality: 'incorrect' }],
+ ] as const) {
+ const res = await dispatchToolCall(engine, op, args as Record<string, unknown>, { ...STDIO_WORLD });
+ expect(parsed(res).error).toBe('invalid_params');
+ }
+ });
+});
+
+describe('takes_supersede', () => {
+ test('inherits kind/holder from the fence row, strikes old, appends next row, mirrors both', async () => {
+ const add = parsed(await dispatchToolCall(engine, 'takes_add', {
+ slug: 'companies/acme-example', claim: 'Old thesis', kind: 'take', holder: 'world', weight: 0.6,
+ }, { ...STDIO_WORLD }));
+ const res = parsed(await dispatchToolCall(engine, 'takes_supersede', {
+ slug: 'companies/acme-example', row_num: add.row_num, claim: 'New thesis',
+ }, { ...STDIO_WORLD }));
+ expect(res.old_row).toBe(add.row_num);
+ expect(res.new_row).toBeGreaterThan(add.row_num);
+ const fence = parseTakesFence(pageMd('companies/acme-example'));
+ const oldRow = fence.takes.find(t => t.rowNum === res.old_row);
+ const newRow = fence.takes.find(t => t.rowNum === res.new_row);
+ expect(oldRow?.active).toBe(false);
+ expect(newRow?.active).toBe(true);
+ expect(newRow?.kind).toBe('take'); // inherited
+ expect(newRow?.holder).toBe('world'); // inherited
+ expect(newRow?.weight).toBeCloseTo(0.5); // 0.6 - 0.1 decay
+ // DB mirror: old row carries the supersession pointer.
+ const db = await engine.listTakes({ page_slug: 'companies/acme-example', active: false });
+ const dbOld = db.find(t => t.row_num === res.old_row);
+ expect(dbOld?.superseded_by).toBe(res.new_row);
+ });
+
+ test('an explicit override holder must clear the fence too', async () => {
+ const add = parsed(await dispatchToolCall(engine, 'takes_add', {
+ slug: 'companies/acme-example', claim: 'World view', kind: 'take', holder: 'world',
+ }, { ...STDIO_WORLD }));
+ const res = await dispatchToolCall(engine, 'takes_supersede', {
+ slug: 'companies/acme-example', row_num: add.row_num, claim: 'Now private', holder: 'brain',
+ }, { ...STDIO_WORLD });
+ expect(parsed(res).error).toBe('permission_denied');
+ });
+});
+
+// Guard-coverage batch — fresh slugs only (earlier describes create takes on
+// the shared fixtures, so row numbers there are order-dependent; these pages
+// are created here and touched by no other describe).
+describe('takes-write guards (invalid_input / row_inactive / md-absent / mcp_resolved scoping)', () => {
+ beforeAll(async () => {
+ for (const slug of ['notes/guards-input', 'notes/guards-inactive']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `about ${slug}` });
+ mkdirSync(join(repo, slug.split('/')[0]), { recursive: true });
+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\nabout ${slug}\n`, 'utf-8');
+ }
+ // DB row but NO .md file — the md-file-absent refusal fixture.
+ await engine.putPage('notes/md-absent', { type: 'note', title: 'md-absent', compiled_truth: 'db only' });
+ });
+
+ test('invalid_input guards over dispatchToolCall → invalid_params', async () => {
+ const cases: Array<Record<string, unknown>> = [
+ // Newline in the claim: fence cells are single-line.
+ { slug: 'notes/guards-input', claim: 'line one\nline two', kind: 'fact', holder: 'world' },
+ // Fence-marker text in the claim: fence-injection refusal.
+ { slug: 'notes/guards-input', claim: 'contains gbrain:takes marker', kind: 'fact', holder: 'world' },
+ // Out-of-range weight (docs promise 0..1; DB would clamp → md/DB divergence).
+ { slug: 'notes/guards-input', claim: 'ok claim', kind: 'fact', holder: 'world', weight: 7 },
+ // Malformed since date (must be YYYY-MM or YYYY-MM-DD).
+ { slug: 'notes/guards-input', claim: 'ok claim', kind: 'fact', holder: 'world', since: '2026/01/01' },
+ ];
+ for (const args of cases) {
+ const res = await dispatchToolCall(engine, 'takes_add', args, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ expect(parsed(res).error).toBe('invalid_params');
+ }
+ // None of the refused adds touched the fence.
+ const fence = parseTakesFence(pageMd('notes/guards-input'));
+ expect(fence.takes.length).toBe(0);
+ });
+
+ test('row_inactive: update and resolve on a superseded row both refuse, naming the supersession', async () => {
+ const add = parsed(await dispatchToolCall(engine, 'takes_add', {
+ slug: 'notes/guards-inactive', claim: 'Original claim', kind: 'take', holder: 'world', weight: 0.6,
+ }, { ...STDIO_WORLD }));
+ const sup = parsed(await dispatchToolCall(engine, 'takes_supersede', {
+ slug: 'notes/guards-inactive', row_num: add.row_num, claim: 'Replacement claim',
+ }, { ...STDIO_WORLD }));
+ expect(sup.old_row).toBe(add.row_num);
+
+ const upd = parsed(await dispatchToolCall(engine, 'takes_update', {
+ slug: 'notes/guards-inactive', row_num: add.row_num, weight: 0.1,
+ }, { ...STDIO_WORLD }));
+ expect(upd.error).toBe('invalid_params');
+ expect(upd.message).toContain('superseded');
+
+ const resv = parsed(await dispatchToolCall(engine, 'takes_resolve', {
+ slug: 'notes/guards-inactive', row_num: add.row_num, quality: 'correct',
+ }, { ...STDIO_WORLD }));
+ expect(resv.error).toBe('invalid_params');
+ expect(resv.message).toContain('superseded');
+ });
+
+ test('md-file-absent: DB row without a page file refuses with takes_mirror_unavailable', async () => {
+ const res = await dispatchToolCall(engine, 'takes_update', {
+ slug: 'notes/md-absent', row_num: 1, weight: 0.5,
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ const body = parsed(res);
+ expect(body.error).toBe('unavailable');
+ expect(body.detail).toBe('takes_mirror_unavailable');
+ });
+
+ test('countMcpResolved is source-scoped: a foreign sourceId sees mcp_resolved 0', async () => {
+ // Control: the default source carries at least one mcp:stdio resolution
+ // (the takes_resolve describe above), so a zero under a foreign scope is
+ // the scoping working — not a dead counter.
+ const home = parsed(await dispatchToolCall(engine, 'takes_scorecard', {}, { ...STDIO_WORLD }));
+ expect(home.mcp_resolved).toBeGreaterThanOrEqual(1);
+ const foreign = parsed(await dispatchToolCall(engine, 'takes_scorecard', {}, {
+ ...STDIO_WORLD, sourceId: 'foreign-scope-src',
+ }));
+ expect(foreign.mcp_resolved).toBe(0);
+ });
+});
+
+// Adversarial-fix regression batch (garrytan/cli-mcp-parity-audit). Fresh
+// slugs + md fixtures written directly here — earlier describes are
+// order-sensitive on the shared fixtures, so nothing below touches them.
+describe('takes-write adversarial regressions (F1 cross-holder / P1-2 containment / P1-4 mirror-nonfatal / F2 strikethrough / P1-1 per-source)', () => {
+ const F1_SLUG = 'people/f1-crosshold';
+ const F2_SLUG = 'notes/f2-strike';
+ const P14_SLUG = 'notes/p1-4-mirror';
+ const P11_SLUG = 'notes/p1-1-persource';
+ const P12_SLUG = 'escape-link/pwned';
+
+ // Exact fence header/separator renderTakesFence emits, so the fixture round-
+ // trips through parseTakesFence identically to a real extract.
+ const FENCE_HEADER = '| # | claim | kind | who | weight | since | source |';
+ const FENCE_SEP = '|---|-------|------|-----|--------|-------|--------|';
+
+ beforeAll(async () => {
+ for (const slug of [F1_SLUG, F2_SLUG, P14_SLUG, P11_SLUG, P12_SLUG]) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `about ${slug}` });
+ // P12's `escape-link/` dir is a symlink the P1-2 test plants itself — do
+ // NOT pre-create it as a real directory here (that would EEXIST the symlink).
+ if (slug !== P12_SLUG) mkdirSync(join(repo, slug.split('/')[0]), { recursive: true });
+ }
+ // F1 fixture: a VALID world row (row 1) + a row parseTakesFence SKIPS
+ // (kind 'finding' is outside {fact,take,bet,hunch}) held by an identity a
+ // world-fenced caller can't see. Written directly so the fence carries a
+ // parse warning the way a schema-pack-extended brain would.
+ writeFileSync(
+ join(repo, `${F1_SLUG}.md`),
+ [
+ `# ${F1_SLUG}`, '', 'Bio.', '', '## Takes', '',
+ TAKES_FENCE_BEGIN,
+ FENCE_HEADER,
+ FENCE_SEP,
+ '| 1 | Ships consensus fact | fact | world | 0.8 | 2026-01 | public |',
+ '| 2 | Private cross-holder finding | finding | people/garry-example | 0.6 | 2026-02 | owner note |',
+ TAKES_FENCE_END,
+ '',
+ ].join('\n'),
+ 'utf-8',
+ );
+ // F2 + P1-4 start as fence-less pages (add appends the fence).
+ for (const slug of [F2_SLUG, P14_SLUG]) {
+ writeFileSync(join(repo, `${slug}.md`), `# ${slug}\n\nabout ${slug}\n`, 'utf-8');
+ }
+ });
+
+ test('F1: a world takes_update on the valid row refuses (fence_unparsed→invalid_params) and the skipped cross-holder row survives on disk', async () => {
+ const res = await dispatchToolCall(engine, 'takes_update', {
+ slug: F1_SLUG, row_num: 1, weight: 0.3,
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ expect(parsed(res).error).toBe('invalid_params');
+ // Load-bearing: the write was refused BEFORE any whole-fence re-render, so
+ // the row the parser skipped (a private, cross-holder finding) is still on
+ // disk. Without the F1 guard the re-render would have deleted it silently.
+ const onDisk = readFileSync(join(repo, `${F1_SLUG}.md`), 'utf-8');
+ expect(onDisk).toContain('Private cross-holder finding');
+ expect(onDisk).toContain('| finding |'); // the skipped row's kind cell intact
+ expect(onDisk).toContain('people/garry-example');
+ // And the valid row was NOT mutated (weight untouched).
+ expect(onDisk).toContain('| 1 | Ships consensus fact | fact | world | 0.8 |');
+ });
+
+ test('P1-2: a symlinked page dir that escapes the repo root is refused; nothing is written outside the tree', async () => {
+ const external = mkdtempSync(join(tmpdir(), 'gbrain-takes-external-'));
+ // repo/escape-link → external (a sibling tree outside the repo root).
+ symlinkSync(external, join(repo, 'escape-link'), 'dir');
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: P12_SLUG, claim: 'evil', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ const body = parsed(res);
+ // isWriteTargetContained refuses; the op surfaces the mirror-unavailable envelope.
+ expect(body.error).toBe('unavailable');
+ expect(body.detail).toBe('takes_mirror_unavailable');
+ // The containment check fired BEFORE any write — the escaping target is empty.
+ expect(existsSync(join(external, 'pwned.md'))).toBe(false);
+ });
+
+ test('P1-4: a DB addTakesBatch failure is non-fatal — the row is durable in markdown and the result carries a mirror_warning', async () => {
+ const throwingEngine = new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'addTakesBatch') {
+ return async () => { throw new Error('simulated DB mirror failure'); };
+ }
+ const v = (target as unknown as Record<string | symbol, unknown>)[prop];
+ return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(target) : v;
+ },
+ });
+ const res = await dispatchToolCall(throwingEngine, 'takes_add', {
+ slug: P14_SLUG, claim: 'md wins even when the DB mirror fails', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ // No throw, no error envelope — md is canonical and it was written.
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.mirror_written).toBe(true);
+ expect(typeof body.mirror_warning).toBe('string');
+ expect(body.mirror_warning).toContain('simulated DB mirror failure');
+ // The durable row is on disk.
+ const fence = parseTakesFence(pageMd(P14_SLUG));
+ expect(fence.takes.some(t => t.claim === 'md wins even when the DB mirror fails')).toBe(true);
+ });
+
+ test('F2: a wholly-strikethrough claim (~~struck~~) is refused (invalid_params) — it would round-trip as inactive', async () => {
+ const res = await dispatchToolCall(engine, 'takes_add', {
+ slug: F2_SLUG, claim: '~~struck~~', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ expect(res.isError).toBe(true);
+ expect(parsed(res).error).toBe('invalid_params');
+ // Nothing landed — the guard fired before any I/O.
+ expect(parseTakesFence(pageMd(F2_SLUG)).takes.length).toBe(0);
+ });
+
+ test('P1-1: a source with its own local_path files the take under THAT root, not the global sync.repo_path root', async () => {
+ const sourceRoot = mkdtempSync(join(tmpdir(), 'gbrain-takes-source-root-'));
+ // Mock the per-source SELECT so the write resolves to sourceRoot; every
+ // other query (getPageId, the DB mirror) delegates to the real engine.
+ const perSourceEngine = new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'executeRaw') {
+ return async (sql: unknown, params: unknown) => {
+ if (typeof sql === 'string' && /SELECT local_path FROM sources/i.test(sql)) {
+ return [{ local_path: sourceRoot }];
+ }
+ return (target as unknown as { executeRaw: (s: unknown, p: unknown) => Promise<unknown> })
+ .executeRaw(sql, params);
+ };
+ }
+ const v = (target as unknown as Record<string | symbol, unknown>)[prop];
+ return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(target) : v;
+ },
+ });
+ const res = await dispatchToolCall(perSourceEngine, 'takes_add', {
+ slug: P11_SLUG, claim: 'lands under the source local_path', kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ expect(res.isError ?? false).toBe(false);
+ // The take file is at the source's own working tree (default layout = root),
+ // NOT the global repo root.
+ const underSourceRoot = join(sourceRoot, `${P11_SLUG}.md`);
+ expect(existsSync(underSourceRoot)).toBe(true);
+ expect(existsSync(join(repo, `${P11_SLUG}.md`))).toBe(false);
+ expect(parseTakesFence(readFileSync(underSourceRoot, 'utf-8')).takes.some(
+ t => t.claim === 'lands under the source local_path',
+ )).toBe(true);
+ });
+});
+
+describe('concurrency [ENG-E4/EV11]', () => {
+ test('concurrent adds to one page: both eventually land with sequential rows, no silent overwrite', async () => {
+ const call = () => dispatchToolCall(engine, 'takes_add', {
+ slug: 'notes/lockrace', claim: `claim-${Math.random()}`, kind: 'fact', holder: 'world',
+ }, { ...STDIO_WORLD });
+ const [a, b] = await Promise.all([call(), call()]);
+ const bodies = [parsed(a), parsed(b)];
+ const oks = bodies.filter(x => typeof x.row_num === 'number');
+ const errs = bodies.filter(x => x.error);
+ // The 2s lock timeout usually lets both serialize; a loser (if any) is
+ // the retryable shape and its retry lands the next row.
+ for (const e of errs) {
+ expect(e.error).toBe('unavailable');
+ expect(e.detail).toBe('retryable');
+ const retry = parsed(await call());
+ oks.push(retry);
+ }
+ const rows = oks.map(x => x.row_num).sort((x, y) => x - y);
+ expect(new Set(rows).size).toBe(rows.length); // sequential, never overwritten
+ const fence = parseTakesFence(pageMd('notes/lockrace'));
+ expect(fence.takes.length).toBe(rows.length);
+ });
+});
diff --git a/test/thin-client-routing.test.ts b/test/thin-client-routing.test.ts
new file mode 100644
index 0000000000..f777379c41
--- /dev/null
+++ b/test/thin-client-routing.test.ts
@@ -0,0 +1,248 @@
+/**
+ * CLI→MCP gap-closure wave [OV6] — unit pins for routeThinClientCommand
+ * (src/commands/thin-client-routing.ts).
+ *
+ * Three behaviors pinned per route:
+ * (a) op name + param mapping (who→holder, --row→row_num, --outcome
+ * true→correct, --days→number, --queue passthrough, --include-flagged);
+ * (b) host-bound forms return false (search modes --reset, search tune
+ * --apply, quarantine scan/clear, takes extract) so the caller falls
+ * through to refuseThinClient's hint;
+ * (c) recognized-but-malformed routable forms print usage + exit(1)
+ * instead of returning false (the subcommand IS routable — the args
+ * are just wrong).
+ *
+ * The remote transport is stubbed via spyOn on the mcp-client module
+ * namespace (NOT mock.module — isolation guard R2 keeps module mocks out of
+ * non-serial files): callRemoteTool records (tool, args) and returns a real
+ * MCP content envelope, so the REAL unpackToolResult exercises the
+ * JSON.parse(content[0].text) path.
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import * as mcpClient from '../src/core/mcp-client.ts';
+import { routeThinClientCommand } from '../src/commands/thin-client-routing.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+const cfg = {} as GBrainConfig; // callRemoteTool is stubbed; cfg is never read
+
+const calls: Array<{ tool: string; args: Record<string, unknown> }> = [];
+let callSpy: ReturnType<typeof spyOn>;
+let logSpy: ReturnType<typeof spyOn>;
+let errSpy: ReturnType<typeof spyOn>;
+const logs: string[] = [];
+const errs: string[] = [];
+
+beforeAll(() => {
+ callSpy = spyOn(mcpClient, 'callRemoteTool').mockImplementation(
+ async (_cfg: GBrainConfig, tool: string, args: Record<string, unknown> = {}) => {
+ calls.push({ tool, args });
+ return {
+ content: [{
+ type: 'text',
+ text: JSON.stringify({ row_num: 1, old_row: 1, new_row: 2, resolved_by: 'mcp:x' }),
+ }],
+ };
+ },
+ );
+ logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
+ errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+});
+
+afterAll(() => {
+ callSpy.mockRestore();
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+});
+
+beforeEach(() => {
+ calls.length = 0;
+ logs.length = 0;
+ errs.length = 0;
+});
+
+/** One recorded remote call, asserted whole (op name + exact args). */
+function soleCall(): { tool: string; args: Record<string, unknown> } {
+ expect(calls).toHaveLength(1);
+ return calls[0]!;
+}
+
+describe('routeThinClientCommand — (a) op name + param mapping per route', () => {
+ test('takes list: positional slug → page_slug, --who → holder, --kind passthrough', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['list', 'people/alice-example', '--who', 'world', '--kind', 'fact'])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_list',
+ args: { page_slug: 'people/alice-example', holder: 'world', kind: 'fact' },
+ });
+ });
+
+ test('takes list with no slug omits page_slug entirely', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['list'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'takes_list', args: {} });
+ });
+
+ test('takes search: positional query + numeric --limit', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['search', 'runway', '--limit', '5'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'takes_search', args: { query: 'runway', limit: 5 } });
+ });
+
+ test('takes scorecard: positional holder', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['scorecard', 'world'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'takes_scorecard', args: { holder: 'world' } });
+ });
+
+ test('takes calibration: --holder flag', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['calibration', '--holder', 'brain'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'takes_calibration', args: { holder: 'brain' } });
+ });
+
+ test('takes add: --who maps to holder, --since passes through, --weight numeric', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', [
+ 'add', 'people/alice-example', '--claim', 'c', '--kind', 'fact', '--who', 'world',
+ '--weight', '0.7', '--source', 'meeting', '--since', '2026-01',
+ ])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_add',
+ args: {
+ slug: 'people/alice-example', claim: 'c', kind: 'fact', holder: 'world',
+ weight: 0.7, source: 'meeting', since: '2026-01',
+ },
+ });
+ expect(logs.join('\n')).toContain('Added take #1');
+ });
+
+ test('takes update: --row maps to row_num', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['update', 'people/alice-example', '--row', '2', '--weight', '0.4'])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_update',
+ args: { slug: 'people/alice-example', row_num: 2, weight: 0.4 },
+ });
+ });
+
+ test('takes resolve: --quality passes through verbatim', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['resolve', 'people/alice-example', '--row', '3', '--quality', 'partial', '--evidence', 'ev', '--value', '12', '--unit', 'usd'])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_resolve',
+ args: { slug: 'people/alice-example', row_num: 3, quality: 'partial', evidence: 'ev', value: 12, unit: 'usd' },
+ });
+ });
+
+ test('takes resolve: back-compat --outcome true maps to quality correct (+ deprecation warn)', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['resolve', 'people/alice-example', '--row', '1', '--outcome', 'true'])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_resolve',
+ args: { slug: 'people/alice-example', row_num: 1, quality: 'correct' },
+ });
+ expect(errs.join('\n')).toContain('[deprecated]');
+ expect(logs.join('\n')).toContain('quality=correct');
+ });
+
+ test('takes resolve: --outcome false maps to quality incorrect', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['resolve', 'people/alice-example', '--row', '1', '--outcome', 'false'])).toBe(true);
+ expect(soleCall().args.quality).toBe('incorrect');
+ });
+
+ test('takes supersede: --row → row_num, --who → holder, claim passthrough', async () => {
+ expect(await routeThinClientCommand(cfg, 'takes', ['supersede', 'people/alice-example', '--row', '1', '--claim', 'newer', '--who', 'brain', '--kind', 'bet', '--weight', '0.3'])).toBe(true);
+ expect(soleCall()).toEqual({
+ tool: 'takes_supersede',
+ args: { slug: 'people/alice-example', row_num: 1, claim: 'newer', kind: 'bet', holder: 'brain', weight: 0.3 },
+ });
+ expect(logs.join('\n')).toContain('Superseded #1 → new #2');
+ });
+
+ test('search modes (read form) → search_modes with empty args', async () => {
+ expect(await routeThinClientCommand(cfg, 'search', ['modes'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'search_modes', args: {} });
+ });
+
+ test('search stats: --days becomes a NUMBER', async () => {
+ expect(await routeThinClientCommand(cfg, 'search', ['stats', '--days', '7'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'search_stats', args: { days: 7 } });
+ });
+
+ test('search tune (read form) → search_tune with empty args', async () => {
+ expect(await routeThinClientCommand(cfg, 'search', ['tune'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'search_tune', args: {} });
+ });
+
+ test('jobs stats: --queue passthrough → get_job_stats', async () => {
+ expect(await routeThinClientCommand(cfg, 'jobs', ['stats', '--queue', 'embed'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'get_job_stats', args: { queue: 'embed' } });
+ });
+
+ test('cache stats → cache_stats with empty args', async () => {
+ expect(await routeThinClientCommand(cfg, 'cache', ['stats'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'cache_stats', args: {} });
+ });
+
+ test('quarantine list: --include-flagged → include_flagged true', async () => {
+ expect(await routeThinClientCommand(cfg, 'quarantine', ['list', '--include-flagged'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'quarantine_list', args: { include_flagged: true } });
+ calls.length = 0;
+ expect(await routeThinClientCommand(cfg, 'quarantine', ['list'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'quarantine_list', args: {} });
+ });
+});
+
+describe('routeThinClientCommand — (b) host-bound forms return false', () => {
+ const hostBound: Array<[string, string[]]> = [
+ ['search', ['modes', '--reset']],
+ ['search', ['tune', '--apply']],
+ ['quarantine', ['scan']],
+ ['quarantine', ['clear']],
+ ['takes', ['extract']],
+ ];
+
+ for (const [command, args] of hostBound) {
+ test(`${command} ${args.join(' ')} → false, no remote call`, async () => {
+ expect(await routeThinClientCommand(cfg, command, args)).toBe(false);
+ expect(calls).toHaveLength(0);
+ });
+ }
+});
+
+describe('routeThinClientCommand — (c) malformed routable forms print usage + exit 1', () => {
+ async function expectUsageExit(command: string, args: string[]): Promise<void> {
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`EXIT:${code}`);
+ }) as never);
+ let exited: string | null = null;
+ try {
+ await routeThinClientCommand(cfg, command, args);
+ } catch (e) {
+ if (!(e as Error).message.startsWith('EXIT:')) throw e;
+ exited = (e as Error).message;
+ } finally {
+ exitSpy.mockRestore();
+ }
+ expect(exited).toBe('EXIT:1');
+ expect(errs.join('\n')).toContain('Usage:');
+ // No remote write attempted on a usage error.
+ expect(calls).toHaveLength(0);
+ }
+
+ test('takes search with no query', async () => {
+ await expectUsageExit('takes', ['search']);
+ });
+
+ test('takes add missing --claim/--kind/--who', async () => {
+ await expectUsageExit('takes', ['add', 'people/alice-example']);
+ });
+
+ test('takes update missing --row', async () => {
+ await expectUsageExit('takes', ['update', 'people/alice-example', '--weight', '0.5']);
+ });
+
+ test('takes resolve missing --quality and --outcome', async () => {
+ await expectUsageExit('takes', ['resolve', 'people/alice-example', '--row', '1']);
+ });
+
+ test('takes resolve with a non-boolean --outcome', async () => {
+ await expectUsageExit('takes', ['resolve', 'people/alice-example', '--row', '1', '--outcome', 'maybe']);
+ });
+
+ test('takes supersede missing --claim', async () => {
+ await expectUsageExit('takes', ['supersede', 'people/alice-example', '--row', '1']);
+ });
+});