Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(readiness): A7 capability readiness, config plane and probed tier
garrytanad07bce3358d
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 9237adff68..90ef8068e5 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -24,6 +24,7 @@- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.+- `src/core/readiness.ts` — capability readiness (agent operator contract A7): `ReadinessEntry {capability, state, reason, why, fix, tier, asset?, http_visible}` for embeddings, chat_llm, writeback, tool_surface, sync, harness_wiring (config tier) and worker, backup per asset, migrations, sync (probed tier); each capability's reasons are a closed exported const (`EMBEDDINGS_REASONS`, …). `configReadiness(cfg, {transport})` is synchronous and memoized per (config object, transport); its only file read is one memoized `peekLock()` (none when this process holds the lock, via `heldLockFor`), plus one process-wide gbrain-binary PATH lookup on the CLI transport only. The HTTP view drops `http_visible:false` entries and passes the rest through `redactForTransport`. `probedReadiness(engine, {cache})` never calls `getStats`/`getHealth`; 60 s cache (`createReadinessCache()` per ServeHttpContext, process-wide otherwise), single-flight, 2 s per-probe bound, stale-while-revalidate; `readinessTail` is MCP initialize's best-effort 250 ms tail. `embeddingEnablement(cfg)` is the one "turn on embeddings" fix: resolves the datastore (PGLite path, Postgres, a mount from `--brain`/`GBRAIN_BRAIN_ID`) and the column width, picks a keyed provider that fits (or asks for a key with `inputs`), and emits in-place `init --force --embedding-model … --embedding-dimensions … [--path …]` or, for a mount, `embeddings enable --brain …`; it never rebuilds a column. `exclusiveFix` turns an exclusive fix into a two-step plan (actor `user` stops the owning serve named by `lock_owner`, `then` the command) unless the command delegates to the owner. `harnessWiringEntry` builds harness-native stdio registration (absolute binary, `--surface verbs`), shared-HTTP `bootstrap harness`, or the MEMORY_VERBS install anchor, with effects and destinations disclosed. Consumers never coach on `disabled_by_choice`. Tests: `test/readiness.test.ts`, `test/readiness-http-cost.test.ts`, `test/readiness-advice-lint.test.ts` (no hand-written enablement advice outside this module; shrink-only baseline), `test/readiness-embedding-enablement.serial.test.ts` (the E2E matrix).- `src/core/secret-scan.ts` — pattern-based secret detection shared by `sources push`, bootstrap verify, the compiled-context sensitivity scan and the transcripts redactor. Detection is FORMAT-based, not prefix-only: vendor shapes (anthropic, openai, voyage, github, gitlab, slack, aws AKIA/ASIA, google, stripe, sendgrid, twilio, supabase sb_secret_/sbp_, npm, huggingface, `digitalocean` `do[opr]_v1_` + 64 hex, gbrain), JWTs, private keys (whole-text claims, below), plus four catch-alls appended LAST (`bearer` — prebuilt two-group layout so only the token is the value; `db_url_credentials` — the `scheme://user:pass@` span of database URLs, host/db kept; `url_credentials` — the same span for `http(s)` (scheme case-insensitive, `gi`), user 0–128 stopping at `:`/`/`, password 1–256 excluding whitespace, `@`, `"`, `'`, `/`, `?`, `#`, with a `validate` hook that rejects placeholder passwords (`<...>`, `${...}`, `$VAR`, all `*`, all `x`); `basic_auth` — two prebuilt case-insensitive forms, `Authorization: Basic` with a 4–2048 char value and bare `Basic` with 16–2048, both with a hard right edge and a `validate` that requires the value to base64-decode to printable ASCII containing `:`; it is NOT in the bearer family, so it joins neither the echo dictionary nor `secret:bearer`). The pattern contract: `CorePattern` carries optional `flags` (default `'g'`), `precheck`, `validate(value)` (O(value), run on the whole match before the claim and the union split; a rejected match is not re-tried from inside) and `since` (the gbrain version that added or last changed the rule; `SECURITY_WAVE_SINCE` = `0.60.31.0` on `digitalocean`, `url_credentials`, `basic_auth` and `private_key_pem`, kept in step with the release that ships a rule change). Compiled patterns keep group 1 = anchor, group 2 = value. `patternSince(pattern)` reads the map; every finding of such a pattern carries `SecretFinding.since`, which the push and bootstrap refusals render. Fixed-length shapes carry a trailing negative lookahead. Per-line claimed-span dedupe is first-wins for ATTRIBUTION (order matters: `Bearer <vendor key>` keeps the vendor name, a fully covered later span is skipped) but coverage is the UNION: every unclaimed slice of a later overlapping span is claimed as a hit of the later pattern (own value, own fingerprint), so a database URL whose username is a vendor-shaped id still loses its password. The opt-in `high_entropy_assignment` rule (`ScanOpts.highEntropy`) requires a 12+ char value that contains a digit and a non-digit AND clears 3.5 bits/char on the bias-corrected (Miller-Madow) estimate `correctedEntropy`, since raw per-character entropy is capped at log2(n) and rejected most random 12-16 char secrets. It is two compiled patterns sharing the name: QUOTED (after `"` or `'`, any run of non-quote, non-whitespace characters) and UNQUOTED (the legacy `[A-Za-z0-9+/_=-]` class plus `!#$%*@^~.?<>`; never `&`, `()[]{}`, `:`, `,` or `;`, so query strings, calls and SQL `SET` lists stay intact, and a password carrying `,`/`;` matches only quoted; the last character excludes `.?!`, so a sentence's full stop is not claimed). Its `validate` rejects values that start with `scheme://`, `./`, `~/`, `${`, `$(` or `<REDACTED:`, dotted identifier paths (`process.env.X`) and `/`-paths holding a character outside the legacy class. Consumers with it on: retrieval output, transcript ingest, hooks and the hook heartbeat, the atoms drain, `embed-facts.ts` error text and the context-engine relay re-scan. Off: the push gate, bootstrap verify/repo and the compiled-context sensitivity scan. Own minimal allowlist + `<ws>/.gbrain-scan-allow` per-finding overrides — deliberately NOT the repo's `.gitleaks.toml` (a public-repo CI fixture policy). Deliberately NOT patterns: `sb_publishable_`, Supabase project refs (identifiers, not credentials). Never spell a literal database or `http(s)` URL with userinfo, or any credential, in this file's comments or in fixtures (assemble test values at runtime; `scripts/check-pg-url-redaction.sh` greps `src/` for every `db_url_credentials` scheme). Long lines are scanned in full (no length cap — a secret on a 1 MB minified line must still redact); what keeps that linear is bounded quantifiers on every shape whose value class could otherwise run to end-of-line — `db_url_credentials` (user ≤128 stopping at `:`/`/`; password 1–256 stopping only at whitespace, `@` and the string delimiters `"`/`'`, so unescaped `/ { } < > | ^ \` and backtick passwords redact), `jwt` (prebuilt so its boundary excludes `-` as well as `_`; segments ≤4096), `high_entropy_assignment` (≤64 identifier chars after the keyword, value ≤4096), `url_credentials` (user ≤128, password ≤256), `basic_auth` (value ≤2048, so its decode is constant work) and the private-key walks (below) — plus a per-pattern `precheck` substring gate on the catch-alls (`@` for both URL patterns; `earer`/`EARER`, since an all-caps `BEARER` scheme is accepted; a case-insensitive `basic`), a carried next-newline position in `scanPemBlocks` (sticky -1, so the header-line count is O(text) even when thousands of hits sit ahead of a newline-free multi-megabyte tail), a lazily-allocated per-line claimed-char bitmap behind the first-wins dedupe (O(value) per hit), and a windowed `buildPreview` (whole line ≤160 chars; otherwise hit−40…+80, edges snapped outward to whole spans, every claimed span in the window spliced by position, so a preview never carries a sibling secret or a fragment). `redactFindings` (= `planRedaction` + `applyRedaction`) rebuilds the text by SPAN-SPLICE in one O(text + hits) pass over the claimed spans, and fills the UNCLAIMED gaps with a bounded echo pass: the values claimed by `bearer` and `high_entropy_assignment` form an echo dictionary (value → pattern; floors `ECHO_MIN_CHARS_BEARER` = 20 / `ECHO_MIN_CHARS_ENTROPY` = 12, values ≤ `ECHO_MAX_VALUE_CHARS` = 512, the first `ECHO_MAX_UNIQUE` = 64 unique values in claim order across BOTH patterns — a value past either cap is redacted at its claim, its echoes are the accepted miss), matched by a streaming merge over the ORIGINAL text — per value, the next occurrence at or beyond the emit cursor (`indexOf` resuming at the cursor, re-sought only once the cursor passes it), leftmost-longest at each step, emitted incrementally into the unclaimed gaps — so retained state is O(values) however long the text is (occurrences are never collected into a list: a repetitive tail against 64 short claimed values meant millions of candidate objects and hundreds of MB of RSS for 64 findings, ahead of message truncation) (never an alternation RegExp — O(text × Σ|values|) on prefix-sharing values; never over emitted tokens, so a value spelling a pattern name cannot nest). Echoes add no findings. `planRedaction` feeds a caller-supplied shared map (`RedactOpts.echoValues`) and `applyRedaction` reads it at apply time, so a multi-field document scrubs an echo in one field of a value claimed in another. Every other pattern redacts exactly what `scanText` reports (a value embedded past its boundary is left as-is; vendor shapes re-match on their own). PRIVATE KEYS: `pemClaims` finds `BEGIN`/`END … PRIVATE KEY` fences in two global passes and merges them in text order. BLOCK: a BEGIN whose next fence is an END within `PEM_BODY_MAX_CHARS` (16384) is claimed header through END; a block never swallows a later BEGIN. FORWARD (BEGIN with no END in view): the header plus the body lines that follow; a header followed by no body line (a marker quoted in prose) is claimed alone. BACKWARD (END with no BEGIN in view): the body lines before the fence plus the fence; an END with no body line before it is no claim. A body line is a whole-line base64 run (`A-Za-z0-9+/=`) indented by up to 16 spaces/tabs; line ends are `\n`, `\r\n` or the literal JSON escapes; interior lines are 16–128 chars, the line next to a fence and a partial line at a cut 1–128; optional RFC 1421 `Proc-Type:`/`DEK-Info:` lines and one blank line may follow BEGIN; a line with anything else, or a run over 128 chars, ends the body. Total claimed body stays within `PEM_BODY_MAX_CHARS`. Each walk stops at the neighbouring fence or the previous claim, so the pass is linear (20k unterminated BEGINs, 20k END-only fences and 1 MB of base64 lines are perf-pinned). Per-line hits that fall wholly inside a key claim are dropped (one key, one finding). A FORWARD claim's finding also carries `legacyFingerprint`, the header-only fingerprint earlier releases reported, so `workspace-push.ts` can name a stale allowlist entry; a truncated key's fingerprint covers its body and therefore depends on where the text was cut, so it is not a stable allowlist key. `privateKeySpans(text)` exports the same claims as sorted, disjoint `{start, end}` spans. Accepted misses: body on the header's own line, space-joined single-line keys, blockquoted (`> `) keys, base64 runs over 128 chars, body past 16384 chars, `http(s)` passwords containing a literal `/`, `?` or `#`, Basic values over 2048 chars, digitless assignment values, dotted passwords whose every segment starts with a letter, and unquoted passwords containing `,` or `;`. False-positive budget: `scripts/secret-scan-fp-budget.ts` diffs findings against a base ref's scanner (`--base`, default `origin/master`) (`--dir <brain>` reports per-pattern counts only, never content) and `test/secret-scan-fp-budget.test.ts` pins a synthetic brain-like fixture (zero findings on its non-secret part in both modes, every planted secret redacted). Shape tests: `test/secret-scan-credential-shapes.test.ts`, `test/secret-scan-private-key-spans.test.ts`. Perf pins: `test/secret-scan-perf.test.ts`. Retrieval output is another consumer of its canonical scanner; that output boundary does not sanitize internal evaluation/provider inputs.- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch. `formatSensitivityDrop(drop, workspaceRoot)` renders the one content-free stderr line `gbrain compile-context` prints per dropped entry: reason `sensitivity_scan`, the pattern family, the fingerprint and the absolute `.gbrain-scan-allow` path, never the value (`test/sensitivity-scan.test.ts`).diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 52011d6e06..751ac2d7b7 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -81,9 +81,7 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },{ path: 'src/core/consent.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (C1/C2 command handlers) land on the collector' },- { path: 'src/core/interaction.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (A5 prompt shims, C5 readers) land on the collector' },{ path: 'src/core/ops/callable.ts', reason: 'held: agent operator wave A0 freeze; tools/list + dispatch wiring lands in A2 on the collector' },- { path: 'src/core/readiness.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (E/F readiness producers) land on the collector' },{ path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },];diff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 9f3185387e..b394a81e1f 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -1414,6 +1414,9 @@"test/ranking-inversion-895.test.ts": 331,"test/rate-leases-uncapped.test.ts": 586,"test/rate-leases.test.ts": 292,+ "test/readiness-advice-lint.test.ts": 400,+ "test/readiness-http-cost.test.ts": 3000,+ "test/readiness.test.ts": 600,"test/real-home-guard-preload.test.ts": 516,"test/recall-budget-policy-thin-cli.test.ts": 15766,"test/recall-budget-policy-transports.test.ts": 36133,diff --git a/src/core/readiness.ts b/src/core/readiness.tsindex 2f81f78de7..7d255db14f 100644--- a/src/core/readiness.ts+++ b/src/core/readiness.ts@@ -2,16 +2,45 @@* Capability readiness (agent operator contract v1, A7): one place that says* what this install can do, why not, and the fix. Two tiers:*- * - config plane (`configReadiness`): synchronous, memoized, in-memory config- * only; the one file read allowed is a memoized `peekLock()` for lock_owner.- * Used by MCP initialize, whoami and write receipts.- * - probed tier (`probedReadiness`): worker, backup, migrations; bounded,- * cached, never `getStats`/`getHealth`. Used by doctor and+ * - config plane (`configReadiness`): synchronous, memoized per (config+ * object, transport), in-memory config only. The one file read it allows is+ * a memoized `peekLock()` for `lock_owner` (none when this process holds the+ * lock itself). Used by MCP initialize, whoami and write receipts. On the+ * CLI transport `harness_wiring` additionally resolves the absolute gbrain+ * binary once per process (a PATH lookup); stdio and http never do.+ * - probed tier (`probedReadiness`): worker, backup (per asset), migrations,+ * sync applicability; 60 s cache, single-flight, 2 s per-probe bound,+ * stale-while-revalidate; never `getStats`/`getHealth`. Used by doctor and* `gbrain://capabilities`.+ *+ * Consumer rule: never coach on `disabled_by_choice` (e.g. `init+ * --no-embedding`). Those entries still carry the enable command as `fix` so+ * doctor can show it as information, but notices and nudges must stay silent+ * (Lanes E/F).+ *+ * Exclusive fixes (they need the brain's single-writer lock) go through+ * `exclusiveFix`: commands that delegate to a running owner stay one step;+ * everything else becomes a two-step plan whose first step (actor `user`)+ * stops the owning serve named by `lock_owner`.*/import type { GBrainConfig } from './config.ts';+import { gbrainPath } from './config.ts';import type { BrainEngine } from './engine.ts';-import type { Action, Transport } from './agent-output.ts';+import { redactForTransport, type Action, type ActionInput, type Effect, type Transport } from './agent-output.ts';+import { detectCapabilities } from './capability.ts';+import { embeddingProviderConfigured } from './brain-score-recommendations.ts';+import { isEngineDegraded } from './degraded-marker.ts';+import { heldLockFor, peekLock, type LockPeekResult } from './pglite-lock.ts';+import { listRecipes, RECIPES } from './ai/recipes/index.ts';+import type { Recipe } from './ai/types.ts';+import { mergedProviderEnv } from './ai/provider-env.ts';+import { resolveSchemaEmbeddingDim } from './embedding-dim-check.ts';+import { DEFAULT_EMBEDDING_DIMENSIONS, NEW_INSTALL_DEFAULT_EMBEDDING_MODEL } from './ai/defaults.ts';+import { getCliOptions, parseGlobalFlags } from './cli-options.ts';+import { validateMountId } from './brain-registry.ts';+import { agentProcessMarker } from './interaction.ts';+import { resolveGbrainBin } from './gbrain-bin.ts';+import { resolveWritebackConfigFromFile } from './facts/writeback-config.ts';export type ReadinessState = 'ok' | 'disabled_by_choice' | 'not_applicable' | 'missing' | 'degraded' | 'unknown';export type CapabilityId =@@ -21,7 +50,7 @@ export type CapabilityId =export interface ReadinessEntry {capability: CapabilityId;state: ReadinessState;- /** Closed vocabulary per capability. */+ /** Closed vocabulary per capability (the `*_REASONS` consts below). */reason: string;why: string;fix?: Action;@@ -41,23 +70,635 @@ export interface ReadinessCache {set(key: string, value: { at: number; value: ReadinessEntry[] }): void;}-export function configReadiness(cfg: GBrainConfig, ctx: { transport: Transport }): ConfigReadiness {- void cfg; void ctx;- return { entries: [], lock_owner: null };+// ── closed reason vocabularies ─────────────────────────────────────────────++export const EMBEDDINGS_REASONS = [+ 'configured', 'embedding_disabled', 'not_configured', 'key_missing', 'unknown_model', 'remote_brain',+] as const;+export const CHAT_LLM_REASONS = ['configured', 'not_configured', 'remote_brain'] as const;+export const WORKER_REASONS = [+ 'worker_running', 'no_pending_jobs', 'no_worker', 'engine_unreachable', 'probe_failed', 'probe_timeout',+] as const;+export const WRITEBACK_REASONS = ['enabled', 'off_by_choice', 'not_configured', 'invalid_mode', 'remote_brain'] as const;+export const BACKUP_REASONS = [+ 'verified', 'covered', 'no_remote', 'unpushed', 'dirty', 'failing', 'unverified', 'info',+ 'engine_unreachable', 'probe_failed', 'probe_timeout',+] as const;+export const TOOL_SURFACE_REASONS = ['surface_full', 'surface_starter', 'surface_verbs', 'remote_brain'] as const;+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;+export const HARNESS_WIRING_REASONS = [+ 'wired_running', 'registration_unverified', 'http_serve_running', 'multiple_sessions', 'multiple_harnesses',+ 'no_harness_detected', 'binary_unresolved', 'remote_transport',+] as const;++const VERIFY = (check: string) => ({ argv: ['gbrain', 'doctor', '--only', check, '--json'] });+const ENABLEMENT_DOCS = 'docs/guides/search-modes.md';++// ── brain axis (in-memory only) ────────────────────────────────────────────++/** `--brain` flag, then GBRAIN_BRAIN_ID; the `.gbrain-mount` dotfile walk is not read on the config plane. */+function brainIdInMemory(): string {+ const raw = getCliOptions().brain ?? process.env.GBRAIN_BRAIN_ID ?? 'host';+ if (!raw || raw === 'host') return 'host';+ try { return validateMountId(raw, '--brain value'); } catch { return 'host'; }}-export async function probedReadiness(engine: BrainEngine, opts: { cache?: ReadinessCache } = {}): Promise<ReadinessEntry[]> {- void engine; void opts;- return [];+// ── embeddings ─────────────────────────────────────────────────────────────++interface EmbeddingChoice { recipe: Recipe; model: string }++function keyedEmbeddingRecipes(): Recipe[] {+ const canonical = NEW_INSTALL_DEFAULT_EMBEDDING_MODEL.split(':')[0];+ const keyed = listRecipes().filter(r => {+ const tp = r.touchpoints.embedding as { models?: string[]; user_provided_models?: boolean } | undefined;+ return !!tp?.models?.length && !tp.user_provided_models && (r.auth_env?.required?.length ?? 0) > 0;+ });+ return [...keyed.filter(r => r.id === canonical), ...keyed.filter(r => r.id !== canonical)];+}++function recipeKeyed(recipe: Recipe, env: Record<string, string>): boolean {+ return (recipe.auth_env?.required ?? []).every(k => !!env[k]);+}++/** The recipe's default model if it can produce `width`-dimensional vectors, else its first model that can. */+function modelForWidth(recipe: Recipe, width: number): string | null {+ const tp = recipe.touchpoints.embedding as { models: string[]; default_model?: string };+ const ordered = [tp.default_model, ...tp.models].filter((m): m is string => !!m);+ for (const model of ordered) {+ if (resolveSchemaEmbeddingDim({ embedding_model: `${recipe.id}:${model}`, embedding_dimensions: width }).ok) return model;+ }+ return null;+}++function firstChoice(recipes: Recipe[], width: number): EmbeddingChoice | null {+ for (const recipe of recipes) {+ const model = modelForWidth(recipe, width);+ if (model) return { recipe, model };+ }+ return null;+}++function providerLabel(recipe: Recipe): string {+ return recipe.name ?? recipe.id;+}++/** Provider keys `gbrain config set` stores on the file plane (src/commands/config.ts FILE_PLANE_API_KEYS). */+const FILE_PLANE_KEY_ENVS: ReadonlySet<string> = new Set([+ 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY', 'VOYAGE_API_KEY', 'DASHSCOPE_API_KEY',+ 'DEEPSEEK_API_KEY', 'LITELLM_API_KEY', 'TOGETHER_API_KEY', 'GOOGLE_API_KEY', 'AZURE_OPENAI_API_KEY',+]);++function keyHow(name: string): string {+ return FILE_PLANE_KEY_ENVS.has(name)+ ? `store it with \`gbrain config set ${name.toLowerCase()} <key>\` (every gbrain process reads it), or export ${name} in the environment of every gbrain process`+ : `export ${name}=<key> in the environment of every gbrain process, including the one your agent harness starts`;+}++function keyInput(recipe: Recipe): ActionInput[] {+ return (recipe.auth_env?.required ?? []).map(name => ({+ name,+ how: `Ask the user for an API key for ${providerLabel(recipe)}; ${keyHow(name)}. Then run the command.`,+ }));+}++/** The datastore the enable command must target, resolved before any argv is built. */+function enableArgv(cfg: GBrainConfig, model: string, width: number): string[] {+ const brainId = brainIdInMemory();+ if (brainId !== 'host') {+ return ['gbrain', 'embeddings', 'enable', '--brain', brainId, '--embedding-model', model, '--embedding-dimensions', String(width)];+ }+ const base = ['gbrain', 'init', '--force', '--embedding-model', model, '--embedding-dimensions', String(width)];+ if (cfg.engine === 'postgres') return base;+ return [...base, '--path', cfg.database_path ?? gbrainPath('brain.pglite')];+}++function datastoreLabel(cfg: GBrainConfig): string {+ const brainId = brainIdInMemory();+ if (brainId !== 'host') return `mounted brain '${brainId}' (the embedding model is set host-wide, so the host brain uses it too)`;+ return cfg.engine === 'postgres' ? 'this Postgres brain' : `the PGLite brain at ${cfg.database_path ?? gbrainPath('brain.pglite')}`;+}++const KEPT = 'Pages, facts and keyword search are kept; existing chunks and facts are queued for vectors, which `gbrain embed --stale` (or the next maintenance cycle) fills.';++function readyEnablement(cfg: GBrainConfig, choice: EmbeddingChoice, width: number): Action {+ const model = `${choice.recipe.id}:${choice.model}`;+ const label = providerLabel(choice.recipe);+ return {+ argv: enableArgv(cfg, model, width),+ consent: ['credentials', 'paid'],+ actor: 'agent',+ why: `Embeddings are off, so search is keyword-only. This turns on ${model} (${width}d) for ${datastoreLabel(cfg)} using the ${label} key already configured. ${KEPT}`,+ user_message: `I can turn on semantic search with ${label} (${model}). It uses your API key and costs a little per page embedded; your notes and saved facts stay as they are. OK to run it?`,+ verify: VERIFY('embeddings'),+ docs: ENABLEMENT_DOCS,+ requires_exclusive: true,+ };}+function keyNeededEnablement(cfg: GBrainConfig, choice: EmbeddingChoice, width: number, note: string): Action {+ const model = `${choice.recipe.id}:${choice.model}`;+ const label = providerLabel(choice.recipe);+ return {+ argv: enableArgv(cfg, model, width),+ consent: ['credentials', 'paid'],+ actor: 'user',+ why: `Embeddings are off, so search is keyword-only, and no configured embedding key fits this brain.${note} Once the key is set this turns on ${model} (${width}d) for ${datastoreLabel(cfg)}. ${KEPT}`,+ user_message: `Semantic search needs an embedding API key. ${label} works with this brain; if you add a key (${(choice.recipe.auth_env?.required ?? []).join(', ')}), I can turn it on. Embedding costs a little per page; your notes and facts stay as they are.`,+ verify: VERIFY('embeddings'),+ docs: ENABLEMENT_DOCS,+ requires_exclusive: true,+ inputs: keyInput(choice.recipe),+ };+}++/** `cfg.embedding_model` as an explicit preference, when it names a known embedding model that fits `width`. */+function preferredChoice(cfg: GBrainConfig, width: number): EmbeddingChoice | null {+ const model = cfg.embedding_model?.trim();+ if (!model?.includes(':')) return null;+ const recipe = RECIPES.get(model.slice(0, model.indexOf(':')));+ if (!recipe?.touchpoints.embedding) return null;+ if (!resolveSchemaEmbeddingDim({ embedding_model: model, embedding_dimensions: width }).ok) return null;+ return { recipe, model: model.slice(model.indexOf(':') + 1) };+}++/**+ * The one "turn on embeddings" fix. Resolves the configured datastore (PGLite+ * path, Postgres, or a mounted brain via `--brain`/GBRAIN_BRAIN_ID) and the+ * brain's vector width (`embedding_dimensions`, default 1024), then picks a+ * model: `cfg.embedding_model` when set and it fits, else a keyed provider+ * that can produce that width. No key → the fix asks the user for one. A+ * width no keyed provider can produce → the fix names a provider that can+ * (or the migration preview when none can); nothing is rebuilt.+ */export function embeddingEnablement(cfg: GBrainConfig): Action {- void cfg;+ const env = mergedProviderEnv(cfg);+ const width = cfg.embedding_dimensions ?? DEFAULT_EMBEDDING_DIMENSIONS;+ const preferred = preferredChoice(cfg, width);+ if (preferred) {+ return recipeKeyed(preferred.recipe, env) ? readyEnablement(cfg, preferred, width) : keyNeededEnablement(cfg, preferred, width, '');+ }+ const recipes = keyedEmbeddingRecipes();+ const ready = recipes.filter(r => recipeKeyed(r, env));+ const pick = firstChoice(ready, width);+ if (pick) return readyEnablement(cfg, pick, width);+ const ask = firstChoice(recipes, width);+ if (!ask) {+ return {+ argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'],+ consent: [],+ actor: 'agent',+ why: `This brain's vector column is ${width}-dimensional and no keyed embedding provider produces ${width}d vectors. Changing the width is a re-embed through \`gbrain migrate embeddings --to <provider:model> --dim <N> --dry-run\` (preview first; pages and facts are kept). Read the status, then ask the user which provider to use.`,+ verify: VERIFY('embeddings'),+ docs: 'docs/guides/embedding-migration.md',+ requires_exclusive: false,+ };+ }+ const note = ready.length > 0+ ? ` The configured ${ready.map(providerLabel).join(', ')} key${ready.length > 1 ? 's' : ''} cannot produce this brain's ${width}d vectors without rebuilding the vector column, so this uses ${providerLabel(ask.recipe)}, which can.`+ : '';+ return keyNeededEnablement(cfg, ask, width, note);+}++function embeddingsEntry(cfg: GBrainConfig): ReadinessEntry {+ const base = { capability: 'embeddings' as const, tier: 'config' as const, http_visible: true };+ if (cfg.remote_mcp) return { ...base, state: 'not_applicable', reason: 'remote_brain', why: 'Embeddings are configured on the remote brain host this thin client talks to.' };+ if (cfg.embedding_disabled) {+ return { ...base, state: 'disabled_by_choice', reason: 'embedding_disabled', why: 'This brain was set up keyless (`--no-embedding`): search is keyword-only by choice.', fix: embeddingEnablement(cfg) };+ }+ const model = cfg.embedding_model?.trim();+ if (!model) return { ...base, state: 'missing', reason: 'not_configured', why: 'No embedding model is configured, so search is keyword-only.', fix: embeddingEnablement(cfg) };+ const providerId = model.includes(':') ? model.slice(0, model.indexOf(':')) : model;+ const recipe = RECIPES.get(providerId);+ if (!recipe?.touchpoints.embedding) {+ return { ...base, state: 'degraded', reason: 'unknown_model', why: `The configured embedding model '${model}' is not a known embedding provider, so vectors cannot be computed.`, fix: embeddingEnablement({ ...cfg, embedding_model: undefined }) };+ }+ const env = mergedProviderEnv(cfg);+ if (embeddingProviderConfigured(model, k => !!env[k]) && detectCapabilities({ config: cfg }).embeddings.available) {+ return { ...base, state: 'ok', reason: 'configured', why: `Embeddings run on ${model}.` };+ }+ const keys = recipe.auth_env?.required ?? [];+ return {+ ...base, state: 'degraded', reason: 'key_missing',+ why: `Embeddings are configured for ${model} but ${keys.join(', ')} is not set, so new content gets no vectors and search falls back to keyword-only.`,+ fix: {+ consent: ['credentials'], actor: 'user', requires_exclusive: false,+ why: `Provide ${keys.join(', ')}: ${keys.map(keyHow).join('; ')}. Queued chunks then embed on the next \`gbrain embed --stale\`.`,+ user_message: `Semantic search is configured for ${providerLabel(recipe)} but its API key is missing. Can you add it?`,+ inputs: keyInput(recipe), verify: VERIFY('embeddings'),+ },+ };+}++// ── chat, writeback, tool surface ──────────────────────────────────────────++function chatEntry(cfg: GBrainConfig): ReadinessEntry {+ const base = { capability: 'chat_llm' as const, tier: 'config' as const, http_visible: true };+ if (cfg.remote_mcp) return { ...base, state: 'not_applicable', reason: 'remote_brain', why: 'Chat models run on the remote brain host.' };+ const caps = detectCapabilities({ config: cfg });+ if (caps.extraction.available) return { ...base, state: 'ok', reason: 'configured', why: `Automatic fact extraction and synthesis run on ${caps.extraction.provider}.` };+ return {+ ...base, state: 'missing', reason: 'not_configured',+ why: 'No chat model key is configured: memory comes from agent-authored facts and explicit writes; automatic extraction, enrichment and synthesis are off.',+ fix: {+ argv: ['gbrain', 'providers', 'list'], consent: ['credentials', 'paid'], actor: 'user', requires_exclusive: false,+ why: 'Adding one chat provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY) turns on automatic extraction; `gbrain providers list` shows which keys each provider needs.',+ user_message: 'Automatic fact extraction needs a chat model API key (Anthropic or OpenAI, for example). Want to add one? It costs a little per page processed.',+ verify: VERIFY('facts_extraction_health'),+ },+ };+}++function writebackEntry(cfg: GBrainConfig): ReadinessEntry {+ const base = { capability: 'writeback' as const, tier: 'config' as const, http_visible: false };+ if (cfg.remote_mcp) return { ...base, state: 'not_applicable', reason: 'remote_brain', why: 'Ambient writeback is configured on the remote brain host.' };+ const wb = resolveWritebackConfigFromFile(cfg);+ if (wb.enabled) return { ...base, state: 'ok', reason: 'enabled', why: `Ambient memory writeback is on (${wb.mode}).` };+ const enable: Action = {+ argv: ['gbrain', 'config', 'set', 'memory.auto_writeback', 'salient'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'Ambient writeback lets the agent save salient facts without being asked; it is opt-in, so the user decides.',+ user_message: 'Should I save important facts from our conversations automatically (ambient writeback, "salient" mode)? You can turn it off any time.',+ verify: { argv: ['gbrain', 'config', 'get', 'memory.auto_writeback'] }, docs: 'docs/guides/ambient-writeback.md',+ };+ if (!wb.mode_valid) return { ...base, state: 'degraded', reason: 'invalid_mode', why: `memory.auto_writeback is set to an unrecognized value, so writeback is off.`, fix: enable };+ if (wb.raw_mode === 'off') return { ...base, state: 'disabled_by_choice', reason: 'off_by_choice', why: 'Ambient memory writeback is turned off by choice.', fix: enable };+ return { ...base, state: 'missing', reason: 'not_configured', why: 'Ambient memory writeback has not been chosen; facts are saved only when asked.', fix: enable };+}++function toolSurfaceEntry(cfg: GBrainConfig): ReadinessEntry {+ const base = { capability: 'tool_surface' as const, tier: 'config' as const, http_visible: true, state: 'ok' as const };+ if (cfg.remote_mcp) return { ...base, state: 'not_applicable', reason: 'remote_brain', why: 'The tool surface is set by the remote brain host.' };+ const surface = cfg.mcp_surface ?? 'full';+ const why = surface === 'full' ? 'gbrain serve exposes every operation by default.'+ : surface === 'starter' ? 'gbrain serve defaults to the starter surface (the daily-driver tool set); `--surface full` exposes everything.'+ : 'gbrain serve defaults to the seven memory verbs; `--surface full` exposes everything.';+ return { ...base, reason: `surface_${surface}`, why };+}++function syncConfigEntry(cfg: GBrainConfig): ReadinessEntry | null {+ if (!cfg.remote_mcp) return null;+ return { capability: 'sync', tier: 'config', http_visible: false, state: 'not_applicable', reason: 'remote_brain', why: 'Sync runs on the remote brain host.' };+}++// ── lock ownership + exclusive fixes ───────────────────────────────────────++/** CLI commands that route themselves through a live owner (`runDelegatedCliOperation` and the persistence delegates). */+const OWNER_DELEGATED_COMMANDS: ReadonlySet<string> = new Set(['reindex-code', 'sync']);++/**+ * Wrap an exclusive fix for the current lock owner. No owner, or a command+ * that delegates to the owner → unchanged. Otherwise a two-step plan: step one+ * (actor `user`) stops the owning serve, `then` the original command.+ */+export function exclusiveFix(action: Action, lockOwner: LockOwner | null): Action {+ if (!action.requires_exclusive || !lockOwner) return action;+ if (action.argv?.[0] === 'gbrain' && OWNER_DELEGATED_COMMANDS.has(action.argv[1] ?? '')) return action;+ const who = lockOwner.transport === 'http'+ ? `the shared \`gbrain serve --http\` (PID ${lockOwner.pid})`+ : `the stdio \`gbrain serve\` an agent session started (PID ${lockOwner.pid})`;+ const restart = lockOwner.transport === 'http'+ ? 'Start `gbrain serve --http` again afterwards.'+ : 'Reopen the agent session afterwards so it restarts its gbrain server.';return {- argv: ['gbrain', 'doctor', '--json'],+ argv: ['kill', String(lockOwner.pid)],consent: [],- actor: 'agent',- why: 'Embeddings are not configured on this brain.',+ actor: 'user',+ why: `${who} holds this brain's single-writer lock and the next command needs it exclusively. Stop that server first (quit the session or run this), then run the next step. ${restart}`,+ user_message: `This needs gbrain's database to itself. Please stop ${who}, then I'll run the next step. ${restart}`,requires_exclusive: false,+ then: action,+ };+}++let peekOverride: ((dataDir: string) => LockPeekResult) | null = null;+/** Test seam: count or fake the config plane's one lock read (null restores `peekLock`). */+export function __setLockPeekForTests(fn: ((dataDir: string) => LockPeekResult) | null): void { peekOverride = fn; }++function isServeProcess(): boolean {+ return parseGlobalFlags(process.argv.slice(2)).rest[0] === 'serve';+}++function lockOwnerFor(cfg: GBrainConfig): LockOwner | null {+ if (cfg.engine !== 'pglite' || cfg.remote_mcp || cfg.database_url) return null;+ const dataDir = cfg.database_path ?? gbrainPath('brain.pglite');+ const self = heldLockFor(dataDir);+ if (self) {+ if (!isServeProcess()) return null;+ return { pid: process.pid, transport: process.argv.includes('--http') ? 'http' : 'stdio',+ ...(self.acquiredAt ? { started_at: new Date(self.acquiredAt).toISOString() } : {}), is_self: true };+ }+ const peek = (peekOverride ?? peekLock)(dataDir);+ if (!peek.held || !peek.isServe || peek.pid === undefined) return null;+ return { pid: peek.pid, transport: peek.http ? 'http' : 'stdio',+ ...(peek.acquiredAt ? { started_at: new Date(peek.acquiredAt).toISOString() } : {}), is_self: peek.pid === process.pid };+}++// ── harness wiring ─────────────────────────────────────────────────────────++export type ReadinessHarness = 'claude-code' | 'codex' | 'opencode';+export interface HarnessWiringInput {+ transport: Transport;+ /** Harnesses detected on this machine (config plane: from process-scoped agent markers). */+ harnesses: readonly ReadinessHarness[];+ lockOwner: LockOwner | null;+ /** Absolute gbrain binary; null when it cannot be resolved (never registered bare). */+ gbrainBin: string | null;+}++const HARNESS_LABEL: Record<ReadinessHarness, string> = { 'claude-code': 'Claude Code', codex: 'Codex', opencode: 'opencode' };+const HARNESS_DESTINATION: Record<ReadinessHarness, string> = {+ 'claude-code': 'the Claude Code MCP config (~/.claude.json)',+ codex: 'the Codex config (~/.codex/config.toml)',+ opencode: 'the opencode config (opencode.json)',+};+const MEMORY_VERBS_INSTALL = 'docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart';++function stdioRegistration(h: ReadinessHarness, bin: string): Action {+ const argv = h === 'claude-code' ? ['claude', 'mcp', 'add', 'gbrain', '--', bin, 'serve', '--surface', 'verbs']+ : h === 'codex' ? ['codex', 'mcp', 'add', 'gbrain', '--', bin, 'serve', '--surface', 'verbs']+ : ['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks'];+ const hooks = h === 'opencode' ? ' No lifecycle hooks are installed (--no-hooks); it must run inside an initialized agent workspace.' : ' No hooks, tool pre-approvals or tokens are added.';+ return {+ argv, consent: ['persistent_install'], actor: 'agent', requires_exclusive: false,+ why: `Registers gbrain as a stdio MCP server (${bin} serve --surface verbs, the seven memory verbs) in ${HARNESS_DESTINATION[h]}, so new ${HARNESS_LABEL[h]} sessions get memory tools.${hooks}`,+ user_message: `I'd like to add gbrain's memory tools to ${HARNESS_LABEL[h]} by writing one MCP server entry to ${HARNESS_DESTINATION[h]}. OK?`,+ verify: VERIFY('harness_wiring'), docs: MEMORY_VERBS_INSTALL,+ };+}++function sharedHttpWiring(selector: ReadinessHarness | 'all'): Action {+ const names = selector === 'all' ? 'each detected harness' : HARNESS_LABEL[selector];+ return {+ argv: ['gbrain', 'bootstrap', 'harness', '--harness', selector, '--yes'],+ consent: ['persistent_install', 'credentials'], actor: 'agent', requires_exclusive: false,+ why: `Wires ${names} to the shared \`gbrain serve --http\` on this machine (it must be running): mints one bearer token per harness (scopes read+write), writes an HTTP MCP entry with that token to the harness config (Claude Code: ~/.claude.json plus a permissions.allow 'mcp__gbrain' pre-approval and lifecycle hooks in ~/.claude/settings.json; Codex: ~/.codex/config.toml; opencode: its user config), so several sessions share one brain without lock contention.`,+ user_message: `To let several agent sessions share this brain, I'd connect ${names} to the local gbrain HTTP server. That stores an access token in the harness config, pre-approves gbrain's tools and installs its session hooks. OK?`,+ verify: VERIFY('harness_wiring'), docs: 'docs/guides/remote-mcp.md',};}++/** `harness_wiring` for a concrete detection result. Doctor (Lane E) passes filesystem-detected harnesses. */+export function harnessWiringEntry(input: HarnessWiringInput): ReadinessEntry {+ const base = { capability: 'harness_wiring' as const, tier: 'config' as const, http_visible: false };+ if (input.transport === 'stdio') return { ...base, state: 'ok', reason: 'wired_running', why: 'An agent harness launched this gbrain MCP server over stdio.' };+ if (input.transport === 'http') return { ...base, state: 'not_applicable', reason: 'remote_transport', why: 'Harness wiring is a property of the brain host.' };+ const { harnesses, lockOwner } = input;+ if (harnesses.length === 0) {+ return { ...base, state: 'missing', reason: 'no_harness_detected', why: 'No agent harness was detected.',+ fix: { consent: ['persistent_install'], actor: 'user', requires_exclusive: false, docs: MEMORY_VERBS_INSTALL,+ why: 'Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw).',+ user_message: 'Which agent app should get gbrain memory? The install guide has a one-line command for each.' } };+ }+ if (lockOwner?.transport === 'http') {+ return { ...base, state: 'unknown', reason: 'http_serve_running', why: 'A shared `gbrain serve --http` is running; harnesses should connect to it instead of starting their own stdio server.', fix: sharedHttpWiring(harnesses.length > 1 ? 'all' : harnesses[0]) };+ }+ if (lockOwner && !lockOwner.is_self) {+ return { ...base, state: 'degraded', reason: 'multiple_sessions', why: `Another gbrain serve (PID ${lockOwner.pid}) holds this brain, so a second stdio server cannot open it; sessions must share one \`gbrain serve --http\`.`, fix: sharedHttpWiring(harnesses.length > 1 ? 'all' : harnesses[0]) };+ }+ if (harnesses.length > 1) {+ return { ...base, state: 'unknown', reason: 'multiple_harnesses', why: `Several harnesses are installed (${harnesses.map(h => HARNESS_LABEL[h]).join(', ')}); they share one brain through \`gbrain serve --http\`.`, fix: sharedHttpWiring('all') };+ }+ const h = harnesses[0];+ if (!input.gbrainBin) {+ return { ...base, state: 'missing', reason: 'binary_unresolved', why: 'The gbrain binary is not on PATH as an absolute path, and harness registrations never use a bare `gbrain` (GUI hosts inherit no PATH).',+ fix: { consent: ['persistent_install'], actor: 'user', requires_exclusive: false, docs: 'INSTALL_FOR_AGENTS.md',+ why: 'Install gbrain globally (`bun install -g github:garrytan/gbrain`) so `gbrain` resolves to an absolute path, then re-run readiness.' } };+ }+ return { ...base, state: 'unknown', reason: 'registration_unverified', why: `${HARNESS_LABEL[h]} is the active harness; its gbrain registration has not been verified from this process.`, fix: stdioRegistration(h, input.gbrainBin) };+}++const MARKER_HARNESS: Record<string, ReadinessHarness> = {+ CLAUDECODE: 'claude-code', CLAUDE_CODE_ENTRYPOINT: 'claude-code', CODEX_SANDBOX: 'codex', CODEX_CI: 'codex', OPENCODE: 'opencode', OPENCODE_PID: 'opencode',+};++let cachedBin: { value: string | null } | null = null;++function harnessConfigEntry(transport: Transport, lockOwner: LockOwner | null): ReadinessEntry {+ if (transport !== 'cli') return harnessWiringEntry({ transport, harnesses: [], lockOwner, gbrainBin: null });+ const marker = agentProcessMarker();+ const harness = marker ? MARKER_HARNESS[marker] : undefined;+ cachedBin ??= { value: resolveGbrainBin() };+ return harnessWiringEntry({ transport, harnesses: harness ? [harness] : [], lockOwner, gbrainBin: cachedBin.value });+}++// ── config plane ───────────────────────────────────────────────────────────++const configMemo = new WeakMap<GBrainConfig, Map<Transport, ConfigReadiness>>();+const lockMemo = new WeakMap<GBrainConfig, LockOwner | null>();++/** Forget memoized config-plane results (status-mode re-probe, config reload). */+export function resetReadinessMemo(cfg?: GBrainConfig): void {+ if (cfg) { configMemo.delete(cfg); lockMemo.delete(cfg); }+ cachedBin = null;+}++/** The HTTP view: drop `http_visible: false` entries, then one redaction pass. */+export function readinessHttpView(entries: readonly ReadinessEntry[]): ReadinessEntry[] {+ return redactForTransport(entries.filter(e => e.http_visible), 'http');+}++export function configReadiness(cfg: GBrainConfig, ctx: { transport: Transport }): ConfigReadiness {+ const memo = configMemo.get(cfg)?.get(ctx.transport);+ if (memo) return memo;+ if (!lockMemo.has(cfg)) lockMemo.set(cfg, lockOwnerFor(cfg));+ const lockOwner = lockMemo.get(cfg) ?? null;+ const entries: ReadinessEntry[] = [embeddingsEntry(cfg), chatEntry(cfg), writebackEntry(cfg), toolSurfaceEntry(cfg)];+ const sync = syncConfigEntry(cfg);+ if (sync) entries.push(sync);+ entries.push(harnessConfigEntry(ctx.transport, lockOwner));+ const result: ConfigReadiness = ctx.transport === 'http'+ ? { entries: readinessHttpView(entries), lock_owner: null }+ : { entries: entries.map(e => (e.fix ? { ...e, fix: exclusiveFix(e.fix, lockOwner) } : e)), lock_owner: lockOwner };+ const byTransport = configMemo.get(cfg) ?? new Map<Transport, ConfigReadiness>();+ byTransport.set(ctx.transport, result);+ configMemo.set(cfg, byTransport);+ return result;+}++// ── probed tier ────────────────────────────────────────────────────────────++export const PROBED_TTL_MS = 60_000;+export const PROBE_TIMEOUT_MS = 2_000;+export const INITIALIZE_TAIL_MS = 250;++class MapCache implements ReadinessCache {+ private readonly m = new Map<string, { at: number; value: ReadinessEntry[] }>();+ get(key: string) { return this.m.get(key); }+ set(key: string, value: { at: number; value: ReadinessEntry[] }) { this.m.set(key, value); }+}+/** A fresh cache (one per ServeHttpContext on HTTP). */+export function createReadinessCache(): ReadinessCache { return new MapCache(); }+const processCache = createReadinessCache();++const engineIds = new WeakMap<object, number>();+let nextEngineId = 1;+function cacheKey(engine: BrainEngine): string {+ let id = engineIds.get(engine);+ if (id === undefined) { id = nextEngineId++; engineIds.set(engine, id); }+ return `probed:${id}`;+}+const inflight = new WeakMap<ReadinessCache, Map<string, Promise<ReadinessEntry[]>>>();++type ProbeResult = ReadinessEntry | ReadinessEntry[];+type Prober = { capability: CapabilityId; run(engine: BrainEngine): Promise<ProbeResult> };++function failedEntry(capability: CapabilityId, reason: 'probe_failed' | 'probe_timeout' | 'engine_unreachable'): ReadinessEntry {+ const why = reason === 'probe_timeout' ? `The ${capability} probe did not answer within ${PROBE_TIMEOUT_MS / 1000}s.`+ : reason === 'engine_unreachable' ? 'The database is unreachable, so this was not probed.'+ : `The ${capability} probe failed.`;+ return { capability, state: 'unknown', reason, why, tier: 'probed', http_visible: false,+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Doctor reports the underlying failure.', requires_exclusive: false } };+}++async function bounded(probe: Prober, engine: BrainEngine): Promise<ReadinessEntry[]> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<'timeout'>(resolve => { timer = setTimeout(() => resolve('timeout'), PROBE_TIMEOUT_MS); });+ try {+ const out = await Promise.race([probe.run(engine), timeout]);+ if (out === 'timeout') return [failedEntry(probe.capability, 'probe_timeout')];+ return Array.isArray(out) ? out : [out];+ } catch {+ return [failedEntry(probe.capability, 'probe_failed')];+ } finally {+ clearTimeout(timer);+ }+}++async function countWaitingJobs(engine: BrainEngine): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'waiting'`);+ return Number(row?.n ?? 0);+}++const workerProbe: Prober = {+ capability: 'worker',+ async run(engine) {+ const base = { capability: 'worker' as const, tier: 'probed' as const, http_visible: false };+ const { readWorkers } = await import('./minions/worker-registry.ts');+ const live = readWorkers(() => null);+ if (live.length > 0) return { ...base, state: 'ok', reason: 'worker_running', why: `${live.length} job worker(s) are running.` };+ const waiting = await countWaitingJobs(engine);+ if (waiting === 0) return { ...base, state: 'ok', reason: 'no_pending_jobs', why: 'No job worker is running and no jobs are waiting.' };+ const pglite = engine.kind === 'pglite';+ return {+ ...base, state: 'missing', reason: 'no_worker',+ why: `${waiting} job(s) are waiting and no worker is running${pglite ? ' (PGLite has no background worker; jobs run with --follow or while a worker holds the brain)' : ''}.`,+ fix: pglite+ ? { argv: ['gbrain', 'jobs', 'work'], consent: [], actor: 'agent', requires_exclusive: true, why: 'Runs the waiting jobs in this process; stop it once the queue drains.', verify: VERIFY('queue_health') }+ : { argv: ['gbrain', 'jobs', 'supervisor', 'start'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Starts the job supervisor, which keeps a worker running for this Postgres brain.', verify: VERIFY('queue_health') },+ };+ },+};++const migrationsProbe: Prober = {+ capability: 'migrations',+ async run(engine) {+ const base = { capability: 'migrations' as const, tier: 'probed' as const, http_visible: false };+ const { LATEST_VERSION } = await import('./migrate.ts');+ const current = parseInt((await engine.getConfig('version')) || '1', 10);+ if (current >= LATEST_VERSION) return { ...base, state: 'ok', reason: 'current', why: `Schema is at v${current}.` };+ return {+ ...base, state: 'degraded', reason: 'pending',+ why: `Schema is at v${current}; v${LATEST_VERSION} is available, so newer features may refuse until migrations run.`,+ fix: { argv: ['gbrain', 'apply-migrations', '--yes', '--no-autopilot-install'], consent: [], actor: 'agent', requires_exclusive: true,+ why: 'Applies the pending schema migrations without installing background services.', verify: VERIFY('schema_version') },+ };+ },+};++const BACKUP_STATE_MAP: Record<string, { state: ReadinessState; reason: (typeof BACKUP_REASONS)[number] }> = {+ ok: { state: 'ok', reason: 'covered' }, info: { state: 'ok', reason: 'info' },+ no_remote: { state: 'degraded', reason: 'no_remote' }, unpushed: { state: 'degraded', reason: 'unpushed' },+ dirty: { state: 'degraded', reason: 'dirty' }, failing: { state: 'degraded', reason: 'failing' },+ unknown: { state: 'unknown', reason: 'unverified' },+};++function backupFix(argv: string[] | null | undefined): Action | undefined {+ if (!argv?.length) return undefined;+ const filled = argv.map(a => a.replace(/^BACKUP_DIR\//, '<BACKUP_DIR>/'));+ const egress: Effect[] = argv[1] === 'bootstrap' || (argv[1] === 'sources' && argv[2] === 'push') ? ['credentials', 'egress'] : [];+ return {+ argv: filled, consent: egress, actor: 'agent', requires_exclusive: argv[1] === 'export',+ why: 'Puts this asset under a backup that survives losing this machine.',+ ...(filled.some(a => a.includes('<BACKUP_DIR>')) ? { inputs: [{ name: 'BACKUP_DIR', how: 'Ask the user where backups should live (a directory outside the brain).' }] } : {}),+ verify: VERIFY('backup_coverage'),+ };+}++const backupProbe: Prober = {+ capability: 'backup',+ async run(engine) {+ const { getBackupStatus } = await import('./backup/coverage.ts');+ const status = await getBackupStatus(engine, { localGitProbes: false, computedBy: 'doctor' });+ return status.assets.map(a => {+ const mapped = a.state === 'ok' && a.verification?.state === 'verified' ? { state: 'ok' as const, reason: 'verified' as const } : BACKUP_STATE_MAP[a.state] ?? BACKUP_STATE_MAP.unknown;+ const fix = backupFix(a.fix_argv);+ return { capability: 'backup' as const, tier: 'probed' as const, http_visible: false, asset: `${a.kind}:${a.id}`, ...mapped,+ why: a.kind === 'db_only' ? 'DB-only pages and facts exist only in the database; git evidence does not cover them.' : `Backup state of ${a.kind} '${a.id}': ${a.state}.`,+ ...(fix ? { fix } : {}) };+ });+ },+};++const syncProbe: Prober = {+ capability: 'sync',+ async run(engine) {+ const base = { capability: 'sync' as const, tier: 'probed' as const, http_visible: false };+ const rows = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM sources WHERE NOT archived AND local_path IS NOT NULL AND local_path <> ''`);+ const n = Number(rows[0]?.n ?? 0);+ if (n === 0) return { ...base, state: 'not_applicable', reason: 'no_repo_sources', why: 'No source is bound to a local repository, so `gbrain sync` has nothing to pull; pages arrive through gbrain writes and imports.' };+ return { ...base, state: 'ok', reason: 'git_sources', why: `${n} source(s) are bound to local repositories that \`gbrain sync\` reads.` };+ },+};++const PROBERS: readonly Prober[] = [workerProbe, backupProbe, migrationsProbe, syncProbe];++async function runProbes(engine: BrainEngine): Promise<ReadinessEntry[]> {+ if (isEngineDegraded(engine)) return PROBERS.map(p => failedEntry(p.capability, 'engine_unreachable'));+ return (await Promise.all(PROBERS.map(p => bounded(p, engine)))).flat();+}++function refresh(engine: BrainEngine, cache: ReadinessCache, key: string): Promise<ReadinessEntry[]> {+ const flights = inflight.get(cache) ?? new Map<string, Promise<ReadinessEntry[]>>();+ inflight.set(cache, flights);+ const existing = flights.get(key);+ if (existing) return existing;+ const p = runProbes(engine).then(value => {+ cache.set(key, { at: Date.now(), value });+ return value;+ }).finally(() => flights.delete(key));+ flights.set(key, p);+ return p;+}++export async function probedReadiness(engine: BrainEngine, opts: { cache?: ReadinessCache } = {}): Promise<ReadinessEntry[]> {+ const cache = opts.cache ?? processCache;+ const key = cacheKey(engine);+ const hit = cache.get(key);+ if (hit && Date.now() - hit.at < PROBED_TTL_MS) return hit.value;+ const pending = refresh(engine, cache, key);+ if (hit) {+ pending.catch(() => {});+ return hit.value;+ }+ return pending;+}++/**+ * MCP initialize's readiness tail: best-effort within 250 ms; undefined on+ * throw or timeout (the probe keeps filling the cache in the background).+ */+export async function readinessTail(engine: BrainEngine, opts: { cache?: ReadinessCache; timeoutMs?: number } = {}): Promise<ReadinessEntry[] | undefined> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const timeout = new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), opts.timeoutMs ?? INITIALIZE_TAIL_MS); });+ const probe = probedReadiness(engine, { cache: opts.cache });+ probe.catch(() => {});+ return await Promise.race([probe, timeout]);+ } catch {+ return undefined;+ } finally {+ clearTimeout(timer);+ }+}diff --git a/test/readiness-http-cost.test.ts b/test/readiness-http-cost.test.tsnew file mode 100644index 0000000000..b7b5e30740--- /dev/null+++ b/test/readiness-http-cost.test.ts@@ -0,0 +1,154 @@+/**+ * A7 readiness cost contract (test/readiness-http-cost.test.ts, named in the+ * agent operator wave spec).+ *+ * Protects: MCP initialize, whoami and write receipts call the config plane on+ * every request, and doctor / `gbrain://capabilities` call the probed tier. A+ * regression that makes the config plane touch the network or re-read the+ * lock per call, or makes the probed tier call getStats/getHealth (the #5061+ * cost class), skip its cache, double-run concurrent probes, or hang past its+ * bound, fails here.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import {+ __setLockPeekForTests, configReadiness, createReadinessCache, probedReadiness, readinessTail,+ PROBED_TTL_MS, PROBE_TIMEOUT_MS, type ReadinessEntry,+} from '../src/core/readiness.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { GBrainConfig } from '../src/core/config.ts';++interface SpyEngine { engine: BrainEngine; calls: string[] }++/** An engine that records every method touched; getStats/getHealth are forbidden. */+function spyEngine(opts: { hang?: boolean; delayMs?: number } = {}): SpyEngine {+ const calls: string[] = [];+ const target: Record<string, unknown> = {+ kind: 'pglite',+ async executeRaw(sql: string) {+ calls.push('executeRaw');+ if (opts.hang) return new Promise(() => {});+ if (opts.delayMs) await new Promise(r => setTimeout(r, opts.delayMs));+ return /count\(\*\)/i.test(sql) ? [{ n: 0 }] : [];+ },+ async getConfig(key: string) {+ calls.push('getConfig');+ return key === 'version' ? String(LATEST_VERSION) : null;+ },+ };+ const engine = new Proxy(target, {+ get(t, prop) {+ if (prop === 'getStats' || prop === 'getHealth') {+ return () => { calls.push(String(prop)); throw new Error(`${String(prop)} must never be called by readiness`); };+ }+ if (typeof prop === 'string' && !(prop in t) && prop !== 'then') calls.push(`missing:${prop}`);+ return t[prop as string];+ },+ }) as unknown as BrainEngine;+ return { engine, calls };+}++afterEach(() => __setLockPeekForTests(null));++describe('config plane cost', () => {+ test('no network, one lock read across transports and repeated calls, memoized per config object', () => {+ const realFetch = globalThis.fetch;+ let fetches = 0;+ globalThis.fetch = (async () => { fetches++; throw new Error('network'); }) as unknown as typeof fetch;+ let peeks = 0;+ __setLockPeekForTests(() => { peeks++; return { held: false }; });+ try {+ const cfg = { engine: 'pglite', database_path: '/brains/cost.pglite', embedding_disabled: true } as GBrainConfig;+ const first = configReadiness(cfg, { transport: 'stdio' });+ for (let i = 0; i < 50; i++) {+ expect(configReadiness(cfg, { transport: 'stdio' })).toBe(first);+ configReadiness(cfg, { transport: 'http' });+ }+ expect(peeks).toBe(1);+ expect(fetches).toBe(0);+ configReadiness({ ...cfg }, { transport: 'stdio' });+ expect(peeks).toBe(2);+ } finally {+ globalThis.fetch = realFetch;+ }+ });++ test('Postgres and thin-client configs never read the PGLite lock', () => {+ let peeks = 0;+ __setLockPeekForTests(() => { peeks++; return { held: false }; });+ configReadiness({ engine: 'postgres', database_url: 'postgres://x/y' } as GBrainConfig, { transport: 'stdio' });+ configReadiness({ engine: 'pglite', remote_mcp: { mcp_url: 'https://h/mcp' } } as unknown as GBrainConfig, { transport: 'http' });+ expect(peeks).toBe(0);+ });+});++describe('probed tier cost', () => {+ test('never calls getStats/getHealth and returns worker, backup, migrations', async () => {+ const { engine, calls } = spyEngine();+ const entries = await probedReadiness(engine, { cache: createReadinessCache() });+ expect(calls).not.toContain('getStats');+ expect(calls).not.toContain('getHealth');+ const caps = new Set(entries.map(e => e.capability));+ for (const c of ['worker', 'migrations', 'sync']) expect(caps.has(c as ReadinessEntry['capability'])).toBe(true);+ expect(entries.find(e => e.capability === 'migrations')).toMatchObject({ state: 'ok', reason: 'current', tier: 'probed' });+ expect(entries.every(e => e.tier === 'probed')).toBe(true);+ });++ test('60 s cache: a second call within the TTL does no engine work', async () => {+ const { engine, calls } = spyEngine();+ const cache = createReadinessCache();+ const a = await probedReadiness(engine, { cache });+ const n = calls.length;+ const b = await probedReadiness(engine, { cache });+ expect(b).toBe(a);+ expect(calls.length).toBe(n);+ });++ test('single-flight: concurrent callers share one probe run', async () => {+ const { engine, calls } = spyEngine({ delayMs: 30 });+ const cache = createReadinessCache();+ const [a, b, c] = await Promise.all([probedReadiness(engine, { cache }), probedReadiness(engine, { cache }), probedReadiness(engine, { cache })]);+ expect(b).toBe(a);+ expect(c).toBe(a);+ const solo = spyEngine();+ await probedReadiness(solo.engine, { cache: createReadinessCache() });+ expect(calls.filter(x => x === 'getConfig').length).toBe(solo.calls.filter(x => x === 'getConfig').length);+ });++ test('stale-while-revalidate: an expired entry is served at once and refreshed in the background', async () => {+ const { engine, calls } = spyEngine();+ const store = new Map<string, { at: number; value: ReadinessEntry[] }>();+ const cache = { get: (k: string) => store.get(k), set: (k: string, v: { at: number; value: ReadinessEntry[] }) => { store.set(k, v); } };+ await probedReadiness(engine, { cache });+ const [key] = [...store.keys()];+ const stale: ReadinessEntry[] = [{ capability: 'worker', state: 'unknown', reason: 'probe_failed', why: 'stale', tier: 'probed', http_visible: false }];+ store.set(key, { at: Date.now() - PROBED_TTL_MS - 1, value: stale });+ const before = calls.length;+ expect(await probedReadiness(engine, { cache })).toBe(stale);+ await new Promise(r => setTimeout(r, 100));+ expect(calls.length).toBeGreaterThan(before);+ expect(store.get(key)?.value).not.toBe(stale);+ });++ test('2 s per-probe bound: a hung probe reports probe_timeout instead of hanging', async () => {+ const { engine } = spyEngine({ hang: true });+ const started = Date.now();+ const entries = await probedReadiness(engine, { cache: createReadinessCache() });+ const elapsed = Date.now() - started;+ expect(elapsed).toBeGreaterThanOrEqual(PROBE_TIMEOUT_MS - 50);+ expect(elapsed).toBeLessThan(PROBE_TIMEOUT_MS + 1500);+ expect(entries.find(e => e.capability === 'worker')?.reason).toMatch(/^probe_(timeout|failed)$/);+ expect(entries.find(e => e.capability === 'migrations')?.reason).toBe('current');+ }, 10_000);++ test('initialize tail: undefined within 250 ms when probes are slow, entries once the cache is warm', async () => {+ const slow = spyEngine({ hang: true });+ const started = Date.now();+ expect(await readinessTail(slow.engine, { cache: createReadinessCache() })).toBeUndefined();+ expect(Date.now() - started).toBeLessThan(1000);+ const fast = spyEngine();+ const cache = createReadinessCache();+ await probedReadiness(fast.engine, { cache });+ expect(Array.isArray(await readinessTail(fast.engine, { cache }))).toBe(true);+ }, 10_000);+});diff --git a/test/readiness.test.ts b/test/readiness.test.tsnew file mode 100644index 0000000000..f9e6415c53--- /dev/null+++ b/test/readiness.test.ts@@ -0,0 +1,267 @@+/**+ * A7 readiness (src/core/readiness.ts): the config-plane state/reason table per+ * capability, the one embedding-enablement fix, harness_wiring by state, the+ * exclusive two-step plan and the HTTP view.+ *+ * Protects: every surface (doctor, MCP initialize, whoami, receipts) reads one+ * answer for "what can this install do and what is the fix". A regression that+ * coaches a keyless-by-choice brain, routes an exclusive fix past a running+ * serve, registers a bare `gbrain` binary or reintroduces a wipe recipe fails here.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import {+ BACKUP_REASONS, CHAT_LLM_REASONS, EMBEDDINGS_REASONS, HARNESS_WIRING_REASONS, MIGRATIONS_REASONS, SYNC_REASONS,+ TOOL_SURFACE_REASONS, WORKER_REASONS, WRITEBACK_REASONS,+ __setLockPeekForTests, configReadiness, embeddingEnablement, exclusiveFix, harnessWiringEntry, readinessHttpView,+ type LockOwner, type ReadinessEntry,+} from '../src/core/readiness.ts';+import { renderAction, cliRenderContext, type Action } from '../src/core/agent-output.ts';+import { listRecipes } from '../src/core/ai/recipes/index.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { withEnv } from './helpers/with-env.ts';++const PROVIDER_ENVS = [...new Set(listRecipes().flatMap(r => r.auth_env?.required ?? []))];++/** Run with every provider key cleared, then `keys` set (no ambient key can leak into a pick). */+function withKeys<T>(keys: Record<string, string>, fn: () => T | Promise<T>): Promise<T> {+ const env: Record<string, string | undefined> = { GBRAIN_MODEL: undefined, GBRAIN_BRAIN_ID: undefined };+ for (const k of PROVIDER_ENVS) env[k] = undefined;+ return withEnv({ ...env, ...keys }, async () => fn());+}++const VOCAB: Record<string, readonly string[]> = {+ embeddings: EMBEDDINGS_REASONS, chat_llm: CHAT_LLM_REASONS, worker: WORKER_REASONS, writeback: WRITEBACK_REASONS,+ backup: BACKUP_REASONS, tool_surface: TOOL_SURFACE_REASONS, sync: SYNC_REASONS, migrations: MIGRATIONS_REASONS,+ harness_wiring: HARNESS_WIRING_REASONS,+};++function entry(entries: ReadinessEntry[], capability: string): ReadinessEntry {+ const found = entries.find(e => e.capability === capability);+ if (!found) throw new Error(`no ${capability} entry`);+ return found;+}++function pglite(extra: Partial<GBrainConfig> = {}): GBrainConfig {+ return { engine: 'pglite', database_path: '/brains/main.pglite', ...extra } as GBrainConfig;+}++afterEach(() => __setLockPeekForTests(null));++describe('config plane: state and reason per capability', () => {+ test('keyless-by-choice brain: embeddings disabled_by_choice, still carrying the enable fix', async () => {+ await withKeys({}, () => {+ __setLockPeekForTests(() => ({ held: false }));+ const { entries } = configReadiness(pglite({ embedding_disabled: true }), { transport: 'cli' });+ const e = entry(entries, 'embeddings');+ expect(e.state).toBe('disabled_by_choice');+ expect(e.reason).toBe('embedding_disabled');+ expect(e.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'init', '--force', '--embedding-model']);+ });+ });++ test('every entry uses its capability\'s closed vocabulary and declares requires_exclusive on fixes', async () => {+ await withKeys({}, () => {+ __setLockPeekForTests(() => ({ held: false }));+ const cfgs = [pglite({ embedding_disabled: true }), pglite(), pglite({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 }),+ pglite({ embedding_model: 'nope:model' }), pglite({ memory: { auto_writeback: 'off' } }), pglite({ memory: { auto_writeback: 'bogus' } }),+ pglite({ mcp_surface: 'verbs' }), { engine: 'postgres', database_url: 'postgres://x/y', remote_mcp: { mcp_url: 'https://h/mcp' } } as unknown as GBrainConfig];+ for (const cfg of cfgs) {+ for (const transport of ['cli', 'stdio'] as const) {+ for (const e of configReadiness(cfg, { transport }).entries) {+ expect(VOCAB[e.capability]).toContain(e.reason);+ expect(e.tier).toBe('config');+ if (e.fix) expect(typeof e.fix.requires_exclusive).toBe('boolean');+ }+ }+ }+ });+ });++ test('embeddings: not_configured, key_missing, unknown_model, ok', async () => {+ await withKeys({}, () => {+ expect(entry(configReadiness(pglite(), { transport: 'stdio' }).entries, 'embeddings')).toMatchObject({ state: 'missing', reason: 'not_configured' });+ const keyless = entry(configReadiness(pglite({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 }), { transport: 'stdio' }).entries, 'embeddings');+ expect(keyless).toMatchObject({ state: 'degraded', reason: 'key_missing' });+ expect(keyless.fix).toMatchObject({ actor: 'user', consent: ['credentials'] });+ expect(keyless.fix?.inputs?.[0]?.name).toBe('OPENAI_API_KEY');+ expect(entry(configReadiness(pglite({ embedding_model: 'nope:model' }), { transport: 'stdio' }).entries, 'embeddings').reason).toBe('unknown_model');+ });+ await withKeys({ OPENAI_API_KEY: 'sk-test' }, () => {+ expect(entry(configReadiness(pglite({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 }), { transport: 'stdio' }).entries, 'embeddings'))+ .toMatchObject({ state: 'ok', reason: 'configured' });+ });+ });++ test('chat, writeback, tool surface and thin-client rows', async () => {+ await withKeys({}, () => {+ const entries = configReadiness(pglite({ mcp_surface: 'verbs', memory: { auto_writeback: 'off' } }), { transport: 'stdio' }).entries;+ expect(entry(entries, 'chat_llm')).toMatchObject({ state: 'missing', reason: 'not_configured' });+ expect(entry(entries, 'writeback')).toMatchObject({ state: 'disabled_by_choice', reason: 'off_by_choice' });+ expect(entry(entries, 'tool_surface')).toMatchObject({ state: 'ok', reason: 'surface_verbs' });+ expect(entry(configReadiness(pglite(), { transport: 'stdio' }).entries, 'writeback')).toMatchObject({ state: 'missing', reason: 'not_configured' });+ const thin = configReadiness({ engine: 'postgres', remote_mcp: { mcp_url: 'https://h/mcp' } } as unknown as GBrainConfig, { transport: 'cli' });+ for (const cap of ['embeddings', 'chat_llm', 'writeback', 'sync']) expect(entry(thin.entries, cap).state).toBe('not_applicable');+ expect(thin.lock_owner).toBeNull();+ });+ await withKeys({ ANTHROPIC_API_KEY: 'sk-ant-test' }, () => {+ expect(entry(configReadiness(pglite(), { transport: 'stdio' }).entries, 'chat_llm')).toMatchObject({ state: 'ok', reason: 'configured' });+ });+ });+});++describe('embeddingEnablement', () => {+ const run = (cfg: GBrainConfig, keys: Record<string, string>, env: Record<string, string> = {}) =>+ withKeys({ ...keys, ...env }, () => embeddingEnablement(cfg));++ test('default path: keyed provider, in-place init with the resolved datastore and width', async () => {+ const a = await run({ engine: 'pglite', embedding_disabled: true } as GBrainConfig, { VOYAGE_API_KEY: 'v' }, { GBRAIN_HOME: '/home/u' });+ expect(a.argv).toEqual(['gbrain', 'init', '--force', '--embedding-model', 'voyage:voyage-4', '--embedding-dimensions', '1024', '--path', '/home/u/.gbrain/brain.pglite']);+ expect(a).toMatchObject({ actor: 'agent', consent: ['credentials', 'paid'], requires_exclusive: true });+ expect(a.why).toContain('Pages, facts and keyword search are kept');+ expect(a.why).toContain('queued for vectors');+ expect(a.argv?.join(' ')).not.toContain('mv ');+ });++ test('custom path and Postgres target their own datastore', async () => {+ expect((await run(pglite({ embedding_disabled: true }), { VOYAGE_API_KEY: 'v' })).argv?.slice(-2)).toEqual(['--path', '/brains/main.pglite']);+ const pg = await run({ engine: 'postgres', database_url: 'postgres://x/y', embedding_disabled: true } as GBrainConfig, { VOYAGE_API_KEY: 'v' });+ expect(pg.argv).toEqual(['gbrain', 'init', '--force', '--embedding-model', 'voyage:voyage-4', '--embedding-dimensions', '1024']);+ });++ test('mounted brain routes through `embeddings enable --brain`, never init --path', async () => {+ const a = await run(pglite({ embedding_disabled: true }), { VOYAGE_API_KEY: 'v' }, { GBRAIN_BRAIN_ID: 'team' });+ expect(a.argv).toEqual(['gbrain', 'embeddings', 'enable', '--brain', 'team', '--embedding-model', 'voyage:voyage-4', '--embedding-dimensions', '1024']);+ });++ test('multiple providers: the canonical default wins; legacy width picks a provider that fits', async () => {+ expect((await run(pglite({ embedding_disabled: true }), { VOYAGE_API_KEY: 'v', OPENAI_API_KEY: 'o' })).argv?.[4]).toBe('voyage:voyage-4');+ const legacy = await run(pglite({ embedding_disabled: true, embedding_dimensions: 1536 }), { VOYAGE_API_KEY: 'v', OPENAI_API_KEY: 'o' });+ expect(legacy.argv?.[4]).toMatch(/^openai:/);+ expect(legacy.argv?.slice(5, 7)).toEqual(['--embedding-dimensions', '1536']);+ });++ test('no key: the fix asks the user for one (actor user, credentials+paid, inputs)', async () => {+ const a = await run(pglite({ embedding_disabled: true }), {});+ expect(a).toMatchObject({ actor: 'user', consent: ['credentials', 'paid'], requires_exclusive: true });+ expect(a.inputs?.map(i => i.name)).toEqual(['VOYAGE_API_KEY']);+ expect(renderAction(a, cliRenderContext()).next).toBe('tell_user_to_run');+ });++ test('width mismatch refuses to rebuild: names a provider that fits instead', async () => {+ const a = await run(pglite({ embedding_disabled: true, embedding_dimensions: 1536 }), { VOYAGE_API_KEY: 'v' });+ expect(a.actor).toBe('user');+ expect(a.inputs?.map(i => i.name)).toEqual(['OPENAI_API_KEY']);+ expect(a.why).toContain('cannot produce');+ const none = await run(pglite({ embedding_disabled: true, embedding_dimensions: 7 }), { VOYAGE_API_KEY: 'v' });+ expect(none.argv).toEqual(['gbrain', 'migrate', 'embeddings', '--status', '--json']);+ expect(none.requires_exclusive).toBe(false);+ });++ test('an explicitly requested model is honoured', async () => {+ const a = await run(pglite({ embedding_disabled: true, embedding_model: 'openai:text-embedding-3-small' }), { VOYAGE_API_KEY: 'v' });+ expect(a.argv?.[4]).toBe('openai:text-embedding-3-small');+ expect(a.inputs?.map(i => i.name)).toEqual(['OPENAI_API_KEY']);+ });+});++describe('harness_wiring by state', () => {+ const BIN = '/opt/gbrain/bin/gbrain';+ const owner = (transport: 'stdio' | 'http', is_self = false): LockOwner => ({ pid: 4242, transport, is_self });++ test('one harness, no serve: harness-native stdio registration with the absolute binary and --surface verbs', () => {+ const claude = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: null, gbrainBin: BIN });+ expect(claude.fix?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'verbs']);+ expect(claude.fix?.consent).toEqual(['persistent_install']);+ expect(claude.fix?.why).toContain('~/.claude.json');+ expect(harnessWiringEntry({ transport: 'cli', harnesses: ['codex'], lockOwner: null, gbrainBin: BIN }).fix?.argv)+ .toEqual(['codex', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'verbs']);+ expect(harnessWiringEntry({ transport: 'cli', harnesses: ['opencode'], lockOwner: null, gbrainBin: BIN }).fix?.argv)+ .toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks']);+ });++ test('never a bare gbrain binary: unresolved binary yields no registration', () => {+ const e = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: null, gbrainBin: null });+ expect(e.reason).toBe('binary_unresolved');+ expect(e.fix?.argv).toBeUndefined();+ });++ test('serve --http running or a second session: shared HTTP wiring, credentials disclosed', () => {+ const http = harnessWiringEntry({ transport: 'cli', harnesses: ['codex'], lockOwner: owner('http'), gbrainBin: BIN });+ expect(http.reason).toBe('http_serve_running');+ expect(http.fix?.argv).toEqual(['gbrain', 'bootstrap', 'harness', '--harness', 'codex', '--yes']);+ expect(http.fix?.consent).toEqual(['persistent_install', 'credentials']);+ expect(http.fix?.why).toContain('bearer token');+ expect(http.fix?.why).toContain('permissions.allow');+ const second = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: owner('stdio'), gbrainBin: BIN });+ expect(second).toMatchObject({ state: 'degraded', reason: 'multiple_sessions' });+ expect(second.fix?.argv).toEqual(['gbrain', 'bootstrap', 'harness', '--harness', 'claude-code', '--yes']);+ expect(harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code', 'codex'], lockOwner: null, gbrainBin: BIN }).fix?.argv?.[4]).toBe('all');+ });++ test('no harness: per-harness install docs; stdio is wired; http is not applicable', () => {+ const none = harnessWiringEntry({ transport: 'cli', harnesses: [], lockOwner: null, gbrainBin: BIN });+ expect(none.reason).toBe('no_harness_detected');+ expect(none.fix?.docs).toContain('docs/protocol/MEMORY_VERBS_v1.md#');+ expect(harnessWiringEntry({ transport: 'stdio', harnesses: [], lockOwner: null, gbrainBin: null })).toMatchObject({ state: 'ok', reason: 'wired_running' });+ expect(harnessWiringEntry({ transport: 'http', harnesses: [], lockOwner: null, gbrainBin: null }).state).toBe('not_applicable');+ });+});++describe('exclusive fixes and lock ownership', () => {+ const action: Action = { argv: ['gbrain', 'init', '--force', '--embedding-model', 'voyage:voyage-4'], consent: ['credentials', 'paid'], actor: 'agent', why: 'w', requires_exclusive: true };++ test('no owner or a non-exclusive fix: unchanged; an owner-delegating command stays one step', () => {+ expect(exclusiveFix(action, null)).toBe(action);+ const plain = { ...action, requires_exclusive: false };+ expect(exclusiveFix(plain, { pid: 1, transport: 'stdio', is_self: false })).toBe(plain);+ const reindex = { ...action, argv: ['gbrain', 'reindex-code', '--yes'] };+ expect(exclusiveFix(reindex, { pid: 1, transport: 'stdio', is_self: false })).toBe(reindex);+ });++ test('a live serve owner: two-step plan, step one (actor user) stops it, then the command', () => {+ const plan = exclusiveFix(action, { pid: 4242, transport: 'http', is_self: false });+ expect(plan).toMatchObject({ actor: 'user', argv: ['kill', '4242'], requires_exclusive: false, then: action });+ expect(plan.why).toContain('gbrain serve --http');+ const rendered = renderAction(plan, cliRenderContext());+ expect(rendered.next).toBe('tell_user_to_run');+ expect(rendered.then?.next).toBe('ask_user');+ });++ test('config plane reads the lock once, derives the owner transport, and wraps exclusive fixes', async () => {+ await withKeys({ VOYAGE_API_KEY: 'v' }, () => {+ let peeks = 0;+ __setLockPeekForTests(() => { peeks++; return { held: true, isServe: true, pid: 999_999, http: false, acquiredAt: 1_700_000_000_000 }; });+ const cfg = pglite({ embedding_disabled: true });+ const r = configReadiness(cfg, { transport: 'stdio' });+ configReadiness(cfg, { transport: 'cli' });+ expect(peeks).toBe(1);+ expect(r.lock_owner).toEqual({ pid: 999_999, transport: 'stdio', started_at: new Date(1_700_000_000_000).toISOString(), is_self: false });+ const fix = entry(r.entries, 'embeddings').fix!;+ expect(fix.argv).toEqual(['kill', '999999']);+ expect(fix.then?.argv?.[1]).toBe('init');+ });+ });++ test('a non-serve holder is not a lock owner', async () => {+ await withKeys({}, () => {+ __setLockPeekForTests(() => ({ held: true, isServe: false, pid: 77 }));+ expect(configReadiness(pglite(), { transport: 'stdio' }).lock_owner).toBeNull();+ });+ });+});++describe('HTTP view', () => {+ test('http_visible:false entries are stripped and paths redacted; no lock owner', async () => {+ await withKeys({ VOYAGE_API_KEY: 'v' }, () => {+ __setLockPeekForTests(() => ({ held: true, isServe: true, pid: 31337, http: true }));+ const view = configReadiness(pglite({ embedding_disabled: true, database_path: '/home/u/.gbrain/brain.pglite' }), { transport: 'http' });+ expect(view.lock_owner).toBeNull();+ expect(view.entries.every(e => e.http_visible)).toBe(true);+ expect(view.entries.map(e => e.capability)).not.toContain('writeback');+ expect(view.entries.map(e => e.capability)).not.toContain('harness_wiring');+ expect(JSON.stringify(view)).not.toContain('/home/u');+ expect(JSON.stringify(view)).not.toContain('31337');+ expect(readinessHttpView([{ capability: 'backup', state: 'ok', reason: 'covered', why: 'x', tier: 'probed', http_visible: false }])).toEqual([]);+ });+ });+});