Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(gate): Cat 41 after-pass consent and false-empty fixes
garrytanb3f4e8ba5935
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a87be2a0a6..4fb108a180 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -69,6 +69,12 @@ Scripts that parse exit codes or `--json` output should read the [behavior chang| Invalid input: `autopilot --interval`, `serve --port`, `dream --phase`, `init --mcp-only` missing flags, `delta --since` | exit 1 | exit 2 (`invalid_params`) | treat 2 as "fix the command" || `gbrain doctor --json` with no brain configured | human text or nothing | one `no_brain` envelope with the `gbrain init` fix | parse the document || `gbrain serve` on a brain another serve holds, or with no brain | exited before the MCP handshake | completes the handshake in status-only mode with one `gbrain_status` tool; `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`) restores the early exit for supervisors | read `gbrain_status`; supervisors pass `--fail-fast` |+| `gbrain doctor` (plain, `--only`, `--remediation-plan`, MCP `run_doctor`) with an embedding key | sent one paid embedding request on every run | no provider call; `embedding_provider` reports `configured, not probed` with a `paid`+`egress` fix (`--only embedding_provider --probe --yes`) | run the probe only after the user agrees |+| `gbrain embed`, `jobs submit embed*`, `features --auto-fix` with a billed embedding provider and no terminal | embedded without asking | exit 3 with the consent payload unless `--yes`, `--max-usd`, tokenmax or a preapproval covers it; writes that embed new content are unchanged | cron jobs that backfill on purpose pass `--yes` (or `--max-usd <n>`), or set a preapproval |+| `doctor --remediation-plan --json` steps | `command` only | each step also carries `fix` with `consent` (`paid` / `destructive`) and `next` | follow `fix.next` |+| A PGLite brain whose automatic repair failed | later commands kept opening it and wrote to `pg_wal/` | every command exits 3 with the consented `pglite-repair` until the user decides; nothing touches the data directory | relay `user_message`; never move or rebuild the brain files yourself |+| `gbrain serve` whose configured brain directory is missing (unmounted drive) or whose writer-lock file cannot be opened | exited before the MCP handshake (`internal_error`) | status-only mode: `gbrain_status` names the path (`missing_brain`, `brain_unopenable`); nothing is created at the path | relay it; the server reopens the brain once it is back |+| `gbrain transcripts recent` while `gbrain serve` holds the brain | `pglite_busy` | reads through the running serve | none || Error envelopes | `error`, `message`, `suggestion` | adds `code`, `fix`, `class`, `retryable`, `docs_cmd`, `contract_version`; `error` unchanged (legacy values frozen) | read `code`, fall back to `error` || Docs pointers in errors | repo-relative paths | absolute URLs pinned to the installed version | open the URL, or run `gbrain errors <code>` offline || MCP results with advice | advice in `_meta` or stderr only | extra `[gbrain notice …]` text blocks plus `_meta.gbrain_notices`; `content[0]` unchanged | parse `content[0]` alone; read the notice blocks |@@ -163,6 +169,17 @@ Scripts that parse exit codes or `--json` output should read the [behavior chang- `think` over HTTP on a keyless brain no longer names the host's API key variable in its answer.- A thin client keeps a remote server's MCP-only fix instead of dropping it: the CLI shows `Fix: call <tool> over MCP with {…}` and `--json` carries it as `tell_user_to_run`.++#### Release-gate fixes (Cat 41 after-pass)++The real-agent eval of the candidate still found nine consent-violation steps and one new false "no notes" answer. Each now has a product fix and a test that fails on the old code:++- Plain `gbrain doctor` no longer spends money: it sent one tiny paid embedding request on every run. Doctor, `--only`, `--remediation-plan`, MCP `run_doctor`, readiness, `features` and `onboard --check` make no provider call; the embedding check says "configured, not probed" and its fix is `gbrain doctor --only embedding_provider --probe --yes` (paid + egress, so the agent asks first). Local providers that bill nothing need no consent.+- Explicit embedding backfills ask first. `gbrain embed` (stale, catch-up, all, a slug, facts, images), `jobs submit embed|embed-backfill|embed-catch-up` and `features --auto-fix` stop with exit 3 and the consent payload (estimate and a `--dry-run` preview) unless `--yes`, `--max-usd`, tokenmax or a preapproval covers them; a user cap below the estimate refuses before anything runs. Every remediation-plan step now carries a `fix` with its effects, so an embed step reads `ask_user` instead of looking free. Writing new content with a configured key still embeds it without asking (that is the feature), and autopilot, cycles and queued jobs keep running under their configured budget; the protocol's consent section says so.+- A brain whose automatic PGLite repair failed is never opened again until the user decides: gbrain records the failure next to the brain, and every command (stats, doctor, list, …) exits 3 with the consented `gbrain pglite-repair --yes --expect <plan_hash>` and its `--dry-run` preview, without touching a byte of the data directory. The refusal says plainly not to copy, rebuild, move or modify the brain files by hand. `pglite-repair --dry-run`, the consented repair (which clears the record), `reinit-pglite` and engine-free `doctor --only` checks still work; `gbrain serve` starts in status-only mode with `reason: repair_failed`.+- A stdio agent learns that local session transcripts exist. Searches about the user's own activity (or that come back empty) carry a `local_transcripts` notice naming where the transcripts are and `gbrain transcripts recent --json`; `gbrain://capabilities` and the initialize readiness tail list them too. `gbrain transcripts recent` now reads through a running `gbrain serve` instead of failing on its lock. The stdio connection still cannot call `get_recent_transcripts`.+- `gbrain serve` with a configured brain directory that is missing (an unmounted drive) or a writer-lock file it cannot open no longer exits before the handshake: it starts in status-only mode, `gbrain_status` names the path, and nothing is created there. It reopens the brain in place once the drive is back.+## [0.60.37.0] - 2026-10-03**Foundations 1: a 10,000-page PGLite brain answers health and orphan checks in well under a second instead of 12 to 15 seconds, imports in about a third less time, records who wrote each page version, fact, take and timeline entry, lets several agents share one brain without losing track of whose session produced what, and gives every legacy token the same grant shape as an OAuth client.**diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 922eb68c3f..cc3f50389b 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -25,6 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps, its message and `BudgetExhausted.pricing` built by `no-pricing.ts` (warn-once preserved when cap is unset, naming the registration command); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math (`reservationCostUsd`, overrides, free local providers, unknown-price `null`) lives in the pure `src/core/budget/reservation-cost.ts`, shared with skillopt preflight's impossible-reservation check so the two cannot disagree. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases. A4 cap sources: `capSource: 'derived' | 'default' | 'user'` (getter `capSource`; an explicit `maxCostUsd` with no declared source is `user`, the pre-A4 behaviour). Only a `user` cap hard-fails an unpriced model, and that `BudgetExhausted` carries `fix` (`noPricingFix`, actor `agent` on the CLI, `host_admin` when `transport` is remote); `derived`/`default` caps warn once and run the model unmetered. Cost exhaustion carries `capSource`, and a `derived` one appends `derived_cap_exhausted` to the agent-contract log (callers report it with `consent.ts`'s `derivedCapExhaustedError`). Pinned by `test/budget-tracker-cap-source.test.ts`.- `src/core/consent.ts` + `src/core/consent-preapproval.ts` — the A4 consent primitive for trusted local CLI handlers. `requireConsent(req, env?)` evaluates the matrix (`paid`: `--yes`, finite `--max-usd`/`--max-cost`, `spend.posture=tokenmax` via `env.getConfig`, or the per-run preapproval; other effects: `--yes`, `--apply`/`--trust`, the per-command `NON_INTERACTIVE_AUTHORIZES` map (only `apply-migrations` → `persistent_install`), or the install preapproval, which never covers `credentials`; `destructive`: `--yes` plus `--expect <plan_hash>` when the request has one, never preapprovable, a mismatch is `preview_changed`), then a TTY prompt through `interaction.readLine` (EOF/timeout = decline), else throws `confirmation_required` carrying `confirmationPayload()` (`isConsentRefusal`; `renderConsentRefusal`/`printConsentRefusal`: `--json` payload document or an `[AGENT]` block with a fenced `[SHOW USER]` relay, exit 3). Caps on the returned `Authorization`: explicit or preapproved or configured → `user`; estimate → `derived` (x1.5, floor $0.25); no estimate → `default` ($5, printed). Refusals, declines and preapproved runs are logged to E11 (code, effects, outcome; never params). Destructive rail: `computePlanHash(selection)` (stable sha256 over brain, source, operation, records + revisions + incarnations, parameters, effects), `persistApproval`/`readApproval` under `<GBRAIN_HOME>/consent/approvals/`, `verifyApproval`/`assertApproval` re-ask on a changed, newly matching or dropped record. Preapprovals (`consent.preapprove.paid.max_usd_per_run`, `consent.preapprove.persistent_install`) live only in the host file plane; `setConsentPreapproval` refuses remote callers. Pinned by `test/consent.test.ts`; observational startup by `test/observational-startup.serial.test.ts`.+- `src/core/embed-consent.ts` — consent for explicit embedding backfills (`gbrain embed`, `jobs submit embed|embed-backfill|embed-catch-up`, `features --auto-fix`): `requireEmbedBackfillConsent` (`paid`, an SQL estimate from the text it would embed, a user cap below the estimate refuses with `cost_cap_exceeded`), null when nothing can spend (`embedWouldSpend`: embeddings off, no credentials, or a local recipe billing $0 per `embeddingProviderIsFree`). `embedBackfillFix` is the doctor-side backlog fix. Write-path embedding and the unattended library paths (autopilot, cycles, queued jobs) are deliberately outside it. Doctor's opt-in live probe asks through `src/commands/doctor/probe-consent.ts` (`paid` + `egress`). Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.- `src/core/agent-markers.ts` — the one `[AGENT] … [/AGENT]` / `[SHOW USER]` builder (`agentBlock`): fixed field vocabulary, every value through `inertText()` so interpolated text cannot open or close a block.- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`), rendered from `pricingSetArgv`; `noPricingFix(guidance, transport)` is the agent-contract `fix` for a user-cap refusal (the registration argv with `inputs` for each rate and the pricing page). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex b0be379efb..450ccf0dee 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -44,3 +44,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/pglite-statements.ts` — `PgliteStatementCache`, the PGLite counterpart of postgres.js prepared statements. `PGLiteEngine._attachDatabase` routes the root handle's `query`/`exec` through it and `transaction()` routes each transaction handle. A statement text seen twice is prepared once as a named server-side statement; later calls send one Bind/Execute/Sync batch and parse rows with parsers resolved at prepare time, instead of PGlite's parse/describe round trips and its per-query copy of `db.parsers`. PostgreSQL's plan cache replans on invalidation; a changed result shape (`0A000`) or missing statement (`26000`) drops the entry and retries outside a transaction. `ALTER`/`CREATE`/`DROP`/`DO`/`DISCARD`/`DEALLOCATE` text and any non-transaction-control `exec` clear the cache, retired names are closed in the next prepare batch, an instance-level `query`/`exec` override (test seams) takes precedence on the root handle, and `_closeInternal` drops the cache with the database so a disconnected engine does not retain its PGLite instance. `dropRowTypeArrayParsers` removes composite-row array parsers after connect, since gbrain never selects those arrays. Pinned by `test/pglite-statements.test.ts`.- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.+- `src/core/pglite-repair-consent.ts` + the repair-failed marker in `src/core/pglite-repair.ts` — when automatic WAL repair fails (or a recent failure put it on cooldown) `recordFailedAutoRepair` writes the sibling `<dataDir>.repair-failed.json`; while it exists `PGLiteEngine.connect()` refuses before `acquireLock` (zero writes to the data dir) with `repairFailedRefusal`: the exit-3 consent payload (effects `destructive`, fix `gbrain pglite-repair [--path] --yes --expect <plan_hash>` from the same `walRepairPlan` the command binds, preview `--dry-run --json`, and the hands-off text `HANDS_OFF_BRAIN_FILES`). The CLI's `exitOnRepairFailed` (`src/cli/cli-error.ts`) exits 3 on it from `connectEngine`; stdio serve maps it to status reason `repair_failed`. Cleared by a completed `pglite-repair` or `reinit-pglite`. Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 9ba3cbed18..77c22becc8 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1547,9 +1547,9 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| gbrain serve is in status-only mode: its brain is locked by another server, missing, or its config is unreadable. | A capability this request needs is not configured or not reachable on this brain. | Call gbrain_status for the cause, the fix and what to tell the user. | agent | `gbrain doctor --json` | 1 | no |+| gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable. | A capability this request needs is not configured or not reachable on this brain. | Call gbrain_status for the cause, the fix and what to tell the user. | agent | `gbrain doctor --json` | 1 | no |-Reasons: `lock_held`, `no_brain`, `config_unreadable`.+Reasons: `lock_held`, `no_brain`, `config_unreadable`, `missing_brain`, `brain_unopenable`, `repair_failed`.### shared_skills_unavailablediff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 2b7f6893dd..20a31f5341 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -795,6 +795,53 @@ unpriced model refuses with a fix whose `inputs` ask you to look up themodel's per-token rates (for example by web search) and register them with`gbrain pricing set`, then retry.+### What is paid, and what is not++- **Explicit embedding backfills are paid work.** `gbrain embed` (`--stale`,+ `--all`, `--catch-up`, a slug, `--facts`, `--images`, `--background`),+ `gbrain jobs submit embed|embed-backfill|embed-catch-up` and+ `gbrain features --auto-fix` (when it would embed) stop with exit 3 and the+ consent payload (`effects: ["paid"]`, an estimate when one is cheap to+ compute, a `--dry-run` preview) unless `--yes`, `--max-usd`,+ `spend.posture=tokenmax` or a per-run preapproval covers them. Every+ `doctor --remediation-plan` step carries a `fix` whose `consent` names this+ (`paid` when the step has a cost or its job calls a provider; repair steps+ are `destructive`), so `next` reads `ask_user` until the user agrees.+- **Writing new content is not a separate paid action.** With an embedding key+ configured, `put_page`, `import`, `sync`, `capture`, `remember` and+ `timeline-add` embed what they write: that is the feature the user turned on+ (embeddings default on when a key is present), so ordinary writes never stop+ for consent. To keep writes text-only, use `--no-embed` where the command has+ it, or a keyless brain.+- **Unattended library paths keep their authorization.** Autopilot, dream+ cycles and queued jobs keep running under their configured budget; the+ gates above apply to the explicit CLI invocations only.+- **Looking never spends.** Plain `gbrain doctor`, `doctor --only`,+ `--remediation-plan`, MCP `run_doctor`, readiness, `features` without+ `--auto-fix` and `onboard --check` make no provider call: the embedding+ provider check reports `configured, not probed` with a fix that runs the+ live probe (`gbrain doctor --only embedding_provider --probe --yes`,+ `consent: ["paid", "egress"]`; one tiny request). Run it only after the+ user agrees. Local providers that bill nothing (ollama, llama-server,+ LM Studio) need no consent for either.++### A brain whose automatic repair failed++When gbrain's automatic PGLite WAL repair fails, it records that next to the+brain (`<brain>.repair-failed.json`, never inside the data directory) and from+then on refuses to open the brain at all: every command exits 3 with the+consent payload (`effects: ["destructive"]`, `fix` =+`gbrain pglite-repair --yes --expect <plan_hash>`, preview+`gbrain pglite-repair --dry-run --json`), so nothing keeps writing into a+damaged brain. Over stdio MCP, `gbrain serve` starts in status-only mode with+`reason: "repair_failed"`. What still works: `gbrain pglite-repair --dry-run`,+the consented `pglite-repair --yes --expect …` (which clears the record),+`gbrain reinit-pglite` (its own consent), engine-free `doctor --only` checks+and `--help`. **Do not copy, rebuild, move or modify the brain.pglite files+yourself**: no hand-made WAL or catalog surgery, no swapping in a rebuilt+copy, no moving the directory aside. Relay `user_message` and let the user+choose the recovery.+### Consent honestyAn agent can always pass `--yes`. Consent gates force a stop and supply the@@ -945,6 +992,12 @@ old behaviour. The release's CHANGELOG entry carries the same table.| Invalid input: `autopilot --interval`, `serve --port`, `dream --phase`, `init --mcp-only` missing flags, `delta --since` | exit 1 | exit 2 (`invalid_params`) | treat 2 as "fix the command" || `gbrain doctor --json` with no brain configured | human text or nothing | one `no_brain` envelope with the `gbrain init` fix | parse the document || `gbrain serve` on a brain another serve holds, or with no brain | exited before the MCP handshake | completes the handshake in status-only mode with one `gbrain_status` tool; `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`) restores the early exit for supervisors | read `gbrain_status`; supervisors pass `--fail-fast` |+| `gbrain doctor` (plain, `--only`, `--remediation-plan`, MCP `run_doctor`) with an embedding key | sent one paid embedding request on every run | no provider call; `embedding_provider` reports `configured, not probed` with a `paid`+`egress` fix (`--only embedding_provider --probe --yes`) | run the probe only after the user agrees |+| `gbrain embed`, `jobs submit embed*`, `features --auto-fix` with a billed embedding provider and no terminal | embedded without asking | exit 3 with the consent payload unless `--yes`, `--max-usd`, tokenmax or a preapproval covers it; writes that embed new content are unchanged | cron jobs that backfill on purpose pass `--yes` (or `--max-usd <n>`), or set a preapproval |+| `doctor --remediation-plan --json` steps | `command` only | each step also carries `fix` with `consent` (`paid` / `destructive`) and `next` | follow `fix.next` |+| A PGLite brain whose automatic repair failed | later commands kept opening it and wrote to `pg_wal/` | every command exits 3 with the consented `pglite-repair` until the user decides; nothing touches the data directory | relay `user_message`; never move or rebuild the brain files yourself |+| `gbrain serve` whose configured brain directory is missing (unmounted drive) or whose writer-lock file cannot be opened | exited before the MCP handshake (`internal_error`) | status-only mode: `gbrain_status` names the path (`missing_brain`, `brain_unopenable`); nothing is created at the path | relay it; the server reopens the brain once it is back |+| `gbrain transcripts recent` while `gbrain serve` holds the brain | `pglite_busy` | reads through the running serve | none || Error envelopes | `error`, `message`, `suggestion` | adds `code`, `fix`, `class`, `retryable`, `docs_cmd`, `contract_version`; `error` unchanged (legacy values frozen) | read `code`, fall back to `error` || Docs pointers in errors | repo-relative paths | absolute URLs pinned to the installed version | open the URL, or run `gbrain errors <code>` offline || MCP results with advice | advice in `_meta` or stderr only | extra `[gbrain notice …]` text blocks plus `_meta.gbrain_notices`; `content[0]` unchanged | parse `content[0]` alone; read the notice blocks |diff --git a/llms-full.txt b/llms-full.txtindex 28d0ee976f..e8647aed1d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3867,6 +3867,53 @@ unpriced model refuses with a fix whose `inputs` ask you to look up themodel's per-token rates (for example by web search) and register them with`gbrain pricing set`, then retry.+### What is paid, and what is not++- **Explicit embedding backfills are paid work.** `gbrain embed` (`--stale`,+ `--all`, `--catch-up`, a slug, `--facts`, `--images`, `--background`),+ `gbrain jobs submit embed|embed-backfill|embed-catch-up` and+ `gbrain features --auto-fix` (when it would embed) stop with exit 3 and the+ consent payload (`effects: ["paid"]`, an estimate when one is cheap to+ compute, a `--dry-run` preview) unless `--yes`, `--max-usd`,+ `spend.posture=tokenmax` or a per-run preapproval covers them. Every+ `doctor --remediation-plan` step carries a `fix` whose `consent` names this+ (`paid` when the step has a cost or its job calls a provider; repair steps+ are `destructive`), so `next` reads `ask_user` until the user agrees.+- **Writing new content is not a separate paid action.** With an embedding key+ configured, `put_page`, `import`, `sync`, `capture`, `remember` and+ `timeline-add` embed what they write: that is the feature the user turned on+ (embeddings default on when a key is present), so ordinary writes never stop+ for consent. To keep writes text-only, use `--no-embed` where the command has+ it, or a keyless brain.+- **Unattended library paths keep their authorization.** Autopilot, dream+ cycles and queued jobs keep running under their configured budget; the+ gates above apply to the explicit CLI invocations only.+- **Looking never spends.** Plain `gbrain doctor`, `doctor --only`,+ `--remediation-plan`, MCP `run_doctor`, readiness, `features` without+ `--auto-fix` and `onboard --check` make no provider call: the embedding+ provider check reports `configured, not probed` with a fix that runs the+ live probe (`gbrain doctor --only embedding_provider --probe --yes`,+ `consent: ["paid", "egress"]`; one tiny request). Run it only after the+ user agrees. Local providers that bill nothing (ollama, llama-server,+ LM Studio) need no consent for either.++### A brain whose automatic repair failed++When gbrain's automatic PGLite WAL repair fails, it records that next to the+brain (`<brain>.repair-failed.json`, never inside the data directory) and from+then on refuses to open the brain at all: every command exits 3 with the+consent payload (`effects: ["destructive"]`, `fix` =+`gbrain pglite-repair --yes --expect <plan_hash>`, preview+`gbrain pglite-repair --dry-run --json`), so nothing keeps writing into a+damaged brain. Over stdio MCP, `gbrain serve` starts in status-only mode with+`reason: "repair_failed"`. What still works: `gbrain pglite-repair --dry-run`,+the consented `pglite-repair --yes --expect …` (which clears the record),+`gbrain reinit-pglite` (its own consent), engine-free `doctor --only` checks+and `--help`. **Do not copy, rebuild, move or modify the brain.pglite files+yourself**: no hand-made WAL or catalog surgery, no swapping in a rebuilt+copy, no moving the directory aside. Relay `user_message` and let the user+choose the recovery.+### Consent honestyAn agent can always pass `--yes`. Consent gates force a stop and supply the@@ -4017,6 +4064,12 @@ old behaviour. The release's CHANGELOG entry carries the same table.| Invalid input: `autopilot --interval`, `serve --port`, `dream --phase`, `init --mcp-only` missing flags, `delta --since` | exit 1 | exit 2 (`invalid_params`) | treat 2 as "fix the command" || `gbrain doctor --json` with no brain configured | human text or nothing | one `no_brain` envelope with the `gbrain init` fix | parse the document || `gbrain serve` on a brain another serve holds, or with no brain | exited before the MCP handshake | completes the handshake in status-only mode with one `gbrain_status` tool; `--fail-fast` (or `GBRAIN_SERVE_FAIL_FAST=1`) restores the early exit for supervisors | read `gbrain_status`; supervisors pass `--fail-fast` |+| `gbrain doctor` (plain, `--only`, `--remediation-plan`, MCP `run_doctor`) with an embedding key | sent one paid embedding request on every run | no provider call; `embedding_provider` reports `configured, not probed` with a `paid`+`egress` fix (`--only embedding_provider --probe --yes`) | run the probe only after the user agrees |+| `gbrain embed`, `jobs submit embed*`, `features --auto-fix` with a billed embedding provider and no terminal | embedded without asking | exit 3 with the consent payload unless `--yes`, `--max-usd`, tokenmax or a preapproval covers it; writes that embed new content are unchanged | cron jobs that backfill on purpose pass `--yes` (or `--max-usd <n>`), or set a preapproval |+| `doctor --remediation-plan --json` steps | `command` only | each step also carries `fix` with `consent` (`paid` / `destructive`) and `next` | follow `fix.next` |+| A PGLite brain whose automatic repair failed | later commands kept opening it and wrote to `pg_wal/` | every command exits 3 with the consented `pglite-repair` until the user decides; nothing touches the data directory | relay `user_message`; never move or rebuild the brain files yourself |+| `gbrain serve` whose configured brain directory is missing (unmounted drive) or whose writer-lock file cannot be opened | exited before the MCP handshake (`internal_error`) | status-only mode: `gbrain_status` names the path (`missing_brain`, `brain_unopenable`); nothing is created at the path | relay it; the server reopens the brain once it is back |+| `gbrain transcripts recent` while `gbrain serve` holds the brain | `pglite_busy` | reads through the running serve | none || Error envelopes | `error`, `message`, `suggestion` | adds `code`, `fix`, `class`, `retryable`, `docs_cmd`, `contract_version`; `error` unchanged (legacy values frozen) | read `code`, fall back to `error` || Docs pointers in errors | repo-relative paths | absolute URLs pinned to the installed version | open the URL, or run `gbrain errors <code>` offline || MCP results with advice | advice in `_meta` or stderr only | extra `[gbrain notice …]` text blocks plus `_meta.gbrain_notices`; `content[0]` unchanged | parse `content[0]` alone; read the notice blocks |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 163c39d7f6..2f17eb42f6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -3,9 +3,9 @@# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in# the same commit as any peel (the guard fails on >50 lines of stale slack).# Columns: path max_lines policy note-src/cli.ts 3195 ratchet +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult+src/cli.ts 3198 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResultsrc/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)-src/commands/doctor.ts 666 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts+src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)@@ -20,7 +20,7 @@ src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2233 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)-src/core/pglite-engine.ts 2921 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)+src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216)src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache keysrc/core/types.ts 2123 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes)diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex 9a06628206..ef709eb556 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -8,6 +8,7 @@"test/agent-journey-tier2.serial.test.ts": 85,"test/agent-journey-upgrade.serial.test.ts": 70,"test/agent-journey.serial.test.ts": 50,+ "test/agent-operator-gate-fixes.serial.test.ts": 45,"test/agent-recovery-consent-journeys.serial.test.ts": 23,"test/agent-register-guards.serial.test.ts": 22,"test/agent-scheduler-contract.serial.test.ts": 39,diff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 7e1184e81d..c372d0758f 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -17,6 +17,7 @@"test/agent-contract-a0.test.ts": 1,"test/agent-contract-goldens.test.ts": 1,"test/agent-install.test.ts": 137,+ "test/agent-operator-gate-fixes.test.ts": 3000,"test/agent-register.test.ts": 347,"test/agent-runner.test.ts": 6,"test/ai-probes-models.test.ts": 16,diff --git a/src/cli.ts b/src/cli.tsindex a18f8068f1..f58c9fc0c1 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -40,7 +40,7 @@ import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitimport { agentJsonGuardMode } from './cli/json-guard.ts';import { printCuratedHelp } from './cli/help/render.ts';import { curatedFlagError } from './cli/help/validate.ts';-import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli/cli-error.ts';+import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli/cli-error.ts';import type { Notice } from './core/agent-output.ts';import { opError } from './core/ops/contract.ts';import { opParamValue } from './cli/op-param-values.ts';@@ -151,7 +151,7 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: ne// answered before any engine or job-queue work (cathedral-6).agent: async () => (await import('./commands/agent.ts')).runAgent as never,// D3: post-connect records whose handler answers --help before the engine; run through the table.- advisor: true, anomalies: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, features: true,+ advisor: true, anomalies: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,founder: true, 'graph-query': true, orphans: true, salience: true, think: true,brainstorm: true, lsd: true, migrate: true, pages: true, pricing: true, 'retrieval-upgrade': true, whoknows: true,};@@ -2008,6 +2008,10 @@ async function routeCliOnlyBeforeTable(command: string, args: string[]): Promisereturn true;}+ // `transcripts recent` reads through a live PGLite serve that owns the brain.+ if (command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args)+ && await (await import('./commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))) return true;+// cathedral-6: `agent register` guards run PRE-connectEngine. A thin client// would otherwise build a scratch PGLite and mint dead credentials into it;// a live PGLite serve holds the single-writer lock, so connectEngine would@@ -2563,12 +2567,13 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Br// no-config path still exits inside connectEngine (keyless cold-home is// TODOS 1050, out of scope). Kill switch: GBRAIN_SERVE_DEGRADED=0.let engine: BrainEngine;- // F4: a stdio serve with no brain / unreadable config completes the MCP- // handshake in status-only mode instead of exiting (connectEngine exits).+ // F4: a stdio serve with no brain / a missing or repair-failed brain / unreadable config+ // completes the MCP handshake in status-only mode instead of exiting (connectEngine exits).const serveStatus = command === 'serve' ? await import('./commands/serve-status.ts') : null;const serveStatusEligible = !!serveStatus?.statusModeEligible(args, (dbMarkerBrainId() ?? 'host') === 'host');- if (serveStatusEligible && !loadConfig()) {- await serveStatus!.runStatusModeServe('no_brain', null, args, () => connectEngine());+ const preConnectReason = serveStatusEligible ? serveStatus!.preConnectStatusReason() : null;+ if (preConnectReason) {+ await serveStatus!.runStatusModeServe(preConnectReason, null, args, () => connectEngine());return null;}try {@@ -2609,8 +2614,9 @@ async function connectCliOnlyEngine(command: string, args: string[]): Promise<Brconst failFast = await import('./core/serve-fail-fast.ts');if (failFast.serveFailFastRequested(args)) process.exit(failFast.writeServeFailFastEnvelope(serveConnectError));}- if (serveStatusEligible && serveStatus!.statusReasonForError(serveConnectError)) {- await serveStatus!.runStatusModeServe('lock_held', serveConnectError, args, () => connectEngine());+ const connectStatusReason = serveStatusEligible ? serveStatus!.statusReasonForError(serveConnectError) : null;+ if (connectStatusReason) {+ await serveStatus!.runStatusModeServe(connectStatusReason, serveConnectError, args, () => connectEngine());return null;}if (command === 'serve' &&@@ -2757,7 +2763,7 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin// and the search-dashboard path), so routing lands here once.const { resolveBrainId } = await import('./core/brain-resolver.ts');const brainId = resolveBrainId(getCliOptions().brain);- if (brainId !== 'host') return connectMountEngine(brainId);+ if (brainId !== 'host') return exitOnRepairFailed(() => connectMountEngine(brainId));const config = loadConfig();if (!config) {@@ -2796,7 +2802,7 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEnginconst noRetry = process.argv.includes('--no-retry-connect') ||process.env.GBRAIN_NO_RETRY_CONNECT === '1';const { connectWithRetry } = await import('./core/db.ts');- await connectWithRetry(engine, toEngineConfig(config), { noRetry });+ await exitOnRepairFailed(() => connectWithRetry(engine, toEngineConfig(config), { noRetry }));// v0.30.1 (Codex X1 / C2): probeOnly skips both hasPendingMigrations() probe// AND initSchema(). Used by `get_health` MCP op + `gbrain upgrade --status`diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.tsindex 1f838c0869..9052f56677 100644--- a/src/cli/cli-error.ts+++ b/src/cli/cli-error.ts@@ -84,6 +84,22 @@ export function exitCliError(e: unknown, command: string, opts: CliErrorWriteOptprocess.exit(writeCliError(e, command, opts));}+/**+ * Open a brain, except one whose automatic PGLite repair failed: that exits 3+ * with the consent payload (the consented `pglite-repair`, effects+ * destructive), so no caller works around it (doctor's filesystem-only+ * fallback included).+ */+export async function exitOnRepairFailed<T>(open: () => Promise<T>): Promise<T> {+ try {+ return await open();+ } catch (e) {+ const { isRepairFailedRefusal } = await import('../core/pglite-repair-consent.ts');+ if (isRepairFailedRefusal(e)) exitCliError(e, cliCommandOf());+ throw e;+ }+}+/*** A warning-class notice from the CLI's own plumbing (not a command result):* stderr, as `Note [code]` lines on a TTY or an `[AGENT]` block otherwise.diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex dde67a87fd..243b738041 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -255,7 +255,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'import', phase: 'post-connect', thinClient: 'none', json: 'document', help: () => import('./help/import.ts'), routes_source: true, load: () => import('./commands/import.ts') },{ name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/export.ts') },{ name: 'files', phase: 'post-connect', thinClient: 'refuse', routes_source: true, load: () => import('./commands/files.ts') },- { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/embed.ts') },+ { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, startup: 'observational', load: () => import('./commands/embed.ts') },{ name: 'serve', phase: 'post-connect', thinClient: 'refuse', help: () => import('./help/serve.ts'), load: () => import('./commands/serve.ts') },// thin client: Agent-bootstrap [CX2-5]: the maintenance sweep runs against the LOCAL engine (the// serve-resident sweep's trusted CLI entry). On a thin client it would fabricate a scratch PGLitediff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.tsindex 85e5440646..4bce243419 100644--- a/src/cli/commands/embed.ts+++ b/src/cli/commands/embed.ts@@ -11,7 +11,14 @@ import type { BrainEngine } from '../../core/engine.ts';import type { CliDispatchContext } from '../command-table.ts';export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) {+ console.log(EMBED_USAGE);+ return;+ }const { SELECTED_CONFIG_BY_ENGINE } = ctx;+ // A4: an explicit backfill is paid work; consent first, on the probe-only engine (startup: 'observational').+ if (!(await authorizeEmbed(engine, args))) return;+ await ctx.completeStartup?.(engine);const { runEmbed } = await import('../../commands/embed.ts');// #3037: mirror the `import` case above — the CLI was discarding the// result, so a run where every chunk failed to embed still exited 0@@ -30,3 +37,44 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchCsetCliExitVerdict(BUDGET_STOP_EXIT_CODE);}}++/**+ * False when consent refused (exit 3 already reported). `--dry-run` and `--help` spend nothing.+ * Consent flags (read by requireConsent): --yes, --max-usd, --max-cost.+ */+async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<boolean> {+ const end = args.indexOf('--');+ const opts = end >= 0 ? args.slice(0, end) : args;+ if (opts.includes('--dry-run') || opts.includes('--help') || opts.includes('-h')) return true;+ const { requireEmbedBackfillConsent } = await import('../../core/embed-consent.ts');+ const { isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');+ const sourceAt = opts.indexOf('--source');+ const estimable = opts.includes('--stale') || opts.includes('--all');+ const argv = ['gbrain', 'embed', ...args.filter(a => a !== '--yes')];+ try {+ await requireEmbedBackfillConsent(engine, {+ command: 'embed',+ argv,+ ...(estimable && !opts.includes('--images') && !opts.includes('--facts') ? { preview_argv: [...argv.filter(a => a !== '--background'), '--dry-run'] } : {}),+ args,+ scope: {+ all: opts.includes('--all'),+ ...(sourceAt >= 0 && opts[sourceAt + 1] ? { sourceId: opts[sourceAt + 1] } : {}),+ unestimated: !estimable || opts.includes('--slugs') || opts.includes('--facts') || opts.includes('--images'),+ },+ });+ return true;+ } catch (e) {+ if (isConsentRefusal(e)) { setCliExitVerdict(printConsentRefusal(e, { json: jsonRequested(args) })); return false; }+ throw e;+ }+}++/** `gbrain embed --help` (answered without a brain) and the usage error. */+const EMBED_USAGE = [+ 'Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --facts',+ ' Embeds chunks without a vector (--stale; --catch-up keeps going until the backlog is empty) or re-embeds pages (--all, a slug, --slugs).',+ ' It calls the configured embedding provider, which bills per token: without a terminal it stops with exit 3 and the consent payload',+ ' unless --yes (cap: the estimate x1.5), --max-usd N, spend.posture=tokenmax or a per-run preapproval covers it. Pass those only after',+ ' the user agrees. --dry-run previews with no provider calls. Local providers that bill nothing (ollama, llama-server, lmstudio) need no approval.',+].join('\n');diff --git a/src/cli/help/doctor.ts b/src/cli/help/doctor.tsindex 2d23ad018f..57a8bceb6d 100644--- a/src/cli/help/doctor.ts+++ b/src/cli/help/doctor.ts@@ -21,6 +21,7 @@ export const help: CliHelpSpec = {{ name: '--skills-dir', type: 'string', desc: 'Override the auto-detected skills/ directory.' },{ name: '--no-migrate', type: 'boolean', desc: 'Report on the database as-is; do not apply pending schema migrations first.' },{ name: '--locks', type: 'boolean', desc: 'List idle-in-transaction backends holding locks (Postgres) and exit.' },+ { name: '--probe', type: 'boolean', desc: 'Also send one tiny paid test request to the configured embedding provider (plain doctor never calls a provider). Non-interactive runs need --yes.', consent: ['paid', 'egress'] },{ name: '--probe-pglite', type: 'boolean', desc: 'Run the PGLite runtime probe (a 5-20 s cold start) even when the disk diagnosis explains a failed connect.' },{ name: '--index-audit', type: 'boolean', desc: 'Report Postgres indexes with zero recorded scans (informational; never drops anything).' },{ name: '--content-audit', type: 'boolean', desc: 'Scan every page in the content-quality check instead of the first 1000.' },diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex c1974c777a..46df2408ad 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -497,6 +497,7 @@ export async function runDoctor(return;}+ if (args.includes('--probe') && !(await (await import('./doctor/probe-consent.ts')).authorizeProviderProbe(engine, args, jsonOutput))) return;const checks = await buildChecks(engine, args, dbSource, connectError);const hasFail = outputResults(checks, jsonOutput, { engine: engine?.kind, db_url_source: dbSource ?? null });diff --git a/src/commands/doctor/checks/embedding-health.ts b/src/commands/doctor/checks/embedding-health.tsindex ceb86f81a7..50d280c0e8 100644--- a/src/commands/doctor/checks/embedding-health.ts+++ b/src/commands/doctor/checks/embedding-health.ts@@ -16,9 +16,25 @@ import { credentialEnvName, keyShadowWarning } from '../../../core/ai/key-warninimport { getRecipe } from '../../../core/ai/recipes/index.ts';import type { Check } from '../../doctor.ts';import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';-import { checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';+import { checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../check-fix.ts';+import { brainRoutingArgs } from '../../../core/brain-resolver.ts';+import type { Action } from '../../../core/agent-output.ts';+import { embeddingProviderIsFree } from '../../../core/embed-consent.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+/** The opt-in live probe: one ~9-token embedding request, so `paid` + `egress` (runs verbatim once approved). */+export function embeddingProbeFix(model: string, free = false): Action {+ return {+ argv: ['gbrain', 'doctor', '--only', 'embedding_provider', '--probe', ...(free ? [] : ['--yes']), '--json', ...brainRoutingArgs()],+ consent: free ? [] : ['paid', 'egress'],+ actor: 'agent',+ why: `Plain doctor never calls the provider. The probe sends one short embedding request to ${model} to confirm the key, model and dimensions work; it costs a fraction of a cent.`,+ user_message: `To confirm your embedding provider works, gbrain can send it one tiny test request (${model}, well under a cent). OK to run it?`,+ verify: doctorVerify('embedding_provider'),+ requires_exclusive: false,+ };+}+async function runEmbeddingProvider(ctx: DoctorContext): Promise<Check[]> {const { progress } = ctx;const engine = connectedEngine(ctx);@@ -107,6 +123,31 @@ async function runEmbeddingProvider(ctx: DoctorContext): Promise<Check[]> {status: 'ok',message: `Skipped (no provider credentials). Model: ${configuredModel}.`,});+ } else if (!ctx.args.includes('--probe')) {+ let colDims: number | null = null;+ try {+ const { readContentChunksEmbeddingDim } = await import('../../../core/embedding-dim-check.ts');+ const colDim = await readContentChunksEmbeddingDim(engine);+ colDims = colDim.exists ? colDim.dims : null;+ } catch { /* column or table missing: fresh brain */ }+ const details = { probed: false, model: configuredModel, dimensions: configuredDims };+ if (colDims !== null && colDims !== configuredDims) {+ checks.push({+ name: 'embedding_provider',+ status: 'warn',+ message: `${configuredModel} is configured for ${configuredDims} dims but the DB column is vector(${colDims}) (not probed). See docs/embedding-migrations.md for a verified backup, migration preview and explicitly authorized repair.`,+ fix_unavailable_reason: 'operator_judgement',+ details,+ });+ } else {+ checks.push({+ name: 'embedding_provider',+ status: 'ok',+ message: `${configuredModel} configured (${configuredDims} dims, credentials present, DB column aligned); not probed: a live probe sends one tiny paid embedding request to the provider and runs only when authorized.`,+ fix: embeddingProbeFix(configuredModel, await embeddingProviderIsFree(configuredModel)),+ details,+ });+ }} else {// Live embed testconst start = Date.now();diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex f38c4f94ea..62e66ce8c5 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -7,6 +7,7 @@* src/commands/doctor/registry.ts and src/core/doctor-categories.ts.*/+import { embedBackfillFix } from '../../../core/embed-consent.ts';import * as db from '../../../core/db.ts';import { loadConfig } from '../../../core/config.ts';import { LATEST_VERSION } from '../../../core/migrate.ts';@@ -360,12 +361,12 @@ async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {'It makes paid embedding calls: confirm with the user unless embedding spend is already approved.';if (health.embed_coverage >= 0.9) {checks.push(backlog > 0- ? { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails }+ ? { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) }: { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}` });} else if (health.embed_coverage > 0) {- checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails });+ checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) });} else {- checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails });+ checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) });}} catch {checks.push(checkError('embeddings', 'check embedding health'));diff --git a/src/commands/doctor/probe-consent.ts b/src/commands/doctor/probe-consent.tsnew file mode 100644index 0000000000..0eab294044--- /dev/null+++ b/src/commands/doctor/probe-consent.ts@@ -0,0 +1,41 @@+/**+ * `gbrain doctor --probe`: the only way doctor calls a model provider. Plain+ * doctor (and `--only`, `--remediation-plan`, MCP `run_doctor`) reports the+ * embedding provider as configured but not probed. The probe goes through the+ * consent matrix (`paid` + `egress`); an unauthorized non-TTY run exits 3+ * before any check. A local provider that bills nothing (ollama,+ * llama-server, lmstudio) needs no consent.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';++/** A one-request provider probe: a fraction of a cent, rounded up so a per-run preapproval compares sanely. */+const PROVIDER_PROBE_EST_USD = 0.0001;++/** False when consent refused (the exit-3 payload is already printed). */+export async function authorizeProviderProbe(engine: BrainEngine | null, args: string[], json: boolean): Promise<boolean> {+ const { embeddingProviderIsFree } = await import('../../core/embed-consent.ts');+ if (await embeddingProviderIsFree()) return true;+ const { requireConsent, isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');+ const end = args.indexOf('--');+ const argv = ['gbrain', 'doctor', ...(end >= 0 ? args.slice(0, end) : args).filter(a => a !== '--yes')];+ try {+ await requireConsent({+ command: 'doctor',+ effects: ['paid', 'egress'],+ actor: 'agent',+ what: 'Probing the embedding provider',+ why: 'The probe sends one short fixed test string (no brain content) to the configured embedding provider to confirm the key, model and dimensions work.',+ risk: 'One provider request; it costs a fraction of a cent and sends no brain content.',+ user_message: 'To confirm your embedding provider works, gbrain can send it one tiny test request (well under a cent). OK to run it?',+ argv,+ est_usd: PROVIDER_PROBE_EST_USD,+ args,+ }, { getConfig: engine ? (key) => engine.getConfig(key) : undefined });+ return true;+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ setCliExitVerdict(printConsentRefusal(e, { json }));+ return false;+ }+}diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex ff44d27117..04a603497c 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -31,7 +31,7 @@ import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { derivedCapExhaustedError, type CapSource } from '../../core/consent.ts';import { previewRemediationPlan, remediateConsent, remediateFlags, remediationPlanHash, type RemediateFlags } from './remediate-consent.ts';-import { cliRenderContext, renderNotice, type Notice } from '../../core/agent-output.ts';+import { cliRenderContext, renderAction, renderNotice, type Action, type Notice } from '../../core/agent-output.ts';export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]@@ -89,6 +89,43 @@ export function jobStepCommand(step: { job: string; params?: Record<string, unknreturn `gbrain jobs submit ${step.job}${step.params && Object.keys(step.params).length ? ` --params ${shellQuote(JSON.stringify(step.params))}` : ''} --follow`;}+/**+ * Every plan step carries an Action (agent operator contract v1): the step's+ * own command, its effects and a verify. A job step is `paid` when it has a+ * cost estimate or its handler calls a model provider (then the argv carries+ * `--yes`, so it runs verbatim once the user agrees, and `next` renders+ * `ask_user`); a repair step rewrites data (`destructive`, plus `paid` when it+ * embeds), so it is always the user's call.+ */+export async function jobStepFix(step: { job: string; params?: Record<string, unknown>; est_usd_cost?: number; rationale?: string }): Promise<Action> {+ const { paidJobNames } = await import('../jobs/shared.ts');+ const paid = (step.est_usd_cost ?? 0) > 0 || (await paidJobNames([step.job])).length > 0;+ const cost = typeof step.est_usd_cost === 'number' && step.est_usd_cost > 0 ? ` (estimated $${step.est_usd_cost.toFixed(4)})` : '';+ return {+ argv: ['gbrain', 'jobs', 'submit', step.job, ...(step.params && Object.keys(step.params).length ? ['--params', JSON.stringify(step.params)] : []), '--follow', ...(paid ? ['--yes'] : [])],+ consent: paid ? ['paid'] : [],+ actor: 'agent',+ why: paid ? `Runs the ${step.job} job, which calls the configured model provider and costs money${cost}.` : `Runs the ${step.job} job (no provider calls).`,+ ...(paid ? { user_message: `Raising the brain score needs the ${step.job} job, which calls your model provider and costs money${cost}. OK to run it?` } : {}),+ verify: { argv: ['gbrain', 'doctor', '--only', 'brain_score', '--json'] },+ requires_exclusive: false,+ };+}++export function repairStepFix(step: Pick<RepairPlanStep, 'kind' | 'command' | 'paid' | 'est_usd_cost' | 'affected' | 'checks'>): Action {+ const cost = step.paid ? (step.est_usd_cost === null ? ' and calls the embedding provider (price unknown)' : ` and costs about $${step.est_usd_cost.toFixed(4)} in embeddings`) : '';+ return {+ argv: step.command.split(' '),+ preview_argv: repairPreviewCommand(step.kind).split(' '),+ consent: ['destructive', ...(step.paid ? ['paid' as const] : [])],+ actor: 'agent',+ why: `Rewrites ${step.affected} stored item(s) for gbrain repair ${step.kind}${cost}.`,+ user_message: `gbrain wants to repair ${step.affected} item(s) (${step.kind}); this rewrites stored data${cost}. OK to apply it?`,+ verify: { argv: ['gbrain', 'doctor', '--only', step.checks.length ? step.checks.join(',') : 'brain_score', '--json'] },+ requires_exclusive: true,+ };+}+/*** `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`, filled from the plan's estimates.* With repair steps, `--expect <plan_hash>` binds the approval to this plan (C1).@@ -142,7 +179,10 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): Pconst plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed } });const planHash = plan.repair_steps?.length ? await remediationPlanHash(engine, args, plan) : undefined;if (args.includes('--json')) {- await writeJsonDocument(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),+ const ctx = cliRenderContext();+ const steps = await Promise.all(plan.plan.map(async step => ({ ...step, command: jobStepCommand(step), fix: renderAction(await jobStepFix(step), ctx) })));+ const repairSteps = plan.repair_steps?.map(step => ({ ...step, fix: renderAction(repairStepFix(step), ctx) }));+ await writeJsonDocument(JSON.stringify({ ...plan, plan: steps, ...(repairSteps ? { repair_steps: repairSteps } : {}),combined_command: combinedRemediateCommand(plan, plan.target_unreachable ? plan.max_reachable_score : targetScore, { noEmbed, planHash }), ...(planHash ? { plan_hash: planHash } : {}),...(migrations ? { notices: [renderNotice(migrations, cliRenderContext())] } : {}) }, null, 2));return;@@ -152,7 +192,8 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): Pconsole.log(`Schema migrations pending: ${migrations.why}`);if (fix?.command) console.log(` apply: ${fix.command}`);}- for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash })) console.log(line);+ const paidJobs = new Set((await Promise.all(plan.plan.map(async step => (await jobStepFix(step)).consent.length ? step.step : null))).filter((n): n is number => n !== null));+ for (const line of renderRemediationPlanLines(plan, targetScore, { noEmbed, planHash, paidSteps: paidJobs })) console.log(line);}interface RemediationPlanShape {@@ -180,7 +221,7 @@ interface RemediationPlanShape {* the score is at target AND no repair step is pending, so an unreachable* target never reads as "nothing to do".*/-export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number, opts: { noEmbed?: boolean; planHash?: string } = {}): string[] {+export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScore: number, opts: { noEmbed?: boolean; planHash?: string; paidSteps?: ReadonlySet<number> } = {}): string[] {const lines: string[] = [];const repairs = plan.repair_steps ?? [];lines.push(`Brain score: ${plan.brain_score_current}/100 → target ${targetScore}`);@@ -197,7 +238,9 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScoconst protectedMark = step.protected ? ' [PROTECTED]' : '';const costMark = step.est_usd_cost ? ` ($${step.est_usd_cost.toFixed(2)})` : '';lines.push(` ${step.step}. [${step.severity}] ${step.job}${protectedMark} — ${step.rationale}${costMark}`);- lines.push(` run: ${jobStepCommand(step)}`);+ lines.push(opts.paidSteps?.has(step.step) || (step.est_usd_cost ?? 0) > 0+ ? ` paid: ask the user first; once they agree run: ${jobStepCommand(step)}`+ : ` run: ${jobStepCommand(step)}`);}}if (repairs.length > 0) {diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 2b1fca77a0..b60d4b0915 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -952,7 +952,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf} else {const slug = args.find(a => !a.startsWith('--'));if (!slug) {- serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] | --stale --images');+ serr('Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--yes | --max-usd N] | --stale --images (gbrain embed --help: paid runs need the user\'s approval)');process.exit(1);}opts = { slug, dryRun, sourceId, batchSize, priority, catchUp };diff --git a/src/commands/features.ts b/src/commands/features.tsindex e8ce6d3b43..31075cee0d 100644--- a/src/commands/features.ts+++ b/src/commands/features.ts@@ -268,7 +268,7 @@ async function executeAutoFix(rec: FeatureRecommendation, engine: BrainEngine):export async function runFeatures(engine: BrainEngine, args: string[]) {if (args.includes('--help') || args.includes('-h')) {- console.log('Usage: gbrain features [--json] [--auto-fix]\n\nScan brain usage and recommend unused features.\n\n --json Output as JSON (for agents)\n --auto-fix Automatically fix all auto-fixable issues');+ console.log('Usage: gbrain features [--json] [--auto-fix [--yes]]\n\nScan brain usage and recommend unused features.\n\n --json Output as JSON (for agents)\n --auto-fix Automatically fix all auto-fixable issues\n --yes Authorize the paid embedding auto-fix (non-interactive runs need it)');return;}@@ -291,6 +291,18 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {// F7: the auto-fix suggestion is a coaching notice on every surface (it was// printed only on a terminal); --json carries it under `notices`.const autoFixNotice = autoFix ? null : featuresAutoFixNotice(pitchable);+ if (autoFix && pitchable.some(r => r.auto_fixable && PAID_AUTO_FIX_IDS.has(r.id))) {+ const { requireEmbedBackfillConsent } = await import('../core/embed-consent.ts');+ const { isConsentRefusal, printConsentRefusal } = await import('../core/consent.ts');+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');+ try {+ await requireEmbedBackfillConsent(engine, { command: 'features', argv: ['gbrain', 'features', ...args.filter(a => a !== '--yes')], args, scope: {} });+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ setCliExitVerdict(printConsentRefusal(e, { json: jsonMode }));+ return;+ }+ }if (jsonMode) {const fixResults: Record<string, { success: boolean; output: string }> = {};if (autoFix) {@@ -347,16 +359,19 @@ export async function runFeatures(engine: BrainEngine, args: string[]) {saveOffers(offers);}+/** Auto-fixes that embed (paid): they need the user's approval (--yes, --max-usd, --max-cost, tokenmax or a preapproval). */+const PAID_AUTO_FIX_IDS: ReadonlySet<string> = new Set(['missing-embeddings', 'low-coverage']);+/** F7: the `features_auto_fix` coaching notice; null when nothing is auto-fixable. */function featuresAutoFixNotice(pitchable: readonly FeatureRecommendation[]): Notice | null {const fixable = pitchable.filter(r => r.auto_fixable);if (fixable.length === 0) return null;- const paid = fixable.some(r => r.id === 'missing-embeddings' || r.id === 'low-coverage');+ const paid = fixable.some(r => PAID_AUTO_FIX_IDS.has(r.id));return {code: 'features_auto_fix', kind: 'coaching',why: `${fixable.length} recommendation(s) can be fixed automatically: ${fixable.map(r => r.title).join(', ')}.`,fix: {- argv: ['gbrain', 'features', '--auto-fix'], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,+ argv: ['gbrain', 'features', '--auto-fix', ...(paid ? ['--yes'] : [])], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,why: paid ? 'Runs the fixes; refreshing embeddings calls the configured embedding provider (a small paid cost).' : 'Runs the fixes (link and timeline extraction; no paid calls).',...(paid ? { user_message: 'gbrain can fill in missing embeddings for your notes; it costs a little in embedding API calls. OK to run it?' } : {}),},diff --git a/src/commands/jobs/submit.ts b/src/commands/jobs/submit.tsindex 1ff3c7a83d..55cff738ff 100644--- a/src/commands/jobs/submit.ts+++ b/src/commands/jobs/submit.ts@@ -93,6 +93,24 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)return;}+ // A4: an explicit embedding backfill submitted from the CLI is paid work (the worker-side handlers keep running unattended).+ const { EMBED_BACKFILL_JOB_NAMES, requireEmbedBackfillConsent } = await import('../../core/embed-consent.ts');+ if (EMBED_BACKFILL_JOB_NAMES.has(name)) {+ const { isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');+ const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');+ const argv = ['gbrain', 'jobs', ...args.filter(a => a !== '--yes')];+ try {+ await requireEmbedBackfillConsent(engine, {+ command: 'jobs submit', argv, preview_argv: [...argv, '--dry-run'], args,+ scope: { all: data.all === true, ...(typeof data.sourceId === 'string' ? { sourceId: data.sourceId } : {}), unestimated: Array.isArray(data.slugs) },+ });+ } catch (e) {+ if (!isConsentRefusal(e)) throw e;+ setCliExitVerdict(printConsentRefusal(e, { json: hasFlag(args, '--json') }));+ return;+ }+ }+try { await queue.ensureSchema(); }catch (e) { console.error(e instanceof Error ? e.message : String(e)); process.exit(1); }diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.tsindex 40eae454e1..a7395d68c8 100644--- a/src/commands/pglite-repair.ts+++ b/src/commands/pglite-repair.ts@@ -24,12 +24,14 @@import { join } from 'node:path';import { shellQuote } from '../core/agent-output.ts';import { currentExitCode } from '../core/cli-force-exit.ts';-import { computePlanHash, type PlanSelection } from '../core/consent.ts';+import { HANDS_OFF_BRAIN_FILES, WAL_REPAIR_BACKUP_SUFFIX, WAL_REPAIR_RISK, walRepairPlan } from '../core/pglite-repair-consent.ts';import { consentGate } from '../core/consent-cli.ts';import { loadConfig, gbrainPath } from '../core/config.ts';import { acquireLock, releaseLock, LiveServeLockError, msSinceLastReap } from '../core/pglite-lock.ts';import {+ clearRepairFailedMarker,inspectPgliteDataDir,+ readRepairFailedMarker,listRepairBackups,readRepairSidecar,recordRepairAttempt,@@ -116,11 +118,8 @@ function emitError(jsonOutput: boolean, code: string, message: string): void {}}-const BACKUP_SUFFIX = '.wal-repair-backup-';--const REPAIR_RISK = 'Data files are preserved; transactions not checkpointed before the corruption may be lost, and indexes are '- + 'not rebuilt (run gbrain reindex --vectors afterwards). Before the reset the current pg_wal and postmaster.pid are moved, '- + `and pg_control copied, into a sibling <data-dir>${BACKUP_SUFFIX}<timestamp> folder (or this incident's existing backup); nothing is deleted.`;+const BACKUP_SUFFIX = WAL_REPAIR_BACKUP_SUFFIX;+const REPAIR_RISK = WAL_REPAIR_RISK;/** The exact undo of a WAL reset: the reset pg_wal set aside, the backed-up pg_wal and pg_control put back (run with gbrain stopped). */export function restoreCommand(dataDir: string, backupPath: string): string {@@ -131,15 +130,7 @@ export function restoreCommand(dataDir: string, backupPath: string): string {].map(argv => shellQuote(argv)).join(' && ');}-/** The diagnosed state an approval binds: the data dir, its WAL segments and the stale postmaster.pid. */-function repairPlan(dataDir: string, d: { verdict: string; walSegments: string[]; postmasterPid: unknown }): { selection: PlanSelection; plan_hash: string } {- const selection: PlanSelection = {- brain: dataDir, source: null, operation: 'pglite-repair',- records: [...d.walSegments.map(id => ({ id: `pg_wal/${id}` })), ...(d.postmasterPid ? [{ id: 'postmaster.pid' }] : [])],- parameters: { verdict: d.verdict }, effects: ['destructive'],- };- return { selection, plan_hash: computePlanHash(selection) };-}+const repairPlan = walRepairPlan;export async function runPgliteRepair(args: string[]): Promise<number> {let opts: RepairCmdOpts;@@ -181,6 +172,7 @@ export async function runPgliteRepair(args: string[]): Promise<number> {const diagnosis = inspectPgliteDataDir(dataDir);if (opts.dryRun) {+ const repairFailed = readRepairFailedMarker(dataDir);if (opts.jsonOutput) {console.log(JSON.stringify({status: 'ok',@@ -189,6 +181,7 @@ export async function runPgliteRepair(args: string[]): Promise<number> {validation,diagnosis,...(validation.ok ? { plan_hash: repairPlan(dataDir, diagnosis).plan_hash, risk: REPAIR_RISK } : {}),+ ...(repairFailed ? { repair_failed: repairFailed, note: HANDS_OFF_BRAIN_FILES } : {}),}));} else {console.log(`PGLite data dir: ${dataDir}`);@@ -212,6 +205,10 @@ export async function runPgliteRepair(args: string[]): Promise<number> {console.log(` Risk: ${REPAIR_RISK}`);console.log(` The repair is the user's decision. Once they agree: ${approved}`);}+ if (repairFailed) {+ console.log(` Automatic repair failed${repairFailed.ts ? ` at ${new Date(repairFailed.ts).toISOString()}` : ''}; gbrain refuses to open this brain until a repair completes.`);+ console.log(` ${HANDS_OFF_BRAIN_FILES}`);+ }}return 0;}@@ -345,6 +342,8 @@ export async function runPgliteRepair(args: string[]): Promise<number> {// prunes, and repeated manual runs during one incident reuse the pinned// backup instead of deleting the pre-damage forensic copy.recordRepairAttempt(dataDir, 'failed', receipt.backupPath);+ // The user approved and the reset completed: commands may open the brain again (the next open proves it).+ clearRepairFailedMarker(dataDir);if (opts.jsonOutput) {console.log(JSON.stringify({diff --git a/src/commands/reinit-pglite.ts b/src/commands/reinit-pglite.tsindex 6ee28b292a..1362b67a4e 100644--- a/src/commands/reinit-pglite.ts+++ b/src/commands/reinit-pglite.ts@@ -134,7 +134,7 @@ export async function runReinitPglite(args: string[]): Promise<void> {// the same path must not inherit the old brain's open repair episode,// cooldown, or reap quarantine — a stale episodeBackupPath would be reused// over the NEW brain's WAL).- for (const sibling of [`${dbPath}.wal-repair-attempt.json`, `${dbPath}.lock-reap.json`]) {+ for (const sibling of [`${dbPath}.wal-repair-attempt.json`, `${dbPath}.lock-reap.json`, `${dbPath}.repair-failed.json`]) {try { rmSync(sibling, { force: true }); } catch { /* best-effort */ }}} catch (e: unknown) {diff --git a/src/commands/serve-status.ts b/src/commands/serve-status.tsindex d36a98ce14..8e0934468a 100644--- a/src/commands/serve-status.ts+++ b/src/commands/serve-status.ts@@ -11,7 +11,7 @@*/import type { BrainEngine } from '../core/engine.ts';import { loadConfig } from '../core/config.ts';-import { gatedReconnect, initialStatusState, markStatusModeEngine, statusHeadline, type StatusReason } from '../mcp/status-mode.ts';+import { gatedReconnect, initialStatusState, markStatusModeEngine, probeStatus, statusHeadline, type StatusReason } from '../mcp/status-mode.ts';export function serveFailFast(args: readonly string[]): boolean {return args.includes('--fail-fast') || process.env.GBRAIN_SERVE_FAIL_FAST === '1';@@ -22,9 +22,23 @@ export function statusModeEligible(args: readonly string[], hostBrain: boolean):return hostBrain && !args.includes('--http') && !serveFailFast(args);}+/**+ * Before any connect (file reads only): no config, a configured PGLite brain+ * whose data dir is missing (never created empty here), or a brain whose+ * automatic repair failed. Lock contention is left to the connect error.+ */+export function preConnectStatusReason(): StatusReason | null {+ if (!loadConfig()) return 'no_brain';+ const probed = probeStatus();+ return probed && (probed.reason === 'missing_brain' || probed.reason === 'repair_failed') ? probed.reason : null;+}+/** Map a connect failure to a status reason; null when status mode does not apply. */export function statusReasonForError(e: unknown): StatusReason | null {- return (e as { code?: unknown } | null)?.code === 'pglite_busy' ? 'lock_held' : null;+ if ((e as { code?: unknown } | null)?.code === 'pglite_busy') return 'lock_held';+ // The brain's sibling writer-lock file cannot be opened (missing parent, read-only drive, permissions).+ if (/Cannot open the stable writer lock file/.test(String((e as Error | null)?.message ?? ''))) return 'brain_unopenable';+ return null;}/** Run the stdio server over a gated lazy engine; resolves when serve's lifecycle does. */diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex 2757f11bab..3337d325d8 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -17,6 +17,7 @@import { homedir } from 'node:os';import type { BrainEngine } from '../core/engine.ts';+import type { RecentTranscript } from '../core/transcripts.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import type { TranscriptFormat } from '../core/transcripts/types.ts';import { runTranscriptsIngest, type TranscriptsIngestResult } from '../core/transcripts/ingest.ts';@@ -617,17 +618,33 @@ export async function runTranscripts(engine: BrainEngine, args: string[]): Promisummary: !parsed.full,limit: parsed.limit,});- if (parsed.json) {- console.log(JSON.stringify(rows, null, 2));- return;- }- if (rows.length === 0) {- console.log('(no recent transcripts in the corpus dir)');- return;- }- rows.forEach(r => {- const date = r.date ?? r.mtime.slice(0, 10);- console.log(`\n--- ${date} | ${r.path} | ${r.length} bytes ---`);- console.log(r.summary);- });+ console.log(renderRecentTranscripts(rows, parsed.json === true));+}++function renderRecentTranscripts(rows: RecentTranscript[], json: boolean): string {+ if (json) return JSON.stringify(rows, null, 2);+ if (rows.length === 0) return '(no recent transcripts in the corpus dir)';+ return rows.map(r => `\n--- ${r.date ?? r.mtime.slice(0, 10)} | ${r.path} | ${r.length} bytes ---\n${r.summary}`).join('\n');+}++/**+ * `gbrain transcripts recent` while a live `gbrain serve` owns the PGLite+ * brain: read through the owner's local socket as the trusted CLI (the+ * stdio agent's own connection still cannot call get_recent_transcripts).+ * False when no live owner serves the brain (the caller connects normally).+ */+export async function runDelegatedTranscriptsRecent(args: string[]): Promise<boolean> {+ const parsed = parseRecentArgs(args);+ if ('help' in parsed) return false;+ const { loadConfig } = await import('../core/config.ts');+ const { getCliOptions } = await import('../core/cli-options.ts');+ const { runDelegatedCliOperation } = await import('./persistence-delegate.ts');+ const params: Record<string, unknown> = {+ ...(parsed.days !== undefined ? { days: parsed.days } : {}),+ ...(parsed.limit !== undefined ? { limit: parsed.limit } : {}),+ summary: !parsed.full,+ ...(parsed.json ? { json: true } : {}),+ };+ return runDelegatedCliOperation('get_recent_transcripts', params, loadConfig(), { brain: getCliOptions().brain },+ (_op, result) => `${renderRecentTranscripts(Array.isArray(result) ? result as RecentTranscript[] : [], parsed.json === true)}\n`);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8e174f5aaf..22d1256552 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -46,10 +46,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],- 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],+ 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--image', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--once', '--order', '--output', '--page', '--params', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],@@ -59,7 +59,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],- 'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers', '--yes'],+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],@@ -72,13 +72,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--image', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--image', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],- 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],+ 'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],@@ -86,7 +86,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--image', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--once', '--only', '--page', '--params', '--path', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--types', '--url', '--yes'],'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],- 'pglite-repair': ['--apply', '--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--max-cost', '--max-usd', '--non-interactive', '--path', '--probe', '--source', '--trust', '--vectors', '--yes'],+ 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],@@ -107,7 +107,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abandon', '--abbrev-ref', '--abort', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],- 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],+ 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],diff --git a/src/core/consent.ts b/src/core/consent.tsindex fbeb8bd4d5..428d1dcebc 100644--- a/src/core/consent.ts+++ b/src/core/consent.ts@@ -313,10 +313,16 @@ export function isConsentRefusal(e: unknown): e is ConsentRefusal {return e instanceof OperationError && e.code === 'confirmation_required' && (e as Partial<ConsentRefusal>).consent !== undefined;}-function consentRefusal(req: ConsentRequest, outcome: 'refused' | 'declined'): ConsentRefusal {- const payload = confirmationPayload(req, cliRenderContext());+/** The exit-3 refusal for `req`, rendered for `ctx` (no prompt, no log): for gates outside requireConsent. */+export function buildConsentRefusal(req: ConsentRequest, ctx: RenderContext = cliRenderContext()): ConsentRefusal {+ const payload = confirmationPayload(req, ctx);const e = opError('confirmation_required', payload.message, payload.suggestion, { why: req.why, fix: consentFix(req) }) as ConsentRefusal;e.consent = payload;+ return e;+}++function consentRefusal(req: ConsentRequest, outcome: 'refused' | 'declined'): ConsentRefusal {+ const e = buildConsentRefusal(req);recordAgentContractEvent({ command: req.command, transport: 'cli', code: 'confirmation_required', effects: [...req.effects], outcome });return e;}diff --git a/src/core/embed-consent.ts b/src/core/embed-consent.tsnew file mode 100644index 0000000000..5e978a27ca--- /dev/null+++ b/src/core/embed-consent.ts@@ -0,0 +1,135 @@+/**+ * Consent for explicit embedding backfills (agent operator contract v1, A4).+ *+ * An explicit backfill (`gbrain embed --stale|--all|--catch-up|<slug>|--facts|--images`,+ * `gbrain jobs submit embed|embed-backfill|embed-catch-up`, `gbrain features --auto-fix`)+ * spends money with the embedding provider, so a CLI handler calls+ * `requireEmbedBackfillConsent()` first: `--yes`, `--max-usd`, `spend.posture=tokenmax`+ * or a per-run preapproval authorize it; a non-interactive run without one exits 3.+ *+ * Out of scope on purpose (no silent flip): the library paths autopilot, cycles and+ * queued jobs already run unattended under their configured budget (`runEmbedCore`,+ * job handlers), and write-path embedding of new content (put_page, import, sync,+ * timeline-add) under a configured key, which is the configured feature, not a+ * separate paid action. See docs/protocol/AGENT_OPERATOR_v1.md "Consent and preapproval".+ */+import type { BrainEngine } from './engine.ts';+import type { Action } from './agent-output.ts';+import { requireConsent, type Authorization } from './consent.ts';+import { opError } from './ops/contract.ts';++/** Job names whose handler is an embedding backfill (an explicit `jobs submit` of one is paid work). */+export const EMBED_BACKFILL_JOB_NAMES: ReadonlySet<string> = new Set(['embed', 'embed-backfill', 'embed-catch-up']);++export interface EmbedBackfillScope {+ /** Every chunk is re-embedded (`--all`); otherwise only chunks without a vector (and chunkless pages). */+ all?: boolean;+ sourceId?: string;+ /** Slug lists, facts and images have no cheap pre-flight estimate. */+ unestimated?: boolean;+}++/**+ * The doctor-side fix for an embedding backlog: the catch-up drain, `paid`+ * (so `next` renders `ask_user`), with `--yes` so it runs verbatim once the+ * user agrees, and the read-only `--dry-run` preview.+ */+export function embedBackfillFix(opts: { backlog: number; verifyCheck: string }): Action {+ const run = ['gbrain', 'embed', '--stale', '--catch-up'];+ return {+ argv: [...run, '--yes'],+ preview_argv: [...run, '--dry-run'],+ consent: ['paid'],+ actor: 'agent',+ why: `${opts.backlog} chunk(s) have no embedding, so vector search cannot see them. The catch-up drain embeds them until the backlog is empty; it sends page text to the embedding provider and costs money.`,+ user_message: `${opts.backlog} piece(s) of your notes are not indexed for meaning-based search yet. Indexing them sends the text to your embedding provider and costs a little money. OK to run it?`,+ verify: { argv: ['gbrain', 'doctor', '--only', opts.verifyCheck, '--json'] },+ requires_exclusive: false,+ };+}++/** A local embedding provider whose recipe bills nothing (ollama, llama-server, lmstudio): no spend, no egress. */+export async function embeddingProviderIsFree(model?: string): Promise<boolean> {+ try {+ const { getEmbeddingModel } = await import('./ai/gateway.ts');+ const { getRecipe } = await import('./ai/recipes/index.ts');+ const provider = (model ?? getEmbeddingModel()).split(':')[0] ?? '';+ return getRecipe(provider)?.touchpoints?.embedding?.cost_per_1m_tokens_usd === 0;+ } catch {+ return false;+ }+}++/** True when an embed run would spend: embeddings on, a paid embedding provider with credentials. */+export async function embedWouldSpend(engine: BrainEngine): Promise<boolean> {+ const { embeddingsDisabled } = await import('./embedding-disabled.ts');+ if (await embeddingsDisabled(engine)) return false;+ try {+ const { isAvailable } = await import('./ai/gateway.ts');+ return isAvailable('embedding') && !(await embeddingProviderIsFree());+ } catch {+ return false;+ }+}++/** Pre-flight USD estimate of a backfill from the text it would embed; null when unknown. */+export async function estimateEmbedBackfillUsd(engine: BrainEngine, scope: EmbedBackfillScope): Promise<number | null> {+ if (scope.unestimated) return null;+ try {+ const { getEmbeddingModel } = await import('./ai/gateway.ts');+ const { estimateCostFromChars, lookupEmbeddingPrice } = await import('./embedding-pricing.ts');+ const price = lookupEmbeddingPrice(getEmbeddingModel());+ if (price.kind !== 'known') return null;+ const params = scope.sourceId ? [scope.sourceId] : [];+ const bySource = scope.sourceId ? ' AND p.source_id = $1' : '';+ const chunks = await engine.executeRaw<{ chars: number | string }>(+ `SELECT COALESCE(SUM(length(c.chunk_text)), 0)::bigint AS chars FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.deleted_at IS NULL${scope.all ? '' : ' AND c.embedding IS NULL'}${bySource}`, params);+ const chunkless = scope.all ? [] : await engine.executeRaw<{ chars: number | string }>(+ `SELECT COALESCE(SUM(length(p.compiled_truth) + length(p.timeline)), 0)::bigint AS chars FROM pages p+ WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id)${bySource}`, params);+ const chars = Number(chunks[0]?.chars ?? 0) + Number(chunkless[0]?.chars ?? 0);+ return estimateCostFromChars(chars, price.pricePerMTok);+ } catch {+ return null;+ }+}++/**+ * CLI handlers only. Null when the run cannot spend (embeddings disabled, no+ * provider credentials); otherwise the Authorization, or throws the exit-3+ * `confirmation_required` refusal. A user cap below the estimate refuses up+ * front with `cost_cap_exceeded` (nothing runs).+ */+export async function requireEmbedBackfillConsent(engine: BrainEngine, opts: {+ command: string;+ /** The exact command that runs once approved (`--yes` is appended). */+ argv: string[];+ preview_argv?: string[];+ args: readonly string[];+ scope: EmbedBackfillScope;+}): Promise<Authorization | null> {+ if (!(await embedWouldSpend(engine))) return null;+ const est = await estimateEmbedBackfillUsd(engine, opts.scope);+ const cost = est === null ? 'its cost could not be estimated in advance' : `it is estimated at $${est.toFixed(4)}`;+ const auth = await requireConsent({+ command: opts.command,+ effects: ['paid'],+ actor: 'agent',+ what: 'Embedding backfill',+ why: `Embedding sends page text to the configured embedding provider, which bills per token; ${cost}.`,+ risk: 'Spends money with the embedding provider. Keyword search keeps working without it.',+ user_message: `Generating the missing embeddings sends your page text to the embedding provider and costs money (${est === null ? 'cost unknown in advance' : `about $${est.toFixed(4)}`}). OK to run it?`,+ argv: opts.argv,+ ...(opts.preview_argv ? { preview_argv: opts.preview_argv } : {}),+ est_usd: est,+ args: opts.args,+ }, { getConfig: (key) => engine.getConfig(key) });+ if (auth.cap_usd !== null && est !== null && est > auth.cap_usd) {+ throw opError('cost_cap_exceeded',+ `The embedding backfill is estimated at $${est.toFixed(4)}, above the $${auth.cap_usd.toFixed(2)} cap; nothing ran.`,+ 'Ask the user whether to raise the cap, then re-run with a higher --max-usd.',+ { why: 'A run whose estimate exceeds its cap would stop part-way.' });+ }+ return auth;+}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2ca409f769..8505872e35 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -226,7 +226,7 @@ export const CODES = {scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },- serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },+ serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, damaged, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable', 'missing_brain', 'brain_unopenable', 'repair_failed'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },@@ -313,6 +313,7 @@ export const NOTICE_CODES = {degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },+ local_transcripts: { kind: 'info', summary: 'The brain host keeps recent session transcripts that page reads never return and this connection cannot read; the fix is the CLI read (`gbrain transcripts recent --json`).' },synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 6de56712ca..2f99e828d1 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -14,6 +14,7 @@ import type { GBrainConfig } from './config.ts';import type { ExplicitReadBinding } from './ops/contract.ts';import { configReadiness } from './readiness.ts';import { affectsRecall, type DegradedStage } from './types.ts';+import { localTranscriptsFix } from './transcripts.ts';// ── degraded recall (F3) ───────────────────────────────────────────────────@@ -232,6 +233,48 @@ export function recallInteropNotices(}}+// ── local transcripts behind a CLI-only reader (F5 follow-up) ─────────────++/** Read ops whose answers can wrongly read as "no transcripts" when the transcript reader is not callable here. */+const TRANSCRIPT_HINT_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'context_pack', 'list_pages']);++/** A request about the user's own recent activity (sessions, conversations, promises, this week...). */+const PERSONAL_ACTIVITY_RE = /\b(transcripts?|sessions?|conversations?|chats?|promis\w*|said|told|discuss\w*|talked|coding|this week|last week|yesterday|today|recent(ly)?|worked on)\b/i;++/**+ * Whether a successful read on a connection that cannot call+ * `get_recent_transcripts` should be told that local transcripts exist:+ * list_pages when it came back empty; search/query/recall/context_pack when+ * the request is about the user's own activity or came back empty.+ */+export function wantsTranscriptHint(op: string, params: Record<string, unknown>, result: unknown): boolean {+ if (!TRANSCRIPT_HINT_OPS.has(op)) return false;+ const empty = emptyRead(op === 'context_pack' ? 'recall' : op, result);+ if (op === 'list_pages') return empty;+ const text = ['query', 'question', 'topic', 'task', 'q'].map(k => params[k]).filter(v => typeof v === 'string').join(' ');+ return empty || PERSONAL_ACTIVITY_RE.test(text);+}++/**+ * `local_transcripts`: the brain host keeps raw session transcripts that+ * pages and search do not cover, and this connection cannot call their+ * reader. Names where they are (stdio only: the owner's own pipe; HTTP never+ * learns host paths) and the CLI read, so "no transcripts" is never the answer.+ * Read-only pointer: no trust is widened (the tool stays uncallable here).+ */+export function localTranscriptsNotice(presence: { dirs: string[]; count: number }): Notice | null {+ if (presence.count === 0) return null;+ const where = presence.dirs.length ? ` in ${presence.dirs.join(', ')}` : '';+ return {+ code: 'local_transcripts',+ kind: 'info',+ why: `This brain host keeps ${presence.count} recent session transcript file(s)${where} (from the last 7 days). They are raw host files, not pages, so search, query, recall and list_pages never return them, and get_recent_transcripts is not callable on this connection. `+ + 'Read them with the command in fix (from a shell on this machine; otherwise ask the user to run it), or read those .txt files directly if you have a shell here. Never answer "no transcripts" or "no notes" from a page search alone.',+ fix: localTranscriptsFix(),+ user_message: 'Your recent session transcripts are on this machine but not in the searchable pages. I can read them with `gbrain transcripts recent --json`; want me to, or can you run it and share the output?',+ };+}+// ── CLI emission for commands without a result document (F7) ──────────────/**diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex 00baa595bf..4a03b6cd98 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -21,7 +21,7 @@ const MAX_KEYS = 10_000;const TTL_MS = 24 * 60 * 60 * 1000;export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts']);export interface NoticeAudience {transport: Transport;diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex 04ed6e3182..c325dbba66 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -15,6 +15,7 @@// process.exit. SQL via engine.executeRaw with `sourceScopeOpts(ctx)`// when ctx threads — onboard surface threads explicitly per A26.+import { embedBackfillFix } from '../embed-consent.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { BrainEngine } from '../engine.ts';import type { RemediationStep } from '../remediation-step.ts';@@ -202,7 +203,7 @@ export async function checkEmbedStaleness(}));}return {- check: { name: 'embed_staleness', status, message },+ check: { name: 'embed_staleness', status, message, ...(staleCount > 0 ? { fix: embedBackfillFix({ backlog: staleCount, verifyCheck: 'embed_staleness' }) } : {}) },remediations,};}diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex 0dc66a0cfa..2d1d372c6b 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -18,7 +18,7 @@ export const PERSISTENCE_IPC_MAX_CONNECTIONS = 8;export const PERSISTENCE_IPC_OPERATIONS = ['put_page', 'capture', 'delete_page', 'restore_page', 'revert_version', 'edit_page','remember', 'forget', 'extract_facts', 'get_write_request', 'list_write_requests', 'cancel_write_request',- 'get_page', 'fetch',+ 'get_page', 'fetch', 'get_recent_transcripts','list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack','put_skill', 'delete_skill', 'join_brain', 'sync_brain_skills', 'leave_brain','get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions',diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex d4bf4f9fd5..d5eb8e09e0 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -62,6 +62,14 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:allowedSources: unrestricted ? undefined : verified.grant.sourceIds };const params = !unrestricted && request.operation === 'get_page' && request.params.source_id === undefined? { ...request.params, source_id: sourceId } : request.params;+ // `gbrain transcripts recent` through the live owner: the verified local CLI reads the host's transcript+ // files directly, as it does without a serve (localOnly ops never dispatch off the stdio pipe).+ if (request.operation === 'get_recent_transcripts') {+ if (verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Raw transcripts are read only by this host\'s trusted CLI.');+ const p = request.params;+ return (await import('../transcripts.ts')).listRecentTranscripts(engine, { days: typeof p.days === 'number' ? p.days : undefined,+ summary: typeof p.summary === 'boolean' ? p.summary : undefined, limit: typeof p.limit === 'number' ? p.limit : undefined });+ }const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);const result = await dispatchToolCall(engine, request.operation, params, {config, remote: verified.remote, transport: verified.remote ? 'stdio' : undefined, sourceId, auth,diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 5d8e08c74c..138e0e292e 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -85,7 +85,7 @@ import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidatiimport { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts';// Engine-live path (#3596): static import, never a lazy `import()` in the// connect() catch. No cycle: pglite-repair.ts imports nothing from this file.-import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, type WalRepairReceipt } from './pglite-repair.ts';+import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, readRepairFailedMarker, recordFailedAutoRepair, type WalRepairReceipt } from './pglite-repair.ts';import { getFtsLanguage } from './fts-language.ts';import { splitEmbeddingSignature, currentSpaceChunkPredicate, lockEmbeddingSources } from './embedding-invalidation.ts';import type {@@ -811,6 +811,10 @@ export class PGLiteEngine implements BrainEngine {this.walRepairReceipt = null; // per-connect: stale receipts must not survive reconnect()const dataDir = config.database_path || undefined; // undefined = in-memory+ // Automatic repair failed earlier: never open (lock + create write the data dir); refuse with the consented repair.+ const failedRepair = dataDir ? readRepairFailedMarker(dataDir) : null;+ if (dataDir && failedRepair) throw (await import('./pglite-repair-consent.ts')).repairFailedRefusal(dataDir, failedRepair); // engine-dynamic-import-ok: refusal path only, keeps the consent graph off every open+// Acquire file lock to prevent concurrent PGLite access (crashes with Aborted())this._lock = await acquireLock(dataDir);@@ -941,6 +945,7 @@ export class PGLiteEngine implements BrainEngine {const wrapped = new Error(buildPgliteInitErrorMessage(verdict, original, process.platform, ctx) +(retryError === undefined ? '' : `\n Cold retry error: ${retryError}`));+ const repairFailed = dataDir ? recordFailedAutoRepair(dataDir, ctx.repair, ctx.backupPath, original) : null;if (this._db) {try { await this._closeInternal(); }catch (closeError) {@@ -952,6 +957,7 @@ export class PGLiteEngine implements BrainEngine {await releaseLock(this._lock);this._lock = null;}+ if (dataDir && repairFailed) throw (await import('./pglite-repair-consent.ts')).repairFailedRefusal(dataDir, repairFailed, original, wrapped.message); // engine-dynamic-import-ok: refusal path onlythrow wrapped;}}diff --git a/src/core/pglite-repair-consent.ts b/src/core/pglite-repair-consent.tsnew file mode 100644index 0000000000..88efb5eea1--- /dev/null+++ b/src/core/pglite-repair-consent.ts@@ -0,0 +1,78 @@+/**+ * The consent shape of `gbrain pglite-repair` (agent operator contract v1,+ * A4/C2), shared by the command itself and by the repair-failed gate in+ * `PGLiteEngine.connect()`: the same plan (data dir, WAL segments, stale+ * postmaster.pid) and plan_hash, so the fix the gate prints+ * (`gbrain pglite-repair --yes --expect <plan_hash>`) is exactly the command+ * the repair accepts once the user agrees.+ */+import { buildConsentRefusal, computePlanHash, type ConsentRefusal, type PlanSelection } from './consent.ts';+import { gbrainPath, loadConfig } from './config.ts';+import { HANDS_OFF_BRAIN_FILES, inspectPgliteDataDir, type RepairFailedMarker } from './pglite-repair.ts';++export const WAL_REPAIR_BACKUP_SUFFIX = '.wal-repair-backup-';++export const WAL_REPAIR_RISK = 'Data files are preserved; transactions not checkpointed before the corruption may be lost, and indexes are '+ + 'not rebuilt (run gbrain reindex --vectors afterwards). Before the reset the current pg_wal and postmaster.pid are moved, '+ + `and pg_control copied, into a sibling <data-dir>${WAL_REPAIR_BACKUP_SUFFIX}<timestamp> folder (or this incident's existing backup); nothing is deleted.`;++export { HANDS_OFF_BRAIN_FILES } from './pglite-repair.ts';++/** The diagnosed state an approval binds: the data dir, its WAL segments and the stale postmaster.pid. */+export function walRepairPlan(dataDir: string, d: { verdict: string; walSegments: string[]; postmasterPid: unknown }): { selection: PlanSelection; plan_hash: string } {+ const selection: PlanSelection = {+ brain: dataDir, source: null, operation: 'pglite-repair',+ records: [...d.walSegments.map(id => ({ id: `pg_wal/${id}` })), ...(d.postmasterPid ? [{ id: 'postmaster.pid' }] : [])],+ parameters: { verdict: d.verdict }, effects: ['destructive'],+ };+ return { selection, plan_hash: computePlanHash(selection) };+}++/** `--path <dir>` only when the brain is not the configured one, so the fix acts on this brain from anywhere. */+function pathArgs(dataDir: string): string[] {+ let configured: string | null = null;+ try {+ const cfg = loadConfig();+ configured = cfg?.engine === 'pglite' ? cfg.database_path || gbrainPath('brain.pglite') : null;+ } catch { configured = null; }+ return configured === dataDir ? [] : ['--path', dataDir];+}++/**+ * The refusal every brain-opening command gets while the repair-failed marker+ * is set: exit 3, effects `destructive`, the consented repair as the fix+ * (rendered `ask_user` on the CLI, `tell_user_to_run` over MCP) and its+ * read-only `--dry-run` preview. Reads the data dir; never writes it.+ */+export function repairFailedRefusal(dataDir: string, marker: RepairFailedMarker, detail?: string, diagnostic?: string): ConsentRefusal {+ const diagnosis = inspectPgliteDataDir(dataDir);+ const plan = walRepairPlan(dataDir, diagnosis);+ const path = pathArgs(dataDir);+ const when = marker.ts ? ` on ${new Date(marker.ts).toISOString()}` : '';+ const backup = marker.backup_path ? ` The automatic attempt's backup is at ${marker.backup_path}.` : '';+ const e = buildConsentRefusal({+ command: 'pglite-repair',+ effects: ['destructive'],+ actor: 'agent',+ what: `Opening the damaged PGLite brain at ${dataDir}`,+ why: `gbrain's automatic WAL repair of this brain failed${when} (${marker.repair}${detail || marker.detail ? `: ${(detail ?? marker.detail)!.split('\n')[0]}` : ''}), `+ + `so every command now refuses to open it and nothing writes to it until the user decides how to recover.${backup} ${HANDS_OFF_BRAIN_FILES}`,+ risk: `The repair rewrites the brain's write-ahead log. ${WAL_REPAIR_RISK} If the damage is in the catalog, WAL repair may not be enough; `+ + 'the other recoveries (restoring a backup the user has, or `gbrain reinit-pglite`, which rebuilds the brain and can lose database-only pages and facts) are also the user\'s decision.',+ user_message: `Your gbrain brain at ${dataDir} is damaged and gbrain's automatic repair did not fix it, so gbrain has stopped opening it to keep it from getting worse. `+ + 'I can run gbrain\'s repair (it keeps a backup, but changes from just before the crash may be lost), or you can restore it from a backup you have. '+ + 'I won\'t copy, move or edit the brain files myself. Which do you want?',+ argv: ['gbrain', 'pglite-repair', ...path],+ preview_argv: ['gbrain', 'pglite-repair', ...path, '--dry-run', '--json'],+ plan_hash: plan.plan_hash,+ args: [],+ });+ (e as ConsentRefusal & { reason?: string }).reason = 'pglite_repair_failed';+ // The open that just failed keeps its full init diagnostic on the thrown error (the CLI renders the payload).+ if (diagnostic) e.message = `${diagnostic}\n\n${e.message}`;+ return e;+}++export function isRepairFailedRefusal(e: unknown): e is ConsentRefusal {+ return (e as { reason?: unknown } | null)?.reason === 'pglite_repair_failed' && (e as { code?: unknown }).code === 'confirmation_required';+}diff --git a/src/core/pglite-repair.ts b/src/core/pglite-repair.tsindex b629bb9082..2a5a44a612 100644--- a/src/core/pglite-repair.ts+++ b/src/core/pglite-repair.ts@@ -132,6 +132,74 @@ interface RepairSidecar {attempts: Array<{ ts: number; outcome: 'repaired' | 'failed'; backupPath: string | null }>;}+/**+ * Durable repair-failed marker: a sibling `<dataDir>.repair-failed.json`+ * (never inside the data dir). Written when automatic WAL repair failed (or a+ * recently failed attempt put it on cooldown); while it exists+ * `PGLiteEngine.connect()` refuses before the lock or PGLite touch the data+ * dir, so no command keeps writing pg_wal/pg_subtrans into a damaged brain.+ * Cleared only by a completed `gbrain pglite-repair` (consented) or+ * `gbrain reinit-pglite`.+ */+const REPAIR_FAILED_SUFFIX = '.repair-failed.json';++/** Said plainly on every repair-failed refusal (an agent once rebuilt the catalog by hand and swapped it in). */+export const HANDS_OFF_BRAIN_FILES = 'Do not copy, rebuild, move or modify the brain.pglite files yourself (no manual WAL or catalog surgery, '+ + 'no swapping in a rebuilt copy, no moving the directory aside): ask the user which recovery they want.';++export interface RepairFailedMarker {+ ts: number;+ /** What the automatic repair did (PgliteInitRepairContext.repair). */+ repair: string;+ backup_path?: string;+ detail?: string;+}++export function repairFailedMarkerPath(dataDir: string): string {+ return `${dataDir}${REPAIR_FAILED_SUFFIX}`;+}++/** The marker, or null when absent. An unreadable marker still counts (fail closed). */+export function readRepairFailedMarker(dataDir: string): RepairFailedMarker | null {+ const path = repairFailedMarkerPath(dataDir);+ if (!existsSync(path)) return null;+ try {+ const raw = JSON.parse(readFileSync(path, 'utf-8')) as Partial<RepairFailedMarker>;+ return {+ ts: typeof raw.ts === 'number' ? raw.ts : 0,+ repair: typeof raw.repair === 'string' ? raw.repair : 'unknown',+ ...(typeof raw.backup_path === 'string' ? { backup_path: raw.backup_path } : {}),+ ...(typeof raw.detail === 'string' ? { detail: raw.detail } : {}),+ };+ } catch {+ return { ts: 0, repair: 'unknown' };+ }+}++export function writeRepairFailedMarker(dataDir: string, marker: RepairFailedMarker): void {+ try {+ const tmp = `${repairFailedMarkerPath(dataDir)}.tmp-${process.pid}`;+ writeFileSync(tmp, JSON.stringify(marker), { mode: 0o644 });+ renameSync(tmp, repairFailedMarkerPath(dataDir));+ } catch { /* best-effort: the open still fails with the repair error */ }+}++/**+ * After a failed open: automatic repair ran and failed, or a recent failure put+ * it on cooldown. Records the marker (so later commands refuse before touching+ * the data dir) and returns it; null for every other outcome.+ */+export function recordFailedAutoRepair(dataDir: string, repair: string, backupPath: string | undefined, original: string): RepairFailedMarker | null {+ if (repair !== 'failed-restored' && repair !== 'failed-not-restored' && repair !== 'skipped-cooldown') return null;+ const marker: RepairFailedMarker = { ts: Date.now(), repair, ...(backupPath ? { backup_path: backupPath } : {}), detail: original.slice(0, 500) };+ writeRepairFailedMarker(dataDir, marker);+ return marker;+}++export function clearRepairFailedMarker(dataDir: string): void {+ try { rmSync(repairFailedMarkerPath(dataDir), { force: true }); } catch { /* best-effort */ }+}+function sidecarPath(dataDir: string): string {return `${dataDir}${SIDECAR_SUFFIX}`;}diff --git a/src/core/readiness.ts b/src/core/readiness.tsindex 9c8eb54488..8af63b7742 100644--- a/src/core/readiness.ts+++ b/src/core/readiness.ts@@ -45,7 +45,7 @@ import { resolveWritebackConfigFromFile } from './facts/writeback-config.ts';export type ReadinessState = 'ok' | 'disabled_by_choice' | 'not_applicable' | 'missing' | 'degraded' | 'unknown';export type CapabilityId =| 'embeddings' | 'chat_llm' | 'worker' | 'writeback' | 'backup' | 'tool_surface'- | 'sync' | 'migrations' | 'harness_wiring';+ | 'sync' | 'migrations' | 'harness_wiring' | 'local_transcripts';export interface ReadinessEntry {capability: CapabilityId;@@ -89,6 +89,8 @@ export const SYNC_REASONS = ['git_sources', 'no_repo_sources', 'remote_brain', 'engine_unreachable', 'probe_failed', 'probe_timeout',] as const;export const MIGRATIONS_REASONS = ['current', 'pending', 'engine_unreachable', 'probe_failed', 'probe_timeout'] as const;+/** Raw session transcripts on the brain host: present (read through the CLI) or none. */+export const LOCAL_TRANSCRIPTS_REASONS = ['transcripts_cli_only', 'no_transcripts', 'engine_unreachable', 'probe_failed', 'probe_timeout'] as const;export const HARNESS_WIRING_REASONS = ['wired_running', 'registration_unverified', 'http_serve_running', 'multiple_sessions', 'multiple_harnesses','no_harness_detected', 'binary_unresolved', 'remote_transport',@@ -628,7 +630,23 @@ const syncProbe: Prober = {},};-const PROBERS: readonly Prober[] = [workerProbe, backupProbe, migrationsProbe, syncProbe];+const transcriptsProbe: Prober = {+ capability: 'local_transcripts',+ async run(engine) {+ const base = { capability: 'local_transcripts' as const, tier: 'probed' as const, http_visible: false };+ const { localTranscriptsFix, recentTranscriptPresence } = await import('./transcripts.ts');+ const p = await recentTranscriptPresence(engine);+ if (p.count === 0) {+ return { ...base, state: 'not_applicable', reason: 'no_transcripts',+ why: 'No session transcripts from the last 7 days in a configured transcript directory (dream.synthesize.session_corpus_dir, dream.synthesize.meeting_transcripts_dir).' };+ }+ return { ...base, state: 'ok', reason: 'transcripts_cli_only',+ why: `${p.count} recent session transcript(s) exist on this host: read them with \`gbrain transcripts recent --json\` (page search never returns them; get_recent_transcripts is local-only on MCP). Files: ${p.dirs.join(', ')}.`,+ fix: localTranscriptsFix() };+ },+};++const PROBERS: readonly Prober[] = [workerProbe, backupProbe, migrationsProbe, syncProbe, transcriptsProbe];async function runProbes(engine: BrainEngine): Promise<ReadinessEntry[]> {if (isEngineDegraded(engine)) return PROBERS.map(p => failedEntry(p.capability, 'engine_unreachable'));diff --git a/src/core/transcripts.ts b/src/core/transcripts.tsindex 61dacaa155..d9bb5dc432 100644--- a/src/core/transcripts.ts+++ b/src/core/transcripts.ts@@ -14,8 +14,9 @@*/import { readFileSync, readdirSync, statSync } from 'node:fs';-import { join, basename } from 'node:path';+import { join, basename, dirname } from 'node:path';import type { BrainEngine } from './engine.ts';+import type { Action } from './agent-output.ts';import { isDreamOutput } from './cycle/transcript-discovery.ts';import { redactFindings } from './secret-scan.ts';@@ -63,15 +64,53 @@ export async function listRecentTranscripts(const summary = opts.summary !== false;const limit = Math.max(1, Math.min(opts.limit ?? 50, 500));+ const { dirs, candidates } = await transcriptCandidates(engine, days);+ if (dirs.length === 0) return [];++ // Newest first.+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);++ const out: RecentTranscript[] = [];+ for (const c of candidates) {+ if (out.length >= limit) break;+ let raw: string;+ try {+ raw = readFileSync(c.path, 'utf-8');+ } catch {+ continue;+ }+ // Skip dream-generated outputs (would re-feed the synthesize loop).+ if (isDreamOutput(raw)) continue;++ const name = basename(c.path);+ const dateMatch = DATE_RE.exec(name);+ // Redact the whole file before the summary/full-read cap cuts it.+ const text = redactFindings(raw, { highEntropy: true }).text;+ out.push({+ path: name,+ date: dateMatch ? dateMatch[1] : null,+ mtime: new Date(c.mtimeMs).toISOString(),+ length: c.size,+ summary: summary ? buildSummary(text) : text.slice(0, FULL_READ_CAP),+ });+ }+ return out;+}++/** The configured transcript corpus dirs (session + meeting), from the brain's config. */+export async function transcriptCorpusDirs(engine: Pick<BrainEngine, 'getConfig'>): Promise<string[]> {const dirs: string[] = [];const sessionDir = await engine.getConfig('dream.synthesize.session_corpus_dir');const meetingDir = await engine.getConfig('dream.synthesize.meeting_transcripts_dir');if (sessionDir) dirs.push(sessionDir);if (meetingDir) dirs.push(meetingDir);- if (dirs.length === 0) return [];+ return dirs;+}+/** `.txt` files modified within `days` in the corpus dirs (stat only, no content read). */+async function transcriptCandidates(engine: Pick<BrainEngine, 'getConfig'>, days: number): Promise<{ dirs: string[]; candidates: { path: string; mtimeMs: number; size: number }[] }> {+ const dirs = await transcriptCorpusDirs(engine);const cutoffMs = Date.now() - days * 86400000;-const candidates: { path: string; mtimeMs: number; size: number }[] = [];for (const dir of dirs) {let entries: string[];@@ -97,35 +136,28 @@ export async function listRecentTranscripts(candidates.push({ path: full, mtimeMs: st.mtimeMs, size: st.size });}}+ return { dirs, candidates };+}- // Newest first.- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);-- const out: RecentTranscript[] = [];- for (const c of candidates) {- if (out.length >= limit) break;- let raw: string;- try {- raw = readFileSync(c.path, 'utf-8');- } catch {- continue;- }- // Skip dream-generated outputs (would re-feed the synthesize loop).- if (isDreamOutput(raw)) continue;+/** The read an agent (or the user) runs to see the transcripts; it works while a live serve holds the brain. */+export function localTranscriptsFix(): Action {+ return {+ argv: ['gbrain', 'transcripts', 'recent', '--json'],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Lists the recent session transcripts with a short summary of each (add --full for the text, --days <n> for a wider window). It reads through a running gbrain serve when one holds the brain.',+ };+}- const name = basename(c.path);- const dateMatch = DATE_RE.exec(name);- // Redact the whole file before the summary/full-read cap cuts it.- const text = redactFindings(raw, { highEntropy: true }).text;- out.push({- path: name,- date: dateMatch ? dateMatch[1] : null,- mtime: new Date(c.mtimeMs).toISOString(),- length: c.size,- summary: summary ? buildSummary(text) : text.slice(0, FULL_READ_CAP),- });- }- return out;+/**+ * Whether local session transcripts exist for the agent-facing pointers+ * (readiness `local_transcripts`, the `local_transcripts` notice): the dirs+ * holding recent `.txt` transcripts and how many there are. Stat only; the+ * count may include dream outputs the reader later skips.+ */+export async function recentTranscriptPresence(engine: Pick<BrainEngine, 'getConfig'>, days = 7): Promise<{ dirs: string[]; count: number }> {+ const { candidates } = await transcriptCandidates(engine, days);+ const dirs = [...new Set(candidates.map(c => dirname(c.path)))];+ return { dirs, count: candidates.length };}/**diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 2a5775cc9a..44289766d9 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -19,7 +19,7 @@ import { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger } from '../core/notice-ledger.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';-import { recallInteropNotices } from '../core/interop-notices.ts';+import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';import { hiddenToolHint } from './hidden-tool-hint.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';@@ -870,6 +870,15 @@ export async function dispatchToolCall(// never a local path or source id). The refresher runs on the stdio// transport ONLY — the WP1/D7 locality axis localOnly ops use; 'http' or// an UNSET marker never probes (fail-closed).+ // F5 follow-up: local transcripts exist but their reader is not callable on this stdio connection.+ if (opts.transport === 'stdio' && opts.remote !== false && !dispatchRenderContext(opts).isCallable('get_recent_transcripts')+ && wantsTranscriptHint(name, safeParams, result)) {+ try {+ const { recentTranscriptPresence } = await import('../core/transcripts.ts');+ const hint = localTranscriptsNotice(await recentTranscriptPresence(engine));+ if (hint) notices.push(hint);+ } catch { /* a pointer, never a failure */ }+ }maybeBackupNotice(notices, opts);if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));diff --git a/src/mcp/initialize-context.ts b/src/mcp/initialize-context.tsindex 7c943f79a6..a8b0183ca1 100644--- a/src/mcp/initialize-context.ts+++ b/src/mcp/initialize-context.ts@@ -16,7 +16,7 @@ import { disabledOpsForPublishGates } from './publish-gates.ts';import type { InstructionTools } from './instructions.ts';/** Readiness entries the instructions tail may name, most limiting first. */-const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker'] as const;+const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker', 'local_transcripts'] as const;/** Config plane + probed tier (≤ 250 ms), ordered by TAIL_PRIORITY; [] on any failure. */export async function instructionReadiness(diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 17777376f5..5d01f0a5fb 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -73,8 +73,10 @@ function contractClauses(c: CallablePredicate): string[] {return out;}-function readinessTail(entries: readonly ReadinessEntry[]): string | null {- const gaps = entries.filter(e => e.state === 'missing' || e.state === 'degraded').slice(0, 2);+function readinessTail(entries: readonly ReadinessEntry[], callable: (op: string) => boolean): string | null {+ // Local transcripts the caller cannot read through MCP are named too, so an empty page search never reads as "no transcripts".+ const gaps = entries.filter(e => e.state === 'missing' || e.state === 'degraded'+ || e.capability === 'local_transcripts' && e.reason === 'transcripts_cli_only' && !callable('get_recent_transcripts')).slice(0, 2);if (gaps.length === 0) return null;const items = gaps.map(e => `${e.capability} ${e.state}: ${e.why.length > 180 ? `${e.why.slice(0, 179)}…` : e.why}`);return `Setup now (details and fixes in gbrain://capabilities): ${items.join(' | ')}`;@@ -93,7 +95,7 @@ export function buildMcpInstructions(opts?: { writeback?: AmbientWritebackOpts |let text = `GBrain agent operating contract (apply on every cold start):\n${clauses.map((c, i) => `${i + 1}. ${c}`).join('\n')}`;if (tools?.statusLine) text += `\n${tools.statusLine}`;if (opts?.writeback) text += `\n\n${buildAmbientWritebackSection(opts.writeback)}`;- const tail = tools?.readiness ? readinessTail(tools.readiness) : null;+ const tail = tools?.readiness ? readinessTail(tools.readiness, tools.callable) : null;if (tail) text += `\n\n${tail}`;return text;}diff --git a/src/mcp/status-mode.ts b/src/mcp/status-mode.tsindex bf462b4b3a..04bfc1d4dc 100644--- a/src/mcp/status-mode.ts+++ b/src/mcp/status-mode.ts@@ -21,10 +21,11 @@ import { isEngineDegraded } from '../core/degraded-marker.ts';import { opError } from '../core/ops/contract.ts';import { configPath, gbrainPath, loadConfig, type GBrainConfig } from '../core/config.ts';import { inspectLockHolder, peekLock } from '../core/pglite-lock.ts';+import { HANDS_OFF_BRAIN_FILES, readRepairFailedMarker, type RepairFailedMarker } from '../core/pglite-repair.ts';import { resetReadinessMemo } from '../core/readiness.ts';export const STATUS_TOOL_NAME = 'gbrain_status';-export type StatusReason = 'lock_held' | 'no_brain' | 'config_unreadable';+export type StatusReason = 'lock_held' | 'no_brain' | 'config_unreadable' | 'missing_brain' | 'brain_unopenable' | 'repair_failed';export interface StatusModeState {reason: StatusReason;@@ -32,6 +33,8 @@ export interface StatusModeState {brain_path?: string;config_path: string;lock_owner?: { pid?: number; transport: 'stdio' | 'http' | 'unknown'; serve: boolean };+ /** repair_failed: the durable marker automatic PGLite repair left. */+ repair_failed?: RepairFailedMarker;recovered: boolean;/** Last re-probe (epoch ms). */checked_at: number;@@ -67,6 +70,10 @@ export function probeStatus(): Omit<StatusModeState, 'recovered'> | null {if (!cfg) return { reason: existsSync(cfgPath) ? 'config_unreadable' : 'no_brain', config_path: cfgPath, brain_path: gbrainPath('brain.pglite'), checked_at: now };const dataDir = brainPathFor(cfg);if (!dataDir) return null;+ // A configured brain that is not there (unmounted drive, moved folder) is never recreated empty here.+ if (!existsSync(dataDir)) return { reason: 'missing_brain', config_path: cfgPath, brain_path: dataDir, checked_at: now };+ const marker = readRepairFailedMarker(dataDir);+ if (marker) return { reason: 'repair_failed', config_path: cfgPath, brain_path: dataDir, checked_at: now, repair_failed: marker };const holder = inspectLockHolder(dataDir);if (!holder.held || holder.pid === process.pid) return null;const peek = peekLock(dataDir);@@ -84,7 +91,8 @@ export function initialStatusState(fallback: StatusReason): StatusModeState {const probed = probeStatus();if (probed) return { ...probed, recovered: false };return { reason: fallback, config_path: configPath(), recovered: false, checked_at: Date.now(),- ...(fallback === 'lock_held' ? { brain_path: brainPathFor(loadConfig()), lock_owner: { transport: 'unknown' as const, serve: false } } : {}) };+ ...(fallback === 'lock_held' ? { brain_path: brainPathFor(loadConfig()), lock_owner: { transport: 'unknown' as const, serve: false } } : {}),+ ...(fallback === 'brain_unopenable' ? { brain_path: brainPathFor(loadConfig()) } : {}) };}/**@@ -116,6 +124,9 @@ function ownerPhrase(state: StatusModeState): string {export function statusHeadline(state: StatusModeState): string {if (state.reason === 'lock_held') return `This brain (${state.brain_path ?? 'its data directory'}) is open in ${ownerPhrase(state)}, so this server cannot open it.`;if (state.reason === 'config_unreadable') return `The gbrain config at ${state.config_path} exists but cannot be read (invalid JSON or unreadable), so this server cannot open a brain.`;+ if (state.reason === 'brain_unopenable') return `The brain at ${state.brain_path ?? 'its configured path'} exists, but its writer lock file next to it cannot be opened (a read-only or unmounted drive, or permissions), so this server cannot open it.`;+ if (state.reason === 'missing_brain') return `The brain configured in ${state.config_path} is not at ${state.brain_path ?? 'its configured path'} (an unmounted drive or a moved folder?), so this server cannot open it. Nothing was created there.`;+ if (state.reason === 'repair_failed') return `The brain at ${state.brain_path ?? 'its data directory'} is damaged and gbrain's automatic repair failed, so gbrain refuses to open it until the user decides how to recover.`;return `No gbrain brain is set up on this machine yet (no config at ${state.config_path}), so this server has no brain to open.`;}@@ -133,6 +144,42 @@ function statusFix(state: StatusModeState): { fix: Action; user_message: string;user_message: 'gbrain memory is installed but no brain exists yet. Should I create a local one now? It stays on this machine and needs no API key.',};}+ if (state.reason === 'missing_brain' || state.reason === 'brain_unopenable') {+ const where = state.brain_path ?? 'its configured path';+ const user_message = state.reason === 'missing_brain'+ ? `Your gbrain brain is configured at ${where}, but nothing is there right now. Is it on a drive that needs mounting, or did it move? Once it's back I'll reconnect. If it's gone for good I can create a new empty brain, but your old notes would not be in it.`+ : `Your gbrain brain at ${where} is there, but gbrain can't open its lock file next to it (a read-only or unmounted drive, or a permissions problem). Can you check that drive? Once it's writable I'll reconnect.`;+ return {+ fix: {+ mcp: { tool: STATUS_TOOL_NAME, arguments: {} }, consent: [], actor: 'user', requires_exclusive: false,+ why: `${state.reason === 'missing_brain' ? `Mount or reconnect the drive that holds ${where}, or point \`database_path\` in ${state.config_path} at where the brain lives now` : `Make the folder holding ${where} writable for this user (or mount the drive read-write)`}; then call gbrain_status again and this server opens the brain in place. ${RESTART_NOTE}`,+ user_message,+ verify: { argv: ['gbrain', 'doctor', '--only', 'connection', '--json'] },+ },+ user_message,+ decisions: state.reason === 'missing_brain' ? [{+ id: 'missing_brain_recovery',+ question: `The brain at ${where} is not there. Bring it back, or start a new empty brain?`,+ options: [+ { id: 'reconnect', label: 'Mount or move the brain back; this server reconnects on the next gbrain_status call.' },+ { id: 'new_brain', label: 'Create a new, empty keyless brain at that path (the old notes are not in it).', argv: ['gbrain', 'init', '--pglite', '--no-embedding', '--path', where] },+ ],+ default: 'reconnect',+ default_reason: 'Nothing is created or overwritten; the user\'s existing brain comes back as soon as its drive does.',+ }] : undefined,+ };+ }+ if (state.reason === 'repair_failed') {+ const user_message = `Your gbrain brain at ${state.brain_path ?? 'its data directory'} is damaged and gbrain's automatic repair did not fix it, so gbrain has stopped opening it to keep it from getting worse. In a terminal you can preview the repair with \`gbrain pglite-repair --dry-run\` and run the one it prints after you agree, or restore the brain from a backup. Nobody should copy, move or edit the brain files by hand.`;+ return {+ fix: {+ argv: ['gbrain', 'pglite-repair', '--dry-run', '--json'], consent: [], actor: 'user', requires_exclusive: false,+ why: `${HANDS_OFF_BRAIN_FILES} The read-only preview names the consented repair (\`gbrain pglite-repair --yes --expect <plan_hash>\`, effects destructive) the user runs once they agree; then call gbrain_status again. ${RESTART_NOTE}`,+ user_message,+ },+ user_message,+ };+ }if (state.reason === 'config_unreadable') {return {fix: {@@ -205,6 +252,7 @@ export function statusPayload(state: StatusModeState): Record<string, unknown> {...(state.brain_path ? { brain_path: state.brain_path } : {}),config_path: state.config_path,...(state.lock_owner ? { lock_owner: state.lock_owner } : {}),+ ...(state.repair_failed ? { repair_failed: state.repair_failed } : {}),fix: renderAction(fix, STATUS_RENDER),user_message,...(decisions ? { decisions } : {}),@@ -217,7 +265,7 @@ export function statusPayload(state: StatusModeState): Record<string, unknown> {/** The one tool advertised in status mode. */export const STATUS_TOOL_DEF = {name: STATUS_TOOL_NAME,- description: 'gbrain is running in status-only mode: its brain is locked by another server, missing, or its config is unreadable. Call this for the cause (lock owner, brain path), the fix and what to tell the user; calling it also re-checks and restores the full tool list once the brain can be opened.',+ description: 'gbrain is running in status-only mode: its brain is locked by another server, missing, damaged (automatic repair failed), or its config is unreadable. Call this for the cause (lock owner, brain path), the fix and what to tell the user; calling it also re-checks and restores the full tool list once the brain can be opened.',inputSchema: { type: 'object' as const, properties: {} },annotations: { title: 'gbrain status (status-only mode)', readOnlyHint: true },};diff --git a/test/agent-journey.serial.test.ts b/test/agent-journey.serial.test.tsindex 83db817ef9..2d85eab736 100644--- a/test/agent-journey.serial.test.ts+++ b/test/agent-journey.serial.test.ts@@ -30,7 +30,7 @@* Serial: real subprocesses and PGLite datastores in temp homes.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -322,3 +322,46 @@ describe('H1a keyless MCP journey (stdio)', () => {expect(timings.first_recall_ms).toBeLessThan(30_000);}, 150_000);});++describe('H2 missing_brain: the configured brain is on a drive that is not mounted', () => {+ let home = '';+ beforeAll(() => { home = mkdtempSync(join(tmpdir(), 'gbrain-journey-missing-')); });+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });++ test('serve completes the handshake in status-only mode naming the path; nothing is created there; mounting it recovers in place', async () => {+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ const offline = join(home, 'offline', 'brain.pglite');+ const mounted = join(home, 'mnt', 'external', 'gbrain', 'brain.pglite');+ mkdirSync(join(home, 'offline'), { recursive: true });+ renameSync(brainPath(home), offline);+ const cfgPath = join(home, '.gbrain', 'config.json');+ writeFileSync(cfgPath, JSON.stringify({ ...JSON.parse(readFileSync(cfgPath, 'utf8')), database_path: mounted }, null, 2));++ const session = await mcp(home, ['--surface', 'verbs']);+ try {+ expect(session.client.getInstructions()).toContain('STATUS-ONLY MODE');+ expect((await session.client.listTools()).tools.map(t => t.name)).toEqual(['gbrain_status']);+ const statusResult = await call(session, 'gbrain_status');+ const status = body(statusResult);+ expect(status).toMatchObject({ status: 'unavailable', reason: 'missing_brain', brain_path: mounted });+ expect(status.why).toContain(mounted);+ expect(status.fix.next).toBe('tell_user_to_run');+ expect(status.decisions[0].options.map((o: { id: string }) => o.id)).toEqual(['reconnect', 'new_brain']);+ expect(status.decisions[0].options[1].argv).toEqual(['gbrain', 'init', '--pglite', '--no-embedding', '--path', mounted]);+ journeyGolden('status-only-missing-brain.json', statusResult, { home });+ expect(existsSync(join(home, 'mnt'))).toBe(false);++ // The drive comes back: the next gbrain_status call opens the brain in place.+ mkdirSync(join(home, 'mnt', 'external', 'gbrain'), { recursive: true });+ renameSync(offline, mounted);+ let recovered = false;+ for (let i = 0; i < 40 && !recovered; i++) {+ recovered = body(await call(session, 'gbrain_status')).status === 'recovered';+ if (!recovered) await new Promise(r => setTimeout(r, 500));+ }+ expect(recovered).toBe(true);+ } finally {+ await session.close();+ }+ }, 180_000);+});diff --git a/test/agent-operator-gate-fixes.serial.test.ts b/test/agent-operator-gate-fixes.serial.test.tsnew file mode 100644index 0000000000..d9c7c3280c--- /dev/null+++ b/test/agent-operator-gate-fixes.serial.test.ts@@ -0,0 +1,305 @@+/**+ * Release-gate fixes from the Cat 41 after-pass (agent operator wave): the+ * consent violations and the false "no notes" answer real agents produced on+ * the candidate, each pinned against the real CLI / stdio MCP server.+ *+ * 1. Plain `gbrain doctor` (and --only, --remediation-plan) sends no provider+ * request; the live embedding probe needs `--probe` plus authorization.+ * 2. Every remediation-plan step carries a fix with its effects; an explicit+ * embedding backfill (`embed`, `jobs submit embed`) refuses unauthorized+ * (exit 3) and runs under a preapproval; ordinary writes still embed.+ * 3. A brain whose automatic PGLite repair failed is never opened again:+ * every command exits 3 with the consented repair, and the data dir stays+ * byte-identical (zero writes) until the user runs the repair.+ * 4. A stdio agent learns that local transcripts exist (notice + readiness)+ * and `gbrain transcripts recent --json` reads them through the live serve.+ *+ * Paid calls go to a local fake OpenAI endpoint that counts requests.+ * Serial: real subprocesses, PGLite brains in temp homes, a bound local port.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { REPO, body, call, gb, journeyEnv, mcp, noticeBlocks, oneDocument, type McpSession } from './helpers/agent-journey.ts';++const DIMS = 1536;++function fakeProvider() {+ const requests: string[] = [];+ const server = Bun.serve({+ port: 0,+ async fetch(req) {+ const url = new URL(req.url);+ requests.push(url.pathname);+ if (url.pathname.endsWith('/embeddings')) {+ const b = await req.json() as { input: string | string[] };+ const inputs = Array.isArray(b.input) ? b.input : [b.input];+ return Response.json({ object: 'list', model: 'text-embedding-3-small',+ data: inputs.map((_, index) => ({ object: 'embedding', index, embedding: Array.from({ length: DIMS }, () => 0.01) })),+ usage: { prompt_tokens: 9, total_tokens: 9 } });+ }+ return Response.json({ error: { message: 'not handled' } }, { status: 404 });+ },+ });+ return { server, embedCalls: () => requests.filter(p => p.endsWith('/embeddings')).length };+}++function writeNotes(home: string, n = 3): string {+ const dir = join(home, 'notes');+ mkdirSync(dir, { recursive: true });+ for (let i = 1; i <= n; i++) writeFileSync(join(dir, `gate-note-${i}.md`), `---\ntitle: Gate note ${i}\n---\n\n# Gate note ${i}\n\nThe heron-gate marker ${i} lives here.\n`);+ return dir;+}++describe('paid provider calls need authorization (doctor probe, remediation plan, embed backfills)', () => {+ let home = '';+ let provider: ReturnType<typeof fakeProvider>;+ let env: Record<string, string> = {};+ const cli = (args: string[], extra: Record<string, string> = {}) => gb(home, args, { env: { ...env, ...extra }, timeoutMs: 180_000 });++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-gate-paid-'));+ provider = fakeProvider();+ env = { OPENAI_API_KEY: 'sk-gate-fake-provider-key', OPENAI_BASE_URL: `http://127.0.0.1:${provider.server.port}/v1` };+ expect((await cli(['init', '--pglite', '--embedding-model', 'openai:text-embedding-3-small', '--non-interactive', '--json'])).exitCode).toBe(0);+ const imp = await cli(['import', writeNotes(home), '--no-embed']);+ expect(imp.exitCode, imp.stderr).toBe(0);+ }, 300_000);++ afterAll(() => {+ provider?.server.stop(true);+ rmSync(home, { recursive: true, force: true });+ });++ test('plain doctor, doctor --only and the remediation plan send no provider request', async () => {+ const before = provider.embedCalls();+ const doctor = await cli(['doctor', '--json']);+ const report = oneDocument(doctor, 'doctor --json');+ const check = (report.checks as Array<Record<string, any>>).find(c => c.name === 'embedding_provider')!;+ expect(check.details).toMatchObject({ probed: false });+ expect(check.fix.consent).toEqual(['paid', 'egress']);+ expect(check.fix.next).toBe('ask_user');+ expect(check.fix.argv).toEqual(expect.arrayContaining(['doctor', '--only', 'embedding_provider', '--probe', '--yes']));++ const only = await cli(['doctor', '--only', 'embedding_provider', '--json']);+ expect(oneDocument(only, 'doctor --only').checks[0].details.probed).toBe(false);++ const plan = oneDocument(await cli(['doctor', '--remediation-plan', '--json']), 'remediation plan');+ expect(provider.embedCalls()).toBe(before);++ const steps = plan.plan as Array<Record<string, any>>;+ expect(steps.length).toBeGreaterThan(0);+ for (const step of steps) {+ expect(step.fix, `${step.id} carries a fix`).toBeTruthy();+ expect(step.fix.consent, `${step.id} declares its effects`).toBeArray();+ expect(['run', 'ask_user']).toContain(step.fix.next);+ }+ const embedStep = steps.find(s => s.job === 'embed')!;+ expect(embedStep.est_usd_cost).toBeGreaterThan(0);+ expect(embedStep.fix.consent).toEqual(['paid']);+ expect(embedStep.fix.next).toBe('ask_user');+ expect(embedStep.fix.argv).toContain('--yes');+ expect(embedStep.fix.user_message).toBeTruthy();+ }, 300_000);++ test('doctor --probe refuses without authorization (exit 3) and probes once with --yes', async () => {+ const before = provider.embedCalls();+ const refused = await cli(['doctor', '--only', 'embedding_provider', '--probe', '--json']);+ expect(refused.exitCode).toBe(3);+ const payload = oneDocument(refused, 'probe refusal');+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['paid', 'egress'] });+ expect(payload.fix.argv).toContain('--yes');+ expect(provider.embedCalls()).toBe(before);++ const probed = await cli(['doctor', '--only', 'embedding_provider', '--probe', '--yes', '--json']);+ const check = oneDocument(probed, 'probe --yes').checks[0];+ expect(check.message).toContain('DB aligned');+ expect(provider.embedCalls()).toBe(before + 1);+ }, 180_000);++ test('explicit embedding backfills refuse unauthorized (exit 3) and spend nothing', async () => {+ const before = provider.embedCalls();+ const stale = await cli(['embed', '--stale', '--catch-up', '--json']);+ expect(stale.exitCode).toBe(3);+ const payload = oneDocument(stale, 'embed refusal');+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['paid'] });+ expect(payload.est_usd).toBeGreaterThan(0);+ expect(payload.fix.next).toBe('ask_user');+ expect(payload.fix.argv.slice(0, 6)).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--json', '--yes']);+ expect(payload.preview.argv).toContain('--dry-run');++ const human = await cli(['embed', '--stale']);+ expect(human.exitCode).toBe(3);+ expect(human.stdout).toContain('[SHOW USER]');++ const job = await cli(['jobs', 'submit', 'embed', '--params', '{"stale":true}', '--follow']);+ expect(job.exitCode).toBe(3);+ expect(provider.embedCalls()).toBe(before);++ const stats = await cli(['stats']);+ expect(stats.stdout).toMatch(/Embedded:\s+0\b/);+ }, 300_000);++ test('a per-run preapproval authorizes the backfill; an ordinary write embeds as configured', async () => {+ expect((await cli(['config', 'set', 'consent.preapprove.paid.max_usd_per_run', '0.5'])).exitCode).toBe(0);+ const before = provider.embedCalls();+ const run = await cli(['embed', '--stale']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(run.stderr).toContain('preapproval');+ expect(provider.embedCalls()).toBeGreaterThan(before);++ // Write-path embedding of new content under a configured key is the configured feature, not a gated action:+ // an ordinary write never asks for consent.+ const write = Bun.spawnSync(['bun', '--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), 'put', 'notes/gate-write-path'], {+ cwd: home, env: journeyEnv(home, env),+ stdin: Buffer.from('---\ntitle: Gate write path\n---\n\nA fresh page written after the backfill.\n'),+ });+ expect(write.exitCode, write.stderr.toString()).toBe(0);+ expect(write.stdout.toString() + write.stderr.toString()).not.toContain('confirmation_required');+ }, 300_000);+});++// ── 3. repair-failed brains are never opened ───────────────────────────────++/** Every file under the data dir, hashed (pg_control and postmaster.pid included: the gate allows zero writes). */+function manifest(dir: string, rel = ''): Record<string, string> {+ const out: Record<string, string> = {};+ for (const name of readdirSync(join(dir, rel))) {+ const r = rel ? `${rel}/${name}` : name;+ const full = join(dir, r);+ if (statSync(full).isDirectory()) Object.assign(out, manifest(dir, r));+ else out[r] = `${statSync(full).size}:${createHash('sha256').update(readFileSync(full)).digest('hex')}`;+ }+ return out;+}++/** Overwrite the tuple area of every pg_class page in the user database: the catalog no longer opens and WAL repair cannot fix it. */+function corruptCatalog(dataDir: string): void {+ for (const db of readdirSync(join(dataDir, 'base'))) {+ if (db === '1') continue;+ const file = join(dataDir, 'base', db, '1259');+ if (!existsSync(file)) continue;+ const bytes = readFileSync(file);+ for (let i = 0; i < bytes.length; i += 8192) bytes.fill(0xff, i + 24, i + 600);+ writeFileSync(file, bytes);+ }+}++describe('a brain whose automatic repair failed is not opened or written', () => {+ let home = '';+ const cli = (args: string[]) => gb(home, args, { timeoutMs: 180_000 });+ const dataDir = () => join(home, '.gbrain', 'brain.pglite');+ const marker = () => `${dataDir()}.repair-failed.json`;++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-gate-repair-'));+ expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await cli(['import', writeNotes(home), '--no-embed'])).exitCode).toBe(0);+ corruptCatalog(dataDir());+ }, 300_000);++ afterAll(() => { rmSync(home, { recursive: true, force: true }); });++ test('the failed automatic repair leaves a marker; every later command exits 3 with the consented repair and writes nothing', async () => {+ const first = await cli(['list', '--json']);+ expect(first.exitCode, first.stderr).toBe(3);+ expect(existsSync(marker())).toBe(true);+ const firstPayload = oneDocument(first, 'first refusal');+ expect(firstPayload).toMatchObject({ code: 'confirmation_required', effects: ['destructive'] });++ const before = manifest(dataDir());+ for (const args of [['stats'], ['doctor', '--json'], ['list'], ['search', 'heron'], ['doctor', '--only', 'brain_score', '--json'], ['status', '--json']]) {+ const r = await cli(args);+ expect(r.exitCode, `gbrain ${args.join(' ')}: ${r.stderr.slice(-500)}`).toBe(3);+ expect(r.stdout + r.stderr).toContain('Do not copy, rebuild, move or modify the brain.pglite files yourself');+ }+ const json = oneDocument(await cli(['stats', '--json']), 'stats --json refusal');+ expect(json).toMatchObject({ status: 'confirmation_required', code: 'confirmation_required', effects: ['destructive'], actor: 'agent' });+ expect(json.fix.next).toBe('ask_user');+ expect(json.fix.argv.slice(0, 4)).toEqual(['gbrain', 'pglite-repair', '--yes', '--expect']);+ expect(json.preview.argv).toEqual(['gbrain', 'pglite-repair', '--dry-run', '--json']);+ expect(json.user_message).toBeTruthy();++ // The repair lane still works and changes nothing on --dry-run; engine-free doctor checks run.+ const dry = await cli(['pglite-repair', '--dry-run', '--json']);+ expect(dry.exitCode).toBe(0);+ const diag = JSON.parse(dry.stdout);+ expect(diag.repair_failed).toBeTruthy();+ expect(diag.plan_hash).toBe(json.plan_hash);+ expect((await cli(['doctor', '--only', 'embedding_key_source', '--json'])).exitCode).toBe(0);++ expect(manifest(dataDir())).toEqual(before);+ }, 600_000);++ test('stdio serve completes the handshake in status-only mode naming the failed repair, without touching the data dir', async () => {+ const before = manifest(dataDir());+ const session = await mcp(home, []);+ try {+ expect((await session.client.listTools()).tools.map(t => t.name)).toEqual(['gbrain_status']);+ const status = body(await call(session, 'gbrain_status'));+ expect(status).toMatchObject({ status: 'unavailable', reason: 'repair_failed' });+ expect(status.fix.next).toBe('tell_user_to_run');+ expect(status.fix.why).toContain('Do not copy, rebuild, move or modify');+ } finally {+ await session.close();+ }+ expect(manifest(dataDir())).toEqual(before);+ }, 180_000);++ test('the consented repair clears the marker', async () => {+ const plan = JSON.parse((await cli(['pglite-repair', '--dry-run', '--json'])).stdout);+ const run = await cli(['pglite-repair', '--yes', '--expect', plan.plan_hash, '--json']);+ expect(run.exitCode, run.stderr).toBe(0);+ expect(existsSync(marker())).toBe(false);+ }, 180_000);+});++// ── 4. local transcripts reach a stdio agent ───────────────────────────────++describe('local transcripts are discoverable from stdio MCP', () => {+ let home = '';+ let session: McpSession | null = null;+ const cli = (args: string[]) => gb(home, args, { timeoutMs: 180_000 });++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-gate-transcripts-'));+ expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await cli(['import', writeNotes(home), '--no-embed'])).exitCode).toBe(0);+ mkdirSync(join(home, 'transcripts'));+ writeFileSync(join(home, 'transcripts', '2026-10-01-session.txt'), 'User: I promise to finish the ledger cutover by Friday.\n');+ expect((await cli(['config', 'set', 'dream.synthesize.session_corpus_dir', join(home, 'transcripts')])).exitCode).toBe(0);+ }, 300_000);++ afterAll(async () => {+ await session?.close();+ rmSync(home, { recursive: true, force: true });+ });++ test('an activity-shaped search names the transcripts and the CLI read; the CLI reads them through the live serve', async () => {+ session = await mcp(home, []);+ const tools = (await session.client.listTools()).tools.map(t => t.name);+ expect(tools).not.toContain('get_recent_transcripts');++ const found = await call(session, 'search', { query: 'what did I promise in my coding sessions this week' });+ const blocks = noticeBlocks(found).filter(b => b.startsWith('[gbrain notice local_transcripts '));+ expect(blocks).toHaveLength(1);+ expect(blocks[0]).toContain('1 recent session transcript file(s)');+ expect(blocks[0]).toContain('gbrain transcripts recent --json');+ expect(blocks[0]).toContain('Never answer "no transcripts"');++ // A plain non-empty listing carries no transcript pointer.+ const listed = await call(session, 'list_pages', {});+ expect(noticeBlocks(listed).some(b => b.startsWith('[gbrain notice local_transcripts '))).toBe(false);++ const capabilities = await session.client.readResource({ uri: 'gbrain://capabilities' });+ const caps = JSON.parse((capabilities.contents[0] as { text: string }).text);+ const entry = (caps.readiness as Array<Record<string, any>>).find(e => e.capability === 'local_transcripts');+ expect(entry).toMatchObject({ state: 'ok', reason: 'transcripts_cli_only' });++ const read = await cli(['transcripts', 'recent', '--json']);+ expect(read.exitCode, read.stderr).toBe(0);+ expect(JSON.parse(read.stdout)[0].summary).toContain('ledger cutover');+ }, 240_000);+});diff --git a/test/agent-operator-gate-fixes.test.ts b/test/agent-operator-gate-fixes.test.tsnew file mode 100644index 0000000000..9568cf2eb8--- /dev/null+++ b/test/agent-operator-gate-fixes.test.ts@@ -0,0 +1,125 @@+/**+ * Unit pins for the Cat 41 release-gate fixes (see the serial journey in+ * agent-operator-gate-fixes.serial.test.ts): remediation-plan step fixes carry+ * their effects, the transcript pointer's trigger and wire shape, the serve status reasons+ * for a missing or unopenable brain, and the repair-failed marker file.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { jobStepFix, repairStepFix } from '../src/commands/doctor/remediate.ts';+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';+import { localTranscriptsNotice, wantsTranscriptHint } from '../src/core/interop-notices.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { PER_CALL_NOTICE_CODES } from '../src/core/notice-ledger.ts';+import { statusReasonForError } from '../src/commands/serve-status.ts';+import { clearRepairFailedMarker, readRepairFailedMarker, repairFailedMarkerPath, writeRepairFailedMarker } from '../src/core/pglite-repair.ts';+import { isRepairFailedRefusal, repairFailedRefusal } from '../src/core/pglite-repair-consent.ts';+import { embedBackfillFix, EMBED_BACKFILL_JOB_NAMES } from '../src/core/embed-consent.ts';+import { embeddingProbeFix } from '../src/commands/doctor/checks/embedding-health.ts';++describe('remediation plan steps carry an Action with their effects', () => {+ test('a paid embed step asks first and runs verbatim once approved', async () => {+ const fix = await jobStepFix({ job: 'embed', params: { stale: true }, est_usd_cost: 0.00005 });+ expect(fix.consent).toEqual(['paid']);+ expect(fix.argv).toEqual(['gbrain', 'jobs', 'submit', 'embed', '--params', '{"stale":true}', '--follow', '--yes']);+ expect(fix.user_message).toBeTruthy();+ expect(renderAction(fix, cliRenderContext()).next).toBe('ask_user');+ });++ test('a provider-calling job is paid even when its estimate is 0', async () => {+ expect((await jobStepFix({ job: 'embed-catch-up', est_usd_cost: 0 })).consent).toEqual(['paid']);+ });++ test('a free job runs without consent', async () => {+ const fix = await jobStepFix({ job: 'extract', params: { stale: true }, est_usd_cost: 0 });+ expect(fix.consent).toEqual([]);+ expect(fix.argv).not.toContain('--yes');+ expect(renderAction(fix, cliRenderContext()).next).toBe('run');+ });++ test('a repair step is destructive (and paid when it embeds) with a read-only preview', () => {+ const fix = repairStepFix({ kind: 'timeline', command: 'gbrain repair timeline --apply', paid: true, est_usd_cost: 0.01, affected: 3, checks: ['timeline_history'] });+ expect(fix.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'timeline_history', '--json']);+ expect(fix.consent).toEqual(['destructive', 'paid']);+ expect(fix.argv).toEqual(['gbrain', 'repair', 'timeline', '--apply']);+ expect(fix.preview_argv).toEqual(['gbrain', 'repair', 'timeline']);+ expect(renderAction(fix, cliRenderContext()).next).toBe('ask_user');+ });+});++describe('doctor and embed fixes', () => {+ test('the embedding probe is paid + egress for a billed provider and free for a local one', () => {+ expect(embeddingProbeFix('openai:text-embedding-3-small').consent).toEqual(['paid', 'egress']);+ expect(embeddingProbeFix('openai:text-embedding-3-small').argv).toContain('--yes');+ expect(embeddingProbeFix('ollama:nomic-embed-text', true).consent).toEqual([]);+ });++ test('the embedding backlog fix asks first and previews with --dry-run', () => {+ const fix = embedBackfillFix({ backlog: 6, verifyCheck: 'embeddings' });+ expect(fix.consent).toEqual(['paid']);+ expect(fix.argv).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--yes']);+ expect(fix.preview_argv).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--dry-run']);+ expect([...EMBED_BACKFILL_JOB_NAMES].sort()).toEqual(['embed', 'embed-backfill', 'embed-catch-up']);+ });+});++describe('local transcripts pointer', () => {+ test('fires on activity-shaped or empty reads, never on a non-empty listing', () => {+ expect(wantsTranscriptHint('search', { query: 'what did I promise in my coding sessions this week' }, [{ slug: 'a' }])).toBe(true);+ expect(wantsTranscriptHint('query', { query: 'larkspur contract term' }, [])).toBe(true);+ expect(wantsTranscriptHint('query', { query: 'larkspur contract term' }, [{ slug: 'a' }])).toBe(false);+ expect(wantsTranscriptHint('list_pages', {}, [{ slug: 'a' }])).toBe(false);+ expect(wantsTranscriptHint('list_pages', {}, [])).toBe(true);+ expect(wantsTranscriptHint('get_page', { slug: 'sessions' }, null)).toBe(false);+ });++ test('a registered per-call info notice whose fix is the CLI read; none without transcripts', () => {+ expect(localTranscriptsNotice({ dirs: [], count: 0 })).toBeNull();+ const n = localTranscriptsNotice({ dirs: ['/host/transcripts'], count: 2 })!;+ expect(n).toMatchObject({ code: 'local_transcripts', kind: 'info' });+ expect(n.fix?.argv).toEqual(['gbrain', 'transcripts', 'recent', '--json']);+ expect(n.why).toContain('/host/transcripts');+ expect(n.why).toContain('Never answer "no transcripts"');+ expect(NOTICE_CODES.local_transcripts.kind).toBe('info');+ expect(PER_CALL_NOTICE_CODES.has('local_transcripts')).toBe(true);+ });+});++describe('serve status reasons and the repair-failed marker', () => {+ let dir = '';+ beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'gate-marker-')); });+ afterAll(() => { rmSync(dir, { recursive: true, force: true }); });++ test('an unopenable writer-lock file is a status-only reason, not a pre-handshake exit', () => {+ expect(statusReasonForError(new Error('Cannot open the stable writer lock file'))).toBe('brain_unopenable');+ expect(statusReasonForError(Object.assign(new Error('busy'), { code: 'pglite_busy' }))).toBe('lock_held');+ expect(statusReasonForError(new Error('something else'))).toBeNull();+ });++ test('the marker is a sibling file; unreadable counts as set; clear removes it', () => {+ const dataDir = join(dir, 'brain.pglite');+ mkdirSync(dataDir);+ expect(readRepairFailedMarker(dataDir)).toBeNull();+ writeRepairFailedMarker(dataDir, { ts: 1, repair: 'failed-restored', backup_path: `${dataDir}.wal-repair-backup-1` });+ expect(repairFailedMarkerPath(dataDir)).toBe(`${dataDir}.repair-failed.json`);+ expect(readRepairFailedMarker(dataDir)).toEqual({ ts: 1, repair: 'failed-restored', backup_path: `${dataDir}.wal-repair-backup-1` });+ writeFileSync(repairFailedMarkerPath(dataDir), '{not json');+ expect(readRepairFailedMarker(dataDir)).toEqual({ ts: 0, repair: 'unknown' });+ clearRepairFailedMarker(dataDir);+ expect(existsSync(repairFailedMarkerPath(dataDir))).toBe(false);+ });++ test('the refusal is the exit-3 consent payload: destructive, the consented repair, the read-only preview, hands off the files', () => {+ const dataDir = join(dir, 'other.pglite');+ mkdirSync(dataDir);+ const e = repairFailedRefusal(dataDir, { ts: 0, repair: 'failed-restored' });+ expect(isRepairFailedRefusal(e)).toBe(true);+ expect(e.consent).toMatchObject({ code: 'confirmation_required', effects: ['destructive'], actor: 'agent' });+ expect(e.consent.fix.argv).toEqual(['gbrain', 'pglite-repair', '--path', dataDir, '--yes', '--expect', e.consent.plan_hash!]);+ expect(e.consent.fix.next).toBe('ask_user');+ expect(e.consent.preview?.argv).toEqual(['gbrain', 'pglite-repair', '--path', dataDir, '--dry-run', '--json']);+ expect(e.consent.why).toContain('Do not copy, rebuild, move or modify the brain.pglite files yourself');+ });+});diff --git a/test/cli-dispatch-lifecycle.serial.test.ts b/test/cli-dispatch-lifecycle.serial.test.tsindex 24b481c1a7..7775fdacd0 100644--- a/test/cli-dispatch-lifecycle.serial.test.ts+++ b/test/cli-dispatch-lifecycle.serial.test.ts@@ -153,7 +153,10 @@ describe('CLI dispatch lifecycle (connect / remote-route / drain / disconnect)',});test('serve is never torn down by the dispatcher', async () => {- writeConfig(LOCAL);+ // The configured data dir exists: serve with a missing brain directory starts status-only instead of connecting.+ const dataDir = join(home, 'brain.pglite');+ mkdirSync(dataDir, { recursive: true });+ writeConfig({ ...LOCAL, database_path: dataDir });expect(await run(['serve'])).toEqual(['connect', 'handler:serve', 'returned']);});diff --git a/test/cli-help-without-brain.serial.test.ts b/test/cli-help-without-brain.serial.test.tsindex 915c52d461..ad1c153d43 100644--- a/test/cli-help-without-brain.serial.test.ts+++ b/test/cli-help-without-brain.serial.test.ts@@ -49,6 +49,8 @@ const HELP_WITHOUT_BRAIN = [// D5: selfHelp handlers that already answered --help before the engine but// were reached only after connect; now SELF_HELP_WITHOUT_ENGINE table entries.'brainstorm', 'lsd', 'migrate', 'pages', 'pricing', 'whoknows',+ // Agent operator gate fixes: embed's usage (incl. its consent flags) prints before the engine.+ 'embed',];/**@@ -60,7 +62,6 @@ const HELP_WITHOUT_BRAIN = [*/const STILL_NEEDS_A_BRAIN = ['config',- 'embed',];async function runHelp(command: string): Promise<{ code: number; out: string }> {diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.tsindex 2160526223..6f2d55f8ad 100644--- a/test/embed.serial.test.ts+++ b/test/embed.serial.test.ts@@ -1078,7 +1078,8 @@ describe('embed --stale time-budget stop is loud (large-brain ceiling)', () => {console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };_resetCliExitVerdictForTests();try {- await run(budgetEngine(), ['--stale', '--batch-size', '1'], { SELECTED_CONFIG_BY_ENGINE: new Map() } as never);+ // `--yes`: an explicit backfill is paid work and this run is the user's approved one.+ await run(budgetEngine(), ['--stale', '--batch-size', '1', '--yes'], { SELECTED_CONFIG_BY_ENGINE: new Map() } as never);expect(currentExitCode()).toBe(BUDGET_STOP_EXIT_CODE);expect(BUDGET_STOP_EXIT_CODE).toBe(11);} finally {diff --git a/test/embedding-recovery.serial.test.ts b/test/embedding-recovery.serial.test.tsindex 3487671853..e8c0ace845 100644--- a/test/embedding-recovery.serial.test.ts+++ b/test/embedding-recovery.serial.test.ts@@ -1464,7 +1464,8 @@ test('explicit archived admission: actual CLI refuses all three routes without lconst dryRun = await run([...args, '--dry-run']);expect(dryRun.code).toBe(0);expect(readFileSync(calls, 'utf8')).toBe('');- const result = await run(args);+ // An explicit backfill is paid work: authorized here so the archived-source refusal is what the run hits.+ const result = await run([...args, '--yes']);expect({ code: result.code, diagnostic: result.code === 1 ? '' : result.stderr }).toEqual({ code: 1, diagnostic: '' });expect(result.stderr).toContain('gbrain sources restore');expect(result.stdout + result.stderr).not.toContain(privateBody);@@ -1476,7 +1477,7 @@ test('explicit archived admission: actual CLI refuses all three routes without lexpect(await snapshot()).toEqual(before);await engine.disconnect();}- expect((await run(['active-target'])).code).toBe(0);+ expect((await run(['active-target', '--yes'])).code).toBe(0);});} finally {await engine.disconnect();diff --git a/test/fixtures/agent-contract/v1/journey/status-only-missing-brain.json b/test/fixtures/agent-contract/v1/journey/status-only-missing-brain.jsonnew file mode 100644index 0000000000..e9d2220603--- /dev/null+++ b/test/fixtures/agent-contract/v1/journey/status-only-missing-brain.json@@ -0,0 +1,8 @@+{+ "content": [+ {+ "type": "text",+ "text": "{\n \"status\": \"unavailable\",\n \"reason\": \"missing_brain\",\n \"why\": \"The brain configured in {{HOME}}/.gbrain/config.json is not at {{HOME}}/mnt/external/gbrain/brain.pglite (an unmounted drive or a moved folder?), so this server cannot open it. Nothing was created there.\",\n \"brain_path\": \"{{HOME}}/mnt/external/gbrain/brain.pglite\",\n \"config_path\": \"{{HOME}}/.gbrain/config.json\",\n \"fix\": {\n \"mcp\": {\n \"tool\": \"gbrain_status\",\n \"arguments\": {}\n },\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Mount or reconnect the drive that holds {{HOME}}/mnt/external/gbrain/brain.pglite, or point `database_path` in {{HOME}}/.gbrain/config.json at where the brain lives now; then call gbrain_status again and this server opens the brain in place. If your client does not refresh its tool list after recovery, restart this MCP server.\",\n \"user_message\": \"Your gbrain brain is configured at {{HOME}}/mnt/external/gbrain/brain.pglite, but nothing is there right now. Is it on a drive that needs mounting, or did it move? Once it's back I'll reconnect. If it's gone for good I can create a new empty brain, but your old notes would not be in it.\",\n \"verify\": {\n \"argv\": [\n \"gbrain\",\n \"doctor\",\n \"--only\",\n \"connection\",\n \"--json\"\n ]\n },\n \"requires_exclusive\": false\n },\n \"user_message\": \"Your gbrain brain is configured at {{HOME}}/mnt/external/gbrain/brain.pglite, but nothing is there right now. Is it on a drive that needs mounting, or did it move? Once it's back I'll reconnect. If it's gone for good I can create a new empty brain, but your old notes would not be in it.\",\n \"decisions\": [\n {\n \"id\": \"missing_brain_recovery\",\n \"question\": \"The brain at {{HOME}}/mnt/external/gbrain/brain.pglite is not there. Bring it back, or start a new empty brain?\",\n \"options\": [\n {\n \"id\": \"reconnect\",\n \"label\": \"Mount or move the brain back; this server reconnects on the next gbrain_status call.\"\n },\n {\n \"id\": \"new_brain\",\n \"label\": \"Create a new, empty keyless brain at that path (the old notes are not in it).\",\n \"argv\": [\n \"gbrain\",\n \"init\",\n \"--pglite\",\n \"--no-embedding\",\n \"--path\",\n \"{{HOME}}/mnt/external/gbrain/brain.pglite\"\n ]\n }\n ],\n \"default\": \"reconnect\",\n \"default_reason\": \"Nothing is created or overwritten; the user's existing brain comes back as soon as its drive does.\"\n }\n ],\n \"checked_at\": \"{{TIME}}\",\n \"contract_version\": 1\n}"+ }+ ]+}diff --git a/test/fixtures/cli-contract/help-baseline.json b/test/fixtures/cli-contract/help-baseline.jsonindex 3d03b4bfbb..a089671b96 100644--- a/test/fixtures/cli-contract/help-baseline.json+++ b/test/fixtures/cli-contract/help-baseline.json@@ -9,7 +9,6 @@"code-refs:stub","config:exit","config:missing_yes",- "embed:exit","files:missing_yes","files:stub","forget:stub",diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 20a458d133..384db9576e 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -2,7 +2,7 @@"golden": {"commandAgnosticConnectBranches": ["readOnlyTimeoutMs !== null",- "serveStatusEligible && !loadConfig()"+ "preConnectReason"],"commands": {"advisor": {@@ -1846,7 +1846,17 @@"transcripts": {"hasSwitchCase": true,"phase": "post-connect",- "preConnectRules": [],+ "preConnectRules": [+ {+ "condition": "command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args) && await (await import('./commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": []+ }+ ],"thinClient": "refuse","thinClientRoutedSubcommands": []},diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex c9c500fd77..ac1c17b308 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -301,6 +301,7 @@"connectors","dream","edges-backfill",+ "embed","export","extract-conversation-facts","features",diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 7fee583136..a04fead0e8 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 234360,- "stdoutSha256": "e9b7650c896d76d66c78c577e47ff8d2d72f2ac1cda7f69cf6fc7df821df2747",+ "stdoutBytes": 234393,+ "stdoutSha256": "8f7de2af4351fa1ceff0b80a2f5b61373e59aff23425909b0b42d18194b7a8b1","toolNames": ["remember","entity",@@ -6236,6 +6236,7 @@"empty_retrieval","features_auto_fix","listing_truncated",+ "local_transcripts","onboard_opportunities","source_binding_narrowed","synthesis_keyless",