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: what this install knows (v1.56.0) (#185)
Sol Aitken54bb28d9b760
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 250ab1c6..bdd4b35c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.55.0",+ "version": "1.56.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 7583cd23..14efdf48 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.55.0",+ "version": "1.56.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 0fbe5b34..68342d08 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,43 @@ 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.56.0] - 2026-09-12++Open Second Brain answers a great deal about the vault it owns and, until this release, very little about itself. An operator with a shell could not ask which version was installed, though the MCP handshake had carried the same fact as `serverInfo.version` since the server existed. An agent on the MCP surface could not ask which projects point at this vault or whether the hosts this install wrote registrations into can still be reached, though both answers had shipped as typed readers with CLI-only consumers. And the first block of text every agent reads at connect time was three frozen strings chosen by scope alone, so a host that disabled a tool still received a paragraph instructing the agent to call it - a confident answer that was wrong before the session began. Nothing in this release computes a new fact. Four surfaces start reading what four readers already produce, and the machinery that made them unreachable is the whole of what changed.++Every card in scope was read against the live source before anything was designed, and three of the five verdicts amended the card. The version card asked to reuse an existing `packageJson.version` import and understated the problem: three independent reads of that field existed in the tree, so adding a fourth would have written the defect into the change meant to answer it. The linked-projects card is smaller than it states - both readers are already pure, typed and tolerant, and the absolute-path question it raises is answered by the shipped `expose_host_paths` contract rather than by a new rule. The connector-health card is largely refuted: per-target status is already a closed vocabulary, an unverified probe is already a named member carrying its reason rather than an assumed success, the deadline is already enforced at ten seconds per probing target, and the aggregate view its own validator believed was the remaining gap already ships as `o2b install --check`. What survives is narrower and of a different shape than the card states, and it is stated in the Notes below along with the one card that was refused outright and not built.++### Added++- **`o2b version`, and `--version` as its synonym.** The verb prints the installed version and exits 0; `--json` renders `{"version":"…"}` for a caller that parses. The root flag is routed to the same renderer rather than printing a line of its own, because two spellings of one question that answer differently are worse than one spelling - the difference is invisible until someone pastes the wrong one into a bug report. Both are declared in the command manifest, so shell completions and `o2b help --json` offer them. `o2b version latest` is a usage error rather than a print of the local version: nothing in this build learns what any other version is, and answering that question with the installed number would be the wrong answer wearing the right shape.+- **`second_brain_wiring`: what this install is wired into.** One read-only tool with a required `view` and no aggregate member, so a projects read never pays for a host probe and every payload stays bounded - the same idiom `brain_brief`, `brain_analytics` and `schema_inspect` already use, for the same token reason. `view=projects` returns one entry per registered project link carrying the four-value pointer state and whether the vault it names still exists, off `linkedProjectsStatus`, which had one consumer and none under `src/mcp`. `view=hosts` returns one entry per registered install target carrying the target, the `VerifyStatus` member, the adapter's details and its fix hint, from the same `verify()` call over the same registry and the same `InstallEnv` that `o2b install --check` makes. An absent or unknown view is refused with `-32602` naming the accepted members, and so is a `hosts` read with no resolved vault. Paths do not travel: `project_ref` and `vault_ref` render through the shipped `expose_host_paths` contract, and because the hosts view carries the adapter's own sentences - which `verify()` composes from the host home, where no store reference applies - the home prefix in those is folded to `~` under the same flag. An MCP response lands in model context, so the payload that hashes the vault path must not name the operator's account beside it.+- **The handshake instructions are rendered from the live capability report.** This server has evaluated a runtime capability window in its constructor for several releases and knows, per tool, whether it is available or withheld and why. `initialize.instructions` did not read it. Guidance whose tool this runtime withheld is now REMOVED rather than contradicted - an instruction and its retraction in one document leave the reader deciding which half is true, and the half printed first is the half that shapes the plan - and a block at the end names each removed tool with the reason the evaluator produced, inventing no second vocabulary. Each scope body is an ordered list of paragraphs of tool-tagged segments; a segment renders when every tool it names is available, the separator of the preceding rendered segment joins the survivors so a dropped clause takes its punctuation with it, and a paragraph whose every tool-bearing segment dropped renders nothing at all, its lead-in included, because "Five tools live here" is a claim that stops being true the moment one of them is withheld.++### Changed++- **One version constant, and the tree's only manifest import.** `src/core/version.ts` exports `OPEN_SECOND_BRAIN_VERSION`; the continuity export header, the MCP handshake and the stamped opencode plugin read it. A census over `src/` holds the import to exactly one module - an equality with a positive control, not a floor - so the fourth copy cannot appear quietly. The same import was previously written two ways, with and without the `with { type: "json" }` attribute, and is now written once.+- **The install environment is built in one place.** `buildInstallEnv` moved from the `o2b install` verb into `src/core/install/env.ts`, so the MCP hosts view verifies the same machine the CLI does. Two builders would be two answers to which machine is under verification, which is the split that constructor's own documentation was written to close. The CLI verb keeps its argument resolution and delegates the construction, and the sentence a run with no vault refuses with is now one constant both surfaces read.+- **The path policy generalises rather than repeats.** `vaultPathField` is now `hostPathReference(path, source)` applied to the vault; `vaultStoreReference` never required the path to be the vault. Both sides of a project link render through it, so `project_ref` and `vault_ref` follow the same `expose_host_paths` contract `vault_path` obeys - an opaque `vault://<hex>` by default, the raw path when the operator sets the flag - and a config that cannot be read renders `{ "error": … }` rather than degrading to the path the reference exists to hide.+- **The instruction block's fully-available render is byte-identical to what shipped before,** pinned against fixtures captured from the strings it replaces, so a reshaping of three bodies cannot become a rewrite of their meaning without a test saying so. One sentence in the `catalog` body is the declared exception, and it is listed under Fixed below. A segment naming a tool its scope does not register fails an orphan census in the same file, so a renamed tool cannot silently take its guidance with it.++### Fixed++- **The dream observer-equivalence test normalised a field but not the hashes derived from it.** `attaching an observer changes nothing the pass writes` compares two vault trees and already normalised the snapshot archive's `size_bytes`, which is nondeterministic because a tar carries the mtimes of the tree it was taken from and the two copies straddle a second under load. The day log's chain hashes are computed over the payload including that real size, and every later line chains off the first through `prev`, so one straddled second re-keyed the whole file in the two places the field had just been removed from. It passed on every developer box and failed on a loaded CI runner. The chain fields are now normalised alongside the size, with the reason stated: the chain has its own end-to-end integrity suites, and what this test asserts is that the observer changed nothing the pass authored.+- **A before-image stamped in the future was never pruned.** `pruneWriteImages` measures each image with `fileAgeMs` and floors the result to whole days. `fileAgeMs` deliberately does not clamp - a file stamped ahead of the clock is a real condition it reports rather than hides - so an age of -1ms became -1 whole day, which is below every retention window including zero, and the image was kept forever. The condition is ordinary rather than exotic: `nowMs` is sampled once before the sweep, and mtime granularity on a synced or networked filesystem rounds a write made just before it up past that sample. It turned CI red on one image of two. The sweep now floors a non-positive age to zero at the call site, where the floor is part of retention's meaning rather than of the measurement, and a test stages the future-stamped image deterministically instead of waiting for the race.+- **`view=projects` returned an unbounded list.** The tool takes a preview-budget exemption whose reason claimed both views were bounded by construction. That is true of `view=hosts` - one entry per adapter in a registry this build closes - and false of `view=projects`, which reads a registry nothing caps: every `o2b brain project link` appends to `projects.json`, and the serialized response grows with it, inline, into model context. The list is now capped at twenty-five and carries `total`, `returned` and `truncated` beside it, the same self-declaring shape the page-lint report uses, so a capped answer cannot be read as a complete one. Capped rather than budgeted because the preview budget is per tool and not per view: at ~2000 characters it would park the hosts view, which renders around 1700 with nothing installed, in an artifact on nearly every call. The exemption reason now states what actually bounds each view.+- **The unresolvable path reference reported the config path into model context.** When the device-local config cannot be read, `vault_path` - and now `project_ref` and `vault_ref` with it - degrade to `{ "error": … }` rather than raising or falling back to the raw path. The reason carried was `ConfigReadError`'s own message, which names the config file twice, once in the condition and once in the `chmod` remedy. That message is right on the four channels it was written for; this is not one of them. It is the field forty-five tools emit precisely so that an absolute path under the operator's home does not travel into model context, so reporting the condition by naming that path reintroduced, in the degraded branch, the leak the resolved branch prevents. The field now carries a path-safe reason and points at `second_brain_status`, which names the file from a field whose contract is to name it.+- **The catalog handshake told the agent that a withheld tool was still callable.** The frozen string said every tool omitted from `tools/list` stays CALLABLE through `tools/call`, which is true of the tools the catalog surface hides and false of the ones a runtime capability window withholds: the window removes them from the very table `tools/call` routes on. Carrying that sentence unchanged into a rendering whose whole subject is the window would ship a handshake contradicting the runtime it was rendered for - the defect this release exists to remove, one paragraph over. The sentence now separates the two cases, the pinned `catalog` fixture carries the corrected text, and the exception to byte-identity is stated in the fixture test, in the module that renders it and in `docs/mcp.md`.+- **Two places said the catalog advertises seven tools without saying when.** `evaluateToolCapabilities` applies the runtime window before counting, so a window withholding one of those seven lowers `advertised_tool_count` with it. The `advertised_tool_count` docblock and the matching `docs/mcp.md` paragraph now state that seven is the no-window count, and name the capability diagnostic as the one tool no window withholds.+- **`docs/mcp.md` said the full server advertises 111 tools.** It advertised 114 before this release and 115 after. Two further counts in the same file were stale in the same way and are fixed with it: the full surface was also given as 49 in the `.mcp.json` section, which now points at the one place the number is stated, and the `catalog` gap was given as a figure that goes stale on the next tool added. That one is restated as the relation it always was - the catalog advertises seven whatever the tool table holds - in the doc and in the `advertised_tool_count` docblock it mirrors, so there is no number left there to drift.++### Notes++- **Release awareness was scoped, verified against the source, and not built.** The card asked for a surface reporting whether a newer version is available "by reading only cached update state". There is no producer for that cache: a search across `src/` for `latestVersion`, `latest_version`, `update-check`, `updateCheck` and `registry.npmjs` returns nothing, so nothing in this tree ever learns what the latest release is. Filling the cache requires a network check, and `renderDataOwnership` in `src/core/install/ownership.ts` renders to the operator, verbatim, that this tool has no server it phones home to, no sync endpoint and no update check. Building the card as written means either making that statement false or shipping a surface whose only possible answer is that it has nothing to report. A collision the card did not see: `o2b update` already exists and means re-applying managed install blocks to host configs, so the obvious verb is taken and the obvious name would mislead about an existing one. The two honest alternatives - registering an outbound release check in the egress registry as a network site like every other outbound path, or reading a version fact some other component already fetched and saying where it came from - both amend an operator-facing promise about network behaviour. That is an operator policy decision rather than an engineering one, and it is recorded here for the operator to take rather than taken on their behalf. The upgrade-plan half of the card needs nothing: `src/core/brain/upgrade.ts` is already a plan and apply migrator.+- The `hosts` view may ask host CLIs, and its description says so. Two of the registered targets declare a host probe, so a worst-case call adds two subprocess round trips, each bounded by the ten-second deadline `--check` already enforces; a diagnostic that can take twenty seconds and does not say so is a surprise. A probe that could not run renders its named reason instead of an assumed success, which is the property the probe module already held and this view carries through unchanged.+- An unresolved vault is refused by name on the `hosts` view rather than reported as ten absent runtimes. `verify()` reads the per-vault sidecar manifest, so an unset vault produces `not-installed` for every target off a path that does not exist - a wrong answer wearing the authority of a completed check.+- The withheld block in the instructions lists the tools that text would have instructed, not the whole withheld set: a `--max-tools` window can withhold over a hundred tools, and pasting that list into the first thing every agent reads would cost more than the guidance it explains. It points at `second_brain_capabilities` on the surfaces that register it. No capability window ever withholds that tool, but the writer scope never registers it at all, and a handshake sending an agent to a tool its own server answers `unknown tool` for would be the defect this rendering removes, reintroduced by the sentence explaining the removal; there the block ends with the names.+- One test limit is stated rather than implied. `os.homedir()` in this runtime does not follow a later `process.env.HOME`, so an in-process test cannot redirect the home the `hosts` view resolves. The named-probe-skip case therefore builds the `InstallEnv` by hand, as the adapter suites do, and asserts the view's own mapping over the real `verify()` answer; a separate deep-equality test is what ties that mapping to the environment the view builds.+## [1.55.0] - 2026-09-10Open Second Brain has known who wrote a signal or a preference since the log shipped, has taken a snapshot before every destructive pass since 0.10, and has sharded the Brain log per device since 0.10.8 so that two machines syncing one vault never fight over one file. What it could not say was who wrote a note. A `brain_create_note`, an `update_note`, an `append_note` or a `write_batch` left no event in the log and no row in any roster, and the bulk of what an agent produces was therefore invisible to attribution, to `brain_event_trace`, and to any rollback finer than the whole `Brain/` tree at a snapshot instant. This release closes that, and the four things that follow from closing it. Every note write now emits one `note-write` event carrying a write id, the operation, the target, the content hash and byte size on both sides, the caller-asserted agent and the server-derived origin channel, with the device riding on the shard name as it does for every event, and the bytes the write replaced kept in a content-addressed store so that a revert has something to restore from. A revert is a plan over those events for one agent, device or path in a window - restore, delete, or a refusal by name when another writer sits on top - sealed by a digest, applied only as the exact plan the operator read, under a snapshot, and recorded as a write of its own so that a revert is itself attributable and revertible. A freeze marker at `Brain/.state/frozen.json`, carried by Syncthing to every device, is refused by name at the one guard every content writer already passes, while the Brain log keeps recording so the refusals are auditable; `o2b brain freeze` and `o2b brain unfreeze` are the operator verbs and `o2b brain status`, `brain_status` and `brain_doctor` all say so. The shard rule the log has followed for a year is now the rule for every append-only ledger in the vault - continuity, idempotency, preference audit, metrics and session lineage each write `<base>.<device-id>.jsonl` and merge every shard at read, and the doctor names a sync-conflict copy under any of those directories, not only the log. And because the log is now the attribution record for every write, every JSONL line it appends carries a per-shard hash chain: a line that was edited, removed or stripped after it was written has a file and a line number, reported by `o2b brain log verify` and the doctor and never used to gate a read.@@ -7458,6 +7495,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.56.0]: https://github.com/itechmeat/open-second-brain/compare/v1.55.0...v1.56.0[1.55.0]: https://github.com/itechmeat/open-second-brain/compare/v1.54.0...v1.55.0[1.54.0]: https://github.com/itechmeat/open-second-brain/compare/v1.53.1...v1.54.0[1.53.1]: https://github.com/itechmeat/open-second-brain/compare/v1.53.0...v1.53.1diff --git a/README.md b/README.mdindex 89e85556..f650efcc 100644--- a/README.md+++ b/README.md@@ -8,9 +8,11 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm## What is new-Open Second Brain 1.54.0 turns `visibility:` from a label into a boundary. The field, the predicate that reads it and the filter that applies it have all shipped for several releases, and until now the filter was wired into one call site and the scope it filtered against came from the caller - so a remote caller that asked for the private scope was handed it. One reserved token is now denied by default at remote reach, enforced at the three roots every read surface reaches page content through: the ranked search pipeline, the page walker, and the by-path and by-chunk-id read primitives. An architecture sweep proves mechanically that there is no fourth root, and it found two direct filesystem reads on its first run.+Open Second Brain 1.56.0 teaches this install to answer questions about itself. `o2b version` prints the installed version and `--version` is routed to the same renderer rather than printing a line of its own, because two spellings of one question that answer differently are worse than one spelling; `--json` renders `{"version":"…"}` for a caller that parses, and `o2b version latest` is a usage error rather than a print of the local number, because nothing in this build learns what any other version is. The MCP handshake has reported that same fact as `serverInfo.version` since the server existed, and both surfaces now read one constant that the tree imports exactly once, held there by a census with a positive control. `second_brain_wiring` puts two readers that had CLI-only consumers on the MCP surface, behind a required `view` and with no aggregate member, so a projects read never pays for a host probe: `view=projects` returns one entry per registered project link with the four-value pointer state and whether the vault it names still exists, and `view=hosts` returns the per-target verdict of the same `verify()` call `o2b install --check` makes, over the same registry and the same install environment, which is now built in one place instead of two. Paths do not travel with either answer - both sides of a project link, and the host home inside an adapter's own sentences, render through the shipped `expose_host_paths` contract, opaque by default and raw only when the operator sets the flag. And the instruction block every agent reads at connect time is rendered from the runtime capability window this server has evaluated for several releases and never consulted: guidance whose tool the host disabled is removed rather than contradicted, each removal named with the reason the evaluator produced, and a paragraph whose every tool-bearing clause dropped renders nothing at all, its lead-in included, because "Five tools live here" stops being true the moment one of them is withheld. With nothing withheld, the rendered text is byte-identical to the three frozen strings it replaces, pinned by fixtures captured from them - save for one sentence in the catalog body, which claimed every tool omitted from `tools/list` stays callable through `tools/call`. That holds for the tools the catalog surface hides and not for the ones a window withholds, so it now separates the two cases.-The reach that decides is a transport fact, not a request field. stdio and the command line mint `local`, because the caller already started the process and holds whatever filesystem access it runs with; every non-loopback HTTP bind mints `remote`. A caller that puts a reach-shaped argument in a tool call is refused by name rather than quietly ignored, and what the local bypass actually proves is written down where it is defined rather than overclaimed. A withheld page is reported exactly as an absent one - byte for byte on the key-addressed reads, where the key spaces are enumerable and a distinguishable refusal would be an existence oracle over the population being hidden. Twenty-four of the seventy-six enumerated note-returning surfaces now consult the field, up from three of seventy-one, and `o2b search check` reports the honest remainder alongside the count of pages the boundary withholds. Schema 12 records what the index measured of each page's frontmatter and backfills it from data the index already holds, so a vault that never wrote the token sees no change at all and no operator has to reindex to get there.+Nothing in this release computes a new fact. Four surfaces start reading what four readers already produce, and the machinery that made them unreachable is the whole of what changed. Every card in scope was read against the live source before anything was designed, and three of the five verdicts amended the card: the version card asked to reuse an existing manifest import and understated the problem, because three independent reads of that field already existed and a fourth would have written the defect into the change meant to answer it; the linked-projects card is smaller than it states, both readers being already pure, typed and tolerant; and the connector-health card is largely refuted, the aggregate view its own validator believed was the remaining gap having already shipped as `o2b install --check`. One card was refused rather than built. Release awareness asked for a surface reporting whether a newer version is available by reading only cached update state, and there is no producer for that cache - nothing in this tree ever learns what the latest release is, filling it requires a network check, and this tool renders to the operator, verbatim, that it has no update check. Both honest alternatives amend an operator-facing promise about network behaviour, which is an operator policy decision rather than an engineering one, and it is recorded in the [CHANGELOG](CHANGELOG.md) for the operator to take rather than taken on their behalf.++Previous releases, 1.55.0 and 1.54.0, made every note write an attributable and revertible event - a write record, a before-image store, a planned revert sealed by a digest, a fleet freeze refused at the one guard every content writer passes, and a per-shard hash chain under every append-only ledger - and turned `visibility:` from a label into a boundary enforced at the three roots every read surface reaches page content through. The [CHANGELOG](CHANGELOG.md) has the detail on both.Previous releases, 1.53.1 and 1.53.0, closed a dedup pass that proposed the same merge forever and could write a merge cycle, and taught Hermes recall to carry the turn's query without leaving the curated lane that makes injection safe. The [CHANGELOG](CHANGELOG.md) has the detail on both.@@ -135,6 +137,8 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra- **A today surface for the operator, and prose that writes back.** `o2b brain today` (and `brain_brief view=today`) renders a read-only, live-derived dashboard - due and overdue obligations, open loops, a chronologically merged typed activity timeline with relative ages, and totals - where every section is re-derived on demand from the vault, never stored, and a failing section reports its error while the rest still render. Jot `@osb loop <text>` in any note to keep an intention visible until you close it with `@osb loop close id=<id>` (ids are printed on the dashboard; loop markers survive scans and are never consumed). Jot `@osb set note=<target> field=<field> value=<value>` and `o2b brain apply-markers --apply` turns it into a schema-validated frontmatter mutation - fail-closed target resolution (ambiguous titles list candidates instead of guessing), one `attribute-write` audit event per applied change with the prior value, idempotent consumption of applied markers, and the whole write path gated behind the opt-in `guardrails.marker_writeback` flag. Report mode needs no flag and writes nothing.+- **It knows what it is, and what it is wired into.** `o2b version` answers on the command line the question the MCP handshake has always answered - one constant behind both, so the two surfaces cannot disagree. `second_brain_wiring` puts two CLI-only answers on the MCP surface: `view=projects` lists every project directory registered against this vault with the state of its pointer file, and `view=hosts` runs the same per-adapter verification `o2b install --check` runs, so an agent can ask whether the runtimes this install wired up can still be reached. Paths in those answers are opaque references unless you asked for raw ones. And the instructions block every agent reads at connect time is now rendered from what this runtime actually left callable: guidance for a tool the host disabled is removed rather than contradicted, and each removal is named with its reason.+- **It knows the machine it is installed on.** `o2b install --friction` lays every supported runtime side by side - how it is installed, whether it caps the tool surface, whether a `--check` on it is a file comparison or a live question put to the host, and whether this build can read the transcripts that runtime writes. Two hosts can now be ASKED (`codex mcp list`, `copilot mcp list`) instead of inferred from a config file, so "installed" and "actually loaded" stop being the same answer. `o2b state status` does the same for the vault: forty declared state locations, each with where it resolved, whether it is reachable, and which setting put it there - and `o2b state migrate` moves the lot to another directory behind a digest manifest, refusing before it commits and reversible after. `o2b brain import-session --discover` finds the session logs already on your disk and says which have never been imported, so cross-agent recall no longer depends on your knowing where each runtime keeps its transcripts.That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.diff --git a/docs/architecture.md b/docs/architecture.mdindex 7b647731..67b1135f 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -379,15 +379,15 @@ disclosure, so `warn`'s observability here is the `owner:` stamp appearing onnew files, not a count in any response.The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape-is the point rather than its size. One hundred classified tools carry 229 call-recipes - one per mode, view or operation, because one executed view is not an-executed classification. Every recipe runs TWICE against the same two-owner-fixture, once with the gate closed and once with it open, and the classification-decides what the open run must show: the 32 recipes classified as reaching-owner-taggable content must surface the marker with the gate off, which is what-stops the closed run from passing vacuously. The other 197 carry a claim of-unreachability, and that claim is executed directly - the marker must be absent-even where nothing is hidden. The first version of this probe asserted only the-closed half, and 81 of its entries were driven against arguments that named-artifacts the fixture never created; they could not have failed. Those three-numbers are pinned as equalities in the same file.+is the point rather than its size. One hundred and one classified tools carry+231 call recipes - one per mode, view or operation, because one executed view+is not an executed classification. Every recipe runs TWICE against the same+two-owner fixture, once with the gate closed and once with it open, and the+classification decides what the open run must show: the 32 recipes classified+as reaching owner-taggable content must surface the marker with the gate off,+which is what stops the closed run from passing vacuously. The other 199 carry+a claim of unreachability, and that claim is executed directly - the marker+must be absent even where nothing is hidden. The first version of this probe+asserted only the closed half, and 81 of its entries were driven against+arguments that named artifacts the fixture never created; they could not have+failed. Those three numbers are pinned as equalities in the same file.diff --git a/docs/brainstorm/what-this-install-knows/cli-output/claude.md b/docs/brainstorm/what-this-install-knows/cli-output/claude.mdnew file mode 100644index 00000000..40418981--- /dev/null+++ b/docs/brainstorm/what-this-install-knows/cli-output/claude.md@@ -0,0 +1,38 @@+### Variant 1: Four seams, one refusal+- **Approach**: Ship each card as its own small, independent addition with no shared model. Card 1 hoists the three `package.json` reads into one `src/core/version.ts` constant and adds `o2b version` plus a root `--version` flag on top of it. Card 2 keeps the frozen scope bodies and appends a generated "withheld tools" block rendered from `capabilityReport`. Cards 3 and 4 become two new read-only MCP tools that wrap `linkedProjectsStatus` and the `runCheck` loop directly, emitting absolute paths and always running probes. Card 5 is closed as refused, with the ownership statement and the taken `update` verb cited as the reason, and nothing is built for it.+- **Trade-offs**:+ - Pro: smallest diff, each card reviewable in isolation, no new abstractions.+ - Pro: card 5 handled with zero policy cost and no contract surface to maintain.+ - Con: card 2 is only half truthful. The writer body still names withheld tools in prose, so an agent is still directed to them, and the appended block merely contradicts the paragraph above it.+ - Con: the hosts tool runs up to a dozen 10-second probes sequentially from inside the MCP server, so a single call can block for minutes and spawns host binaries on every read.+ - Con: absolute host paths leave the server with no stated policy, which sits uneasily next to the sibling landscape tool's "vault-relative" charter.+ - Con: the question "is a newer release available" has no answer at all on either surface, so the wave's spine (every self-question answered from live state, unknowns named) is not fully honoured.+- **Complexity**: small+- **Risk**: medium++### Variant 2: One installation report+- **Approach**: Introduce a single read-only core module, `src/core/install/self-report.ts`, that assembles a typed `InstallationReport` with four sections: `version` (from the new shared version constant), `tools` (the existing capability report), `projects` (from `linkedProjectsStatus`, with `pointer` state and a `paths` disclosure flag), and `hosts` (the `VerifyResult[]` aggregate, with probes named `not-run` unless the caller passes `probe: true`, and run concurrently under the existing deadline when they do). The CLI gets `o2b version` and `--version` reading the `version` section, and the MCP server gets one new tool, `brain_mcp_installation`, returning the whole report or one section by argument. Card 2 splits each scope body into a per-tool paragraph map keyed by tool name, and `buildInstructions` renders only paragraphs for `available` tools and appends a withheld list with reasons. Card 5 ships its honest residue as a fifth `release` section whose `state` is a closed vocabulary (`not-checked` today, with `reason: no-update-check-by-policy`), pointing at `docs/updating.md` and the existing `brain upgrade` plan, and the card is recorded as refused-as-specified.+- **Trade-offs**:+ - Pro: one model answers every self-question on both surfaces, and every absent answer is a named vocabulary member, which is the house idiom and the wave's spine.+ - Pro: card 2 becomes fully truthful because withheld tools vanish from prose instead of being contradicted below it.+ - Pro: probes are opt-in and bounded, so the default read is fast and side-effect free, and the "unverified" state is reported by name rather than assumed.+ - Pro: card 5 gets a durable, truthful surface that an agent can query without any network, and the ownership statement stays verbatim.+ - Con: largest diff of the three, touching CLI, MCP, instructions, and a new core module in one PR.+ - Con: the per-tool paragraph map duplicates tool naming already present in the tool registry, so DRY is improved but not perfected.+ - Con: a `release` section that can only ever say `not-checked` risks reading as a placeholder unless the reason text and docs are explicit that the state is deliberate.+- **Complexity**: large+- **Risk**: medium++### Variant 3: Grow the landscape, compare on demand+- **Approach**: Reuse the existing sibling inventory tool instead of adding tools. `brain_mcp_landscape` gains two additive sections, `projects` and `hosts`, backed by the same pure readers, so no new tool name enters `tools/list`. Card 1 adds the shared version constant and `o2b version`, and card 2 uses the same per-tool paragraph filtering as Variant 2. Card 5's residue becomes a pure comparator: `o2b version --compare <semver>` answers `newer | same | older | invalid` for a latest version the operator or harness obtained by their own means, then prints the upgrade plan pointer, so Open Second Brain never fetches, caches, or auto-installs anything.+- **Trade-offs**:+ - Pro: zero new MCP tool names, and existing clients discover the new facts through a tool they already call.+ - Pro: the comparator is deterministic, network-free, and gives scripts the "is newer available" bit once they supply the input.+ - Con: it breaks the landscape module's own written charter. Its header promises that environment values are never read and discovery is vault-relative, while host verification reads host config paths, reports absolute project paths, and may spawn host binaries. Growing that tool makes its rationale false.+ - Con: the comparator answers a question only after the caller has already answered it elsewhere, so its utility is marginal and it adds a flag surface the reference docs must carry forever.+ - Con: loading unrelated host and project data into every landscape call widens a tool whose consumers today expect a small vault inventory.+- **Complexity**: medium+- **Risk**: high++### Recommended: Variant 2+**Rationale**: Variant 2 is the only one where every card lands as a named, closed-vocabulary answer on both the CLI and MCP surfaces, which is the wave's stated spine and the tree's house style, and it is the only one that makes card 2 fully truthful rather than self-contradicting. Its extra size is contained in one new read-only core module and one new tool, and it keeps the ownership statement, the existing `update` verb, and the landscape tool's charter untouched, whereas Variant 3 would falsify a module's own rationale and Variant 1 leaves the release question unanswered on every surface.diff --git a/docs/brainstorm/what-this-install-knows/cli-output/prompt.md b/docs/brainstorm/what-this-install-knows/cli-output/prompt.mdnew file mode 100644index 00000000..414e27cb--- /dev/null+++ b/docs/brainstorm/what-this-install-knows/cli-output/prompt.md@@ -0,0 +1,111 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++This is one release wave bundling five kanban cards under a single spine: every question an agent or operator asks the installation about itself - which version am I, which tools can I actually call, which projects am I linked to, are my connectors reachable, is a newer release available - is answered from live state, and an unknown is named rather than presented as healthy.++The five cards, with the premise verification already performed against live source (these verdicts are facts read from the tree today, not claims to re-derive):++## Card 1 - t_dee1d1fe (priority 4): `o2b version` subcommand and `--version` flag+Add a first-class way for scripts and agent harnesses to read the installed Open Second Brain CLI version, printing `package.json` `version` (the single source of truth), honouring the inherited `--json` flag for structured output.+PREMISE CONFIRMED, with one correction that enlarges the task: there is no `--version` handling in `src/cli/main.ts` and no `version` entry in `src/cli/command-manifest.ts`. But the card says "reuse the existing pattern in `src/cli/brain/verbs/continuity.ts`" as if there were one site. There are THREE independent reads of `package.json` `version` in the tree today: `src/cli/brain/verbs/continuity.ts:40,43` (`CLI_VERSION`), `src/mcp/protocol.ts:9,14` (`SERVER_VERSION`, already reported in the MCP handshake `serverInfo.version`), and `src/core/install/opencode-plugin-asset.ts:39` (embedded in a generated plugin header). Adding a fourth read would make four. The version fact is therefore already answerable over MCP and not over the CLI.++## Card 2 - t_cf827c77 (priority 2): MCP server instructions generated from the active tool allowlist+`initialize.instructions` must be generated from the registered/allowed tool set rather than a hard-coded list, so agents are never directed to tools unavailable in the current runtime profile.+PREMISE CONFIRMED exactly. `buildInstructions` (`src/mcp/instructions.ts:159-162`) selects one of three frozen strings from `SCOPE_BODIES` by `TOOL_SCOPE` and prepends an identity line; nothing else influences it. The handshake at `src/mcp/server.ts:375-378` passes only `agent` and `scope`. The writer body (`src/mcp/instructions.ts:33`) names all five tools in prose. Meanwhile `evaluateToolCapabilities` (`src/mcp/capabilities.ts:41-62`) already computes, per tool, an `available` or `withheld` entry with a human-readable `reason`, plus `available_tool_count`, `advertised_tool_count` and a `host_ceiling` block; it is called in the server constructor (`src/mcp/server.ts:148-155`) and its result is stored on `this.capabilityReport`, so the full report IS in hand at `handleInitialize` time. No plumbing is missing - only the decision of what truthful text to render from it. Existing precedent in the same file: deprecated aliases stay callable but are deliberately not advertised in `tools/list` (`src/mcp/server.ts:383-385`), so the advertised surface differing from the callable one is already an accepted shape here.++## Card 3 - t_49315346 (priority 2): MCP project discovery for linked project contexts+Expose linked projects through a read-only MCP tool so an agent can choose the right project context before invoking memory/search/write tools.+PREMISE CONFIRMED, and the build is smaller than the card assumes. Two pure readers already exist and are typed: `listLinkedProjects` (`src/core/brain/portability/pointer.ts:231-238`, tolerant read so a hand-damaged registry degrades rather than throwing) and `linkedProjectsStatus` (`:245-262`, which additionally reports a four-value pointer state - `missing` | `malformed` | `mismatch` | `ok` - plus a `vaultExists` flag). A grep for both names across `src/` finds consumers ONLY in `src/cli/brain/verbs/project.ts:12,13,59,107`; nothing under `src/mcp` touches them. One open policy question the design must answer: the registry is keyed on ABSOLUTE host filesystem paths (`src/core/brain/portability/pointer.ts:214-216`, `:234`), while every other path this MCP server emits is vault-relative by policy - compare the sibling read-only inventory tool `brain_mcp_landscape` (`src/mcp/brain/landscape-tools.ts:13-35`), which states "Environment values are never read. Discovery is vault-relative."++## Card 4 - t_09d7e9e9 (priority 1): dynamic connector health dashboard with unverified-state labelling+Show connector status, deadline failures and inspection results, and never present an unverified connector as healthy.+PREMISE LARGELY REFUTED - more so than the card's own validator concluded. Everything substantive the card asks for already ships, AND so does the aggregate view the validator believed was the residue:+ - Per-target status is a closed vocabulary on both sides: `AdapterStatus` (`not-installed` | `installed` | `drift` | `unsupported-on-this-platform`, `src/core/install/types.ts:21-27`) and `VerifyStatus` (`ok` | `drift` | `not-installed` | `mcp-unreachable`, `:39-45`).+ - Unverified is already named, never assumed healthy: `HOST_PROBE_RESULT` (`answered` | `binary-missing` | `probe-failed` | `not-declared`, `src/core/install/host-probe.ts:87-93`), whose module header states "A probe that reports success when it could not run is the misleading default this module exists to remove" (`:17-22`).+ - The deadline is already enforced: `HOST_PROBE_TIMEOUT_MS = 10_000` (`src/core/install/host-probe.ts:158`) with the wait bounded in the runner (`:174-181`); the timeout becomes one more named outcome rather than a hang. The probe is keyless, starts no model turn, writes nothing, and spawns under the adapter's injected environment rather than the ambient one.+ - The aggregate exists: `runCheck` (`src/cli/install/install.ts:452-489`) iterates EVERY registered adapter (`defaultRegistry.list()`), collects `VerifyResult[]`, renders a table (`renderVerifyTable`, `src/cli/install/render.ts:176-188`) or structured JSON (`renderVerifyJson`, `:190-198`), and returns an exit code that distinguishes drift from unreachable from ok (`exitCodeForVerify`, `:492-506`).+The genuine residue is therefore narrow and of a different shape than the card states: this whole aggregate is CLI-only. An agent on the MCP surface cannot ask whether the hosts this install wrote registrations into can still be reached. That is the same gap shape as Card 3.++## Card 5 - t_c64b7cab (priority 1): explicit opt-in release awareness+Report whether a newer Open Second Brain version is available, reading only cached update state, producing an upgrade plan on demand, never blocking, auto-installing, or making hidden network checks.+PREMISE REFUTED AS SPECIFIED. There is no producer for the cache the card depends on: a grep across `src/` for `latestVersion`, `latest_version`, `update-check`, `updateCheck`, `registry.npmjs` returns nothing. Nothing in this tree ever learns what the latest release is, so "cached update state" would have to be populated by a network check - which is exactly what the data-ownership statement promises the operator does not happen: `src/core/install/ownership.ts:794` renders, verbatim, "this tool has no account of its own, no server it phones home to, no sync endpoint and no update check", via `renderDataOwnership` at `:786`. A further collision the card did not see: `o2b update` ALREADY EXISTS (`src/cli/update.ts`, `src/core/install/update.ts`) and means something entirely different - re-applying managed-file install blocks to host configs - so the obvious verb is taken. The upgrade-plan half has a substrate (`src/core/brain/upgrade.ts`, a plan/apply managed-file migrator). Only the "is there a newer version" fact is missing, and it is the part that carries the policy cost.++The variants you produce must cover how to ship cards 1-4 coherently AND how to handle card 5 honestly. Recording a refuted card as a refusal with its reason, rather than building it, is an acceptable and expected deliverable in this project - but the variants should differ in how they treat card 5's residue.++# Project context++Open Second Brain - a second brain for AI agents over Obsidian-compatible Markdown vaults. TypeScript on the Bun runtime, ~1.55.0, shipped as an `o2b` CLI plus an MCP server (three tool scopes: full, writer, catalog) plus install adapters for a dozen agent runtimes.++Recent commits:+5f415267 feat: who wrote what, and how to take it back (v1.55.0) (#184)+dc552590 feat: private is not a suggestion (v1.54.0) (#183)+23e6b81e fix(brain): merged pages leave the dedup pool, and the write seam refuses cycles (v1.53.1) (#182)+c2e13f9d fix(hermes): make prefetch recall query-aware (#181)+5102f142 fix(hermes): record context-pack receipts and explicit outcomes (#179)+323e2f09 feat: nothing writes silently, nothing degrades silently (v1.52.0) (#178)+6d3e8b23 feat: what earns its keep (v1.51.0) (#177)+86544b9b fix(hermes): the bridge child inherits a PATH that can find Bun (v1.50.3) (#176)+ba1a9678 fix(hermes): preserve context-pack recall (v1.50.2) (#172)+4ba335d4 ci: adopt Bun 1.4.0 - pin the toolchain and rebuild the bundle it gates (#175)+1e8792cb fix: a provider the host cannot read is not an unconfigured one (v1.50.1) (#171)+962228ae fix(mcp): the pairing one tool declared and the other only enforced (v1.50.0) (#169)+aa73af4b feat: what the machine already has (v1.50.0) (#168)+b49af81e feat: a label is not a boundary (v1.49.0) (#166)+280469d2 feat: nothing runs unwatched (v1.48.0) (#165)+aa818084 feat: wiring what exists (v1.47.0) (#164)+a6d10dab feat: evidence at the boundary (v1.46.0) (#162)+29ea0099 fix: the flush that never landed (v1.45.1) (#158)+8d05a62a feat: silence is not an answer (v1.45.0) (#159)+34f96b84 fix: reuse and reap Hermes MCP bridges (v1.44.1) (#156)++Related files:+- src/cli/main.ts (1168 lines; dispatcher is a plain `switch` on `argv[0]` at :495-501, help/`-h` handled at :495)+- src/cli/command-manifest.ts (declarative manifest of ~140 commands; root carries only the inherited `--json` flag)+- src/cli/brain/verbs/continuity.ts:40,43 (`CLI_VERSION`)+- src/mcp/protocol.ts:9,14 (`SERVER_VERSION`, used in handshake `serverInfo`)+- src/core/install/opencode-plugin-asset.ts:39 (third version read)+- src/mcp/instructions.ts (162 lines; `WRITER_INSTRUCTIONS` :33, `FULL_INSTRUCTIONS` :87, `CATALOG_INSTRUCTIONS`, `SCOPE_BODIES` :145-148, `buildInstructions` :159-162)+- src/mcp/capabilities.ts (162 lines; `RuntimeCapabilityWindow` :14-17, `evaluateToolCapabilities` :41-62, report shape :70-83, `hostCeiling` :100-121)+- src/mcp/server.ts:148-155 (constructor evaluation), :357-380 (`handleInitialize`), :383-385 (hidden aliases not advertised)+- src/core/brain/portability/pointer.ts:214-216, :231-238, :245-262+- src/cli/brain/verbs/project.ts:12,13,59,107 (only consumers today)+- src/mcp/brain/landscape-tools.ts (sibling read-only inventory tool `brain_mcp_landscape`)+- src/core/install/types.ts:21-45, src/core/install/host-probe.ts, src/cli/install/install.ts:452-506, src/cli/install/render.ts:176-198+- src/core/install/ownership.ts:786, :794+- src/cli/update.ts, src/core/install/update.ts, src/core/brain/upgrade.ts+- docs/cli-reference.md, docs/mcp.md, docs/updating.md, CHANGELOG.md++Conventions:+- `package.json` `version` is the single source of truth, mirrored into eight manifests plus `pyproject.toml` by `bun run scripts/sync-version.ts`; CI gates on `--check`. Never hand-edit a mirrored file.+- Tests are Bun tests under `tests/`, mirroring `src/` layout. `bun run validate` = typecheck + lint + test. Formatter `bun run fmt` (oxfmt), linter `bun run lint` (oxlint). Both must be green before every commit.+- House style, visible throughout the tree: an absent answer is a NAMED member of a closed vocabulary carrying its reason, never an assumed success. Frozen constant objects (`Object.freeze`) with a derived union type are the idiom for such vocabularies.+- Module headers carry a short prose rationale explaining why the module exists and which wrong default it removes.+- Public prose uses the full product name "Open Second Brain", never an abbreviation; no exclamation marks; no AI-authorship markers.++Constraints:+- SOLID, KISS, DRY. Repeated literals hoist into named constants. Match the surrounding idiom.+- No fallback that silently does nothing and misleads; errors surface explicitly and by name. No stubs. No hardcoded values that belong in constants.+- No hardcoded natural-language phrases in any language other than English; other-language cases must be handled abstractly, because the project cannot enumerate the languages of the world.+- Do not change existing public CLI or MCP contracts in a breaking way. Deprecated surfaces stay callable.+- No new external runtime dependencies.+- No schema migration and no search reindex in this wave.+- Everything added here must be read-only with respect to user content.+- One pull request, one CHANGELOG version.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/what-this-install-knows/design.md b/docs/brainstorm/what-this-install-knows/design.mdnew file mode 100644index 00000000..b4bd0d1c--- /dev/null+++ b/docs/brainstorm/what-this-install-knows/design.md@@ -0,0 +1,295 @@+# What this install knows about itself - design++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain answers a great deal about the vault it owns and very+little about itself. An agent or operator asking the installation which+version it is, which of its tools are actually callable in this runtime,+which projects point at this vault, or whether the hosts it wrote+registrations into can still be reached, gets either no answer, an answer+only one of the two surfaces can hear, or - in the case of the MCP+instruction block - a confident answer that is wrong the moment a host+disables a tool.++The machinery to answer all four questions already exists in the tree as+typed readers. What is missing is the seam between those readers and the+surface that needs them. This wave builds those seams and records, with+its reason, the one question in scope that cannot be answered honestly at+all.++## Premise verification++Every card was read against live source before anything was designed.+Three premises hold, one is largely refuted, one is refuted outright.++### t_dee1d1fe - `o2b version` and `--version` - CONFIRMED, enlarged++No `--version` handling exists in `src/cli/main.ts` and no `version`+entry exists in `src/cli/command-manifest.ts`. The card's "reuse the+existing `packageJson.version` import pattern" is correct but understates+the problem: there are three independent reads of `package.json`+`version` in the tree today - `src/cli/brain/verbs/continuity.ts:40,43`+(`CLI_VERSION`), `src/mcp/protocol.ts:9,14` (`SERVER_VERSION`), and+`src/core/install/opencode-plugin-asset.ts:39`. Adding a fourth would+make four copies of a fact the repository declares has exactly one+source. The correction enlarges the card: hoist first, then build on the+hoisted constant.++A second consequence of that reading: `SERVER_VERSION` is already+reported in the MCP handshake as `serverInfo.version`, so the version+fact is answerable over MCP today and not over the CLI. Only the CLI half+is missing.++### t_cf827c77 - instructions from the capability window - CONFIRMED++`buildInstructions` (`src/mcp/instructions.ts:159-162`) selects one of+three frozen strings from `SCOPE_BODIES` (`:145-148`) by `TOOL_SCOPE` and+prepends an identity line. Nothing else influences it. The handshake+(`src/mcp/server.ts:375-378`) passes only `agent` and `scope`. The writer+body (`:33`) names all five writer tools in prose; the full body (`:87`)+names nine tools across three paragraphs.++Meanwhile `evaluateToolCapabilities` (`src/mcp/capabilities.ts:41-62`)+already computes, per tool, an `available` or `withheld` entry carrying a+human-readable reason, and the server evaluates it in its constructor+(`src/mcp/server.ts:148-155`) and stores the result on+`this.capabilityReport` (`:155`). The report is therefore in hand at+`handleInitialize` time with no plumbing to add. What is missing is only+the decision about what truthful text to render from it.++### t_49315346 - linked projects on the MCP surface - CONFIRMED, smaller than stated++`listLinkedProjects` (`src/core/brain/portability/pointer.ts:231-238`)+and `linkedProjectsStatus` (`:245-262`) are both pure, typed, tolerant+readers; the second already answers the harder question, reporting a+four-value pointer state and a `vaultExists` flag. A grep for both names+across `src/` finds consumers only in `src/cli/brain/verbs/project.ts`.+Nothing under `src/mcp` touches either. The build is a seam, not a+feature.++### t_09d7e9e9 - connector health - LARGELY REFUTED++The card asks for a connector health view that bounds its checks by a+deadline and never presents an unverified connector as healthy. Every+substantive property it asks for already ships, and so does the aggregate+view the card's own validator believed was the remaining gap:++- Per-target status is a closed vocabulary on both sides: `AdapterStatus`+ (`src/core/install/types.ts:21-27`) and `VerifyStatus` (`:39-45`).+- Unverified is already a named member carrying its reason, never an+ assumed `ok`: `HOST_PROBE_RESULT`+ (`src/core/install/host-probe.ts:87-93`), under a module header stating+ that "a probe that reports success when it could not run is the+ misleading default this module exists to remove" (`:17-22`).+- The deadline is already enforced: `HOST_PROBE_TIMEOUT_MS = 10_000`+ (`:158`), with the wait bounded in the runner (`:174-181`) and the+ timeout becoming one more named outcome rather than a hang.+- The aggregate already exists: `runCheck`+ (`src/cli/install/install.ts:452-489`) iterates every registered+ adapter, collects `VerifyResult[]`, renders a table+ (`src/cli/install/render.ts:176-188`) or structured JSON (`:190-198`),+ and returns an exit code distinguishing drift from unreachable+ (`:492-506`).++The genuine residue is narrower and of a different shape than the card+states: all of it is CLI-only. An agent on the MCP surface cannot ask+whether the hosts this install wired up can still be reached. That is the+same gap shape as t_49315346, which is why the two ship as one tool.++### t_c64b7cab - release awareness - REFUTED, not built++The card asks for a surface that reports whether a newer Open Second+Brain version is available by "reading only cached update state". There+is no producer for that cache. A grep across `src/` for `latestVersion`,+`latest_version`, `update-check`, `updateCheck` and `registry.npmjs`+returns nothing: nothing in this tree ever learns what the latest release+is. A cache with no producer would have to be filled by a network check,+and `src/core/install/ownership.ts:794` renders to the operator, verbatim,+that this tool has "no account of its own, no server it phones home to,+no sync endpoint and no update check". Building the card as written means+either making that statement false or shipping a surface whose only+possible answer is that it has nothing to report.++A collision the card did not see: `o2b update` already exists+(`src/cli/update.ts`, `src/core/install/update.ts`) and means re-applying+managed install blocks to host configs, so the obvious verb is taken and+the obvious name would mislead about an existing one.++**Verdict: refused as specified.** Nothing is built for this card in this+wave. The two honest alternatives - registering an outbound release check+in the egress registry as a network site like every other outbound path,+or reading a version fact some other component already fetched and saying+where it came from - both amend an operator-facing promise about network+behaviour. That is an operator policy decision, not an engineering one,+and it is recorded here for the operator to take rather than taken on+their behalf. The upgrade-plan half of the card needs nothing:+`src/core/brain/upgrade.ts` is already a plan/apply migrator.++## Scope++- One shared version constant, with the three existing readers repointed+ at it.+- `o2b version` subcommand and a root `--version` flag, both honouring+ the inherited `--json` flag.+- `initialize.instructions` rendered from the live capability report:+ guidance for a withheld tool is not emitted, and every withheld tool is+ named with the reason the evaluator already computed.+- One read-only MCP tool, `second_brain_wiring`, with two views:+ `projects` (linked project registry with its health) and `hosts` (the+ per-adapter verify aggregate).+- Docs, CHANGELOG and the version bump that CLAUDE.md requires inside the+ feature pull request.+- The recorded refusal of t_c64b7cab above, carried into the CHANGELOG+ notes and the card's handoff summary.++## Out of scope++- Any network call, cached or otherwise, and any change to the data+ ownership statement (t_c64b7cab).+- A second HTTP surface. The loopback explorer+ (`src/core/brain/explorer.ts:345-356`) already exists for live views and+ is not extended here.+- Duplicating the version or the capability report inside the new MCP+ tool: `serverInfo.version` and `second_brain_capabilities` already+ answer both on that surface.+- Any schema migration, search reindex, or ranking change.+- Rewriting the CLI dispatcher. `version` joins the existing `switch`.++## Chosen approach++The consultant's Variant 2 - one coherent model over live state, every+absent answer a named vocabulary member, both surfaces served - with+three project-context overrides recorded under "Design decisions" below.++Each of the four buildable cards is a seam onto a reader that already+exists. Nothing new computes connector health, project health, tool+availability, or the version; four surfaces start reading what four+readers already produce.++## Design decisions++- **One version constant, hoisted before anything is built on it.**+ `src/core/version.ts` exports `OPEN_SECOND_BRAIN_VERSION` from the+ single `package.json` import; `CLI_VERSION`, `SERVER_VERSION` and the+ opencode plugin header read it. Adding a fourth independent read to+ serve `o2b version` would be the defect this wave exists to remove,+ written into the change that removes it.++- **The new MCP tool covers only what is missing.** Variant 2 proposed a+ four-section installation report including `version` and `tools`. Both+ are already answered on the MCP surface - `serverInfo.version`+ (`src/mcp/protocol.ts:14`) and `second_brain_capabilities`+ (`src/mcp/tools.ts:461`, always available and never withheld) - so the+ report would have been two new copies of two shipped answers. Override+ recorded: the tool carries `projects` and `hosts` only.++- **One tool with a required `view`, not two tools.** The house idiom for+ consolidated reads is demonstrably a `view` parameter -+ `brain_brief`, `brain_analytics` and `schema_inspect` all take one, and+ `src/mcp/brain/landscape-tools.ts:26` names the reason (token diet).+ Both views answer the same question class, "what is this install wired+ into", so they belong on one tool. `view` is required with no aggregate+ member, keeping every payload bounded, exactly as `brain_brief` does.++- **Instruction bodies become tool-tagged segments.** Variant 2 proposed a+ per-tool paragraph map. That fits the writer body, whose five bullets+ are already one per tool, and not the full body, which is prose naming+ nine tools across three paragraphs. Override recorded: each scope body+ becomes an ordered list of segments, each declaring the tool names its+ text depends on. A segment renders when every tool it names is+ available; a segment naming no tool always renders. The full body's+ memory-contract paragraph decomposes into one segment per writer tool,+ which is the shape its semicolon-joined clauses already have. The+ withheld list is appended from the report's own `withheld` entries and+ their reasons, so no second vocabulary is invented.++- **Withheld guidance is removed, not contradicted.** Appending a+ withheld-tools block beneath prose that still instructs the agent to+ call those tools leaves the first text every agent reads+ self-contradicting. The segment model is what makes removal possible.++- **The `hosts` view reuses the existing verify path and declares its+ cost.** `verify()` per adapter is exactly what `o2b install --check`+ calls; reusing it means one implementation of connector health, not+ two. Two of the ten registered targets declare a `hostProbe`+ (`src/core/runtime/host-facts.ts:509`, `:530`), so the worst case adds+ two bounded ten-second probes. The tool description states that it may+ ask host CLIs and that the wait is bounded, because a diagnostic that+ can take twenty seconds and does not say so is a surprise.++- **Paths follow the contract that already governs them.** The registry+ is keyed on absolute host paths+ (`src/core/brain/portability/pointer.ts:214-216`), and this server has a+ shipped policy for that: `vaultPathField`+ (`src/mcp/vault-path-field.ts`) emits an opaque stable reference+ (`vault://<hex>`, keyed by the device-local installation secret) unless+ `expose_host_paths` is set. `vaultStoreReference`+ (`src/core/config.ts:614-621`) takes any path, so project directories+ render through the same function under the same flag. No second path+ policy is invented, and+ `tests/core/architecture/vault-path-census.test.ts` keeps the new site+ honest.++- **A degraded field carries its reason.** Following+ `unresolvedField` (`src/mcp/vault-path-field.ts`), a reference that+ cannot be computed because the config is unreadable renders as+ `{ error }` rather than falling back to the raw host path, which would+ breach the policy the field exists to enforce.++- **`--version` is handled before the dispatcher, `version` inside it.**+ The root flag joins the existing `-h`/`--help` check at+ `src/cli/main.ts:495`; the subcommand joins the `switch` at `:501`. No+ new dispatch mechanism.++## File changes++New:++- `src/core/version.ts` - the single version constant.+- `src/cli/version.ts` - the `o2b version` verb and its renderers.+- `src/mcp/instruction-segments.ts` - the segment type, the three scope+ bodies as segment lists, and the renderer.+- `src/mcp/wiring-tools.ts` - `second_brain_wiring` and its two views.+- `tests/core/version.test.ts`, `tests/cli/version.test.ts`,+ `tests/mcp/instruction-segments.test.ts`, `tests/mcp/wiring-tools.test.ts`.++Modified:++- `src/cli/brain/verbs/continuity.ts`, `src/mcp/protocol.ts`,+ `src/core/install/opencode-plugin-asset.ts` - read the shared constant.+- `src/cli/main.ts` - `--version` flag, `version` case.+- `src/cli/command-manifest.ts` - the `version` command and the root+ `--version` flag.+- `src/mcp/instructions.ts` - `buildInstructions` gains the capability+ report input and renders segments.+- `src/mcp/server.ts` - pass `this.capabilityReport` into+ `buildInstructions`.+- `src/mcp/tools.ts` - register the wiring tool.+- `src/mcp/registry-guard.ts` - the preview-budget rationale row for the+ new tool.+- `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/mcp.md`.+- `package.json` plus the eight mirrored manifests and `pyproject.toml`,+ via `bun run scripts/sync-version.ts`.++## Risks and open questions++- **Instruction text is the first thing every agent reads.** Rewriting+ three bodies into segments risks changing meaning, not only shape. The+ mitigation is a test pinning that a full capability window renders text+ byte-identical to today's for each of the three scopes, so only the+ withheld case differs.+- **The `hosts` view spawns host CLI subprocesses.** Bounded by+ `HOST_PROBE_TIMEOUT_MS` per probing target and limited to two such+ targets today, but a future adapter declaring a probe raises the+ ceiling. The description states the behaviour rather than hiding it.+- **`verify()` needs a resolved vault.** `runCheck` refuses with a usage+ error when the vault is unset (`src/cli/install/install.ts:456-462`);+ the MCP view must refuse by name in the same case rather than reporting+ every target as not-installed off a bogus path.+- **Open question deferred to the operator, not to implementation:**+ whether Open Second Brain should ever learn what its latest release is,+ and at what cost to the data ownership statement (t_c64b7cab).diff --git a/docs/brainstorm/what-this-install-knows/plan.md b/docs/brainstorm/what-this-install-knows/plan.mdnew file mode 100644index 00000000..513ed521--- /dev/null+++ b/docs/brainstorm/what-this-install-knows/plan.md@@ -0,0 +1,122 @@+# What this install knows about itself - implementation plan++Nine tasks. Each is one atomic commit, test-first, with the project+formatter and linter green before the commit is created.++Cards: t_dee1d1fe (tasks 1-2), t_cf827c77 (task 3), t_49315346 (task 4),+t_09d7e9e9 (task 5), t_c64b7cab (task 9, recorded refusal only).++## Tasks++### Task 1: One version constant+- **Files**: `src/core/version.ts` (new), `src/cli/brain/verbs/continuity.ts`,+ `src/mcp/protocol.ts`, `src/core/install/opencode-plugin-asset.ts`,+ `tests/core/version.test.ts` (new)+- **Acceptance**: a test asserts `OPEN_SECOND_BRAIN_VERSION` equals the+ `version` field read from `package.json`, and a source scan asserts that+ `src/` contains exactly one `package.json` import with a `version` read -+ the one in `src/core/version.ts`. The scan fails today with three hits,+ which is the failing state to reach first.+- **Depends on**: none++### Task 2: `o2b version` and `--version`+- **Files**: `src/cli/version.ts` (new), `src/cli/main.ts`,+ `src/cli/command-manifest.ts`, `tests/cli/version.test.ts` (new)+- **Acceptance**: `o2b version` prints the constant and exits 0;+ `o2b version --json` prints `{"version":"<constant>"}` and parses;+ `o2b --version` prints the same line as `o2b version`; the manifest+ carries a `version` command and a root `--version` flag, and the+ manifest-completeness ratchet+ (`tests/cli/manifest-completeness.test.ts`) accounts for the new case.+ That ratchet enumerates the dispatchers and asks the manifest to+ account for each, so adding the `switch` case before the manifest entry+ is what makes it fail first. An unknown argument after `version` is a+ usage error, not silence.+- **Depends on**: Task 1++### Task 3: Instructions rendered from the capability report+- **Files**: `src/mcp/instruction-segments.ts` (new),+ `src/mcp/instructions.ts`, `src/mcp/server.ts`,+ `tests/mcp/instruction-segments.test.ts` (new),+ `tests/mcp/mcp.test.ts` (the existing `buildInstructions` coverage)+- **Acceptance**: four tests. (a) With every tool available, each of the+ three scopes renders byte-identical text to the current constant - the+ pin that keeps this from becoming a rewrite. (b) With `brain_note`+ withheld, the writer body contains no line naming `brain_note` and the+ rendered text names it once, in a withheld block, carrying the exact+ reason string the evaluator produced. (c) With every non-diagnostic tool+ withheld, the body is the identity line plus the withheld block and+ nothing that instructs a call. (d) The unresolved-identity branch still+ renders the reason in place of the identity line, unchanged. A segment+ declaring a tool name that no scope's tool table contains fails a test,+ so a renamed tool cannot silently orphan its guidance.+- **Depends on**: none++### Task 4: `second_brain_wiring`, `projects` view+- **Files**: `src/mcp/wiring-tools.ts` (new), `src/mcp/tools.ts`,+ `src/mcp/registry-guard.ts`, `tests/mcp/wiring-tools.test.ts` (new)+- **Acceptance**: `view: "projects"` returns one entry per registered+ link carrying the project reference, the vault reference, the+ four-value `pointer` state and `vaultExists`. With `expose_host_paths`+ unset, no absolute host path appears anywhere in the payload, asserted+ against the serialised JSON, and+ `tests/core/architecture/vault-path-census.test.ts` passes. With the+ flag set, the raw paths appear. An unreadable config renders each+ reference as `{ error }` and never as a raw path. A registry damaged by+ hand degrades to the entries it can read, matching `listLinkedProjects`,+ rather than throwing. An absent `view`, or an unknown one, is an+ `INVALID_PARAMS` error naming the accepted members.+- **Depends on**: none++### Task 5: `second_brain_wiring`, `hosts` view+- **Files**: `src/mcp/wiring-tools.ts`, `tests/mcp/wiring-tools.test.ts`+- **Acceptance**: `view: "hosts"` returns one entry per registered adapter+ carrying `target`, the `VerifyStatus` member, `details` and `fix_hint`,+ from the same `verify()` call `o2b install --check` makes - asserted by a+ test that drives both and compares. With the vault unresolved, the view+ refuses by name with the same reason `runCheck` gives, and does not+ report ten targets as not-installed. The injected host-probe runner+ (`setHostProbeRunner`) drives the unreachable branch without a host+ binary present, and a probe that cannot run renders its named+ `HOST_PROBE_RESULT` reason rather than an `ok`.+- **Depends on**: Task 4++### Task 6: Scope placement and census+- **Files**: `src/mcp/tools.ts`, existing architecture and tool-census+ tests. The preview-budget rationale row lands in Task 4 with the+ registration it describes; this task only proves the surface is+ complete.+- **Acceptance**: the full tool census test passes with the new name, the+ tool is absent from the writer and catalog scopes, no import cycle is+ introduced (`tests/core/architecture/import-cycles.test.ts`), and+ `bun run typecheck` and `bun run lint` are green.+- **Depends on**: Tasks 4, 5++### Task 7: Documentation+- **Files**: `README.md`, `docs/cli-reference.md`, `docs/mcp.md`+- **Acceptance**: `docs/cli-reference.md` documents `o2b version`, its+ `--json` output and the root `--version` flag; `docs/mcp.md` documents+ `second_brain_wiring`, both views, the path policy and the probe cost;+ `README.md` gains one short paragraph. The repository link checker+ (`bun run link-ratchet:check`) passes.+- **Depends on**: Tasks 2, 5++### Task 8: Version bump and CHANGELOG+- **Files**: `package.json`, the eight mirrored manifests and+ `pyproject.toml` via `bun run scripts/sync-version.ts`, `CHANGELOG.md`+- **Acceptance**: `CHANGELOG.md` carries one new `## [1.56.0] - <date>`+ heading with its `compare` link reference at the bottom;+ `bun run sync-version:check` exits 0; the heading and `package.json`+ agree. Minor bump: four additive capabilities, no breaking contract+ change.+- **Depends on**: Tasks 1-7++### Task 9: Record the refusal of t_c64b7cab+- **Files**: `CHANGELOG.md` (Notes section)+- **Acceptance**: the notes state that release awareness was scoped,+ verified against source, and not built, naming both the missing+ producer and `src/core/install/ownership.ts:794`, and stating that the+ decision is the operator's. The design document already carries the+ full verdict. The card's own handoff summary is written at the tracker+ tick, after the release.+- **Depends on**: Task 8diff --git a/docs/brainstorm/what-this-install-knows/variants.md b/docs/brainstorm/what-this-install-knows/variants.mdnew file mode 100644index 00000000..ae7c1499--- /dev/null+++ b/docs/brainstorm/what-this-install-knows/variants.md@@ -0,0 +1,106 @@+# What this install knows about itself - variants++Audit trail for the phase-0 brainstorm. The consultant was Claude Code,+run once against `cli-output/prompt.md`; it returned three parseable+variants and one recommendation on the first attempt, so the Codex+fallback was not invoked.++The prompt carried the premise verification performed before the+brainstorm - the five cards' anchors opened, the mechanisms they claimed+missing grepped for - so the consultant reasoned against the tree as it+is rather than as the cards describe it.++## Consultant output, verbatim++### Variant 1: Four seams, one refusal+- **Approach**: Ship each card as its own small, independent addition with no shared model. Card 1 hoists the three `package.json` reads into one `src/core/version.ts` constant and adds `o2b version` plus a root `--version` flag on top of it. Card 2 keeps the frozen scope bodies and appends a generated "withheld tools" block rendered from `capabilityReport`. Cards 3 and 4 become two new read-only MCP tools that wrap `linkedProjectsStatus` and the `runCheck` loop directly, emitting absolute paths and always running probes. Card 5 is closed as refused, with the ownership statement and the taken `update` verb cited as the reason, and nothing is built for it.+- **Trade-offs**:+ - Pro: smallest diff, each card reviewable in isolation, no new abstractions.+ - Pro: card 5 handled with zero policy cost and no contract surface to maintain.+ - Con: card 2 is only half truthful. The writer body still names withheld tools in prose, so an agent is still directed to them, and the appended block merely contradicts the paragraph above it.+ - Con: the hosts tool runs up to a dozen 10-second probes sequentially from inside the MCP server, so a single call can block for minutes and spawns host binaries on every read.+ - Con: absolute host paths leave the server with no stated policy, which sits uneasily next to the sibling landscape tool's "vault-relative" charter.+ - Con: the question "is a newer release available" has no answer at all on either surface, so the wave's spine (every self-question answered from live state, unknowns named) is not fully honoured.+- **Complexity**: small+- **Risk**: medium++### Variant 2: One installation report+- **Approach**: Introduce a single read-only core module, `src/core/install/self-report.ts`, that assembles a typed `InstallationReport` with four sections: `version` (from the new shared version constant), `tools` (the existing capability report), `projects` (from `linkedProjectsStatus`, with `pointer` state and a `paths` disclosure flag), and `hosts` (the `VerifyResult[]` aggregate, with probes named `not-run` unless the caller passes `probe: true`, and run concurrently under the existing deadline when they do). The CLI gets `o2b version` and `--version` reading the `version` section, and the MCP server gets one new tool, `brain_mcp_installation`, returning the whole report or one section by argument. Card 2 splits each scope body into a per-tool paragraph map keyed by tool name, and `buildInstructions` renders only paragraphs for `available` tools and appends a withheld list with reasons. Card 5 ships its honest residue as a fifth `release` section whose `state` is a closed vocabulary (`not-checked` today, with `reason: no-update-check-by-policy`), pointing at `docs/updating.md` and the existing `brain upgrade` plan, and the card is recorded as refused-as-specified.+- **Trade-offs**:+ - Pro: one model answers every self-question on both surfaces, and every absent answer is a named vocabulary member, which is the house idiom and the wave's spine.+ - Pro: card 2 becomes fully truthful because withheld tools vanish from prose instead of being contradicted below it.+ - Pro: probes are opt-in and bounded, so the default read is fast and side-effect free, and the "unverified" state is reported by name rather than assumed.+ - Pro: card 5 gets a durable, truthful surface that an agent can query without any network, and the ownership statement stays verbatim.+ - Con: largest diff of the three, touching CLI, MCP, instructions, and a new core module in one PR.+ - Con: the per-tool paragraph map duplicates tool naming already present in the tool registry, so DRY is improved but not perfected.+ - Con: a `release` section that can only ever say `not-checked` risks reading as a placeholder unless the reason text and docs are explicit that the state is deliberate.+- **Complexity**: large+- **Risk**: medium++### Variant 3: Grow the landscape, compare on demand+- **Approach**: Reuse the existing sibling inventory tool instead of adding tools. `brain_mcp_landscape` gains two additive sections, `projects` and `hosts`, backed by the same pure readers, so no new tool name enters `tools/list`. Card 1 adds the shared version constant and `o2b version`, and card 2 uses the same per-tool paragraph filtering as Variant 2. Card 5's residue becomes a pure comparator: `o2b version --compare <semver>` answers `newer | same | older | invalid` for a latest version the operator or harness obtained by their own means, then prints the upgrade plan pointer, so Open Second Brain never fetches, caches, or auto-installs anything.+- **Trade-offs**:+ - Pro: zero new MCP tool names, and existing clients discover the new facts through a tool they already call.+ - Pro: the comparator is deterministic, network-free, and gives scripts the "is newer available" bit once they supply the input.+ - Con: it breaks the landscape module's own written charter. Its header promises that environment values are never read and discovery is vault-relative, while host verification reads host config paths, reports absolute project paths, and may spawn host binaries. Growing that tool makes its rationale false.+ - Con: the comparator answers a question only after the caller has already answered it elsewhere, so its utility is marginal and it adds a flag surface the reference docs must carry forever.+ - Con: loading unrelated host and project data into every landscape call widens a tool whose consumers today expect a small vault inventory.+- **Complexity**: medium+- **Risk**: high++### Recommended: Variant 2+**Rationale**: Variant 2 is the only one where every card lands as a named, closed-vocabulary answer on both the CLI and MCP surfaces, which is the wave's stated spine and the tree's house style, and it is the only one that makes card 2 fully truthful rather than self-contradicting. Its extra size is contained in one new read-only core module and one new tool, and it keeps the ownership statement, the existing `update` verb, and the landscape tool's charter untouched, whereas Variant 3 would falsify a module's own rationale and Variant 1 leaves the release question unanswered on every surface.++## Orchestrator decision++**Variant 2 adopted, with three overrides.**++The spine is right and is the only one of the three that both surfaces+can carry: one coherent model over live state, every absent answer a+named member of a closed vocabulary. Variant 1 was rejected on its own+admitted defect - appending a withheld-tools block beneath prose that+still instructs the agent to call those tools leaves the first text every+agent reads self-contradicting, which is a smaller version of the bug the+card is about. Variant 3 was rejected because growing `brain_mcp_landscape`+falsifies that module's written charter, and because a comparator that+answers "is a newer version available" only after the caller has+already established it adds a permanent flag surface for a marginal+answer.++Three overrides, each from project context the consultant did not have:++1. **No `version` or `tools` section in the new MCP tool.** Variant 2+ proposed a four-section installation report. Two of those sections are+ already answered on the MCP surface: `serverInfo.version` carries the+ version in the handshake (`src/mcp/protocol.ts:14`) and+ `second_brain_capabilities` returns the whole capability report and is+ never withheld (`src/mcp/tools.ts:453-461`). Shipping them again would+ be two new copies of two shipped answers. The tool carries the two+ views that are genuinely missing.++2. **No `release` section for t_c64b7cab.** Variant 2 proposed a fifth+ section whose state could only ever read `not-checked`, and named the+ risk itself in its own trade-offs. A field with no producer, whose+ single possible value is the absence of an answer, is a stub: it costs+ a permanent output contract, a schema, documentation and a test, and+ returns nothing the documentation does not already say. The card is+ recorded as refused with its reason in `design.md` instead, which is a+ deliverable in this project. The residue is an operator policy+ decision about network behaviour, and taking it inside an+ implementation PR would be taking it on the operator's behalf.++3. **Tool-tagged segments, not a per-tool paragraph map.** The map fits+ the writer body, whose five bullets are already one per tool, and not+ the full body, which is prose naming nine tools across three+ paragraphs. Segments that declare the tool names their text depends on+ cover both shapes with one model, and the full body's semicolon-joined+ memory-contract clauses decompose into one segment per writer tool+ without being rewritten.++One further refinement inside Variant 2's own terms: the consultant+proposed making host probes opt-in behind a `probe: true` argument.+Adapters have no non-probing `verify()` path, so building one means+touching every adapter for a flag - a large change to avoid a bounded+cost that two of ten targets can incur+(`src/core/runtime/host-facts.ts:509`, `:530`). The view reuses `verify()`+as it is and states the cost in the tool description instead.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex d7357e8e..df0f07d0 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -21,12 +21,36 @@ o2b mcp Run the MCP tool server (stdio by default; --transo2b state status|migrate|rollbackInventory the state this vault holds, move it to another directory, or put it back (see "State surfaces" below)o2b tool-call Invoke an MCP tool handler from the CLI+o2b version Print the installed Open Second Brain version; --version is a synonymo2b help --json Print the command/flag manifest as JSONo2b completions --shell zsh Print completions for bash|zsh|fish|elvish|nushell|powershello2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinkso2b update Update Open Second Brain across all detected runtimes; --target <name> / --dry-run / --force / --json```+### `o2b version` (since v1.56.0)++`o2b version` prints the installed version and exits 0:++```console+$ o2b version+1.56.0+$ o2b version --json+{"version":"1.56.0"}+```++`o2b --version` is a synonym and renders the same line, `--json` included -+the flag is routed to the verb rather than printing a second line that could+drift from it. Both are declared in the command manifest, so shell completions+and `o2b help --json` offer them.++The verb takes no positional argument. `o2b version latest` is a usage error+rather than a print of the local version: nothing in this build learns what any+other version is, and answering a question about the latest release with the+installed one would be the wrong answer wearing the right shape. The MCP+handshake has always carried the same fact as `serverInfo.version`, and both+now read one constant.+### `o2b install` exit codesEvery code the verb can return, in one table. A CI script that gates ondiff --git a/docs/mcp.md b/docs/mcp.mdindex 74b37d1e..1062c781 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -172,7 +172,7 @@ Either way a call that has already entered one of them runs it to the end.## Tool Highlights-The full server currently advertises 111 tools; the 18 deprecated predecessor+The full server currently advertises 115 tools; the 18 deprecated predecessornames were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone(see "Consolidated views and deprecated aliases" below). The table highlightsthe operator-facing core,@@ -188,6 +188,7 @@ flags for a narrower per-process full server.| `second_brain_capabilities` | Report the tools available to this MCP process and the withheld-tool reasons after runtime capability filtering. | — || `second_brain_status` | Report config and vault status, with secrets redacted. | — || `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |+| `second_brain_wiring` | Report what this install is wired into. `view=projects` lists every registered project link with its pointer state and whether the vault it names still exists; `view=hosts` verifies every registered install target through the same `verify()` call `o2b install --check` makes. See "Installation wiring" below for the path policy and the probe cost. | `view` || `vault_health` | Run vault, config, and plugin manifest health checks. Since v1.50.0 the response also carries `state_surfaces`: the same inventory `o2b state status` renders (every declared in-vault state surface with its resolved path, tier, reachability verdict and the configuration layer that placed it), as a sibling FIELD rather than a contribution to `ok` — an absent surface is normal on a young vault and an unchecked one carries its own reason. An unreadable machine config resolves to no overrides here rather than failing the report; the `checks` array already names that fault. | — || `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | — || `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | — |@@ -355,6 +356,79 @@ All tool results contain both an unstructured `content` text block (a JSONserialization of the structured payload) and a `structuredContent` object soclients that prefer typed results can use it directly.+## Installation wiring (since v1.56.0)++`second_brain_wiring` answers what this install is wired into. Both answers+existed before it and neither was reachable from this surface: the linked+project registry was readable only through `o2b brain project status`, and+the per-adapter verify aggregate only through `o2b install --check`. Nothing+here computes health of its own - each view is a seam onto the reader that+already produced the answer.++`view` is required and there is no aggregate member, so a projects read never+pays for a host probe. An absent or unknown `view` is refused with `-32602`+naming the accepted members, and `view=hosts` without a resolved vault is+refused with the same code and the sentence `o2b install --check` gives -+verify reads a per-vault manifest, so an unset vault would report every+runtime absent.++Every payload carries `vault_path` and `view` at the top level, whichever view+answered.++**`view=projects`** returns one entry per registered project link:++| Field | Meaning |+| --- | --- |+| `project_ref` | The project directory, under the path policy below. |+| `vault_ref` | The vault it points at, under the same policy. |+| `pointer` | `ok`, `missing`, `malformed`, or `mismatch` - the state of that project's `.o2b-vault.json` against the registry. |+| `vault_exists` | Whether the vault directory is still present. |++Beside `projects` the payload carries `total` (links found), `returned`+(entries actually carried) and `truncated`. The list is capped at 25: nothing+caps `projects.json` - every `o2b brain project link` appends to it - and this+response lands in model context, so the bound is in the payload rather than in+an assumption about how many projects an operator links. The `view=hosts` list+is not capped; a registry this build closes bounds it already. The CLI verb+stays uncapped too - it renders to a terminal.++A registry file damaged by hand reads as no links at all - not as the entries+it can still parse - and the call succeeds. That is the tolerance the CLI+reader already has (`listLinkedProjects` parses the registry as a whole), and+this view answers what `o2b brain project status` answers rather than refusing+where the verb tolerates. A server started without a config path reads the+machine default, as `view=hosts` does.++**`view=hosts`** returns one entry per registered install target, carrying+`target`, the `VerifyStatus` member (`ok`, `drift`, `not-installed`,+`mcp-unreachable`), the `details` the adapter observed, and `fix_hint`. Those+last two are the adapter's own sentences and name the host config files it+looked at, so the home prefix in them is folded to `~` under the same+`expose_host_paths` flag that governs the reference fields below. It is+the same `verify()` call over the same registry and the same `InstallEnv` that+`o2b install --check` makes, so connector health has one implementation rather+than two that can drift.++Two things this view states rather than hides. It may ask host CLIs: two of the+registered targets declare a host probe (`codex mcp list`, `copilot mcp list`),+so a worst-case call adds two subprocess round trips, each bounded by the same+ten-second deadline `--check` uses, and a probe that could not run renders its+named reason instead of an assumed `ok`. And an unresolved vault is refused by+name with the sentence `o2b install --check` gives, because `verify()` reads+the per-vault sidecar manifest and an unset vault would otherwise report every+target as not-installed off a path that does not exist.++**Paths.** The project registry is keyed on absolute host paths, and an MCP+response lands in model context, so `project_ref` and `vault_ref` follow the+same `expose_host_paths` contract `vault_path` obeys: an opaque, stable+`vault://<hex>` reference by default, the raw path when the operator sets the+flag. A config that cannot be read renders `{ "error": "..." }` in the field+rather than degrading to the path the reference exists to hide. That reason is+path-safe: it does not name the config file either, because the file lives+under the operator's home and this is the field that exists to keep host paths+out of model context. `second_brain_status` and `vault_health` name it, from+fields whose contract is to name it.+## ResourcesThe server also exposes a `resources` capability for hosts that prefer@@ -533,8 +607,40 @@ max tool window`.`advertised_tool_count` is the number a host actually LISTS: available minusthe tools marked hidden, which `tools/list` filters out. Under the `catalog`-surface the two numbers are a hundred and three apart, and it is the-advertised one a host's ceiling applies to.+surface it is seven whatever the tool table's size - the capability+diagnostic, the five always-loaded Brain tools and `tool_hydrate` - and+everything the surface merely hides stays callable through `tools/call`. It+is the advertised number a host's ceiling applies to.++Seven is the no-window count. The window is applied before the count, so a+window that withholds one of those seven lowers `advertised_tool_count` with+it, and a tool the window withheld is not callable through `tools/call`+either - unlike one the catalog surface merely hid. The capability+diagnostic is the one tool no window withholds.++### The handshake instructions follow the window (since v1.56.0)++`initialize.instructions` used to be one frozen string per scope, so a host+that disabled `brain_note` still received a paragraph telling the agent to call+it. The text is now rendered from the same capability report: guidance whose+tool this runtime withheld is REMOVED rather than contradicted, and a block at+the end names each removed tool with the reason the evaluator produced.++A runtime that withholds nothing renders text byte-identical to what shipped+before, so the only difference is in the withheld cases. The one deliberate+exception is in the `catalog` body: the frozen string said every tool omitted+from `tools/list` stays callable through `tools/call`, which holds for the+tools the catalog surface hides and not for the ones a window withholds, so+that sentence now separates the two cases. The block lists the+tools this text would have instructed and cannot, not the whole withheld set -+a `--max-tools` window can withhold over a hundred tools, and pasting that list+into the first thing every agent reads would cost more than the removed+guidance did. On a surface that registers `second_brain_capabilities` the+block closes by pointing there for the complete report; no capability window+ever withholds that tool. The writer scope does not register it at all, so+there the block ends with the names - a handshake sending an agent to a tool+its own server answers `unknown tool` for would be the defect this rendering+removes, reintroduced by the sentence that explains the removal.### The host ceiling (since v1.50.0)@@ -862,7 +968,7 @@ server to your Codex MCP config the same way as Hermes.The plugin's `.mcp.json` ships **two** MCP-server entries:-- `open-second-brain` - the full surface: 49 advertised tools (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_memory_bridge`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.+- `open-second-brain` - the full surface, whose advertised tool count is stated once under "Tool Highlights" above (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_memory_bridge`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 9349416a..b8a2c4dc 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.55.0",+ "version": "1.56.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex d3a1bae6..1d8685fb 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -3461,20 +3461,21 @@ function deriveRuntimeAgentName(runtimeId, operatorName) {}// src/mcp/vault-path-field.ts-function unresolvedField(err) {- return { error: err.message };-}var VAULT_PATH_OUTPUT_SCHEMA = Object.freeze({});-function vaultPathField(ctx) {- const configPath = ctx.configPath ?? undefined;+var CONFIG_UNREADABLE_REASON = "the device-local config could not be read, so this reference cannot be " + "resolved; call second_brain_status for the file and the remedy";+function hostPathReference(path, source) {+ const configPath = source.configPath ?? undefined;try {- return resolveExposeHostPaths(configPath) ? ctx.vault : vaultStoreReference(ctx.vault, configPath);+ return resolveExposeHostPaths(configPath) ? path : vaultStoreReference(path, configPath);} catch (err) {if (err instanceof ConfigReadError)- return unresolvedField(err);+ return { error: CONFIG_UNREADABLE_REASON };throw err;}}+function vaultPathField(ctx) {+ return hostPathReference(ctx.vault, ctx);+}// src/openclaw/index.tsvar OPENCLAW_TRANSPORT_REACH = TRANSPORT_REACH.remote;diff --git a/package.json b/package.jsonindex 5951d4bf..d70eb1e5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.55.0",+ "version": "1.56.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 17b91b9a..0e24c310 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.55.0"+version: "1.56.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 dbad9936..b952b54d 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.55.0",+ "version": "1.56.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 17b91b9a..0e24c310 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.55.0"+version: "1.56.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 180be371..00a996d7 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.55.0"+version = "1.56.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/scripts/measure-token-surface.ts b/scripts/measure-token-surface.tsindex 5644a0ab..a5a5571e 100644--- a/scripts/measure-token-surface.ts+++ b/scripts/measure-token-surface.ts@@ -19,6 +19,8 @@ import { budgetActiveBody } from "../src/core/brain/active-budget.ts";import { parseFrontmatterText } from "../src/core/vault.ts";import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";import { buildInstructions } from "../src/mcp/instructions.ts";+import { evaluateToolCapabilities } from "../src/mcp/capabilities.ts";+import { SERVER_NAME } from "../src/mcp/protocol.ts";import { buildToolTable } from "../src/mcp/tools.ts";import {TOOL_SCOPE,@@ -65,8 +67,20 @@ const listed = rows.filter((r) => !r.hidden);const hidden = rows.filter((r) => r.hidden);// Every scope opens with the identity line, so every scope is measured.+// The window is left unset on purpose: this measures the WIDEST block a+// host can be handed, and a runtime that withholds tools is handed less.const instructionChars = Object.fromEntries(- TOOL_SCOPES.map((scope) => [scope, buildInstructions({ agent: "agent", scope }).length]),+ TOOL_SCOPES.map((scope) => [+ scope,+ buildInstructions({+ agent: "agent",+ scope,+ capabilities: evaluateToolCapabilities(buildToolTable(scope), {+ scope,+ serverName: SERVER_NAME,+ }).report,+ }).length,+ ]),) as Record<ToolScope, number>;const vault = resolveVault();diff --git a/src/cli/aider.ts b/src/cli/aider.tsindex 56ea58f6..a3d29fef 100644--- a/src/cli/aider.ts+++ b/src/cli/aider.ts@@ -22,15 +22,14 @@import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";-import { homedir } from "node:os";import { dirname, join, resolve } from "node:path";import { parseFlags } from "./argparse.ts";-import { defaultConfigPath, discoverConfig } from "../core/config.ts";+import { defaultConfigPath } from "../core/config.ts";import { requireVault } from "./helpers.ts";import { atomicWriteFileSync } from "../core/fs-atomic.ts";import { buildPayload } from "../core/install/payload.ts";-import type { InstallEnv } from "../core/install/types.ts";+import { buildInstallEnv } from "../core/install/env.ts";import {bracketAiderSession,renderAiderSidecar,@@ -79,7 +78,7 @@ async function cmdAiderWrap(argv: string[]): Promise<number> {const configPath = (flags["config"] as string | undefined) ?? defaultConfigPath();const vault = requireVault(flags["vault"] as string | undefined, configPath);- const env = buildEnv(vault, configPath);+ const env = buildInstallEnv({ vault, configPath });const payload = buildPayload({vault,agent_name: env.env["VAULT_AGENT_NAME"] ?? null,@@ -120,14 +119,6 @@ async function cmdAiderWrap(argv: string[]): Promise<number> {return result.exit.code ?? 1;}-function buildEnv(vault: string, configPath: string): InstallEnv {- const cfg = discoverConfig(configPath).data;- const merged = { ...process.env } as Record<string, string>;- if (cfg["agent_name"]) merged["VAULT_AGENT_NAME"] = cfg["agent_name"];- if (cfg["timezone"]) merged["VAULT_TIMEZONE"] = cfg["timezone"];- return { vault, home: homedir(), cwd: process.cwd(), env: merged, now: new Date() };-}-function runAider(bin: string, sidecar: string, args: string[], cwd: string): AiderSpawnResult {const proc = spawnSync(bin, ["--read", sidecar, ...args], {cwd,diff --git a/src/cli/brain/verbs/continuity.ts b/src/cli/brain/verbs/continuity.tsindex 34c94b65..d767346b 100644--- a/src/cli/brain/verbs/continuity.ts+++ b/src/cli/brain/verbs/continuity.ts@@ -37,10 +37,10 @@ import {countSessionlessRecords,renderAtifTrajectories,} from "../../../core/brain/continuity/export-atif.ts";-import packageJson from "../../../../package.json" with { type: "json" };+import { OPEN_SECOND_BRAIN_VERSION } from "../../../core/version.ts";import { brainVerbContext, fail, parse, usageError } from "../helpers.ts";-const CLI_VERSION: string = packageJson.version;+const CLI_VERSION: string = OPEN_SECOND_BRAIN_VERSION;const USAGE ="usage: o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json]\n" +diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 5653807b..4f8b471d 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -23,9 +23,20 @@ export const INHERITED_JSON_FLAG: CliFlagManifest = Object.freeze({inherited: true,});+/**+ * The root synonym for `o2b version`. It is declared here and not only+ * handled in `main.ts` because the completion scripts and `o2b help+ * --json` are built from this manifest: a flag the manifest never heard+ * of is a flag no shell offers.+ */+export const ROOT_VERSION_FLAG: CliFlagManifest = Object.freeze({+ name: "version",+ type: "boolean",+});+export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command: "o2b",- flags: [INHERITED_JSON_FLAG],+ flags: [INHERITED_JSON_FLAG, ROOT_VERSION_FLAG],commands: [command("status", "Show Open Second Brain configuration status", [flag("config", "string"),@@ -66,6 +77,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("disable-tool", "string-array"),flag("max-tools", "string"),]),+ command("version", "Print the installed Open Second Brain version"),command("help", "Print command help or the command manifest"),command("completions", "Print shell completion script for o2b", [flag("shell", "string")]),command("install-cli", "Create symlinks for o2b and vault-log"),diff --git a/src/cli/install/install.ts b/src/cli/install/install.tsindex 25fcf604..5d6fc1f5 100644--- a/src/cli/install/install.ts+++ b/src/cli/install/install.ts@@ -28,11 +28,10 @@* The two are not the same answer and no longer share a code.*/-import { homedir } from "node:os";-import { parseFlags } from "../argparse.ts";import { defaultConfigPath, discoverConfig, resolveVault } from "../../core/config.ts";import { defaultRegistry } from "../../core/install/registry.ts";+import { VAULT_NOT_CONFIGURED_REASON, buildInstallEnv } from "../../core/install/env.ts";// The canonical adapter set registers itself into `defaultRegistry` at// module-load time via this barrel (single source of the adapter list).import "../../core/install/adapters/all.ts";@@ -163,34 +162,19 @@ export function resolveInstallVault(explicitVault: string | null, configPath: st}/**- * The `InstallEnv` every adapter on this run is handed.+ * The `InstallEnv` this run's adapters see.*- * `OPEN_SECOND_BRAIN_CONFIG` is stamped from the resolved `--config` so- * that ONE file parameterises the whole run. It did not used to be: the- * agent name, timezone and vault came from `--config`, while- * `install_hook_timeout_seconds` and `mcp_tool_profile` were read by- * `installSettingsSource` out of `~/.config/open-second-brain/config.yaml`- * because `InstallEnv` carried no config path and the resolver fell back- * to the machine default. On a box with both files populated, `--apply`- * generated from one and `--check` verified against the other. Publishing- * the choice as the variable `resolveDefaultConfigPath` already consults- * first keeps a single override in a single place, and keeps `InstallEnv`- * the complete description of the run it is documented to be.+ * The construction itself lives in `core/install/env.ts`, shared with+ * the MCP `second_brain_wiring` hosts view so the two surfaces cannot+ * describe different machines. This wrapper is the CLI's argument+ * resolution: `--vault` then the canonical resolver, and the `--config`+ * the whole run is parameterised by.*/-function buildInstallEnv(args: ParsedInstallArgs): InstallEnv {- const cfg = discoverConfig(args.config).data;- const vault = resolveInstallVault(args.vault, args.config);- const env = { ...process.env } as Record<string, string>;- env["OPEN_SECOND_BRAIN_CONFIG"] = args.config;- if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];- if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];- return {- vault,- home: homedir(),- cwd: process.cwd(),- env,- now: new Date(),- };+function installEnvForArgs(args: ParsedInstallArgs): InstallEnv {+ return buildInstallEnv({+ vault: resolveInstallVault(args.vault, args.config),+ configPath: args.config,+ });}function buildApplyOpts(@@ -281,7 +265,7 @@ export async function cmdInstall(argv: string[]): Promise<number> {}function runDetect(args: ParsedInstallArgs): number {- const env = buildInstallEnv(args);+ const env = installEnvForArgs(args);const results = defaultRegistry.detectAll(env);if (args.json) {process.stdout.write(renderDetectJson(results));@@ -350,7 +334,7 @@ function runFriction(args: ParsedInstallArgs): number {if (value !== null && resolveTarget(value) === null) return refuseUnknownTarget(flag, value);}- const env = buildInstallEnv(args);+ const env = installEnvForArgs(args);let payload;try {payload = loadPayload(args, env);@@ -386,7 +370,7 @@ function runFriction(args: ParsedInstallArgs): number {function runTarget(args: ParsedInstallArgs): number {const adapter = defaultRegistry.get(args.target!);if (!adapter) return refuseUnknownTarget("--target", args.target!);- const env = buildInstallEnv(args);+ const env = installEnvForArgs(args);let payload;try {payload = loadPayload(args, env);@@ -450,14 +434,12 @@ function runTarget(args: ParsedInstallArgs): number {}function runCheck(args: ParsedInstallArgs): number {- const env = buildInstallEnv(args);+ const env = installEnvForArgs(args);// `verify()` reads the per-vault sidecar manifest. With an unset vault,// every adapter would silently report "not-installed" off a bogus path// and the operator gets no signal that the vault is unconfigured.if (!env.vault) {- process.stderr.write(- "error: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.\n",- );+ process.stderr.write(`error: ${VAULT_NOT_CONFIGURED_REASON}\n`);return INSTALL_EXIT.usage;}const targets = args.targetdiff --git a/src/cli/json-helpers.ts b/src/cli/json-helpers.tsindex efdfb19a..dec89524 100644--- a/src/cli/json-helpers.ts+++ b/src/cli/json-helpers.ts@@ -56,6 +56,7 @@ export const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set(["partner","doctor","onboarding",+ "version",]);/**diff --git a/src/cli/main.ts b/src/cli/main.tsindex 9b913e06..594ba883 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -56,6 +56,7 @@ import {uninstallCli,} from "./install-cli.ts";import { cmdUpdate } from "./update.ts";+import { ROOT_VERSION_FLAG_TOKEN, cmdVersion } from "./version.ts";import { planUninstall, renderPlan } from "./uninstall.ts";import { cmdInstall } from "./install/install.ts";import { cmdUninstallTarget } from "./install/uninstall-target.ts";@@ -65,7 +66,7 @@ import {renderOnboardingChecklist,searchIndexExists,} from "./onboarding.ts";-import { CLI_COMMAND_MANIFEST, manifestForJson } from "./command-manifest.ts";+import { CLI_COMMAND_MANIFEST, ROOT_VERSION_FLAG, manifestForJson } from "./command-manifest.ts";import { COMPLETION_SHELLS, isCompletionShell, renderCompletions } from "./completions.ts";import { MCPServer } from "../mcp/server.ts";import { CLI_TRANSPORT_REACH } from "./transport-reach.ts";@@ -971,6 +972,16 @@ function cmdCompletions(argv: ReadonlyArray<string>): number {/** The command that hands this process over to the MCP transport. */const MCP_COMMAND = "mcp";+/**+ * The verb the root `--version` flag is a synonym of.+ *+ * Read off the flag declaration rather than spelled again, because the+ * synonym is only a synonym while the two words agree. The dispatcher+ * case itself stays a string literal, for the reason given there; that+ * the two reach the same verb is what `tests/cli/version.test.ts` pins.+ */+const VERSION_COMMAND = ROOT_VERSION_FLAG.name;+/*** Which origin channel this invocation is, derived from the command line* and from nothing else (Unit C, `src/core/origin-channel.ts`).@@ -1002,7 +1013,13 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {process.stdout.write(renderHelp());return 0;}- const command = argv[0]!;+ // The synonym of `o2b version`, REWRITTEN to the verb rather than+ // handled beside it. Routing it through the one dispatcher is what+ // makes the two spellings answer identically: an arm of its own also+ // skipped the `CliError` handler below, so `o2b version latest` said+ // "error: version takes no positional arguments" and exited 2 while+ // `o2b --version latest` printed a stack trace and exited 1.+ const command = argv[0] === ROOT_VERSION_FLAG_TOKEN ? VERSION_COMMAND : argv[0]!;const rest = argv.slice(1);// Claim the origin channel for this process before anything can write.@@ -1073,6 +1090,12 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>return cmdHelp(rest);case "completions":return cmdCompletions(rest);+ // A string literal like every sibling case, and not the constant+ // above: `tests/cli/manifest-completeness.test.ts` reads this+ // switch with `case "([^"]+)":`, so a case named through a+ // constant is a case that census cannot see.+ case "version":+ return cmdVersion(rest);case "aider":return await handleAiderSubcommand(rest);case "brain":diff --git a/src/cli/version.ts b/src/cli/version.tsnew file mode 100644index 00000000..1171a255--- /dev/null+++ b/src/cli/version.ts@@ -0,0 +1,53 @@+/**+ * `o2b version` - what this install is.+ *+ * The MCP handshake has always carried `serverInfo.version`; the shell+ * had no way to ask. This verb closes that half, and the root+ * `--version` flag in `main.ts` routes here rather than rendering a+ * second line of its own: two spellings of one question that answer+ * differently are worse than one spelling, because the difference is+ * invisible until someone pastes the wrong one into a bug report.+ *+ * The version itself is not computed here. `src/core/version.ts` holds+ * the tree's only read of the manifest, and this verb reports it.+ */++import { OPEN_SECOND_BRAIN_VERSION } from "../core/version.ts";+import { CliError, parseFlags } from "./argparse.ts";+import { ROOT_VERSION_FLAG } from "./command-manifest.ts";+import { sortedReplacer } from "./helpers.ts";++/**+ * The root synonym `main.ts` matches on, spelled from the manifest+ * declaration so the dispatcher and the completion scripts cannot come+ * to disagree about what the flag is called.+ */+export const ROOT_VERSION_FLAG_TOKEN = `--${ROOT_VERSION_FLAG.name}`;++/** JSON member name, shared by the renderer and the tests that parse it. */+const VERSION_FIELD = "version";++const USAGE = "usage: o2b version [--json]";++/**+ * Render the version to stdout.+ *+ * `argv` is everything after the verb (or after the root flag). It takes+ * no positional argument: `o2b version latest` is a request this verb+ * cannot honour - nothing in this tree learns what any other version is+ * - so it is a usage error rather than a silent print of the local one.+ */+export function cmdVersion(argv: ReadonlyArray<string>): number {+ const { flags, positional } = parseFlags(argv, { json: { type: "boolean" } });+ if (positional.length > 0) {+ throw new CliError(`version takes no positional arguments: ${positional.join(" ")}\n${USAGE}`);+ }+ if (flags["json"] === true) {+ process.stdout.write(+ JSON.stringify({ [VERSION_FIELD]: OPEN_SECOND_BRAIN_VERSION }, sortedReplacer) + "\n",+ );+ return 0;+ }+ process.stdout.write(`${OPEN_SECOND_BRAIN_VERSION}\n`);+ return 0;+}diff --git a/src/core/brain/notes/write-record.ts b/src/core/brain/notes/write-record.tsindex 4b4dfa70..2277198c 100644--- a/src/core/brain/notes/write-record.ts+++ b/src/core/brain/notes/write-record.ts@@ -362,8 +362,19 @@ export function pruneWriteImages(// An unmeasurable age is not an old age: a file whose mtime this// process cannot read is kept, because "I could not tell" must never// resolve to "remove it".+ //+ // A NEGATIVE age is not a young age either, and it is floored here+ // rather than in `fileAgeMs`, which documents that it does not clamp+ // and has a test pinning the future-stamped case. A file stamped at+ // or after `nowMs` is zero days old for retention. Unfloored,+ // `msToWholeDays` takes -1ms to -1 whole day, which is below every+ // window including zero, so the image is kept forever - and the+ // condition is ordinary rather than exotic: `nowMs` is sampled once+ // before the sweep, and mtime granularity on a synced or networked+ // filesystem rounds a write made just before it up past it. This+ // flaked the `olderThanDays: 0` cases in CI on one image of two.const ageMs = fileAgeMs(path, nowMs);- if (ageMs === null || msToWholeDays(ageMs) < olderThanDays) {+ if (ageMs === null || msToWholeDays(Math.max(0, ageMs)) < olderThanDays) {kept += 1;continue;}diff --git a/src/core/install/env.ts b/src/core/install/env.tsnew file mode 100644index 00000000..b0e4e0d1--- /dev/null+++ b/src/core/install/env.ts@@ -0,0 +1,63 @@+/**+ * The `InstallEnv` every adapter on a run is handed, built once.+ *+ * `InstallEnv` is documented as the complete description of a run, and+ * building it was private to the `o2b install` verb. The MCP `hosts`+ * view answers the same question over the same adapters, and a second+ * env builder would be a second answer to "which machine is being+ * verified" - the split this constructor's own docblock in the CLI was+ * written to close, one surface over.+ *+ * Core rather than CLI because both callers need it and core is the+ * layer they share; nothing here writes to stdout or exits.+ */++import { homedir } from "node:os";++import { discoverConfig } from "../config.ts";+import type { InstallEnv } from "./types.ts";++/**+ * Why a run with no vault refuses instead of verifying.+ *+ * `verify()` reads the per-vault sidecar manifest, so with an unset+ * vault every adapter reports `not-installed` off a bogus path and the+ * operator is told ten runtimes are absent when the real condition is+ * that nothing was configured. Named here rather than in each surface+ * so the CLI's usage error and the MCP refusal say the same sentence.+ */+export const VAULT_NOT_CONFIGURED_REASON =+ "vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.";++/** What an install run needs to know before it can build its env. */+export interface InstallEnvInput {+ /** The resolved vault; the empty string when nothing resolved one. */+ readonly vault: string;+ /** The config file that parameterises the whole run. */+ readonly configPath: string;+}++/**+ * The environment adapters see.+ *+ * `OPEN_SECOND_BRAIN_CONFIG` is stamped from the resolved config path so+ * that ONE file parameterises the run: the agent name, timezone and+ * vault came from `--config` while `install_hook_timeout_seconds` and+ * `mcp_tool_profile` were read out of the machine default, and on a box+ * with both files populated `--apply` generated from one and `--check`+ * verified against the other.+ */+export function buildInstallEnv(input: InstallEnvInput): InstallEnv {+ const cfg = discoverConfig(input.configPath).data;+ const env = { ...process.env } as Record<string, string>;+ env["OPEN_SECOND_BRAIN_CONFIG"] = input.configPath;+ if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];+ if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];+ return {+ vault: input.vault,+ home: homedir(),+ cwd: process.cwd(),+ env,+ now: new Date(),+ };+}diff --git a/src/core/install/opencode-plugin-asset.ts b/src/core/install/opencode-plugin-asset.tsindex 3cea8197..8519f313 100644--- a/src/core/install/opencode-plugin-asset.ts+++ b/src/core/install/opencode-plugin-asset.ts@@ -13,7 +13,7 @@import { readFileSync } from "node:fs";import { join } from "node:path";-import packageJson from "../../../package.json";+import { OPEN_SECOND_BRAIN_VERSION } from "../version.ts";const PLUGIN_SOURCE_PATH = join(import.meta.dir,@@ -36,7 +36,7 @@ export const OPENCODE_PLUGIN_FILENAME = "open-second-brain.ts";export function installedPluginContent(): string {const source = readFileSync(PLUGIN_SOURCE_PATH, "utf8");return (- `// open-second-brain plugin v${packageJson.version}` ++ `// open-second-brain plugin v${OPEN_SECOND_BRAIN_VERSION}` +" (installed copy; re-apply `o2b install --target opencode --apply` after upgrades)\n" +source);diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.tsindex 57cefc79..e14b33bf 100644--- a/src/core/install/ownership.ts+++ b/src/core/install/ownership.ts@@ -306,10 +306,17 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma"runtime_config_blocks row the adapters already declare",],[- "src/cli/install/install.ts",+ "src/mcp/wiring-tools.ts",+ "the only out-of-vault path it handles is `InstallEnv.home`, and it handles it in order to " ++ "REMOVE it: `foldHostHome` folds that prefix out of the adapter sentences before they reach " ++ "an MCP payload. The tool reads install state and writes nothing anywhere",+ ],+ [+ "src/core/install/env.ts","the only out-of-vault path it builds is `InstallEnv.home`, which it hands to the adapters; " +- "every file written from it belongs to the runtime_config_blocks row, and this verb writes " +- "nothing outside the vault on its own account",+ "every file written from it belongs to the runtime_config_blocks row, and this constructor " ++ "writes nothing at all. It is where the `o2b install` verb used to resolve the home, moved " ++ "here so the MCP wiring view verifies the same machine the CLI does",],["src/cli/install/init-interactive.ts",@@ -434,6 +441,12 @@ export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new M"operator-supplied absolute path; there is no home or XDG token in the source to match on. " +"Where it actually resolved IS measured per run and printed on the first line",],+ [+ "src/cli/aider.ts",+ "the wrapper still writes the aider sidecar, but it no longer builds the home path it writes " ++ "under: `InstallEnv` now arrives from `core/install/env.ts`, the one constructor the MCP " ++ "wiring view shares, so there is no root token left in this file to match on",+ ],["src/cli/brain/verbs/bench.ts","the bench directory is a relative path resolved against the working directory, so it carries " +diff --git a/src/core/version.ts b/src/core/version.tsnew file mode 100644index 00000000..13be3ed1--- /dev/null+++ b/src/core/version.ts@@ -0,0 +1,21 @@+/**+ * The version of this Open Second Brain install, read once.+ *+ * `package.json` `version` is the repository's single source of truth+ * (`CLAUDE.md`), mirrored into the plugin manifests and `pyproject.toml`+ * by `scripts/sync-version.ts`. This module is the single source of+ * truth for the same fact INSIDE `src/`: every surface that reports a+ * version - the CLI verb, the MCP handshake, the continuity export+ * header, the stamped opencode plugin - reads this constant rather than+ * importing the manifest again.+ *+ * It is a leaf on purpose. It imports the manifest and nothing else, so+ * any layer may depend on it without pulling a dependency along, and+ * `tests/core/version.test.ts` holds the census that keeps the manifest+ * import from spreading back out.+ */++import packageJson from "../../package.json" with { type: "json" };++/** The version this install reports on every surface. */+export const OPEN_SECOND_BRAIN_VERSION: string = packageJson.version;diff --git a/src/mcp/instruction-segments.ts b/src/mcp/instruction-segments.tsnew file mode 100644index 00000000..a84c5c1e--- /dev/null+++ b/src/mcp/instruction-segments.ts@@ -0,0 +1,493 @@+/**+ * The scope bodies of `initialize.instructions`, as tool-tagged segments.+ *+ * ## Why the text is not a constant any more+ *+ * The instruction block is the first thing every agent reads, and it used+ * to be one frozen string per scope. This server already evaluates a+ * runtime capability window and knows, per tool, whether it is available+ * or withheld and why (`evaluateToolCapabilities`) - so a host that+ * disables `brain_note` produced a handshake whose opening paragraph+ * instructed the agent to call it. The agent then calls, reads the+ * refusal, and learns that the first text it was given was wrong.+ *+ * Appending a "…except these" block beneath the same prose does not fix+ * that. An instruction and its retraction in one document leave the+ * reader deciding which half is true, and the half printed first is the+ * one that shapes the plan. So the guidance is REMOVED, and the removal+ * is NAMED with the reason the evaluator already produced. No second+ * vocabulary is invented here: every reason in the withheld block is a+ * string {@link evaluateToolCapabilities} wrote.+ *+ * ## The model+ *+ * A scope body is an ordered list of {@link InstructionParagraph}s+ * joined by a blank line. A paragraph is an ordered list of+ * {@link InstructionSegment}s, each declaring the tool names its text+ * instructs the reader to call.+ *+ * - A segment renders when EVERY tool it names is available. A segment+ * naming none is unconditional text.+ * - Between two rendered segments goes the `separator` of the earlier+ * one, so a dropped clause takes its own punctuation with it and the+ * survivors still read as one sentence.+ * - A paragraph whose every tool-bearing segment was dropped renders+ * NOTHING, its unconditional text included. A lead-in with nothing+ * left to lead into is not guidance, and a sentence such as "Five+ * tools live here" is a claim that stops being true the moment one+ * of them is withheld.+ * - The exception to that last rule is declared, not inferred: a+ * segment marked {@link InstructionSegment.standsAlone} states a+ * fact of its own rather than introducing the items around it, so it+ * keeps its paragraph alive when they go.+ *+ * A paragraph's LEAD-IN is a segment, not a prefix welded to the first+ * item. It has to be, or withholding the first tool takes the heading+ * with it and the survivors open mid-sentence - the memory contract+ * losing "Memory contract: call", the view list losing "Consolidated+ * read views:".+ *+ * The fully-available render is byte-identical to the strings this model+ * replaces; `tests/mcp/instruction-segments.test.ts` pins that against a+ * captured fixture so a reshaping cannot quietly become a rewrite.+ *+ * The catalog body carries the one deliberate exception. Its frozen+ * string said every tool omitted from `tools/list` stays callable+ * through `tools/call`; that is true of the catalog surface's hiding+ * and false of a capability window, which removes the tool from the+ * table `tools/call` routes on. Carrying that sentence unchanged into a+ * module whose whole subject is the window would ship a handshake that+ * contradicts the runtime it was rendered for, so the sentence now+ * separates the two cases and the fixture carries the corrected text.+ *+ * ## What the withheld block does and does not list+ *+ * It lists the tools THIS TEXT would have instructed and cannot - the+ * intersection of the report's `withheld` entries with the names the+ * scope's segments declare. Not the whole withheld set: a `max_tools`+ * window on the full scope withholds over a hundred tools, and pasting+ * that list into the handshake would spend more tokens explaining an+ * absence than the removed guidance ever cost.+ *+ * The block closes by saying where the complete report is - but only on+ * a surface that has one. No capability WINDOW ever withholds+ * {@link CAPABILITY_DIAGNOSTIC_TOOL}, and the writer scope does not+ * register it at all: `buildToolTable("writer")` is the five always-+ * loaded tools and nothing else. Pointing an agent there would be the+ * defect this module exists to remove, reintroduced by the sentence+ * that explains the removal, so the pointer is emitted only when the+ * report says the tool is available and the names stand alone+ * otherwise.+ */++import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";+import { TOOL_SCOPE, type ToolCapabilityReport, type ToolScope } from "./tool-contract.ts";++/** One run of instruction text and the tools whose availability it assumes. */+export interface InstructionSegment {+ /**+ * Tool names the text instructs the reader to call. Empty means the+ * text stands whatever the runtime withholds.+ */+ readonly tools: ReadonlyArray<string>;+ /** The text, carrying no leading or trailing separator of its own. */+ readonly text: string;+ /**+ * Placed before the next rendered segment of the same paragraph.+ * Absent on the last segment, and on any segment whose successor+ * begins a new sentence of its own.+ */+ readonly separator?: string;+ /**+ * Exempts this segment from the paragraph-drop rule.+ *+ * Unconditional text is a lead-in by default, and a lead-in goes when+ * its items go. A segment that states a fact of its own does not:+ * what the catalog surface's hiding does and does not do to+ * callability is true whatever the runtime withholds, and it is the+ * sentence the catalog's "Second pass" depends on to mean anything.+ */+ readonly standsAlone?: boolean;+}++/** Segments that render as one paragraph. */+export interface InstructionParagraph {+ readonly segments: ReadonlyArray<InstructionSegment>;+ /** Appended once after the last rendered segment, when any rendered. */+ readonly end?: string;+}++/**+ * Between two paragraphs, and between the body and the withheld block.+ *+ * Exported because the identity line is joined to the body with this+ * same break one module up: two spellings of one document's block+ * separator can drift, and the fixture that would catch the drift is+ * pinned against the joined result.+ */+export const PARAGRAPH_BREAK = "\n\n";++/** Between the lines of a bulleted paragraph. */+const LINE_BREAK = "\n";++/** Between two clauses of one sentence. */+const CLAUSE = "; ";++/** Between two sentences of one paragraph. */+const SENTENCE = ". ";++/** Between two items of an inline list. */+const ITEM = ", ";++/** Between a lead-in and the first item it introduces. */+const LEAD_IN = " ";++/** Indent of a bullet, matching the shipped writer body. */+const BULLET = " - ";++/** Heading of the block that names what this runtime withheld. */+export const WITHHELD_BLOCK_HEADING =+ "Withheld in this runtime, so the guidance naming them is not in the text above:";++/** Closing line of the withheld block: where the complete report is. */+const WITHHELD_BLOCK_POINTER =+ `Call ${CAPABILITY_DIAGNOSTIC_TOOL} for the complete availability report; ` ++ "it lists tools this text never names.";++/**+ * Reason a segment's tool carries when the report knows nothing about it.+ *+ * Unreachable in a shipped build - the orphan census in+ * `tests/mcp/instruction-segments.test.ts` fails on a segment naming a+ * tool its scope does not register - and stated anyway, because the+ * alternative is a segment that disappears with no line saying so.+ */+const UNREGISTERED_REASON = "not registered in this server's tool table";++/** The always-loaded writer surface, in the order the writer body lists it. */+const WRITER_TOOLS = Object.freeze([+ "brain_feedback",+ "brain_apply_evidence",+ "brain_note",+ "brain_pinned_context",+ "brain_context",+]);++/** The deferred catalog's own entry point. */+const HYDRATE_TOOL = "tool_hydrate";++/** The consolidated read views the full body advertises. */+const VIEW_TOOLS = Object.freeze(["brain_brief", "brain_analytics", "schema_inspect"]);++/** The escape hatch for a truncated preview. */+const ARTIFACT_TOOL = "brain_artifact_get";++/** Text that stands whatever the runtime withholds. */+function unconditional(text: string, separator?: string): InstructionSegment {+ return { tools: [], text, ...(separator === undefined ? {} : { separator }) };+}++const FULL_BODY: ReadonlyArray<InstructionParagraph> = Object.freeze([+ {+ end: ".",+ segments: [+ unconditional("Memory contract: call", LEAD_IN),+ {+ tools: ["brain_feedback"],+ text: "brain_feedback once per taste signal the user expresses",+ separator: CLAUSE,+ },+ {+ tools: ["brain_apply_evidence"],+ text:+ "brain_apply_evidence right after producing a durable artifact a preference " ++ "in `Brain/preferences/` scopes to (result: applied | violated | outdated)",+ separator: CLAUSE,+ },+ {+ tools: ["brain_note"],+ text: "brain_note for narrative milestones that fit neither",+ separator: CLAUSE,+ },+ {+ tools: ["brain_pinned_context"],+ text: "brain_pinned_context for current-task facts that must survive context rotation",+ separator: SENTENCE,+ },+ {+ tools: ["brain_context"],+ text: "brain_context bootstraps a session when the host injects no active.md hook",+ separator: SENTENCE,+ },+ unconditional(+ "Skip Brain calls for casual chat, exploration, and trivial edits - " ++ "a misrecorded signal is worse than a missed one",+ ),+ ],+ },+ {+ end: ".",+ segments: [+ unconditional("Consolidated read views:", LEAD_IN),+ {+ tools: ["brain_brief"],+ text: "brain_brief (view: morning | daily | weekly | monthly | operator | digest)",+ separator: ITEM,+ },+ {+ tools: ["brain_analytics"],+ text:+ "brain_analytics (view: timeline | attention_flows | belief_evolution | " ++ "concept_synthesis)",+ separator: ITEM,+ },+ {+ tools: ["schema_inspect"],+ text:+ "schema_inspect (view: graph | lint | stats | orphans | explain_type | " ++ "active_pack | packs)",+ separator: SENTENCE,+ },+ {+ // The sentence is about the aliases of those three views, so it+ // stands or falls with them rather than dangling on its own.+ tools: VIEW_TOOLS,+ text: "The per-view predecessor names still resolve via tools/call as deprecated aliases",+ },+ ],+ },+ {+ segments: [+ {+ tools: [ARTIFACT_TOOL],+ text:+ "Preview budget: a large result may arrive as a JSON envelope with " ++ "`preview_truncated: true` and an `artifact_id`; fetch the full payload " ++ "with brain_artifact_get only when the preview is not enough.",+ },+ ],+ },+]);++const WRITER_BODY: ReadonlyArray<InstructionParagraph> = Object.freeze([+ { segments: [unconditional("Open Second Brain — always-loaded MCP surface.")] },+ {+ segments: [+ {+ // The count is a claim about the whole set, so it goes when any+ // member does; the bullets that survive still say what is here.+ tools: WRITER_TOOLS,+ text:+ "Five tools live here (four writers + one reader; the server's name is\n" ++ "preserved for backward compatibility with existing client configs):",+ separator: LINE_BREAK,+ },+ {+ tools: ["brain_feedback"],+ text: `${BULLET}brain_feedback — record one new taste signal the user just expressed.`,+ separator: LINE_BREAK,+ },+ {+ tools: ["brain_apply_evidence"],+ text:+ `${BULLET}brain_apply_evidence — record applied | violated | outdated against an\n` ++ " active preference for an artifact this turn produced.",+ separator: LINE_BREAK,+ },+ {+ tools: ["brain_note"],+ text:+ `${BULLET}brain_note — record one narrative milestone (release shipped,\n` ++ " PR merged, fact discovered) that fits neither\n" ++ " category.",+ separator: LINE_BREAK,+ },+ {+ tools: ["brain_pinned_context"],+ text:+ `${BULLET}brain_pinned_context — read/write/append/clear Brain/pinned.md for\n` ++ " current-task facts that should survive context\n" ++ " rotation without becoming permanent preferences.",+ separator: LINE_BREAK,+ },+ {+ tools: ["brain_context"],+ text:+ `${BULLET}brain_context — pull the current Brain/active.md body plus\n` ++ " pinned context and active-preference counts.\n" ++ " Read-only. Use at session\n" ++ " start when the host runtime lacks a SessionStart\n" ++ " hook (Cursor, Aider, raw Claude API). Runtimes that\n" ++ " already inject active.md via a hook can skip this.",+ },+ ],+ },+ {+ segments: [+ unconditional(+ 'The remaining Brain surface lives on the sibling "open-second-brain"\n' ++ "MCP server (deferred), including additional read-only, analytics,\n" ++ "maintenance, and workflow tools beyond the always-loaded writer set.\n" ++ "Use ToolSearch to discover and reach it.",+ ),+ ],+ },+ {+ segments: [+ {+ tools: WRITER_TOOLS.filter((name) => name !== "brain_context"),+ text:+ "Prefer the writer-server copies of brain_feedback / brain_apply_evidence /\n" ++ "brain_note / brain_pinned_context over any duplicate exposed by the full server — both call the same\n" ++ "handler, but the writer copy is always available without ToolSearch.",+ },+ ],+ },+]);++const CATALOG_BODY: ReadonlyArray<InstructionParagraph> = Object.freeze([+ { segments: [unconditional("Open Second Brain — two-pass catalog MCP surface.")] },+ {+ segments: [+ {+ // The enumeration is a claim about a set, so it goes when a+ // member does.+ tools: [...WRITER_TOOLS, HYDRATE_TOOL],+ text:+ "This server advertises a compact first-pass tool set: the capability\n" ++ "diagnostic, the five always-loaded Brain writers/readers, and\n" ++ "tool_hydrate",+ separator: SENTENCE,+ },+ {+ // The fact that nothing is unreachable does not depend on which+ // tools this runtime allows, and the "Second pass" paragraph+ // below is unreadable without it.+ tools: [],+ standsAlone: true,+ text:+ "A tool the catalog surface alone omits from\n" ++ "tools/list stays CALLABLE via tools/call — the omission keeps schema\n" ++ "tokens out of your prompt until needed. A tool a runtime capability\n" ++ "window withholds is not callable at all.",+ },+ ],+ },+ {+ segments: [+ {+ tools: [HYDRATE_TOOL],+ text:+ "Second pass: call tool_hydrate with no arguments to get the compact\n" ++ "catalog (name, one-line description, group) of every tool in this\n" ++ "process, then call tool_hydrate with names: [...] to fetch the full\n" ++ "input/output schemas for the tools you actually need. After hydration,\n" ++ "invoke those tools directly by name through tools/call — no further\n" ++ "registration step exists or is needed.",+ },+ ],+ },+ {+ segments: [+ {+ tools: [HYDRATE_TOOL],+ text:+ "Do not invent substitute workflows for a capability you cannot see:\n" ++ "hydrate the catalog first; the tool is almost certainly already here.",+ },+ ],+ },+]);++/**+ * The body of each scope.+ *+ * A total map rather than a chain of `if`s: a scope added to+ * {@link TOOL_SCOPE} without a body here fails to compile.+ */+const SCOPE_BODIES: Readonly<Record<ToolScope, ReadonlyArray<InstructionParagraph>>> =+ Object.freeze({+ [TOOL_SCOPE.full]: FULL_BODY,+ [TOOL_SCOPE.writer]: WRITER_BODY,+ [TOOL_SCOPE.catalog]: CATALOG_BODY,+ });++/** Every tool name the segments of `scope` declare, in declaration order. */+export function segmentToolNames(scope: ToolScope): string[] {+ const seen = new Set<string>();+ for (const paragraph of SCOPE_BODIES[scope]) {+ for (const segment of paragraph.segments) {+ for (const name of segment.tools) seen.add(name);+ }+ }+ return [...seen];+}++/** One paragraph, or null when nothing in it survived the runtime. */+function renderParagraph(+ paragraph: InstructionParagraph,+ isAvailable: (name: string) => boolean,+): string | null {+ const rendered = paragraph.segments.filter((segment) => segment.tools.every(isAvailable));+ if (rendered.length === 0) return null;+ const conditional = paragraph.segments.some((segment) => segment.tools.length > 0);+ const survivesOnItsOwn = rendered.some(+ (segment) => segment.tools.length > 0 || segment.standsAlone === true,+ );+ if (conditional && !survivesOnItsOwn) return null;+ let out = "";+ let pending = "";+ for (const segment of rendered) {+ out += pending + segment.text;+ pending = segment.separator ?? "";+ }+ return out + (paragraph.end ?? "");+}++/** The withheld block, or null when this scope's guidance survived intact. */+function renderWithheldBlock(scope: ToolScope, report: ToolCapabilityReport): string | null {+ const reasons = new Map(report.withheld.map((entry) => [entry.name, entry.reason]));+ const available = new Set(report.available.map((entry) => entry.name));+ const lines: string[] = [];+ for (const name of segmentToolNames(scope)) {+ if (available.has(name)) continue;+ lines.push(`${BULLET}${name}: ${reasons.get(name) ?? UNREGISTERED_REASON}`);+ }+ if (lines.length === 0) return null;+ if (!available.has(CAPABILITY_DIAGNOSTIC_TOOL)) {+ return [WITHHELD_BLOCK_HEADING, ...lines].join(LINE_BREAK);+ }+ return [WITHHELD_BLOCK_HEADING, ...lines, "", WITHHELD_BLOCK_POINTER].join(LINE_BREAK);+}++/**+ * The instruction body for `scope` under the runtime `report` describes.+ *+ * The identity line is not part of it: that is the caller's, because it+ * answers a different question and refuses for a different reason.+ *+ * Both arguments carry the scope, and a mismatch is refused BY NAME+ * rather than rendered. The evaluator's `available` set is what decides+ * every segment here, so a report built for another scope deletes every+ * paragraph and then explains the deletion with reasons that are not+ * true of this server - a confident wrong answer where the caller+ * passed two arguments that disagree.+ */+export function renderScopeBody(scope: ToolScope, report: ToolCapabilityReport): string {+ if (report.scope !== scope) {+ throw new Error(+ `capability report is for the ${report.scope} scope, not ${scope}: ` ++ "the instruction body and the availability it renders must describe one server",+ );+ }+ const available = new Set(report.available.map((entry) => entry.name));+ const isAvailable = (name: string): boolean => available.has(name);+ const blocks: string[] = [];+ for (const paragraph of SCOPE_BODIES[scope]) {+ const text = renderParagraph(paragraph, isAvailable);+ if (text !== null) blocks.push(text);+ }+ const withheld = renderWithheldBlock(scope, report);+ if (withheld !== null) blocks.push(withheld);+ return blocks.join(PARAGRAPH_BREAK);+}diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 9e34be53..9da3a17d 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -1,14 +1,21 @@/*** Server-supplied instructions returned in `initialize.instructions`.*+ * Two independent facts assemble here and nowhere else: WHO this agent+ * is on this vault, and WHAT this runtime actually left callable. The+ * identity line answers the first and refuses in its own way when the+ * config cannot be read; `instruction-segments.ts` answers the second+ * and renders the body from the live capability report.+ ** The Brain observing-memory layer is the canonical writable surface:* four writer tools (`brain_feedback`, `brain_apply_evidence`,- * `brain_note`, `brain_pinned_context`) plus the read-only `brain_context` reader live on the- * always-loaded writer scope; the remaining `brain_*` surface ships on- * the deferred full server.+ * `brain_note`, `brain_pinned_context`) plus the read-only+ * `brain_context` reader live on the always-loaded writer scope; the+ * remaining `brain_*` surface ships on the deferred full server.*/-import { TOOL_SCOPE, type ToolScope } from "./tool-contract.ts";+import { PARAGRAPH_BREAK, renderScopeBody } from "./instruction-segments.ts";+import { TOOL_SCOPE, type ToolCapabilityReport, type ToolScope } from "./tool-contract.ts";export interface BuildInstructionsOpts {/**@@ -25,88 +32,20 @@ export interface BuildInstructionsOpts {readonly agent: string | Error;/** Which surface's body follows the identity line. Defaults to full. */readonly scope?: ToolScope;+ /**+ * What this runtime left callable, as the server's own evaluator+ * computed it.+ *+ * Required rather than optional: a default of "assume everything is+ * available" is exactly the wrong answer this parameter exists to+ * remove, and it would be indistinguishable at the call site from a+ * runtime that really does have everything. The server holds the+ * report on the instance from construction, so there is no caller that+ * would have to invent one.+ */+ readonly capabilities: ToolCapabilityReport;}-/** Separator between the identity sentence and every paragraph after it. */-const PARAGRAPH_BREAK = "\n\n";--const WRITER_INSTRUCTIONS = `Open Second Brain — always-loaded MCP surface.--Five tools live here (four writers + one reader; the server's name is-preserved for backward compatibility with existing client configs):- - brain_feedback — record one new taste signal the user just expressed.- - brain_apply_evidence — record applied | violated | outdated against an- active preference for an artifact this turn produced.- - brain_note — record one narrative milestone (release shipped,- PR merged, fact discovered) that fits neither- category.- - brain_pinned_context — read/write/append/clear Brain/pinned.md for- current-task facts that should survive context- rotation without becoming permanent preferences.- - brain_context — pull the current Brain/active.md body plus- pinned context and active-preference counts.- Read-only. Use at session- start when the host runtime lacks a SessionStart- hook (Cursor, Aider, raw Claude API). Runtimes that- already inject active.md via a hook can skip this.--The remaining Brain surface lives on the sibling "open-second-brain"-MCP server (deferred), including additional read-only, analytics,-maintenance, and workflow tools beyond the always-loaded writer set.-Use ToolSearch to discover and reach it.--Prefer the writer-server copies of brain_feedback / brain_apply_evidence /-brain_note / brain_pinned_context over any duplicate exposed by the full server — both call the same-handler, but the writer copy is always available without ToolSearch.`;--const CATALOG_INSTRUCTIONS = `Open Second Brain — two-pass catalog MCP surface.--This server advertises a compact first-pass tool set: the capability-diagnostic, the five always-loaded Brain writers/readers, and-tool_hydrate. Every other Open Second Brain tool stays CALLABLE via-tools/call — it is only omitted from tools/list to keep schema tokens-out of your prompt until needed.--Second pass: call tool_hydrate with no arguments to get the compact-catalog (name, one-line description, group) of every tool in this-process, then call tool_hydrate with names: [...] to fetch the full-input/output schemas for the tools you actually need. After hydration,-invoke those tools directly by name through tools/call — no further-registration step exists or is needed.--Do not invent substitute workflows for a capability you cannot see:-hydrate the catalog first; the tool is almost certainly already here.`;--/**- * The body every scope other than writer and catalog carries.- *- * Deliberately terse (token-diet): per-tool detail lives in the tool- * descriptions and docs/mcp.md; this text carries only the contract that- * cannot be read off the schemas.- */-const FULL_INSTRUCTIONS =- "Memory contract: call brain_feedback once per taste signal the " +- "user expresses; brain_apply_evidence right after producing a " +- "durable artifact a preference in `Brain/preferences/` scopes to " +- "(result: applied | violated | outdated); brain_note for narrative " +- "milestones that fit neither; brain_pinned_context for current-task " +- "facts that must survive context rotation. brain_context " +- "bootstraps a session when the host injects no active.md hook. " +- "Skip Brain calls for casual chat, exploration, and trivial edits - " +- "a misrecorded signal is worse than a missed one." +- PARAGRAPH_BREAK +- "Consolidated read views: brain_brief (view: morning | daily | " +- "weekly | monthly | operator | digest), brain_analytics (view: " +- "timeline | attention_flows | belief_evolution | concept_synthesis), " +- "schema_inspect (view: graph | lint | stats | orphans | " +- "explain_type | active_pack | packs). The per-view predecessor " +- "names still resolve via tools/call as deprecated aliases." +- PARAGRAPH_BREAK +- "Preview budget: a large result may arrive as a JSON envelope with " +- "`preview_truncated: true` and an `artifact_id`; fetch the full " +- "payload with brain_artifact_get only when the preview is not " +- "enough.";-/*** The opening identity sentence of every scope's instructions.*@@ -133,20 +72,6 @@ function identityLine(agent: string | Error): string {);}-/**- * The body each scope carries after the identity line.- *- * A total map rather than a chain of `if`s: a scope added to- * {@link TOOL_SCOPE} without a body here fails to compile, which is the- * only reason the omission that this function used to carry - two of three- * scopes returning before `agent` was read - could not recur.- */-const SCOPE_BODIES: Readonly<Record<ToolScope, string>> = Object.freeze({- [TOOL_SCOPE.full]: FULL_INSTRUCTIONS,- [TOOL_SCOPE.writer]: WRITER_INSTRUCTIONS,- [TOOL_SCOPE.catalog]: CATALOG_INSTRUCTIONS,-});-/*** Build the `initialize.instructions` block for one server process.*@@ -157,6 +82,6 @@ const SCOPE_BODIES: Readonly<Record<ToolScope, string>> = Object.freeze({* writers.*/export function buildInstructions(opts: BuildInstructionsOpts): string {- const body = SCOPE_BODIES[opts.scope ?? TOOL_SCOPE.full];- return identityLine(opts.agent) + PARAGRAPH_BREAK + body;+ const scope = opts.scope ?? TOOL_SCOPE.full;+ return identityLine(opts.agent) + PARAGRAPH_BREAK + renderScopeBody(scope, opts.capabilities);}diff --git a/src/mcp/protocol.ts b/src/mcp/protocol.tsindex ac4704e2..7cb12e33 100644--- a/src/mcp/protocol.ts+++ b/src/mcp/protocol.ts@@ -6,12 +6,12 @@* same JSON-RPC error codes.*/-import packageJson from "../../package.json" with { type: "json" };+import { OPEN_SECOND_BRAIN_VERSION } from "../core/version.ts";export const PROTOCOL_VERSION = "2025-06-18";export const SERVER_NAME = "open-second-brain";export const JSONRPC_VERSION = "2.0";-export const SERVER_VERSION: string = packageJson.version;+export const SERVER_VERSION: string = OPEN_SECOND_BRAIN_VERSION;export const PARSE_ERROR = -32700;export const INVALID_REQUEST = -32600;diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 50f23c30..063dcd02 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -364,6 +364,8 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.fr// Bounded-by-construction reads.second_brain_capabilities: "fixed-size capability report",+ second_brain_wiring:+ "view=hosts is bounded by construction (one small fixed-shape entry per adapter in a registry this build closes); view=projects reads a registry nothing caps, so its list is capped in the handler at WIRING_MAX_PROJECTS and carries total/returned/truncated beside it, self-declaring its truncation",second_brain_status:"diagnostic contract; callers need full brain/search/config blocks, not a preview envelope",brain_context:diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex a97861d9..2d953739 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -375,6 +375,10 @@ export class MCPServer {instructions: buildInstructions({agent: identity,scope: this.scope,+ // Computed in the constructor and held on the instance, so the+ // handshake states what this runtime actually left callable+ // without evaluating the window a second time.+ capabilities: this.capabilityReport,}),};}diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.tsindex b22e7560..1f08a74f 100644--- a/src/mcp/tool-contract.ts+++ b/src/mcp/tool-contract.ts@@ -89,9 +89,18 @@ export interface ToolCapabilityReport {readonly available_tool_count: number;/*** The tools a host actually LISTS: `available_tool_count` minus the- * ones marked `hidden`, which `tools/list` filters out. The two- * numbers are a hundred and three apart under the `catalog` surface,- * and it is this one the host's ceiling applies to.+ * ones marked `hidden`, which `tools/list` filters out. Under the+ * `catalog` surface it is seven whatever the tool table's size - the+ * capability diagnostic, the five always-loaded Brain tools and+ * `tool_hydrate` - and it is this number the host's ceiling applies+ * to. Stated as the relation rather than as the gap, which was a+ * figure that went stale on the next tool added and twice had.+ *+ * Seven is the NO-WINDOW count. `evaluateToolCapabilities` applies+ * the runtime capability window before counting, so a window that+ * withholds one of those seven lowers this number with it - the only+ * exception being the capability diagnostic, which no window+ * withholds.*/readonly advertised_tool_count: number;readonly host_ceiling: HostCeilingReport;diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex b2936d3d..0f1204d7 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -32,6 +32,7 @@ import { collectRuntimeNotices } from "../core/brain/runtime-notices.ts";import { probeVaultDirectory, type UnresolvedField } from "../core/vault-presence.ts";import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";import { BRAIN_TOOLS } from "./brain-tools.ts";+import { WIRING_TOOLS } from "./wiring-tools.ts";import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";import { SCHEMA_TOOLS } from "./schema-tools.ts";import { WATCHDOG_TOOLS } from "./watchdog-tools.ts";@@ -551,6 +552,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniti...SCHEMA_TOOLS,...WATCHDOG_TOOLS,...SKILL_TOOLS,+ ...WIRING_TOOLS,];if (scope === TOOL_SCOPE.writer) return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));// The hydrate tool closes over the finished table (itself included)diff --git a/src/mcp/vault-path-field.ts b/src/mcp/vault-path-field.tsindex eb21d18e..1477184e 100644--- a/src/mcp/vault-path-field.ts+++ b/src/mcp/vault-path-field.ts@@ -15,6 +15,11 @@* the raw host path instead would breach the redaction contract this* function exists to enforce, so there is no value to fall back to.*+ * The reason it reports is {@link CONFIG_UNREADABLE_REASON} rather than+ * the error's own message, which names the config file - a path under+ * the operator's home, in the one field written to keep host paths out+ * of model context.+ ** ## Why it is a module of its own** It used to be a private function inside `./tools.ts`, where the ten@@ -31,6 +36,7 @@*/import { ConfigReadError, resolveExposeHostPaths, vaultStoreReference } from "../core/config.ts";+import { escapeRegex } from "../core/strings.ts";import type { UnresolvedField } from "../core/vault-presence.ts";import type { OutputSchema } from "./output-contract.ts";@@ -65,28 +71,130 @@ export function unresolvedField(err: Error): UnresolvedField {export const VAULT_PATH_OUTPUT_SCHEMA: OutputSchema = Object.freeze({});/**- * The two fields this producer reads, and nothing else.+ * The one field the path POLICY reads: which config decides it.** Declared structurally rather than as {@link ServerContext} so the* OpenClaw plugin - a second runtime with its own context shape, and* three emissions of this same field - can reach it. A contract honoured* on one runtime and not the other is the defect this module exists to* close, one surface over.+ *+ * Split from {@link VaultPathSource} because the policy readers below+ * take a path (or a sentence) as their subject and never look at+ * `ctx.vault`: asking them for a vault they ignore reads as if the vault+ * were the thing being rendered.*/-export interface VaultPathSource {- readonly vault: string;+export interface HostPathPolicySource {readonly configPath?: string | null;}+/** The policy source plus the vault {@link vaultPathField} renders. */+export interface VaultPathSource extends HostPathPolicySource {+ readonly vault: string;+}++/**+ * The contract above, applied to any absolute host path.+ *+ * `vaultStoreReference` never required the path to be the vault - it+ * keys an HMAC over whatever it is handed - and the redaction contract+ * is about the response landing in model context, which is equally true+ * of a linked project's directory. `second_brain_wiring` renders both+ * sides of a project link through this, so there is one path policy on+ * this surface rather than a second one written for the second field.+ */+/**+ * What the degraded field says instead of {@link ConfigReadError}'s own+ * message.+ *+ * That message names the config file twice - once in the condition and+ * once in the `chmod` remedy - and it is right to, on the four channels+ * it was written for: a CLI refusal, an MCP error envelope, a hook's+ * stderr, and the two read-only diagnostics whose whole job is to name+ * the broken file. This is none of those. It is the field forty-five+ * tools emit into model context precisely so that an absolute host path+ * does not travel there, and the config file lives under the operator's+ * home. Reporting the condition by naming that path would reintroduce,+ * in the degraded branch, the leak the resolved branch exists to+ * prevent.+ *+ * Nothing is lost to the operator: `second_brain_status` and+ * `vault_health` still name the file, from their own fields, under the+ * contract that says those fields may.+ */+export const CONFIG_UNREADABLE_REASON =+ "the device-local config could not be read, so this reference cannot be " ++ "resolved; call second_brain_status for the file and the remedy";++export function hostPathReference(+ path: string,+ source: HostPathPolicySource,+): string | UnresolvedField {+ const configPath = source.configPath ?? undefined;+ try {+ return resolveExposeHostPaths(configPath) ? path : vaultStoreReference(path, configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return { error: CONFIG_UNREADABLE_REASON };+ throw err;+ }+}+/** The contract above, as the one value every emitting site returns. */export function vaultPathField(ctx: VaultPathSource): string | UnresolvedField {- const configPath = ctx.configPath ?? undefined;+ return hostPathReference(ctx.vault, ctx);+}++/** How a folded path names the host home. */+const HOME_REFERENCE = "~";++/**+ * The shortest home this function will fold.+ *+ * A home of `/` (or the empty string an unresolved lookup leaves) is a+ * prefix of every absolute path on the machine, so folding it would+ * rewrite unrelated paths into nonsense rather than redact anything.+ */+const SHORTEST_FOLDABLE_HOME = 2;++/**+ * What may NOT follow the home for the match to be the home.+ *+ * A plain prefix replacement run under a home named `dev` would clip a+ * sibling named `developer` in the same sentence into `~eloper`: a+ * mangled path is worse than either the raw one or the folded one,+ * because it names a file that does not exist. The home matches only+ * where the next character cannot continue a directory name - a+ * separator, punctuation, whitespace, or the end of the sentence.+ */+const NAME_CHARACTER = "[A-Za-z0-9._-]";++/**+ * Free-form adapter prose with the host home folded to `~`.+ *+ * `verify()` composes its `details` and `fix_hint` sentences from+ * `InstallEnv.home`, so a drifted install names an absolute path under+ * the operator's account - in the same MCP payload whose `vault_path`+ * was deliberately reduced to an opaque reference. {@link+ * hostPathReference} does not apply: a store reference keys the VAULT,+ * and hashing a third party's `~/.grok/hooks/...` would name nothing the+ * reader can act on.+ *+ * So the home PREFIX is folded instead. The file stays identifiable, the+ * account name does not travel, and the rewrite is one exact+ * substitution of a string this run resolved - never a search for+ * path-shaped text inside a sentence.+ *+ * Fails closed: an unreadable config folds, because printing raw host+ * paths is the branch an operator opts into.+ */+export function foldHostHome(text: string, home: string, source: HostPathPolicySource): string {+ if (home.length < SHORTEST_FOLDABLE_HOME) return text;try {- return resolveExposeHostPaths(configPath)- ? ctx.vault- : vaultStoreReference(ctx.vault, configPath);+ if (resolveExposeHostPaths(source.configPath ?? undefined)) return text;} catch (err) {- if (err instanceof ConfigReadError) return unresolvedField(err);- throw err;+ if (!(err instanceof ConfigReadError)) throw err;+ // Fall through and fold: an unreadable config is not consent to+ // print host paths, and the branch that prints them is opt-in.}+ return text.replace(new RegExp(`${escapeRegex(home)}(?!${NAME_CHARACTER})`, "g"), HOME_REFERENCE);}diff --git a/src/mcp/wiring-tools.ts b/src/mcp/wiring-tools.tsnew file mode 100644index 00000000..ed3fa3c1--- /dev/null+++ b/src/mcp/wiring-tools.ts@@ -0,0 +1,307 @@+/**+ * `second_brain_wiring` - what this install is wired into.+ *+ * Two questions of one class, and both were answerable only from a+ * shell. `linkedProjectsStatus` reports every registered project link+ * with its pointer state and had one consumer, `o2b brain project+ * status`; the per-adapter `verify()` aggregate behind `o2b install+ * --check` reports whether the hosts this install wrote registrations+ * into can still be reached, and had none outside the CLI. An agent on+ * the MCP surface could not ask either.+ *+ * Nothing here computes health. Both views are a seam onto a reader+ * that already exists, which is why they ship as one tool: a second+ * implementation of connector health would be a second answer to a+ * question that already has one.+ *+ * ## Why one tool with a required `view`+ *+ * The house idiom for a consolidated read is a `view` parameter -+ * `brain_brief`, `brain_analytics` and `schema_inspect` all take one,+ * and `brain/landscape-tools.ts` names the reason: schema tokens are+ * paid by every client on every request. There is deliberately no+ * aggregate member. Every payload stays bounded, and an operator who+ * wants the hosts view does not pay for two host probes to read a+ * project registry.+ *+ * ## Paths+ *+ * The project registry is keyed on absolute host paths and an MCP+ * response lands in model context, so every path-valued FIELD here goes+ * through {@link hostPathReference} - the same `expose_host_paths`+ * contract `vault_path` obeys, generalised to a second path rather than+ * reimplemented for one.+ *+ * The hosts view also carries free-form adapter prose, and `verify()`+ * composes those sentences from `InstallEnv.home`. A store reference+ * cannot render them - it keys the vault, not a third party's config+ * file - so they go through {@link foldHostHome}, which folds the one+ * home prefix this run resolved. The two mechanisms answer the same+ * question, `expose_host_paths`, off the same config.+ */++import {+ linkedProjectsStatus,+ type LinkedProjectStatus,+} from "../core/brain/portability/pointer.ts";+import { defaultConfigPath } from "../core/config.ts";+import { VAULT_NOT_CONFIGURED_REASON, buildInstallEnv } from "../core/install/env.ts";+import { defaultRegistry } from "../core/install/registry.ts";+// The canonical adapter set registers itself into `defaultRegistry` at+// module-load time through this barrel, exactly as the CLI verb does.+import "../core/install/adapters/all.ts";+import type { VerifyResult } from "../core/install/types.ts";+import { dispatchByView } from "./brain/shared.ts";+import { INVALID_PARAMS, MCPError } from "./protocol.ts";+import type { ServerContext, ToolDefinition } from "./tool-contract.ts";+import {+ VAULT_PATH_OUTPUT_SCHEMA,+ type HostPathPolicySource,+ foldHostHome,+ hostPathReference,+ vaultPathField,+} from "./vault-path-field.ts";++/** The tool name, shared with the tests and the registry guard. */+export const WIRING_TOOL_NAME = "second_brain_wiring";++/** The view this tool answers about linked projects. */+const PROJECTS_VIEW = "projects";++/** The view this tool answers about the hosts this install wrote into. */+const HOSTS_VIEW = "hosts";++/** Membership list of the accepted `view` values, in schema order. */+export const WIRING_VIEWS: ReadonlyArray<string> = Object.freeze([PROJECTS_VIEW, HOSTS_VIEW]);++/**+ * Most project links `view=projects` carries inline.+ *+ * The hosts view is bounded by construction - one entry per adapter in+ * a registry this build closes - and the projects view is not. Nothing+ * caps `projects.json`: every `o2b brain project link` appends to it,+ * so the registry grows with the operator's habits and the serialized+ * result grows with it. That is the one thing this tool's+ * preview-budget exemption claims cannot happen, and the claim has to+ * be made true by the payload rather than by hope.+ *+ * Capped rather than budgeted because the budget is per TOOL, not per+ * view: the shared `MCP_PREVIEW_BUDGET` is ~2000 characters and the+ * hosts view already renders around 1700 with nothing installed, so a+ * tool-wide budget would park an operator's connector diagnostic in an+ * artifact on almost every call. The cap here bounds the view that+ * needs bounding and leaves the other one alone.+ *+ * Matches `PAGE_LINT_MAX_FINDINGS` at twenty-five, and the list+ * declares its own truncation the same way that report does, so a+ * capped answer can never be read as a complete one.+ */+export const WIRING_MAX_PROJECTS = 25;++/** One registered project link, rendered under the path policy. */+function projectEntry(status: LinkedProjectStatus, ctx: ServerContext): Record<string, unknown> {+ return {+ project_ref: hostPathReference(status.path, ctx),+ vault_ref: hostPathReference(status.vault, ctx),+ pointer: status.pointer,+ vault_exists: status.vaultExists,+ };+}++/**+ * Every project registered against THIS install's config.+ *+ * A server started without a config path falls back to the machine+ * default, exactly as {@link viewHosts} does and exactly as the CLI verb+ * this view mirrors (`o2b brain project status`) always has. It used to+ * answer the empty list instead, which reported "nothing is linked" for+ * a box whose registry was full - and disagreed with the sibling view in+ * the same payload family about what an unnamed config means.+ *+ * The registry itself is read tolerantly (`listLinkedProjects` passes+ * `tolerateParseError`), so a damaged `projects.json` reads as no links+ * on this surface as it does on the CLI. That is core's contract, not+ * this view's: a tool that refused where the verb tolerates would be the+ * second answer this file exists to avoid.+ *+ * The list is capped at {@link WIRING_MAX_PROJECTS} and carries `total`,+ * `returned` and `truncated` beside it, so what an unbounded registry+ * costs this payload is bounded and a capped answer cannot be read as a+ * complete one. The CLI verb is uncapped and stays so: it renders to a+ * terminal, not into model context.+ */+function viewProjects(ctx: ServerContext): Record<string, unknown> {+ const links = linkedProjectsStatus(ctx.configPath ?? defaultConfigPath());+ const returned = links.slice(0, WIRING_MAX_PROJECTS);+ return {+ vault_path: vaultPathField(ctx),+ view: PROJECTS_VIEW,+ projects: returned.map((status) => projectEntry(status, ctx)),+ total: links.length,+ returned: returned.length,+ truncated: links.length > returned.length,+ };+}++/**+ * One adapter's verify answer, as the payload carries it.+ *+ * `details` and `fix_hint` are the adapter's own sentences and name the+ * files it looked at, so they are folded against the home this run+ * verified rather than copied through; see {@link foldHostHome}.+ *+ * Exported for the test that drives a named probe SKIP through it. That+ * branch is only reachable from an installed target verified against a+ * specific host home, and `os.homedir()` in this runtime does not follow+ * a later `process.env.HOME`, so an in-process test cannot redirect the+ * home {@link viewHosts} resolves. It builds the `InstallEnv` by hand -+ * exactly as the adapter suites do - and asserts this mapping over the+ * real `verify()` answer instead of over a synthetic one.+ */+export function hostWiringEntry(+ result: VerifyResult,+ home: string,+ policy: HostPathPolicySource,+): Record<string, unknown> {+ return {+ target: result.target,+ status: result.status,+ details: result.details.map((line) => foldHostHome(line, home, policy)),+ fix_hint: result.fix_hint === null ? null : foldHostHome(result.fix_hint, home, policy),+ };+}++/**+ * Every registered install target, verified.+ *+ * The same `verify()` call per adapter that `o2b install --check`+ * makes, over the same registry and the same `InstallEnv`. Reusing it+ * means one implementation of connector health rather than a second one+ * that can come to disagree with the first.+ *+ * The vault is refused rather than defaulted. `verify()` reads the+ * per-vault sidecar manifest, so an unset vault makes every adapter+ * report `not-installed` off a bogus path - ten runtimes reported+ * absent when the real condition is that nothing was configured. The+ * refusal carries the sentence `runCheck` gives, from the one constant+ * both surfaces read.+ */+function viewHosts(ctx: ServerContext): Record<string, unknown> {+ if (ctx.vault.trim() === "") throw new MCPError(INVALID_PARAMS, VAULT_NOT_CONFIGURED_REASON);+ const env = buildInstallEnv({+ vault: ctx.vault,+ configPath: ctx.configPath ?? defaultConfigPath(),+ });+ return {+ vault_path: vaultPathField(ctx),+ view: HOSTS_VIEW,+ hosts: defaultRegistry+ .list()+ .map((adapter) => hostWiringEntry(adapter.verify(env), env.home, ctx)),+ };+}++const WIRING_VIEW_HANDLERS: Readonly<+ Record<string, (ctx: ServerContext) => Record<string, unknown>>+> = Object.freeze({+ [PROJECTS_VIEW]: viewProjects,+ [HOSTS_VIEW]: viewHosts,+});++function toolWiring(ctx: ServerContext, args: Record<string, unknown>): unknown {+ return dispatchByView(WIRING_VIEW_HANDLERS, ctx, args);+}++export const WIRING_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: WIRING_TOOL_NAME,+ // Under the 300-character registry cap: the path policy and the+ // per-view field tables are long-form guidance, and `registry-guard.ts`+ // states that those belong in docs/mcp.md rather than in a schema every+ // client pays for on every request.+ description:+ "Report what this Open Second Brain install is wired into. view=projects lists each registered project link with its pointer state and whether its vault still exists; view=hosts verifies every install target as `o2b install --check` does, and may ask host CLIs under a bounded wait. Read-only.",+ inputSchema: {+ type: "object",+ properties: {+ view: {+ type: "string",+ enum: [...WIRING_VIEWS],+ description:+ "Which wiring to report. Required; there is no aggregate view, so a projects read never pays for a host probe.",+ },+ },+ required: ["view"],+ additionalProperties: false,+ },+ outputSchema: {+ type: "object",+ required: ["vault_path", "view"],+ properties: {+ vault_path: VAULT_PATH_OUTPUT_SCHEMA,+ view: { type: "string", description: "The view this payload answers." },+ total: {+ type: "number",+ description: "view=projects: registered project links found, the cap included.",+ },+ returned: {+ type: "number",+ description: "view=projects: entries actually carried in `projects`.",+ },+ truncated: {+ type: "boolean",+ description: "view=projects: true iff `total` exceeds `returned`.",+ },+ projects: {+ type: "array",+ description:+ "view=projects: one entry per registered project link, capped; " ++ "read `total`, `returned` and `truncated` beside it.",+ items: {+ type: "object",+ required: ["project_ref", "vault_ref", "pointer", "vault_exists"],+ properties: {+ project_ref: VAULT_PATH_OUTPUT_SCHEMA,+ vault_ref: VAULT_PATH_OUTPUT_SCHEMA,+ pointer: {+ type: "string",+ description: "Pointer-file state: ok, missing, malformed, or mismatch.",+ },+ vault_exists: {+ type: "boolean",+ description: "Whether the vault directory the link names is still present.",+ },+ },+ },+ },+ hosts: {+ type: "array",+ description: "view=hosts: one entry per registered install target.",+ items: {+ type: "object",+ required: ["target", "status", "details", "fix_hint"],+ properties: {+ target: { type: "string", description: "The install target id." },+ status: {+ type: "string",+ description: "Verify status: ok, drift, not-installed, or mcp-unreachable.",+ },+ details: {+ type: "array",+ description:+ "What the adapter observed, one line per finding. Host paths in these " ++ "sentences are folded to `~` unless `expose_host_paths` is set.",+ items: { type: "string" },+ },+ // Nullable, and the descriptor language has no union form;+ // see VAULT_PATH_OUTPUT_SCHEMA for why empty is the honest+ // shape. Folded against the host home exactly as `details` is.+ fix_hint: {},+ },+ },+ },+ },+ },+ handler: toolWiring,+ },+]);diff --git a/tests/cli/version.test.ts b/tests/cli/version.test.tsnew file mode 100644index 00000000..331c3990--- /dev/null+++ b/tests/cli/version.test.ts@@ -0,0 +1,107 @@+/**+ * `o2b version` and the root `--version` flag.+ *+ * The MCP surface has always answered this question - the handshake+ * carries `serverInfo.version` - and the CLI never did. An operator with+ * a shell and no MCP client had no way to ask an install which version+ * it is, which is the first question every bug report starts with.+ *+ * Three properties are pinned here, and the third is the one worth+ * naming: the flag and the verb render the SAME line. Two spellings of+ * one question that answer differently are worse than one spelling,+ * because the difference is invisible until someone pastes the wrong+ * one into a report.+ */++import { describe, expect, test } from "bun:test";++import { OPEN_SECOND_BRAIN_VERSION } from "../../src/core/version.ts";+import { CLI_COMMAND_MANIFEST, allFlagNames } from "../../src/cli/command-manifest.ts";+import { runCli } from "../helpers/run-cli.ts";++/** The verb under test, and the root flag that is its synonym. */+const VERSION_COMMAND = "version";+const VERSION_FLAG = "--version";++/** Exit code the CLI reserves for a usage error. */+const USAGE_EXIT = 2;++/** Both spellings refuse `argv` identically; see the test that calls it. */+async function expectSameRefusal(argv: ReadonlyArray<string>): Promise<void> {+ const viaFlag = await runCli([VERSION_FLAG, ...argv]);+ const viaVerb = await runCli([VERSION_COMMAND, ...argv]);+ expect(viaFlag.returncode).toBe(USAGE_EXIT);+ expect(viaFlag.returncode).toBe(viaVerb.returncode);+ expect(viaFlag.stderr).toBe(viaVerb.stderr);+ expect(viaFlag.stdout).toBe("");+}++describe("o2b version", () => {+ test("prints the version constant and exits 0", async () => {+ const result = await runCli([VERSION_COMMAND]);+ expect(result.returncode).toBe(0);+ expect(result.stdout).toBe(`${OPEN_SECOND_BRAIN_VERSION}\n`);+ expect(result.stderr).toBe("");+ });++ test("--json prints a parseable object carrying the same version", async () => {+ const result = await runCli([VERSION_COMMAND, "--json"]);+ expect(result.returncode).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({ version: OPEN_SECOND_BRAIN_VERSION });+ });++ test("the root flag renders the same line as the verb", async () => {+ const viaFlag = await runCli([VERSION_FLAG]);+ const viaVerb = await runCli([VERSION_COMMAND]);+ expect(viaFlag.returncode).toBe(0);+ expect(viaFlag.stdout).toBe(viaVerb.stdout);+ });++ test("the root flag honours --json too", async () => {+ const result = await runCli([VERSION_FLAG, "--json"]);+ expect(result.returncode).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({ version: OPEN_SECOND_BRAIN_VERSION });+ });++ test("an unknown argument is a usage error, not silence", async () => {+ const result = await runCli([VERSION_COMMAND, "latest"]);+ expect(result.returncode).toBe(USAGE_EXIT);+ expect(result.stderr).toContain("latest");+ expect(result.stdout).toBe("");+ });++ test("an unknown flag is a usage error", async () => {+ const result = await runCli([VERSION_COMMAND, "--short"]);+ expect(result.returncode).toBe(USAGE_EXIT);+ expect(result.stderr).toContain("--short");+ });++ test("the two spellings answer a bad argument identically, not just a good one", async () => {+ // The property in the docblock is about the SAME line, and a usage+ // error is a line. Handling the root flag in an arm of its own put+ // it outside the dispatcher's `CliError` handler, so the flag threw+ // a stack trace and exited 1 where the verb printed a usage error+ // and exited 2 - the divergence the synonym exists to prevent,+ // visible only to whoever typed the wrong one.+ // Sequential by construction, and not a loop: `runCli` refuses a+ // concurrent in-process run by name, because it swaps the+ // environment, the working directory and both streams.+ await expectSameRefusal(["latest"]);+ await expectSameRefusal(["--short"]);+ });+});++describe("the manifest models both spellings", () => {+ test("a top-level version command", () => {+ const entry = CLI_COMMAND_MANIFEST.commands.find((c) => c.name === VERSION_COMMAND);+ expect(entry).toBeDefined();+ expect(entry!.summary.trim().length).toBeGreaterThan(0);+ });++ test("a root --version flag, so completions offer it", () => {+ const root = CLI_COMMAND_MANIFEST.flags.find((f) => f.name === VERSION_COMMAND);+ expect(root).toBeDefined();+ expect(root!.type).toBe("boolean");+ expect(allFlagNames()).toContain(VERSION_COMMAND);+ });+});diff --git a/tests/core/architecture/vault-path-census.test.ts b/tests/core/architecture/vault-path-census.test.tsindex 0584a936..fdf70fde 100644--- a/tests/core/architecture/vault-path-census.test.ts+++ b/tests/core/architecture/vault-path-census.test.ts@@ -109,8 +109,24 @@ const VAULT_PATH_SCHEMA_DESCRIPTOR = "VAULT_PATH_OUTPUT_SCHEMA";* changed count is a fact about this release that someone states, in the* same commit, rather than a drift nobody sees. Re-measure it only after* deciding the move is intended.+ *+ * 44 to 46: `second_brain_wiring` joined the surface and emits the field+ * once per view, through the producer.+ *+ * That tool is also where this census's reach ends, so the limit is+ * stated rather than left to be discovered. The population is keyed on+ * the FIELD NAME `vault_path`, and the tool carries three other+ * path-bearing members: `project_ref` and `vault_ref`, which render+ * through `hostPathReference` (the generalisation of the same+ * producer), and the adapter prose in `details` / `fix_hint`, where the+ * path arrives inside a sentence no store reference can render and+ * `foldHostHome` folds the home prefix instead. Neither class is+ * visible here. What guards them is `tests/mcp/wiring-tools.test.ts`,+ * which asserts over the SERIALISED payload of both views - and a+ * future view that adds a fourth path-bearing member under a fourth+ * name needs its own assertion there, because this count will not move.*/-const EMITTING_SITES = 44;+const EMITTING_SITES = 46;/** One `vault_path:` property found in the source. */interface FieldSite {diff --git a/tests/core/brain/dream-progress.test.ts b/tests/core/brain/dream-progress.test.tsindex 436d54df..055ad605 100644--- a/tests/core/brain/dream-progress.test.ts+++ b/tests/core/brain/dream-progress.test.ts@@ -152,6 +152,21 @@ describe("dream progress", () => {// member of that entry (run_id, reason, channel) still compares.const ARCHIVE_SIZE_FIELD = /(size_bytes"?:\s*"?)\d+/g;const ARCHIVE_SIZE_PLACEHOLDER = "$1<archive-size>";+ // The chain hashes carry that size with them, so normalising the+ // field alone leaves the nondeterminism in the two places the+ // field was taken out of. `h` is computed over the payload+ // INCLUDING the real `size_bytes`, and every later line in the day+ // log chains off it through `prev`, so one straddled second+ // re-keys the whole file - which is this test failing on a loaded+ // CI runner and passing on every developer box.+ //+ // The chain is not what this test is for, and it is not left+ // unguarded: the log-integrity suites verify it end to end. What+ // this one asserts is that attaching an observer changes nothing+ // the pass AUTHORED, and what the pass authored is the payloads.+ // `prev: null` is a literal, not a digest, and stays.+ const CHAIN_HASH_FIELD = /("(?:h|prev)":")[0-9a-f]{64}"/g;+ const CHAIN_HASH_PLACEHOLDER = '$1<chain-hash>"';const NORMALISED_PREFIX = "Brain/log/";const authored = (root: string): Map<string, string> => {const kept = new Map<string, string>();@@ -162,10 +177,9 @@ describe("dream progress", () => {kept.set(path,path.startsWith(NORMALISED_PREFIX)- ? readFileSync(join(root, path), "utf8").replaceAll(- ARCHIVE_SIZE_FIELD,- ARCHIVE_SIZE_PLACEHOLDER,- )+ ? readFileSync(join(root, path), "utf8")+ .replaceAll(ARCHIVE_SIZE_FIELD, ARCHIVE_SIZE_PLACEHOLDER)+ .replaceAll(CHAIN_HASH_FIELD, CHAIN_HASH_PLACEHOLDER): digest,);}diff --git a/tests/core/brain/notes/write-record.test.ts b/tests/core/brain/notes/write-record.test.tsindex b2a37655..08e102eb 100644--- a/tests/core/brain/notes/write-record.test.ts+++ b/tests/core/brain/notes/write-record.test.ts@@ -15,6 +15,7 @@ import {mkdtempSync,readFileSync,rmSync,+ utimesSync,writeFileSync,} from "node:fs";import { tmpdir } from "node:os";@@ -102,6 +103,21 @@ describe("storeBeforeImage", () => {storeBeforeImage(vault, "two");expect(pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed).toHaveLength(2);});++ test("an image stamped in the future is zero days old, not minus one", () => {+ // `nowMs` is sampled once before the sweep, and mtime granularity on+ // a synced or networked filesystem can round a write made just+ // before it up past it. Unfloored, `msToWholeDays` turns that -1ms+ // into -1 whole day, which is below every window including zero, so+ // the image is kept forever. This is the condition that flaked the+ // `olderThanDays: 0` cases in CI on one image of two, staged here+ // deterministically rather than waited for.+ storeBeforeImage(vault, "one");+ const ahead = storeBeforeImage(vault, "two");+ const future = Date.now() / 1000 + 0.05;+ utimesSync(ahead.path, future, future);+ expect(pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed).toHaveLength(2);+ });});describe("recordNoteWrite", () => {diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.tsindex ba239b03..d0307f69 100644--- a/tests/core/install/tool-ceiling.test.ts+++ b/tests/core/install/tool-ceiling.test.ts@@ -340,7 +340,7 @@ describe("the capability report states the ceiling it runs under", () => {test("the advertised count is the one a host lists, not the registered one", () => {const evaluated = report("cursor");- expect(evaluated.available_tool_count).toBe(114);+ expect(evaluated.available_tool_count).toBe(115);expect(evaluated.advertised_tool_count).toBe(7);});});diff --git a/tests/core/version.test.ts b/tests/core/version.test.tsnew file mode 100644index 00000000..65c8e23e--- /dev/null+++ b/tests/core/version.test.ts@@ -0,0 +1,121 @@+/**+ * The single source of the Open Second Brain version, and the census+ * that keeps it single.+ *+ * ## The defect+ *+ * `CLAUDE.md` states that `package.json` `version` is the one source of+ * truth, and `scripts/sync-version.ts` enforces that for the manifests+ * it mirrors into. Inside `src/` nothing enforced it: three modules+ * imported `package.json` and read `version` off it independently -+ * `src/cli/brain/verbs/continuity.ts` as `CLI_VERSION`,+ * `src/mcp/protocol.ts` as `SERVER_VERSION`, and+ * `src/core/install/opencode-plugin-asset.ts` inline in the plugin+ * header. Three copies of one fact do not disagree today, and that is+ * the whole risk: they cannot be seen to disagree either, because+ * nothing names them as copies. Adding a fourth read to serve+ * `o2b version` would have written the defect into the change meant to+ * answer the question.+ *+ * ## The population, defined structurally+ *+ * Every `.ts` module under {@link SRC_ROOT} is read, lexed by the shared+ * {@link lexCode} view (comments blanked, literal DELIMITERS kept so an+ * import specifier is still recognisable), and every static `import`+ * whose specifier ends in `package.json` is collected. The disposition+ * is an equality, not a floor: exactly one module may hold that import,+ * and it is {@link VERSION_MODULE}.+ *+ * ## What this census cannot see, stated rather than implied+ *+ * - A dynamic `await import("../package.json")` is not a static import+ * declaration and is invisible here. Nothing in the tree does that,+ * and the equality below would not notice if something started.+ * - A module that reads `package.json` off the filesystem at runtime+ * is deliberately out of population: `src/core/doctor.ts` and+ * `src/core/brain/architect/scan.ts` both do, and both are reading+ * SOME project's manifest discovered at a runtime root, not this+ * install's own version. Folding them in would make the census+ * answer a different question than the one it is named for.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync, readdirSync } from "node:fs";+import { join, relative, resolve } from "node:path";++import { lexCode } from "../helpers/source-lexer.ts";+import { OPEN_SECOND_BRAIN_VERSION } from "../../src/core/version.ts";+import packageJson from "../../package.json" with { type: "json" };++/** The shipped source tree this census scans. */+const SRC_ROOT = resolve(import.meta.dir, "..", "..", "src");++/** Repository root, for reporting paths a reader can open. */+const REPO_ROOT = resolve(import.meta.dir, "..", "..");++/** The one module permitted to import the manifest. */+const VERSION_MODULE = "src/core/version.ts";++/** The manifest specifier suffix a version read comes through. */+const MANIFEST_SPECIFIER = "package.json";++/** Every `.ts` module under `dir`, recursively, in stable order. */+function modules(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...modules(path));+ else if (entry.name.endsWith(".ts")) out.push(path);+ }+ return out;+}++/** Static import declarations in `text` whose specifier is the manifest. */+function manifestImports(text: string): number {+ const code = lexCode(text);+ const probe = /\bimport\b[^;]*?\bfrom\s*(["'])([^"']*)\1/g;+ let count = 0;+ for (const match of code.matchAll(probe)) {+ // The code view blanks literal CONTENTS, so read the specifier back+ // out of the original text at the same offset - the views share+ // every offset by construction.+ const at = match.index + match[0].length - match[2]!.length - 1;+ const specifier = text.slice(at, at + match[2]!.length);+ if (specifier.endsWith(MANIFEST_SPECIFIER)) count++;+ }+ return count;+}++describe("the Open Second Brain version constant", () => {+ test("carries the version package.json declares", () => {+ expect(OPEN_SECOND_BRAIN_VERSION).toBe(packageJson.version);+ });++ test("is a non-empty dotted version, not an empty string a bad read would leave", () => {+ expect(OPEN_SECOND_BRAIN_VERSION).toMatch(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/);+ });+});++describe("manifest import census", () => {+ test("exactly one module under src/ imports package.json", () => {+ const holders: string[] = [];+ for (const file of modules(SRC_ROOT)) {+ const count = manifestImports(readFileSync(file, "utf8"));+ for (let i = 0; i < count; i++) holders.push(relative(REPO_ROOT, file));+ }+ expect(holders).toEqual([VERSION_MODULE]);+ });++ test("the scan sees an import, and only where it is really one", () => {+ // Positive control first: a census that cannot fail proves nothing.+ expect(manifestImports('import pkg from "../package.json";\n')).toBe(1);+ expect(manifestImports('import pkg from "../package.json" with { type: "json" };\n')).toBe(1);+ // A different specifier is not this import.+ expect(manifestImports('import { x } from "./config.ts";\n')).toBe(0);+ // The specifier quoted in a comment or a string is not an import.+ expect(manifestImports('// import pkg from "../package.json"\n')).toBe(0);+ expect(manifestImports('const doc = `import pkg from "../package.json"`;\n')).toBe(0);+ });+});diff --git a/tests/fixtures/instruction-bodies/catalog.txt b/tests/fixtures/instruction-bodies/catalog.txtnew file mode 100644index 00000000..88cc35c5--- /dev/null+++ b/tests/fixtures/instruction-bodies/catalog.txt@@ -0,0 +1,18 @@+Open Second Brain — two-pass catalog MCP surface.++This server advertises a compact first-pass tool set: the capability+diagnostic, the five always-loaded Brain writers/readers, and+tool_hydrate. A tool the catalog surface alone omits from+tools/list stays CALLABLE via tools/call — the omission keeps schema+tokens out of your prompt until needed. A tool a runtime capability+window withholds is not callable at all.++Second pass: call tool_hydrate with no arguments to get the compact+catalog (name, one-line description, group) of every tool in this+process, then call tool_hydrate with names: [...] to fetch the full+input/output schemas for the tools you actually need. After hydration,+invoke those tools directly by name through tools/call — no further+registration step exists or is needed.++Do not invent substitute workflows for a capability you cannot see:+hydrate the catalog first; the tool is almost certainly already here.diff --git a/tests/fixtures/instruction-bodies/full.txt b/tests/fixtures/instruction-bodies/full.txtnew file mode 100644index 00000000..457c57f5--- /dev/null+++ b/tests/fixtures/instruction-bodies/full.txt@@ -0,0 +1,5 @@+Memory contract: call brain_feedback once per taste signal the user expresses; brain_apply_evidence right after producing a durable artifact a preference in `Brain/preferences/` scopes to (result: applied | violated | outdated); brain_note for narrative milestones that fit neither; brain_pinned_context for current-task facts that must survive context rotation. brain_context bootstraps a session when the host injects no active.md hook. Skip Brain calls for casual chat, exploration, and trivial edits - a misrecorded signal is worse than a missed one.++Consolidated read views: brain_brief (view: morning | daily | weekly | monthly | operator | digest), brain_analytics (view: timeline | attention_flows | belief_evolution | concept_synthesis), schema_inspect (view: graph | lint | stats | orphans | explain_type | active_pack | packs). The per-view predecessor names still resolve via tools/call as deprecated aliases.++Preview budget: a large result may arrive as a JSON envelope with `preview_truncated: true` and an `artifact_id`; fetch the full payload with brain_artifact_get only when the preview is not enough.diff --git a/tests/fixtures/instruction-bodies/writer.txt b/tests/fixtures/instruction-bodies/writer.txtnew file mode 100644index 00000000..360d11f1--- /dev/null+++ b/tests/fixtures/instruction-bodies/writer.txt@@ -0,0 +1,28 @@+Open Second Brain — always-loaded MCP surface.++Five tools live here (four writers + one reader; the server's name is+preserved for backward compatibility with existing client configs):+ - brain_feedback — record one new taste signal the user just expressed.+ - brain_apply_evidence — record applied | violated | outdated against an+ active preference for an artifact this turn produced.+ - brain_note — record one narrative milestone (release shipped,+ PR merged, fact discovered) that fits neither+ category.+ - brain_pinned_context — read/write/append/clear Brain/pinned.md for+ current-task facts that should survive context+ rotation without becoming permanent preferences.+ - brain_context — pull the current Brain/active.md body plus+ pinned context and active-preference counts.+ Read-only. Use at session+ start when the host runtime lacks a SessionStart+ hook (Cursor, Aider, raw Claude API). Runtimes that+ already inject active.md via a hook can skip this.++The remaining Brain surface lives on the sibling "open-second-brain"+MCP server (deferred), including additional read-only, analytics,+maintenance, and workflow tools beyond the always-loaded writer set.+Use ToolSearch to discover and reach it.++Prefer the writer-server copies of brain_feedback / brain_apply_evidence /+brain_note / brain_pinned_context over any duplicate exposed by the full server — both call the same+handler, but the writer copy is always available without ToolSearch.diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.tsindex e8e4820a..45f1c940 100644--- a/tests/helpers/tool-probe-catalogue.ts+++ b/tests/helpers/tool-probe-catalogue.ts@@ -222,7 +222,8 @@ export const REASON = Object.freeze({"owner-taggable page, so `pageOwner` has no subject to read.",catalog:"a catalog of this server's own surface - the tool table, the skills manifest, the " +- "preset list - answered without opening a vault page, so no page's owner is reachable.",+ "preset list, the install's own wiring - answered without opening a vault page, so no " ++ "page's owner is reachable.",writerEcho:"a writer: the response echoes the artifact this very call created, planned or refused, " +"so the only ownership it can name is the one the caller supplied.",@@ -288,8 +289,8 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS* `docs/mcp.md` and the release notes. Equalities, not floors - see the* test that reads them.*/-export const PROBE_ENTRY_COUNT = 100;-export const PROBE_RECIPE_COUNT = 229;+export const PROBE_ENTRY_COUNT = 101;+export const PROBE_RECIPE_COUNT = 231;export const PROBE_TWO_SIDED_COUNT = 32;/**@@ -1068,6 +1069,13 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [},{ name: "second_brain_capabilities", calls: one({}, REASON.catalog) },{ name: "second_brain_status", calls: one({}, REASON.aggregateOnly) },+ {+ name: "second_brain_wiring",+ calls: [+ { args: { view: "projects" }, reason: REASON.catalog },+ { args: { view: "hosts" }, reason: REASON.catalog },+ ],+ },{ name: "skills_attach", calls: one({ query: QUERY }, REASON.catalog) },{ name: "tool_hydrate", calls: one({}, REASON.catalog) },{ name: "vault_health", calls: one({}, REASON.aggregateOnly) },diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.tsindex 40c99bb2..c6f50b20 100644--- a/tests/mcp/agent-scope-matrix.test.ts+++ b/tests/mcp/agent-scope-matrix.test.ts@@ -210,8 +210,10 @@ test("the matrix classifies every tool exactly once", () => {expect(classified.toSorted()).toEqual(actual);});-test("the tool count is unchanged: an argument was added, never a tool", () => {- expect(TOOLS.length).toBe(114);+test("the tool count is the measured surface, not a remembered one", () => {+ // 114 to 115: `second_brain_wiring` joined the surface in the release+ // that made the install's own wiring readable over MCP.+ expect(TOOLS.length).toBe(115);});test("every argument-scoped surface declares agent_scope in its input schema", () => {diff --git a/tests/mcp/config-read-failure-server.test.ts b/tests/mcp/config-read-failure-server.test.tsindex 729ddede..e25a3e68 100644--- a/tests/mcp/config-read-failure-server.test.ts+++ b/tests/mcp/config-read-failure-server.test.ts@@ -28,6 +28,7 @@ import { join } from "node:path";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";+import { CONFIG_UNREADABLE_REASON } from "../../src/mcp/vault-path-field.ts";const VALID_CONFIG = `vault: "/srv/example-vault"\nagent_name: "vps-agent"\n`;@@ -157,11 +158,14 @@ describe("the read-only diagnostics answer through the request path", () => {expect(payload!["ok"]).toBe(false);// The same degraded field the handler-level test pins, now actually// reachable: an unresolvable store reference reports the reason and- // never falls back to the raw host path.- expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toContain(- configPath,+ // never falls back to the raw host path. The reason is path-safe -+ // the config file is named by `config_writeable` above, which is a+ // field that may name it; this one is not.+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(+ CONFIG_UNREADABLE_REASON,);expect(JSON.stringify(payload!["vault_path"])).not.toContain(vault);+ expect(JSON.stringify(payload!["vault_path"])).not.toContain(configPath);});/**@@ -177,8 +181,8 @@ describe("the read-only diagnostics answer through the request path", () => {const { payload, toolError, rpcError } = await callThroughServer("brain_mcp_landscape");expect(rpcError).toBeUndefined();expect(toolError).toBeUndefined();- expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toContain(- configPath,+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(+ CONFIG_UNREADABLE_REASON,);expect(payload!["servers"]).toBeDefined();});diff --git a/tests/mcp/config-read-failure-tools.test.ts b/tests/mcp/config-read-failure-tools.test.tsindex 3fd2f5a6..0699d4aa 100644--- a/tests/mcp/config-read-failure-tools.test.ts+++ b/tests/mcp/config-read-failure-tools.test.ts@@ -27,6 +27,7 @@ import { join } from "node:path";import { buildToolTable, findTool } from "../../src/mcp/tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";+import { CONFIG_UNREADABLE_REASON } from "../../src/mcp/vault-path-field.ts";const VALID_CONFIG = `vault: "/srv/example-vault"\napi_key: "secret"\n`;@@ -105,10 +106,13 @@ describe("vault_health reports the broken config instead of throwing on it", ()const payload = await callTool("vault_health");expect(payload).toHaveProperty("vault_path");const vaultPath = payload["vault_path"] as Record<string, unknown>;- expect(String(vaultPath["error"])).toContain(configPath);+ expect(String(vaultPath["error"])).toBe(CONFIG_UNREADABLE_REASON);// The redaction contract holds even in the degraded shape: an- // unresolvable reference must not fall back to the raw host path.+ // unresolvable reference must not fall back to the raw host path,+ // and must not name the config file either - `config_writeable`+ // above is the field that names it.expect(JSON.stringify(payload["vault_path"])).not.toContain(vault);+ expect(JSON.stringify(payload["vault_path"])).not.toContain(configPath);});});diff --git a/tests/mcp/instruction-segments.test.ts b/tests/mcp/instruction-segments.test.tsnew file mode 100644index 00000000..bf2b08f3--- /dev/null+++ b/tests/mcp/instruction-segments.test.ts@@ -0,0 +1,355 @@+/**+ * `initialize.instructions` rendered from the live capability report.+ *+ * ## The defect+ *+ * The instruction block is the first text every agent reads, and it was+ * three frozen strings chosen by scope alone. A host that disables+ * `brain_note` - a supported runtime capability window this server+ * already evaluates and reports on - still received a paragraph telling+ * the agent to call it. The agent then calls a tool that is not there,+ * reads the refusal, and works out for itself that the first thing it+ * was told was wrong.+ *+ * Appending "…except these" beneath the same prose would not fix it: an+ * instruction and its retraction in one document leave the reader to+ * decide which half is true. So the guidance is REMOVED rather than+ * contradicted, and the removal is named with the reason the evaluator+ * already computed.+ *+ * ## What is pinned here+ *+ * The rewrite's own risk is that shaping three bodies into segments+ * changes their MEANING. The first test removes that risk by pinning the+ * fully-available render of each scope against a byte-for-byte fixture+ * captured from the frozen strings this change replaces. Only the+ * withheld cases may differ, and the rest of this file is those cases.+ *+ * One sentence in `catalog.txt` is a deliberate exception. The frozen+ * string said every tool omitted from `tools/list` stays callable+ * through `tools/call`, which was true of the catalog surface's hiding+ * and false of a capability window - the window removes the tool from+ * the table `tools/call` routes on. A window is exactly what this+ * module renders for, so the one paragraph that contradicted it was+ * rewritten rather than pinned, and the fixture carries the corrected+ * text.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { buildInstructions } from "../../src/mcp/instructions.ts";+import {+ PARAGRAPH_BREAK,+ WITHHELD_BLOCK_HEADING,+ segmentToolNames,+} from "../../src/mcp/instruction-segments.ts";+import {+ CAPABILITY_DIAGNOSTIC_TOOL,+ evaluateToolCapabilities,+ type RuntimeCapabilityWindow,+} from "../../src/mcp/capabilities.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import {+ TOOL_SCOPE,+ TOOL_SCOPES,+ type ToolCapabilityReport,+ type ToolScope,+} from "../../src/mcp/tool-contract.ts";++/** Where the byte-identity fixtures captured from the frozen strings live. */+const FIXTURE_DIR = join(import.meta.dir, "..", "fixtures", "instruction-bodies");++/** Agent name the fixtures were captured under. */+const AGENT = "pin-agent";++/** The tool the withheld cases exercise, and the reason the evaluator gives it. */+const WITHHELD_TOOL = "brain_note";+const DISABLED_REASON = "disabled by runtime capability window";++/** Server name for reports built here; nothing under test reads it. */+const TEST_SERVER = "open-second-brain-test";++function reportFor(scope: ToolScope, window?: RuntimeCapabilityWindow): ToolCapabilityReport {+ return evaluateToolCapabilities(buildToolTable(scope), {+ scope,+ serverName: TEST_SERVER,+ window,+ }).report;+}++/** The pinned body for `scope`, without the trailing newline the file carries. */+function fixtureBody(scope: ToolScope): string {+ const text = readFileSync(join(FIXTURE_DIR, `${scope}.txt`), "utf8");+ expect(`${scope}.txt ends with a newline: ${text.endsWith("\n")}`).toBe(+ `${scope}.txt ends with a newline: true`,+ );+ return text.slice(0, -1);+}++/** The identity sentence every scope opens with, for the resolved case. */+const IDENTITY_LINE =+ `You are @${AGENT} on this Open Second Brain vault. ` ++ "Always log under this identity; do not invent or change the name.";++describe("a fully available runtime renders exactly what shipped before", () => {+ for (const scope of TOOL_SCOPES) {+ test(`${scope} scope is byte-identical to the pinned body`, () => {+ const text = buildInstructions({+ agent: AGENT,+ scope,+ capabilities: reportFor(scope),+ });+ expect(text).toBe(`${IDENTITY_LINE}\n\n${fixtureBody(scope)}`);+ });+ }+});++describe("a withheld tool loses its guidance rather than gaining a retraction", () => {+ const window: RuntimeCapabilityWindow = { disabledTools: [WITHHELD_TOOL] };++ test("the writer body carries no line instructing the withheld tool", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.writer,+ capabilities: reportFor(TOOL_SCOPE.writer, window),+ });+ const [body, withheldBlock] = text.split(WITHHELD_BLOCK_HEADING);+ expect(withheldBlock).toBeDefined();+ expect(body).not.toContain(WITHHELD_TOOL);+ });++ test("the tool is named once, in the withheld block, with the evaluator's reason", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.writer,+ capabilities: reportFor(TOOL_SCOPE.writer, window),+ });+ const occurrences = text.split(WITHHELD_TOOL).length - 1;+ expect(occurrences).toBe(1);+ expect(text).toContain(`${WITHHELD_TOOL}: ${DISABLED_REASON}`);+ });++ test("the guidance for the tools that remain is still there", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.writer,+ capabilities: reportFor(TOOL_SCOPE.writer, window),+ });+ expect(text).toContain("brain_feedback");+ expect(text).toContain("brain_pinned_context");+ });++ test("the full scope keeps the memory contract minus the withheld clause", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.full, window),+ });+ const [body] = text.split(WITHHELD_BLOCK_HEADING);+ expect(body).toContain("Memory contract: call brain_feedback");+ expect(body).toContain("brain_pinned_context for current-task facts");+ expect(body).not.toContain(WITHHELD_TOOL);+ });+});++describe("a runtime that withholds everything instructs nothing", () => {+ // Only the always-available diagnostic survives the window.+ const window: RuntimeCapabilityWindow = { allowedTools: [CAPABILITY_DIAGNOSTIC_TOOL] };++ for (const scope of TOOL_SCOPES) {+ test(`${scope} scope names no withheld tool outside the withheld block`, () => {+ const report = reportFor(scope, window);+ const text = buildInstructions({ agent: AGENT, scope, capabilities: report });+ const [body] = text.split(WITHHELD_BLOCK_HEADING);+ // The loop below is vacuous over an empty set, and a window that+ // stopped being honoured would produce exactly that.+ expect(report.withheld.length).toBeGreaterThan(0);+ for (const entry of report.withheld) {+ expect(`${scope} body names ${entry.name}: ${body!.includes(entry.name)}`).toBe(+ `${scope} body names ${entry.name}: false`,+ );+ }+ });++ test(`${scope} scope still opens with the identity line`, () => {+ const text = buildInstructions({+ agent: AGENT,+ scope,+ capabilities: reportFor(scope, window),+ });+ expect(text.startsWith(IDENTITY_LINE)).toBe(true);+ });+ }++ test("the withheld block names the tools whose guidance was removed", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.writer,+ capabilities: reportFor(TOOL_SCOPE.writer, window),+ });+ expect(text).toContain(WITHHELD_BLOCK_HEADING);+ expect(text).toContain(`${WITHHELD_TOOL}: not allowed by runtime capability window`);+ });++ test("a paragraph whose every tool-bearing clause went renders nothing at all", () => {+ // The full body's memory-contract paragraph closes with an+ // unconditional caveat ("Skip Brain calls for casual chat..."). With+ // every writer withheld it has nothing left to caveat, and a+ // surviving orphan sentence is the shape this rule exists to+ // prevent.+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.full, window),+ });+ const [body] = text.split(WITHHELD_BLOCK_HEADING);+ expect(body).not.toContain("Skip Brain calls");+ expect(body).not.toContain("Memory contract");+ });+});++describe("a dropped clause takes its punctuation and leaves its lead-in", () => {+ /** The paragraph `text` opens, as a whole and with nothing appended. */+ function paragraphOpening(text: string, prefix: string): string {+ const paragraph = text.split(PARAGRAPH_BREAK).find((block) => block.startsWith(prefix));+ expect(paragraph).toBeDefined();+ return paragraph!;+ }++ test("the memory contract keeps its lead-in when the first tool named goes", () => {+ // Exact text, not `toContain`: a doubled "; ", a stranded separator+ // or a heading welded to the dropped clause are all invisible to a+ // substring probe, and all of them are what this rule is about.+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.full, { disabledTools: ["brain_feedback"] }),+ });+ expect(paragraphOpening(text, "Memory contract")).toBe(+ "Memory contract: call brain_apply_evidence right after producing a durable artifact " ++ "a preference in `Brain/preferences/` scopes to (result: applied | violated | " ++ "outdated); brain_note for narrative milestones that fit neither; " ++ "brain_pinned_context for current-task facts that must survive context rotation. " ++ "brain_context bootstraps a session when the host injects no active.md hook. " ++ "Skip Brain calls for casual chat, exploration, and trivial edits - " ++ "a misrecorded signal is worse than a missed one.",+ );+ });++ test("the view list keeps its lead-in when the first view named goes", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.full, { disabledTools: ["brain_brief"] }),+ });+ expect(paragraphOpening(text, "Consolidated read views")).toBe(+ "Consolidated read views: brain_analytics (view: timeline | attention_flows | " ++ "belief_evolution | concept_synthesis), schema_inspect (view: graph | lint | stats " ++ "| orphans | explain_type | active_pack | packs).",+ );+ });++ test("the catalog keeps the fact its second pass depends on", () => {+ // The enumeration ("the five always-loaded Brain writers/readers")+ // stops being true and goes. The sentence beside it stays, because+ // without it the reader meets "Second pass:" with no first pass+ // described anywhere - and it stays TRUE under a window because it+ // separates the two reasons a tool can be missing from tools/list:+ // the catalog surface hides it (still callable) and the window+ // withholds it (not callable), which is exactly the case this test+ // stages.+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.catalog,+ capabilities: reportFor(TOOL_SCOPE.catalog, { disabledTools: [WITHHELD_TOOL] }),+ });+ const [body] = text.split(WITHHELD_BLOCK_HEADING);+ expect(body).not.toContain("compact first-pass tool set");+ expect(paragraphOpening(text, "A tool the catalog")).toBe(+ "A tool the catalog surface alone omits from\n" ++ "tools/list stays CALLABLE via tools/call — the omission keeps schema\n" ++ "tokens out of your prompt until needed. A tool a runtime capability\n" ++ "window withholds is not callable at all.",+ );+ expect(body).toContain("Second pass: call tool_hydrate");+ });+});++describe("the block points at a report only where there is one to read", () => {+ const window: RuntimeCapabilityWindow = { disabledTools: [WITHHELD_TOOL] };++ test("the full scope, which registers the diagnostic, names it", () => {+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.full, window),+ });+ expect(text).toContain(CAPABILITY_DIAGNOSTIC_TOOL);+ });++ test("the writer scope, which does not register it, does not send an agent there", () => {+ // `buildToolTable("writer")` is the five always-loaded tools and+ // nothing else, so the pointer would have named a tool this server+ // answers `unknown tool` for - the defect the module removes,+ // reintroduced by the sentence explaining the removal.+ const registered = new Set(buildToolTable(TOOL_SCOPE.writer).map((tool) => tool.name));+ expect(registered.has(CAPABILITY_DIAGNOSTIC_TOOL)).toBe(false);+ const text = buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.writer,+ capabilities: reportFor(TOOL_SCOPE.writer, window),+ });+ expect(text).toContain(WITHHELD_BLOCK_HEADING);+ expect(text).not.toContain(CAPABILITY_DIAGNOSTIC_TOOL);+ });+});++describe("the unresolved-identity branch is unchanged", () => {+ for (const scope of TOOL_SCOPES) {+ test(`${scope} scope renders the reason in place of a name`, () => {+ const reason = new Error("config unreadable: /etc/open-second-brain/config.yaml");+ const text = buildInstructions({+ agent: reason,+ scope,+ capabilities: reportFor(scope),+ });+ expect(text).toContain("UNRESOLVED");+ expect(text).toContain(reason.message);+ expect(text).not.toContain("You are @");+ expect(text.endsWith(fixtureBody(scope))).toBe(true);+ });+ }+});++describe("two arguments that disagree are refused, not rendered", () => {+ test("a report built for another scope names the mismatch", () => {+ // Every segment is decided by the report's `available` set, so a+ // writer report under the full scope deletes the whole body and+ // then explains the deletion with reasons that are false of this+ // server. The caller passed two arguments that describe different+ // servers; that is the error, and it says so.+ expect(() =>+ buildInstructions({+ agent: AGENT,+ scope: TOOL_SCOPE.full,+ capabilities: reportFor(TOOL_SCOPE.writer),+ }),+ ).toThrow(/writer scope, not full/);+ });+});++describe("no segment can orphan its guidance on a renamed tool", () => {+ for (const scope of TOOL_SCOPES) {+ test(`every tool a ${scope} segment names is in the ${scope} tool table`, () => {+ const registered = new Set(buildToolTable(scope).map((tool) => tool.name));+ const orphans = segmentToolNames(scope).filter((name) => !registered.has(name));+ expect(orphans).toEqual([]);+ });++ test(`${scope} segments name at least one tool, so the census has a population`, () => {+ expect(segmentToolNames(scope).length).toBeGreaterThan(0);+ });+ }+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 4e8a5323..b74e4996 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -185,6 +185,9 @@ describe("tool listing", () => {"second_brain_capabilities",// Core read/health (writable legacy tools removed in v0.9.0)."second_brain_status",+ // What this install is wired into: linked projects, verified+ // install targets (what-this-install-knows).+ "second_brain_wiring","second_brain_query","vault_health",// Preview-budget artifact fetch (added in v0.18.0).@@ -767,7 +770,9 @@ describe("stdio loop", () => {// t_c87644b4) = 113.// + brain_writes (recorded note writes, who-wrote-what Task A// t_662f4e82) = 114.- expect(list.result.tools.length).toBe(114);+ // + second_brain_wiring (linked projects and verified install targets,+ // what-this-install-knows t_49315346 + t_09d7e9e9) = 115.+ expect(list.result.tools.length).toBe(115);});test("returns parse error for invalid JSON", async () => {@@ -864,13 +869,29 @@ describe("serveStdioFromString respects scope+name", () => {});import { buildInstructions } from "../../src/mcp/instructions.ts";-import { TOOL_SCOPE, TOOL_SCOPES } from "../../src/mcp/tool-contract.ts";+import { evaluateToolCapabilities } from "../../src/mcp/capabilities.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import { TOOL_SCOPE, TOOL_SCOPES, type ToolScope } from "../../src/mcp/tool-contract.ts";++/**+ * The capability report of a runtime that withholds nothing. The+ * withheld cases have their own file+ * (`tests/mcp/instruction-segments.test.ts`); these tests are about the+ * identity line, which is the same on every runtime.+ */+function fullCapabilities(scope: ToolScope) {+ return evaluateToolCapabilities(buildToolTable(scope), {+ scope,+ serverName: "open-second-brain-test",+ }).report;+}describe("buildInstructions writer mode", () => {test("writer instructions name both tools and point at the full server", () => {const text = buildInstructions({agent: "@agent",scope: TOOL_SCOPE.writer,+ capabilities: fullCapabilities(TOOL_SCOPE.writer),});expect(text).toContain("brain_feedback");expect(text).toContain("brain_apply_evidence");@@ -893,13 +914,21 @@ describe("buildInstructions states the identity on every scope", () => {// remembering to extend this loop.for (const scope of TOOL_SCOPES) {test(`${scope} scope names the resolved agent`, () => {- const text = buildInstructions({ agent: AGENT, scope });+ const text = buildInstructions({+ agent: AGENT,+ scope,+ capabilities: fullCapabilities(scope),+ });expect(text).toContain(`You are @${AGENT} on this Open Second Brain vault.`);});test(`${scope} scope renders a refusal, never a name, when identity is unresolved`, () => {const reason = new Error("config unreadable: /etc/open-second-brain/config.yaml");- const text = buildInstructions({ agent: reason, scope });+ const text = buildInstructions({+ agent: reason,+ scope,+ capabilities: fullCapabilities(scope),+ });expect(text).toContain("UNRESOLVED");expect(text).toContain(reason.message);expect(text).not.toContain("You are @");diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.tsindex 8865acf5..fc07b65f 100644--- a/tests/mcp/removed-tools.test.ts+++ b/tests/mcp/removed-tools.test.ts@@ -193,5 +193,7 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn// t_c87644b4) = 113.// + brain_writes (recorded note writes, who-wrote-what Task A// t_662f4e82) = 114.- expect(list.result.tools.length).toBe(114);+ // + second_brain_wiring (linked projects and verified install targets,+ // what-this-install-knows t_49315346 + t_09d7e9e9) = 115.+ expect(list.result.tools.length).toBe(115);});diff --git a/tests/mcp/runtime-capabilities.test.ts b/tests/mcp/runtime-capabilities.test.tsindex b7278ffd..66f904fd 100644--- a/tests/mcp/runtime-capabilities.test.ts+++ b/tests/mcp/runtime-capabilities.test.ts@@ -3,9 +3,13 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { JSONRPC_VERSION, MCPServer } from "../../src/mcp/index.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { WITHHELD_BLOCK_HEADING } from "../../src/mcp/instruction-segments.ts";import { runCli } from "../helpers/run-cli.ts";+/** Any path: nothing in these tests reads the vault. */+const VAULT = "/tmp/o2b-runtime-capability-test";+describe("MCP runtime capability window", () => {test("runtime deny withholds a tool and reports the reason", async () => {const server = new MCPServer(@@ -86,3 +90,49 @@ describe("MCP runtime capability window", () => {}});});++describe("the handshake an actual host reads reflects the actual window", () => {+ /** The tool whose guidance the window removes. */+ const WITHHELD = "brain_note";++ /** A server's `initialize.instructions`, as the host receives them. */+ async function handshake(server: MCPServer): Promise<string> {+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "window-test", version: "0" },+ },+ })) as { result: { instructions: string } };+ return response.result.instructions;+ }++ test("a disabled writer loses its guidance and is named as withheld", async () => {+ // Every other test of this rendering calls `buildInstructions` with+ // a report it built itself, so the wire between the server's own+ // capability report and the block it hands the host was unasserted:+ // dropping the window on the way to `buildInstructions` compiled,+ // shipped a handshake instructing a disabled tool, and failed+ // nothing. This drives `initialize` on the server instead.+ const windowed = await handshake(+ new MCPServer(+ { vault: VAULT },+ { scope: "writer", capabilityWindow: { disabledTools: [WITHHELD] } },+ ),+ );+ const open = await handshake(new MCPServer({ vault: VAULT }, { scope: "writer" }));++ expect(open).toContain(`- ${WITHHELD}`);+ const [body, withheldBlock] = windowed.split(WITHHELD_BLOCK_HEADING);+ expect(body).not.toContain(WITHHELD);+ expect(withheldBlock).toContain(WITHHELD);+ });++ test("an unwindowed server carries no withheld block at all", async () => {+ const text = await handshake(new MCPServer({ vault: VAULT }, { scope: "writer" }));+ expect(text).not.toContain(WITHHELD_BLOCK_HEADING);+ });+});diff --git a/tests/mcp/wiring-tools.test.ts b/tests/mcp/wiring-tools.test.tsnew file mode 100644index 00000000..ee7723db--- /dev/null+++ b/tests/mcp/wiring-tools.test.ts@@ -0,0 +1,537 @@+/**+ * `second_brain_wiring` - what this install is wired into.+ *+ * Two readers already answered this and neither was reachable from the+ * MCP surface. `linkedProjectsStatus` reports every registered project+ * link with its pointer state, and had one consumer: the CLI verb+ * `o2b brain project status`. That is the whole gap this view closes -+ * no new health model, no second registry walk.+ *+ * The path policy is the part worth testing hard. The registry is keyed+ * on ABSOLUTE host paths, and an MCP response lands in model context, so+ * every reference here goes through the same `expose_host_paths`+ * contract `vault_path` already obeys. A payload that leaked a project+ * directory would be the same defect the vault-path census exists to+ * prevent, one field over.+ *+ * The hosts view leaks differently: `verify()` composes its `details`+ * and `fix_hint` sentences from `InstallEnv.home`, so the path arrives+ * inside prose no store reference can render. `foldHostHome` folds the+ * home prefix there, and the no-host-path assertion below is over the+ * SERIALISED payload of both views - the census in+ * `tests/core/architecture/vault-path-census.test.ts` is keyed on the+ * field name `vault_path` and cannot see either of these fields.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { Writable } from "node:stream";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import {+ WIRING_MAX_PROJECTS,+ WIRING_TOOL_NAME,+ WIRING_VIEWS,+ hostWiringEntry,+} from "../../src/mcp/wiring-tools.ts";+import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";+import { foldHostHome } from "../../src/mcp/vault-path-field.ts";+import {+ projectsRegistryPath,+ registerLinkedProject,+ writeVaultPointer,+ VAULT_POINTER_FILE,+} from "../../src/core/brain/portability/pointer.ts";+import { INSTALLATION_SECRET_ENV_KEY, VAULT_STORE_REF_PREFIX } from "../../src/core/config.ts";+import { VAULT_NOT_CONFIGURED_REASON, buildInstallEnv } from "../../src/core/install/env.ts";+import { defaultRegistry } from "../../src/core/install/registry.ts";+import "../../src/core/install/adapters/all.ts";+import {+ HOST_PROBE_RESULT,+ resetHostProbeRunner,+ setHostProbeRunner,+} from "../../src/core/install/host-probe.ts";+import { VERIFY_STATUSES, type InstallEnv } from "../../src/core/install/types.ts";+import {+ codexAdapter,+ resetCodexRunner,+ setCodexRunner,+} from "../../src/core/install/adapters/codex.ts";+import { buildPayload } from "../../src/core/install/payload.ts";++/** Deterministic 32-hex key so `vault://<hex>` is stable across runs. */+const SECRET = "0123456789abcdef0123456789abcdef";++/** The escape hatch that restores raw host paths. */+const EXPOSE_ENV = "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS";++/** The override `defaultConfigPath` consults before the host home. */+const CONFIG_PATH_ENV = "OPEN_SECOND_BRAIN_CONFIG";++/**+ * Every environment variable this file writes.+ *+ * Bun runs the whole suite in ONE process and `tests/setup.ts` makes it+ * hermetic by pointing `OPEN_SECOND_BRAIN_CONFIG` at a throwaway config+ * for every file that does not set its own. A `delete` here therefore+ * does not restore a prior state - it destroys that default for every+ * file bun schedules after this one, which is why the restore below is+ * a snapshot of the value rather than a removal of the key.+ */+const MUTATED_ENV: ReadonlyArray<string> = Object.freeze([+ INSTALLATION_SECRET_ENV_KEY,+ EXPOSE_ENV,+ CONFIG_PATH_ENV,+]);++interface Sandbox {+ readonly root: string;+ readonly configPath: string;+ readonly vault: string;+ readonly project: string;+}++let sandbox: Sandbox;+let savedEnv: Map<string, string | undefined>;++function makeSandbox(): Sandbox {+ const root = mkdtempSync(join(tmpdir(), "o2b-wiring-"));+ const configPath = join(root, "config", "config.yaml");+ mkdirSync(join(root, "config"), { recursive: true });+ writeFileSync(configPath, "vault: \n", "utf8");+ const vault = join(root, "vault");+ const project = join(root, "project");+ mkdirSync(vault, { recursive: true });+ mkdirSync(project, { recursive: true });+ return { root, configPath, vault, project };+}++beforeEach(() => {+ savedEnv = new Map(MUTATED_ENV.map((key) => [key, process.env[key]]));+ process.env[INSTALLATION_SECRET_ENV_KEY] = SECRET;+ delete process.env[EXPOSE_ENV];+ sandbox = makeSandbox();+});++afterEach(() => {+ for (const [key, value] of savedEnv) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(sandbox.root, { recursive: true, force: true });+});++/** `server` overrides the default context, for the tests about that context. */+async function callWiring(+ args: Record<string, unknown>,+ server: MCPServer = new MCPServer({ vault: sandbox.vault, configPath: sandbox.configPath }),+): Promise<{+ payload?: Record<string, unknown>;+ error?: { code: number; message: string };+}> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "wiring-test", version: "0" },+ },+ });+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name: WIRING_TOOL_NAME, arguments: args },+ })) as {+ result?: { content: ReadonlyArray<{ type: string; text: string }> };+ error?: { code: number; message: string };+ };+ if (response.error) return { error: response.error };+ return { payload: JSON.parse(response.result!.content[0]!.text) };+}++describe("second_brain_wiring registration", () => {+ test("is in the full tool table and in neither reduced scope", () => {+ expect(buildToolTable("full").find((t) => t.name === WIRING_TOOL_NAME)).toBeDefined();+ expect(buildToolTable("writer").find((t) => t.name === WIRING_TOOL_NAME)).toBeUndefined();+ const catalog = buildToolTable("catalog").find((t) => t.name === WIRING_TOOL_NAME);+ expect(catalog?.hidden).toBe(true);+ });++ test("view is required, and an absent one names the accepted members", async () => {+ const { error } = await callWiring({});+ expect(error?.code).toBe(INVALID_PARAMS);+ for (const view of WIRING_VIEWS) expect(error?.message).toContain(view);+ });++ test("an unknown view is refused by name rather than defaulted", async () => {+ const { error } = await callWiring({ view: "everything" });+ expect(error?.code).toBe(INVALID_PARAMS);+ expect(error?.message).toContain("everything");+ });+});++describe("view=projects", () => {+ test("reports one entry per registered link with its pointer state", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ writeVaultPointer(sandbox.project, sandbox.vault);+ const { payload } = await callWiring({ view: "projects" });+ expect(payload!["view"]).toBe("projects");+ const projects = payload!["projects"] as Array<Record<string, unknown>>;+ expect(projects).toHaveLength(1);+ expect(projects[0]).toMatchObject({ pointer: "ok", vault_exists: true });+ });++ test("an empty registry is an empty list, not an error", async () => {+ const { payload } = await callWiring({ view: "projects" });+ expect(payload!["projects"]).toEqual([]);+ expect(payload!["total"]).toBe(0);+ expect(payload!["returned"]).toBe(0);+ expect(payload!["truncated"]).toBe(false);+ });++ test("an uncapped registry is capped, and the payload says so", async () => {+ // Nothing caps `projects.json` - every `o2b brain project link`+ // appends to it - and this response lands in model context, so the+ // bound has to be in the payload rather than in the expectation+ // that operators link few projects.+ const over = WIRING_MAX_PROJECTS + 3;+ for (let i = 0; i < over; i++) {+ const project = join(sandbox.root, `linked-${i}`);+ mkdirSync(project, { recursive: true });+ registerLinkedProject(sandbox.configPath, project, sandbox.vault);+ }+ const { payload } = await callWiring({ view: "projects" });+ expect((payload!["projects"] as unknown[]).length).toBe(WIRING_MAX_PROJECTS);+ expect(payload!["total"]).toBe(over);+ expect(payload!["returned"]).toBe(WIRING_MAX_PROJECTS);+ expect(payload!["truncated"]).toBe(true);+ });++ test("a registry under the cap is not reported as truncated", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ const { payload } = await callWiring({ view: "projects" });+ expect(payload!["total"]).toBe(1);+ expect(payload!["returned"]).toBe(1);+ expect(payload!["truncated"]).toBe(false);+ });++ test("each of the four pointer states is reported as itself", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ const missing = await callWiring({ view: "projects" });+ expect((missing.payload!["projects"] as Array<Record<string, unknown>>)[0]!["pointer"]).toBe(+ "missing",+ );++ writeFileSync(join(sandbox.project, VAULT_POINTER_FILE), "{ not json", "utf8");+ const malformed = await callWiring({ view: "projects" });+ expect((malformed.payload!["projects"] as Array<Record<string, unknown>>)[0]!["pointer"]).toBe(+ "malformed",+ );++ const other = join(sandbox.root, "other-vault");+ mkdirSync(other, { recursive: true });+ writeVaultPointer(sandbox.project, other);+ const mismatch = await callWiring({ view: "projects" });+ expect((mismatch.payload!["projects"] as Array<Record<string, unknown>>)[0]!["pointer"]).toBe(+ "mismatch",+ );+ });++ test("a vault that no longer exists is reported, not hidden", async () => {+ const gone = join(sandbox.root, "removed-vault");+ mkdirSync(gone, { recursive: true });+ registerLinkedProject(sandbox.configPath, sandbox.project, gone);+ rmSync(gone, { recursive: true, force: true });+ const { payload } = await callWiring({ view: "projects" });+ expect((payload!["projects"] as Array<Record<string, unknown>>)[0]).toMatchObject({+ vault_exists: false,+ });+ });+});++describe("view=projects path policy", () => {+ test("no absolute host path appears anywhere in the serialised payload", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ writeVaultPointer(sandbox.project, sandbox.vault);+ const { payload } = await callWiring({ view: "projects" });+ const serialised = JSON.stringify(payload);+ expect(serialised).not.toContain(sandbox.project);+ expect(serialised).not.toContain(sandbox.vault);+ expect(serialised).toContain(VAULT_STORE_REF_PREFIX);+ });++ test("with expose_host_paths on, the raw paths are what the operator asked for", async () => {+ process.env[EXPOSE_ENV] = "true";+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ const { payload } = await callWiring({ view: "projects" });+ const projects = payload!["projects"] as Array<Record<string, unknown>>;+ expect(projects[0]!["project_ref"]).toBe(sandbox.project);+ expect(projects[0]!["vault_ref"]).toBe(sandbox.vault);+ });++ test("a config that cannot be read renders the reason, never the raw path", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ // The secret keys the reference and lives in the config; an+ // unreadable config leaves the reference unresolvable, and the+ // contract forbids degrading to the path the reference hides.+ delete process.env[INSTALLATION_SECRET_ENV_KEY];+ // A directory where the config file belongs: `discoverConfig`+ // refuses a path that is not a regular file, which is the one+ // ConfigReadError branch a test can stage without depending on the+ // running user being unable to read a chmod-ed file.+ rmSync(sandbox.configPath, { force: true });+ mkdirSync(sandbox.configPath, { recursive: true });+ const { payload } = await callWiring({ view: "projects" });+ const serialised = JSON.stringify(payload);+ expect(serialised).not.toContain(sandbox.project);+ // Both sides of the link, not just the one: the two fields are+ // rendered by the same call and an assertion over one of them would+ // pass for a payload that leaked the other.+ expect(serialised).not.toContain(sandbox.vault);+ const projects = payload!["projects"] as Array<Record<string, unknown>>;+ expect(projects[0]!["project_ref"]).toHaveProperty("error");+ expect(projects[0]!["vault_ref"]).toHaveProperty("error");+ });++ test("a registry damaged by hand reads as no links, exactly as the CLI verb does", async () => {+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ writeFileSync(projectsRegistryPath(sandbox.configPath), "{ broken", "utf8");+ const { payload } = await callWiring({ view: "projects" });+ // `listLinkedProjects` passes `tolerateParseError`, so this view+ // answers what `o2b brain project status` answers. It is core's+ // tolerance, not this view's: a tool that refused where the verb+ // tolerates would be the second answer this file exists to avoid.+ expect(payload!["projects"]).toEqual([]);+ });++ test("a server given no config path reads the machine default, not an empty list", async () => {+ // The view used to answer `[]` here, which reports "nothing is+ // linked" for a box whose registry is full - and disagreed with+ // `view=hosts` in the same tool, which has always defaulted. The+ // default is redirected through the env override `defaultConfigPath`+ // consults first, since `os.homedir()` cannot be moved in-process.+ registerLinkedProject(sandbox.configPath, sandbox.project, sandbox.vault);+ writeVaultPointer(sandbox.project, sandbox.vault);+ process.env[CONFIG_PATH_ENV] = sandbox.configPath;+ // No local restore: `afterEach` puts every key in `MUTATED_ENV` back+ // to the value it snapshotted, which for this one is the hermetic+ // default `tests/setup.ts` installs for the whole process.+ const server = new MCPServer({ vault: sandbox.vault });+ const { payload } = await callWiring({ view: "projects" }, server);+ expect((payload!["projects"] as unknown[]).length).toBe(1);+ });+});++/** How a folded sentence names the host home; see `foldHostHome`. */+const FOLDED_HOME = "~";++/** The identity a staged registration is written under. */+const STAGE_AGENT = "wiring-test";++/** The timezone a staged registration is written under. */+const STAGE_TIMEZONE = "UTC";++/**+ * A codex registration this build wrote, under `home`.+ *+ * An unstaged target verifies to "no install manifest entry" - a+ * sentence carrying no path at all - so a path assertion over it would+ * pass for the wrong reason. An absent binary sends `apply` down the+ * file-writing path, so the registration exists as a real artifact.+ *+ * LEAVES both runners stubbed, because `verify()` consults them too -+ * an unstubbed host probe would spawn whatever `codex` binary the test+ * machine happens to have. Every caller resets them in its own+ * `finally`; a caller that wants a different probe answer overrides it.+ */+function stageCodexInstall(home: string, vault: string): InstallEnv {+ const installEnv: InstallEnv = {+ vault,+ home,+ cwd: home,+ env: { VAULT_AGENT_NAME: STAGE_AGENT, VAULT_TIMEZONE: STAGE_TIMEZONE },+ now: new Date(),+ };+ const payload = buildPayload({ vault, agent_name: STAGE_AGENT, timezone: STAGE_TIMEZONE });+ setCodexRunner({+ available: () => false,+ run: () => {+ throw new Error("the adapter must not spawn codex when it reported the binary absent");+ },+ });+ setHostProbeRunner({+ available: () => false,+ run: () => {+ throw new Error("the probe must not spawn when it reported the binary absent");+ },+ });+ const sink = new Writable({ write: (_c, _e, cb) => cb() }) as unknown as NodeJS.WriteStream;+ codexAdapter.apply(codexAdapter.plan(payload, installEnv), payload, installEnv, {+ dryRun: false,+ force: false,+ stdout: sink,+ stderr: sink,+ });+ return installEnv;+}++describe("view=hosts", () => {+ test("reports one entry per registered adapter", async () => {+ const { payload } = await callWiring({ view: "hosts" });+ expect(payload!["view"]).toBe("hosts");+ const hosts = payload!["hosts"] as Array<Record<string, unknown>>;+ expect(hosts.map((h) => h["target"])).toEqual([...defaultRegistry.targets()]);+ for (const host of hosts) {+ expect([...VERIFY_STATUSES] as string[]).toContain(host["status"] as string);+ expect(Array.isArray(host["details"])).toBe(true);+ expect(host).toHaveProperty("fix_hint");+ }+ });++ test("it is the same verify() answer, over the same registry and env", async () => {+ // Not "an equivalent aggregate": the same call over the same+ // registry with the same env, so one implementation of connector+ // health cannot become two that disagree. The env is built through+ // `buildInstallEnv` - the constructor `o2b install` now shares - so+ // splitting that constructor again fails here.+ const env = buildInstallEnv({ vault: sandbox.vault, configPath: sandbox.configPath });+ const policy = { configPath: sandbox.configPath };+ const direct = defaultRegistry.list().map((adapter) => adapter.verify(env));+ const { payload } = await callWiring({ view: "hosts" });+ const hosts = payload!["hosts"] as Array<Record<string, unknown>>;+ expect(hosts).toEqual(direct.map((r) => hostWiringEntry(r, env.home, policy)));+ });++ test("the serialised payload of neither view carries this process's home", async () => {+ // The cheap end-to-end guard. It is not the one with teeth - an+ // install-free home verifies to "no install manifest entry", a+ // sentence with no path in it - so the folding assertions below+ // stage a registration first.+ const answers = await Promise.all(WIRING_VIEWS.map((view) => callWiring({ view })));+ for (const { payload } of answers) {+ expect(JSON.stringify(payload)).not.toContain(homedir());+ }+ });++ test("adapter prose folds the host home instead of naming it", () => {+ const home = mkdtempSync(join(sandbox.root, "fold-home-"));+ const installEnv = stageCodexInstall(home, sandbox.vault);+ try {+ const entry = hostWiringEntry(codexAdapter.verify(installEnv), home, {+ configPath: sandbox.configPath,+ });+ const details = (entry["details"] as string[]).join("; ");+ // Staged, so the sentence names a file: the assertion below is+ // about WHICH form that name takes, not about its absence.+ expect(details).toContain(`${FOLDED_HOME}/.codex/`);+ expect(details).not.toContain(home);+ } finally {+ resetHostProbeRunner();+ resetCodexRunner();+ }+ });++ test("a sibling home that extends this one is left alone", () => {+ // A plain prefix replacement run under a home named `dev` clips a+ // sibling named `developer` into `~eloper` - a path that names no+ // file, which is worse than either the raw one or the folded one.+ const home = join(sandbox.root, "dev");+ const sibling = `${home}eloper/.codex/config.toml`;+ const folded = foldHostHome(`${home}/.codex/config.toml and ${sibling}`, home, {+ configPath: sandbox.configPath,+ });+ expect(folded).toBe(`${FOLDED_HOME}/.codex/config.toml and ${sibling}`);+ });++ test("the home folds at the end of a sentence and before punctuation too", () => {+ const home = join(sandbox.root, "dev");+ const folded = foldHostHome(`checked ${home}, then ${home}`, home, {+ configPath: sandbox.configPath,+ });+ expect(folded).toBe(`checked ${FOLDED_HOME}, then ${FOLDED_HOME}`);+ });++ test("`expose_host_paths` restores the raw path in that same sentence", () => {+ // The escape hatch is ONE flag for both mechanisms: the config that+ // un-hashes `vault_path` un-folds the adapter prose with it.+ const home = mkdtempSync(join(sandbox.root, "expose-home-"));+ const installEnv = stageCodexInstall(home, sandbox.vault);+ process.env[EXPOSE_ENV] = "1";+ try {+ const entry = hostWiringEntry(codexAdapter.verify(installEnv), home, {+ configPath: sandbox.configPath,+ });+ expect((entry["details"] as string[]).join("; ")).toContain(`${home}/.codex/`);+ } finally {+ // `afterEach` restores EXPOSE_ENV from the snapshot; the runners+ // are process-global and have no snapshot, so they reset here.+ resetHostProbeRunner();+ resetCodexRunner();+ }+ });++ test("an unresolved vault is refused by name, not reported as ten clean targets", async () => {+ const server = new MCPServer({ vault: "", configPath: sandbox.configPath });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "wiring-test", version: "0" },+ },+ });+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name: WIRING_TOOL_NAME, arguments: { view: "hosts" } },+ })) as {+ result?: { content: ReadonlyArray<{ text: string }> };+ error?: { code: number; message: string };+ };+ expect(response.error?.message).toContain(VAULT_NOT_CONFIGURED_REASON);+ // The code docs/mcp.md gives for this refusal, alongside the one it+ // gives for a bad `view`.+ expect(response.error?.code).toBe(INVALID_PARAMS);+ expect(response.result).toBeUndefined();+ });+ test("a probe that cannot run reaches the payload as its named reason, not an ok", () => {+ // The branch needs an INSTALLED target verified against a specific+ // host home, and `os.homedir()` here does not follow a later+ // `process.env.HOME`, so the home the view resolves cannot be+ // redirected in-process. The env is therefore built by hand, as the+ // adapter suites do, and the assertion is over the view's own+ // mapping of the real `verify()` answer - the deep-equality test+ // above is what ties that mapping to the env the view builds.+ const home = mkdtempSync(join(sandbox.root, "probe-home-"));+ const installEnv = stageCodexInstall(home, sandbox.vault);+ try {+ // The host binary answers, and refuses.+ setHostProbeRunner({+ available: () => true,+ run: () => ({ exitCode: 4, stdout: "", stderr: "failed to load configuration\n" }),+ });+ const entry = hostWiringEntry(codexAdapter.verify(installEnv), home, {+ configPath: sandbox.configPath,+ });+ const details = (entry["details"] as string[]).join("; ");+ expect(details).toContain("exited 4");+ expect(details).toContain("failed to load configuration");+ // The skip is NAMED, so nothing here reads as a host-confirmed+ // registration.+ expect(details).not.toContain(HOST_PROBE_RESULT.answered);+ expect(entry["target"]).toBe(codexAdapter.target);+ } finally {+ resetHostProbeRunner();+ resetCodexRunner();+ }+ });+});