Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: operability, safety & first-run experience (v1.29.0) (#134)
Sol Aitken70fb36e1c7db
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 1b12a869..44195e30 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.28.0",+ "version": "1.29.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 62f1241f..3729b874 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.28.0",+ "version": "1.29.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b907c032..b5e8a22d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.29.0] - 2026-07-10++An operability, safety, and first-run release that makes Open Second Brain robust and pleasant to set up and operate: a guided first-run checklist, actionable config diagnostics, resilient hooks and rate-limit handling, safe mutating operations, a hardened optional HTTP transport, and usage visibility. Every new surface is additive and off by default or byte-identical when its condition is absent; the release adds no new dependency and the kernel still calls no LLM.++### Added++- **Guided first-run onboarding checklist.** `o2b init` now prints a state-aware, ordered set of next steps beyond search indexing (vault config, Brain scaffold, first index, agent identity, an optional embedding key, a first feedback signal, session import, and a health check), each with a done flag and a copy-pasteable command. A re-runnable `o2b onboarding` verb (text or `--json`) shows the same checklist any time. It reuses the runtime-notice and doctor-remediation surfaces; read-only, no network, no model.+- **Config-validator remediation.** The install/config doctor's `CheckResult` gains an optional `fix` field carrying a copy-pasteable remediation command, populated in every failing check (`mkdir`/`chmod` for vault and config, `o2b update` for a missing or invalid manifest). `o2b doctor` renders it under failing checks, gains a scriptable `--json` report (per-check `fix` plus an aggregate `{total, failed}` summary) and a summary line, and surfaces `fix` through `vault_health` and the OpenClaw doctor. The 0/1 exit stays the scriptable gate - the doctor becomes a self-service repair tool.+- **Runtime-state notice channel.** A deterministic, no-network, no-LLM probe surfaces OSB's own transient conditions - semantic search degraded (enabled but no embedding key resolved), the search index missing or rebuilding, and a read-only vault - as notices that ride the existing SessionStart injection surface (prepended only when a condition holds, so a healthy vault stays byte-identical) and fold into `vault_health` for pull consumers. Default on; opt out with `OPEN_SECOND_BRAIN_RUNTIME_NOTICES=false`.+- **Hook process self-watchdog and fail-open context load.** A lifecycle hook now arms a hard time ceiling on itself (default 55s, override `OPEN_SECOND_BRAIN_HOOK_CEILING_MS`): a healthy run exits normally, and a hung hook self-terminates at the deadline with an audit line instead of orphaning a process or blocking the agent. SessionStart context assembly runs fail-open - a slow or failing assembly degrades to the last-good cached body (or empty), never a partial or poisoned write. Distinct from the `brain_watchdog` vault-health probe.+- **Expectation and strict count guards on mutating ops.** `--expect N` asserts how many items a mutation will touch and `--strict` refuses a guardless mutation; on a mismatch the op aborts before writing and surfaces the matched list. Wired into delete-by-source, hygiene apply, and dream run (MCP and CLI), each reporting honest `matched` vs `changed` counts. The atomic writer gains an opt-in content-equality short-circuit that skips an identical write (no mtime churn). No block-query DSL; guards default off.+- **Per-skill invocation telemetry.** How often each installed skill is actually invoked is captured as an append-only `skill_invoked` continuity record, emitted from the session-import tool-call scan across Claude Code and opencode logs (`get_skill` and the host-native `Skill`; discovery and attach are not invocations). Counts are derived read-side, deduped by content-address id so re-import is idempotent, and surfaced via `brain_skill_proposals` `operation: usage` and `o2b brain skill-proposals usage`. Deterministic, no LLM; distinct from proposal ranking and outcome-weighted recall.++### Changed++- **Configurable embedding retry budget for 429/5xx.** The embedding provider's per-batch transient-retry budget is now runtime-configurable via `embedding_max_retries` / `OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES`, with the default raised from a hardcoded 3 to 6, threaded into both the OpenAI-compatible and ZeroEntropy providers, so a reindex against a strict-RPM account no longer exhausts the budget and silently drops chunks. `ping()` still probes once and multi-key auth failover stays independent; the concurrency knob already exists as `embedding_concurrency`.+- **Hardened optional loopback HTTP transport.** The opt-in `o2b mcp --transport http` server gains a mandatory, non-bypassable Host/Origin DNS-rebinding guard (a foreign Host or cross-origin/opaque Origin is rejected before auth) and an unauthenticated `GET /health` liveness probe. The bearer token is now optional on a loopback bind (loopback + guards are the baseline defence) but mandatory on a non-loopback host - the server refuses to expose an unauthenticated endpoint on the network, with no permissive fallback. stdio stays the default transport.+## [1.28.0] - 2026-07-10A retrieval and ranking quality release: embedding-layer robustness, faster and smarter candidate retrieval, a fully offline reranker with a per-store eval gate, ranking signals learned from real outcomes, and a named benchmark to score the whole. Every new surface is additive and off by default where it changes an existing path; the release adds no new dependency and no ML runtime, and the kernel still calls no LLM.@@ -6429,6 +6447,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.29.0]: https://github.com/itechmeat/open-second-brain/compare/v1.28.0...v1.29.0[1.28.0]: https://github.com/itechmeat/open-second-brain/compare/v1.27.1...v1.28.0[1.27.1]: https://github.com/itechmeat/open-second-brain/compare/v1.27.0...v1.27.1[1.27.0]: https://github.com/itechmeat/open-second-brain/compare/v1.26.1...v1.27.0diff --git a/README.md b/README.mdindex 622dae15..8f9e1b5b 100644--- a/README.md+++ b/README.md@@ -104,7 +104,7 @@ That is the day-to-day picture. The full capability surface, every CLI verb, and## Safety-- Plain Markdown on your filesystem. No daemon, no background writes. The MCP server is a stdio subprocess that exits with the parent runtime.+- Plain Markdown on your filesystem. No daemon, no background writes. The MCP server is a stdio subprocess that exits with the parent runtime. An optional HTTP transport (`o2b mcp --transport http`) is off by default and safe by design: it binds loopback (`127.0.0.1`), enforces a Host/Origin DNS-rebinding guard on every request, and exposes an unauthenticated `GET /health` liveness probe. A bearer token (`--api-key`) is optional on loopback and mandatory when binding a non-loopback host - the server refuses to expose an unauthenticated endpoint on the network.- Your vault is the only source of truth - no hidden state, no cloud copy.- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.- Secrets are not supposed to live in the vault. Daily logs and config exports run through a best-effort redactor, `$secret:NAME` references resolve from the local environment and are never stored, and Brain redaction strips `<private>...</private>` regions before storage.diff --git a/docs/brainstorm/operability-first-run/design.md b/docs/brainstorm/operability-first-run/design.mdnew file mode 100644index 00000000..a838a2d1--- /dev/null+++ b/docs/brainstorm/operability-first-run/design.md@@ -0,0 +1,205 @@+# Operability, Safety & First-Run - Design++## Problem++A freshly installed Open Second Brain is harder to stand up and operate than+it should be. A new vault prints one next step (search indexing); the doctor+diagnoses failures without telling the operator how to fix them; health is+pull-only, so an agent learns semantic search fell back to lexical only by+polling; lifecycle hooks have no self-imposed time ceiling and the inject path+fails fast instead of degrading; the embedding retry budget is a hardcoded 3+that silently drops chunks under strict rate limits; mutating sweeps can touch+far more files than expected and rewrite unchanged files; the HTTP transport+lacks a DNS-rebinding guard and a health endpoint; and skill proposals rank+with no signal about which skills agents actually use.++This release makes the system robust and pleasant to set up and operate, as one+coherent scope, without adding a dependency and without the kernel calling an+LLM.++## Scope++Eight in-scope board tasks:++- `t_9b0bb1be` - configurable 429/rate-limit retry budget for embeddings.+- `t_fb132614` - process self-watchdog (hard time ceiling) + fail-open context+ load for lifecycle hooks.+- `t_5161e7ab` - runtime-state notice channel on the injection surface.+- `t_b3dc1454` - config validator that prints copy-pasteable remediation per+ failing check, with a scriptable aggregate status.+- `t_67e491f6` - `--expect N` / `--strict` guards + honest matched/changed+ reporting on mutating ops.+- `t_bdd82ecf` - hardened optional loopback HTTP transport (Host/Origin+ rebinding guard, health endpoint, optional bearer).+- `t_56a12bde` - per-skill invocation telemetry feeding skill-proposal ranking.+- `t_84500f39` - guided first-run onboarding checklist (implemented last; ties+ the config/health/notice surfaces together).++## Out of scope++- Quota-error classification (`t_8880a68d`, an out-of-scope child of the retry+ task) - the retry task raises/exposes the retry budget only.+- A block-addressing query DSL or markdown AST for the mutation guards - port+ the guard/reporting concepts only.+- A third-party plugin notice bus (mem9's model) - notices cover OSB's own+ subsystems only.+- Replacing the pull-based `brain_doctor` / `vault_health` - notices complement+ them.+- On-chain / Solana anchoring - never in scope for this project.++## Chosen approach++Variant 1 (see `variants.md`): thin composition on existing seams. New modules+are small and single-purpose; no new MCP tool is added (notices fold into+`vault_health` and the inject surface; skill usage folds into+`brain_skill_proposals`); the frozen 98-tool surface is preserved; no new+dependency; every new behaviour is additive and byte-identical when its+condition is absent or its gate is off.++## Design decisions++### Configurable embedding retry (`t_9b0bb1be`)+`ResolvedEmbeddingConfig` gains `maxRetries` (default 6, raised from the+hardcoded 3). It is read in `resolveSearchConfig` from `embedding_max_retries`+/ `OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES` via the existing `parseInteger`+`{min:1}` path, added to the frozen `semantic` object, and range-validated in+`validateResolvedConfig`. `OpenAICompatProvider.embed()` threads+`config.maxRetries` into `embedBatchWithRetry` -> `embedBatchOnKey`'s+`maxAttempts`; `ping()` keeps its explicit single attempt. `ZeroEntropyProvider`+gets the identical thread for parity. Backoff stays exponential with jitter; the+last backoff value repeats when attempts exceed the array length (already the+code's behaviour). The max-concurrency knob the upstream feature suggests+already exists as `embedding_concurrency`; it is documented, not re-added.++### Hook self-watchdog + fail-open inject (`t_fb132614`)+A reusable process-ceiling primitive arms a hard time ceiling (default ~55s,+overridable via `OPEN_SECOND_BRAIN_HOOK_CEILING_MS`) using an `unref`ed timer so+it never itself keeps a process alive; on expiry it appends a watchdog audit+line and exits 0 (never a partial write). The timer's `exit` and clock are+injectable so the primitive is unit-tested without spawning. It wraps the two+lifecycle-hook entry points (`active-inject`, `session-capture`).++A fail-open inject loader assembles the injected context inside a guard: on+success it records the assembled body as last-good under+`<vault>/.open-second-brain/`; on any error or overrun it degrades to the+last-good body, or to empty when no cache exists, and appends an audit line. It+never emits a partial or poisoned payload. Reuses `appendAuditRecord`+(`src/core/reliability/audit.ts`).++### Runtime-state notices (`t_5161e7ab`)+`collectRuntimeNotices(vault, {configPath})` returns a small ordered list of+`{code, severity, message}`, computed deterministically with no network and no+LLM: semantic search degraded (enabled but embedding key unresolved, or the+sqlite-vec extension unavailable), indexing lag / reindex in progress+(structural markers under `.open-second-brain/` and an index-older-than-newest-+note check), and read-only vault (a write probe). Notices render as a compact+`Runtime notices:` block prepended to the `active-inject` `additionalContext`+only when the list is non-empty (a healthy vault stays byte-identical), and are+folded into `vault_health` output for pull consumers. Default on; suppressible+via an opt-out env. It does not absorb the quota task.++### Doctor remediation (`t_b3dc1454`)+`CheckResult` gains an optional `fix` field (a copy-pasteable command). Each+failing branch in `src/core/doctor.ts` populates it where a deterministic fix+exists (checks with no deterministic fix omit it). It renders in all three+existing consumers: `o2b doctor` (which gains `--json` and an aggregate+`N checks, M failed` summary; the 0/1 exit stays the scriptable status),+`vault_health`, and the OpenClaw surface. This is the install/config doctor+(`src/core/doctor.ts`), distinct from the Brain-invariant doctor+(`src/core/brain/doctor.ts`).++### Mutation guards (`t_67e491f6`)+A pure `assertExpectedCount({matched, expect, strict, willMutate})` helper+throws a structured error carrying the match list when `expect` mismatches the+matched count, and refuses a guardless mutation when `strict` is set. The atomic+writer gains an opt-in `skipIfUnchanged` that reads the target and short-circuits+identical content, returning whether it actually wrote; this threads through+`writeFrontmatterAtomic` so signal/preference/page writers can report+`changed`. The guard + reporting wire into the three dry-run-capable mutating+ops (delete-by-source, hygiene apply, dream run) and their CLI verbs; each op+payload gains honest `matched` vs `changed` counts. `brain_review_candidates`+stays read-only (its `would_*` lists are the match source). No block-query DSL.++### Hardened HTTP transport (`t_bdd82ecf`)+The existing `src/mcp/http.ts` is hardened, not rewritten. A mandatory,+non-bypassable Host DNS-rebinding guard rejects any request whose `Host` header+is not the loopback host (or the explicitly bound host); a mandatory Origin+guard rejects a present-but-foreign `Origin`. A `GET /health` endpoint returns+`200` with a small JSON status (auth-exempt but still Host-guarded); other GETs+stay `405`. The bearer becomes optional on a loopback bind (loopback + guards+are the baseline defence) but stays required on a non-loopback bind - binding to+a public interface without a token is refused (no permissive fallback). stdio+stays the default transport.++### Skill invocation telemetry (`t_56a12bde`)+A new append-only continuity kind `skill_invoked` is emitted from the existing+session-import tool-call loop when a skill invocation is seen (disambiguated per+turn/call so each invocation hashes to a distinct record id). Counts are derived+read-side by mirroring the usage-signal decay math (append-only, replayable, no+mutable counter). The derived per-skill count feeds skill-proposal ranking and+is surfaced through `brain_skill_proposals` as a new `usage` view and the+matching CLI view. Deterministic, no LLM. No new tool (frozen surface intact).++### Guided onboarding (`t_84500f39`, last)+`buildOnboardingChecklist(vault, config)` computes an ordered set of steps from+real state (config persisted? index built? agent name set? embedding key+resolvable? any feedback signal yet? importable sessions present?), each with a+status, a copy-pasteable command, and a hint. `cmdInit` renders it after the+existing (retained) search block; a re-runnable `onboarding` verb prints it any+time. It reuses the doctor remediation and runtime-notice surfaces so the+checklist reflects the same signals the rest of the release exposes.++## File changes++New:+- `src/core/reliability/process-ceiling.ts` - hard time-ceiling primitive.+- `src/core/brain/runtime-notices.ts` - deterministic notice collector.+- `src/core/brain/count-guard.ts` - `assertExpectedCount` + `CountGuardError`.+- `src/core/brain/skill-usage.ts` - derive per-skill invocation counts.+- `src/cli/onboarding.ts` - onboarding checklist builder + renderer.+- Tests mirroring each under `tests/`.++Changed:+- `src/core/types.ts` - `CheckResult.fix?`.+- `src/core/doctor.ts` - populate `fix` per failing check.+- `src/core/search/types.ts`, `src/core/search/index.ts` - `maxRetries`.+- `src/core/search/embeddings/openai-compat.ts`, `.../zeroentropy.ts` - thread+ `maxRetries`.+- `src/core/fs-atomic.ts`, `src/core/vault.ts` - `skipIfUnchanged` ++ `changed` return.+- `src/mcp/http.ts` - Host/Origin guard, `/health`, optional bearer.+- `src/mcp/tools.ts` (`vault_health`) - `fix` + `notices`.+- `src/openclaw/index.ts` - render `fix`.+- `hooks/active-inject.ts`, `hooks/session-capture.ts` - ceiling + fail-open ++ notices.+- `src/core/brain/continuity/types.ts` - `skill_invoked` kind.+- `src/core/brain/sessions/import.ts` - emit `skill_invoked`.+- `src/mcp/skill-tools.ts` (optional supplementary emit).+- `src/core/brain/skill-proposals.ts`, `src/mcp/brain/procedure-tools.ts` -+ usage view + ranking feed.+- `src/cli/main.ts` (`cmdInit`, `cmdDoctor`, new `onboarding`),+ `src/cli/command-manifest.ts`.+- CLI verbs: `forget-source.ts`, `hygiene.ts`, `dream.ts`, `feedback.ts` -+ `--expect` / `--strict`.+- MCP ops: `ingest-tools.ts`, `hygiene-tools.ts`, `feedback-tools.ts` - guard ++ matched/changed.+- `CHANGELOG.md`, `package.json`, mirrored manifests (via `sync-version.ts`),+ `README.md` (HTTP transport + onboarding), `docs/`.++## Risks++- **HTTP hardening loosening the bearer.** Mitigation: loopback + Host/Origin+ guard are mandatory and non-bypassable; a non-loopback bind still requires a+ bearer; the guard is unit-tested against rebinding and cross-origin.+- **Process ceiling can't interrupt a truly synchronous hang.** Mitigation: the+ realistic hangs are async I/O (embedding fetch, fs stall on a network mount),+ which the `unref`ed timer + `AbortController` timeouts already cover; the host+ `timeout` in `hooks.json` remains a second line.+- **Notices changing injected context.** Mitigation: notices render only when a+ real degraded condition exists, so a healthy vault is byte-identical; an+ opt-out env exists.+- **Skill-invocation dedup collapsing distinct invocations.** Mitigation:+ each record carries a per-turn/call disambiguator so identical-second+ invocations hash to distinct ids.+- **Content-equality skip masking a needed mtime bump.** Mitigation:+ `skipIfUnchanged` is opt-in; default write behaviour is unchanged.diff --git a/docs/brainstorm/operability-first-run/plan.md b/docs/brainstorm/operability-first-run/plan.mdnew file mode 100644index 00000000..1b62b92e--- /dev/null+++ b/docs/brainstorm/operability-first-run/plan.md@@ -0,0 +1,186 @@+# Operability, Safety & First-Run - Per-Task Plan++Implementation order follows the sequence hint: resilience -> visibility ->+guards/transport -> telemetry -> onboarding last. Each task is test-driven: a+failing acceptance test first, then minimal code, then zero-warning+`bun run validate`.++---++## t_9b0bb1be - Configurable 429 retry budget++**Files.**+- `src/core/search/types.ts` - add `readonly maxRetries: number` to+ `ResolvedEmbeddingConfig`.+- `src/core/search/index.ts` - `DEFAULTS.maxRetries = 6`; read+ `embedding_max_retries` / `OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES`+ (`parseInteger`, `{min:1}`); add to frozen `semantic`; range-validate in+ `validateResolvedConfig`.+- `src/core/search/embeddings/openai-compat.ts` - thread `config.maxRetries`+ into `embed()`'s retry (`embedBatchOnKey` `maxAttempts`); keep `ping()` at 1.+- `src/core/search/embeddings/zeroentropy.ts` - same thread.+- `tests/core/search/embeddings.test.ts` (+ zeroentropy test) - retry cases.++**Acceptance test.** With `embedding_max_retries=5` a provider hitting `429`+four times then `200` succeeds and makes exactly 5 attempts; with the default,+6 attempts; a non-retriable `400` still fails fast on attempt 1; `ping()` still+makes a single attempt. Config out of range fails validation.++**Depends on.** None. (Out-of-scope child `t_8880a68d` not pulled in.)++---++## t_fb132614 - Hook self-watchdog + fail-open inject++**Files.**+- `src/core/reliability/process-ceiling.ts` (new) - `armProcessCeiling({+ ceilingMs, onExpire?, exit?, setTimer? })` returning a disarm fn; `unref`ed+ timer; default ceiling from `OPEN_SECOND_BRAIN_HOOK_CEILING_MS` (~55000).+- `src/core/brain/inject-failopen.ts` (new) - last-good cache read/write under+ `<vault>/.open-second-brain/` + degrade-to-cached/empty wrapper with an audit+ line.+- `hooks/active-inject.ts`, `hooks/session-capture.ts` - arm the ceiling; route+ inject assembly through the fail-open loader.+- `tests/core/reliability/process-ceiling.test.ts`,+ `tests/core/brain/inject-failopen.test.ts` (new).++**Acceptance test.** A ceiling armed with an injected fake timer + injected+`exit` fires `onExpire` and calls `exit(0)` at the ceiling when work has not+completed, and does nothing when disarmed first. The fail-open loader, given an+assembler that throws, returns the previously-cached body (and, with no cache,+empty), never a partial value, and appends exactly one degrade audit record.++**Depends on.** None (foundational).++---++## t_5161e7ab - Runtime-state notice channel++**Files.**+- `src/core/brain/runtime-notices.ts` (new) - `collectRuntimeNotices(vault,+ {configPath})` -> `RuntimeNotice[]` (`{code, severity, message}`), covering+ degraded semantic search, indexing lag / reindex-in-progress, read-only vault.+- `hooks/active-inject.ts` - prepend a `Runtime notices:` block when non-empty.+- `src/mcp/tools.ts` (`vault_health`) - add a `notices` array.+- `tests/core/brain/runtime-notices.test.ts`, an inject-surface test, a+ `vault_health` test.++**Acceptance test.** A vault with semantic enabled but no embedding key yields a+`semantic_degraded` notice; a read-only vault yields a `vault_read_only` notice;+a healthy vault yields none and the injected `additionalContext` is+byte-identical to today. `vault_health` surfaces the same notices. No network is+touched (verified with a no-network harness).++**Depends on.** None; consumed by onboarding (`t_84500f39`).++---++## t_b3dc1454 - Config validator remediation++**Files.**+- `src/core/types.ts` - `CheckResult.fix?: string`.+- `src/core/doctor.ts` - populate `fix` in each failing branch with a concrete+ command.+- `src/cli/main.ts` (`cmdDoctor`) - render `fix`; add `--json`; print an+ aggregate `N checks, M failed` summary; keep 0/1 exit.+- `src/mcp/tools.ts` (`vault_health`), `src/openclaw/index.ts` - render `fix`.+- `tests/core/doctor.test.ts`, a `cmdDoctor` CLI test, a `vault_health` test.++**Acceptance test.** A missing/unwriteable vault check carries a+copy-pasteable `fix` command; a passing check omits `fix`; `o2b doctor --json`+emits `{ok, checks:[{name, ok, message, fix?}], summary:{total, failed}}` and+exits `1` when any check fails, `0` when all pass; `vault_health` includes+`fix`.++**Depends on.** None; consumed by onboarding.++---++## t_67e491f6 - Expect/strict guards + matched/changed++**Files.**+- `src/core/brain/count-guard.ts` (new) - `assertExpectedCount` ++ `CountGuardError` (carries the match list).+- `src/core/fs-atomic.ts` - optional `skipIfUnchanged` returning `changed:boolean`.+- `src/core/vault.ts` (`writeFrontmatterAtomic`) - thread `changed` through.+- `src/mcp/brain/ingest-tools.ts`, `hygiene-tools.ts`, `feedback-tools.ts` -+ wire `expect`/`strict`; add `matched`/`changed` to payloads.+- CLI verbs `forget-source.ts`, `hygiene.ts`, `dream.ts`, `feedback.ts` -+ `--expect` (string->int), `--strict` (bool).+- `tests/core/brain/count-guard.test.ts`, `tests/core/fs-atomic.test.ts`, and+ op-level tests.++**Acceptance test.** A delete/hygiene/dream op run with `--expect 3` when it+would touch 5 aborts without writing and returns the 5-item match list; the same+op with `--strict` and no `--expect` aborts as guardless; a write of identical+content with `skipIfUnchanged` returns `changed:false` and leaves the file mtime+untouched; each op payload reports `matched` and `changed` distinctly.++**Depends on.** None.++---++## t_bdd82ecf - Hardened optional HTTP transport++**Files.**+- `src/mcp/http.ts` - mandatory Host DNS-rebinding guard, mandatory Origin+ guard, `GET /health`, optional bearer on loopback / required on non-loopback.+- `src/cli/main.ts` (`cmdMcp`) - allow `--transport http` without `--api-key` on+ a loopback host; keep requiring it on a non-loopback host.+- `tests/mcp/http-transport.test.ts` - update + extend.+- `README.md` - document the opt-in transport and its security model.++**Acceptance test.** A request with a non-loopback `Host` header is rejected+`403` (DNS-rebinding guard); a request with a foreign `Origin` is rejected+`403`; `GET /health` returns `200` JSON with no bearer; a loopback server with+no configured bearer serves an authenticated-free `initialize`; a configured+bearer is still enforced (`401` on wrong/missing); starting an HTTP transport on+a non-loopback host with no bearer is refused.++**Depends on.** None. Extra CodeRabbit attention here (security-sensitive).++---++## t_56a12bde - Per-skill invocation telemetry++**Files.**+- `src/core/brain/continuity/types.ts` - add `"skill_invoked"` kind.+- `src/core/brain/sessions/import.ts` - emit a `skill_invoked` record per skill+ invocation in the tool-call loop (per-turn/call disambiguator).+- `src/core/brain/skill-usage.ts` (new) - derive per-skill counts (mirror+ usage-signal decay).+- `src/core/brain/skill-proposals.ts` - feed counts into ranking.+- `src/mcp/brain/procedure-tools.ts` (`brain_skill_proposals`) - `usage` view.+- `src/cli/brain/verbs/skill-proposals.ts` - `usage` view.+- `tests/core/brain/skill-usage.test.ts`, a session-import test, an MCP test.++**Acceptance test.** Importing a session that invokes skill `release` three+times and `triage` once yields four `skill_invoked` records with distinct ids;+`deriveSkillUsage` reports `release:3, triage:1`; `brain_skill_proposals`+`operation:"usage"` returns the same counts; a vault with no invocations is+byte-identical (no records, empty usage). No LLM is called.++**Depends on.** None. Distinct from `t_6fc8663c` (verifier gate) and+`t_703f7b18` (outcome ranking).++---++## t_84500f39 - Guided first-run onboarding (last)++**Files.**+- `src/cli/onboarding.ts` (new) - `buildOnboardingChecklist(vault, config)` ->+ ordered steps (status, command, hint), computed from real state; renderer.+- `src/cli/main.ts` - extend `cmdInit` to render the checklist after the+ retained search block; add a re-runnable `onboarding` verb.+- `src/cli/command-manifest.ts` - register the verb.+- `tests/cli/onboarding.test.ts`, a `cmdInit` test.++**Acceptance test.** `buildOnboardingChecklist` on a bare vault marks+"persist config" done and "build search index", "set agent name", "record first+feedback" as todo, each with a copy-pasteable command; after indexing, the index+step flips to done; `o2b onboarding` re-runs the checklist any time; `o2b init`+still prints the existing search block plus the checklist. It reflects the same+doctor/notice signals the rest of the release exposes.++**Depends on.** `t_b3dc1454` (doctor remediation) and `t_5161e7ab` (notices) for+the surfaces it reuses; implemented last.diff --git a/docs/brainstorm/operability-first-run/variants.md b/docs/brainstorm/operability-first-run/variants.mdnew file mode 100644index 00000000..38c44e8b--- /dev/null+++ b/docs/brainstorm/operability-first-run/variants.md@@ -0,0 +1,99 @@+# Operability, Safety & First-Run - Architectural Variants++Three whole-release approaches for the eight in-scope tasks (guided+onboarding, config-validator remediation, runtime-state notices, hook+self-watchdog + fail-open inject, configurable 429 retry, expect/strict+mutation guards, hardened optional HTTP transport, per-skill invocation+telemetry). Hard constraint across all three: no new runtime dependency, no+ML runtime, kernel calls no LLM, safe-by-default HTTP.++## Variant 1 - Thin composition on existing seams++**Approach.** Each task extends the nearest existing module or seam rather+than introducing a subsystem:++- Retry budget: add `maxRetries` to the resolved embedding config, threaded+ through the existing `resolveSearchConfig` env/config reader and the+ existing `embedBatchWithRetry` loop. Raise the default 3 -> 6.+- Doctor remediation: add an optional `fix` field to the existing+ `CheckResult` shape; populate it in each failing `check*` branch; render it+ in the three existing consumers (`o2b doctor`, `vault_health`, OpenClaw).+- Runtime notices: a small deterministic collector rendered into the existing+ `active-inject` `additionalContext` surface and folded into the existing+ `vault_health` output. No new MCP tool.+- Hook resilience: a reusable process-ceiling primitive plus a fail-open+ context loader wired into the two lifecycle-hook entry points, reusing the+ existing `appendAuditRecord` writer.+- Mutation guards: a pure count-guard helper plus an opt-in content-equality+ short-circuit on the existing atomic writer, wired into the existing+ dry-run-capable ops and their CLI verbs.+- HTTP transport: harden the transport that already exists (`src/mcp/http.ts`)+ with a Host/Origin rebinding guard, a health endpoint, and an optional+ (loopback) / required (non-loopback) bearer.+- Skill telemetry: a new append-only continuity `kind` emitted from the+ existing session-import tool-call loop, derived read-side with the existing+ usage-signal decay math, surfaced through the existing+ `brain_skill_proposals` tool as a new view.+- Onboarding: extend the existing `cmdInit` post-init block into a state-driven+ multi-step checklist, reusing the doctor and notices surfaces, plus a+ re-runnable verb.++**Trade-offs.** Touches many files with small edits; each task is independently+testable and independently revertible. Preserves the codebase's narrow-module,+additive, byte-identical-when-off ethos and the frozen 98-tool MCP surface (no+tool added). Downside: the operability story is spread across the tree rather+than sitting in one named home, so the release's conceptual unity lives in the+docs, not in a package boundary.++**Complexity:** medium. **Risk:** low.++## Variant 2 - Unified operability core++**Approach.** Introduce `src/core/operability/` as a single cohesive+subsystem: notices, process watchdog, count-guard, doctor-remediation+catalogue, and onboarding checklist share types and helpers there, exposed+through one new MCP tool `brain_operability` with views (`doctor`, `notices`,+`onboarding`, `skill_usage`). The HTTP hardening and retry config still live+in their own modules but register their state through the operability core.++**Trade-offs.** Gives operability an obvious home and one discoverable tool;+future operability features have a clear landing zone. But it over-centralises+loosely-related concerns (a retry budget and a first-run checklist do not+belong to one module), fights the established narrow-module convention, and+grows the frozen MCP surface (98 -> 99), forcing the parity-test edits and a+deliberate surface-change decision. The single tool also becomes a+grab-bag with a wide `view` enum.++**Complexity:** large. **Risk:** medium.++## Variant 3 - Runtime-daemon-centric++**Approach.** Make the hardened HTTP transport the primary operability+surface: a long-lived server exposes `/health`, `/notices`, and `/doctor`+endpoints; the process watchdog and notices become server-side, pushed to+connected clients over SSE. Onboarding and the CLI doctor become thin clients+of the same endpoints.++**Trade-offs.** Elegant for HTTP consumers and centralises push. But it+couples first-run and CLI concerns to a running server, directly contradicts+the stdio-default / opt-in-HTTP posture the transport task mandates (the+transport must stay optional and off by default), and makes the safe-by-default+story harder (more surface listening). Heaviest to build and test; the+first-run experience should not require a daemon.++**Complexity:** large. **Risk:** high.++## Recommended: Variant 1++Variant 1 matches how every prior release in this codebase shipped: additive+surfaces, byte-identical when off, no new dependency, each task landing on the+seam nearest its concern with its own acceptance test. It keeps the frozen MCP+tool surface intact (notices fold into `vault_health`; skill usage folds into+`brain_skill_proposals`), which avoids a surface-change decision that the scope+does not require. It also isolates the one security-sensitive surface (the HTTP+transport) as a self-contained hardening of an existing module, so its guard+logic is reviewed and tested in one place rather than spread across a new+subsystem. Variant 2's unified core is attractive conceptually but buys+coupling and frozen-surface churn for concerns that are only thematically+related; Variant 3 inverts the transport task's own safe-by-default, opt-in+requirement. We take Variant 1.diff --git a/hooks/active-inject.ts b/hooks/active-inject.tsindex 96fa363c..9db80c6d 100644--- a/hooks/active-inject.ts+++ b/hooks/active-inject.ts@@ -28,6 +28,7 @@*/import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";import { resolveVault } from "../src/core/config.ts";import { parseFrontmatterText } from "../src/core/vault.ts";@@ -36,77 +37,155 @@ import { budgetActiveBody } from "../src/core/brain/active-budget.ts";import { INJECT_BUDGET_CHARS_DEFAULT, loadBrainConfig } from "../src/core/brain/policy.ts";import { healCliSymlinks } from "../src/cli/install-cli.ts";import { ensureVaultCurrent } from "../src/core/maintenance/ensure-current.ts";+import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";+import { appendAuditRecord } from "../src/core/reliability/audit.ts";+import { loadInjectContextFailOpen } from "../src/core/brain/inject-failopen.ts";+import { collectRuntimeNotices, renderRuntimeNotices } from "../src/core/brain/runtime-notices.ts";import { asHookPayload, readHookInput } from "./lib/stdin.ts";import { isContextEventName } from "./lib/context-events.ts";-async function main(): Promise<void> {- let payload;+/**+ * Best-effort hook audit line. Never throws: a failure to record must never+ * disturb the fail-soft hook contract, and a hung filesystem is exactly when+ * this runs, so it is wrapped defensively.+ */+function auditHook(vault: string | null, action: string, details: Record<string, unknown>): void {+ if (vault === null) return;try {- payload = asHookPayload(await readHookInput());+ appendAuditRecord(join(vault, ".open-second-brain", "hook-audit"), {+ timestamp: new Date().toISOString(),+ actor: "active-inject",+ action,+ target: "SessionStart",+ ok: false,+ details,+ });} catch {- return;+ // best-effort}+}- // The hook is registered separately for each event; the payload's- // `hook_event_name` tells us which one fired. Default to- // `SessionStart` only when the field is missing entirely (e.g. an- // empty stdin payload, or a runtime that doesn't populate the name).- const hookEventName =- typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0- ? payload.hook_event_name- : "SessionStart";-- // Default-closed allowlist: only event names whose output schema- // accepts `additionalContext` may produce stdout. Emitting under- // any other name (PostCompact included) is rejected by the runtime- // and echoes the full payload back as a validation error - the- // post-compaction path is the SessionStart `compact` matcher.- if (!isContextEventName(hookEventName)) return;-- // Self-heal the ~/.local/bin CLI symlinks on SessionStart only: a plugin- // update can leave them dangling or pointing at an old version. Runs from- // the current checkout (resolved via $CLAUDE_PLUGIN_ROOT); strictly- // best-effort, and gated to SessionStart so PostCompact does not trigger- // avoidable filesystem side effects. Never affects the injection below.- if (hookEventName === "SessionStart") {+async function main(): Promise<void> {+ // Arm the process self-watchdog first so a hang anywhere below (vault+ // resolution, a stalled read, an overrunning assembly) still self-terminates+ // at the ceiling with a clean exit instead of orphaning the hook process.+ let auditVault: string | null = null;+ const disarm = armProcessCeiling({+ ceilingMs: resolveHookCeilingMs(),+ onExpire: () => auditHook(auditVault, "hook_ceiling_exceeded", { hook: "active-inject" }),+ });+ try {+ let payload;try {- healCliSymlinks();+ payload = asHookPayload(await readHookInput());} catch {- // ignore — opportunistic; must never disrupt the session+ return;}- }- const vault = resolveVault();- if (vault === null) return;+ // The hook is registered separately for each event; the payload's+ // `hook_event_name` tells us which one fired. Default to+ // `SessionStart` only when the field is missing entirely (e.g. an+ // empty stdin payload, or a runtime that doesn't populate the name).+ const hookEventName =+ typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0+ ? payload.hook_event_name+ : "SessionStart";++ // Default-closed allowlist: only event names whose output schema+ // accepts `additionalContext` may produce stdout. Emitting under+ // any other name (PostCompact included) is rejected by the runtime+ // and echoes the full payload back as a validation error - the+ // post-compaction path is the SessionStart `compact` matcher.+ if (!isContextEventName(hookEventName)) return;++ // Self-heal the ~/.local/bin CLI symlinks on SessionStart only: a plugin+ // update can leave them dangling or pointing at an old version. Runs from+ // the current checkout (resolved via $CLAUDE_PLUGIN_ROOT); strictly+ // best-effort, and gated to SessionStart so PostCompact does not trigger+ // avoidable filesystem side effects. Never affects the injection below.+ if (hookEventName === "SessionStart") {+ try {+ healCliSymlinks();+ } catch {+ // ignore — opportunistic; must never disrupt the session+ }+ }++ const vault = resolveVault();+ if (vault === null) return;+ auditVault = vault;++ // Hands-off post-upgrade maintenance on SessionStart: migrate a stale+ // _brain.yaml/_BRAIN.md and rebuild a stale/missing search index (the+ // reindex runs detached so it survives this short-lived hook). Best-effort,+ // never blocks injection. In background mode the synchronous part (brain+ // upgrade + spawning the reindex) completes before this awaits.+ if (hookEventName === "SessionStart") {+ // Fire-and-forget: never put maintenance on the hook's critical path.+ // background:true spawns the reindex detached; we do not await the result.+ void ensureVaultCurrent(vault, { background: true }).catch(() => {+ // opportunistic; must never disrupt the session+ });+ }- // Hands-off post-upgrade maintenance on SessionStart: migrate a stale- // _brain.yaml/_BRAIN.md and rebuild a stale/missing search index (the- // reindex runs detached so it survives this short-lived hook). Best-effort,- // never blocks injection. In background mode the synchronous part (brain- // upgrade + spawning the reindex) completes before this awaits.- if (hookEventName === "SessionStart") {- // Fire-and-forget: never put maintenance on the hook's critical path.- // background:true spawns the reindex detached; we do not await the result.- void ensureVaultCurrent(vault, { background: true }).catch(() => {- // opportunistic; must never disrupt the session+ // Fail-open context load: assemble the injected body inside a guard that+ // degrades to the last-good cache (or empty) on any error, never emitting+ // a partial or poisoned payload. A successful non-empty body refreshes the+ // last-good snapshot.+ const { context } = await loadInjectContextFailOpen({+ vault,+ key: "active",+ assemble: () => assembleActiveContext(vault),+ audit: (source) =>+ auditHook(vault, "inject_failopen_degraded", { hook: "active-inject", source }),});+ if (context.length === 0) return;++ const out = {+ hookSpecificOutput: {+ hookEventName,+ additionalContext: context,+ },+ };+ process.stdout.write(JSON.stringify(out) + "\n");+ } finally {+ disarm();}+}++/**+ * Assemble the injected context body. Returns an empty string when there is+ * legitimately nothing to inject (no active.md, empty body); throws on a+ * genuine read error so the fail-open loader degrades to the last-good cache.+ */+function assembleActiveContext(vault: string): string {+ // Runtime-state notices ride the same injection surface as active.md so the+ // agent is proactively aware of a degraded/transient condition (semantic+ // search fell back to lexical, index missing/rebuilding, read-only vault)+ // without a diagnostic round-trip. Best-effort and computed with no network;+ // an empty list keeps the injected body byte-identical to before.+ const noticesBlock = renderRuntimeNotices(collectRuntimeNotices(vault));const activePath = brainActivePath(vault);- if (!existsSync(activePath)) return;+ const activeBody = existsSync(activePath) ? readActiveBody(vault, activePath) : "";- let body: string;- try {- body = readFileSync(activePath, "utf8");- } catch {- return;- }+ const parts = [noticesBlock, activeBody].filter((p) => p.length > 0);+ return parts.join("\n\n");+}++/**+ * Read + budget the active.md / lessons.md body. Returns an empty string when+ * the body is empty; throws on a genuine read error (permissions, fs stall) so+ * the fail-open loader degrades to the last-good cache.+ */+function readActiveBody(vault: string, activePath: string): string {+ const body = readFileSync(activePath, "utf8");// Drop the `kind: brain-active / generated_at` frontmatter - it// carries no signal for the agent, only provenance for tooling.const [, fmBody] = parseFrontmatterText(body);const trimmed = fmBody.trim();- if (trimmed.length === 0) return;+ if (trimmed.length === 0) return "";// Injection budget (token-diet): a large preference set must not// flood the session preamble. Config errors fall back to the@@ -128,18 +207,9 @@ async function main(): Promise<void> {// the active-preferences injection above.const lessonsBody = readLessonsBody(brainLessonsPath(vault), budget);- const additionalContext =- lessonsBody === null- ? budgetActiveBody(trimmed, budget)- : `${budgetActiveBody(trimmed, budget)}\n\n${lessonsBody}`;-- const out = {- hookSpecificOutput: {- hookEventName,- additionalContext,- },- };- process.stdout.write(JSON.stringify(out) + "\n");+ return lessonsBody === null+ ? budgetActiveBody(trimmed, budget)+ : `${budgetActiveBody(trimmed, budget)}\n\n${lessonsBody}`;}/**diff --git a/hooks/lib/process-ceiling.ts b/hooks/lib/process-ceiling.tsnew file mode 100644index 00000000..2ae6c579--- /dev/null+++ b/hooks/lib/process-ceiling.ts@@ -0,0 +1,91 @@+/**+ * Process self-watchdog: a hard time ceiling a spawned hook arms on itself.+ *+ * Lifecycle hooks (session-start context injection, session capture) run as+ * short-lived processes in the host runtime. A hung hook (slow embedding,+ * stuck reindex, filesystem stall) must never orphan a process or block the+ * host agent indefinitely. Arming this ceiling guarantees the process exits+ * cleanly at the deadline instead of hanging forever.+ *+ * The timer is `unref`ed so it never itself keeps the process alive: on a+ * healthy run the hook finishes and exits normally well before the ceiling,+ * and `disarm()` clears the timer. The ceiling only fires when the process is+ * still alive at the deadline (blocked on async I/O), at which point it runs a+ * best-effort `onExpire` side effect (an audit line) and exits 0 - never a+ * partial or poisoned write, and never the blocking exit code.+ *+ * Note: a JavaScript timer cannot interrupt a fully-synchronous CPU hang on a+ * single thread; the realistic hook hangs are asynchronous (network fetch,+ * fs stall on a mounted volume), which this covers. The host runtime's own+ * per-hook timeout remains a second line of defence.+ */++export const DEFAULT_HOOK_CEILING_MS = 55_000;++/** Floor below which a configured ceiling is treated as a typo and ignored. */+const MIN_HOOK_CEILING_MS = 1_000;++/**+ * Resolve the hook time ceiling from the environment. A valid integer at or+ * above the floor wins; anything else (absent, non-numeric, below the floor)+ * falls back to the default so a typo can never disable the watchdog.+ */+export function resolveHookCeilingMs(+ env: Record<string, string | undefined> = process.env,+): number {+ const raw = env["OPEN_SECOND_BRAIN_HOOK_CEILING_MS"]?.trim();+ if (!raw) return DEFAULT_HOOK_CEILING_MS;+ const value = Number(raw);+ if (!Number.isFinite(value) || value < MIN_HOOK_CEILING_MS) return DEFAULT_HOOK_CEILING_MS;+ return Math.floor(value);+}++export interface ProcessCeilingOptions {+ /** Hard deadline in milliseconds. */+ readonly ceilingMs: number;+ /** Best-effort side effect run just before exit (e.g. an audit line). */+ readonly onExpire?: () => void;+ /** Exit hook; defaults to `process.exit`. Injectable for tests. */+ readonly exit?: (code: number) => void;+ /** Timer scheduler; defaults to an `unref`ed `setTimeout`. Injectable. */+ readonly setTimer?: (fn: () => void, ms: number) => unknown;+ /** Timer canceller; defaults to `clearTimeout`. Injectable. */+ readonly clearTimer?: (handle: unknown) => void;+}++/**+ * Arm the ceiling. Returns an idempotent `disarm()` the caller invokes in a+ * `finally` once the real work completes.+ */+export function armProcessCeiling(opts: ProcessCeilingOptions): () => void {+ const exit = opts.exit ?? ((code: number) => process.exit(code));+ const setTimer = opts.setTimer ?? defaultSetTimer;+ const clearTimer = opts.clearTimer ?? defaultClearTimer;++ const handle = setTimer(() => {+ try {+ opts.onExpire?.();+ } catch {+ // The audit side effect is best-effort; never let it block the exit.+ }+ exit(0);+ }, opts.ceilingMs);++ let disarmed = false;+ return () => {+ if (disarmed) return;+ disarmed = true;+ clearTimer(handle);+ };+}++function defaultSetTimer(fn: () => void, ms: number): unknown {+ const timer = setTimeout(fn, ms);+ // Do not let the ceiling itself keep the event loop alive.+ (timer as { unref?: () => void }).unref?.();+ return timer;+}++function defaultClearTimer(handle: unknown): void {+ clearTimeout(handle as ReturnType<typeof setTimeout>);+}diff --git a/hooks/session-capture.ts b/hooks/session-capture.tsindex 462ace8d..39e1757f 100644--- a/hooks/session-capture.ts+++ b/hooks/session-capture.ts@@ -5,24 +5,55 @@* intentionally silent so a hook problem never blocks the agent.*/+import { join } from "node:path";+import { resolveAgentName, resolveVault } from "../src/core/config.ts";import { captureSessionLifecycleEvent } from "../src/core/brain/session-lifecycle.ts";+import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";+import { appendAuditRecord } from "../src/core/reliability/audit.ts";import { normalizeHookPayload, readHookInput } from "./lib/stdin.ts";async function main(): Promise<void> {- const vault = resolveVault();- if (vault === null) return;- let payload: unknown;+ // Arm the process self-watchdog so a hung capture (stalled read, slow+ // continuity append) self-terminates at the ceiling instead of orphaning+ // the hook process or blocking the host agent.+ let auditVault: string | null = null;+ const disarm = armProcessCeiling({+ ceilingMs: resolveHookCeilingMs(),+ onExpire: () => {+ if (auditVault === null) return;+ try {+ appendAuditRecord(join(auditVault, ".open-second-brain", "hook-audit"), {+ timestamp: new Date().toISOString(),+ actor: "session-capture",+ action: "hook_ceiling_exceeded",+ target: "session-capture",+ ok: false,+ details: { hook: "session-capture" },+ });+ } catch {+ // best-effort+ }+ },+ });try {- payload = await readHookInput();- } catch {- payload = null;+ const vault = resolveVault();+ if (vault === null) return;+ auditVault = vault;+ let payload: unknown;+ try {+ payload = await readHookInput();+ } catch {+ payload = null;+ }+ // Normalize grok's camelCase payload to the internal snake_case shape so the+ // lifecycle capture reads the same fields it does for Claude Code and Codex.+ await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {+ agent: resolveAgentName(),+ });+ } finally {+ disarm();}- // Normalize grok's camelCase payload to the internal snake_case shape so the- // lifecycle capture reads the same fields it does for Claude Code and Codex.- await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {- agent: resolveAgentName(),- });}main().catch(() => {diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 9fe3b92d..9d8be38f 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.28.0",+ "version": "1.29.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 14794c5e..7108af6f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.28.0",+ "version": "1.29.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex b7bfe4ba..f257891f 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.28.0"+version: "1.29.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 5faa252c..83851e44 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.28.0",+ "version": "1.29.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex b7bfe4ba..f257891f 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.28.0"+version: "1.29.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex f79cb525..ab40e6f5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.28.0"+version = "1.29.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.tsindex 1b29a9a2..1af668da 100644--- a/src/cli/brain/verbs/dream.ts+++ b/src/cli/brain/verbs/dream.ts@@ -13,6 +13,7 @@import { resolveAgentName } from "../../../core/config.ts";import { dream } from "../../../core/brain/dream.ts";+import { CountGuardError, assertExpectedCount } from "../../../core/brain/count-guard.ts";import {applyDreamBundle,discardDreamBundle,@@ -39,6 +40,8 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {"dry-run": { type: "boolean" },now: { type: "string" },agent: { type: "string" },+ expect: { type: "string" },+ strict: { type: "boolean" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -179,6 +182,41 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {}// action === "run": the legacy inline pass.+ const expectRaw = flags["expect"] as string | undefined;+ let expect: number | null = null;+ if (expectRaw !== undefined) {+ const n = Number(expectRaw);+ if (!Number.isInteger(n) || n < 0) return fail("--expect must be a non-negative integer");+ expect = n;+ }+ const strict = flags["strict"] === true;+ // Only pay for a preview pass when a guard is requested.+ if (expect !== null || strict) {+ try {+ const preview = dream(vault, {+ ...(now !== null ? { now } : {}),+ dryRun: true,+ ...(agent ? { agentName: agent } : {}),+ });+ const matchList = [+ ...preview.new_unconfirmed,+ ...preview.confirmed,+ ...preview.retired.map((r) => r.id),+ ...preview.moved_to_processed,+ ];+ assertExpectedCount({+ matched: matchList.length,+ expect,+ strict,+ willMutate: !flags["dry-run"],+ matchList,+ });+ } catch (exc) {+ if (exc instanceof CountGuardError) return fail(exc.message);+ return fail(`dream preview failed: ${(exc as Error).message ?? exc}`);+ }+ }+let summary;try {summary = dream(vault, {diff --git a/src/cli/brain/verbs/forget-source.ts b/src/cli/brain/verbs/forget-source.tsindex bb77acf5..8f59c492 100644--- a/src/cli/brain/verbs/forget-source.ts+++ b/src/cli/brain/verbs/forget-source.ts@@ -12,6 +12,7 @@*/import { deleteBySource } from "../../../core/brain/source-cleanup.ts";+import { CountGuardError, assertExpectedCount } from "../../../core/brain/count-guard.ts";import { brainVerbContext, fail, info, ok, okJson, parse } from "../helpers.ts";export async function cmdBrainForgetSource(argv: string[]): Promise<number> {@@ -19,22 +20,55 @@ export async function cmdBrainForgetSource(argv: string[]): Promise<number> {vault: { type: "string" },confirm: { type: "boolean" },"include-originals": { type: "boolean" },+ expect: { type: "string" },+ strict: { type: "boolean" },json: { type: "boolean" },});const sourceFile = positional[0];if (!sourceFile) {return fail(- "usage: o2b brain forget-source <source> [--confirm] [--include-originals] [--json]",+ "usage: o2b brain forget-source <source> [--confirm] [--include-originals] " ++ "[--expect N] [--strict] [--json]",);}+ const expectRaw = flags["expect"] as string | undefined;+ let expect: number | null = null;+ if (expectRaw !== undefined) {+ const n = Number(expectRaw);+ if (!Number.isInteger(n) || n < 0) {+ return fail("--expect must be a non-negative integer");+ }+ expect = n;+ }+ const strict = flags["strict"] === true;+ const confirm = flags["confirm"] === true;+ const includeOriginals = flags["include-originals"] === true;+try {const { vault } = brainVerbContext(flags);- const plan = deleteBySource(vault, sourceFile, {- confirm: flags["confirm"] === true,- includeOriginals: flags["include-originals"] === true,- now: new Date(),+ const now = new Date();+ // Preview first so the count guard asserts the blast radius before any+ // deletion; only then confirm.+ const preview = deleteBySource(vault, sourceFile, {+ confirm: false,+ includeOriginals,+ now,+ });+ assertExpectedCount({+ matched: preview.blastRadius,+ expect,+ strict,+ willMutate: confirm,+ matchList: [+ ...preview.derived.map((e) => e.match ?? e.path),+ ...preview.mentions.map((e) => e.match ?? e.path),+ ...preview.originals,+ ],});+ const plan = confirm+ ? deleteBySource(vault, sourceFile, { confirm: true, includeOriginals, now })+ : preview;if (flags["json"]) {okJson({@@ -42,6 +76,8 @@ export async function cmdBrainForgetSource(argv: string[]): Promise<number> {confirmed: plan.confirmed,include_originals: plan.includeOriginals,blast_radius: plan.blastRadius,+ matched: plan.blastRadius,+ changed: plan.deleted.length,derived: plan.derived.map((e) => ({path: e.path,kind: e.kind,diff --git a/src/cli/brain/verbs/hygiene.ts b/src/cli/brain/verbs/hygiene.tsindex c779c8ad..3f2b5512 100644--- a/src/cli/brain/verbs/hygiene.ts+++ b/src/cli/brain/verbs/hygiene.ts@@ -12,6 +12,7 @@import { applyHygienePlan } from "../../../core/brain/hygiene/apply.ts";import { buildHygienePlan } from "../../../core/brain/hygiene/plan.ts";+import { assertExpectedCount } from "../../../core/brain/count-guard.ts";import { resolveConflictFindings } from "../../../core/brain/hygiene/resolve-conflicts.ts";import { runHygieneScan } from "../../../core/brain/hygiene/scan.ts";import {@@ -61,10 +62,21 @@ export async function cmdBrainHygiene(argv: string[]): Promise<number> {detectors: { type: "string" },ids: { type: "string" },"dry-run": { type: "boolean" },+ expect: { type: "string" },+ strict: { type: "boolean" },json: { type: "boolean" },});const { config, vault } = brainVerbContext(flags);+ const expectRaw = flags["expect"] as string | undefined;+ let expect: number | null = null;+ if (expectRaw !== undefined) {+ const n = Number(expectRaw);+ if (!Number.isInteger(n) || n < 0) return fail("--expect must be a non-negative integer");+ expect = n;+ }+ const strict = flags["strict"] === true;+let detectors: HygieneDetectorId[] | undefined;try {detectors = parseDetectors(flags["detectors"] as string | undefined);@@ -108,6 +120,17 @@ export async function cmdBrainHygiene(argv: string[]): Promise<number> {return fail("apply requires --ids <finding-id,...> from a prior scan");}const plan = buildHygienePlan(report, { ids });+ try {+ assertExpectedCount({+ matched: plan.selected.length,+ expect,+ strict,+ willMutate: !flags["dry-run"],+ matchList: plan.selected.map((finding) => finding.id),+ });+ } catch (exc) {+ return fail((exc as Error).message);+ }let result;try {result = await applyHygienePlan(vault, plan, {diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.tsindex faad3db2..8132f3d8 100644--- a/src/cli/brain/verbs/skill-proposals.ts+++ b/src/cli/brain/verbs/skill-proposals.ts@@ -4,6 +4,7 @@ import {listPendingSkillProposals,rejectSkillProposal,} from "../../../core/brain/skill-proposals.ts";+import { deriveSkillUsage } from "../../../core/brain/skill-usage.ts";import { CliError, brainVerbContext, parse } from "../helpers.ts";export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {@@ -13,7 +14,28 @@ export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {if (sub === "list") return list(rest);if (sub === "accept") return accept(rest);if (sub === "reject") return reject(rest);- throw new CliError("brain skill-proposals: expected learn, list, accept, or reject");+ if (sub === "usage") return usage(rest);+ throw new CliError("brain skill-proposals: expected learn, list, accept, reject, or usage");+}++function usage(argv: string[]): number {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const vault = brainVerbContext(flags).vault;+ const rows = deriveSkillUsage(vault);++ if (flags["json"]) {+ process.stdout.write(JSON.stringify({ total: rows.length, usage: rows }, null, 2) + "\n");+ return 0;+ }++ process.stdout.write(`${rows.length} skill(s) with recorded invocations:\n`);+ for (const row of rows) {+ process.stdout.write(` ${row.skill} invocations=${row.invocationCount}\n`);+ }+ return 0;}function learn(argv: string[]): number {diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 28c83e46..c6f8e668 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -44,6 +44,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("config", "string"),flag("repo", "string"),]),+ command("onboarding", "Show the guided first-run setup checklist", [+ flag("vault", "string"),+ flag("config", "string"),+ ]),command("export-config", "Write a redacted config snapshot", [flag("config", "string"),flag("output", "string"),diff --git a/src/cli/main.ts b/src/cli/main.tsindex 7ed4f1c8..21e631a2 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -49,10 +49,11 @@ import { planUninstall, renderPlan } from "./uninstall.ts";import { cmdInstall } from "./install/install.ts";import { cmdUninstallTarget } from "./install/uninstall-target.ts";import { cmdInitInteractive } from "./install/init-interactive.ts";+import { buildOnboardingChecklist, renderOnboardingChecklist } from "./onboarding.ts";import { CLI_COMMAND_MANIFEST, manifestForJson } from "./command-manifest.ts";import { COMPLETION_SHELLS, isCompletionShell, renderCompletions } from "./completions.ts";import { MCPServer } from "../mcp/server.ts";-import { startHttp } from "../mcp/http.ts";+import { startHttp, isLoopbackHost } from "../mcp/http.ts";import { serveStdio } from "../mcp/stdio.ts";import { SERVER_VERSION } from "../mcp/protocol.ts";import { buildToolTable } from "../mcp/tools.ts";@@ -160,6 +161,33 @@ async function cmdInit(argv: string[]): Promise<number> {process.stdout.write(`timezone persisted to: ${configPath}\n`);}writeSearchInitBlock(configPath);+ // Guided first-run onboarding: turn the bare init into a walked-through+ // checklist of state-aware next steps (t_84500f39). Additive - the search+ // block above is unchanged. Best-effort: a checklist failure must never fail+ // the init that already persisted config.+ try {+ const checklist = buildOnboardingChecklist(resolvedVault, { configPath });+ process.stdout.write(renderOnboardingChecklist(checklist));+ } catch {+ // onboarding is advisory; never break init+ }+ return 0;+}++async function cmdOnboarding(argv: string[]): Promise<number> {+ const { flags } = parseFlags(argv, {+ vault: { type: "string" },+ config: { type: "string" },+ json: { type: "boolean" },+ });+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();+ const vault = requireVault(flags["vault"] as string | undefined, config);+ const checklist = buildOnboardingChecklist(vault, { configPath: config });+ if (flags["json"]) {+ process.stdout.write(JSON.stringify(checklist, sortedReplacer, 2) + "\n");+ return 0;+ }+ process.stdout.write(renderOnboardingChecklist(checklist));return 0;}@@ -220,6 +248,7 @@ async function cmdDoctor(argv: string[]): Promise<number> {vault: { type: "string" },config: { type: "string" },repo: { type: "string" },+ json: { type: "boolean" },});const config = (flags["config"] as string | undefined) ?? defaultConfigPath();const vault = requireVault(flags["vault"] as string | undefined, config);@@ -235,12 +264,33 @@ async function cmdDoctor(argv: string[]): Promise<number> {process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);return 1;}- let allOk = true;+ const failed = results.filter((r) => !r.ok).length;++ if (flags["json"]) {+ const payload = {+ ok: failed === 0,+ checks: results.map((r) => ({+ name: r.name,+ ok: r.ok,+ message: r.message,+ ...(r.fix !== undefined ? { fix: r.fix } : {}),+ })),+ summary: { total: results.length, failed },+ };+ process.stdout.write(JSON.stringify(payload, sortedReplacer, 2) + "\n");+ return failed === 0 ? 0 : 1;+ }+for (const r of results) {process.stdout.write(`[${r.ok ? "OK" : "FAIL"}] ${r.name}: ${r.message}\n`);- if (!r.ok) allOk = false;- }- return allOk ? 0 : 1;+ // Attach the copy-pasteable remediation right under a failing check so an+ // operator can fix it without leaving the doctor output.+ if (!r.ok && r.fix) process.stdout.write(` fix: ${r.fix}\n`);+ }+ // Scriptable aggregate: a summary line plus the 0/1 exit make `o2b doctor`+ // usable as a setup/CI gate.+ process.stdout.write(`\ndoctor: ${results.length} checks, ${failed} failed\n`);+ return failed === 0 ? 0 : 1;}async function cmdExportConfig(argv: string[]): Promise<number> {@@ -437,8 +487,13 @@ async function cmdMcp(argv: string[]): Promise<number> {}const host = flags["host"] as string;const apiKey = flags["api-key"] as string | undefined;- if (transport === "http" && (apiKey === undefined || apiKey === "")) {- process.stderr.write("o2b mcp: --api-key is required when --transport http is used\n");+ // Bearer is optional on a loopback bind (the loopback bind + Host/Origin+ // rebinding guard are the baseline defence) but mandatory on a non-loopback+ // host, which would otherwise expose the Brain unauthenticated on the network.+ if (transport === "http" && !isLoopbackHost(host) && (apiKey === undefined || apiKey === "")) {+ process.stderr.write(+ "o2b mcp: --api-key is required when --transport http binds a non-loopback --host\n",+ );return 2;}@@ -807,6 +862,8 @@ const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set(["vault","discipline","partner",+ "doctor",+ "onboarding",]);async function dispatchCommand(command: string, rest: string[]): Promise<number> {@@ -818,6 +875,8 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>return await cmdInit(rest);case "doctor":return await cmdDoctor(rest);+ case "onboarding":+ return await cmdOnboarding(rest);case "export-config":return await cmdExportConfig(rest);case "index":diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.tsnew file mode 100644index 00000000..cde4c325--- /dev/null+++ b/src/cli/onboarding.ts@@ -0,0 +1,177 @@+/**+ * Guided first-run onboarding checklist (t_84500f39).+ *+ * A freshly initialized vault otherwise gets a single search-indexing hint.+ * This turns `o2b init` (and a re-runnable `o2b onboarding` verb) into a+ * walked-through setup: a state-driven, ordered list of next steps - vault+ * config, Brain scaffold, first index, agent identity, an optional embedding+ * key, a first feedback signal, importing existing sessions, and a health+ * check. Each step reports whether it is already satisfied and carries a+ * copy-pasteable command, so time-to-value is short for both human operators+ * and the agent driving onboarding. It reuses the same runtime-state notice+ * channel the rest of the release exposes. Deterministic; reads state only.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { discoverConfig } from "../core/config.ts";+import { resolveSearchConfig } from "../core/search/index.ts";+import {+ collectRuntimeNotices,+ renderRuntimeNotices,+ type RuntimeNotice,+} from "../core/brain/runtime-notices.ts";++export interface OnboardingStep {+ readonly id: string;+ readonly title: string;+ readonly done: boolean;+ /** Whether the step is advisory (does not gate `complete`). */+ readonly optional: boolean;+ /** Copy-pasteable command to advance the step, or null when informational. */+ readonly command: string | null;+ readonly hint: string;+}++export interface OnboardingChecklist {+ readonly vault: string;+ readonly steps: ReadonlyArray<OnboardingStep>;+ readonly notices: ReadonlyArray<RuntimeNotice>;+ /** True when every required (non-optional) step is satisfied. */+ readonly complete: boolean;+}++export interface OnboardingOptions {+ readonly configPath?: string;+ readonly env?: Record<string, string | undefined>;+}++/** Count markdown files under a vault-relative directory, 0 when absent. */+function countMarkdown(dir: string): number {+ if (!existsSync(dir)) return 0;+ try {+ return readdirSync(dir).filter((n) => n.endsWith(".md")).length;+ } catch {+ return 0;+ }+}++/**+ * Compute the onboarding checklist from the vault's real on-disk + config+ * state. Pure read: never writes, never calls the network or an LLM.+ */+export function buildOnboardingChecklist(+ vault: string,+ opts: OnboardingOptions = {},+): OnboardingChecklist {+ const config = discoverConfig(opts.configPath).data;+ const search = resolveSearchConfig({ vault, configPath: opts.configPath });++ const vaultConfigured = typeof config["vault"] === "string" && config["vault"].length > 0;+ const brainScaffolded = existsSync(join(vault, "Brain"));+ const indexBuilt = existsSync(search.dbPath);+ const agentNamed =+ (typeof config["agent_name"] === "string" && config["agent_name"].length > 0) ||+ (typeof config["agentName"] === "string" && config["agentName"].length > 0);+ // A local (or disabled) provider needs no embedding key, so semantic search+ // is "ready" without one - mirroring the runtime-notice `networked` logic.+ const networked = search.semantic.provider !== "local" && search.semantic.provider !== "disabled";+ const semanticReady = search.semantic.enabled && (!networked || Boolean(search.semantic.apiKey));+ const hasFirstSignal =+ countMarkdown(join(vault, "Brain", "preferences")) > 0 ||+ countMarkdown(join(vault, "Brain", "inbox")) > 0;++ const steps: OnboardingStep[] = [+ {+ id: "vault_configured",+ title: "Vault configured",+ done: vaultConfigured,+ optional: false,+ command: vaultConfigured ? null : `o2b init --vault "${vault}"`,+ hint: `Vault: ${vault}`,+ },+ {+ id: "scaffold_brain",+ title: "Scaffold the Brain layer",+ done: brainScaffolded,+ optional: false,+ command: brainScaffolded ? null : "o2b brain init",+ hint: "Creates Brain/ (preferences, inbox, log, ...).",+ },+ {+ id: "build_index",+ title: "Build the search index",+ done: indexBuilt,+ optional: false,+ command: indexBuilt ? null : "o2b search index",+ hint: "Lexical recall works once the index exists.",+ },+ {+ id: "agent_name",+ title: "Register an agent identity",+ done: agentNamed,+ optional: false,+ command: agentNamed ? null : `o2b init --vault "${vault}" --agent-name <your-agent>`,+ hint: "Signals and evidence are attributed to this name.",+ },+ {+ id: "semantic_search",+ title: "Enable semantic search (optional)",+ done: semanticReady,+ optional: true,+ command: semanticReady ? null : "o2b search check",+ hint: "Set an embedding key to add semantic recall on top of lexical.",+ },+ {+ id: "first_feedback",+ title: "Record a first feedback signal",+ done: hasFirstSignal,+ optional: false,+ command: hasFirstSignal ? null : 'o2b brain feedback positive <topic> "<principle>"',+ hint: "Teach the Brain one durable preference to prove the loop.",+ },+ {+ id: "import_sessions",+ title: "Import existing agent sessions (optional)",+ done: false,+ optional: true,+ command: "o2b brain import-session <path>",+ hint: "Replay past Claude Code / Codex / opencode logs into the Brain.",+ },+ {+ id: "verify",+ title: "Verify the setup",+ done: false,+ optional: true,+ command: "o2b doctor",+ hint: "Each failing check prints an exact remediation command.",+ },+ ];++ const complete = steps.every((s) => s.optional || s.done);+ const notices = collectRuntimeNotices(vault, {+ ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),+ ...(opts.env !== undefined ? { env: opts.env } : {}),+ });++ return { vault, steps, notices, complete };+}++/** Render the checklist as a human-readable block for the CLI. */+export function renderOnboardingChecklist(checklist: OnboardingChecklist): string {+ const lines: string[] = ["", "Next steps:"];+ for (const step of checklist.steps) {+ const box = step.done ? "[x]" : "[ ]";+ const tag = step.optional && !step.done ? " (optional)" : "";+ lines.push(` ${box} ${step.title}${tag}`);+ if (!step.done && step.command) lines.push(` run: ${step.command}`);+ }+ if (checklist.complete) {+ lines.push("", "All required steps are done. Your Second Brain is ready.");+ }+ const noticeBlock = renderRuntimeNotices(checklist.notices);+ if (noticeBlock.length > 0) lines.push("", noticeBlock);+ lines.push("");+ return lines.join("\n");+}diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.tsindex 5da7ae4d..e257038c 100644--- a/src/core/brain/continuity/types.ts+++ b/src/core/brain/continuity/types.ts@@ -26,6 +26,7 @@ export type ContinuityRecordKind =| "context_pack_outcome"| "host_memory_write"| "recall_observed_use"+ | "skill_invoked"| "source_invalidation";export type ContinuityPayload = Readonly<Record<string, unknown>>;diff --git a/src/core/brain/count-guard.ts b/src/core/brain/count-guard.tsnew file mode 100644index 00000000..71d381b2--- /dev/null+++ b/src/core/brain/count-guard.ts@@ -0,0 +1,82 @@+/**+ * Count guards for mutating operations.+ *+ * Ports the discipline from iwe's mutating markdown ops (not its block-query+ * DSL): an `--expect N` assertion that a mutation will touch exactly N items,+ * and a `--strict` mode that refuses any guardless mutation. On a mismatch the+ * operation aborts BEFORE writing, surfacing the actual match list so the+ * operator sees precisely what would have changed. Both guards default off, so+ * an op that passes neither is byte-identical to before.+ */++export class CountGuardError extends Error {+ readonly code = "COUNT_GUARD";+ readonly matched: number;+ readonly expected: number | null;+ readonly matchList: ReadonlyArray<string>;++ constructor(message: string, matched: number, expected: number | null, matchList: string[]) {+ super(message);+ this.name = "CountGuardError";+ this.matched = matched;+ this.expected = expected;+ this.matchList = matchList;+ }+}++export interface CountGuardOptions {+ /** How many items the operation matched / would touch. */+ readonly matched: number;+ /** `--expect N`: the asserted count. Absent/null means no assertion. */+ readonly expect?: number | null;+ /** `--strict`: refuse a mutation that carries no `--expect` guard. */+ readonly strict?: boolean;+ /** True when this call is about to actually mutate (not a dry-run). */+ readonly willMutate: boolean;+ /** The matched items, surfaced in the error so the operator sees them. */+ readonly matchList?: ReadonlyArray<string>;+}++/** Cap on how many match entries are inlined into the error message. */+const MATCH_LIST_PREVIEW = 20;++/**+ * Assert the guards. Throws {@link CountGuardError} on an `--expect` mismatch+ * or on a guardless mutation under `--strict`; otherwise returns. Call this+ * before performing the write, with the count the operation would touch.+ */+export function assertExpectedCount(opts: CountGuardOptions): void {+ const matchList = [...(opts.matchList ?? [])];+ const expected = opts.expect ?? null;++ if (expected !== null && expected !== opts.matched) {+ throw new CountGuardError(+ `--expect ${expected} but the operation matched ${opts.matched}; aborting without writing.` ++ renderMatchList(matchList),+ opts.matched,+ expected,+ matchList,+ );+ }++ if (opts.strict && expected === null && opts.willMutate) {+ throw new CountGuardError(+ `--strict refuses a guardless mutation: pass --expect ${opts.matched} to confirm the ` ++ `${opts.matched} matched item(s), or drop --strict.` ++ renderMatchList(matchList),+ opts.matched,+ null,+ matchList,+ );+ }+}++function renderMatchList(matchList: ReadonlyArray<string>): string {+ if (matchList.length === 0) return "";+ const shown = matchList.slice(0, MATCH_LIST_PREVIEW);+ const suffix =+ matchList.length > MATCH_LIST_PREVIEW+ ? `\n ... and ${matchList.length - MATCH_LIST_PREVIEW} more`+ : "";+ return `\nMatched:\n${shown.map((m) => ` - ${m}`).join("\n")}${suffix}`;+}diff --git a/src/core/brain/inject-failopen.ts b/src/core/brain/inject-failopen.tsnew file mode 100644index 00000000..952bac93--- /dev/null+++ b/src/core/brain/inject-failopen.ts@@ -0,0 +1,92 @@+/**+ * Fail-open context load for lifecycle-hook injection.+ *+ * When session-start context assembly overruns or throws (a slow embedding,+ * a stuck reindex, a filesystem stall), the inject path must degrade to the+ * last-good context or an empty context - never error noisily and never emit+ * a partial or poisoned payload. This module wraps an assembler with that+ * guarantee and keeps a durable last-good snapshot under the machine-local+ * `.open-second-brain/inject-cache/` directory.+ *+ * A successful non-empty assembly is written to the cache. A legitimately+ * empty assembly (nothing to inject this session) is NOT cached, so it never+ * clobbers a good snapshot a later error would degrade to. Only a thrown+ * assembly degrades, and it audits exactly once.+ */++import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteText } from "../fs-atomic.ts";++const INJECT_CACHE_DIR = ".open-second-brain";+const INJECT_CACHE_SUBDIR = "inject-cache";++function cachePath(vault: string, key: string): string {+ return join(vault, INJECT_CACHE_DIR, INJECT_CACHE_SUBDIR, `${key}.txt`);+}++/** Read the last-good injected body for `key`, or null when none/unreadable. */+export function readInjectCache(vault: string, key: string): string | null {+ const path = cachePath(vault, key);+ if (!existsSync(path)) return null;+ try {+ return readFileSync(path, "utf8");+ } catch {+ return null;+ }+}++/** Persist a last-good injected body. Best-effort: a write failure is swallowed. */+export function writeInjectCache(vault: string, key: string, body: string): void {+ try {+ atomicWriteText(cachePath(vault, key), body);+ } catch {+ // The cache is an optimization; a failure to persist must never disturb+ // the inject path.+ }+}++/** Where a degrade landed: a fresh assembly, the cached last-good, or empty. */+export type InjectContextSource = "fresh" | "cached" | "empty";++export interface FailOpenResult {+ readonly context: string;+ readonly degraded: boolean;+ readonly source: InjectContextSource;+}++export interface LoadInjectContextOptions {+ readonly vault: string;+ /** Cache key (e.g. the hook/surface name). */+ readonly key: string;+ /** Assembles the injected context. May be sync or async; may throw. */+ readonly assemble: () => string | Promise<string>;+ /** Called once when the load degrades (source: cached | empty). */+ readonly audit?: (source: Exclude<InjectContextSource, "fresh">, error: unknown) => void;+}++/**+ * Run `assemble` fail-open. On success return the assembled context (caching+ * it when non-empty). On any throw degrade to the last-good cache, or to empty+ * when no cache exists, auditing the degrade once.+ */+export async function loadInjectContextFailOpen(+ opts: LoadInjectContextOptions,+): Promise<FailOpenResult> {+ try {+ const context = await opts.assemble();+ if (context.length > 0) {+ writeInjectCache(opts.vault, opts.key, context);+ }+ return { context, degraded: false, source: "fresh" };+ } catch (error) {+ const cached = readInjectCache(opts.vault, opts.key);+ if (cached !== null && cached.length > 0) {+ opts.audit?.("cached", error);+ return { context: cached, degraded: true, source: "cached" };+ }+ opts.audit?.("empty", error);+ return { context: "", degraded: true, source: "empty" };+ }+}diff --git a/src/core/brain/runtime-notices.ts b/src/core/brain/runtime-notices.tsnew file mode 100644index 00000000..c7cf94fa--- /dev/null+++ b/src/core/brain/runtime-notices.ts@@ -0,0 +1,124 @@+/**+ * Runtime-state notice channel.+ *+ * Open Second Brain's health signals are otherwise pull-only (brain_doctor,+ * brain_health, vault_health): the agent must poll to learn that semantic+ * search fell back to lexical, that the index is not built or is rebuilding,+ * or that the vault is read-only. This collector computes those transient+ * conditions deterministically - no network, no LLM, no DB open - so they can+ * ride the existing SessionStart injection surface (and vault_health) as a+ * proactive push, letting the agent adjust behaviour without a diagnostic+ * round-trip.+ *+ * Notices only exist while a real condition holds, so a healthy vault yields+ * none and the injected context stays byte-identical. Scope is OSB's own+ * subsystems (embeddings/index availability, read-only mode); it is not a+ * third-party plugin notice bus and does not classify quota errors.+ */++import { existsSync } from "node:fs";++import lockfile from "proper-lockfile";++import { resolveSearchConfig } from "../search/index.ts";+import { checkVaultWriteable } from "../doctor.ts";++export type RuntimeNoticeSeverity = "info" | "warning";++export interface RuntimeNotice {+ readonly code: string;+ readonly severity: RuntimeNoticeSeverity;+ readonly message: string;+}++export interface RuntimeNoticeOptions {+ readonly configPath?: string;+ readonly env?: Record<string, string | undefined>;+}++/**+ * Collect the current runtime-state notices for `vault`. Never throws: any+ * probe failure is swallowed so the channel can be called from the fail-soft+ * inject path. Returns an empty list when everything is nominal or when the+ * channel is opted out via `OPEN_SECOND_BRAIN_RUNTIME_NOTICES`.+ */+export function collectRuntimeNotices(+ vault: string,+ opts: RuntimeNoticeOptions = {},+): RuntimeNotice[] {+ const env = opts.env ?? process.env;+ const optOut = env["OPEN_SECOND_BRAIN_RUNTIME_NOTICES"]?.trim().toLowerCase();+ if (optOut === "false" || optOut === "0") return [];++ const notices: RuntimeNotice[] = [];++ // Vault writability: a read-only vault means every memory write will fail.+ try {+ const writeable = checkVaultWriteable(vault);+ if (!writeable.ok) {+ notices.push({+ code: "vault_read_only",+ severity: "warning",+ message: `Vault is not writable, so memory writes will fail (${writeable.message}). Fix permissions on ${vault} or point VAULT_DIR at a writable vault.`,+ });+ }+ } catch {+ // best-effort+ }++ // Search index availability + semantic degradation.+ try {+ const config = resolveSearchConfig({ vault, configPath: opts.configPath });+ const dbPath = config.dbPath;+ const indexExists = existsSync(dbPath);++ if (!indexExists) {+ notices.push({+ code: "search_index_missing",+ severity: "info",+ message: "Search index is not built yet, so recall returns nothing. Run: o2b search index",+ });+ } else if (reindexInProgress(dbPath)) {+ notices.push({+ code: "reindex_in_progress",+ severity: "info",+ message: "Search index is rebuilding; recent recall results may lag until it completes.",+ });+ }++ const semantic = config.semantic;+ const networked = semantic.provider !== "local" && semantic.provider !== "disabled";+ if (semantic.enabled && networked && !semantic.apiKey) {+ notices.push({+ code: "semantic_degraded",+ severity: "warning",+ message:+ "Semantic search is enabled but no embedding key resolved, so search has fallen back to lexical. Run: o2b search check",+ });+ }+ } catch {+ // best-effort+ }++ return notices;+}++/**+ * A live reindex holds a heartbeated writer lock on the index path (see+ * search/store.ts). Detecting a non-stale lock is the "reindex in progress"+ * signal. Best-effort: any probe error means "not detectable", not a notice.+ */+function reindexInProgress(dbPath: string): boolean {+ try {+ return lockfile.checkSync(dbPath, { realpath: false });+ } catch {+ return false;+ }+}++/** Render notices as a compact injectable block; empty string when clean. */+export function renderRuntimeNotices(notices: ReadonlyArray<RuntimeNotice>): string {+ if (notices.length === 0) return "";+ const lines = notices.map((n) => `- [${n.severity}] ${n.message}`);+ return `Runtime notices:\n${lines.join("\n")}`;+}diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex f94c887d..a99c9bfe 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -29,6 +29,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "nodeimport { basename, join, resolve } from "node:path";import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";+import { appendContinuityRecord } from "../continuity/store.ts";import { discoverMarkersDetailed } from "../inline.ts";import { writeSignal } from "../signal.ts";import { importSessionRecall } from "../session-recall.ts";@@ -39,6 +40,7 @@ import {SessionImportError,type SessionAdapter,type SessionAdapterId,+ type SessionToolCall,type SessionTurn,} from "./types.ts";import { validateBrainFeedbackInput } from "./validate-feedback.ts";@@ -137,6 +139,8 @@ export interface ImportSessionResult {readonly signals_created: number;readonly signals_deduped: number;readonly tool_replays: number;+ /** Per-skill invocations captured as skill_invoked continuity records. */+ readonly skill_invocations: number;readonly malformed: number;readonly filtered_turns: number;/** Capture-boundary verdict for this file (Memory Integrity Suite). */@@ -222,6 +226,7 @@ export async function importSession(let signalsCreated = 0;let signalsDeduped = 0;let toolReplays = 0;+ let skillInvocations = 0;let malformed = 0;let filteredTurns = 0;let suppressedTurns = 0;@@ -313,6 +318,7 @@ export async function importSession(signals_created: 0,signals_deduped: 0,tool_replays: 0,+ skill_invocations: 0,malformed: 0,filtered_turns: 0,boundary_decision: boundaryDecision,@@ -394,6 +400,30 @@ export async function importSession(// Path B — brain_feedback tool_use replay.if (!mayWrite) continue;for (const call of turn.toolCalls ?? []) {+ // Per-skill invocation telemetry (t_56a12bde): count real skill+ // invocations across runtimes as append-only skill_invoked records.+ // Deterministic and idempotent across re-imports (the source ref keys on+ // the session + call id + skill, so re-running dedupes rather than+ // double-counts). Skipped on a dry run.+ const invokedSkill = resolveInvokedSkill(call);+ if (invokedSkill !== null && opts.dryRun !== true) {+ try {+ appendContinuityRecord(vault, {+ kind: "skill_invoked",+ createdAt: invocationTimestamp(turn.timestamp, now),+ sourceRefs: [{ id: `${sessionKey}:${call.id ?? turn.turnId}:${invokedSkill}` }],+ payload: {+ skill: invokedSkill,+ agent: agentLabelForTurn(turn, adapter.id, opts.agent),+ tool: call.name,+ runtime: adapter.id,+ },+ });+ skillInvocations++;+ } catch {+ // Telemetry is best-effort; a failed append never fails the import.+ }+ }if (call.name !== "brain_feedback") continue;const validated = validateBrainFeedbackInput(call.input);if (!validated.ok) {@@ -460,6 +490,7 @@ export async function importSession(signals_created: signalsCreated,signals_deduped: signalsDeduped,tool_replays: toolReplays,+ skill_invocations: skillInvocations,malformed,boundary_decision: boundaryDecision,suppressed_turns: suppressedTurns,@@ -483,6 +514,38 @@ function agentLabelForTurn(turn: SessionTurn, adapter: SessionAdapterId, fallbacreturn getAdapter(adapter).defaultAgent.trim() || fallback;}+/**+ * Extract the invoked skill name from a tool call, or null when the call is+ * not a skill invocation. Counts an actual skill fetch (`get_skill`, however+ * namespaced by the runtime) and the host-native `Skill` tool; discovery+ * (`list_skills`) and per-turn relevance scoring (`skills_attach`) are not+ * invocations and are ignored.+ */+function resolveInvokedSkill(call: SessionToolCall): string | null {+ const input = call.input ?? {};+ const pick = (key: string): string | null => {+ const value = input[key];+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;+ };+ const name = call.name;+ if (name === "get_skill" || name.endsWith("__get_skill")) {+ return pick("name") ?? pick("skill");+ }+ if (name === "Skill") {+ return pick("command") ?? pick("skill") ?? pick("name");+ }+ return null;+}++/** ISO-second timestamp for an invocation: the turn's own time when valid. */+function invocationTimestamp(turnTimestamp: string | undefined, now: Date): string {+ if (turnTimestamp) {+ const ms = Date.parse(turnTimestamp);+ if (Number.isFinite(ms) && ms > 0 && ms <= now.getTime()) return isoSecond(new Date(ms));+ }+ return isoSecond(now);+}+export async function importSessionPath(vault: string,path: string,diff --git a/src/core/brain/skill-usage.ts b/src/core/brain/skill-usage.tsnew file mode 100644index 00000000..5aa8f6c4--- /dev/null+++ b/src/core/brain/skill-usage.ts@@ -0,0 +1,85 @@+/**+ * Per-skill invocation telemetry (t_56a12bde).+ *+ * How often each installed skill is actually invoked by an agent runtime is a+ * usage signal distinct from proposing, ranking, or verifying skills. Each+ * invocation is captured as an append-only `skill_invoked` continuity record+ * (emitted by the session-import tool-call scan across Claude Code / opencode+ * logs). Counts are DERIVED read-side here - a replayable aggregation, never a+ * mutated counter - mirroring the working-memory usage-signal shape, so the+ * dream / synthesis pass can rank, retain, or retire skills on real evidence.+ * Deterministic; no LLM.+ */++import { loadNormalizedContinuityRecords } from "./continuity/read-model.ts";+import { decayWeight } from "./continuity/usage-signal.ts";++export interface SkillUsage {+ readonly skill: string;+ /** How many times the skill was invoked across all captured runtimes. */+ readonly invocationCount: number;+ /** Most recent invocation time, epoch ms, or null when never dated. */+ readonly lastInvokedAtMs: number | null;+ /** Recency/frequency decay weight in (0, 1], for ranking. */+ readonly weight: number;+}++interface MutableUsage {+ count: number;+ firstAtMs: number | null;+ lastAtMs: number | null;+}++/**+ * Derive per-skill invocation counts from `skill_invoked` continuity records.+ * Ranked by count descending, then skill name ascending for stable output.+ */+export function deriveSkillUsage(vault: string, opts: { nowMs?: number } = {}): SkillUsage[] {+ const records = loadNormalizedContinuityRecords(vault, { kind: "skill_invoked" });+ const bySkill = new Map<string, MutableUsage>();+ // Continuity logs are append-only with no write-time dedup, so a re-imported+ // session re-appends byte-identical records. Their content-addressed id+ // (kind + createdAt + sourceRefs + payload) is stable, so counting DISTINCT+ // ids makes the derivation idempotent across re-imports.+ const seen = new Set<string>();++ for (const record of records) {+ if (seen.has(record.id)) continue;+ seen.add(record.id);+ const skill = typeof record.payload["skill"] === "string" ? record.payload["skill"] : null;+ if (skill === null || skill.length === 0) continue;+ const atMs = Date.parse(record.createdAt);+ const dated = Number.isFinite(atMs) ? atMs : null;+ const entry = bySkill.get(skill) ?? { count: 0, firstAtMs: null, lastAtMs: null };+ entry.count += 1;+ if (dated !== null) {+ entry.firstAtMs = entry.firstAtMs === null ? dated : Math.min(entry.firstAtMs, dated);+ entry.lastAtMs = entry.lastAtMs === null ? dated : Math.max(entry.lastAtMs, dated);+ }+ bySkill.set(skill, entry);+ }++ const nowMs = opts.nowMs ?? Date.now();+ const usage: SkillUsage[] = [];+ for (const [skill, entry] of bySkill) {+ // Decay from the creation baseline with the invocation count as the+ // frequency signal, reusing the shared working-memory decay curve.+ const weight = decayWeight(+ {+ createdAtMs: entry.firstAtMs ?? nowMs,+ accessCount: entry.count,+ lastAccessAtMs: entry.lastAtMs,+ },+ nowMs,+ );+ usage.push({+ skill,+ invocationCount: entry.count,+ lastInvokedAtMs: entry.lastAtMs,+ weight,+ });+ }++ usage.sort((a, b) => b.invocationCount - a.invocationCount || a.skill.localeCompare(b.skill));+ return usage;+}diff --git a/src/core/doctor.ts b/src/core/doctor.tsindex 2d75672a..c53b5879 100644--- a/src/core/doctor.ts+++ b/src/core/doctor.ts@@ -21,9 +21,21 @@ import { isFile } from "./fs-utils.ts";import { checkCodegraph } from "./partner/codegraph.ts";import type { CheckResult } from "./types.ts";+/**+ * Shipped plugin manifests are generated artifacts, not hand-edited files, so+ * a missing / malformed / schema-invalid manifest is repaired by re-syncing+ * the plugin checkout rather than a bespoke per-file edit.+ */+const MANIFEST_FIX = "o2b update";+export function checkVaultWriteable(vault: string): CheckResult {if (!existsSync(vault)) {- return { name: "vault_writeable", ok: false, message: `vault directory missing: ${vault}` };+ return {+ name: "vault_writeable",+ ok: false,+ message: `vault directory missing: ${vault}`,+ fix: `mkdir -p "${vault}"`,+ };}const probe = join(vault, ".open-second-brain-doctor-test");try {@@ -35,6 +47,7 @@ export function checkVaultWriteable(vault: string): CheckResult {name: "vault_writeable",ok: false,message: `cannot write to vault: ${(exc as Error).message ?? exc}`,+ fix: `chmod u+rwx "${vault}"`,};}return { name: "vault_writeable", ok: true, message: `vault exists and is writable: ${vault}` };@@ -54,6 +67,7 @@ export function checkConfigWriteable(config: string): CheckResult {name: "config_writeable",ok: false,message: `cannot write config ${config}: ${(exc as Error).message ?? exc}`,+ fix: `mkdir -p "${dirname(config)}" && chmod u+rwx "${dirname(config)}"`,};}return { name: "config_writeable", ok: true, message: `config writable: ${config}` };@@ -67,7 +81,7 @@ interface JsonLoadResult {function loadJsonManifest(path: string, name: string): JsonLoadResult {if (!isFile(path)) {return {- result: { name, ok: false, message: `missing: ${path}` },+ result: { name, ok: false, message: `missing: ${path}`, fix: MANIFEST_FIX },data: null,};}@@ -76,13 +90,18 @@ function loadJsonManifest(path: string, name: string): JsonLoadResult {data = JSON.parse(readFileSync(path, "utf8"));} catch (exc) {return {- result: { name, ok: false, message: `invalid JSON: ${path} (${(exc as Error).message})` },+ result: {+ name,+ ok: false,+ message: `invalid JSON: ${path} (${(exc as Error).message})`,+ fix: MANIFEST_FIX,+ },data: null,};}if (!data || typeof data !== "object" || Array.isArray(data)) {return {- result: { name, ok: false, message: `invalid manifest object: ${path}` },+ result: { name, ok: false, message: `invalid manifest object: ${path}`, fix: MANIFEST_FIX },data: null,};}@@ -150,6 +169,7 @@ export function checkCodexManifest(path: string): CheckResult {name: "codex_manifest",ok: false,message: `schema invalid: ${path} (${problems.join("; ")})`,+ fix: MANIFEST_FIX,};}return { name: "codex_manifest", ok: true, message: `valid Codex manifest: ${path}` };@@ -203,6 +223,7 @@ export function checkClaudeManifest(path: string): CheckResult {name: "claude_manifest",ok: false,message: `schema invalid: ${path} (${problems.join("; ")})`,+ fix: MANIFEST_FIX,};}return { name: "claude_manifest", ok: true, message: `valid Claude manifest: ${path}` };@@ -210,7 +231,7 @@ export function checkClaudeManifest(path: string): CheckResult {export function checkHermesManifest(path: string): CheckResult {if (!isFile(path)) {- return { name: "hermes_manifest", ok: false, message: `missing: ${path}` };+ return { name: "hermes_manifest", ok: false, message: `missing: ${path}`, fix: MANIFEST_FIX };}let text: string;try {@@ -220,6 +241,7 @@ export function checkHermesManifest(path: string): CheckResult {name: "hermes_manifest",ok: false,message: `invalid text: ${path} (${(exc as Error).message ?? exc})`,+ fix: MANIFEST_FIX,};}const required = ["name", "version", "description"];@@ -232,6 +254,7 @@ export function checkHermesManifest(path: string): CheckResult {name: "hermes_manifest",ok: false,message: `schema invalid: ${path} (missing ${missing.join(", ")})`,+ fix: MANIFEST_FIX,};}return { name: "hermes_manifest", ok: true, message: `readable Hermes manifest: ${path}` };@@ -253,6 +276,7 @@ export function checkOpenclawManifest(path: string): CheckResult {name: "openclaw_manifest",ok: false,message: `schema invalid: ${path} (${problems.join("; ")})`,+ fix: MANIFEST_FIX,};}return { name: "openclaw_manifest", ok: true, message: `valid OpenClaw manifest: ${path}` };@@ -276,6 +300,7 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {name: "openclaw_package_json_extensions",ok: false,message: "package.json missing or empty openclaw.extensions array",+ fix: MANIFEST_FIX,});return results;}@@ -291,6 +316,7 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {name: `openclaw_entry_invalid_${typeof entry}`,ok: false,message: `extension entry must be a string, got: ${typeof entry}`,+ fix: MANIFEST_FIX,});continue;}@@ -306,6 +332,7 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {name: `openclaw_entry_${entry}`,ok: false,message: `missing extension entry: ${entry}`,+ fix: MANIFEST_FIX,});}}diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.tsindex 6672b96e..54b4d8c1 100644--- a/src/core/fs-atomic.ts+++ b/src/core/fs-atomic.ts@@ -13,22 +13,57 @@import {closeSync,+ existsSync,fsyncSync,linkSync,mkdirSync,openSync,+ readFileSync,renameSync,unlinkSync,writeSync,} from "node:fs";import { basename, dirname, join } from "node:path";-export function atomicWriteFileSync(target: string, contents: string): void {+export interface AtomicWriteOptions {+ /**+ * Skip the write when the target already holds byte-identical content. Off+ * by default (a write always happens). When on, an unchanged target is left+ * untouched - no temp file, no rename, no mtime bump - which stops spurious+ * churn in a vault the user is also hand-editing.+ */+ readonly skipIfUnchanged?: boolean;+}++/**+ * Atomic overwrite. Returns `true` when it wrote, `false` when+ * `skipIfUnchanged` short-circuited an identical write.+ */+export function atomicWriteFileSync(+ target: string,+ contents: string,+ opts: AtomicWriteOptions = {},+): boolean {+ if (opts.skipIfUnchanged && isUnchanged(target, contents)) return false;withTempFile(target, contents, (tmpPath) => {// POSIX `rename(2)` is atomic and clobbers an existing target — that's// exactly the "overwrite" semantic we want. No exclusivity guarantee.renameSync(tmpPath, target);});+ return true;+}++/**+ * True when `target` exists and already holds byte-identical `contents`. A+ * read error is treated as "changed" so a genuine write still proceeds.+ */+function isUnchanged(target: string, contents: string): boolean {+ if (!existsSync(target)) return false;+ try {+ return readFileSync(target, "utf8") === contents;+ } catch {+ return false;+ }}export interface AtomicWriteTextOptions {@@ -41,20 +76,28 @@ export interface AtomicWriteTextOptions {* persist a payload their own parser would reject.*/readonly validate?: (candidate: string) => void;+ /**+ * Skip the write when the target already holds byte-identical content.+ * Off by default. The validate hook still runs first so a rejected+ * payload never counts as "unchanged".+ */+ readonly skipIfUnchanged?: boolean;}/*** Validated atomic overwrite for sensitive text files (configs,* schema documents). Same temp-file + fsync + rename pipeline as* {@link atomicWriteFileSync}, plus a validation hook and a private- * default mode.+ * default mode. Returns `true` when it wrote, `false` when+ * `skipIfUnchanged` short-circuited an identical write.*/export function atomicWriteText(targetPath: string,candidate: string,opts: AtomicWriteTextOptions = {},-): void {+): boolean {opts.validate?.(candidate);+ if (opts.skipIfUnchanged && isUnchanged(targetPath, candidate)) return false;withTempFile(targetPath,candidate,@@ -63,6 +106,7 @@ export function atomicWriteText(},opts.mode ?? 0o600,);+ return true;}/**diff --git a/src/core/search/embeddings/openai-compat.ts b/src/core/search/embeddings/openai-compat.tsindex 1cb84e3e..23fd882c 100644--- a/src/core/search/embeddings/openai-compat.ts+++ b/src/core/search/embeddings/openai-compat.ts@@ -128,6 +128,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {const vectors = await this.embedBatchWithRetry(batch.map((b) => b.text),{+ maxAttempts: this.config.maxRetries,parentSignal: cancel.signal,},);diff --git a/src/core/search/embeddings/zeroentropy.ts b/src/core/search/embeddings/zeroentropy.tsindex 85133747..d6a4c3dd 100644--- a/src/core/search/embeddings/zeroentropy.ts+++ b/src/core/search/embeddings/zeroentropy.ts@@ -111,7 +111,7 @@ export class ZeroEntropyProvider implements EmbeddingProvider {if (cancel.signal.aborted) return;const vectors = await this.embedBatchWithRetry(batch.map((b) => b.text),- { parentSignal: cancel.signal },+ { maxAttempts: this.config.maxRetries, parentSignal: cancel.signal },);for (let i = 0; i < vectors.length; i++) {out[batch[i]!.originalIndex] = vectors[i]!;diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex af3cfa24..c3c0ddfe 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -138,6 +138,7 @@ const DEFAULTS = {timeoutMs: 10_000,concurrency: 4,batchSize: 32,+ maxRetries: 6,costGateUsd: 0,mmrLambda: 0.7,maxHops: 1,@@ -293,6 +294,9 @@ function validateResolvedConfig(config: ResolvedSearchConfig): void {validateIntegerRange(config.semantic.batchSize, "embedding_batch_size", {min: 1,});+ validateIntegerRange(config.semantic.maxRetries, "embedding_max_retries", {+ min: 1,+ });}function parseProvider(raw: string | null): ResolvedEmbeddingConfig["provider"] {@@ -457,6 +461,12 @@ export function resolveSearchConfig(opts: {"embedding_batch_size",{ min: 1 },);+ const maxRetries = parseInteger(+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES", "embedding_max_retries"),+ DEFAULTS.maxRetries,+ "embedding_max_retries",+ { min: 1 },+ );const costGateUsd = parseNonNegativeFloat(envOrConfig(env, config, "OPEN_SECOND_BRAIN_EMBEDDING_COST_GATE", "embedding_cost_gate_usd"),DEFAULTS.costGateUsd,@@ -474,6 +484,7 @@ export function resolveSearchConfig(opts: {timeoutMs,concurrency,batchSize,+ maxRetries,costGateUsd,});diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex d29870ab..72323f55 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -587,6 +587,15 @@ export interface ResolvedEmbeddingConfig {readonly timeoutMs: number;readonly concurrency: number;readonly batchSize: number;+ /**+ * Per-batch transient-retry budget (attempts, not extra retries) for+ * 429 / 5xx / network errors. Default 6, raised from the former hardcoded+ * 3 so an agent reindexing against a strict-RPM embedding account does not+ * exhaust the budget and silently drop chunks. Configurable via+ * `embedding_max_retries` / `OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES`.+ * Multi-key auth failover (`apiKeys`) is independent of this count.+ */+ readonly maxRetries: number;/*** Spend ceiling in USD for a single embedding run (Embedding Provider* Suite). 0 (default) disables the gate. When positive, an embeddingdiff --git a/src/core/types.ts b/src/core/types.tsindex 0ef75bf2..23bc8917 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -18,6 +18,13 @@ export interface CheckResult {readonly name: string;readonly ok: boolean;readonly message: string;+ /**+ * Optional copy-pasteable remediation command for a failing check, turning+ * the doctor from a diagnostic into a self-service repair tool. Present only+ * on failures with a deterministic fix; omitted on passing checks and on+ * failures with no single obvious command.+ */+ readonly fix?: string;}/** Outcome pair from `installCli`. */diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 6b7942b8..374f5b79 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -47,7 +47,7 @@ import {type ObservedUseEntry,} from "../../core/brain/observed-use.ts";import { coerceStr, coerceBool, coerceIsoDate } from "../coerce.ts";-import { vaultRelativeSafe } from "./shared.ts";+import { enforceCountGuard, readCountGuardArgs, vaultRelativeSafe } from "./shared.ts";/*** Build the slug used in the signal / preference filename. We never let@@ -242,6 +242,21 @@ async function toolBrainFeedback(// ----- brain_dream ---------------------------------------------------------+/** The set of preference ids a dream summary would create/confirm/retire/move. */+function dreamChangeList(summary: {+ readonly new_unconfirmed: ReadonlyArray<string>;+ readonly confirmed: ReadonlyArray<string>;+ readonly retired: ReadonlyArray<{ readonly id: string }>;+ readonly moved_to_processed: ReadonlyArray<string>;+}): string[] {+ return [+ ...summary.new_unconfirmed,+ ...summary.confirmed,+ ...summary.retired.map((r) => r.id),+ ...summary.moved_to_processed,+ ];+}+async function toolBrainDream(ctx: ServerContext,args: Record<string, unknown>,@@ -324,11 +339,31 @@ async function toolBrainDream(}}+ const { expect, strict } = readCountGuardArgs(args);+ // Only pay for a preview pass when a guard is actually requested; otherwise+ // the run is byte-identical to before.+ if (expect !== null || strict) {+ const preview = dream(ctx.vault, {+ dryRun: true,+ ...(nowDate ? { now: nowDate } : {}),+ ...(agent ? { agentName: agent } : {}),+ });+ const previewList = dreamChangeList(preview);+ enforceCountGuard({+ matched: previewList.length,+ expect,+ strict,+ willMutate: !dryRun,+ matchList: previewList,+ });+ }+const summary = dream(ctx.vault, {dryRun,...(nowDate ? { now: nowDate } : {}),...(agent ? { agentName: agent } : {}),});+ const changeList = dreamChangeList(summary);// The summary is already a Plain Old Frozen Object — JSON-serialise// verbatim. We surface `snapshot_path` / `log_path` as vault-relative@@ -336,6 +371,10 @@ async function toolBrainDream(return {run_id: summary.run_id,changed: summary.changed,+ // Honest matched-vs-changed: `matched` is what the pass would touch;+ // `changed_count` is what it actually wrote (0 on a dry run).+ matched: changeList.length,+ changed_count: dryRun ? 0 : changeList.length,dry_run: dryRun,new_unconfirmed: [...summary.new_unconfirmed],confirmed: [...summary.confirmed],@@ -624,6 +663,16 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([description:"Optional caller identity; a mismatch with the configured primary agent emits a warning. Defaults to the server-resolved name.",},+ expect: {+ type: "integer",+ minimum: 0,+ description:+ "action=run count guard: assert the pass will create/confirm/retire/move exactly N preferences. On mismatch it aborts without writing.",+ },+ strict: {+ type: "boolean",+ description: "action=run: refuse a guardless run (no `expect`). Default false.",+ },},additionalProperties: false,},diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.tsindex 2acbe9ab..5260a52f 100644--- a/src/mcp/brain/hygiene-tools.ts+++ b/src/mcp/brain/hygiene-tools.ts@@ -34,7 +34,7 @@ import { coerceBool } from "../coerce.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import type { ServerContext, ToolDefinition } from "../tools.ts";-import { vaultRelativeSafe } from "./shared.ts";+import { enforceCountGuard, readCountGuardArgs, vaultRelativeSafe } from "./shared.ts";function coerceStringArray(args: Record<string, unknown>, key: string): string[] | undefined {const raw = args[key];@@ -143,6 +143,16 @@ async function toolBrainHygiene(throw new MCPError(INVALID_PARAMS, "apply requires explicit finding 'ids' from a prior scan");}const plan = buildHygienePlan(report, { ids });+ const { expect, strict } = readCountGuardArgs(args);+ // Guard on the selected findings BEFORE applying so an unexpected blast+ // radius aborts without touching the vault.+ enforceCountGuard({+ matched: plan.selected.length,+ expect,+ strict,+ willMutate: !dryRun,+ matchList: plan.selected.map((finding) => finding.id),+ });const result = await applyHygienePlan(ctx.vault, plan, {dryRun,agent: resolveAgentName(ctx.configPath ?? undefined),@@ -156,6 +166,9 @@ async function toolBrainHygiene(unknown_ids: plan.unknown_ids,planned: result.planned,applied: result.applied,+ // Honest matched-vs-changed: findings selected vs. findings actually applied.+ matched: plan.selected.length,+ changed: result.applied.length,errors: result.errors,};}@@ -188,6 +201,16 @@ export const HYGIENE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "boolean",description: "Preview apply/refresh with zero writes.",},+ expect: {+ type: "integer",+ minimum: 0,+ description:+ "Count guard (apply mode): assert exactly N findings will be applied. On mismatch the apply aborts without writing.",+ },+ strict: {+ type: "boolean",+ description: "Refuse a guardless apply (no `expect`). Default false.",+ },},additionalProperties: false,},diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex db7c4b72..c0080ae0 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -24,7 +24,7 @@ import { coerceBoolOptional, coerceInt, coerceStr } from "../coerce.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import type { ServerContext, ToolDefinition } from "../tools.ts";import { parseExtractionIntakeArgs } from "./intake-args.ts";-import { wrapToolErrors } from "./shared.ts";+import { enforceCountGuard, readCountGuardArgs, wrapToolErrors } from "./shared.ts";const TOOL = "brain_ingest_source";const SEARCH_TOOL = "brain_search_by_source";@@ -81,6 +81,10 @@ function serializePlan(plan: SourceCleanupPlan): Record<string, unknown> {confirmed: plan.confirmed,include_originals: plan.includeOriginals,blast_radius: plan.blastRadius,+ // Honest matched-vs-changed accounting: `matched` is what the plan would+ // touch; `changed` is what was actually removed (0 on a dry run).+ matched: plan.blastRadius,+ changed: plan.deleted.length,derived: plan.derived.map(serializeEntry),mentions: plan.mentions.map(serializeEntry),originals: [...plan.originals],@@ -91,6 +95,15 @@ function serializePlan(plan: SourceCleanupPlan): Record<string, unknown> {};}+/** The vault-relative identities a cleanup plan would touch (for guard output). */+function planMatchList(plan: SourceCleanupPlan): string[] {+ return [+ ...plan.derived.map((e) => e.match ?? e.id),+ ...plan.mentions.map((e) => e.match ?? e.id),+ ...plan.originals,+ ];+}+async function toolBrainSearchBySource(ctx: ServerContext,args: Record<string, unknown>,@@ -112,12 +125,27 @@ async function toolBrainDeleteBySource(const confirm = coerceBoolOptional(args, "confirm") ?? false;const includeOriginals = coerceBoolOptional(args, "include_originals") ?? false;const agent = coerceStr(args, "agent", false) ?? undefined;- const plan = deleteBySource(ctx.vault, sourceFile, {- confirm,+ const { expect, strict } = readCountGuardArgs(args);+ const now = new Date();+ const baseOpts = {includeOriginals,- now: new Date(),+ now,...(agent !== undefined ? { agent } : {}),+ };++ // Compute the (non-destructive) plan first so the count guard can assert the+ // blast radius BEFORE anything is deleted; only then confirm the removal.+ const preview = deleteBySource(ctx.vault, sourceFile, { confirm: false, ...baseOpts });+ enforceCountGuard({+ matched: preview.blastRadius,+ expect,+ strict,+ willMutate: confirm,+ matchList: planMatchList(preview),});+ const plan = confirm+ ? deleteBySource(ctx.vault, sourceFile, { confirm: true, ...baseOpts })+ : preview;return serializePlan(plan);}@@ -271,6 +299,16 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",description: "Optional agent identity recorded in the audit reason.",},+ expect: {+ type: "integer",+ minimum: 0,+ description:+ "Count guard: assert the blast radius equals N. On mismatch the op aborts without deleting and returns the matched list.",+ },+ strict: {+ type: "boolean",+ description: "Refuse a confirmed deletion that carries no `expect` guard. Default false.",+ },},required: ["source_file"],additionalProperties: false,diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.tsindex d05444c7..e64a81c1 100644--- a/src/mcp/brain/procedure-tools.ts+++ b/src/mcp/brain/procedure-tools.ts@@ -13,6 +13,7 @@ import {listPendingSkillProposals,rejectSkillProposal,} from "../../core/brain/skill-proposals.ts";+import { deriveSkillUsage } from "../../core/brain/skill-usage.ts";import {listProceduralMemory,markProceduralMemoryUsed,@@ -68,9 +69,16 @@ async function toolBrainSkillProposals(const reviewed = rejectSkillProposal(ctx.vault, slug, { note });return { ...reviewed };}+ if (operation === "usage") {+ // Per-skill invocation telemetry (t_56a12bde): deterministic counts+ // derived from skill_invoked continuity records, distinct from proposing+ // or ranking. Real usage evidence for the dream/synthesis pass.+ const usage = deriveSkillUsage(ctx.vault);+ return { total: usage.length, usage };+ }throw new MCPError(INVALID_PARAMS,- "brain_skill_proposals: operation must be one of learn|list|accept|reject",+ "brain_skill_proposals: operation must be one of learn|list|accept|reject|usage",);}@@ -213,13 +221,13 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_skill_proposals",description:- "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject).",+ "Learn/list/review deterministic skill proposals from continuity records (learn, list, accept, reject), and read per-skill invocation usage counts (usage).",inputSchema: {type: "object",properties: {operation: {type: "string",- enum: ["learn", "list", "accept", "reject"],+ enum: ["learn", "list", "accept", "reject", "usage"],description: "Tool operation.",},min_support: {diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.tsindex 18ff08b6..c028ec27 100644--- a/src/mcp/brain/shared.ts+++ b/src/mcp/brain/shared.ts@@ -12,6 +12,45 @@ import { formatLocalTimestamp } from "../../core/brain/present-time.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext } from "../tools.ts";import { coerceBool } from "../coerce.ts";+import {+ CountGuardError,+ assertExpectedCount,+ type CountGuardOptions,+} from "../../core/brain/count-guard.ts";++/**+ * Read the shared `--expect` / `--strict` count-guard arguments from an MCP+ * tool payload. `expect` absent means no assertion; a non-integer or negative+ * value is a client error.+ */+export function readCountGuardArgs(args: Record<string, unknown>): {+ expect: number | null;+ strict: boolean;+} {+ const raw = args["expect"];+ let expect: number | null = null;+ if (raw !== undefined && raw !== null) {+ const n = typeof raw === "number" ? raw : Number(raw);+ if (!Number.isInteger(n) || n < 0) {+ throw new MCPError(INVALID_PARAMS, "'expect' must be a non-negative integer");+ }+ expect = n;+ }+ return { expect, strict: coerceBool(args, "strict") === true };+}++/**+ * Run the count guard, mapping a {@link CountGuardError} to INVALID_PARAMS so+ * the caller (not the server) is blamed for the mismatch / guardless mutation.+ */+export function enforceCountGuard(opts: CountGuardOptions): void {+ try {+ assertExpectedCount(opts);+ } catch (err) {+ if (err instanceof CountGuardError) throw new MCPError(INVALID_PARAMS, err.message);+ throw err;+ }+}export const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;diff --git a/src/mcp/http.ts b/src/mcp/http.tsindex 4bf1a6de..c8677849 100644--- a/src/mcp/http.ts+++ b/src/mcp/http.ts@@ -37,14 +37,21 @@ export async function startHttp(runtimeOpts: MCPServerRuntimeOptions = {},): Promise<HttpServerHandle> {const apiKey = opts.apiKey ?? null;- if (apiKey === null || apiKey === "") {- throw new Error("HTTP MCP transport requires --api-key");- }const host = opts.host ?? "127.0.0.1";+ // Safe by default: on the loopback default a bearer is optional (the+ // loopback bind + Host/Origin rebinding guard are the baseline defence).+ // Binding to a NON-loopback interface exposes the Brain on the network, so+ // a bearer is mandatory there - no permissive fallback.+ if (!isLoopbackHost(host) && (apiKey === null || apiKey === "")) {+ throw new Error(+ "HTTP MCP transport bound to a non-loopback host requires --api-key " ++ `(host=${host}); refusing to expose an unauthenticated endpoint on the network`,+ );+ }const port = opts.port ?? 0;const mcp = new MCPServer(ctx, runtimeOpts);const server = createServer(async (req, res) => {- await handleHttpRequest(mcp, apiKey, req, res);+ await handleHttpRequest(mcp, apiKey, host, req, res);});server.listen(port, host);await once(server, "listening");@@ -74,11 +81,39 @@ export async function serveHttp(async function handleHttpRequest(mcp: MCPServer,- apiKey: string,+ apiKey: string | null,+ boundHost: string,req: IncomingMessage,res: ServerResponse,): Promise<void> {- if (!authorized(req, apiKey)) {+ // DNS-rebinding guard (always enforced, never bypassable): a malicious web+ // page that resolves its own domain to 127.0.0.1 still sends its Host /+ // Origin, so rejecting any non-loopback Host/Origin blocks the rebind even+ // when the socket is loopback-bound.+ if (!hostAllowed(req, boundHost)) {+ res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });+ res.end("Forbidden: Host not allowed\n");+ return;+ }+ if (!originAllowed(req, boundHost)) {+ res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });+ res.end("Forbidden: Origin not allowed\n");+ return;+ }++ const path = (req.url ?? "/").split("?")[0];++ // Health endpoint: an unauthenticated liveness probe (still behind the Host+ // guard), so a supervisor can check the transport without a bearer.+ if (req.method === "GET" && path === "/health") {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ status: "ok", transport: "http" }) + "\n");+ return;+ }++ // Bearer is optional on loopback (guards are the baseline) but enforced when+ // configured; a non-loopback bind always has a key (see startHttp).+ if (apiKey !== null && apiKey !== "" && !authorized(req, apiKey)) {res.writeHead(401, { "content-type": "text/plain; charset=utf-8" });res.end("Unauthorized\n");return;@@ -140,6 +175,72 @@ function authorized(req: IncomingMessage, apiKey: string): boolean {return constantTimeEqual(presented, apiKey);}+/** Canonical loopback host names a rebinding guard trusts. */+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);++export function isLoopbackHost(host: string): boolean {+ return LOOPBACK_HOSTS.has(normaliseHostname(host));+}++/** Strip a port and IPv6 brackets, lowercase - `[::1]:8080` -> `::1`. */+function normaliseHostname(value: string): string {+ let host = value.trim().toLowerCase();+ if (host.startsWith("[")) {+ // Bracketed IPv6, optionally with :port after the bracket.+ const end = host.indexOf("]");+ return end === -1 ? host.slice(1) : host.slice(1, end);+ }+ // IPv4/hostname: drop a trailing :port (a bare IPv6 has multiple colons).+ const colon = host.indexOf(":");+ if (colon !== -1 && host.indexOf(":", colon + 1) === -1) host = host.slice(0, colon);+ return host;+}++/**+ * DNS rebinding exploits a LOOPBACK-bound server reached from a victim's+ * browser (a malicious site rebinds its own domain to 127.0.0.1). The guard is+ * therefore meaningful only for a loopback bind, where the trusted Host set is+ * the enumerable loopback names. A non-loopback bind is an explicit network+ * exposure that always carries a mandatory bearer (see startHttp), so the+ * bearer - not a Host allowlist we cannot enumerate for a wildcard bind - is+ * the auth boundary there; blocking the machine's real IP / DNS Host would+ * make `0.0.0.0` unusable. Skip the guard for non-loopback binds.+ */+function hostGuardApplies(boundHost: string): boolean {+ return isLoopbackHost(boundHost);+}++/**+ * The `Host` header must name a loopback address or the exact bound host.+ * A present-but-foreign Host is the DNS-rebinding signal and is rejected; an+ * absent Host (uncommon; not a browser rebind) is allowed.+ */+function hostAllowed(req: IncomingMessage, boundHost: string): boolean {+ if (!hostGuardApplies(boundHost)) return true;+ const host = req.headers.host;+ if (host === undefined) return true;+ const hostname = normaliseHostname(host);+ return isLoopbackHost(hostname) || hostname === normaliseHostname(boundHost);+}++/**+ * When an `Origin` is present (a browser request), its host must be loopback+ * or the bound host; a cross-origin browser request is rejected. A missing+ * Origin (non-browser client) is allowed.+ */+function originAllowed(req: IncomingMessage, boundHost: string): boolean {+ if (!hostGuardApplies(boundHost)) return true;+ const origin = firstHeader(req.headers.origin);+ if (origin === undefined || origin === "" || origin === "null") return origin !== "null";+ let hostname: string;+ try {+ hostname = new URL(origin).hostname.toLowerCase();+ } catch {+ return false;+ }+ return isLoopbackHost(hostname) || hostname === normaliseHostname(boundHost);+}+function bearerToken(value: string | undefined): string | undefined {if (value === undefined) return undefined;const m = /^Bearer\s+(.+)$/i.exec(value.trim());diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 4b751369..7afef3b6 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -25,6 +25,7 @@ import { discoverConfig, redactMapping } from "../core/config.ts";import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";import { computeBrainStatus } from "../core/brain/status.ts";import { doctor } from "../core/doctor.ts";+import { collectRuntimeNotices } from "../core/brain/runtime-notices.ts";import { isDir } from "../core/fs-utils.ts";import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";import { BRAIN_TOOLS } from "./brain-tools.ts";@@ -203,13 +204,21 @@ async function toolVaultHealth(name: r.name,ok: r.ok,message: r.message,+ ...(r.fix !== undefined ? { fix: r.fix } : {}),}));+ // Runtime-state notices (transient operational conditions) surfaced for+ // pull consumers, mirroring the proactive SessionStart injection push.+ const notices = collectRuntimeNotices(ctx.vault, {+ configPath: ctx.configPath ?? undefined,+ }).map((n) => ({ code: n.code, severity: n.severity, message: n.message }));+return {vault_path: ctx.vault,config_path: ctx.configPath ? String(ctx.configPath) : null,repo_root: repoRoot ? String(repoRoot) : null,ok: payload.every((c) => c.ok),checks: payload,+ notices,};}diff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex e2cd0f7e..5bd6825c 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -162,6 +162,7 @@ export default definePluginEntry({name: r.name,ok: r.ok,message: r.message,+ ...(r.fix !== undefined ? { fix: r.fix } : {}),})),};return {diff --git a/tests/cli/cli-json-contract.test.ts b/tests/cli/cli-json-contract.test.tsindex 76aacfa8..f7d7882f 100644--- a/tests/cli/cli-json-contract.test.ts+++ b/tests/cli/cli-json-contract.test.ts@@ -30,12 +30,12 @@ function env(): Record<string, string> {describe("inherited CLI --json contract", () => {test("text-only commands accept --json and return a fallback envelope", async () => {- const result = await runCli(["doctor", "--vault", vault, "--json"], {+ const result = await runCli(["init", "--vault", vault, "--json"], {env: env(),});const parsed = JSON.parse(result.stdout);- expect(parsed.command).toBe("doctor");+ expect(parsed.command).toBe("init");expect(parsed.code).toBe(result.returncode);expect(typeof parsed.ok).toBe("boolean");expect(typeof parsed.stdout).toBe("string");@@ -55,6 +55,20 @@ describe("inherited CLI --json contract", () => {expect(parsed).not.toHaveProperty("stdout");});+ test("doctor --json is a semantic report, not the fallback envelope", async () => {+ const result = await runCli(["doctor", "--vault", vault, "--json"], {+ env: env(),+ });+ const parsed = JSON.parse(result.stdout);+ // Semantic payload: no envelope wrapper, a structured per-check list and+ // an aggregate summary the operator can gate a setup/CI step on.+ expect(parsed).not.toHaveProperty("command");+ expect(parsed).not.toHaveProperty("stdout");+ expect(Array.isArray(parsed.checks)).toBe(true);+ expect(typeof parsed.summary.total).toBe("number");+ expect(typeof parsed.summary.failed).toBe("number");+ });+test("fallback JSON redacts secret-shaped output", async () => {const result = await runCli(["init", "--vault", vault, "--agent-name", "api_key=super-secret-value", "--json"],diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.tsindex 3cea5cab..76f55adb 100644--- a/tests/cli/cli.test.ts+++ b/tests/cli/cli.test.ts@@ -153,6 +153,36 @@ describe("doctor", () => {expect(r.stdout).toContain("[FAIL]");});+ test("prints a copy-pasteable fix and an aggregate summary for a failure", async () => {+ const r = await runCli(["doctor", "--vault", "/nonexistent/path"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("fix: mkdir -p");+ expect(r.stdout).toMatch(/doctor: \d+ checks, [1-9]\d* failed/);+ });++ test("--json emits a scriptable report with fix and summary", async () => {+ const r = await runCli(["doctor", "--vault", "/nonexistent/path", "--json"]);+ expect(r.returncode).toBe(1);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.ok).toBe(false);+ expect(parsed.summary.failed).toBeGreaterThan(0);+ const failing = parsed.checks.find((c: { ok: boolean }) => !c.ok);+ expect(typeof failing.fix).toBe("string");+ expect(failing.fix.length).toBeGreaterThan(0);+ });++ test("--json on a healthy vault reports ok with zero failures", async () => {+ const r = await runCli(["doctor", "--vault", tmp, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: "", XDG_CONFIG_HOME: "", VAULT_DIR: "" },+ });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.ok).toBe(true);+ expect(parsed.summary.failed).toBe(0);+ // A passing check omits the remediation fix.+ expect(parsed.checks.every((c: { fix?: string }) => c.fix === undefined)).toBe(true);+ });+test("with --repo checks manifests", async () => {const vault = createSandboxVault(tmp);const repo = createPluginRepo(tmp, true);@@ -173,6 +203,38 @@ describe("doctor", () => {});});+describe("onboarding", () => {+ test("init prints the guided onboarding checklist after the search block", async () => {+ const vault = join(tmp, "ob-vault");+ const config = join(tmp, "ob-config.yaml");+ const r = await runCli(["init", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config, XDG_CONFIG_HOME: "", VAULT_DIR: "" },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("initialized vault");+ expect(r.stdout).toContain("Next steps:");+ expect(r.stdout).toContain("o2b search index");+ });++ test("o2b onboarding re-runs the checklist and supports --json", async () => {+ const vault = join(tmp, "ob-vault2");+ const config = join(tmp, "ob-config2.yaml");+ const env = { OPEN_SECOND_BRAIN_CONFIG: config, XDG_CONFIG_HOME: "", VAULT_DIR: "" };+ await runCli(["init", "--vault", vault], { env });++ const text = await runCli(["onboarding", "--vault", vault, "--config", config], { env });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("Next steps:");++ const json = await runCli(["onboarding", "--vault", vault, "--config", config, "--json"], {+ env,+ });+ const parsed = JSON.parse(json.stdout);+ expect(Array.isArray(parsed.steps)).toBe(true);+ expect(parsed.steps.find((s: { id: string }) => s.id === "vault_configured").done).toBe(true);+ });+});+describe("index", () => {test("errors when no vault anywhere", async () => {const cfg = join(tmp, "config.yaml");diff --git a/tests/cli/onboarding.test.ts b/tests/cli/onboarding.test.tsnew file mode 100644index 00000000..af3a80b7--- /dev/null+++ b/tests/cli/onboarding.test.ts@@ -0,0 +1,75 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildOnboardingChecklist, renderOnboardingChecklist } from "../../src/cli/onboarding.ts";++let vault: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-onboarding-"));+ configPath = join(vault, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`, "utf8");+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function stepById(vaultDir: string, id: string) {+ const checklist = buildOnboardingChecklist(vaultDir, { configPath, env: {} });+ return checklist.steps.find((s) => s.id === id)!;+}++test("a bare initialized vault marks config done and later steps todo", () => {+ const checklist = buildOnboardingChecklist(vault, { configPath, env: {} });+ const byId = new Map(checklist.steps.map((s) => [s.id, s]));+ expect(byId.get("vault_configured")!.done).toBe(true);+ expect(byId.get("build_index")!.done).toBe(false);+ expect(byId.get("build_index")!.command).toContain("o2b search index");+ expect(byId.get("scaffold_brain")!.done).toBe(false);+ expect(byId.get("agent_name")!.done).toBe(false);+ // Required steps still pending -> not complete.+ expect(checklist.complete).toBe(false);+});++test("a built search index flips the index step to done", () => {+ expect(stepById(vault, "build_index").done).toBe(false);+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "x", "utf8");+ expect(stepById(vault, "build_index").done).toBe(true);+});++test("a configured agent name flips the agent step to done", () => {+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-dev"\n`, "utf8");+ expect(stepById(vault, "agent_name").done).toBe(true);+});++test("recording a first preference flips the feedback step to done", () => {+ expect(stepById(vault, "first_feedback").done).toBe(false);+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ writeFileSync(join(vault, "Brain", "preferences", "pref-x.md"), "---\nid: pref-x\n---\n", "utf8");+ expect(stepById(vault, "first_feedback").done).toBe(true);+});++test("a local embedding provider is semantic-ready without an API key", () => {+ writeFileSync(+ configPath,+ `vault: "${vault}"\nsearch_semantic_enabled: "true"\nembedding_provider: "local"\n`,+ "utf8",+ );+ // No embedding key, but a local provider needs none - the optional semantic+ // step is satisfied, matching the runtime-notice logic.+ expect(stepById(vault, "semantic_search").done).toBe(true);+});++test("the checklist renders a human-readable block with checkboxes and commands", () => {+ const checklist = buildOnboardingChecklist(vault, { configPath, env: {} });+ const text = renderOnboardingChecklist(checklist);+ expect(text).toContain("Next steps:");+ expect(text).toContain("[x]"); // config done+ expect(text).toContain("[ ]"); // pending steps+ expect(text).toContain("o2b search index");+});diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.tsindex e9cefbfa..4617a3ee 100644--- a/tests/core/brain.sessions.import.test.ts+++ b/tests/core/brain.sessions.import.test.ts@@ -296,3 +296,49 @@ describe("importSessionPath (directory walk)", () => {expect(result.warnings.length).toBe(1);});});++describe("per-skill invocation telemetry", () => {+ function writeSkillSession(path: string): void {+ writeFileSync(+ path,+ [+ '{"parentUuid":null,"sessionId":"sk","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"do a release"},"uuid":"u1","timestamp":"2026-06-01T10:00:00.000Z"}',+ '{"parentUuid":"u1","sessionId":"sk","type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"c1","name":"get_skill","input":{"name":"release"}}]},"uuid":"a1","timestamp":"2026-06-01T10:00:01.000Z"}',+ '{"parentUuid":"a1","sessionId":"sk","type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"c2","name":"Skill","input":{"command":"release"}}]},"uuid":"a2","timestamp":"2026-06-01T10:00:02.000Z"}',+ '{"parentUuid":"a2","sessionId":"sk","type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"c3","name":"get_skill","input":{"name":"triage"}}]},"uuid":"a3","timestamp":"2026-06-01T10:00:03.000Z"}',+ "",+ ].join("\n"),+ );+ }++ test("counts get_skill / Skill invocations and derives per-skill usage", async () => {+ const { deriveSkillUsage } = await import("../../src/core/brain/skill-usage.ts");+ const fixture = join(tmp, "skills.jsonl");+ writeSkillSession(fixture);++ const res = await importSession(tmp, fixture, { agent: "test" });+ expect(res.skill_invocations).toBe(3);++ const usage = deriveSkillUsage(tmp);+ expect(usage.map((u) => [u.skill, u.invocationCount])).toEqual([+ ["release", 2],+ ["triage", 1],+ ]);+ });++ test("a dry run records no invocations and re-import is idempotent", async () => {+ const { deriveSkillUsage } = await import("../../src/core/brain/skill-usage.ts");+ const fixture = join(tmp, "skills.jsonl");+ writeSkillSession(fixture);++ const dry = await importSession(tmp, fixture, { agent: "test", dryRun: true });+ expect(dry.skill_invocations).toBe(0);+ expect(deriveSkillUsage(tmp)).toEqual([]);++ await importSession(tmp, fixture, { agent: "test" });+ // Re-importing the same session dedupes rather than double-counting.+ await importSession(tmp, fixture, { agent: "test" });+ const usage = deriveSkillUsage(tmp);+ expect(usage.find((u) => u.skill === "release")!.invocationCount).toBe(2);+ });+});diff --git a/tests/core/brain/count-guard.test.ts b/tests/core/brain/count-guard.test.tsnew file mode 100644index 00000000..b1e55421--- /dev/null+++ b/tests/core/brain/count-guard.test.ts@@ -0,0 +1,54 @@+import { expect, test } from "bun:test";++import { CountGuardError, assertExpectedCount } from "../../../src/core/brain/count-guard.ts";++test("a matching --expect passes", () => {+ expect(() => assertExpectedCount({ matched: 3, expect: 3, willMutate: true })).not.toThrow();+});++test("a mismatched --expect throws with the matched count and match list", () => {+ let err: CountGuardError | null = null;+ try {+ assertExpectedCount({+ matched: 5,+ expect: 3,+ willMutate: true,+ matchList: ["a.md", "b.md", "c.md", "d.md", "e.md"],+ });+ } catch (e) {+ err = e as CountGuardError;+ }+ expect(err).toBeInstanceOf(CountGuardError);+ expect(err!.matched).toBe(5);+ expect(err!.expected).toBe(3);+ expect(err!.message).toContain("5");+ expect(err!.message).toContain("3");+ // The match list is surfaced so the operator sees exactly what would change.+ expect(err!.message).toContain("a.md");+ expect(err!.matchList).toEqual(["a.md", "b.md", "c.md", "d.md", "e.md"]);+});++test("--strict refuses a guardless mutation (no --expect)", () => {+ let err: CountGuardError | null = null;+ try {+ assertExpectedCount({ matched: 2, strict: true, willMutate: true });+ } catch (e) {+ err = e as CountGuardError;+ }+ expect(err).toBeInstanceOf(CountGuardError);+ expect(err!.message.toLowerCase()).toContain("strict");+});++test("--strict with an explicit --expect that matches passes", () => {+ expect(() =>+ assertExpectedCount({ matched: 2, expect: 2, strict: true, willMutate: true }),+ ).not.toThrow();+});++test("--strict does not fire on a dry-run (no mutation)", () => {+ expect(() => assertExpectedCount({ matched: 2, strict: true, willMutate: false })).not.toThrow();+});++test("with neither guard the call is a no-op (default off)", () => {+ expect(() => assertExpectedCount({ matched: 99, willMutate: true })).not.toThrow();+});diff --git a/tests/core/brain/inject-failopen.test.ts b/tests/core/brain/inject-failopen.test.tsnew file mode 100644index 00000000..36129bde--- /dev/null+++ b/tests/core/brain/inject-failopen.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ loadInjectContextFailOpen,+ readInjectCache,+} from "../../../src/core/brain/inject-failopen.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-failopen-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("a fresh non-empty assembly is returned and cached as last-good", async () => {+ const res = await loadInjectContextFailOpen({+ vault,+ key: "active",+ assemble: () => "fresh body",+ });+ expect(res).toEqual({ context: "fresh body", degraded: false, source: "fresh" });+ expect(readInjectCache(vault, "active")).toBe("fresh body");+});++test("a thrown assembly degrades to the last-good cache and audits once", async () => {+ await loadInjectContextFailOpen({ vault, key: "active", assemble: () => "good v1" });++ const audits: Array<{ source: string }> = [];+ const res = await loadInjectContextFailOpen({+ vault,+ key: "active",+ assemble: () => {+ throw new Error("embedding timed out");+ },+ audit: (source) => audits.push({ source }),+ });+ expect(res).toEqual({ context: "good v1", degraded: true, source: "cached" });+ expect(audits).toEqual([{ source: "cached" }]);+});++test("a thrown assembly with no cache degrades to empty, never a partial write", async () => {+ const audits: string[] = [];+ const res = await loadInjectContextFailOpen({+ vault,+ key: "active",+ assemble: () => {+ throw new Error("stat stalled");+ },+ audit: (source) => audits.push(source),+ });+ expect(res).toEqual({ context: "", degraded: true, source: "empty" });+ expect(audits).toEqual(["empty"]);+ expect(existsSync(join(vault, ".open-second-brain", "inject-cache", "active.txt"))).toBe(false);+});++test("a legitimately empty assembly does not clobber the last-good cache", async () => {+ await loadInjectContextFailOpen({ vault, key: "active", assemble: () => "good v1" });+ const res = await loadInjectContextFailOpen({ vault, key: "active", assemble: () => "" });+ expect(res).toEqual({ context: "", degraded: false, source: "fresh" });+ // The prior good body is preserved so a later error can still degrade to it.+ expect(readInjectCache(vault, "active")).toBe("good v1");+ const raw = readFileSync(join(vault, ".open-second-brain", "inject-cache", "active.txt"), "utf8");+ expect(raw).toBe("good v1");+});diff --git a/tests/core/brain/runtime-notices.test.ts b/tests/core/brain/runtime-notices.test.tsnew file mode 100644index 00000000..0e30e3af--- /dev/null+++ b/tests/core/brain/runtime-notices.test.ts@@ -0,0 +1,110 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ collectRuntimeNotices,+ renderRuntimeNotices,+} from "../../../src/core/brain/runtime-notices.ts";++let vault: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-notices-"));+ configPath = join(vault, "config.yaml");+});++afterEach(() => {+ // Restore writability so cleanup succeeds even after a read-only test.+ try {+ chmodSync(vault, 0o700);+ } catch {+ /* ignore */+ }+ rmSync(vault, { recursive: true, force: true });+});++function writeConfig(body: string): void {+ writeFileSync(configPath, `vault: "${vault}"\n${body}`, "utf8");+}++/** Pretend the search index already exists so index-missing does not fire. */+function seedIndex(): void {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "x", "utf8");+}++test("a healthy, indexed, lexical-only vault yields no notices", () => {+ writeConfig("");+ seedIndex();+ expect(collectRuntimeNotices(vault, { configPath, env: {} })).toEqual([]);+});++test("semantic enabled without a resolvable key yields a degraded notice", () => {+ writeConfig(+ [+ `search_semantic_enabled: "true"`,+ `embedding_provider: "openai-compat"`,+ `embedding_base_url: "https://example.invalid/v1"`,+ `embedding_model: "m"`,+ "",+ ].join("\n"),+ );+ seedIndex();+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });+ const codes = notices.map((n) => n.code);+ expect(codes).toContain("semantic_degraded");+ const degraded = notices.find((n) => n.code === "semantic_degraded")!;+ expect(degraded.severity).toBe("warning");+ expect(degraded.message.toLowerCase()).toContain("embedding");+});++test("a missing search index yields an index notice", () => {+ writeConfig("");+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });+ expect(notices.map((n) => n.code)).toContain("search_index_missing");+});++test("a read-only vault yields a read-only notice", () => {+ writeConfig("");+ seedIndex();+ chmodSync(vault, 0o500);+ const notices = collectRuntimeNotices(vault, { configPath, env: {} });+ // Skip the assertion if the platform/user still permits the write probe+ // (e.g. running as root ignores mode bits); the notice is best-effort.+ const probe = join(vault, ".probe-write-check");+ let writable = false;+ try {+ writeFileSync(probe, "x");+ rmSync(probe);+ writable = true;+ } catch {+ /* not writable, as intended */+ }+ if (!writable) {+ expect(notices.map((n) => n.code)).toContain("vault_read_only");+ }+});++test("the opt-out env suppresses all notices", () => {+ writeConfig("");+ // Index missing would normally fire; the opt-out silences everything.+ const notices = collectRuntimeNotices(vault, {+ configPath,+ env: { OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false" },+ });+ expect(notices).toEqual([]);+});++test("renderRuntimeNotices formats a compact block and is empty when clean", () => {+ expect(renderRuntimeNotices([])).toBe("");+ const block = renderRuntimeNotices([+ { code: "semantic_degraded", severity: "warning", message: "no key" },+ { code: "search_index_missing", severity: "info", message: "build it" },+ ]);+ expect(block).toContain("Runtime notices:");+ expect(block).toContain("no key");+ expect(block).toContain("build it");+});diff --git a/tests/core/brain/skill-usage.test.ts b/tests/core/brain/skill-usage.test.tsnew file mode 100644index 00000000..eee5b743--- /dev/null+++ b/tests/core/brain/skill-usage.test.ts@@ -0,0 +1,56 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";+import { deriveSkillUsage } from "../../../src/core/brain/skill-usage.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-skill-usage-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function invoke(skill: string, seq: number, at: string): void {+ appendContinuityRecord(vault, {+ kind: "skill_invoked",+ createdAt: at,+ sourceRefs: [{ id: `sess:${skill}:${seq}` }],+ payload: { skill, agent: "claude", tool: "get_skill" },+ });+}++test("a vault with no invocations derives an empty usage list", () => {+ expect(deriveSkillUsage(vault)).toEqual([]);+});++test("groups skill_invoked records into per-skill counts, ranked by count", () => {+ invoke("release", 1, "2026-06-01T10:00:00Z");+ invoke("release", 2, "2026-06-02T10:00:00Z");+ invoke("release", 3, "2026-06-03T10:00:00Z");+ invoke("triage", 1, "2026-06-01T11:00:00Z");++ const usage = deriveSkillUsage(vault, { nowMs: Date.parse("2026-06-04T00:00:00Z") });+ expect(usage.map((u) => [u.skill, u.invocationCount])).toEqual([+ ["release", 3],+ ["triage", 1],+ ]);+ const release = usage[0]!;+ expect(release.lastInvokedAtMs).toBe(Date.parse("2026-06-03T10:00:00Z"));+ expect(release.weight).toBeGreaterThan(0);+ expect(release.weight).toBeLessThanOrEqual(1);+});++test("distinct invocations in the same second are counted separately", () => {+ // Same skill, same timestamp, different source ref => distinct records.+ invoke("release", 1, "2026-06-01T10:00:00Z");+ invoke("release", 2, "2026-06-01T10:00:00Z");+ const usage = deriveSkillUsage(vault);+ expect(usage).toHaveLength(1);+ expect(usage[0]!.invocationCount).toBe(2);+});diff --git a/tests/core/doctor.test.ts b/tests/core/doctor.test.tsindex 920e9361..854b9b5a 100644--- a/tests/core/doctor.test.ts+++ b/tests/core/doctor.test.ts@@ -38,6 +38,16 @@ describe("checkVaultWriteable", () => {expect(r.ok).toBe(false);expect(r.message.toLowerCase()).toContain("missing");});++ test("a passing check carries no remediation fix", () => {+ expect(checkVaultWriteable(tmp).fix).toBeUndefined();+ });++ test("a failing check carries a copy-pasteable remediation fix", () => {+ const r = checkVaultWriteable(join(tmp, "does_not_exist"));+ expect(typeof r.fix).toBe("string");+ expect((r.fix ?? "").length).toBeGreaterThan(0);+ });});describe("checkConfigWriteable", () => {diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.tsindex 3decf9fa..e19e83a3 100644--- a/tests/core/fs-atomic.test.ts+++ b/tests/core/fs-atomic.test.ts@@ -143,3 +143,34 @@ describe("atomicWriteText", () => {expect(readFileSync(target, "utf8")).toBe("second\n");});});++describe("skipIfUnchanged short-circuit", () => {+ test("atomicWriteFileSync returns true on a real write and false on a no-op", () => {+ const target = join(tmp, "noop.txt");+ // First write to a fresh path always writes.+ expect(atomicWriteFileSync(target, "body\n", { skipIfUnchanged: true })).toBe(true);+ const firstMtime = statSync(target).mtimeMs;++ // Identical content short-circuits: no write, mtime unchanged.+ expect(atomicWriteFileSync(target, "body\n", { skipIfUnchanged: true })).toBe(false);+ expect(statSync(target).mtimeMs).toBe(firstMtime);++ // Different content writes and reports the change.+ expect(atomicWriteFileSync(target, "changed\n", { skipIfUnchanged: true })).toBe(true);+ expect(readFileSync(target, "utf8")).toBe("changed\n");+ });++ test("without the flag an identical write still rewrites (default unchanged)", () => {+ const target = join(tmp, "always.txt");+ atomicWriteFileSync(target, "body\n");+ // Default behaviour returns true and rewrites.+ expect(atomicWriteFileSync(target, "body\n")).toBe(true);+ });++ test("atomicWriteText short-circuits identical content too", () => {+ const target = join(tmp, "text.txt");+ expect(atomicWriteText(target, "hello", { skipIfUnchanged: true })).toBe(true);+ expect(atomicWriteText(target, "hello", { skipIfUnchanged: true })).toBe(false);+ expect(atomicWriteText(target, "world", { skipIfUnchanged: true })).toBe(true);+ });+});diff --git a/tests/core/search/config.test.ts b/tests/core/search/config.test.tsindex ead61568..843a803b 100644--- a/tests/core/search/config.test.ts+++ b/tests/core/search/config.test.ts@@ -26,6 +26,7 @@ const ENV_KEYS = ["OPEN_SECOND_BRAIN_EMBEDDING_TIMEOUT","OPEN_SECOND_BRAIN_EMBEDDING_CONCURRENCY","OPEN_SECOND_BRAIN_EMBEDDING_BATCH",+ "OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES","OPEN_SECOND_BRAIN_SEARCH_RECENCY_SHAPE","OPEN_SECOND_BRAIN_SEARCH_RECENCY_SCALE","OPEN_SECOND_BRAIN_SEARCH_RECENCY_AMPLITUDE",@@ -81,6 +82,22 @@ test("defaults are returned when config and env are empty", () => {expect(ignoreRaws).toContain("Brain/.snapshots");});+test("embedding retry budget defaults to 6 and is overridable via env and config", () => {+ writeFileSync(configPath, `vault: "${tmp}"\n`);+ expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(6);++ writeFileSync(configPath, `vault: "${tmp}"\nembedding_max_retries: "9"\n`);+ expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(9);++ process.env["OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES"] = "2";+ expect(resolveSearchConfig({ vault: tmp, configPath }).semantic.maxRetries).toBe(2);+});++test("embedding retry budget below 1 is rejected", () => {+ writeFileSync(configPath, `vault: "${tmp}"\nembedding_max_retries: "0"\n`);+ expect(() => resolveSearchConfig({ vault: tmp, configPath })).toThrow(/embedding_max_retries/);+});+test("recall recency defaults to the Weibull curve params", () => {writeFileSync(configPath, `vault: "${tmp}"\n`);const cfg = resolveSearchConfig({ vault: tmp, configPath });diff --git a/tests/core/search/embeddings.local-provider.test.ts b/tests/core/search/embeddings.local-provider.test.tsindex 05a9c472..5dc8571c 100644--- a/tests/core/search/embeddings.local-provider.test.ts+++ b/tests/core/search/embeddings.local-provider.test.ts@@ -77,6 +77,7 @@ test("makeProvider returns a LocalProvider for provider 'local'", () => {concurrency: 1,batchSize: 1,costGateUsd: 0,+ maxRetries: 3,});const p = makeProvider(config);expect(p).toBeInstanceOf(LocalProvider);@@ -96,6 +97,7 @@ test("makeProvider local needs no api key", () => {concurrency: 1,batchSize: 1,costGateUsd: 0,+ maxRetries: 3,});expect(() => makeProvider(config)).not.toThrow();expect(makeProvider(config).dimension).toBe(LOCAL_DEFAULT_DIMENSION);diff --git a/tests/core/search/embeddings.test.ts b/tests/core/search/embeddings.test.tsindex 2027c991..fe94df1e 100644--- a/tests/core/search/embeddings.test.ts+++ b/tests/core/search/embeddings.test.ts@@ -21,6 +21,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddinconcurrency: 2,batchSize: 32,costGateUsd: 0,+ maxRetries: 3,...overrides,});}@@ -155,6 +156,40 @@ test("embed() throws EMBEDDING_PROVIDER_HTTP after exhausting retries on 5xx", aexpect(server.callCount()).toBe(3);});+test("embed() honours a configurable maxRetries budget on 429", async () => {+ let calls = 0;+ server.setHandler((req) => {+ calls++;+ if (calls < 5) return { status: 429, body: { error: "rate limited" } };+ return {+ status: 200,+ body: {+ data: [{ object: "embedding", embedding: [0.5, 0.5, 0.5, 0.5], index: 0 }],+ model: (req.body as { model: string }).model,+ },+ };+ });++ // Five attempts allowed: four 429s then a 200 succeeds on the fifth.+ const p = new OpenAICompatProvider(cfg({ maxRetries: 5 }), { backoffMs: [1, 1, 1, 1] });+ const out = await p.embed(["rate"]);+ expect(out.length).toBe(1);+ expect(calls).toBe(5);+});++test("embed() gives up at the maxRetries ceiling on sustained 429", async () => {+ server.setHandler(() => ({ status: 429, body: { error: "rate limited" } }));+ const p = new OpenAICompatProvider(cfg({ maxRetries: 2 }), { backoffMs: [1] });+ let err: SearchError | null = null;+ try {+ await p.embed(["x"]);+ } catch (e) {+ err = e as SearchError;+ }+ expect(err?.code).toBe("EMBEDDING_PROVIDER_HTTP");+ expect(server.callCount()).toBe(2);+});+test("embed() fails over to the next key on 401 and pins the working key", async () => {const seenKeys: string[] = [];server.setHandler((req) => {@@ -271,6 +306,7 @@ test("makeProvider returns NullProvider when semantic is disabled", () => {concurrency: 1,batchSize: 1,costGateUsd: 0,+ maxRetries: 3,});expect(p).toBeInstanceOf(NullProvider);});@@ -288,6 +324,7 @@ test("makeProvider throws when key is missing under openai-compat", () => {concurrency: 1,batchSize: 1,costGateUsd: 0,+ maxRetries: 3,}),).toThrow(/embedding_api_key/);});diff --git a/tests/core/search/embeddings.zeroentropy.test.ts b/tests/core/search/embeddings.zeroentropy.test.tsindex 6ac7dc30..836649ee 100644--- a/tests/core/search/embeddings.zeroentropy.test.ts+++ b/tests/core/search/embeddings.zeroentropy.test.ts@@ -20,6 +20,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddinconcurrency: 2,batchSize: 32,costGateUsd: 0,+ maxRetries: 3,...overrides,});}diff --git a/tests/core/search/index-offline.test.ts b/tests/core/search/index-offline.test.tsindex cba8c779..0cbb74b0 100644--- a/tests/core/search/index-offline.test.ts+++ b/tests/core/search/index-offline.test.ts@@ -97,6 +97,7 @@ test("the semantic backend is declared when embeddings are computed", async () =concurrency: 2,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});diff --git a/tests/core/search/indexer-abort.test.ts b/tests/core/search/indexer-abort.test.tsindex e3fe458e..129ea916 100644--- a/tests/core/search/indexer-abort.test.ts+++ b/tests/core/search/indexer-abort.test.ts@@ -126,6 +126,7 @@ test("aborting between embed batches stops further embedding but keeps committedconcurrency: 1,batchSize: 1,costGateUsd: 0,+ maxRetries: 3,},});// Index documents first (no embeddings), so the abort isolates thediff --git a/tests/core/search/indexer.embeddings.test.ts b/tests/core/search/indexer.embeddings.test.tsindex dc3e4820..8e768d23 100644--- a/tests/core/search/indexer.embeddings.test.ts+++ b/tests/core/search/indexer.embeddings.test.ts@@ -40,6 +40,7 @@ function semanticConfig(model = "fake-model", dim = 4) {concurrency: 2,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});}@@ -104,6 +105,7 @@ test("--embeddings without a key throws EMBEDDING_KEY_MISSING", async () => {concurrency: 1,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});let err: SearchError | null = null;diff --git a/tests/core/search/local-embedder-rrf.integration.test.ts b/tests/core/search/local-embedder-rrf.integration.test.tsindex cdca2f7a..be2ea46b 100644--- a/tests/core/search/local-embedder-rrf.integration.test.ts+++ b/tests/core/search/local-embedder-rrf.integration.test.ts@@ -46,6 +46,7 @@ function localConfig(fusionMode: "linear" | "rrf" = "linear") {concurrency: 2,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});}diff --git a/tests/core/search/search.test.ts b/tests/core/search/search.test.tsindex aaac402e..305e7e01 100644--- a/tests/core/search/search.test.ts+++ b/tests/core/search/search.test.ts@@ -42,6 +42,7 @@ function semanticConfig() {concurrency: 2,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});}@@ -347,6 +348,7 @@ test("explicit --semantic without vec extension throws (configured-down case)",concurrency: 1,batchSize: 8,costGateUsd: 0,+ maxRetries: 3,},});await indexVault(cfg);diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.tsindex 79d73c84..fa2262a3 100644--- a/tests/core/search/store.test.ts+++ b/tests/core/search/store.test.ts@@ -26,6 +26,7 @@ function makeConfig(overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchCoconcurrency: 4,batchSize: 32,costGateUsd: 0,+ maxRetries: 3,});return Object.freeze({vault: tmp,diff --git a/tests/core/search/store.vec.test.ts b/tests/core/search/store.vec.test.tsindex 720e01e9..6dec9f2d 100644--- a/tests/core/search/store.vec.test.ts+++ b/tests/core/search/store.vec.test.ts@@ -29,6 +29,7 @@ function semanticConfig(concurrency: 4,batchSize: 32,costGateUsd: 0,+ maxRetries: 3,});return Object.freeze({vault: tmp,diff --git a/tests/helpers/search-fixtures.ts b/tests/helpers/search-fixtures.tsindex b771c26c..56704e17 100644--- a/tests/helpers/search-fixtures.ts+++ b/tests/helpers/search-fixtures.ts@@ -97,6 +97,7 @@ export function makeConfig(opts: {concurrency: 4,batchSize: 32,costGateUsd: 0,+ maxRetries: 3,});const semantic: ResolvedEmbeddingConfig = Object.freeze({...baseSemantic,diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.tsindex 5f84a2f0..370b80c7 100644--- a/tests/hooks/active-inject.test.ts+++ b/tests/hooks/active-inject.test.ts@@ -39,6 +39,9 @@ async function runHook(payload: unknown, env: Record<string, string> = {}): Promconst inherited: Record<string, string> = {PATH: process.env["PATH"] ?? "",HOME: configHome,+ // Isolate the active.md injection behaviour from the runtime-notice+ // channel by default; the dedicated notice test re-enables it.+ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",};const proc = Bun.spawn(["bun", "run", HOOK], {stdin: "pipe",@@ -246,4 +249,35 @@ describe("active-inject hook", () => {expect(r.exit).toBe(0);expect(r.stdout).toBe("");});++ test("prepends a runtime-notice block when a transient condition holds", async () => {+ writeActive(+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` — Rule body\n",+ );+ // Notices on (override the harness default); no search index exists in+ // this bare vault, so the index-missing notice fires and rides the surface.+ const r = await runHook(+ { hook_event_name: "SessionStart" },+ { VAULT_DIR: vault, OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "true" },+ );+ expect(r.exit).toBe(0);+ const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;+ expect(injected).toContain("Runtime notices:");+ expect(injected).toContain("Search index is not built");+ // The active body still follows the notice block.+ expect(injected).toContain("pref-foo");+ expect(injected.indexOf("Runtime notices:")).toBeLessThan(injected.indexOf("pref-foo"));+ });++ test("injects notices alone when there is no active.md body", async () => {+ // No active.md at all; the notice channel still surfaces the condition.+ const r = await runHook(+ { hook_event_name: "SessionStart" },+ { VAULT_DIR: vault, OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "true" },+ );+ expect(r.exit).toBe(0);+ const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;+ expect(injected).toContain("Runtime notices:");+ expect(injected).toContain("Search index is not built");+ });});diff --git a/tests/hooks/process-ceiling.test.ts b/tests/hooks/process-ceiling.test.tsnew file mode 100644index 00000000..16548325--- /dev/null+++ b/tests/hooks/process-ceiling.test.ts@@ -0,0 +1,93 @@+import { expect, test } from "bun:test";++import {+ DEFAULT_HOOK_CEILING_MS,+ armProcessCeiling,+ resolveHookCeilingMs,+} from "../../hooks/lib/process-ceiling.ts";++test("armProcessCeiling schedules at the configured ceiling and self-terminates on expiry", () => {+ let scheduledMs = -1;+ let fired: (() => void) | null = null;+ const exits: number[] = [];+ let expired = false;++ const disarm = armProcessCeiling({+ ceilingMs: 55_000,+ onExpire: () => {+ expired = true;+ },+ exit: (code) => {+ exits.push(code);+ },+ setTimer: (fn, ms) => {+ scheduledMs = ms;+ fired = fn;+ return { id: 1 };+ },+ clearTimer: () => {+ /* not expected in this test */+ },+ });++ expect(scheduledMs).toBe(55_000);+ expect(exits).toEqual([]);++ // Simulate the process still running at the deadline.+ fired!();+ expect(expired).toBe(true);+ expect(exits).toEqual([0]);++ disarm();+});++test("disarming before the ceiling clears the timer and never exits", () => {+ const exits: number[] = [];+ let cleared: unknown = null;++ const disarm = armProcessCeiling({+ ceilingMs: 1_000,+ exit: (code) => exits.push(code),+ setTimer: () => ({ id: 42 }),+ clearTimer: (handle) => {+ cleared = handle;+ },+ });++ disarm();+ expect(cleared).toEqual({ id: 42 });+ // Idempotent: a second disarm is a no-op.+ disarm();+ expect(exits).toEqual([]);+});++test("an onExpire that throws still lets the process exit", () => {+ const exits: number[] = [];+ let fired: (() => void) | null = null;+ armProcessCeiling({+ ceilingMs: 10,+ onExpire: () => {+ throw new Error("audit blew up");+ },+ exit: (code) => exits.push(code),+ setTimer: (fn) => {+ fired = fn;+ return {};+ },+ clearTimer: () => {},+ });+ fired!();+ expect(exits).toEqual([0]);+});++test("resolveHookCeilingMs: default, override, and invalid fallback", () => {+ expect(resolveHookCeilingMs({})).toBe(DEFAULT_HOOK_CEILING_MS);+ expect(resolveHookCeilingMs({ OPEN_SECOND_BRAIN_HOOK_CEILING_MS: "30000" })).toBe(30_000);+ // Below the floor and non-numeric fall back to the default.+ expect(resolveHookCeilingMs({ OPEN_SECOND_BRAIN_HOOK_CEILING_MS: "10" })).toBe(+ DEFAULT_HOOK_CEILING_MS,+ );+ expect(resolveHookCeilingMs({ OPEN_SECOND_BRAIN_HOOK_CEILING_MS: "nope" })).toBe(+ DEFAULT_HOOK_CEILING_MS,+ );+});diff --git a/tests/mcp/count-guard.test.ts b/tests/mcp/count-guard.test.tsnew file mode 100644index 00000000..5d445341--- /dev/null+++ b/tests/mcp/count-guard.test.ts@@ -0,0 +1,111 @@+/**+ * Acceptance: the --expect / --strict count guards and matched-vs-changed+ * reporting wired into brain_hygiene apply (t_67e491f6). A mismatched --expect+ * or a guardless --strict aborts BEFORE writing (the vault is untouched); a+ * matching guard applies and reports honest matched/changed counts.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-count-guard-"));+ bootstrapBrain(vault);+ writePref("dup-a", "same-topic", "collect metrics before optimizing the code");+ writePref("dup-b", "same-topic", "collect metrics before optimizing the code base");+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function writePref(slug: string, topic: string, principle: string): void {+ writeFileSync(+ join(vault, "Brain", "preferences", `pref-${slug}.md`),+ [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "tags: [brain, brain/preference]",+ `topic: ${topic}`,+ "_status: confirmed",+ `principle: ${principle}`,+ "created_at: 2026-01-01T00:00:00Z",+ "unconfirmed_until: 2026-01-15T00:00:00Z",+ "---",+ "",+ ].join("\n"),+ "utf8",+ );+}++async function init(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "t", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+}++async function call(server: MCPServer, args: Record<string, unknown>): Promise<any> {+ return (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_hygiene", arguments: args },+ })) as any;+}++async function scanIds(server: MCPServer): Promise<string[]> {+ const scan = await call(server, { mode: "scan", detectors: ["dedup"] });+ const findings = scan.result.structuredContent.findings as Array<{ id: string }>;+ return findings.map((f) => f.id);+}++test("a mismatched --expect aborts the apply without writing", async () => {+ const server = new MCPServer({ vault });+ await init(server);+ const ids = await scanIds(server);+ expect(ids.length).toBeGreaterThan(0);++ const r = await call(server, { mode: "apply", ids, expect: 999 });+ // INVALID_PARAMS with the guard message; nothing is deleted.+ expect(r.error.code).toBe(-32602);+ expect(r.error.message).toContain("--expect 999");+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-b.md"))).toBe(true);+});++test("--strict refuses a guardless apply", async () => {+ const server = new MCPServer({ vault });+ await init(server);+ const ids = await scanIds(server);+ const r = await call(server, { mode: "apply", ids, strict: true });+ expect(r.error.code).toBe(-32602);+ expect(r.error.message.toLowerCase()).toContain("strict");+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-b.md"))).toBe(true);+});++test("a matching --expect applies and reports matched vs changed", async () => {+ const server = new MCPServer({ vault });+ await init(server);+ const ids = await scanIds(server);+ const matched = ids.length;+ const r = await call(server, { mode: "apply", ids, expect: matched });+ const s = r.result.structuredContent;+ expect(s.matched).toBe(matched);+ expect(s.changed).toBe(s.applied.length);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-b.md"))).toBe(false);+});diff --git a/tests/mcp/http-transport.test.ts b/tests/mcp/http-transport.test.tsindex f8ee3417..e7fb825a 100644--- a/tests/mcp/http-transport.test.ts+++ b/tests/mcp/http-transport.test.ts@@ -1,10 +1,46 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdtempSync, rmSync } from "node:fs";+import { request } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";import { JSONRPC_VERSION, PROTOCOL_VERSION, startHttp } from "../../src/mcp/index.ts";+interface RawResponse {+ readonly status: number;+ readonly body: string;+}++/**+ * Raw HTTP request with fully-controllable headers (fetch forbids overriding+ * Host). Used to exercise the DNS-rebinding guard.+ */+function rawRequest(+ url: string,+ opts: { method?: string; headers?: Record<string, string>; body?: string } = {},+): Promise<RawResponse> {+ const u = new URL(url);+ return new Promise((resolve, reject) => {+ const req = request(+ {+ hostname: u.hostname,+ port: u.port,+ path: u.pathname,+ method: opts.method ?? "GET",+ headers: opts.headers ?? {},+ },+ (res) => {+ let body = "";+ res.on("data", (c) => (body += c));+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));+ },+ );+ req.on("error", reject);+ if (opts.body !== undefined) req.write(opts.body);+ req.end();+ });+}+interface JsonObject {readonly [key: string]: any;}@@ -41,8 +77,125 @@ async function post(}describe("Streamable HTTP MCP transport", () => {- test("refuses to start without an API key", async () => {- await expect(startHttp({ vault }, { host: "127.0.0.1", port: 0 })).rejects.toThrow(/api-key/i);+ test("refuses to bind a non-loopback host without an API key", async () => {+ await expect(startHttp({ vault }, { host: "0.0.0.0", port: 0 })).rejects.toThrow(/api-key/i);+ });++ test("starts on loopback without an API key (guards are the baseline)", async () => {+ const handle = await startHttp({ vault }, { host: "127.0.0.1", port: 0 });+ try {+ const res = await post(+ handle.url,+ rpc("initialize", 1, { protocolVersion: PROTOCOL_VERSION, capabilities: {} }),+ );+ expect(res.status).toBe(200);+ const body = await responseJson(res);+ expect(body.result.protocolVersion).toBe(PROTOCOL_VERSION);+ } finally {+ await handle.close();+ }+ });++ test("GET /health returns 200 without a bearer", async () => {+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "127.0.0.1", port: 0 });+ try {+ const res = await rawRequest(`${handle.url}/health`, { method: "GET" });+ expect(res.status).toBe(200);+ expect(JSON.parse(res.body).status).toBe("ok");+ } finally {+ await handle.close();+ }+ });++ test("rejects a mismatched Host header (DNS-rebinding guard)", async () => {+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "127.0.0.1", port: 0 });+ try {+ const res = await rawRequest(handle.url, {+ method: "POST",+ headers: { host: "evil.example.com", "content-type": "application/json" },+ body: JSON.stringify(rpc("ping", 1)),+ });+ expect(res.status).toBe(403);+ expect(res.body).toContain("Host not allowed");+ } finally {+ await handle.close();+ }+ });++ test("rejects a cross-origin Origin header", async () => {+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "127.0.0.1", port: 0 });+ try {+ const res = await rawRequest(handle.url, {+ method: "POST",+ headers: {+ host: `127.0.0.1:${handle.port}`,+ origin: "http://evil.example.com",+ authorization: "Bearer secret",+ "content-type": "application/json",+ },+ body: JSON.stringify(rpc("ping", 1)),+ });+ expect(res.status).toBe(403);+ expect(res.body).toContain("Origin not allowed");+ } finally {+ await handle.close();+ }+ });++ test("a non-loopback (0.0.0.0) bind accepts the machine's real Host/Origin", async () => {+ // Binding a wildcard is an explicit network exposure gated by the mandatory+ // bearer; the DNS-rebinding Host/Origin guard (a loopback-only concern)+ // must not reject the machine's real IP / DNS Host, which would make+ // 0.0.0.0 unusable. We connect over loopback but present a foreign Host.+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "0.0.0.0", port: 0 });+ try {+ const res = await rawRequest(`http://127.0.0.1:${handle.port}`, {+ method: "POST",+ headers: {+ host: "box.internal.example",+ origin: "http://box.internal.example",+ authorization: "Bearer secret",+ "content-type": "application/json",+ },+ body: JSON.stringify(rpc("ping", 1)),+ });+ expect(res.status).toBe(200);+ } finally {+ await handle.close();+ }+ });++ test("a non-loopback bind still enforces the bearer", async () => {+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "0.0.0.0", port: 0 });+ try {+ const res = await rawRequest(`http://127.0.0.1:${handle.port}`, {+ method: "POST",+ headers: { host: "box.internal.example", "content-type": "application/json" },+ body: JSON.stringify(rpc("ping", 1)),+ });+ expect(res.status).toBe(401);+ } finally {+ await handle.close();+ }+ });++ test("accepts a loopback Origin", async () => {+ const handle = await startHttp({ vault }, { apiKey: "secret", host: "127.0.0.1", port: 0 });+ try {+ const res = await rawRequest(handle.url, {+ method: "POST",+ headers: {+ host: `127.0.0.1:${handle.port}`,+ origin: `http://127.0.0.1:${handle.port}`,+ authorization: "Bearer secret",+ "content-type": "application/json",+ },+ body: JSON.stringify(rpc("ping", 1)),+ });+ expect(res.status).toBe(200);+ } finally {+ await handle.close();+ }});test("uses generic 401 for missing and wrong API keys", async () => {diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex f7762dcf..ffd1c2ee 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -464,6 +464,8 @@ describe("tool calls", () => {expect(names.has("vault_writeable")).toBe(true);expect(names.has("claude_manifest")).toBe(true);expect(names.has("hermes_manifest")).toBe(true);+ // Runtime-state notices ride the pull surface too (array, empty when clean).+ expect(Array.isArray(s.notices)).toBe(true);});test("unknown tool returns method-not-found", async () => {