Skip to content

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: scoped operator rules per project, harness and host, per-profile Hermes settings on a multiplexed gateway and readers that answer at the caller's reach (v1.70.0) (#229)

Serg Eroshe39c2f2258e04
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6cdf893a..2e2f4ea5 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.69.0",
+ "version": "1.70.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
@@ -12,11 +12,11 @@
"mcpServers": {
"open-second-brain": {
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",
- "args": ["mcp"]
+ "args": ["mcp", "--harness", "claude-code"]
},
"open-second-brain-writer": {
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",
- "args": ["mcp", "--scope", "writer"],
+ "args": ["mcp", "--scope", "writer", "--harness", "claude-code"],
"alwaysLoad": true
}
}
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index c4c88646..c32b5742 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.69.0",
+ "version": "1.70.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/CHANGELOG.md b/CHANGELOG.md
index 0442b1d9..d7a06faa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,65 @@ 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.70.0] - 2026-10-03
+
+A setting or a rule meant for one context no longer carries over into another: on a Hermes gateway that multiplexes profiles, the Open Second Brain plugin reads every profile-scoped setting from the turn's profile scope and gives each profile its own MCP child, and the operator can now write standing rules for one project, one harness or one machine under `Brain/standing-rules/`, which the SessionStart hook and `brain_context` render below the operator standing rules at local reach; the today, monthly and operator brief views, the doctor's counts and repair preview, and the obligation, intention, health, trigger, stale-scan, review-candidates, intent-review, retention, context-receipts, tension, lifecycle, expire, evidence, feedback, derived-fact, decision, label, scaffold, dream, maintenance, dead-end, diarize, hygiene refresh and anticipatory-context tools now answer at the caller's reach.
+
+### Added
+
+- **Scoped operator rules.** Beside the vault-wide `Brain/standing-rules.md`, the operator can write one file per scope value: `Brain/standing-rules/project/<key>.md`, `Brain/standing-rules/harness/<harness id>.md` and `Brain/standing-rules/host/<device id>.md`. Each session renders the files whose key matches its own project, harness and device, under a `## Scoped operator rules` header that states the precedence (the operator standing rules above take precedence over them, and they take precedence over every recalled preference, lesson and context pack that follows) and one `### Project: <key>`, `### Harness: <key>` or `### Host: <key>` subheading per file. The operator's text is never rewritten. A file that cannot be read is replaced by one `UNAVAILABLE:` line naming its vault-relative path and the error code (`ESCAPE` for a file or folder behind a symbolic link that leaves the vault). The files are read on every render and never cached, and they render only at local reach.
+- **A server-resolved scope identity.** No caller names its own scope. The project is the basename of the directory holding the nearest `.o2b-vault.json` pointer found from the workspace directory (written by `o2b brain project link`); the harness comes from the launch-time `--harness` option, falling back to `--host-target`; the host is the device id. Keys are normalised (NFC, lowercase) to letters, combining marks, digits and `-` in any script, at most 64 characters. An axis that does not resolve matches no file.
+- **`o2b mcp --harness <id>`.** Names the harness the server runs under, from a closed list (`aider`, `claude-code`, `codex`, `copilot-cli`, `cursor`, `gemini-cli`, `generic`, `grok`, `hermes`, `kiro`, `openclaw`, `opencode`, `pi`); an unknown value exits 2 and lists the accepted ones.
+- **`scoped_rules` on `brain_context`.** At local reach, when at least one scoped file matched (or the host notice applies), the scoped block follows the standing rules in `content` and the result carries `scoped_rules: {scope: {project, harness, host}, files: [{path, axis, truncated}]}` with vault-relative paths. No input argument is added.
+- **`active.scoped_rules_max_chars`.** Caps the scoped block (default 2000, at least 200); when the cap cuts anything the host file drops first, then the harness file, and a notice states the kept and total characters and the number of dropped files.
+- **Per-profile Hermes settings on a multiplexed gateway.** With `gateway.multiplex_profiles` on, `VAULT_DIR`, `VAULT_AGENT_NAME`, `VAULT_TIMEZONE`, `OPEN_SECOND_BRAIN_CONFIG` and `OPEN_SECOND_BRAIN_MCP_TIMEOUT` are read from the turn's Hermes profile scope (the profile's `.env`), never from the gateway process environment, which belongs to the launch profile. A setting the profile does not hold falls through to the config chain (pointer, active profile, config key, default). `XDG_CONFIG_HOME` and `LOCALAPPDATA` are read from the profile scope first and fall back to the gateway process environment when the profile does not set them, so a profile's own config directory locates its own config file. Without multiplexing every answer is unchanged.
+- **`settings_source:` in `hermes open-second-brain config`.** The first line names the source this command resolved from: `profile scope (multiplexed gateway)`, or `process environment (this command; a gateway with gateway.multiplex_profiles reads each profile's .env)`.
+
+### Changed
+
+- **The Claude Code and Hermes plugins launch `o2b mcp` with `--harness`.** The Claude Code plugin registers both of its MCP servers with `--harness claude-code`, and the Hermes plugin launches its bridge with `--harness hermes`. An `o2b` older than 1.70.0 refuses the flag, so the Hermes bridge does not start until `o2b` is updated together with the plugin; the Claude Code plugin runs the `o2b` it ships and needs no step.
+- **A refused `--host-target` value is echoed JSON-quoted.** `o2b mcp` used to echo a refused `--host-target` value raw on stderr; like a refused `--harness` value, it is now a JSON string with every C0 and C1 control character escaped as `\uXXXX` (or its short JSON escape).
+- **The scoped block is charged against the injection budget.** Unlike the operator standing rules, it is a budgeted source of the SessionStart hook: its rendered length is subtracted from `inject_budget_chars` before the active context is assembled, its header and the room for its notices ride inside that budget and its section cap is never larger than what the budget leaves after them, and the receipt's `budget` block records it as `scoped_rules_chars` beside the unchanged `inject_budget_chars`.
+- **The SessionStart hook renders project and host files.** Harness-scoped files render on the MCP surfaces only in this release.
+- **Each Hermes profile gets its own MCP child on a multiplexed gateway.** The child's environment carries the profile's own agent name, timezone, config path and vault instead of the launch profile's, and two profiles that share a vault but differ in any of those, or in their config directories (`XDG_CONFIG_HOME`, `LOCALAPPDATA`), no longer share one child. On a multiplexed gateway a bridge keeps the timeout it was built with, so a restart never reads the profile scope from a thread that has none; elsewhere the timeout is read at each start, as before.
+- **A Hermes setting ignored from the gateway environment is named once.** Under multiplexing each profile-scoped variable set in the gateway process environment logs one WARNING per process from the plugin's config module, without its value, saying to set it in the profile's `.env` instead; the shadowing hint names the profile's `.env`.
+- **A turn with no bound profile scope degrades.** When the gateway bound no profile scope, the settings readers raise a named `ProfileScopeError` (a `ConfigReadError`) instead of reading the launch profile's values, and the per-turn vault reminder is omitted with one WARNING instead of failing the turn. A Hermes whose profile-scope module is present but fails to import is treated the same way (one WARNING naming the exception type, and no further import attempt in that process), never as a gateway without profiles, and `hermes memory status` leaves out `config_file` when no profile scope is bound instead of failing.
+- **The today, monthly and operator brief views and the doctor's counts answer at the caller's reach.** Below local reach `brain_brief` `view="today"` no longer lists an open loop or obligation on a page the caller cannot read and counts only the files it may scan; `view="monthly"` counts events, status transitions, retirements and contradictions from the events the caller may see, like the daily and weekly views; `view="operator"` computes its doctor and digest counts, its top actions, its verification entries and counts and its trust verdict from what the caller may see; and `brain_doctor` fills its removed-tool warning cap and the per-code cap of its `uncertain` stream, counts the stale-dependency `states_changed` and each stale row's consumers, and runs its concept-gap and contradiction detectors from readable pages and records only. A local caller and the CLI see no change.
+- **Scoped rule files cannot be written by an agent.** Every write path that refuses `Brain/standing-rules.md` now also refuses any path inside `Brain/standing-rules/`, compared as written and after resolving symbolic links, so a not-yet-existing file reached through a linked folder is refused too. A rules folder or file behind a symbolic link that leaves the vault no longer makes the other guarded writes (labels, attributes, marker writeback, `brain_write_session`) fail.
+- **Docs:** `docs/how-it-works.md` gains "Scoped operator rules", `docs/mcp.md` the `scoped_rules` key and `--harness`, `docs/cli-reference.md` the `o2b mcp --harness` line, `docs/observability.md` the `scoped_rules_chars` field, `docs/stability.md` the two new layers, `install/hermes.md` "Multiple Hermes profiles", and `docs/updating.md` "Upgrading to 1.70.0"; the README names this release.
+
+### Fixed
+
+- **The today view no longer lists an open loop from a page the caller cannot read.** Below local reach `view="today"` used to return the text and path of an open loop on a page withheld by visibility.
+- **The operator view no longer lists a verification entry the caller cannot read.** Below local reach `view="operator"` used to list verification entries by record id and page path for records withheld from the caller.
+- **`brain_obligation` answers at the caller's reach.** Below local reach it used to list, show, complete and remove an obligation page withheld by visibility; such a page is now treated as absent, and `add` refuses its slug as before.
+- **`brain_health` and `brain_doctor` count concept gaps over readable principles.** Below local reach `concept_gaps` and the doctor's `concept-gap` warnings used to name terms that only withheld preferences carried; the semantic-health detectors now read only the preferences and signals the caller may read.
+- **`brain_trigger` scans answer at the caller's reach.** Below local reach `operation="scan"` used to count, create and list triggers about withheld preferences; its sources now read only readable records, and every trigger row asks the caller's reach as well as the owner scope.
+- **`brain_stale_scan`, `brain_review_candidates` and `brain_retention` answer at the caller's reach.** Below local reach they used to list withheld preferences and signals by id and path; such rows are now left out, and the retention `summary` counts the rows returned.
+- **`brain_intention`, `brain_intent_review` and the dream preview's signal clusters answer at the caller's reach.** Below local reach `brain_intention` used to list and show an intention chain withheld by visibility and fold it into a new version on `set`; such a chain is now treated as absent by `list`, `show` and `move`, and `set` refuses it; `list` judges each chain by its own file name, so a readable chain whose file name is not scope-shaped stays listed and a file named without letters or digits no longer fails the call. `brain_intent_review` and the `clusters_below_threshold` and `intent_reviews` of `brain_review_candidates` used to fold withheld inbox signals into their topics and counts; they now fold only the records the caller may read. `brain_obligation` `remove` and `brain_intention` `move` leave the archive name out of the answer below local reach.
+- **Retention and forget-plan rows carry the vault-relative path.** `brain_retention` recommendations and the forget-plan entries used to carry a path pointing out of the vault, so a `brain_trigger` scan below local reach never queued a retention trigger, even for a readable record.
+- **`brain_doctor` and the operator view leave out a withheld instruction file.** Below local reach `instruction_file_warnings` used to name a vault-root `AGENTS.md`, `CLAUDE.md` or `GEMINI.md` withheld by visibility, with its line count.
+- **A withheld page no longer moves a readable stale-dependency row or the `uncertain` cap.** Below local reach a withheld consumer could hide a readable state's row, and withheld pages could fill the per-code cap of the doctor's `uncertain` stream.
+- **`brain_context_receipts` answers at the caller's reach for the operator rules.** Below local reach a SessionStart injection receipt used to carry the standing-rules and scoped-rules items and the figures that measure them; it now leaves them out, and `summary` leaves them out of its item totals and counts a receipt left with no item as empty. A receipt that recorded only the rules (a session with no `active.md` body, or a degraded run with no cached body) is left out of `list` and `summary` and answered by `show` as an unknown id, and the `budget` block leaves a receipt with no budgeted body left.
+- **The `brain_doctor` repair preview counts at the caller's reach.** Below local reach `repair` used to fill the removed-tool cap and count concept gaps over every page before its findings were filtered, so its `unfixable` counts moved with withheld pages; the checks behind the plan now read only the pages and records the caller may read.
+- **`brain_tension` answers at the caller's reach.** Below local reach `detect` used to read, count and pair notes withheld by visibility and return the tension, and `list`, `show`, `verify` and the transitions used to answer for it. `detect` now reads only the notes the caller may read, a persisted tension page carries the stricter `visibility` of its two source notes, and a tension page the caller cannot read is answered as absent (`no tension: <slug>`) before anything is written.
+- **`brain_lifecycle` and `brain_expire` refuse a page the caller cannot read.** Below local reach `tombstone`, `supersede`, `temporal-replace` and `brain_expire` used to write to a page or record withheld by visibility; such a target is now refused with the error a missing one gets (`note does not exist`, `no signal or preference with id`), before anything is written, and `curator` leaves out the rows of such pages.
+- **The writers that name a preference, a decision or a page answer at the caller's reach.** Below local reach `brain_apply_evidence` and the `apply_evidence` operation of `brain_write_batch` used to accept evidence against a preference withheld by visibility, `brain_derive_fact` a withheld premise, `brain_scaffold_stub` a withheld source, and `brain_decision`, `brain_labels` `assign`/`remove` and `brain_lifecycle` `tip` used to show, rewrite or resolve a withheld page; such a page or record is now treated as absent before anything is written. The `brain_feedback` conflict and routing hints and `brain_design_note` grounding read only readable records. The `brain_scaffold_stub` ambiguity refusal no longer ends in an empty candidate list when none of the candidates is readable.
+- **`brain_dream` and `brain_maintenance` run a real pass at local reach only.** Below local reach `brain_dream` serves a dry run planned over the records the caller may read, and refuses a real pass, a step and the staged lifecycle; `brain_maintenance` refuses `run`. At local reach `brain_maintenance` `run` is allowed even when `integrity.owner_scope_delivery` is `fail`.
+- **A preference drafted by the dream pass keeps the visibility of its sources.** A preference drafted from signals reserved with `visibility`, or superseding or rebutting a reserved record, used to be written without a `visibility` line; it now carries the strictest visibility of those sources.
+- **`brain_dead_ends`, `brain_diarize`, `brain_hygiene` `refresh` and `brain_anticipatory_context` answer at the caller's reach.** Below local reach they used to list, profile, re-derive or archive pages and records withheld by visibility, or serve a context bundle built for the local operator; they now read only the pages and records the caller may read, and `brain_dead_ends` `record` still counts every active dead end against the cap but moves only readable ones into the archive.
+- **A non-finite Hermes MCP timeout is read as meant.** `OPEN_SECOND_BRAIN_MCP_TIMEOUT=nan` used to become the request deadline itself; it is now a malformed value that keeps the default deadline with one WARNING, `inf` disables the deadline like a non-positive value, and the WARNING for a malformed value no longer prints the value.
+
+### Notes
+
+- Other variables the TypeScript core reads from the environment (search settings, the MCP API key, embedding keys, the Telegram settings) still come from the gateway process environment on a multiplexed Hermes gateway.
+- The shared Hermes bridge resolves the gateway's working directory, so it usually matches no project-scoped file.
+- A Hermes gateway that serves a routed profile home without multiplexing keeps reading the process environment.
+- There are no combination scope files (for example project and host together); the matching single-axis files are joined instead.
+- The operator view's `dream_summary` counts (the dry-run dream's warnings, uncertain and quarantined entries), and the dream warnings its trust verdict folds in, are still taken over the whole Brain layer below local reach; they name no record.
+- A create aimed at an existing page refuses whoever may read it: `brain_obligation` `add`, `brain_intention` `set` over a withheld chain, `brain_decision` `record`, `brain_feedback` `force_confirmed`, the `brain_derive_fact` slug, `brain_write_batch` `create_note` and the `brain_scaffold_stub` target.
+- The review obligation `brain_decision` `record` opens names the decision's title and does not take the decision page's `visibility`.
+
## [1.69.0] - 2026-10-02
Ingest now reads more than Markdown: one format registry maps a file's extension to a format, CSV, TSV and HTML sources get a derived `## Table` or `## Parts` section and their content hash on the summary page, which carries the source's visibility, PDF, Office, EPUB, RTF and image files are named as format skips instead of counted as unclassifiable, and the read-only `o2b brain extract` previews what ingest derives from a file; the daily log pages, the daily and weekly briefs, the analytics, claims, backlinks, log, topic, preference, MOC audit and doctor readers, the source-cleanup tools and the recall verdict's root coverage now answer at the caller's reach, private regions and table cells are redacted in linear time, and `brain_recall_gate` accepts the `turn_id` the Hermes plugin sends.
@@ -8071,6 +8130,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.70.0]: https://github.com/itechmeat/open-second-brain/compare/v1.69.0...v1.70.0
[1.69.0]: https://github.com/itechmeat/open-second-brain/compare/v1.68.0...v1.69.0
[1.68.0]: https://github.com/itechmeat/open-second-brain/compare/v1.67.0...v1.68.0
[1.67.0]: https://github.com/itechmeat/open-second-brain/compare/v1.66.0...v1.67.0
diff --git a/README.md b/README.md
index e4c11830..f5f81b51 100644
--- a/README.md
+++ b/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.69.0 teaches ingest to read more than Markdown. One format registry decides what a file is: CSV, TSV and HTML files are planned by default and `brain_ingest_source` writes what it derives from them onto the summary page that search indexes - a `## Table` section of fenced plain-text row groups that each repeat the header, with named caps and redacted credential columns, or a `## Parts` section of HTML headings and their line spans, never the body - with `source_format`, `source_content_hash` and the table's counts in frontmatter. PDF, Office, EPUB, RTF and image files are named per file as `format-not-extractable` instead of counted as unknown, and `o2b brain extract` previews the extraction of any file without writing. The recall verdict's root coverage, the daily and weekly briefs, the daily log pages, the analytics, claims, backlinks, MOC audit and doctor readers and the source-cleanup tools now answer at the caller's reach, a summary page carries its source's visibility, private regions and table cells are redacted in linear time, `brain_recall_gate` accepts the `turn_id` the Hermes plugin sends, multi-line prompts that start with a command name are now admitted by the surfacing gate, and the architecture notes name the module edges a link cannot carry instead of claiming there are none. Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.70.0 keeps a setting or a rule meant for one context out of the others. On a Hermes gateway that multiplexes profiles, the plugin reads the vault, agent name, timezone, config path and timeout from the turn's profile scope instead of the launch profile's process environment, warns once per gateway variable it ignores, and gives each profile its own MCP child. Standing rules can now be written for one project, one harness or one machine under `Brain/standing-rules/`: the server resolves the project from the linked `.o2b-vault.json` pointer, the harness from the new `o2b mcp --harness` option and the host from the device id, and the SessionStart hook and `brain_context` render the matching files below the operator standing rules, at local reach only and charged against the injection budget. The today, monthly and operator brief views, the doctor's counts and repair preview, and more than twenty other reading and writing tools now answer at the caller's reach, and a remote client runs only a dry dream. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/scope-resolution/cli-output/claude.md b/docs/brainstorm/scope-resolution/cli-output/claude.md
new file mode 100644
index 00000000..ca4b8415
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/cli-output/claude.md
@@ -0,0 +1,39 @@
+### Variant 1: Three local seams
+
+- **Approach**: Each lane is fixed where it lives today. In `config.py`, every resolver gains an optional `env: Mapping[str, str]` parameter defaulting to `os.environ`, and `provider.py` builds a per-turn mapping from `agent.secret_scope.get_secret` when `is_multiplex_active()` is true, keying the `o2b mcp` child by `(vault, repo_root, command, PATH, agent_name, timezone)` and passing those two as env overrides to the spawn. Scoped standing rules become sibling files under a new `Brain/standing-rules/` directory (`project/<slug>.md`, `harness/<id>.md`, `host/<device-id>.md`) read by a second reader that appends ranked blocks after the untouched constitution; identity is resolved inline in `server.ts` at `initialize` (clientInfo name mapped through a frozen harness vocabulary, cwd or MCP roots walked for `.o2b-vault.json`, device id from config) and in the hook from cwd and a harness constant. The three left-over views and two doctor counts each take the reach-filtered page list the v1.68 reach-aware reader already produces.
+- **Trade-offs**:
+ - Pro: smallest diff, every change is near the code it corrects, parity suite and the pinned `ConfigReadError` message untouched because the default argument preserves today's reads byte for byte.
+ - Pro: no wire change, no new runtime dependency, scoped rules are plain files an operator can edit in Obsidian.
+ - Con: identity derivation lives in two places (server initialize and hook), so the harness vocabulary and the project walk-up can drift between them.
+ - Con: per-view reach filtering is five separate edits, each a chance to miss a count that still reads the whole layer.
+ - Con: the child-per-profile key multiplies long-lived `o2b mcp` processes on a gateway with many profiles sharing one vault.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: One derived session identity, one rules ladder, one reach layer
+
+- **Approach**: A new `src/core/runtime/session-identity.ts` computes a frozen `{ project, harness, host }` triple exactly once per process from server-held facts only: `--host-target` or the `initialize` clientInfo name mapped through a closed `HARNESS_ID` vocabulary with a census test, the `.o2b-vault.json` walk-up from the server cwd or first MCP root for project, and the device id for host, with a typed `IdentityUnresolved` reason per axis instead of a guess. A `standing-rules-ladder.ts` module reads the constitution with the existing reader and then the scoped files under `Brain/standing-rules/`, ranks them vault, project, harness, host, and renders one block that both the SessionStart hook and `brain_context` consume; the Brain-root refusal plus the named guard extended to the directory keep them unwritable. The Hermes plugin gets a `ProfileSettings` value resolved per turn through a tiny `settings_source` protocol (environ by default, secret scope under multiplexing) that `config.py` functions accept as an argument, and the bridge keys children by that value and overrides their env; the left-overs read from a `ReachLayer` object that pre-filters pages once per request and is passed to the three views and two doctor counts.
+- **Trade-offs**:
+ - Pro: identity decided in one server-owned module matches the origin-channel precedent and is testable as a vocabulary census; scoped rules can never be caller-named because the ladder takes the triple, not arguments.
+ - Pro: a single `ReachLayer` makes "remote never depends on withheld pages" a property of the input rather than of five call sites, and local reach passes the unfiltered layer so bytes stay identical.
+ - Pro: `UnscopedSecretError` maps to one new named `ProfileScopeError` sibling of `ConfigReadError`, so the pinned message survives and the failure surfaces by name.
+ - Con: largest surface area in one release, touching hook, MCP, CLI, Python and five readers at once.
+ - Con: the ladder must decide what to inject at remote reach for a caller whose project and host are meaningless, which needs an explicit rule (constitution only) rather than falling out of the design.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Scope axes extended, identity carried on the wire
+
+- **Approach**: Scoped rules are ordinary Brain pages under `Brain/rules/` whose frontmatter uses the existing `scope-key.ts` vocabulary, with `harness` and `host` added to `SCOPE_AXES`, so selection reuses composite-scope matching and search filters. Identity still comes from the server, but the Hermes plugin stops spawning a child per profile: one child per vault serves all profiles and the bridge attaches the turn's agent name and timezone as JSON-RPC `_meta` on each `tools/call`, which the server reads as transport facts (not tool arguments) and uses to override the inherited environment for that call. Reach is pushed down into the page index so every reader, including the three views and two doctor counts, is filtered without per-site edits.
+- **Trade-offs**:
+ - Pro: no process multiplication on multiplexed gateways and rules participate in search, backlinks and dedup like any page.
+ - Pro: one index-level reach filter covers the left-overs and any future reader.
+ - Con: extending `SCOPE_AXES` changes dedup and source-identity keys across search and the query cache, a wide blast radius unrelated to the theme.
+ - Con: per-call `_meta` makes agent name a request-time property; every code path that read it from process env at startup (write receipts, ledgers, logs) must become request-scoped or it carries the launch profile over anyway.
+ - Con: an index-level reach filter changes what local readers see unless gated carefully, and the "byte-identical at local reach" pin is hard to prove.
+ - Con: `Brain/rules/` pages sit outside the Brain-root refusal story of `standing-rules.ts`, so uneditability has to be re-argued.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: It is the only variant where identity, rule ranking and reach filtering each have exactly one owner, which is what the release theme demands and what the project's conventions already reward (closed vocabularies with a census, server-derived identity, failures named by class). Variant 1 is cheaper but leaves the harness vocabulary and project walk-up duplicated between hook and server, the exact kind of drift that lets one context carry over into another. Variant 3 reaches into search keys and the page index and would break the byte-identical pins the constraints require.
diff --git a/docs/brainstorm/scope-resolution/cli-output/expected-output.md b/docs/brainstorm/scope-resolution/cli-output/expected-output.md
new file mode 100644
index 00000000..b0d68171
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/cli-output/expected-output.md
@@ -0,0 +1,158 @@
+# Expected output, before and after
+
+Fixture: vault `<vault>` with `Brain/standing-rules.md`:
+
+```
+# Operator
+
+- Never push to main.
+```
+
+and, for the "after" blocks, `Brain/standing-rules/project/proj-x.md`:
+
+```
+- Run the Python suite before every commit in this project.
+```
+
+Two project directories `proj-x` and `proj-y`, each linked to `<vault>` with `o2b brain project link`. The "before" blocks marked "captured" were run on d49c4697 from the worktree with Bun 1.4.0; the "after" blocks are the target shape pinned by `plan.md`.
+
+## SessionStart hook preamble (`hooks/active-inject.ts`, payload `cwd` = `proj-x`)
+
+Before (captured; no memory layer yet, so only the constitution):
+
+```
+## Operator standing rules
+
+The rules below are written by the operator of this vault. They take precedence over every recalled preference, lesson and context pack that follows.
+
+# Operator
+
+- Never push to main.
+```
+
+After, payload `cwd` = `proj-x`:
+
+```
+## Operator standing rules
+
+The rules below are written by the operator of this vault. They take precedence over every recalled preference, lesson and context pack that follows.
+
+# Operator
+
+- Never push to main.
+
+## Scoped operator rules
+
+The rules below are written by the operator of this vault for this project, harness or host. The operator standing rules above take precedence over them, and they take precedence over every recalled preference, lesson and context pack that follows.
+
+### Project: proj-x
+
+- Run the Python suite before every commit in this project.
+```
+
+After, payload `cwd` = `proj-y`: byte-identical to the "before" block (no `project/proj-y.md`). A `harness/claude-code.md` file never renders in the hook.
+
+Receipt `budget` block of the `proj-x` run (default caps):
+
+```json
+{ "inject_budget_chars": 8000, "budgeted_source_count": 2, "scoped_rules_chars": <n> }
+```
+
+(`<n>` is the rendered scoped block's length; the active body was budgeted to `8000 - <n>`.)
+
+## `brain_context` (stdio server started in `proj-x` with `--harness claude-code`)
+
+Before: `content` starts with the standing block, then the memory body; the response has a `standing_rules` key and no `scoped_rules` key.
+
+After, local reach:
+
+```json
+{
+ "content": "## Operator standing rules\n\n...\n\n## Scoped operator rules\n\n...\n\n### Project: proj-x\n\n- Run the Python suite before every commit in this project.\n\n<memory body>",
+ "standing_rules": {
+ "path": "Brain/standing-rules.md",
+ "content": "# Operator\n\n- Never push to main.",
+ "truncated": false
+ },
+ "scoped_rules": {
+ "scope": { "project": "proj-x", "harness": "claude-code", "host": null },
+ "files": [
+ { "path": "Brain/standing-rules/project/proj-x.md", "axis": "project", "truncated": false }
+ ]
+ }
+}
+```
+
+(`host` is `null` here because the device id is the empty opt-out; other keys omitted.)
+
+After, remote reach (no reach minted): identical to the response of the same vault without `Brain/standing-rules/project/proj-x.md`, byte for byte after normalising `generated_at`: no scoped block in `content` and no `scoped_rules` key.
+
+## `o2b mcp --harness <id>`
+
+Before (captured):
+
+```
+$ o2b mcp --harness codex
+error: unknown flag: --harness
+(exit 2)
+```
+
+After:
+
+```
+$ o2b mcp --harness nope
+o2b mcp: invalid --harness value: "nope"; expected one of: aider, claude-code, codex, copilot-cli, cursor, gemini-cli, generic, grok, hermes, kiro, openclaw, opencode, pi
+(exit 2)
+```
+
+The existing `--host-target` refusal is unchanged (captured):
+
+```
+o2b mcp: invalid --host-target value: "nope"; expected one of: aider, codex, copilot-cli, cursor, gemini-cli, generic, grok, kiro, opencode, pi
+```
+
+## `hermes open-second-brain config`
+
+Before:
+
+```
+config_path: <config dir>/open-second-brain/config.toml
+vault: <vault>
+agent_name: <agent name from the process environment>
+timezone: (unset)
+```
+
+After, multiplexed gateway, profile scope bound with `VAULT_AGENT_NAME=profile-b-agent`, the launch profile's `VAULT_AGENT_NAME` set in the process environment:
+
+```
+settings_source: profile scope (multiplexed gateway)
+config_path: <config dir>/open-second-brain/config.toml
+vault: <vault>
+agent_name: profile-b-agent
+timezone: (unset)
+```
+
+After, single-profile gateway: `settings_source: process environment (this command; a gateway with gateway.multiplex_profiles reads each profile's .env)` as the first line, then the "before" block unchanged.
+
+`hermes open-second-brain status` keeps its three lines (`provider:`, `available:`, `vault:`); under multiplexing `vault:` is the profile's vault.
+
+Gateway log line (once per process per ignored name; the value is never shown):
+
+```
+WARNING plugins.hermes.config: open-second-brain: ignoring VAULT_AGENT_NAME from the gateway process environment on a multiplexed gateway; set it in the profile's .env instead
+```
+
+## `ProfileScopeError` (multiplexing on, no scope bound)
+
+```
+$ hermes open-second-brain config
+settings_source: profile scope (multiplexed gateway)
+error: OPEN_SECOND_BRAIN_CONFIG cannot be resolved: this multiplexed Hermes gateway bound no profile scope for the call, and Open Second Brain does not fall back to the gateway's process environment, which belongs to the launch profile. Restart the gateway (hermes gateway restart); if it persists, report it.
+(exit 2)
+```
+
+In the gateway log the same sentence follows Hermes's own `Memory provider plugin init failed:` prefix, and `prefetch` logs once:
+
+```
+WARNING plugins.hermes.provider: open-second-brain: no profile scope bound for this turn; the vault reminder is omitted
+```
diff --git a/docs/brainstorm/scope-resolution/cli-output/prompt.md b/docs/brainstorm/scope-resolution/cli-output/prompt.md
new file mode 100644
index 00000000..4fcb89b1
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/cli-output/prompt.md
@@ -0,0 +1,69 @@
+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
+
+One release of Open Second Brain whose theme is "a setting or a rule meant for one context must not carry over into another".
+
+1. Per-profile configuration for the Hermes memory plugin on multiplexed gateways. The Python plugin (`plugins/hermes/`) reads `VAULT_DIR`, `VAULT_AGENT_NAME`, `VAULT_TIMEZONE`, `OPEN_SECOND_BRAIN_CONFIG` (config.py) and `OPEN_SECOND_BRAIN_MCP_TIMEOUT` (bridge.py) straight from `os.environ`. A Hermes gateway with `multiplex_profiles: true` serves several profiles from one process; the process environment belongs to the launch profile. Hermes exposes `agent.secret_scope` with `is_multiplex_active()` and `get_secret(name, default)`, which reads the turn's bound profile scope and raises `UnscopedSecretError` when multiplexing is on and no scope is bound. The plugin also spawns one long-lived `o2b mcp` child per key `(vault, repo_root, command, PATH)` and gives it a copy of the gateway's environment, so the TypeScript core reads the launch profile's agent name and timezone from its inherited environment. `config.py` must stay importable without Hermes and without a package (a doctor check and a parity suite load it by file location and pin today's answers byte for byte). The plugin's existing `ConfigReadError` message is pinned by a parity test.
+
+2. Standing rules scoped to project, harness and host, ranked below the operator's vault-wide constitution (`Brain/standing-rules.md`, read by `readStandingRules`, injected first by the SessionStart hook and by the `brain_context` MCP tool, exempt from the injection budget, refused to every write tool by the Brain-root refusal and a named guard). Today the server resolves no project, harness or machine identity: the `project` scope axis comes from page frontmatter or a tool argument, "host" in the code means an install target (a harness), `clientInfo` from MCP initialize is never read, and the only machine identity is an 8-hex device id kept in device-local config. `o2b mcp` already accepts `--host-target <install target id>` written by install adapters; the Claude Code plugin, Hermes and OpenClaw launch it without that flag, and those three are not install targets. A linked project directory carries a `.o2b-vault.json` pointer. Results at remote reach (a caller with no minted reach) must not depend on content withheld from that caller.
+
+3. A small lane of reach left-overs from the previous release: the today brief view lists open loops (text and path) from pages hidden by visibility at remote reach; the monthly and operator brief views and two doctor counts (a removed-tool warning cap, a stale-dependency count) are computed over the whole layer.
+
+# Project context
+
+Open Second Brain, TypeScript on Bun 1.4.0 (part of src/ is also bundled for Node as the OpenClaw plugin), a Python 3.11 stdlib-only Hermes plugin, MCP server plus `o2b` CLI over an Obsidian-compatible Markdown vault.
+Recent commits:
+d49c4697 feat: ingest that reads CSV, TSV and HTML into table and parts sections, names the formats it skips and previews with o2b brain extract (v1.69.0) (#228)
+f5c46615 feat: dependency facts from project manifests, Terraform seeds in the pre-extractor and readers that answer at the caller's reach (v1.68.0) (#227)
+400b20ea feat: distillation pages that prove what they quote and say how much of their source the vault holds (v1.67.0)
+3ec2334a feat: stable error codes on the MCP wire, typed rerank degradation and a rerank doctor check (v1.66.0) (#225)
+a1ecfe7b feat: unattended maintenance recipes, install-owned lane tasks and an MCP fault guard (v1.65.0) (#224)
+4499698c feat: search that honours pins and event time, diagnostics that prove action, writes that name their residue (v1.64.0) (#223)
+a0b3c2e0 feat: exactly-one binding for mentions and imports, once-only write receipts, selectable search breadth and per-device ledgers (v1.63.0) (#222)
+f4f9e3e6 feat: silent failures surface by name in redaction, receipts, ingest, search store, doctor (v1.62.0) (#220)
+eb3c4c85 docs: concise README, ZCode client page, CLI reference and safety notes moved to child pages (#219)
+f22df2c5 chore(apb): zg search, code-ranker and OpenCodeReview before push, scope-scan hardening (#218)
+83979b9d fix: MCP startup off the upgrade path, fair ingest locks, inline plugin MCP manifest, inbox archive (v1.61.0) (#217)
+3e59f319 feat: decision-model uses, adapters and setup skill (v1.60.0) (#215)
+eacad953 feat: optional decision-model core and decision-model rerank kind (v1.59.0) (#214)
+0afa0c5a chore(deps): bump the bun-minor-and-patch group with 5 updates (#201)
+f6212cd2 fix: quiet one-line Stop reminder via Claude Code feedback channel (v1.58.2) (#202)
+534befdb chore(deps): bump the github-actions group with 3 updates (#200)
+5c550263 fix: session capture off the hook path, registry scanner hygiene (v1.58.1) (#199)
+6f33c424 feat: payload registry and knowledge packs, boundary hardening, CJK chunking (v1.58.0) (#197)
+a4d3ecf8 fix(codex): real plugin files and a truthful install check (v1.57.1) (#193)
+d7e6094a feat: a second platform (v1.57.0) (#191)
+Related files:
+- plugins/hermes/config.py, plugins/hermes/bridge.py, plugins/hermes/provider.py, tests/python/test_resolver_parity.py
+- src/core/brain/standing-rules.ts, src/core/brain/path-constants.ts, src/core/brain/paths.ts, src/core/scope-key.ts
+- hooks/active-inject.ts, src/mcp/brain/context-tools.ts, src/mcp/server.ts, src/mcp/tool-contract.ts, src/cli/main.ts
+- src/core/runtime/host-facts.ts, src/core/config.ts (resolveDeviceId), src/core/brain/portability/pointer.ts
+- src/core/brain/open-loops.ts, src/core/brain/today-dashboard.ts, src/core/brain/monthly-review.ts, src/core/brain/trust/operator-summary.ts, src/core/brain/doctor/*
+Conventions:
+- Closed vocabularies are frozen objects with a census test; named error classes with structured fields; operator text is opaque bytes; every failure surfaces by name.
+- Identity that decides scope is derived by the server, never named by the caller (precedent: origin channel, never a tool argument).
+- The version bump and the CHANGELOG entry ride inside the feature PR.
+Constraints:
+- No new runtime dependency, no `os.hostname()`, no host names in public text.
+- The vault-wide constitution file and its reader stay byte-identical; its header text and its budget exemption are pinned by tests.
+- `brain_context` takes no input argument (`additionalProperties: false`); no scope may be caller-named.
+- Local reach behaviour stays byte-identical for the left-overs; remote reach must not depend on withheld pages.
+- Without Hermes multiplexing the plugin must answer exactly as today.
+
+# 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/scope-resolution/design.md b/docs/brainstorm/scope-resolution/design.md
new file mode 100644
index 00000000..6e708c01
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/design.md
@@ -0,0 +1,165 @@
+# Per-context scope resolution - per-profile Hermes settings on multiplexed gateways, standing rules scoped to project, harness and host, and reach left-overs
+
+**Status:** draft (phase 1 spec review applied)
+**Author:** release orchestrator (via feature-release-playbook)
+**Audience:** implementation
+**Base:** origin/main d49c4697 (v1.69.0), branch `feat/scope-resolution`, target version 1.70.0 (minor)
+
+## Problem statement
+
+A setting or a rule meant for one context carries over into another in two places. First, the Hermes memory plugin reads `VAULT_DIR`, `VAULT_AGENT_NAME`, `VAULT_TIMEZONE`, `OPEN_SECOND_BRAIN_CONFIG` and `OPEN_SECOND_BRAIN_MCP_TIMEOUT` straight from `os.environ` (`plugins/hermes/config.py:358, :380, :406, :188`, `bridge.py:66`). On a Hermes gateway with `multiplex_profiles: true` one process serves several profiles and the process environment belongs to the launch profile, so a secondary profile writes into the launch profile's vault under the launch profile's agent name. Second, the operator's standing rules are one vault-wide file (`Brain/standing-rules.md`); a rule that holds for one project, one harness or one machine is injected into every session everywhere. A third, smaller gap carries over from v1.69.0: the today, monthly and operator brief views and two doctor counts answer over the whole Brain layer at remote reach, and the today view even returns the text and path of an open loop on a page the caller may not read.
+
+## Premise verification (live source, d49c4697)
+
+Full evidence: the three reconnaissance reports of this wave. The orchestrator re-opened the anchors this design builds on: `standing-rules.ts:60-217`, `text-budget.ts:24-146`, `active-inject.ts:160-200, 230-260, 309-430`, `policy/blocks/active.ts:50-145`, `context-tools.ts:365-554`, `server.ts:75-100`, `tool-contract.ts:111-152, 207`, `main.ts:760-790`, `host-facts.ts:61-90`, `config.ts:455-470`, `portability/pointer.ts:34-43, 123-133`, `plugins/hermes/bridge.py:255-294`, `plugins/hermes/config.py:100-127, 465-488`, `plugins/hermes/cli.py:40-100`, `provider.py:442-466`, `.claude-plugin/plugin.json`, `tests/mcp/plugin-mcp-servers.test.ts:33-40`, `operator-summary.ts:72-243`, `health-tools.ts:160-190`, and ran the current hook and the current `o2b mcp` flag validation (outputs in `cli-output/expected-output.md`).
+
+### Card 1 (per-profile Hermes plugin configuration) - confirmed, widened
+
+- Confirmed: nothing under `plugins/hermes` calls `get_secret`, `is_multiplex_active` or anything in `agent.secret_scope`. The Hermes contract (`is_multiplex_active()`, `get_secret(name, default)`, `UnscopedSecretError`) exists in the installed Hermes and Hermes's own memory plugins already follow the two-mode pattern.
+- Narrowed by the validator, applied: the variable names are `VAULT_AGENT_NAME` and `VAULT_TIMEZONE` (not the card's spellings); the anchors moved to `:358/:380/:406`.
+- Widened, carry-over 1: the `o2b mcp` child inherits a copy of the gateway environment (`provider.py:390-395, 419-439`), and the TypeScript core reads the agent name and timezone from that inherited environment (`src/core/config.ts:324-329, 395-402`). A plugin-side resolver alone would leave the core writing under the launch profile's name. The child environment must carry the scoped values.
+- Widened, carry-over 2: the shared-bridge key `(vault, repo_root, command, PATH)` (`provider.py:167-180`) holds no identity, so two profiles that share a vault but differ in agent name, timezone or config file would share one child and one identity.
+- Refuted detail of the card: "skip cron sessions". Hermes binds a profile scope for routed cron fires and marks them multiplexed (`cron/scheduler.py:3178, :3783`), so the two-mode rule covers cron with no special case. The note came from upstream code that is not available for inspection and is not adopted.
+
+### Card 2 (standing rules scoped to project, harness and host) - partly false, narrowed and built as narrowed
+
+The card made three claims that the source refutes:
+
+1. False: "`SCOPE_AXES` normalizes owner/session/project server-side". The axes are normalised there, but no value is resolved by the server: `project` comes from page frontmatter (`scopeFromFrontmatter`, `scope-key.ts:53-61`) or from a caller-named tool argument (`project_scope` on `brain_search` and the session-summary tool). No server-resolved project identity exists.
+2. False: "Open Second Brain already computes host probes (`second_brain_wiring view=hosts`)". "Host" in this code base means an install target, which is a harness (`INSTALL_TARGET_ID`, `host-facts.ts:61-72`), not a machine. Nothing calls `os.hostname()`; the only per-machine identity is the device id (`resolveDeviceId`, `config.ts:461`).
+3. False: "`src/mcp/server.ts:127` is the MCP scope method". That line is a request type. `handleInitialize` reads only `protocolVersion`; `clientInfo` is read nowhere in `src/`; `ServerContext` carries no project, harness or host.
+
+Narrowed: the scope identity is derived by the server from operator-owned or packaged facts only, the layer is single-axis files in a dedicated directory, harness-scoped files render on the MCP surfaces only, and the layer renders only at local reach.
+
+### Lane D (v1.69.0 reach left-overs) - confirmed, one item understated
+
+- Understated: the today view's open loops are not a count. At remote reach `open_loops.openLoops` lists the loop text and the path of a page withheld by visibility (probe through the real MCP server: `{"text":"zzreservedloopzz","path":"Notes/PRIVATE_PATH.md","line":6}`), because `scanOpenLoops` walks `walkMarkdownFiles` with no visibility predicate (`open-loops.ts:149-176`). docs/mcp.md:2180-2182 states the opposite and is false today.
+- Confirmed by A/B probe: the monthly view (`events 7 / status_transitions 4 / retired 1 / contradictions 1` against `2 / 1 / 0 / 0`) and the operator view (`preference_count 2/1`, `warnings 11/3`, `trust_verdict investigate/watch`) differ with and without withheld records at remote reach.
+- Confirmed by code: the removed-tool warning cap counts withheld candidates before the MCP filter (`removed-tool-checks.ts:37, 87-117`), and the stale-dependency note counts `states_changed` over the whole layer (`stale-dependency.ts:186, 211`).
+- The steer's expected lane (status triple, removed-tool cap and stale count, ranking statistics, the entity page naming a reserved source path) was overturned by the left-overs report's ranking: the today loops return content, so they come first; the status triple, the entity-page provenance and the ranking statistics are not small (see Out of scope).
+
+## Scope
+
+1. **Hermes plugin, two-mode settings.** Under multiplexing every profile-scoped setting comes from the turn's profile scope, never from the gateway process environment; without multiplexing the plugin answers exactly as today. A named `ProfileScopeError`, one value-free WARNING per ignored process-environment name, a scoped child environment, an identity-bearing shared-bridge key, a bridge timeout fixed at construction, and a degrading `prefetch`.
+2. **Scoped standing rules.** `Brain/standing-rules/{project,harness,host}/<key>.md`, one file per resolved scope value, rendered below the constitution and above recalled content, charged against the injection budget, refused to every write path, never cached, at local reach only.
+3. **Server-resolved scope identity.** Project from the nearest `.o2b-vault.json` pointer; harness from a new `o2b mcp --harness <id>` runtime option (falling back to `--host-target`), packaged into the Claude Code plugin registration and the Hermes bridge argv; host from the device id.
+4. **Surfaces.** The SessionStart hook (project and host only) and `brain_context` (all three axes, a new optional `scoped_rules` output key); `o2b mcp --harness`.
+5. **Reach left-overs.** The today view's open loops, the monthly view's counts, the doctor's removed-tool cap and stale-dependency count, and the operator view's doctor, digest, top-action and trust-verdict fields, each at the caller's reach with an A/B probe through the real MCP server.
+6. Docs, CHANGELOG, README, version 1.70.0.
+
+## Out of scope (deferred, by name)
+
+- **Combination scope files** (`project+host` and the like): the number of combinations grows quickly and no anchor needs them; the union of matching single-axis files covers the upstream `host:harness:project` triple.
+- **Harness-scoped files in the SessionStart hook**: the hook has no server-side harness signal (`CLAUDE_PLUGIN_ROOT` is exported by both Claude Code and Codex), and a per-harness marker on the hook command is constrained by the mirror sync's `o2b-hook <name>` fallback rule. Harness files render on the MCP surfaces only in this release.
+- **A standing-rules lane in OpenClaw**: OpenClaw runs in-process, never launches `o2b mcp`, and injects only an identity reminder (`src/openclaw/index.ts:58-75`); there is no lane to scope.
+- **Other variables the TypeScript core reads from the gateway environment** (search settings, `OPEN_SECOND_BRAIN_MCP_API_KEY`, embedding keys, `TELEGRAM_*`): they still come from the process environment on a multiplexed gateway. Hermes's `strip_launch_profile_env` is Hermes-internal and not adopted (see variants).
+- **The desktop routed-home case without multiplexing** (`serves_routed_profile` true, multiplex flag false): stays on `os.environ`, as in Hermes's own plugins.
+- **The pre-existing absolute path in the constitution's failure and truncation text** (`standing-rules.ts:254-276`): the constitution is byte-identical by contract; the new layer uses vault-relative paths only and does not copy the pattern.
+- **Status triple at reach** (`brain_status`, `second_brain_status`, `osb://status`): three surfaces, the census pin of `osb://status` as the only excluded resource, and index and vault-scope counts that stay whole-vault; a lane of its own.
+- **Entity page naming a reserved source path through summary-id provenance**: changing the provenance target changes which pages `brain_search_by_source` and `brain_delete_by_source` find at local reach (deletion semantics) and needs its own answer for `brain_intake_entities`.
+- **Two-call remote re-ingest**: needs a caller-lane summary identity across ingest, the manifest and source cleanup; a design, not a fix.
+- **Session tools' private-region model**: session turns carry no `visibility` field; a new model.
+- **Ranking statistics over withheld pages**: per-reader corpus statistics would change scores for every reader; no small hook.
+- **Operator view `dream_summary` at reach**: counts from a dry-run dream over the whole layer (and the dream warnings the trust verdict folds in); recomputing a dream at reach is not small. Stated as the remaining residual. (`verification_delta` moved to the caller's reach in D4, see below.)
+- **Tier-drift recount in the operator view**: `brain_doctor` below local reach recounts the tier-drift warning against the search index (`recountTierDrift` in `src/mcp/brain/health-tools.ts`); the operator view's doctor pass does not, so with a populated index the two warning counts can differ by that one row. It names no record; aligning them is a follow-up, not a content disclosure.
+
+## Chosen approach
+
+The consultant's Variant 2 ("one derived session identity, one rules ladder, one reach layer"), adjusted. Identity is derived in one server-owned place from facts the caller cannot name, the scoped layer is one reader beside the untouched constitution reader, and the Hermes plugin gains one internal reader that switches on the Hermes multiplex flag. Adjustments, with evidence:
+
+1. The constitution reader is not wrapped in a "ladder": `standing-rules.ts`, its header and its exemption are pinned byte for byte (`brain-context-standing-rules.test.ts:120-180`, `active-inject.test.ts:445-548`). The scoped reader is a second module whose block is joined after the constitution's.
+2. Identity never comes from `clientInfo` or MCP roots: both are named by the client about itself (tests send arbitrary names; Hermes sends a constant). The harness is a launch-time `--harness` argument written by the packager or installer.
+3. No `ReachLayer` object: the shipped pattern is a per-reader `readable` predicate that is omitted at local reach (`readableAtContextReachOrUndefined`), which keeps local reach byte-identical and the fast paths intact. Lane D threads that predicate per reader.
+4. No settings-source argument on the Hermes resolvers: the doctor parity check and the parity suite call them with no arguments by file location; one internal reader keeps their signatures and answers unchanged.
+5. The scoped layer renders at local reach only, the rule the consultant flagged as missing from its own variant.
+
+## Design decisions
+
+### Scoped rules (lane A substrate)
+
+- **S1 Layout.** `Brain/standing-rules/project/<key>.md`, `Brain/standing-rules/harness/<harness id>.md`, `Brain/standing-rules/host/<device id>.md`. One file per scope value, not frontmatter inside the constitution: the constitution reader may not branch on content (`standing-rules.ts:37-44`) and its file stays byte-identical. Under `Brain/` the files inherit the note-target refusal and the importer rejections at no cost.
+- **S2 Vocabularies.** `SCOPED_RULE_AXIS` (project, harness, host; census row) and a closed `HARNESS_ID` = every `INSTALL_TARGET_ID` member plus `claude-code`, `hermes`, `openclaw` (census row). `HARNESS_ID` is kept separate from `INSTALL_TARGET_ID` because `host-facts-census.test.ts` requires that vocabulary to equal the install adapter registry, and Claude Code, Hermes and OpenClaw have no install adapter. `SCOPE_AXES` is not extended: it feeds page dedup keys, hub-candidate pools and search filters (`scope-key.ts` consumers), all frontmatter-and-caller-named by design.
+- **S3 Key normaliser.** `scopedRuleKey(value)`: NFC, lowercase, NFC again, every run of characters outside `\p{L}\p{M}\p{N}` becomes `-` (amended in review, see "Review amendments"), leading and trailing `-` removed, capped at 64 characters, empty gives `null`. Unicode letters and digits are kept so a project name with no Latin characters still keys (`resolveSessionScope` throws on such names, `session-scope.ts:26-41`). No language is enumerated.
+- **S4 Reader.** `readScopedRules(vault, identity, {maxChars})` takes an already-resolved identity; an axis whose value is `null` matches nothing (fail closed). It reads at most one file per axis (one value per axis), ENOENT and an empty file are absence, any other read failure renders an `UNAVAILABLE: <vault-relative path> could not be read (<error code>).` line in that file's place, never an absolute path and never the error message (Node error messages carry absolute paths).
+- **S5 Rendering.** A code-authored header stating the precedence: the operator standing rules above take precedence over these rules, and these take precedence over every recalled preference, lesson and context pack that follows. Each file gets a subheading built only from the axis label and the key (`### Project: <key>`). The operator's bytes stay opaque.
+- **S6 Cap.** `active.scoped_rules_max_chars` (default 2000, min 200, max `STANDING_RULES_MAX_CHARS_MAX`), applied through `applySectionBudget` with one section per file and priority project 0, harness 1, host 2, so the host file drops first. The effective cap in the hook is `max(0, min(scoped_rules_max_chars, inject_budget_chars - SCOPED_RULES_HEADER.length - SCOPED_RULES_NOTICE_RESERVE))` so the whole block, header and notices included, can never exceed the budget it is charged against (amended in review, see "Review amendments"). When the cap cut anything a notice built from integers is appended.
+- **S7 Budget: charged, not exempt.** The constitution's exemption is argued as the constitution's own property (`standing-rules.ts:5-11`). The scoped block is a meter source `"scoped-rules"` on `LANE_BUDGETED`; its rendered length is subtracted from the `inject_budget_chars` handed to `assembleActiveContext` (floor 0); the receipt's `budget` block records `scoped_rules_chars` as a separate integer beside `inject_budget_chars`, which stays the configured value.
+- **S8 Placement.** Hook: after `renderStandingBlock`, outside the fail-open boundary, never cached (the inject cache key `"active"` is vault-wide, so a cached block could replay project X's rules in project Y). `brain_context`: after the standing block, before the memory body.
+- **S9 Uneditable.** `assertStandingRulesNotTargeted` refuses every path inside `Brain/standing-rules/` as well as the constitution file, lexically and then canonically (the nearest existing ancestor is canonicalised so a not-yet-existing file under a symlinked folder is caught), reusing `StandingRulesWriteRefusedError` with the concrete path. This covers all six guarded call sites (labels x2, attributes x2, marker write-back, write-session). No CLI verb writes the layer. Tool descriptions never name the directory; the uneditable test's substring check is extended to the directory.
+- **S10 Host notice.** When the device id cannot be read (`ConfigReadError`) and the host directory holds at least one file, the block carries one fixed sentence that host-scoped rules were not applied because the device id could not be read, naming `o2b brain doctor` for the cause, no value and no path. A device id of `""` (the explicit opt-out) is silent; `brain_context` still reports `scope.host: null`. Decided against the steer's runtime notice because the runtime-notice collector runs on every surface and has no identity input; the block is where the gap matters.
+
+### Identity (lane A resolves, lane B wires)
+
+- **I1 Project.** The basename of the directory holding the nearest `.o2b-vault.json` pointer found from the workspace directory (`findVaultPointer`), keyed by `scopedRuleKey`; no pointer or a malformed pointer gives `null`. The pointer is operator-written by `o2b brain project link` and already walked by every vault resolution; git remotes cost subprocesses and are absent outside git. The pointer must name the serving vault (amended in review, see "Review amendments").
+- **I2 Workspace directory.** Hook: payload `cwd`, falling back to `process.cwd()`. Stdio MCP server: `process.cwd()` captured once in `main.ts` and passed as the runtime option `workspaceDir` (injectable in tests). A server built without it resolves project `null`.
+- **I3 Harness.** `o2b mcp --harness <HARNESS_ID>`, validated against the closed list (unknown value: exit 2 with the list, the `--host-target` message shape), falling back to `--host-target` when absent (install targets are a subset of `HARNESS_ID`), else `null`. Packaged: the Claude Code plugin's two MCP registrations gain `--harness claude-code`; the Hermes bridge argv gains `--harness hermes`. The manifest file is owned by the release lane (it also carries the synced version), so one lane edits it. OpenClaw launches no `o2b mcp`. Install adapters already write `--host-target`, so no adapter changes. Never `clientInfo`, never a tool argument, never page frontmatter; a census test (modelled on `origin-channel-census.test.ts`) asserts no MCP tool schema property spells the harness.
+- **I4 Host.** `resolveDeviceId(configPath)`, read lazily only when the layer renders (local reach), `""` gives `null`, `ConfigReadError` gives `null` plus S10. Never `os.hostname()`: not stable, not unique, and host names must not reach public text.
+- **I5 Hook scope.** The hook resolves project and host only; the docs say plainly that harness-scoped files render on the MCP surfaces only in this release.
+
+### Surfaces (lane B)
+
+- **B1 `brain_context`.** `readScopedBlock(ctx)` beside `readStandingBlock`; its text joins after the standing block in `content`; optional output key `scoped_rules: {scope: {project, harness, host}, files: [{path, axis, truncated}]}` (vault-relative POSIX paths) present only when at least one file matched; no new input argument (`additionalProperties: false` stays).
+- **B2 Reach.** The layer renders only when `contextReach(ctx) === TRANSPORT_REACH.local`. At remote reach the server's cwd and device are not the caller's, so the block, the key and the device-id read are all skipped, and the output is byte-identical with and without scoped files.
+- **B3 `--harness` on the CLI manifest** (`command-manifest.ts`) so the help and the flag census see it.
+
+### Hermes plugin (lane C), per the Hermes reconnaissance section 4
+
+- **H1 Scoped names.** `PROFILE_SCOPED_ENV = (VAULT_DIR, VAULT_AGENT_NAME, VAULT_TIMEZONE, OPEN_SECOND_BRAIN_CONFIG, OPEN_SECOND_BRAIN_MCP_TIMEOUT)` beside the existing constants. `PATH`, `PATHEXT` and `HOME` stay process-global in both modes: they describe the OS. `XDG_CONFIG_HOME` and `LOCALAPPDATA` are scope-first, env-fallback (`SCOPE_FIRST_ENV`, read through `scope_first_setting`; review amendment): on a multiplexed gateway Hermes scopes them like any other `.env` name, so `config_path()` and `_windows_local_app_data()` read the bound scope's non-empty value and fall back to the process environment only when the scope has none (most installs, where the value is the OS's own); not multiplexed they read the process environment only. They stay out of `PROFILE_SCOPED_ENV`, which never falls back. The scoped MCP child receives the scope's value for both names, so it resolves the same config file as the plugin.
+- **H2 One reader.** `_env_setting(name)`: when a lazy, absolute, `try/except`-guarded `from agent.secret_scope import ...` succeeds and `is_multiplex_active()` is true, `get_secret(name, None)`; a miss (`None` or empty) falls through to the rest of the existing chain (pointer, active profile, config key, default), never to `os.environ`. Otherwise today's `os.environ.get(name)`, unchanged. `config.py` stays importable without a package (the doctor parity check and the parity suite load it by file location).
+- **H3 `ProfileScopeError(ConfigReadError)`.** Own `__init__` (the pinned `ConfigReadError` template is untouched), value-free message, attributes `name`, `path`, `reason`, raised `from` `UnscopedSecretError`. Every existing `ConfigReadError` catch site already does the right thing: `is_available` refuses and the refusal reaches the gateway log, `initialize` propagates, the wizard readback skips the field, the two CLI diagnostics print it and exit 2.
+- **H4 Warning.** Under multiplexing, for each scoped name with a non-empty `os.environ` value, one WARNING per process per name from `plugins.hermes.config`, never the value, deduplicated under a lock, with a test-only reset.
+- **H5 Child and key.** Under multiplexing `initialize` resolves vault, agent name, timezone, config path and timeout once under the bound scope; the child environment is the existing one with every scoped name removed and the resolved non-empty values set (`VAULT_DIR` only when the vault came from the scope). `McpBrainBridge(timeout=...)` so a restart from the plugin's own `sync_turn` thread never reads the environment. `_shared_bridge_key` gains agent name, timezone, config path and timeout; without multiplexing those are constant per process, so sharing is unchanged.
+- **H6 `prefetch` degrades** on `ProfileScopeError`: the reminder is omitted for that turn and a WARNING is logged once, matching `_safe_call`'s degrade policy, instead of failing the turn.
+- **H7 `shadowing_source`** under multiplexing checks the scope value and says the setting in this Hermes profile's `.env` overrides the config file; the non-multiplexed text is byte-identical.
+- **H8 `--harness hermes`** appended to the bridge argv after `--vault` and `--repo`.
+- **H9 Diagnostics.** `hermes open-second-brain config` prints one more line, `settings_source:`, naming `profile scope (multiplexed gateway)` or `process environment (this command; a gateway with gateway.multiplex_profiles reads each profile's .env)` (review amendment: the command runs in its own, never-multiplexed process), so an operator can see which source answered. Values are never printed for ignored names.
+- **H10 Cron** needs no special case (see premise verification).
+
+### Reach left-overs (lane D)
+
+- **D1 Today.** `ScanOpenLoopsOptions.readable` and `TodayDashboardOptions.readable`, tested before the file is read, so a withheld file is neither read nor counted in `scannedFiles`; obligations filtered by `readable("Brain/obligations/<slug>.md")`. Totals follow because they are arithmetic over the sections.
+- **D2 Monthly.** `BuildMonthlyReviewOptions.eventAtReach`, applied once to the event index before transitions, contradictions and neglected areas, the same `eventAtReach` rule the digest, today, timeline and the daily and weekly briefs use, so monthly and weekly counts agree over the same window.
+- **D3 Doctor.** `RunDoctorOptions.readable` and `DoctorCheckContext.readable` in core, because the cap and `states_changed` are computed inside the checks and the MCP-side filter cannot restore a slot the cap already spent. `StaleDependencyOptions.readable` filters states before `states_changed`.
+- **D4 Operator.** `BuildOperatorSummaryOptions.keepIssue`, `.readable`, `.keepAction`: doctor counts over kept issues, digest counts by readable path, top actions filtered by target before the top-N slice, verification-delta entries and their summary counts kept only when the caller may see the record and page each names (additive option `keepVerification`, added during implementation because the entries named withheld record ids and page paths and their counts drove the trust verdict), the trust verdict recomputed from the kept streams. `dream_summary` stays as the stated residual.
+- **D5** Every option is omitted at local reach (not passed as always-true), so local reach stays byte-identical. Each reader gets an A/B probe through the real MCP server at remote reach on `tests/helpers/reach-log-fixture.ts`, with evidence inside both the 24-hour and the 30-day windows, plus a local control that still sees the withheld item. The `brain_brief` and `brain_doctor` registry reasons are rewritten to state what remains; `brain_brief` stays `excluded`.
+
+### Release and docs (lane E)
+
+- Version 1.70.0 (minor: additive output key, additive CLI flag, additive Hermes contract). CHANGELOG `## [1.70.0]` with the link reference; README release paragraph; `docs/how-it-works.md`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/observability.md`, `docs/stability.md`, `install/hermes.md` (a "Multiple Hermes profiles" subsection with the install-shadowing pitfall), `docs/updating.md` ("Upgrading to 1.70.0": update `o2b` and the Hermes plugin together, because the bridge now passes `--harness`).
+- Residuals stated in the CHANGELOG: other variables the TypeScript core reads from the gateway environment; the Hermes shared bridge resolves the gateway's working directory, so it usually renders no project-scoped file; the routed-home case without multiplexing; combination scope files; harness-scoped files in the SessionStart hook; operator `dream_summary`; the deferred left-overs above.
+
+## File changes
+
+New:
+
+- `src/core/brain/scoped-rules.ts`, `src/core/brain/scope-identity.ts`
+- `tests/core/brain/scoped-rules.test.ts`, `tests/core/brain/scope-identity.test.ts`, `tests/core/brain/scoped-rules-guard.test.ts`
+- `tests/hooks/active-inject-scoped-rules.test.ts`, `tests/mcp/brain-context-scoped-rules.test.ts`, `tests/core/architecture/harness-identity-census.test.ts`, `tests/cli/mcp-harness-flag.test.ts`
+- `tests/python/test_profile_scope.py`
+- `tests/mcp/today-open-loops-reach.test.ts`, `tests/mcp/brief-monthly-reach.test.ts`, `tests/mcp/doctor-counts-reach.test.ts`, `tests/mcp/brief-operator-reach.test.ts`
+
+Changed: see plan.md "File ownership" (every file is owned by exactly one lane).
+
+## Risks and open questions
+
+- **Stale `o2b` on PATH with a new Hermes plugin.** The bridge prefers an `o2b` found on PATH (`provider.py:461-465`); an older binary refuses `--harness` with `unknown flag` and the bridge fails to start. The failure is explicit (the stderr tail names the flag), not silent; `docs/updating.md` and `install/hermes.md` say to update both together. Accepted.
+- **Budget arithmetic.** With a small `inject_budget_chars` and a full scoped layer the active body can shrink to zero; that is the operator's configuration and the receipt shows both integers. The hook test pins the arithmetic.
+- **Device id first use.** `resolveDeviceId` may generate and persist an id on first use; the log writers already do the same on every vault, so the scoped reader adds no new write. The test preload pins `O2B_DEVICE_ID=""`; host tests set it per test through `tests/helpers/device-id.ts`.
+- **Receipt `budgeted_source_count`** now counts the scoped source when it rendered; the docs state that the scoped source is subtracted, not charged against the full ceiling.
+- **Degraded hook runs** keep the sources produced outside the fail-open boundary (the standing and the scoped rules) in the receipt items; `scoped_rules_chars` is recorded only on measured runs, matching the existing budget block (amended in review, see "Review amendments").
+- No open questions remain; every decision named in the reconnaissance reports is settled above.
+
+## Review amendments (pre-engine review, round 1)
+
+- **S3 amended: combining marks are key characters.** The pinned run `[^\p{L}\p{N}]` treated every combining mark as a separator, so `हिन्दी` keyed to `ह-न-द`, `مُحَمَّد` to `م-ح-م-د` and `İstanbul` to `i-stanbul`, and distinct names collided. The run is now `[^\p{L}\p{M}\p{N}]`, and the value is normalised to NFC again after lowercasing (lowercasing can decompose: `İ` lowercases to `i` plus U+0307, which NFC cannot recompose, so that key keeps the mark). `Café` and `café` both key to `café`. The file lookup and the project basename still use the one function, so lookup stays a fixed point.
+- **I1 amended: the pointer must name the serving vault.** A pointer that names another vault, or is malformed, no longer stops the walk: `resolveProjectScope(workspaceDir, servingVault)` keeps walking up and accepts the nearest pointer whose vault has the same real path as the serving vault, else `null`. Without it, a repository cloned under a linked project could ship a committed `.o2b-vault.json` and so choose or suppress the project scope of every session started inside it. `brain_context` passes its vault and the hook passes the vault it resolved.
+- **S6 amended: the header and the notices ride inside the injection budget.** The cap covered the sections only, so with `inject_budget_chars` at or below `scoped_rules_max_chars` the block (a 274-character header plus the notices) overshot the budget it is charged against. The hook now reserves the header and `SCOPED_RULES_NOTICE_RESERVE` (the separators, the longest truncation notice and the host notice, derived from the notice texts) before applying the cap, floor 0. `brain_context` has no injection budget and keeps the configured cap. A section whose body cannot fit under the cap is dropped whole and reported truncated, never left as a bare `### <Axis>: <key>` heading (the section budgeter's additive `headLines` option).
+- **Receipts amended.** A degraded hook run keeps the `scoped-rules` item beside `standing-rules`: both are produced outside the fail-open boundary and reach the payload (an `outsideBoundary` flag on the meter source, not the lane). A measured run whose only budgeted source is the scoped block (no `active.md`) now carries the `budget` block with `scoped_rules_chars`.
+- **Escaping symlinks render as unavailable.** A scoped rule file or axis folder that is a symlink leaving the vault fails the containment check; that check now runs inside the per-file read, so the file renders the `UNAVAILABLE: <vault-relative path> could not be read (ESCAPE).` line instead of failing `brain_context` with an absolute path, and `brain_context` keeps the constitution and the memory layer if the scoped reader still throws. A symlinked axis folder INSIDE the vault is followed at local reach by design: local reach reads everything the operator put in the vault.
+- **Write guard compared like for like.** Both sides of the scoped directory check resolve through the nearest existing ancestor (a directory that does not exist yet under a symlinked vault root compared lexically before), through the native realpath (on-disk casing), and case-folded on macOS and Windows for the tail that does not exist yet.
+- **Receipts at the caller's reach.** Below local reach `brain_context_receipts` drops the `standing-rules` and `scoped-rules` items of an injection receipt and every figure that counts or measures them (item count, whole-text hash and lengths, `total_bytes`, `total_tokens`, `scoped_rules_chars`, `budgeted_source_count`); `summary` leaves them out of its item totals. `summary` folds without the rule items, so a degraded injection that kept only the rules counts as an empty receipt; a measured injection receipt whose every item was a rule block (a session with no `active.md` body) is withheld whole: `list` and `summary` leave it out and `show` answers `receipt not found`; the `budget` block leaves a receipt with no budgeted body left.
+- **CLI refusals quote the value.** `o2b mcp --harness` and `--host-target` print a refused value with `JSON.stringify`.
+- **Residual, by design: the device id in the scoped block.** At local reach the `### Host: <device id>` heading, `scoped_rules.scope.host` and the rule path carry the device id. The id already names the log shards in the vault and is never the host name; an operator who sets `O2B_DEVICE_ID` to a machine name chooses to have that value in the model context.
+- **Residual, by design: the body figures of an over-budget receipt.** Below local reach a receipt keeps its `active-body` and `lessons-body` items, but when the scoped block shrank the memory budget enough to force a trim of an over-budget `active.md` body, those items' `bytes` and `tokens` still describe the trimmed body. Only an over-budget body is affected, and the difference is inherent to charging the rules against the injection budget; the rule items themselves and every figure that counts them are withheld as stated above.
+- **The host notice on `brain_context` (corrected by the self review).** The `hostUnreadable` arm of `readScopedBlock` is reachable through the tool: a readable config that holds no device id, in a directory that cannot be written, makes the first-use id impossible to persist, and the call renders the notice with `scope.host: null` (pinned in `tests/mcp/brain-context-scoped-rules.test.ts`). An unreadable config file still fails the call with `config_unreadable`, and a config home that cannot be created fails it through the vault reference (`vault_path` needs the installation key in the same home), before the scoped block is built.
+- **Deferred, unchanged from the design:** the status triple at reach, entity-page provenance, the two-call remote re-ingest, the session private-region model, ranking statistics over withheld pages, and the operator view's `dream_summary` counts.
diff --git a/docs/brainstorm/scope-resolution/plan.md b/docs/brainstorm/scope-resolution/plan.md
new file mode 100644
index 00000000..12deea17
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/plan.md
@@ -0,0 +1,298 @@
+# Per-context scope resolution - implementation plan
+
+Design: `docs/brainstorm/scope-resolution/design.md` (decision ids S*, I*, B*, H*, D* below refer to its "Design decisions").
+
+## How to run this plan
+
+Five lanes with DISJOINT file ownership run concurrently in the one worktree. Lane A (TypeScript substrate) commits first; lane B waits only on the lane A file named in its task's "Depends on"; lanes C, D and E wait on nothing. A lane edits only the files listed for it under "File ownership".
+
+Every task is TDD: write the named test first, run it and see it fail for the stated reason, implement, see it pass, then format and lint the lane's own files only (`bunx oxfmt <files>` and `bunx oxlint -c oxlint.json <files>` for TypeScript; `python3 -m compileall -q plugins/hermes` for Python (this machine has Python 3.14 and no 3.11; CI runs 3.11, so use no syntax newer than 3.11)), then ONE step `git commit --only <own paths> -m "<conventional message>"`. Retry on `index.lock`; after five pre-commit rejections caused by another lane's files, check your own files and commit with `--no-verify`.
+
+Shared settings for every lane:
+
+- `export TMPDIR=$HOME/.cache/osb-wave-20261003a/tmp` (mkdir -p) and `PATH="$HOME/.cache/osb-pr-prepare/bun-1.4.0/bun-linux-x64:$PATH"` (Bun 1.4.0, the CI pin).
+- Per-task gates: `bun test <the task's test files>` and, for TypeScript lanes, `bun run typecheck`. Never the whole suite; the integrator runs the full gates once.
+- Tests compare vault-relative POSIX paths and basenames, never absolute paths (Windows CI); a path embedded in JSON is normalised with `replaceAll("\\\\", "/")`.
+- No identifier containing `secret`, `token`, `api_key` or `password` before `=` or `:` and a quoted literal, in TypeScript and Python. Reserved-page fixtures are named `PRIVATE_PATH`, `PRIVATE_BODY`, `privateBody`; credential-shaped literals come from `fakeCredential()`.
+- No new runtime dependency. No `os.hostname()`.
+
+Dependency-wait rule for lane B: before a task that depends on a lane A file, poll `git log --oneline -- <file>` every 30 s, up to 15 min, until lane A's commit of that file appears; if it does not, stop and report the wait as the failure.
+
+Dependencies:
+
+- A1 -> A2 -> A3 -> A4 (one lane, in order).
+- A1 + A2 -> B1 -> B2; A3 -> B3; B2 + A4 + E1 -> B4 (B4 waits on lane E's E1 commit of `.claude-plugin/plugin.json`).
+- C1 -> C2 -> C3 -> C4 (no dependency on A or B; C4 pins the argv from this contract).
+- D1 -> D2 -> D3 -> D4 (independent).
+- E1, E2, E3 (independent; they describe this contract, not the code).
+
+The OpenClaw bundle (`openclaw/index.js`) belongs to no lane: the integrator runs `bun run build:openclaw` after the last `src/` change and commits it last if it changed.
+
+## Cross-lane contract (pinned now; no lane renames or re-spells any of this)
+
+### `src/core/brain/path-constants.ts` and `src/core/brain/paths.ts` (lane A, A1)
+
+- `export const BRAIN_SCOPED_RULES_DIR = "standing-rules";` (a directory under `Brain/`, beside `BRAIN_STANDING_RULES_FILE = "standing-rules.md"`).
+- `export function brainScopedRulesDir(vault: string): string` - absolute `<vault>/Brain/standing-rules`.
+- `export function brainScopedRulePath(vault: string, axis: ScopedRuleAxis, key: string): string` - absolute `<vault>/Brain/standing-rules/<axis>/<key>.md`.
+
+### `src/core/brain/scoped-rules.ts` (lane A, A1-A2)
+
+- `export const SCOPED_RULE_AXIS = Object.freeze({ project: "project", harness: "harness", host: "host" } as const);` `export type ScopedRuleAxis`; `export const SCOPED_RULE_AXES: ReadonlyArray<ScopedRuleAxis>` = project, harness, host (this order = drop priority 0, 1, 2); `export function isScopedRuleAxis(value: unknown): value is ScopedRuleAxis`. Census row `SCOPED_RULE_AXIS` in `tests/core/architecture/verdict-vocabulary-census.test.ts`.
+- `export const SCOPED_RULE_AXIS_LABEL: Readonly<Record<ScopedRuleAxis, string>> = Object.freeze({ project: "Project", harness: "Harness", host: "Host" });`
+- `export const HARNESS_ID = Object.freeze({ ...INSTALL_TARGET_ID, claudeCode: "claude-code", hermes: "hermes", openclaw: "openclaw" } as const);` `export type HarnessId`; `export const HARNESS_IDS: ReadonlyArray<HarnessId>` sorted alphabetically: aider, claude-code, codex, copilot-cli, cursor, gemini-cli, generic, grok, hermes, kiro, openclaw, opencode, pi; `export function isHarnessId(value: unknown): value is HarnessId`. Census row `HARNESS_ID`. `INSTALL_TARGET_ID` and `host-facts-census.test.ts` are untouched.
+- `export const SCOPED_RULE_KEY_MAX_CHARS = 64;` `export function scopedRuleKey(value: string): string | null` - `value.normalize("NFC").toLowerCase().normalize("NFC")`, every run matching `/[^\p{L}\p{M}\p{N}]+/gu` replaced by `-` (amended in review: combining marks are key characters, see design.md "Review amendments"), leading/trailing `-` stripped, sliced to 64 then trailing `-` stripped again, `""` gives `null`.
+- `export const SCOPED_RULES_MAX_CHARS_DEFAULT = 2000;` `export const SCOPED_RULES_MAX_CHARS_MIN = 200;` `export const SCOPED_RULES_MAX_CHARS_MAX = STANDING_RULES_MAX_CHARS_MAX;`
+- `export const SCOPED_RULES_HEADER = "## Scoped operator rules\n\n" + "The rules below are written by the operator of this vault for this project, harness or host. " + "The operator standing rules above take precedence over them, and they take precedence over every recalled preference, lesson and context pack that follows.";`
+- Per-file subheading: `` `### ${SCOPED_RULE_AXIS_LABEL[axis]}: ${key}` ``.
+- Unreadable file line (in place of the body): `` `UNAVAILABLE: ${relPath} could not be read (${code}).` `` where `code` is `err.code` when it is a string, else `err.name`; never the error message, never an absolute path.
+- Truncation notice (appended after a blank line when the cap cut anything): `` `_Scoped rules truncated to the configured cap: kept ${keptChars} of ${totalChars} characters, ${droppedFiles} file(s) dropped._` ``
+- `export const SCOPED_RULES_HOST_UNREADABLE_NOTICE = "Host-scoped rules were not applied: this device's id could not be read. Run o2b brain doctor for the cause.";` (appended as the last line of the block, only when `hostUnreadable` is true AND `Brain/standing-rules/host/` holds at least one `.md` file; when no file matched but the notice applies, the block is the header plus the notice).
+- `export interface ScopedRuleIdentity { readonly project: string | null; readonly harness: HarnessId | null; readonly host: string | null }`
+- `export interface ScopedRuleFile { readonly axis: ScopedRuleAxis; readonly key: string; readonly path: string; readonly truncated: boolean }` - `path` vault-relative POSIX (`Brain/standing-rules/project/x.md`); a file dropped whole by the cap is listed with `truncated: true`; an unreadable file is listed with `truncated: false`.
+- `export interface ScopedRules { readonly identity: ScopedRuleIdentity; readonly files: ReadonlyArray<ScopedRuleFile>; readonly text: string }` - `text` is the rendered block (header, sections, optional truncation notice, optional host notice), `""` when nothing matched and no notice applies.
+- `export interface ReadScopedRulesOptions { readonly maxChars?: number; readonly hostUnreadable?: boolean }`
+- `export function readScopedRules(vault: string, identity: ScopedRuleIdentity, opts?: ReadScopedRulesOptions): ScopedRules` - never throws for a per-file read failure; budget through `applySectionBudget` with section keys `` `${axis}:${key}` `` and priority = index in `SCOPED_RULE_AXES`; the header and notices are not counted against the cap.
+
+### `src/core/brain/standing-rules.ts` guard (lane A, A3)
+
+- `assertStandingRulesNotTargeted(vault, notePath, surface)` keeps its signature and now also throws `StandingRulesWriteRefusedError(<absolute candidate path>, surface)` for any candidate equal to or inside `brainScopedRulesDir(vault)`, compared lexically and then canonically (canonicalise the nearest existing ancestor and re-append the missing tail). Error class, `name`, fields and message template unchanged.
+
+### `src/core/brain/scope-identity.ts` (lane A, A2)
+
+- `export function resolveProjectScope(workspaceDir: string | null, servingVault: string): string | null` - walks `findVaultPointer` up from `workspaceDir`; the first pointer whose vault has the serving vault's real path gives `scopedRuleKey(basename(probe.dir))`; a pointer naming another vault or a malformed one is skipped; `null` for a null dir or when none matches (amended in review, see design.md "Review amendments").
+- `export interface HostScope { readonly host: string | null; readonly unreadable: boolean }`
+- `export function resolveHostScope(configPath: string | undefined): HostScope` - `resolveDeviceId(configPath)`; `""` gives `{host: null, unreadable: false}`; a thrown `ConfigReadError` gives `{host: null, unreadable: true}`; any other throw propagates; a value gives `{host: scopedRuleKey(id), unreadable: false}`.
+- `export function resolveHarnessScope(harness: HarnessId | undefined, hostTarget: InstallTargetId | undefined): HarnessId | null` - `harness ?? hostTarget ?? null`.
+
+### Config knob (lane A, A4)
+
+- YAML key `active.scoped_rules_max_chars`; `KNOWN_KEYS` gains `"scoped_rules_max_chars"`; parsed by `optionalCharCount` with `SCOPED_RULES_MAX_CHARS_MIN` and `SCOPED_RULES_MAX_CHARS_MAX`; `BrainActiveConfig.scoped_rules_max_chars?: number` in `types.ts`; `export function resolveScopedRulesMaxChars(cfg: BrainConfig | null): number` in `policy/blocks/active.ts`, re-exported from `policy.ts`; template entry `def("scoped_rules_max_chars", SCOPED_RULES_MAX_CHARS_DEFAULT)` with a comment that it is charged against `inject_budget_chars`; ratchet row `active_scoped_rules_max_chars`.
+
+### Server and CLI (lane B)
+
+- CLI flag `--harness <id>` on `o2b mcp` (`main.ts` option table `"harness": { type: "string" }`, `command-manifest.ts` `flag("harness", "string")`). Invalid value: stderr `` `o2b mcp: invalid --harness value: ${JSON.stringify(value)}; expected one of: ${HARNESS_IDS.join(", ")}\n` ``, exit 2 (amended in review: the value is JSON-quoted, as in the `--host-target` refusal).
+- `MCPServerRuntimeOptions.harness?: HarnessId` and `MCPServerRuntimeOptions.workspaceDir?: string` (`main.ts` passes `process.cwd()` captured once).
+- `ServerContext.ruleScope?: RuleScopeSources` with `export interface RuleScopeSources { readonly workspaceDir: string | null; readonly harness: HarnessId | null }` in `src/mcp/tool-contract.ts`; the server sets `harness` to `resolveHarnessScope(opts.harness, opts.hostTarget)`.
+- `brain_context` output key (optional, present only when at least one file matched or the host notice applies): `scoped_rules: { scope: { project: string | null, harness: string | null, host: string | null }, files: Array<{ path: string, axis: "project" | "harness" | "host", truncated: boolean }> }`. Added to `BRAIN_CONTEXT_OUTPUT_SCHEMA`. No input property. Rendered only when `contextReach(ctx) === TRANSPORT_REACH.local`.
+- Hook: meter source name `SOURCE_SCOPED_RULES = "scoped-rules"` on `LANE_BUDGETED`; receipt `budget` block gains `scoped_rules_chars: number` (the rendered scoped block length; `0` when absent) beside the unchanged `inject_budget_chars` and `budgeted_source_count`. `assembleActiveContext` receives `max(0, injectBudgetChars - scopedBlock.length)`; the scoped cap is `min(scopedRulesMaxChars, injectBudgetChars)`, amended by the review to `max(0, min(scopedRulesMaxChars, injectBudgetChars - SCOPED_RULES_HEADER.length - SCOPED_RULES_NOTICE_RESERVE))` so the header and the notices ride inside the budget (design S6 amended).
+- Packaged args, `.claude-plugin/plugin.json` (written by lane E in E1, asserted by lane B in B4): `"args": ["mcp", "--harness", "claude-code"]` and `"args": ["mcp", "--scope", "writer", "--harness", "claude-code"]`.
+
+### Hermes plugin (lane C)
+
+- `config.PROFILE_SCOPED_ENV: tuple[str, ...] = (VAULT_DIR_ENV, AGENT_NAME_ENV, TIMEZONE_ENV, CONFIG_PATH_ENV, "OPEN_SECOND_BRAIN_MCP_TIMEOUT")` (the timeout name moves into config.py as `REQUEST_TIMEOUT_ENV`; bridge.py imports it).
+- `config.is_multiplexed() -> bool`; `config.env_setting(name: str) -> str | None` (the one reader; empty counts as unset).
+- `config.SCOPE_FIRST_ENV: tuple[str, ...] = (XDG_CONFIG_HOME_ENV, LOCALAPPDATA_ENV)` and `config.scope_first_setting(name: str) -> str | None` (review amendment): multiplexed, the bound scope's non-empty value, else `os.environ`; not multiplexed, `os.environ` only; unbound raises `ProfileScopeError`. `config_path()` and `_windows_local_app_data()` read through it, and the scoped MCP child env carries the scope's value for both names. `PATH`, `PATHEXT` and `HOME` stay process-global.
+- `class ProfileScopeError(ConfigReadError)` with `__init__(self, name: str)`, attributes `name`, `path` (`""`), `reason` (`"no profile scope bound"`), message: `"{name} cannot be resolved: this multiplexed Hermes gateway bound no profile scope for the call, and Open Second Brain does not fall back to the gateway's process environment, which belongs to the launch profile. Restart the gateway (hermes gateway restart); if it persists, report it."`
+- WARNING template (logger `plugins.hermes.config`): `"%s: ignoring %s from the gateway process environment on a multiplexed gateway; set it in the profile's .env instead"` with `PLUGIN_NAME` and the name; test reset `config._reset_scope_warnings_for_tests()`.
+- `prefetch` degrade WARNING (logger `plugins.hermes.provider`, once per process): `"%s: no profile scope bound for this turn; the vault reminder is omitted"` with `PROVIDER_NAME`.
+- Multiplexed `shadowing_source` text: `"the {env_key} setting in this Hermes profile's .env overrides the config file"`.
+- `McpBrainBridge(..., timeout: float | None = None)`; `start` uses it when not `None`, else `resolve_request_timeout()` as today.
+- `bridge.HARNESS_ARGV = ("--harness", "hermes")`; `_argv()` = command, then `--vault <v>` when set, then `--repo <r>` when set, then `--harness hermes`.
+- `cli._config` prints `settings_source: profile scope (multiplexed gateway)` or `settings_source: process environment (this command; a gateway with gateway.multiplex_profiles reads each profile's .env)` (review amendment) as its FIRST line (it cannot raise), then `config_path:`; `config_path()` moves inside the `try`, because under multiplexing it reads `OPEN_SECOND_BRAIN_CONFIG` through `env_setting` and can raise `ProfileScopeError`.
+
+### Lane D options (lane D)
+
+- `ScanOpenLoopsOptions.readable?: (rel: string) => boolean`; `TodayDashboardOptions.readable?: (rel: string) => boolean`.
+- `BuildMonthlyReviewOptions.eventAtReach?: (event: LogEvent) => LogEvent | null` (the same signature `TodayDashboardOptions.eventAtReach` uses today; copy its type, do not widen it).
+- `RunDoctorOptions.readable?` and `DoctorCheckContext.readable?: (rel: string) => boolean`; `StaleDependencyOptions.readable?: (rel: string) => boolean`.
+- `BuildOperatorSummaryOptions.keepIssue?: (issue: DoctorIssueNaming) => boolean`, `.readable?: (rel: string) => boolean`, `.keepAction?: (action: ActionItem) => boolean`.
+- Every option is omitted at local reach; handlers pass `readableAtContextReachOrUndefined(ctx)` / `requestRefView(ctx)` only when it filters something.
+
+### Docs vocabulary (lane E)
+
+- Section headings: in `docs/how-it-works.md` `### Scoped operator rules`; in `install/hermes.md` `### Multiple Hermes profiles`; in `docs/updating.md` `## Upgrading to 1.70.0`; CHANGELOG `## [1.70.0] - 2026-10-03` and `[1.70.0]: https://github.com/itechmeat/open-second-brain/compare/v1.69.0...v1.70.0`.
+- The docs never name the directory in any MCP tool description (lane B owns descriptions; they do not change).
+
+## File ownership
+
+Lane A (TypeScript substrate, commits first):
+
+- `src/core/brain/path-constants.ts`, `src/core/brain/paths.ts`, `src/core/brain/scoped-rules.ts` (new), `src/core/brain/scope-identity.ts` (new), `src/core/brain/standing-rules.ts`
+- `src/core/brain/policy/blocks/active.ts`, `src/core/brain/policy.ts`, `src/core/brain/types.ts`, `src/core/brain/config-template.ts`
+- `tests/core/brain/scoped-rules.test.ts` (new), `tests/core/brain/scope-identity.test.ts` (new), `tests/core/brain/scoped-rules-guard.test.ts` (new), `tests/core/architecture/verdict-vocabulary-census.test.ts`, `tests/core/brain/policy-active.test.ts`, `tests/core/brain/config-template-ratchet.test.ts`
+
+Lane B (TypeScript surfaces):
+
+- `hooks/active-inject.ts`, `src/mcp/brain/context-tools.ts`, `src/mcp/server.ts`, `src/mcp/tool-contract.ts`, `src/cli/main.ts`, `src/cli/command-manifest.ts`
+- `tests/hooks/active-inject-scoped-rules.test.ts` (new), `tests/mcp/brain-context-scoped-rules.test.ts` (new), `tests/core/architecture/harness-identity-census.test.ts` (new), `tests/cli/mcp-harness-flag.test.ts` (new), `tests/mcp/plugin-mcp-servers.test.ts`, `tests/mcp/brain-standing-rules-uneditable.test.ts`
+
+Lane C (Hermes Python plugin):
+
+- `plugins/hermes/config.py`, `plugins/hermes/bridge.py`, `plugins/hermes/provider.py`, `plugins/hermes/cli.py`
+- `tests/python/test_profile_scope.py` (new), `tests/python/test_memory_provider.py`
+
+Lane D (reach left-overs):
+
+- `src/core/brain/open-loops.ts`, `src/core/brain/today-dashboard.ts`, `src/core/brain/monthly-review.ts`, `src/core/brain/trust/operator-summary.ts`, `src/core/brain/doctor/report.ts`, `src/core/brain/doctor/check.ts`, `src/core/brain/doctor.ts`, `src/core/brain/doctor/removed-tool-checks.ts`, `src/core/brain/stale-dependency.ts`, `src/mcp/brain/brief-tools.ts`, `src/mcp/brain/health-tools.ts`, `src/core/search/visibility-surface-registry.ts`
+- `tests/mcp/today-open-loops-reach.test.ts` (new), `tests/mcp/brief-monthly-reach.test.ts` (new), `tests/mcp/doctor-counts-reach.test.ts` (new), `tests/mcp/brief-operator-reach.test.ts` (new), `tests/core/brain/today-dashboard.test.ts`
+
+Lane E (docs and release):
+
+- `docs/how-it-works.md`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/observability.md`, `docs/stability.md`, `docs/updating.md`, `install/hermes.md`, `README.md`, `plugins/codex/README.md` (generated mirror), `CHANGELOG.md`, `package.json`, `.claude-plugin/plugin.json` (both the version that `sync-version.ts` writes and the packaged `--harness claude-code` args pinned in the contract, so one lane owns the whole file) and the other files `scripts/sync-version.ts` regenerates (`plugin.yaml`, `plugins/hermes/plugin.yaml`, `.codex-plugin/plugin.json`, `plugins/codex/.codex-plugin/plugin.json`, `openclaw.plugin.json`, `pyproject.toml`, `uv.lock`).
+
+Integrator only: `openclaw/index.js`.
+
+## Tasks
+
+### Lane A - substrate
+
+#### Task A1: Vocabularies, key normaliser and paths
+
+- **Files**: `src/core/brain/path-constants.ts`, `src/core/brain/paths.ts`, `src/core/brain/scoped-rules.ts` (vocabularies, `scopedRuleKey`, constants only), `tests/core/brain/scoped-rules.test.ts`, `tests/core/architecture/verdict-vocabulary-census.test.ts`
+- **Failing first**: `scopedRuleKey("プロジェクト 2")` is `"プロジェクト-2"` and `scopedRuleKey("Έργο Άλφα")` is `"έργο-άλφα"`, `scopedRuleKey(" My_Repo.v2 ")` is `"my-repo-v2"`, `scopedRuleKey("---")` is `null`, a 100-character name keys to at most 64 characters; `HARNESS_IDS` equals the alphabetical list and contains every `INSTALL_TARGET_IDS` member; `brainScopedRulePath(vault, "project", "x")` ends in `Brain/standing-rules/project/x.md` after separator normalisation; census rows `SCOPED_RULE_AXIS` and `HARNESS_ID` pass. Fails on the missing module.
+- **Commands**: `bun test tests/core/brain/scoped-rules.test.ts tests/core/architecture/verdict-vocabulary-census.test.ts tests/core/architecture/host-facts-census.test.ts && bun run typecheck`
+- **Commit**: `feat(brain): add the scoped-rule axis and harness vocabularies`
+- **Depends on**: none
+
+#### Task A2: Identity resolvers and the scoped reader
+
+- **Files**: `src/core/brain/scope-identity.ts`, `src/core/brain/scoped-rules.ts` (reader and renderer), `tests/core/brain/scope-identity.test.ts`, `tests/core/brain/scoped-rules.test.ts`
+- **Failing first**: (1) a temp project dir linked with `writeVaultPointer` resolves `resolveProjectScope(<subdir>)` to the key of its basename; no pointer gives `null`; a malformed pointer gives `null`. (2) `withDeviceId("aaaa0001", ...)` gives `{host: "aaaa0001", unreadable: false}`, `""` gives `{null, false}`, an unreadable config (directory in the file's place, `CHMOD_CANNOT_DENY`-safe) gives `{null, true}`. (3) `readScopedRules` with identity `{project: "x", harness: null, host: null}` and files `project/x.md` and `project/y.md` renders only x after `SCOPED_RULES_HEADER` with `### Project: x`; a null axis matches nothing; `maxChars: 200` with three files drops host first and the notice reports integers; an unreadable file renders the `UNAVAILABLE:` line with a vault-relative path; `hostUnreadable: true` with a `host/` file appends `SCOPED_RULES_HOST_UNREADABLE_NOTICE`; no rendered text contains the vault's absolute path.
+- **Commands**: `bun test tests/core/brain/scope-identity.test.ts tests/core/brain/scoped-rules.test.ts && bun run typecheck`
+- **Commit**: `feat(brain): resolve project, harness and host scope and read scoped rules`
+- **Depends on**: A1
+
+#### Task A3: Write guard covers the directory
+
+- **Files**: `src/core/brain/standing-rules.ts`, `tests/core/brain/scoped-rules-guard.test.ts`
+- **Failing first**: `assertStandingRulesNotTargeted(vault, "Brain/standing-rules/project/x.md", "test")` throws `StandingRulesWriteRefusedError`; so does a not-yet-existing file reached through a symlinked folder pointing at `Brain/standing-rules/` (guarded for platforms that cannot symlink); `Brain/standing-rules-notes.md` and `Notes/standing-rules/x.md` do not throw; the constitution path still throws with the unchanged message.
+- **Commands**: `bun test tests/core/brain/scoped-rules-guard.test.ts tests/core/brain/standing-rules.test.ts tests/mcp/brain-standing-rules-uneditable.test.ts tests/core/brain/write-session tests/core/brain/attributes.test.ts && bun run typecheck`
+- **Commit**: `feat(brain): refuse writes into the scoped standing-rules directory`
+- **Depends on**: A2
+
+#### Task A4: Config knob
+
+- **Files**: `src/core/brain/policy/blocks/active.ts`, `src/core/brain/policy.ts`, `src/core/brain/types.ts`, `src/core/brain/config-template.ts`, `tests/core/brain/policy-active.test.ts`, `tests/core/brain/config-template-ratchet.test.ts`
+- **Failing first**: `active: { scoped_rules_max_chars: 150 }` is refused with the range message naming `active.scoped_rules_max_chars`; `500` parses; `resolveScopedRulesMaxChars(null)` is 2000; the ratchet row `active_scoped_rules_max_chars` matches the template.
+- **Commands**: `bun test tests/core/brain/policy-active.test.ts tests/core/brain/config-template-ratchet.test.ts && bun run typecheck`
+- **Commit**: `feat(brain): add the active.scoped_rules_max_chars cap`
+- **Depends on**: A3
+
+### Lane B - surfaces
+
+#### Task B1: `--harness` on `o2b mcp` and the server context
+
+- **Files**: `src/cli/main.ts`, `src/cli/command-manifest.ts`, `src/mcp/server.ts`, `src/mcp/tool-contract.ts`, `tests/cli/mcp-harness-flag.test.ts`
+- **Failing first**: `o2b mcp --harness nope` exits 2 with the pinned message listing `HARNESS_IDS`; a server built with `{harness: "codex", workspaceDir: dir}` exposes `ctx.ruleScope` `{workspaceDir: dir, harness: "codex"}`; with only `hostTarget: "cursor"` the harness is `cursor`; with neither it is `null`. Fails on `unknown flag: --harness`.
+- **Commands**: `bun test tests/cli/mcp-harness-flag.test.ts tests/cli/mcp-scope-arg.test.ts && bun run typecheck`
+- **Commit**: `feat(mcp): resolve the harness from a launch-time --harness option`
+- **Depends on**: A1 (`src/core/brain/scoped-rules.ts`), A2 (`src/core/brain/scope-identity.ts`)
+
+#### Task B2: `brain_context` renders the scoped layer at local reach
+
+- **Files**: `src/mcp/brain/context-tools.ts`, `tests/mcp/brain-context-scoped-rules.test.ts`, `tests/core/architecture/harness-identity-census.test.ts`
+- **Failing first**, all through the real `MCPServer` with normalised `generated_at`: (1) project A/B: vault with `project/x.md` (unique marker) called from workspace Y gives output identical to the vault without it, and from workspace X `content` holds the marker after `STANDING_RULES_HEADER` and before the memory body, plus `scoped_rules.files[0].path === "Brain/standing-rules/project/x.md"`; (2) harness A/B: `--harness codex` against `harness/cursor.md` identical with and without the file; `--harness cursor` renders it; (3) host A/B: `O2B_DEVICE_ID=aaaa0001` against `host/bbbb0002.md` identical; (4) remote reach (no reach minted) from workspace X with `project/x.md` is byte-identical to the vault without it; (5) census: no tool input schema property under `src/mcp/` is named `harness` or ends in `_harness`, and no tool description contains `` `${BRAIN_SCOPED_RULES_DIR}/` ``.
+- **Commands**: `bun test tests/mcp/brain-context-scoped-rules.test.ts tests/mcp/brain-context-standing-rules.test.ts tests/core/architecture/harness-identity-census.test.ts tests/core/architecture/visibility-surface-census.test.ts && bun run typecheck`
+- **Commit**: `feat(mcp): add scoped operator rules to brain_context at local reach`
+- **Depends on**: B1, A2
+
+#### Task B3: Uneditable matrix for the directory
+
+- **Files**: `tests/mcp/brain-standing-rules-uneditable.test.ts`
+- **Failing first**: the four caller-named write tools and `brain_labels` refuse `Brain/standing-rules/project/x.md` with bytes unchanged, and the substring check also rejects `` `${BRAIN_SCOPED_RULES_DIR}/` `` in tool names and descriptions. Fails until A3 lands (the labels row).
+- **Commands**: `bun test tests/mcp/brain-standing-rules-uneditable.test.ts`
+- **Commit**: `test(mcp): pin the scoped standing-rules directory as uneditable`
+- **Depends on**: A3 (`src/core/brain/standing-rules.ts`)
+
+#### Task B4: SessionStart hook lane and the packaged harness
+
+- **Files**: `hooks/active-inject.ts`, `tests/hooks/active-inject-scoped-rules.test.ts`, `tests/mcp/plugin-mcp-servers.test.ts`
+- **Failing first**: (1) two temp project dirs X and Y linked to one vault; run A with `project/x.md`, run B without, both with payload `cwd` Y: stdout identical and neither holds the marker; with `cwd` X the marker follows the standing header and precedes the active body; (2) a `harness/claude-code.md` file never renders in the hook; (3) budget: `inject_budget_chars: 500`, `scoped_rules_max_chars: 200` and a 5000-character `project/x.md`: the scoped block is capped, the active body is budgeted to `500 - scopedBlock.length`, the receipt's `budget` records `inject_budget_chars: 500` and `scoped_rules_chars` equal to the block length; (4) the plugin manifest test expects the two `--harness claude-code` arg lists.
+- **Commands**: `bun test tests/hooks/active-inject-scoped-rules.test.ts tests/hooks/active-inject.test.ts tests/mcp/plugin-mcp-servers.test.ts && bun run typecheck && bun run sync-plugin-mirrors:check`
+- **Commit**: `feat(hooks): inject project and host scoped rules at session start`
+- **Depends on**: B2, A4 (`src/core/brain/policy/blocks/active.ts`), E1 (`.claude-plugin/plugin.json`)
+
+### Lane C - Hermes plugin
+
+#### Task C1: Two-mode reader and `ProfileScopeError`
+
+- **Files**: `plugins/hermes/config.py`, `tests/python/test_profile_scope.py`, `tests/python/test_memory_provider.py` (`_CONFIG_ENV_KEYS` gains the timeout name)
+- **Failing first**, with a fake `agent.secret_scope` injected through `patch.dict(sys.modules, {"agent": pkg, "agent.secret_scope": fake})`: (a) no stub: today's answers; (b) stub with multiplexing off: `os.environ` wins and `fake.get_secret` is never called; (c) multiplexing on with a scope: scoped values beat conflicting `os.environ` values for vault, agent name, timezone and config path; (d) empty scope: falls through to the config chain, not to `os.environ`; (e) `get_secret` raises: `resolve_vault` and `resolve_agent_name` raise `ProfileScopeError`, an instance of `ConfigReadError`, whose `__cause__` is the fake `UnscopedSecretError` and whose message holds no environment value.
+- **Commands**: `cd tests/python && python3 -m unittest test_profile_scope test_resolver_parity -v`
+- **Commit**: `feat(hermes): resolve profile-scoped settings from the Hermes profile scope`
+- **Depends on**: none
+
+#### Task C2: Warning, `shadowing_source` and CLI line
+
+- **Files**: `plugins/hermes/config.py`, `plugins/hermes/cli.py`, `tests/python/test_profile_scope.py`
+- **Failing first**: (c') one WARNING per ignored name from `plugins.hermes.config`, the value string absent from every record; (g) repeated calls log once (`_reset_scope_warnings_for_tests` between tests); the multiplexed `shadowing_source("agent_name")` names the profile `.env`, the non-multiplexed text is unchanged; `cli._config` prints `settings_source:` as its first line in both modes, and with no scope bound prints the `ProfileScopeError` naming `OPEN_SECOND_BRAIN_CONFIG` and exits 2.
+- **Commands**: `cd tests/python && python3 -m unittest test_profile_scope test_memory_provider -v`
+- **Commit**: `feat(hermes): warn once per ignored gateway variable and name the settings source`
+- **Depends on**: C1
+
+#### Task C3: Scoped child environment, bridge key and timeout
+
+- **Files**: `plugins/hermes/provider.py`, `plugins/hermes/bridge.py`, `tests/python/test_profile_scope.py`
+- **Failing first**: (f) under multiplexing the env passed to the patched `McpBrainBridge` has the launch `VAULT_AGENT_NAME` replaced by the scoped one and no other scoped name from `os.environ`; two scopes with the same vault and different agent names produce two bridges; without multiplexing `_resolve_env()` and sharing are unchanged; (h) a bridge built with `timeout=7.0` restarted from a bare `threading.Thread` never calls `get_secret`; `prefetch` with `get_secret` raising returns without the reminder and logs the degrade WARNING once.
+- **Commands**: `cd tests/python && python3 -m unittest test_profile_scope test_memory_provider -v`
+- **Commit**: `feat(hermes): give each profile its own MCP child identity on a multiplexed gateway`
+- **Depends on**: C2
+
+#### Task C4: `--harness hermes` in the bridge argv
+
+- **Files**: `plugins/hermes/bridge.py`, `tests/python/test_memory_provider.py`
+- **Failing first**: `_argv()` ends with `["--harness", "hermes"]` with and without `--vault` and `--repo` (extend the argv tests at `test_memory_provider.py:1709-1740`).
+- **Commands**: `cd tests/python && python3 -m unittest test_memory_provider test_profile_scope test_resolver_parity -v && cd ../.. && python3 -m compileall -q plugins/hermes`
+- **Commit**: `feat(hermes): launch the MCP bridge with --harness hermes`
+- **Depends on**: C3
+
+### Lane D - reach left-overs
+
+#### Task D1: Today view open loops at reach
+
+- **Files**: `src/core/brain/open-loops.ts`, `src/core/brain/today-dashboard.ts`, `src/mcp/brain/brief-tools.ts`, `tests/mcp/today-open-loops-reach.test.ts`, `tests/core/brain/today-dashboard.test.ts`
+- **Failing first**: a `notes.read_paths: [Notes]` vault with `Notes/PRIVATE_PATH.md` (reserved visibility, `@osb loop zzreservedloopzz`) against the same vault without it: `brain_brief view=today` at remote reach gives identical normalised output (red today: the loop text, its path and `openLoopsCount`/`scannedFiles` 2 against 1); the local control lists the loop.
+- **Commands**: `bun test tests/mcp/today-open-loops-reach.test.ts tests/core/brain/today-dashboard.test.ts && bun run typecheck`
+- **Commit**: `fix(brief): list today's open loops at the caller's reach`
+- **Depends on**: none
+
+#### Task D2: Monthly view at reach
+
+- **Files**: `src/core/brain/monthly-review.ts`, `src/mcp/brain/brief-tools.ts`, `tests/mcp/brief-monthly-reach.test.ts`
+- **Failing first**: on `buildReachLogFixture` with and without the reserved records, `view=monthly` at remote reach gives identical normalised summaries (red today: 7/4/1/1 against 2/1/0/0); the local control keeps 7/4/1/1.
+- **Commands**: `bun test tests/mcp/brief-monthly-reach.test.ts tests/mcp/brain-monthly.test.ts && bun run typecheck`
+- **Commit**: `fix(brief): count the monthly view at the caller's reach`
+- **Depends on**: D1
+
+#### Task D3: Doctor removed-tool cap and stale-dependency count at reach
+
+- **Files**: `src/core/brain/doctor/report.ts`, `src/core/brain/doctor/check.ts`, `src/core/brain/doctor.ts`, `src/core/brain/doctor/removed-tool-checks.ts`, `src/core/brain/stale-dependency.ts`, `src/mcp/brain/health-tools.ts`, `tests/mcp/doctor-counts-reach.test.ts`
+- **Failing first**: vault A has a reserved page that sorts first plus 50 readable pages naming a removed tool, vault B only the 50: `brain_doctor` warning lists at remote reach are identical; a reserved retired record changes `states_changed` in A only today, and after the fix the uncertain note is identical.
+- **Commands**: `bun test tests/mcp/doctor-counts-reach.test.ts tests/mcp/log-readers-reach-round3.test.ts tests/core/brain/doctor && bun run typecheck`
+- **Commit**: `fix(doctor): cap removed-tool warnings and count stale dependencies at the caller's reach`
+- **Depends on**: D2
+
+#### Task D4: Operator view at reach and registry reasons
+
+- **Files**: `src/core/brain/trust/operator-summary.ts`, `src/mcp/brain/brief-tools.ts`, `src/core/search/visibility-surface-registry.ts`, `tests/mcp/brief-operator-reach.test.ts`
+- **Failing first**: `view=operator` at remote reach with and without the reserved records gives identical `digest_summary`, `doctor_summary`, `top_actions` and `trust_verdict` (red today: preference_count 2/1, warnings 11/3, investigate/watch); the local control is unchanged; the `brain_brief` and `brain_doctor` registry reasons name only `dream_summary` and `verification_delta` as the remaining whole-layer counts.
+- **Commands**: `bun test tests/mcp/brief-operator-reach.test.ts tests/mcp/operator-summary-tool.test.ts tests/core/architecture/visibility-surface-census.test.ts && bun run typecheck`
+- **Commit**: `fix(brief): answer the operator view at the caller's reach`
+- **Depends on**: D3
+
+### Lane E - docs and release
+
+#### Task E1: Version and CHANGELOG
+
+- **Files**: `package.json`, `CHANGELOG.md`, `README.md`, `plugins/codex/README.md`, `.claude-plugin/plugin.json` (version via the sync, plus the two `--harness claude-code` arg lists from the contract), and the other files `sync-version.ts` regenerates
+- **Failing first**: `bun run scripts/sync-version.ts --check` and `bun test tests/version.test.ts` fail after `package.json` is set to 1.70.0 and before the sync; pass after. `tests/mcp/plugin-mcp-servers.test.ts` is lane B's and goes red on the new args until B4 lands; that is expected and not lane E's to fix.
+- **Commands**: `bun run scripts/sync-version.ts && bun run sync-plugin-mirrors && bun test tests/version.test.ts && bun run sync-plugin-mirrors:check`
+- **Commit**: `chore(release): 1.70.0 changelog and version` (README and `plugins/codex/README.md` in this first commit)
+- **Depends on**: none
+
+#### Task E2: Scoped rules and `--harness` docs
+
+- **Files**: `docs/how-it-works.md` (constitution section, `### Scoped operator rules` with the precedence sentence and the hook/MCP split), `docs/mcp.md` (`brain_context` `scoped_rules` key, `--harness` on the server line, the today/monthly/operator/doctor residual sentences at :2180-2182 and :2218-2222 rewritten to what remains), `docs/cli-reference.md` (`o2b mcp --harness`), `docs/observability.md` (receipt `scoped_rules_chars`)
+- **Failing first**: `bun test tests/docs` (docs conformance) stays green; grep shows no `standing-rules/` mention in any tool description string.
+- **Commands**: `bun test tests/docs`
+- **Commit**: `docs: describe scoped operator rules and the --harness option`
+- **Depends on**: none
+
+#### Task E3: Hermes and stability docs
+
+- **Files**: `install/hermes.md` (`### Multiple Hermes profiles`: per-profile `.env`, the process environment ignored under `gateway.multiplex_profiles`, the WARNING, the residual variables, the install-shadowing pitfall), `docs/stability.md` (one sentence for the multiplexed environment layer, one for the scoped layer), `docs/updating.md` (`## Upgrading to 1.70.0`)
+- **Failing first**: `bun test tests/docs/install-verify-conformance.test.ts` stays green.
+- **Commands**: `bun test tests/docs`
+- **Commit**: `docs: per-profile Hermes settings and the 1.70.0 upgrade notes`
+- **Depends on**: none
diff --git a/docs/brainstorm/scope-resolution/variants.md b/docs/brainstorm/scope-resolution/variants.md
new file mode 100644
index 00000000..943a6774
--- /dev/null
+++ b/docs/brainstorm/scope-resolution/variants.md
@@ -0,0 +1,40 @@
+# Per-context scope resolution - variants and decision
+
+Consultant: the primary CLI consultant (`claude -p`, prompt in `cli-output/prompt.md`, verbatim answer in `cli-output/claude.md`). Exit 0, three parseable variants; the fallback consultant was not run.
+
+## Variant 1: Three local seams - lost
+
+Fix each lane where it lives: an optional `env` mapping on every Hermes resolver, sibling scoped-rule files read by a second reader, identity resolved inline in `server.ts` at `initialize` (from `clientInfo`) and separately in the hook, per-view reach edits.
+
+Why it lost: identity derived in two places drifts, which is the cross-context carry-over this release exists to close, and `clientInfo` is a name the client asserts about itself. Its file layout and its untouched constitution survive in the chosen variant.
+
+## Variant 2: One derived identity, one rules ladder, one reach layer - chosen, adjusted
+
+Consultant's recommendation, accepted with five adjustments (evidence in `design.md`, "Chosen approach"):
+
+1. No ladder around the constitution: `standing-rules.ts`, its header and its exemption are pinned byte for byte; the scoped reader is a second module joined after it.
+2. No `clientInfo` and no MCP roots as identity sources: both are caller-named. The harness comes from a launch-time `--harness` argument.
+3. No `ReachLayer` object: the shipped per-reader `readable` predicate, omitted at local reach, keeps local output byte-identical and the fast paths intact.
+4. No settings-source argument on the Hermes resolvers: the doctor parity check and the parity suite call them with no arguments by file location.
+5. The scoped layer renders at local reach only, the rule the consultant named as missing from its own variant.
+
+## Variant 3: Scope axes extended, identity on the wire - lost
+
+Scoped rules as ordinary pages with `harness` and `host` added to `SCOPE_AXES`; one Hermes child per vault with the turn's agent name sent as JSON-RPC `_meta`; reach pushed into the page index.
+
+Why it lost: extending `SCOPE_AXES` changes page dedup keys, hub-candidate pools and search filters; per-call `_meta` turns the agent name into a request property every startup reader would have to learn, or it carries the launch profile over anyway; an index-level reach filter puts the local byte-identity pin at risk; rule pages outside the Brain-root refusal need uneditability argued again.
+
+## Alternatives considered inside the chosen variant
+
+| Question | Chosen | Lost, and why |
+|---|---|---|
+| Where a scoped rule lives | One file per scope value under `Brain/standing-rules/<axis>/<key>.md` | Frontmatter scoping inside the constitution: the constitution reader must not branch on content (`standing-rules.ts:37-44`) and its file is pinned byte for byte. |
+| Harness source | Packaged `o2b mcp --harness <id>`, falling back to `--host-target` | `clientInfo` from MCP initialize: named by the client about itself (tests send arbitrary names, Hermes sends a constant), so a caller could pick its own rules. |
+| Host source | Device id (`resolveDeviceId`) | `os.hostname()`: not stable, not unique, and host names must not reach public text or rule file names. |
+| Budget of the scoped layer | Charged against `inject_budget_chars`, own cap, recorded in the receipt | Exempt like the constitution: the exemption is argued as the constitution's own property; three more exempt files would let scoped text grow the preamble without bound. |
+| Axis vocabulary | Separate `SCOPED_RULE_AXIS` and `HARNESS_ID` | Extending `SCOPE_AXES`: it feeds page dedup keys, hub candidates and search filters, which are frontmatter- and caller-named by design. Extending `INSTALL_TARGET_ID`: its census requires it to equal the install adapter registry. |
+| Hermes child environment | Explicit: copy, strip `PROFILE_SCOPED_ENV`, set resolved values | Adopting Hermes `strip_launch_profile_env`: Hermes-internal (`tools/environments/local.py`), not a plugin contract, and it would tie the plugin to an unpublished helper; the explicit strip names exactly what this plugin owns. |
+| Missing profile scope | New `ProfileScopeError(ConfigReadError)` with its own message | Reusing `ConfigReadError`'s template: it says the config FILE is unreadable, which is false here, and its text is pinned by the parity test. A subclass keeps every existing catch site correct without touching that template. |
+| Scoped-rule key | Unicode letters and digits kept (NFC, lowercased) | The session slug rule `[^a-z0-9]+`: throws on a project name with no Latin letters or digits, so such a project could never be keyed. |
+| Host-unreadable report | One fixed sentence inside the scoped block, only when host files exist | A runtime notice: the collector runs on every surface without identity input, and would fire where no host file could apply. |
+| Left-over lane content | Today loops, monthly, doctor counts, operator view | Status triple, entity-page provenance, ranking statistics: each is a lane of its own or a design change (recorded in `design.md`, "Out of scope"). |
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index e6120181..387eb9d0 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -17,7 +17,7 @@ o2b doctor Run vault + adapter checks
o2b index Rebuild the Markdown page index
o2b export-config Write a redacted config snapshot
o2b secrets list|status Inspect $secret:NAME references without printing values
-o2b mcp Run the MCP tool server (stdio by default; --transport http binds loopback, and a key - --api-key or, kept out of the process list, OPEN_SECOND_BRAIN_MCP_API_KEY - is required only for a non-loopback --host); --scope full|writer|catalog, --tool-profile full|writer|catalog|recall|minimal (an unknown profile exits 2 rather than serving the full surface), --host-target <runtime>, --probe, --allow-tool, --disable-tool, --max-tools
+o2b mcp Run the MCP tool server (stdio by default; --transport http binds loopback, and a key - --api-key or, kept out of the process list, OPEN_SECOND_BRAIN_MCP_API_KEY - is required only for a non-loopback --host); --scope full|writer|catalog, --tool-profile full|writer|catalog|recall|minimal (an unknown profile exits 2 rather than serving the full surface), --host-target <runtime>, --harness <id>, --probe, --allow-tool, --disable-tool, --max-tools
o2b state status|migrate|rollback
Inventory 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
@@ -279,7 +279,30 @@ that documents "no limit" is not recorded as unchecked.
launched it. Install adapters write it into the registration they generate;
an unrecognised value is refused with exit `2` naming the known ids, rather
than dropped - silently ignoring it would report the ceiling as unchecked on
-a host that publishes one. It carries no other behaviour.
+a host that publishes one. Its only other use is as the fallback for
+`--harness` below.
+
+**`o2b mcp --harness <id>`** (since v1.70.0) names the harness the server
+runs under, so `brain_context` can render the operator's
+`Brain/standing-rules/harness/<id>.md` (see "Scoped operator rules" in
+[`how-it-works.md`](how-it-works.md)). The list is closed: `aider`,
+`claude-code`, `codex`, `copilot-cli`, `cursor`, `gemini-cli`, `generic`,
+`grok`, `hermes`, `kiro`, `openclaw`, `opencode`, `pi`. Without it the
+server takes `--host-target`, and with neither it matches no harness
+file. An unrecognised value exits `2`:
+
+```
+$ o2b mcp --harness nope
+o2b mcp: invalid --harness value: "nope"; expected one of: aider, claude-code, codex, copilot-cli, cursor, gemini-cli, generic, grok, hermes, kiro, openclaw, opencode, pi
+```
+
+Both refusals echo the value as a JSON string with every control
+character escaped; a refused `--host-target` value was echoed raw before
+v1.70.0.
+
+The Claude Code plugin registers both of its servers with
+`--harness claude-code`, and the Hermes plugin launches its bridge with
+`--harness hermes`.
`second_brain_capabilities` reads it back and reports a `host_ceiling`
object beside the tool counts: `target`, `kind`, `max_tools`, `source`,
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index f3942166..7385f97f 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -494,7 +494,8 @@ flowchart LR
(`brain_create_note`, `brain_update_note`, `brain_append_note`,
`brain_write_batch`), and `brain_labels` - which takes a caller-named
path but resolves it through the weaker containment-only resolver - is
- refused by a named guard that knows this one file. Nothing generates or
+ refused by a named guard that knows this one file (and, since v1.70.0,
+ the `Brain/standing-rules/` directory beside it). Nothing generates or
rewrites it.
- **SessionStart hook** (`startup | resume | clear | compact`) injects
the body as `additionalContext` so the agent sees current rules at
@@ -535,6 +536,98 @@ flowchart LR
unpin re-derive it from `preferences/` and `retired/`. Deleting the
file is harmless: the next dream regenerates it.
+### Scoped operator rules
+
+Since v1.70.0 the operator can also write rules that hold for one
+project, one harness or one machine, one file per scope value, beside
+the vault-wide `Brain/standing-rules.md`:
+
+| File | Matches when |
+|---|---|
+| `Brain/standing-rules/project/<key>.md` | the session runs in a project linked to the vault whose key is `<key>` |
+| `Brain/standing-rules/harness/<harness id>.md` | the MCP server was launched for that harness |
+| `Brain/standing-rules/host/<device id>.md` | the session runs on the device with that id |
+
+The scope identity is resolved by the server from facts the operator
+or the packager wrote, never from anything a caller names about itself:
+
+- **Project:** the directory holding the nearest `.o2b-vault.json`
+ pointer found from the workspace directory (the pointer
+ `o2b brain project link` writes), by its basename. The hook uses the
+ payload's `cwd` (else its own working directory), the MCP server the
+ directory it was started in.
+ Only a pointer that names the vault serving the session counts: a
+ pointer naming another vault, or one that cannot be read, is skipped
+ and the walk continues upward. No such pointer matches no project
+ file.
+- **Harness:** the `--harness <id>` option of `o2b mcp`, falling back to
+ `--host-target`. The Claude Code plugin registers both of its servers
+ with `--harness claude-code` and the Hermes plugin launches its bridge
+ with `--harness hermes`; install adapters already write
+ `--host-target`. A server launched with neither matches no harness
+ file.
+- **Host:** the device id (`device_id` in the config, or
+ `O2B_DEVICE_ID`). An empty device id is the explicit opt-out and
+ matches no host file. A device id that cannot be read applies no host
+ file either, and when `Brain/standing-rules/host/` holds a file the
+ block ends with one sentence saying so and naming `o2b brain doctor`
+ for the cause.
+
+A project or device name becomes a key by lowercasing it in Unicode
+normal form NFC and turning every run of characters that is not a
+letter, a combining mark or a digit, in any script, into one `-`,
+without leading or trailing `-` and at most 64 characters: a project
+folder `My_Repo.v2` keys to `my-repo-v2`, and a name written with vowel
+signs or accents keeps them, so `Café` and `café` share the key
+`café`.
+
+The matching files are joined under one `## Scoped operator rules`
+header, which states the precedence: the operator standing rules above
+take precedence over them, and they take precedence over every recalled
+preference, lesson and context pack that follows. Each file gets a
+`### Project: <key>`, `### Harness: <key>` or `### Host: <key>`
+subheading, and its own text follows as written. A file that cannot be
+read is replaced by one line, `UNAVAILABLE: <vault-relative path> could
+not be read (<error code>).`, and so is a file or an axis folder that is
+a symbolic link leading out of the vault, with the code `ESCAPE`; an
+empty or missing file is no rule.
+
+Where each layer renders:
+
+- **SessionStart hook:** project and host files, right after the
+ operator standing rules and before the active body. Harness files do
+ not render in the hook in this release, because the hook has no
+ launch-time harness of its own.
+- **`brain_context`:** project, harness and host files, after the
+ standing-rules block and before the memory body, plus an optional
+ `scoped_rules` key with the resolved scope and the matched files (see
+ [`mcp.md`](mcp.md)).
+- **Reach:** the layer renders only for a local caller. Below local
+ reach the server's working directory and device are not the caller's,
+ so neither the block nor the key appears and the device id is not
+ read.
+
+The block's sections are capped by `active.scoped_rules_max_chars`
+(default 2,000, at least 200); the cap covers the sections only, not the
+header or the notices. When the cap cuts anything the host file goes
+first, then the harness file, then the project file, and the block ends
+with a notice of the characters kept and the files dropped; a file whose
+rules cannot fit at all is dropped whole rather than left as a bare
+subheading. Unlike the vault-wide file, the block is charged against the
+injection budget in the SessionStart hook: there the header and room for
+the notices ride inside `active.inject_budget_chars`, so the section cap
+is the smaller of `scoped_rules_max_chars` and what the budget leaves
+after them (never below zero), the rendered block is subtracted from
+`inject_budget_chars` before the active body is budgeted, and the
+block's length is recorded as `scoped_rules_chars` on the hook's receipt
+(see [`observability.md`](observability.md)). The files are read on every render and never cached, so one
+project's rules are never replayed in another.
+
+The directory is as far out of an agent's reach as the vault-wide file:
+every write path that refuses `Brain/standing-rules.md` refuses any path
+inside `Brain/standing-rules/` too, compared as written and after
+resolving symbolic links, and nothing generates or rewrites the files.
+
## CLI / MCP surface
The same operations are reachable through two channels. Read columns
diff --git a/docs/mcp.md b/docs/mcp.md
index 816af477..e93ab0b6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -700,7 +700,8 @@ Optional flags:
- `--scope full|writer` — choose the full server or the always-loaded writer subset.
- `--writer-only` — alias for `--scope writer`.
- `--tool-profile full|writer|catalog|recall|minimal` — a named scope-plus-window bundle (see "Tool-surface profiles" below).
-- `--host-target <runtime>` — name the runtime that launched this server, so the capability report can cite that host's published tool ceiling. Install adapters write it into the registration they generate; an unrecognised value exits `2` naming the known ids. It changes nothing else.
+- `--host-target <runtime>` — name the runtime that launched this server, so the capability report can cite that host's published tool ceiling. Install adapters write it into the registration they generate; an unrecognised value exits `2` naming the known ids. It also stands in for `--harness` when that option is absent, and changes nothing else.
+- `--harness <id>` — name the harness this server runs under (since v1.70.0), from a closed list: `aider`, `claude-code`, `codex`, `copilot-cli`, `cursor`, `gemini-cli`, `generic`, `grok`, `hermes`, `kiro`, `openclaw`, `opencode`, `pi`. It selects which `Brain/standing-rules/harness/<id>.md` file `brain_context` renders (see "Scoped operator rules" in [`how-it-works.md`](how-it-works.md)); the Claude Code plugin passes `--harness claude-code` and the Hermes plugin `--harness hermes`. An unrecognised value exits `2` naming the accepted ids. No tool argument names the harness.
- `--probe` — start an in-process handshake and print whether the server can advertise tools, then exit.
- `--transport stdio|http` — choose stdio (default) or Streamable HTTP.
- `--host HOST` — HTTP bind host (default `127.0.0.1`).
@@ -1255,7 +1256,7 @@ The plugin manifest `.claude-plugin/plugin.json` declares **two** MCP-server ent
- `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).
+Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`), and since v1.70.0 both are registered with `--harness claude-code`. 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).
`brain_feedback`'s `scope` argument stays optional. When the vault declares `feedback.default_scope` in `Brain/_brain.yaml`, a call that omits `scope` records the signal under that default category; an explicit `scope` always wins, and with no default configured a scope-less call stays scope-less. The same effective scope is reused for a `force_confirmed: true` preference so the preference and its signal share one scope. The configured value is validated against the same constraints as any signal `scope` (non-empty after trim, single-line, at most 128 characters).
@@ -2177,10 +2178,11 @@ format characters), when it contains NUL, or when it exceeds the cap.
when every evidence event citing it is about such a record, or when
the pointer names a page the caller cannot read, recompute the
`events_by_kind` and `vault_delta` counts from the events the caller
- may see, and take no report snapshot and show no `delta`. The monthly
- and operator views, and the today view outside its recent activity,
- still count over the whole Brain layer and name no record. The
- read-only preview of the same
+ may see, and take no report snapshot and show no `delta`. Since
+ v1.70.0 the today, monthly and operator views answer at the caller's
+ reach too; only the operator view's `dream_summary` counts, and the
+ dream warnings its trust verdict folds in, still count over the whole
+ Brain layer, and they name no record. The read-only preview of the same
extraction is the CLI verb `o2b brain extract` (see
[`cli-reference.md`](cli-reference.md)).
- Since v1.69.0 more readers treat a page or record the caller cannot
@@ -2216,7 +2218,150 @@ format characters), when it contains NUL, or when it exceeds the cap.
`visibility` applies to the page. The empty-search coverage verdict no
longer counts a root as reached through a page the caller cannot read.
Some counts still run over the whole Brain layer and name no record:
- the monthly and operator views, the status views, the cap on
- `removed-tool-reference` warnings and the `brain_doctor`
- stale-dependency note; the ranking statistics of `brain_search` are
- taken over the shared index.
+ the operator view's `dream_summary` counts (and the dream warnings its
+ trust verdict folds in) and the status views; the ranking statistics of `brain_search` are taken over
+ the shared index.
+- Since v1.70.0 `brain_context` renders the operator's scoped rules for a
+ local caller. After the standing-rules block, and before the memory
+ body, `content` carries a `## Scoped operator rules` block built from
+ `Brain/standing-rules/project/<key>.md`,
+ `Brain/standing-rules/harness/<harness id>.md` and
+ `Brain/standing-rules/host/<device id>.md`, the files whose key matches
+ the scope the server resolved: the project from the nearest
+ `.o2b-vault.json` pointer above the directory the server was started
+ in, the harness from `--harness` (falling back to `--host-target`) and
+ the host from the device id. The result then carries an optional
+ `scoped_rules` key, present only when at least one file matched or the
+ block carries the notice that host-scoped rules were not applied:
+
+ ```json
+ {
+ "scope": { "project": "proj-x", "harness": "claude-code", "host": null },
+ "files": [
+ { "path": "Brain/standing-rules/project/proj-x.md", "axis": "project", "truncated": false }
+ ]
+ }
+ ```
+
+ `path` is vault-relative, `axis` is `project`, `harness` or `host`, and
+ `truncated` is `true` for a file the `active.scoped_rules_max_chars` cap
+ cut; `brain_context` has no injection budget, so the cap applies as
+ configured. The tool renders the notice that host-scoped rules were
+ not applied, with `scope.host: null`, when the device id cannot be
+ resolved but the call can still be answered, for example when no
+ device id is stored yet and the configuration directory cannot be
+ written; an unreadable configuration file, or a config home that
+ cannot be created, fails the whole call first. The tool gains no
+ input argument. Below local reach neither the
+ block nor the key appears: the output is the same as for a vault
+ without the directory. Every write tool refuses a path inside
+ `Brain/standing-rules/`, as it refuses `Brain/standing-rules.md`. See
+ "Scoped operator rules" in [`how-it-works.md`](how-it-works.md).
+- Since v1.70.0 more brief and doctor counts answer at the caller's
+ reach; a local caller and the CLI see no change. Below local reach
+ `brain_brief` `view="today"` lists no open loop or obligation from a
+ page the caller cannot read and counts only the files it may read in
+ `scannedFiles`; `view="monthly"` counts events, status transitions,
+ retirements, contradictions and neglected areas from the events the
+ caller may see, the same rule as the daily and weekly views;
+ `view="operator"` takes its doctor counts from the findings the caller
+ may see, its digest counts from readable pages, its top actions from
+ readable targets before the top entries are picked, its verification
+ entries and their counts from the records and pages the caller may
+ read, and recomputes its trust verdict from those; and `brain_doctor`
+ fills the cap on `removed-tool-reference` warnings and the per-code
+ cap of its `uncertain` stream from readable pages, counts the
+ stale-dependency note's `states_changed` and each stale row's
+ consumers from the pages and records the caller can read (a withheld
+ page is neither a state nor a consumer), runs its concept-gap and
+ contradiction detectors over readable preferences and signals only,
+ and leaves out an `instruction_file_warnings` entry for a vault-root
+ instruction file the caller cannot read; the operator view's
+ `instruction_file_warnings` follow the same rule.
+- Since v1.70.0 more readers answer at the caller's reach; a local
+ caller and the CLI see no change. Below local reach
+ `brain_obligation` lists, shows, completes and removes an obligation
+ page the caller cannot read exactly as an absent one (`show` answers
+ `present: false`, `done` and `remove` refuse with `no obligation`),
+ `remove` leaves `archive_path` out of its answer, and `add` still
+ refuses a slug whose page exists. `brain_intention` treats a chain the
+ caller cannot read the same way (`list` leaves it out, `show` answers
+ `present: false`, `move` refuses with `no active intention`), `move`
+ leaves `archive_path` out, and `set` refuses a scope whose withheld
+ chain exists instead of folding it into a new version. `brain_health`
+ computes `concept_gaps`, the `suppressed` counts and the verdict
+ over the preferences and signals the caller can read, so a term only
+ withheld principles carry is not reported. `brain_trigger`
+ `operation="scan"` builds its candidates from readable records only,
+ so `candidates` counts none the caller cannot read and the scan
+ writes no trigger about such a record; every trigger row and
+ transition treats a trigger naming such a record as absent.
+ `brain_stale_scan`, `brain_review_candidates` and `brain_retention`
+ list no preference or signal the caller cannot read, and
+ `brain_retention` counts its `summary` over the rows it returns.
+ `brain_review_candidates` plans its dry run over the signals,
+ preferences and retired records the caller can read, so its
+ `clusters_below_threshold` and `intent_reviews` fold no withheld
+ signal, and `brain_intent_review` folds the same readable records.
+- Since v1.70.0 `brain_context_receipts` answers at the caller's reach
+ for the operator rules. Below local reach a SessionStart injection
+ receipt leaves out the `standing-rules` and `scoped-rules` items,
+ their source references and every figure that counts or measures
+ them (the item count, the whole-text hash and lengths, the total bytes
+ and tokens, `scoped_rules_chars` and `budgeted_source_count`), and
+ `summary` leaves them out of its item totals, counting a receipt left
+ with no item in `empty_receipts`. A measured injection receipt whose
+ every item was an operator-rule block (a session with no `active.md`
+ body) is left out of `list` and `summary` before their limit and fold
+ bound, and `show` answers it with `receipt not found`; the `budget`
+ block is dropped from a receipt that has no budgeted body left. A
+ stored receipt is otherwise returned as recorded, with no visibility
+ check at read time.
+- Since v1.70.0 `brain_doctor` with `repair` runs the checks behind its
+ plan over the pages and records the caller can read, so below local
+ reach the `unfixable` counts (the removed-tool cap, the concept gaps)
+ are the counts a vault without the withheld pages gives.
+- Since v1.70.0 `brain_tension`, `brain_lifecycle` and `brain_expire`
+ answer at the caller's reach; a local caller and the CLI see no
+ change. Below local reach `brain_tension` `detect` reads only the notes
+ the caller may read (`scanned_files` counts those) and pairs nothing
+ from the others; a persisted tension page carries the stricter
+ `visibility` of its two source notes, and `list`, `verify` and `show`,
+ `confirm`, `dismiss` and `resolve` treat a tension page the caller
+ cannot read as absent (`no tension: <slug>`). `brain_lifecycle`
+ `tombstone`, `supersede` and `temporal-replace`, and `brain_expire`,
+ refuse a page or record the caller cannot read with the error a
+ missing one gets (`note does not exist: <path>`, `no signal or
+ preference with id`), before anything is written; `brain_lifecycle`
+ `curator` leaves out a row whose key names such a page or record.
+- Since v1.70.0 the writers that name a preference, a premise, a
+ decision, a label target, a stub source or a chain id answer at the
+ caller's reach; a local caller and the CLI see no change. Below local
+ reach a page or record the caller cannot read is treated as absent
+ before anything is written: `brain_apply_evidence` and the
+ `apply_evidence` operation of `brain_write_batch` refuse it as a
+ missing preference, `brain_derive_fact` as a missing premise,
+ `brain_decision` `show`, `outcome` and `rate` with `no decision:
+ <slug>` (and `list`, `compare`, `history`, `recall` and `similar`
+ leave it out), `brain_labels` `assign` and `remove` with `note does
+ not exist`, `brain_scaffold_stub` as an unknown source (and `list`
+ leaves it out), and `brain_lifecycle` `tip` reads it as an unknown id.
+ The `brain_feedback` conflict and routing hints score only
+ readable preferences and signals, and `brain_design_note` grounds only
+ on readable tensions and decisions.
+- Since v1.70.0 `brain_dream` serves only a dry run below local reach,
+ planned over the records the caller can read; a real pass, a single
+ step and the staged lifecycle are refused, and `brain_maintenance`
+ `run` is refused too (its `status` still answers). A preference the
+ dream pass drafts carries the strictest `visibility` of the signals it
+ is drafted from and of the record it supersedes or rebuts, at every
+ reach.
+- Since v1.70.0 `brain_dead_ends` `list`, `brain_diarize`, `brain_hygiene`
+ `mode="refresh"` and `brain_anticipatory_context` answer at the
+ caller's reach. Below local reach `brain_dead_ends` lists only readable
+ dead ends and `record` leaves out the archived ids; `brain_diarize`
+ answers a subject page the caller cannot read as an unknown entity and
+ takes no evidence from a source page it cannot read; `refresh` plans,
+ re-derives and archives only readable derived pages; and
+ `brain_anticipatory_context` builds its bundle for the caller without
+ reading or writing the shared cache, answering `cache_state: "miss"`.
diff --git a/docs/observability.md b/docs/observability.md
index 2d25935f..21a57c64 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -181,6 +181,7 @@ No-consumer regression tests cover each gated surface, so a future call site can
- The recall-inject hook's optional decision-model filter (`decision_model_uses: "recall_inject:shadow|enforce"`, see `docs/decision-models/recall-inject.md`) adds to the hook's `recall_telemetry` `metadata` and to its local hook-audit line a `decision_model` object: `mode`, `outcome` (`ok`, `not_sent` or `degraded`), `latency_ms` (the time the filter added to the prompt), `notes_dropped` and `abstained` (in `shadow`, what `enforce` would have done). Only the local audit line adds `degrade_reason` on a failure. In `enforce` a withheld brief is an `abstain` with reason `decision_model_abstain` (status `empty`). Its `decision_model_call` records carry `note_paths` (a note that may not leave the machine as `(withheld)`), `helps`, `inject_any`, `abstained`, `notes_dropped`, `withheld_count`, `budget_dropped_count` and `budget_ms`; an enforced brief that got shorter writes one `token_impact` sample with `source: decision_model:recall_inject` when `token_impact_ledger_enabled` is on. None of these carries prompt or note text. `o2b decision-model report --use recall_inject` reads them with p50/p95 added latency, timeout rate, abstain rate and notes dropped next to the hook's recall telemetry.
- `brain_recall_telemetry` `operation: "cost"` (MCP) and `o2b brain recall-telemetry cost` fold WRITE volume against the read telemetry above: memory-write ops (Brain-log `feedback`/`apply-evidence`/`note` verbs plus `host_memory_write` continuity records) are counted per period and reported alongside reads as a write-vs-read ratio, a `write_heavy` flag, and a rough weighted cost signal. Weights (`--write-cost`/`--read-cost`, default 1 each) model "some tools charge on write, some on read"; `--write-heavy-ratio` (default 1) sets the write-heavy threshold. Read-only; period-scoped by `--since`/`--until`. `brain_create_note` file creation emits no telemetry event today and is not counted.
- `brain_context_receipts` and `o2b brain context-receipts` inspect served-context receipts.
+- The SessionStart hook writes one `context_receipt` per injection (`host: "hook"`, `trigger: "session_inject"`) with one item per source it injected. On a measured run its `budget` block carries `inject_budget_chars` (the configured value), `budgeted_source_count` and, since v1.70.0, `scoped_rules_chars`: the length of the rendered scoped operator rules block, `0` when none rendered. The scoped block is a budgeted source named `scoped-rules`, but it is subtracted from the budget rather than charged against the full ceiling: the active body was budgeted to `inject_budget_chars` minus `scoped_rules_chars` (never below zero). The `budget` block is present whenever the scoped block rendered, also when there is no `active.md`. A run that fell back to the last good cache records no `budget` block, as before, but keeps the `standing-rules` and `scoped-rules` items, which are produced outside the fail-open boundary. See "Scoped operator rules" in [`how-it-works.md`](how-it-works.md).
- `brain_route_metrics` (MCP, `operation: "list"|"summary"`) reads route-level MCP tool latency. `list` returns raw `mcp_route_latency` records (filter by `tool`/`status`/`since`/`until`/`limit`); `summary` rolls each tool up into count, error count, and min/avg/max plus p50/p95/p99 latency, ordered slowest-first so an operator can identify which endpoint blocks an agent turn by route rather than by aggregate benchmark. Records are emitted only when `mcp_route_metrics_enabled` is on (default off); read-only.
- `brain_token_impact` (MCP, `operation: "record"|"outcome"|"list"|"summary"`) is the durable value-of-memory ledger. `record` posts one context pack's prompt-token delta (`baseline_tokens` − `packed_tokens`, labelled `method: tokenizer|heuristic` — how the CALLER produced the counts, never how accurate they are; the ledger counts nothing itself and verifies neither. Samples written under the retired `exact`/`fallback` labels are still read and classified) plus an optional modeled inference-avoidance estimate (`modeled_avoided_inferences` × `modeled_tokens_per_inference`); `outcome` posts a `first_pass`/`repair`/`retry` result. `summary` keeps the two ledgers STRICTLY SEPARATE: `prompt_token_delta` reports the net/saved/added tokens with a per-`method` split (so a tokenizer-produced count is never averaged in with a heuristic estimate), while `modeled_inference_avoidance` reports the raw modeled figure and a `calibrated_savings_tokens` dampened by the observed first-pass rate from posted outcomes (null until an outcome exists — uncalibrated, not zero). `list` returns raw samples (filter by `pack_id`/`method`/`host`/`since`/`until`/`limit`); `summary` accepts `max_samples` to bound aggregation. Writes are emitted only when `token_impact_ledger_enabled` is on (default off) and are payload-safe (counts + opaque `pack_id` only, never prompts or recalled text); `list`/`summary` read regardless of the gate. Aggregates are recomputed from the continuity store on every read, so they survive restarts.
- `brain_event_trace` (MCP) and `o2b brain event-trace` join the Brain log to the continuity store: given a logged event (by day, `--at` stamp, kind, or `--session-id`), they resolve the continuity records attached to it via the stable correlation ids above (`session_id`, `turn_id`, and artifact `sourceRefs`), so an operator can answer "which context was supplied to this action?" from one surface. Each attached record reports `joinedBy` (`session` / `turn` / `artifact`); open the full record through the per-kind readers (`context-receipts show`, `recall-telemetry`, `generation-reports show`). Read-only; `private` records are dropped unless explicitly kept.
diff --git a/docs/stability.md b/docs/stability.md
index 9824f2dd..21662028 100644
--- a/docs/stability.md
+++ b/docs/stability.md
@@ -37,6 +37,11 @@ Examples frozen at 1.0.0: `vault`, `agent_name`, `timezone`
per-operation variants (`OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`), and
`report_snapshots_enabled` (`OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS`).
Unknown keys remain warnings, never errors.
+On a Hermes gateway that multiplexes profiles, the Hermes plugin reads
+`VAULT_DIR`, `VAULT_AGENT_NAME`, `VAULT_TIMEZONE`,
+`OPEN_SECOND_BRAIN_CONFIG` and `OPEN_SECOND_BRAIN_MCP_TIMEOUT` from the
+turn's profile scope in place of the process environment (since 1.70.0);
+the order is otherwise the same.
### Search index schema
@@ -72,6 +77,10 @@ directories are never modified or deleted by generators. Storage
timestamps are canonical UTC everywhere (frontmatter, log headings,
run ids); timezone conversion is strictly a presentation-layer
concern.
+`Brain/standing-rules.md` and the scoped rule files under
+`Brain/standing-rules/` (`project/`, `harness/` and `host/`, since
+1.70.0) are operator-written: no generator or tool writes them, and
+their layout and file naming are part of this contract.
## What counts as breaking
diff --git a/docs/updating.md b/docs/updating.md
index 965712bf..d0676f8b 100644
--- a/docs/updating.md
+++ b/docs/updating.md
@@ -47,6 +47,101 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed
`.claude/skills/`) and warns with the exact replacement for any stale
reference it finds (`removed-tool-reference`).
+## Upgrading to 1.70.0
+
+One step is required for Hermes users: update the `o2b` CLI and the
+Hermes plugin together. Seven changes are visible to an operator or a
+client.
+
+**Update `o2b` and the Hermes plugin together.** The Hermes plugin now
+launches its MCP bridge as `o2b mcp --harness hermes`, and an `o2b`
+older than 1.70.0 refuses `--harness` as an unknown flag, so the bridge
+does not start; the bridge's stderr in the gateway log names the flag.
+The `o2b` links that `scripts/o2b install-cli` creates follow the
+plugin; an `o2b` installed some other way must be updated as well. The
+Claude Code plugin's two MCP registrations gain `--harness claude-code`
+in the same release, so they need no step.
+
+**Hermes settings come from the profile on a multiplexed gateway.** With
+`gateway.multiplex_profiles: true`, `VAULT_DIR`, `VAULT_AGENT_NAME`,
+`VAULT_TIMEZONE`, `OPEN_SECOND_BRAIN_CONFIG` and
+`OPEN_SECOND_BRAIN_MCP_TIMEOUT` are read from each turn's profile scope
+(the profile's `.env`), no longer from the gateway process environment.
+A profile that relied on the launch profile's environment now falls
+through to the Open Second Brain config chain instead; move such a
+setting into that profile's `.env`. The gateway log names each ignored
+variable once with a WARNING. A single-profile gateway is unchanged.
+See "Multiple Hermes profiles" in [`install/hermes.md`](../install/hermes.md).
+
+**`hermes open-second-brain config` prints the settings source first.**
+The first line is now `settings_source: ...`, naming the source this
+command resolved from (`profile scope (multiplexed gateway)`, or
+`process environment` with a note that a multiplexed gateway reads each
+profile's `.env`), and `config_path:` follows it; when no profile
+scope is bound, the named error replaces the path. A script that reads
+`config_path:` from the first line must look for it by name. On a
+multiplexed gateway each profile identity (vault, agent name, timezone,
+config path and timeout) gets its own `o2b mcp` child, so the gateway
+runs more child processes, and a child whose identity changed (for
+example after an edited `.env`) stays alive until the gateway exits. A
+call with no bound profile scope reports a `ProfileScopeError` naming
+the variable, and `prefetch` omits the vault reminder for that turn with
+one WARNING.
+
+**Scoped operator rules.** Files under `Brain/standing-rules/project/`,
+`Brain/standing-rules/harness/` and `Brain/standing-rules/host/` are
+now rendered for the matching project, harness and device, after the
+operator standing rules, in the SessionStart hook (project and host
+only) and in `brain_context`, for a local caller only. A vault without
+the directory renders exactly as before. The block is charged against
+`active.inject_budget_chars` and capped by the new
+`active.scoped_rules_max_chars` (default 2,000); the hook receipt's
+`budget` block gains `scoped_rules_chars`, and `brain_context` gains an
+optional `scoped_rules` key. Every write path now refuses paths inside
+`Brain/standing-rules/`. See "Scoped operator rules" in
+[`how-it-works.md`](how-it-works.md).
+
+**`o2b mcp --harness <id>`.** A new optional flag naming the harness;
+an unknown value exits `2`. `--host-target` now also stands in for it
+when it is absent, and a refused `--host-target` value is now echoed as
+a JSON string with its control characters escaped, as a refused
+`--harness` value is; a script that matches the raw value on stderr must
+match the quoted one.
+
+**More brief and doctor counts answer at the caller's reach.** Below
+local reach `brain_brief` `view="today"` no longer lists an open loop
+or obligation from a page the caller cannot read, `view="monthly"`
+counts from the events the caller may see, `view="operator"` computes
+its doctor and digest counts, top actions, verification entries and
+trust verdict from what the caller may see, and the `brain_doctor`
+removed-tool warning cap, `uncertain` cap, stale-dependency counts,
+concept-gap and contradiction detectors and instruction-file warnings
+leave out what the caller cannot read, and the `brain_doctor` `repair`
+preview plans from the same checks. `brain_obligation`,
+`brain_intention`, `brain_health`, `brain_trigger` scans,
+`brain_stale_scan`, `brain_review_candidates`, `brain_intent_review`,
+`brain_retention`, `brain_tension` and `brain_context_receipts` answer
+the same way. A local caller and the CLI see no change.
+
+**A remote client runs only a dry dream.** Below local reach (an HTTP
+bind on a non-loopback interface) `brain_dream` serves a dry run and
+refuses a real pass, a step and the staged lifecycle, and
+`brain_maintenance` refuses `run`; schedule them on the vault's own
+host (`o2b brain dream`, `o2b brain maintenance run`, or a stdio or
+loopback client). The lifecycle (including the chain tip), expire,
+evidence, feedback, derived-fact, decision, label, scaffold, dead-end,
+diarize, hygiene refresh and anticipatory-context tools treat a page the
+caller cannot read as absent, and a write aimed at such a page is
+refused before anything is written.
+
+**Derived pages keep the visibility of their sources.** A preference
+the dream pass drafts from signals reserved with `visibility`, or that
+supersedes or rebuts a reserved record, now carries the strictest
+`visibility` of those sources, and a tension page carries the stricter
+`visibility` of its two source notes, refreshed when it is detected
+again. Such pages were written without a `visibility` line before, so
+they may now be withheld from a remote caller.
+
## Upgrading to 1.69.0
No step below is required. Ten changes are visible to an operator or a
diff --git a/hooks/active-inject.ts b/hooks/active-inject.ts
index 2414e390..8c5f5489 100644
--- a/hooks/active-inject.ts
+++ b/hooks/active-inject.ts
@@ -5,13 +5,18 @@
* confirmed and quarantined preferences without explicitly calling
* `brain_query` first.
*
- * Two lanes share the surface, and the order between them is the point.
+ * Three lanes share the surface, and the order between them is the point.
* `Brain/standing-rules.md` is operator-authored and goes FIRST, read
* outside the fail-open memory load so it survives a memory-layer
- * failure and never enters the inject cache. Everything after it -
- * runtime notices, `active.md`, `lessons.md` - is what the agent learned
- * about itself, assembled inside the fail-open boundary and charged
- * against the configured injection budget.
+ * failure and never enters the inject cache. The scoped operator rules
+ * for this session's project and this device
+ * (`Brain/standing-rules/{project,host}/<key>.md`) come next, also read
+ * outside the boundary and never cached - the cache key is vault-wide, so
+ * a cached block could replay one project's rules in another - but
+ * charged against the injection budget. Everything after them - runtime
+ * notices, `active.md`, `lessons.md` - is what the agent learned about
+ * itself, assembled inside the fail-open boundary and charged against
+ * what is left of the configured injection budget.
*
* Contract (identical for Claude Code and Codex):
* stdin: hook payload JSON. The vault path is resolved from the
@@ -23,9 +28,10 @@
* {
* "hookSpecificOutput": {
* "hookEventName": "SessionStart" | "PostCompact",
- * "additionalContext": "<standing-rules block, then the budgeted
- * memory context: runtime notices, the
- * rendered Brain/active.md body, lessons>"
+ * "additionalContext": "<standing-rules block, the scoped rules
+ * block, then the budgeted memory context:
+ * runtime notices, the rendered
+ * Brain/active.md body, lessons>"
* }
* }
*
@@ -59,8 +65,15 @@ import { budgetActiveBody } from "../src/core/brain/active-budget.ts";
import {
INJECT_BUDGET_CHARS_DEFAULT,
loadBrainConfig,
+ resolveScopedRulesMaxChars,
resolveStandingRulesMaxChars,
} from "../src/core/brain/policy.ts";
+import {
+ readScopedRules,
+ SCOPED_RULES_HEADER,
+ SCOPED_RULES_NOTICE_RESERVE,
+} from "../src/core/brain/scoped-rules.ts";
+import { resolveHostScope, resolveProjectScope } from "../src/core/brain/scope-identity.ts";
import {
readStandingRules,
renderStandingRules,
@@ -74,7 +87,13 @@ import { loadInjectContextFailOpen } from "../src/core/brain/inject-failopen.ts"
import { collectRuntimeNotices, renderRuntimeNotices } from "../src/core/brain/runtime-notices.ts";
import { asHookPayload, readHookInput } from "./lib/stdin.ts";
import { isContextEventName } from "./lib/context-events.ts";
-import { emitContextReceipt } from "../src/core/brain/context-receipts.ts";
+import {
+ emitContextReceipt,
+ RECEIPT_ITEM_ACTIVE_BODY,
+ RECEIPT_ITEM_LESSONS_BODY,
+ RECEIPT_ITEM_SCOPED_RULES,
+ RECEIPT_ITEM_STANDING_RULES,
+} from "../src/core/brain/context-receipts.ts";
import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";
import type { InjectContextSource } from "../src/core/brain/inject-failopen.ts";
import type { BrainConfig } from "../src/core/brain/types.ts";
@@ -163,8 +182,13 @@ async function main(): Promise<void> {
});
}
- const meter: InjectionMeter = { sources: [], budgetChars: null };
const limits = resolveInjectionLimits(vault);
+ const meter: InjectionMeter = {
+ sources: [],
+ configuredBudgetChars: limits.injectBudgetChars,
+ budgetChars: null,
+ scopedRulesChars: 0,
+ };
// The operator's standing rules, read BEFORE and OUTSIDE the fail-open
// load below. That single placement buys three properties at once:
@@ -175,6 +199,17 @@ async function main(): Promise<void> {
// is unreadable.
const standingBlock = renderStandingBlock(vault, limits.standingRulesMaxChars, meter);
+ // The scoped operator rules for the project this session runs in (the
+ // payload's `cwd`, else this process's) and for this device. Outside
+ // the fail-open boundary and never cached, like the constitution; but
+ // CHARGED: its length comes off the budget the memory body gets, and
+ // the whole block - header and notices included - fits that budget:
+ // the cap over its sections is what is left once they are reserved.
+ const workspaceDir =
+ typeof payload.cwd === "string" && payload.cwd.length > 0 ? payload.cwd : process.cwd();
+ const scopedBlock = renderScopedBlock(vault, workspaceDir, scopedSectionCap(limits), meter);
+ const memoryBudget = Math.max(0, limits.injectBudgetChars - scopedBlock.length);
+
// Fail-open context load: assemble the injected body inside a guard that
// degrades to the last-good cache (or empty) on any error, never emitting
// a partial or poisoned payload. A successful non-empty body refreshes the
@@ -182,7 +217,7 @@ async function main(): Promise<void> {
const { context: memoryContext, source } = await loadInjectContextFailOpen({
vault,
key: "active",
- assemble: () => assembleActiveContext(vault, limits.injectBudgetChars, meter),
+ assemble: () => assembleActiveContext(vault, memoryBudget, meter),
audit: (degradedSource) =>
auditHook(vault, "inject_failopen_degraded", {
hook: "active-inject",
@@ -191,7 +226,7 @@ async function main(): Promise<void> {
});
// The early return now fires only when there are NEITHER standing rules
// NOR memory - a vault with rules and a broken memory layer still speaks.
- const context = joinBlocks([standingBlock, memoryContext]);
+ const context = joinBlocks([standingBlock, scopedBlock, memoryContext]);
if (context.length === 0) return;
const out = {
@@ -220,9 +255,10 @@ async function main(): Promise<void> {
* its own cap, not `inject_budget_chars`, and emitted whatever the
* memory layer does - so it is the one lane still real in a
* degraded injection.
- * - BUDGETED: charged against `inject_budget_chars`. Two of these
- * exist today and each is charged against the FULL configured
- * ceiling, which is why the receipt records their count.
+ * - BUDGETED: charged against `inject_budget_chars`. The scoped rules
+ * are charged first and their length is subtracted; the active and
+ * lessons bodies are each charged against what is left, which is why
+ * the receipt records the count and the scoped length.
* - UNBUDGETED: assembled inside the boundary but not charged (the
* runtime notices, which are bounded by the number of conditions
* that can hold rather than by a character count).
@@ -244,20 +280,34 @@ interface InjectionSource {
readonly name: string;
readonly text: string;
readonly lane: InjectionLane;
+ /**
+ * Produced outside the fail-open boundary (the standing and scoped
+ * rules), so it reached the payload even when the memory body was
+ * replaced by the cache, and stays in a degraded receipt.
+ */
+ readonly outsideBoundary: boolean;
}
/** Mutable accumulator threaded through the assembly, read after it returns. */
interface InjectionMeter {
readonly sources: InjectionSource[];
- /** The `inject_budget_chars` the budgeted sub-bodies were charged against. */
+ /** The configured `inject_budget_chars`, before the scoped rules are charged. */
+ readonly configuredBudgetChars: number;
+ /**
+ * The configured `inject_budget_chars` once a budgeted body was measured
+ * under it; `null` while nothing was.
+ */
budgetChars: number | null;
+ /** Length of the rendered scoped-rules block, subtracted from the budget; 0 when absent. */
+ scopedRulesChars: number;
}
/** Sub-body identifiers recorded per injection. Structural, not content-derived. */
-const SOURCE_STANDING_RULES = "standing-rules";
+const SOURCE_STANDING_RULES = RECEIPT_ITEM_STANDING_RULES;
+const SOURCE_SCOPED_RULES = RECEIPT_ITEM_SCOPED_RULES;
const SOURCE_RUNTIME_NOTICES = "runtime-notices";
-const SOURCE_ACTIVE_BODY = "active-body";
-const SOURCE_LESSONS_BODY = "lessons-body";
+const SOURCE_ACTIVE_BODY = RECEIPT_ITEM_ACTIVE_BODY;
+const SOURCE_LESSONS_BODY = RECEIPT_ITEM_LESSONS_BODY;
/** Blank line between two injected blocks. */
const BLOCK_SEPARATOR = "\n\n";
@@ -295,9 +345,10 @@ interface RecordInjectionSizeInput {
* sub-bodies in `meter` were never emitted (assembly threw), so the
* record says `sources_measured: false` and drops them - a per-source
* breakdown of a body that was replaced by a cached one would be a
- * finding that never happened. The exempt lane is kept in that case,
- * because it is produced outside the boundary and did reach the payload;
- * omitting it would understate an injection that really happened.
+ * finding that never happened. The sources produced outside the boundary
+ * (the standing and scoped rules) are kept in that case, because they did
+ * reach the payload; omitting them would understate an injection that
+ * really happened.
*
* FAIL-SOFT. The whole body sits in one try/catch. The receipt sink takes
* a continuity-store lock and writes to disk; contention, a read-only
@@ -313,7 +364,7 @@ function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): vo
emitContextReceipt(vault, {
options: { host: "hook", trigger: "session_inject" },
items: input.meter.sources
- .filter((source) => measured || source.lane === LANE_EXEMPT)
+ .filter((source) => measured || source.outsideBoundary)
.map((source) => ({
id: source.name,
bytes: byteLength(source.text),
@@ -323,12 +374,13 @@ function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): vo
...(input.meter.budgetChars !== null && measured
? {
budget: {
+ // The CONFIGURED ceiling, unchanged by the scoped block.
inject_budget_chars: input.meter.budgetChars,
- // Both budgeted sub-bodies are charged against the SAME
- // configured ceiling, so the effective ceiling is this
- // count times `inject_budget_chars`. Recorded as two
- // numbers rather than implied by one.
+ // The active and lessons bodies are each charged against
+ // `inject_budget_chars - scoped_rules_chars`; the scoped
+ // block itself is counted here when it rendered.
budgeted_source_count: budgetedSourceCount(input.meter),
+ scoped_rules_chars: input.meter.scopedRulesChars,
},
}
: {}),
@@ -364,6 +416,23 @@ function budgetedSourceCount(meter: InjectionMeter): number {
interface InjectionLimits {
readonly injectBudgetChars: number;
readonly standingRulesMaxChars: number;
+ readonly scopedRulesMaxChars: number;
+}
+
+/**
+ * The cap over the scoped block's sections: the configured cap, clamped
+ * to what the injection budget leaves once the block's header and the
+ * room for its notices are reserved, floor 0. With it the whole block -
+ * not only its sections - fits the budget it is charged against.
+ */
+function scopedSectionCap(limits: InjectionLimits): number {
+ return Math.max(
+ 0,
+ Math.min(
+ limits.scopedRulesMaxChars,
+ limits.injectBudgetChars - SCOPED_RULES_HEADER.length - SCOPED_RULES_NOTICE_RESERVE,
+ ),
+ );
}
/**
@@ -398,6 +467,7 @@ function resolveInjectionLimits(vault: string): InjectionLimits {
return {
injectBudgetChars: cfg?.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT,
standingRulesMaxChars: resolveStandingRulesMaxChars(cfg),
+ scopedRulesMaxChars: resolveScopedRulesMaxChars(cfg),
};
}
@@ -422,7 +492,61 @@ function renderStandingBlock(vault: string, maxChars: number, meter: InjectionMe
} catch (err) {
block = renderStandingRulesFailure(path, err);
}
- meter.sources.push({ name: SOURCE_STANDING_RULES, text: block, lane: LANE_EXEMPT });
+ meter.sources.push({
+ name: SOURCE_STANDING_RULES,
+ text: block,
+ lane: LANE_EXEMPT,
+ outsideBoundary: true,
+ });
+ return block;
+}
+
+/**
+ * Render the scoped operator rules for this session's project and this
+ * device, or "" when none applies.
+ *
+ * Project and host only: a harness file renders on the MCP surfaces,
+ * where the harness comes from the packaged `--harness`. This hook is
+ * shared by Claude Code and Codex through one `o2b-hook` shim and has no
+ * harness signal of its own, so it resolves the harness to nothing and
+ * matches no harness file.
+ *
+ * Never throws: a failure to resolve the scope or read the directory
+ * must not take the constitution and the memory context down with it.
+ */
+function renderScopedBlock(
+ vault: string,
+ workspaceDir: string,
+ maxChars: number,
+ meter: InjectionMeter,
+): string {
+ let block: string;
+ try {
+ let host: { readonly host: string | null; readonly unreadable: boolean };
+ try {
+ host = resolveHostScope(undefined);
+ } catch {
+ host = { host: null, unreadable: true };
+ }
+ block = readScopedRules(
+ vault,
+ { project: resolveProjectScope(workspaceDir, vault), harness: null, host: host.host },
+ { maxChars, hostUnreadable: host.unreadable },
+ ).text;
+ } catch {
+ return "";
+ }
+ if (block.length === 0) return "";
+ meter.sources.push({
+ name: SOURCE_SCOPED_RULES,
+ text: block,
+ lane: LANE_BUDGETED,
+ outsideBoundary: true,
+ });
+ meter.scopedRulesChars = block.length;
+ // A budgeted source was measured under the configured ceiling, so the
+ // receipt carries the budget block even when no memory body follows.
+ meter.budgetChars = meter.configuredBudgetChars;
return block;
}
@@ -446,6 +570,7 @@ function assembleActiveContext(vault: string, budget: number, meter: InjectionMe
name: SOURCE_RUNTIME_NOTICES,
text: noticesBlock,
lane: LANE_UNBUDGETED,
+ outsideBoundary: false,
});
}
@@ -480,8 +605,11 @@ function readActiveBody(
// the default here rather than raising. Recorded on the meter only at
// this point, because a vault with no `active.md` charged nothing
// against it and a receipt naming a budget nothing was measured under
- // would be a number with no measurement behind it.
- meter.budgetChars = budget;
+ // would be a number with no measurement behind it. The CONFIGURED
+ // ceiling is recorded, not the `budget` argument: that is what is left
+ // after the scoped rules were charged, and the receipt reports the two
+ // separately (`inject_budget_chars`, `scoped_rules_chars`).
+ meter.budgetChars = meter.configuredBudgetChars;
// Auto-load the lessons digest alongside active.md so the agent gets
// the unified, signed, recency-scored corpus (preferences + dead-ends)
@@ -491,9 +619,19 @@ function readActiveBody(
const lessonsBody = readLessonsBody(brainLessonsPath(vault), budget);
const budgetedActive = budgetActiveBody(trimmed, budget);
- meter.sources.push({ name: SOURCE_ACTIVE_BODY, text: budgetedActive, lane: LANE_BUDGETED });
+ meter.sources.push({
+ name: SOURCE_ACTIVE_BODY,
+ text: budgetedActive,
+ lane: LANE_BUDGETED,
+ outsideBoundary: false,
+ });
if (lessonsBody !== null) {
- meter.sources.push({ name: SOURCE_LESSONS_BODY, text: lessonsBody, lane: LANE_BUDGETED });
+ meter.sources.push({
+ name: SOURCE_LESSONS_BODY,
+ text: lessonsBody,
+ lane: LANE_BUDGETED,
+ outsideBoundary: false,
+ });
}
return lessonsBody === null ? budgetedActive : joinBlocks([budgetedActive, lessonsBody]);
diff --git a/install/hermes.md b/install/hermes.md
index a8678715..9cab9c42 100644
--- a/install/hermes.md
+++ b/install/hermes.md
@@ -97,6 +97,67 @@ at a time), so activation is one explicit command:
| Plugin update | **Automatic** — `memory.provider` persists in `config.yaml` | nothing |
| Deactivate / uninstall | Not auto | `hermes memory off` (reverts to built-in) |
+### Multiple Hermes profiles
+
+A Hermes gateway with `gateway.multiplex_profiles: true` serves several
+profiles from one process, and that process's environment belongs to
+the profile that launched it. Since v1.70.0 the plugin then reads its
+profile-scoped settings from each turn's own profile scope - the
+profile's `.env`, as Hermes composes it - and never from the gateway
+process environment:
+
+| Variable | Setting |
+|---|---|
+| `VAULT_DIR` | vault |
+| `VAULT_AGENT_NAME` | agent name |
+| `VAULT_TIMEZONE` | timezone |
+| `OPEN_SECOND_BRAIN_CONFIG` | config file path |
+| `OPEN_SECOND_BRAIN_MCP_TIMEOUT` | MCP request timeout |
+
+Set these in each profile's `.env`. A variable the profile does not set
+falls through to the Open Second Brain config chain (the project
+pointer, the active profile, the config file, the default), not to the
+gateway environment. Each profile gets its own `o2b mcp` child, started
+with its own vault, agent name, timezone and config path, so two
+profiles that share a vault but not an agent name write under their own
+names. Without multiplexing nothing changes: the plugin reads the
+process environment as before.
+
+When one of these variables is also set in the gateway process
+environment, the gateway log names it once per process with a WARNING
+from the plugin's config module, never its value:
+
+```
+open-second-brain: ignoring VAULT_AGENT_NAME from the gateway process environment on a multiplexed gateway; set it in the profile's .env instead
+```
+
+If the gateway bound no profile scope for a call, the plugin refuses to
+guess: the provider reports a `ProfileScopeError` naming the variable
+and the remedy (`hermes gateway restart`), and a turn in that state
+runs without the vault reminder instead of failing.
+
+What stays process-wide on a multiplexed gateway:
+
+- `HOME`, `PATH` and `PATHEXT` describe the machine, not the profile,
+ and are read from the process environment in both modes.
+- `XDG_CONFIG_HOME` and `LOCALAPPDATA`, which locate the config file,
+ are read from the profile's `.env` first; a profile that does not set
+ one uses the gateway process environment's value, so a value set in
+ the launch profile's `.env` is seen by every profile that sets none.
+- Other variables the `o2b mcp` child reads - the search settings,
+ `OPEN_SECOND_BRAIN_MCP_API_KEY`, embedding provider keys and the
+ `TELEGRAM_*` settings - are still inherited from the gateway process
+ environment.
+- A gateway that serves a routed profile home without multiplexing
+ reads the process environment, as Hermes's own memory providers do.
+
+One install pitfall: Hermes looks for a memory provider in its own
+bundled `plugins/memory/open-second-brain/` before
+`$HERMES_HOME/plugins/open-second-brain/`. A copy left in the bundled
+location shadows the plugin `hermes plugins install` and
+`hermes plugins update` manage, so an update appears to change nothing.
+Remove such a copy and restart the gateway.
+
## 5. Verify
```bash
@@ -130,6 +191,13 @@ o2b doctor --vault /path/to/vault --repo .
`memory.provider` persists across updates, so the provider stays active
with no re-activation step.
+Keep the `o2b` on PATH at the plugin's version. The links step 2
+creates point into the plugin and follow it; an `o2b` installed some
+other way must be updated too. Since v1.70.0 the plugin launches its
+bridge with `o2b mcp --harness hermes`, and an older `o2b` refuses
+`--harness` as an unknown flag, so the bridge does not start; the
+gateway log shows the flag in the bridge's stderr.
+
## Uninstall
Deactivate first (reverts to built-in memory), then remove:
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index b8d4c4d3..d489426e 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.69.0",
+ "version": "1.70.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index ce8985f1..9145a3c6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.69.0",
+ "version": "1.70.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.yaml
index 95b02340..4127447a 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.69.0"
+version: "1.70.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index ad4afe87..da60ef36 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.69.0",
+ "version": "1.70.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/codex/README.md b/plugins/codex/README.md
index 6dda182c..94e2f4a8 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.69.0 teaches ingest to read more than Markdown. One format registry decides what a file is: CSV, TSV and HTML files are planned by default and `brain_ingest_source` writes what it derives from them onto the summary page that search indexes - a `## Table` section of fenced plain-text row groups that each repeat the header, with named caps and redacted credential columns, or a `## Parts` section of HTML headings and their line spans, never the body - with `source_format`, `source_content_hash` and the table's counts in frontmatter. PDF, Office, EPUB, RTF and image files are named per file as `format-not-extractable` instead of counted as unknown, and `o2b brain extract` previews the extraction of any file without writing. The recall verdict's root coverage, the daily and weekly briefs, the daily log pages, the analytics, claims, backlinks, MOC audit and doctor readers and the source-cleanup tools now answer at the caller's reach, a summary page carries its source's visibility, private regions and table cells are redacted in linear time, `brain_recall_gate` accepts the `turn_id` the Hermes plugin sends, multi-line prompts that start with a command name are now admitted by the surfacing gate, and the architecture notes name the module edges a link cannot carry instead of claiming there are none. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.70.0 keeps a setting or a rule meant for one context out of the others. On a Hermes gateway that multiplexes profiles, the plugin reads the vault, agent name, timezone, config path and timeout from the turn's profile scope instead of the launch profile's process environment, warns once per gateway variable it ignores, and gives each profile its own MCP child. Standing rules can now be written for one project, one harness or one machine under `Brain/standing-rules/`: the server resolves the project from the linked `.o2b-vault.json` pointer, the harness from the new `o2b mcp --harness` option and the host from the device id, and the SessionStart hook and `brain_context` render the matching files below the operator standing rules, at local reach only and charged against the injection budget. The today, monthly and operator brief views, the doctor's counts and repair preview, and more than twenty other reading and writing tools now answer at the caller's reach, and a remote client runs only a dry dream. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/bridge.py b/plugins/hermes/bridge.py
index ca000609..68221cd0 100644
--- a/plugins/hermes/bridge.py
+++ b/plugins/hermes/bridge.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import json
import logging
+import math
import os
import subprocess
import sys
@@ -24,7 +25,13 @@ from collections import deque
from collections.abc import Mapping
from typing import Any, Protocol, runtime_checkable
+from .config import REQUEST_TIMEOUT_ENV, env_setting
+
PROTOCOL_VERSION = "2025-06-18"
+# The harness this bridge launches the server for. The server resolves its
+# harness scope (which harness-scoped operator rules apply) from this launch
+# argument alone, never from the name a client gives about itself.
+HARNESS_ARGV: tuple[str, ...] = ("--harness", "hermes")
CLIENT_NAME = "open-second-brain-hermes-provider"
logger = logging.getLogger(__name__)
@@ -36,7 +43,9 @@ logger = logging.getLogger(__name__)
# generous on purpose: a tool call can legitimately take tens of seconds when
# it opens the store for writing and the integrity scan runs.
DEFAULT_REQUEST_TIMEOUT_SECONDS = 120.0
-REQUEST_TIMEOUT_ENV = "OPEN_SECOND_BRAIN_MCP_TIMEOUT"
+# ``REQUEST_TIMEOUT_ENV`` lives in config.py with the other profile-scoped
+# names and is re-exported from here; on a multiplexed Hermes gateway it is
+# read from the profile scope, never from the gateway's process environment.
# The child's stderr is where the runtime says why it refused to start ("error:
# 'bun' is not on PATH."), and the JSON-RPC channel only ever reports the
@@ -61,22 +70,31 @@ def resolve_request_timeout() -> float | None:
A non-positive value disables the deadline, which is the escape hatch for
an operator whose vault legitimately outruns it; it is spelled explicitly
rather than reached by a malformed value, and a malformed value falls back
- to the default rather than to no bound at all.
+ to the default rather than to no bound at all. ``nan`` is malformed (it
+ never compares equal, so it would also split every shared-bridge key);
+ ``inf`` is an explicit "no bound", like a non-positive value. The WARNING
+ names the variable only: the value belongs to a profile and lands in the
+ shared gateway log.
+
+ :raises config.ProfileScopeError: on a multiplexed gateway with no profile
+ scope bound; the provider resolves it once where the scope is bound
+ and hands the bridge the result (see ``McpBrainBridge(timeout=...)``).
"""
- raw = os.environ.get(REQUEST_TIMEOUT_ENV)
+ raw = env_setting(REQUEST_TIMEOUT_ENV)
if raw is None or raw.strip() == "":
return DEFAULT_REQUEST_TIMEOUT_SECONDS
try:
seconds = float(raw)
except ValueError:
+ seconds = math.nan
+ if math.isnan(seconds):
logger.warning(
- "%s is not a number (%r); using the %.0fs default",
+ "%s is not a number; using the %.0fs default",
REQUEST_TIMEOUT_ENV,
- raw,
DEFAULT_REQUEST_TIMEOUT_SECONDS,
)
return DEFAULT_REQUEST_TIMEOUT_SECONDS
- return None if seconds <= 0 else seconds
+ return None if seconds <= 0 or math.isinf(seconds) else seconds
class BridgeError(RuntimeError):
@@ -251,6 +269,12 @@ class McpBrainBridge:
``PATH`` too small to contain Bun, and the ``o2b`` wrapper refuses to run
when its own ``command -v bun`` misses - so the caller that resolved an
absolute Bun passes an environment carrying that Bun's directory.
+
+ ``timeout`` fixes the per-request deadline at construction; a non-positive
+ value disables it. ``None`` (the default) reads it at every ``start`` as
+ before. A multiplexed Hermes gateway passes it, because a restart can run
+ on the plugin's own capture thread, where no profile scope is bound and the
+ scoped setting cannot be read.
"""
def __init__(
@@ -262,8 +286,10 @@ class McpBrainBridge:
spawn: Any = None,
cwd: str | None = None,
env: Mapping[str, str] | None = None,
+ timeout: float | None = None,
) -> None:
self._vault = vault
+ self._timeout = timeout
self._repo_root = repo_root
self._command = command
self._spawn = spawn or self._default_spawn
@@ -291,6 +317,7 @@ class McpBrainBridge:
# directory - which silently empties skill_auto_attach.
if self._repo_root:
argv += ["--repo", self._repo_root]
+ argv += HARNESS_ARGV
return argv
_watchdog_absent_warned = False
@@ -444,6 +471,11 @@ class McpBrainBridge:
return exc
return type(exc)(f"{exc}\n--- child stderr (last lines) ---\n{excerpt}")
+ def _request_timeout(self) -> float | None:
+ if self._timeout is None:
+ return resolve_request_timeout()
+ return None if self._timeout <= 0 else self._timeout
+
def start(self) -> None:
with self._lock:
if self._started:
@@ -452,7 +484,7 @@ class McpBrainBridge:
self._stderr_thread = None
self._proc = self._spawn(self._argv())
self._client = JsonRpcStdioClient(
- self._proc.stdin, self._proc.stdout, timeout=resolve_request_timeout()
+ self._proc.stdin, self._proc.stdout, timeout=self._request_timeout()
)
pid = getattr(self._proc, "pid", "unknown")
logger.debug("open-second-brain MCP child spawned pid=%s", pid)
diff --git a/plugins/hermes/cli.py b/plugins/hermes/cli.py
index 1c8e8c92..2a5902db 100644
--- a/plugins/hermes/cli.py
+++ b/plugins/hermes/cli.py
@@ -67,12 +67,28 @@ def _status() -> int:
return 0 if available else 1
+#: ``settings_source:`` values. The command runs in its own process, which
+#: Hermes never marks as multiplexed, so the process-environment line says it
+#: describes this command and names where a multiplexed gateway reads instead.
+_SOURCE_PROFILE_SCOPE = "profile scope (multiplexed gateway)"
+_SOURCE_PROCESS_ENVIRONMENT = (
+ "process environment (this command; a gateway with gateway.multiplex_profiles "
+ "reads each profile's .env)"
+)
+
+
def _config() -> int:
- # The config path is resolved from the environment alone and is printable
- # even when the file behind it is not, which is exactly the case an
- # operator needs to see: the path this process looked at.
- print(f"config_path: {config.config_path()}")
+ # Which source answered comes first and cannot fail: on a multiplexed
+ # gateway the profile scope does, and the gateway's own environment is
+ # ignored, so an operator comparing values needs to know which to check.
+ source = _SOURCE_PROFILE_SCOPE if config.is_multiplexed() else _SOURCE_PROCESS_ENVIRONMENT
+ print(f"settings_source: {source}")
try:
+ # The config path is printable even when the file behind it is not,
+ # which is exactly the case an operator needs to see: the path this
+ # process looked at. It is inside the try because on a multiplexed
+ # gateway with no profile scope bound it cannot be resolved at all.
+ print(f"config_path: {config.config_path()}")
vault = config.resolve_vault()
agent_name = config.resolve_agent_name()
timezone = config.resolve_timezone()
diff --git a/plugins/hermes/config.py b/plugins/hermes/config.py
index b246133c..0d9b44d9 100644
--- a/plugins/hermes/config.py
+++ b/plugins/hermes/config.py
@@ -19,11 +19,29 @@ fixture table through BOTH implementations rather than asserting each side's
behaviour separately.
- config path: ``OPEN_SECOND_BRAIN_CONFIG`` -> ``XDG_CONFIG_HOME`` -> ``~/.config``
+ (``XDG_CONFIG_HOME`` and ``LOCALAPPDATA`` through
+ :func:`scope_first_setting`)
- vault: ``VAULT_DIR`` env -> project pointer walk-up -> active named
profile -> ``vault`` field -> ``None``, every result tilde-expanded
- agent name: ``VAULT_AGENT_NAME`` env -> ``agent_name``/``agentName`` -> ``"agent"``
- timezone: ``VAULT_TIMEZONE`` env -> ``timezone`` field -> ``None``
+## Two modes: a multiplexed Hermes gateway
+
+"env" above means :func:`env_setting`, the one reader of the names in
+:data:`PROFILE_SCOPED_ENV`. A Hermes gateway with ``multiplex_profiles`` serves
+several profiles from one process, and that process's environment belongs to
+the profile that launched it. So when Hermes reports multiplexing, a scoped
+name is read from the profile scope Hermes bound for the call (the profile's
+``.env`` and secret sources) and NEVER from ``os.environ``; an unset scoped
+value falls through to the rest of the chain (pointer, profile, config key,
+default), and a call with no scope bound refuses with
+:class:`ProfileScopeError`. Without multiplexing - and whenever Hermes or its
+``agent.secret_scope`` module is absent, which is how the parity suite and the
+doctor load this file - the reader is the plain ``os.environ`` lookup, so every
+answer is unchanged. A scope module that is present but fails to import is
+treated as multiplexed with no scope bound, never as absent.
+
## Where the mirror is deliberately imperfect
Three differences remain, named here rather than left as a false claim:
@@ -51,11 +69,13 @@ processing, and the LAST occurrence of a duplicate key winning.
from __future__ import annotations
+import importlib
import json
import logging
import os
import re
import stat
+import threading
from collections.abc import Mapping
from pathlib import Path
@@ -76,6 +96,30 @@ AGENT_NAME_ENV = "VAULT_AGENT_NAME"
TIMEZONE_ENV = "VAULT_TIMEZONE"
CONFIG_PATH_ENV = "OPEN_SECOND_BRAIN_CONFIG"
XDG_CONFIG_HOME_ENV = "XDG_CONFIG_HOME"
+LOCALAPPDATA_ENV = "LOCALAPPDATA"
+#: Per-request deadline of the MCP bridge, read by ``bridge.py``.
+REQUEST_TIMEOUT_ENV = "OPEN_SECOND_BRAIN_MCP_TIMEOUT"
+
+#: The settings that belong to a Hermes profile rather than to the process.
+#: On a multiplexed gateway these come from the bound profile scope only.
+#: ``PATH``, ``PATHEXT`` and ``HOME`` describe the operating system and stay
+#: process-global in both modes: Hermes keeps them out of a profile scope.
+PROFILE_SCOPED_ENV: tuple[str, ...] = (
+ VAULT_DIR_ENV,
+ AGENT_NAME_ENV,
+ TIMEZONE_ENV,
+ CONFIG_PATH_ENV,
+ REQUEST_TIMEOUT_ENV,
+)
+
+#: The config directories, which are scope-first on a multiplexed gateway.
+#: Hermes scopes them like any other ``.env`` name, so a profile's value lives
+#: in its scope and only the launch profile's value is in ``os.environ``;
+#: reading ``os.environ`` alone would hand every profile the launch profile's
+#: config file. Unlike :data:`PROFILE_SCOPED_ENV`, a name the scope leaves
+#: unset falls back to the process environment, because on most installs it
+#: is the operating system's own value and no profile sets it.
+SCOPE_FIRST_ENV: tuple[str, ...] = (XDG_CONFIG_HOME_ENV, LOCALAPPDATA_ENV)
#: Characters a config value may not contain, mirroring
#: ``CONFIG_VALUE_REJECTED_CHARS`` in ``src/core/config.ts``. The reader strips
@@ -95,6 +139,12 @@ _TARGET_TEMPLATE_PATH = _TEMPLATES_DIR / f"identity-reminder.{_TARGET}.txt"
_template_cache: str | None = None
+# Scoped names already reported as ignored in this process, plus the scope
+# module's own name once its import failure is reported. One WARNING per name,
+# not per call: the resolvers run on every turn.
+_scope_warned: set[str] = set()
+_scope_warned_lock = threading.Lock()
+
# Line splitter matching the TypeScript `text.split(/\r?\n/)`. `str.splitlines`
# also breaks on form feed, U+2028 and friends, which would make the two
# parsers disagree about how many lines a file has.
@@ -127,6 +177,180 @@ class ConfigReadError(Exception):
self.reason = reason
+class ProfileScopeError(ConfigReadError):
+ """A profile-scoped setting was read on a multiplexed gateway with no scope.
+
+ A subclass of :class:`ConfigReadError` so every site that already refuses,
+ propagates or reports an unreadable configuration does the same here: the
+ setting the operator configured exists, and it is not the one this call
+ can see. The message names the setting and never a value; it does not use
+ the parent's file-read template, which is pinned to the file case.
+ """
+
+ def __init__(self, name: str) -> None:
+ Exception.__init__(
+ self,
+ f"{name} cannot be resolved: this multiplexed Hermes gateway bound no "
+ "profile scope for the call, and Open Second Brain does not fall back to "
+ "the gateway's process environment, which belongs to the launch profile. "
+ "Restart the gateway (hermes gateway restart); if it persists, report it.",
+ )
+ self.name = name
+ self.path = ""
+ self.reason = "no profile scope bound"
+
+
+#: Hermes's profile-scope module, and the module names whose absence means
+#: "not running inside a Hermes that scopes settings".
+_SCOPE_MODULE_NAME = "agent.secret_scope"
+_ABSENT_SCOPE_MODULE_NAMES = frozenset({"agent", _SCOPE_MODULE_NAME})
+
+
+#: Set once the scope module failed to import for a reason other than its
+#: absence, so later reads fail closed without importing it again (a present
+#: module that fails would otherwise rerun its top-level code on every read).
+#: Absent and present modules are still looked up per call.
+_scope_module_failed = False
+
+
+class _UnusableProfileScope:
+ """Stands in for a Hermes scope module that is present but failed to import.
+
+ It answers "multiplexed, no scope bound", so every profile-scoped read
+ refuses with :class:`ProfileScopeError` instead of serving the launch
+ profile's process environment to every profile.
+ """
+
+ class UnscopedSecretError(Exception):
+ """The scope module could not be imported, so no scope is bound."""
+
+ @staticmethod
+ def is_multiplex_active() -> bool:
+ return True
+
+ @classmethod
+ def get_secret(cls, name: str, default: str | None = None) -> str | None:
+ raise cls.UnscopedSecretError(name)
+
+
+def _profile_scope_module():
+ """Hermes's ``agent.secret_scope`` module, or ``None`` outside Hermes.
+
+ Imported lazily, absolutely and per call: this file is also loaded by file
+ location with no package and no Hermes (the resolver parity suite and the
+ doctor's parity check), where the import must fail quietly and leave the
+ process-environment answers in force. Only the absence of ``agent`` or of
+ ``agent.secret_scope`` counts as "outside Hermes"; any other import failure
+ is a Hermes whose scoping is broken, which fails closed: one WARNING naming
+ the exception type, then :class:`_UnusableProfileScope`, which later calls
+ return without importing the module again.
+ """
+ global _scope_module_failed
+ if _scope_module_failed:
+ return _UnusableProfileScope
+ try:
+ return importlib.import_module(_SCOPE_MODULE_NAME)
+ except ModuleNotFoundError as exc:
+ if exc.name in _ABSENT_SCOPE_MODULE_NAMES:
+ return None
+ failure: Exception = exc
+ except Exception as exc: # noqa: BLE001 - any failure of a present module fails closed
+ failure = exc
+ _scope_module_failed = True
+ _warn_scope_module_failed(failure)
+ return _UnusableProfileScope
+
+
+def _warn_scope_module_failed(exc: Exception) -> None:
+ """Say once per process that the scope module failed, naming its type only."""
+ with _scope_warned_lock:
+ if _SCOPE_MODULE_NAME in _scope_warned:
+ return
+ _scope_warned.add(_SCOPE_MODULE_NAME)
+ logger.warning(
+ "%s: %s failed to import (%s); profile-scoped settings are refused until it imports",
+ PLUGIN_NAME,
+ _SCOPE_MODULE_NAME,
+ type(exc).__name__,
+ )
+
+
+def is_multiplexed() -> bool:
+ """Whether Hermes reports a multiplexed gateway for the current call."""
+ scope_module = _profile_scope_module()
+ return scope_module is not None and bool(scope_module.is_multiplex_active())
+
+
+def env_setting(name: str) -> str | None:
+ """The one reader of a profile-scoped setting; empty counts as unset.
+
+ Not multiplexed: ``os.environ``, exactly as before. Multiplexed: the bound
+ profile scope only - a miss is ``None`` and the caller's chain continues;
+ the process environment is never consulted. Names outside
+ :data:`PROFILE_SCOPED_ENV` are process-global and always read from
+ ``os.environ``.
+
+ :raises ProfileScopeError: when multiplexed and no scope is bound.
+ """
+ scope_module = _profile_scope_module() if name in PROFILE_SCOPED_ENV else None
+ if scope_module is None or not scope_module.is_multiplex_active():
+ return os.environ.get(name) or None
+ _warn_ignored_process_value(name)
+ try:
+ value = scope_module.get_secret(name, None)
+ except scope_module.UnscopedSecretError as exc:
+ raise ProfileScopeError(name) from exc
+ return value or None
+
+
+def scope_first_setting(name: str) -> str | None:
+ """A :data:`SCOPE_FIRST_ENV` name: the bound scope's value, else ``os.environ``.
+
+ Not multiplexed: ``os.environ``, exactly as before, and the scope is never
+ read. Multiplexed: the bound profile scope's non-empty value, falling back
+ to the process environment when the scope has none.
+
+ :raises ProfileScopeError: when multiplexed and no scope is bound.
+ """
+ scope_module = _profile_scope_module()
+ if scope_module is not None and scope_module.is_multiplex_active():
+ try:
+ value = scope_module.get_secret(name, None)
+ except scope_module.UnscopedSecretError as exc:
+ raise ProfileScopeError(name) from exc
+ if value:
+ return value
+ return os.environ.get(name) or None
+
+
+def _warn_ignored_process_value(name: str) -> None:
+ """Say once per process that a gateway-environment value is not used.
+
+ Names the variable and never its value: the value belongs to the launch
+ profile and may be a path or an identity the other profiles must not see.
+ """
+ if not os.environ.get(name):
+ return
+ with _scope_warned_lock:
+ if name in _scope_warned:
+ return
+ _scope_warned.add(name)
+ logger.warning(
+ "%s: ignoring %s from the gateway process environment on a multiplexed gateway; "
+ "set it in the profile's .env instead",
+ PLUGIN_NAME,
+ name,
+ )
+
+
+def _reset_scope_warnings_for_tests() -> None:
+ """Test-only: forget which ignored names were already reported and a failed import."""
+ global _scope_module_failed
+ with _scope_warned_lock:
+ _scope_warned.clear()
+ _scope_module_failed = False
+
+
class ConfigValueError(ValueError):
"""A value that cannot survive the round trip through the config format."""
@@ -179,16 +403,16 @@ def expand_tilde(value: str) -> str:
def _windows_local_app_data() -> Path:
"""``%LOCALAPPDATA%``, or ``~/AppData/Local`` in a stripped environment."""
- local = os.environ.get("LOCALAPPDATA")
+ local = scope_first_setting(LOCALAPPDATA_ENV)
return Path(local) if local else Path.home() / "AppData" / "Local"
def config_path() -> Path:
"""Resolve the plugin config path (``OPEN_SECOND_BRAIN_CONFIG`` -> XDG -> platform default)."""
- override = os.environ.get(CONFIG_PATH_ENV)
+ override = env_setting(CONFIG_PATH_ENV)
if override:
return Path(expand_tilde(override))
- xdg = os.environ.get(XDG_CONFIG_HOME_ENV)
+ xdg = scope_first_setting(XDG_CONFIG_HOME_ENV)
if xdg:
return Path(expand_tilde(xdg)) / PLUGIN_NAME / CONFIG_FILENAME
if os.name == "nt":
@@ -355,7 +579,7 @@ def resolve_agent_name() -> str:
:raises ConfigReadError: when the config file is present but unreadable.
"""
- env_value = os.environ.get(AGENT_NAME_ENV)
+ env_value = env_setting(AGENT_NAME_ENV)
if env_value:
return env_value
data = _config_data()
@@ -377,7 +601,7 @@ def resolve_vault(cwd: str | None = None) -> str | None:
directory when omitted, which is what the gateway passes implicitly.
:raises ConfigReadError: when the config file is present but unreadable.
"""
- env_value = os.environ.get(VAULT_DIR_ENV)
+ env_value = env_setting(VAULT_DIR_ENV)
if env_value:
return expand_tilde(env_value)
pointer_vault = _resolve_pointer_vault(cwd if cwd is not None else os.getcwd())
@@ -403,7 +627,7 @@ def resolve_timezone() -> str | None:
:raises ConfigReadError: when the config file is present but unreadable.
"""
- env_value = os.environ.get(TIMEZONE_ENV)
+ env_value = env_setting(TIMEZONE_ENV)
if env_value:
return env_value
return _config_data().get("timezone") or None
@@ -474,7 +698,10 @@ def shadowing_source(key: str) -> str | None:
env_key = {"vault": VAULT_DIR_ENV, "agent_name": AGENT_NAME_ENV, "timezone": TIMEZONE_ENV}.get(
key
)
- if env_key and os.environ.get(env_key):
+ if env_key and is_multiplexed():
+ if env_setting(env_key):
+ return f"the {env_key} setting in this Hermes profile's .env overrides the config file"
+ elif env_key and os.environ.get(env_key):
return f"the {env_key} environment variable overrides the config file"
if key != "vault":
return None
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 95b02340..4127447a 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.69.0"
+version: "1.70.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.py
index a4dec061..9f5d9a5e 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -28,7 +28,7 @@ if TYPE_CHECKING:
from . import config
from ._base import MemoryProvider
from ._schemas import static_tool_schemas
-from .bridge import BrainBridge, BridgeError, McpBrainBridge
+from .bridge import BrainBridge, BridgeError, McpBrainBridge, resolve_request_timeout
logger = logging.getLogger(__name__)
@@ -159,7 +159,10 @@ _PREFETCH_QUERY_MODE = "ranked"
# configuration in this Python process. Cache eviction deliberately calls
# AIAgent.release_clients() without shutting down memory providers, so
# constructing one Bun child per provider leaks a child for every new session.
-_SharedBridgeKey = tuple[str | None, str | None, tuple[str, ...], str | None]
+# The trailing tuple is the identity the child runs under on a multiplexed
+# gateway (agent name, timezone, config path, request deadline); it is empty
+# without multiplexing, where those are constant for the whole process.
+_SharedBridgeKey = tuple[str | None, str | None, tuple[str, ...], str | None, tuple[Any, ...]]
_SHARED_BRIDGES: dict[_SharedBridgeKey, BrainBridge] = {}
_SHARED_BRIDGES_LOCK = threading.RLock()
@@ -169,6 +172,7 @@ def _shared_bridge_key(
repo_root: str | None,
command: tuple[str, ...],
env: Mapping[str, str] | None = None,
+ identity: tuple[Any, ...] = (),
) -> _SharedBridgeKey:
"""Identity of a bridge: what it runs, where, and the ``PATH`` it runs with.
@@ -176,8 +180,18 @@ def _shared_bridge_key(
two children launched with different search paths are different servers -
sharing one bridge between them would hand the second caller a child that
resolved its runtime somewhere else.
+
+ ``identity`` carries what a multiplexed gateway's profiles may differ in
+ besides the vault: two profiles sharing a vault under different agent
+ names must not share one child, or one of them writes as the other.
"""
- return (vault, repo_root, tuple(command), None if env is None else env.get("PATH"))
+ return (
+ vault,
+ repo_root,
+ tuple(command),
+ None if env is None else env.get("PATH"),
+ tuple(identity),
+ )
def _get_shared_bridge(
@@ -186,17 +200,25 @@ def _get_shared_bridge(
repo_root: str | None,
command: tuple[str, ...],
env: Mapping[str, str] | None = None,
+ identity: tuple[Any, ...] = (),
+ timeout: float | None = None,
) -> BrainBridge:
- """Return the one bridge for this gateway/configuration key."""
- key = _shared_bridge_key(vault, repo_root, command, env)
+ """Return the one bridge for this gateway/configuration key.
+
+ ``timeout`` is passed to the bridge only when given (a multiplexed
+ gateway); otherwise the bridge reads its deadline at start, as before.
+ """
+ key = _shared_bridge_key(vault, repo_root, command, env, identity)
with _SHARED_BRIDGES_LOCK:
bridge = _SHARED_BRIDGES.get(key)
if bridge is None:
+ extra: dict[str, Any] = {} if timeout is None else {"timeout": timeout}
bridge = McpBrainBridge(
vault=vault,
repo_root=repo_root,
command=command,
env=env,
+ **extra,
)
_SHARED_BRIDGES[key] = bridge
return bridge
@@ -214,6 +236,30 @@ def _shutdown_shared_bridges() -> None:
pass
+_scope_degrade_warned = False
+_scope_degrade_lock = threading.Lock()
+
+
+def _warn_scope_degrade_once() -> None:
+ """One WARNING per process when ``prefetch`` runs with no profile scope."""
+ global _scope_degrade_warned
+ with _scope_degrade_lock:
+ if _scope_degrade_warned:
+ return
+ _scope_degrade_warned = True
+ logger.warning(
+ "%s: no profile scope bound for this turn; the vault reminder is omitted",
+ OpenSecondBrainMemoryProvider.PROVIDER_NAME,
+ )
+
+
+def _reset_scope_degrade_warning_for_tests() -> None:
+ """Test-only: allow the prefetch degrade warning to fire again."""
+ global _scope_degrade_warned
+ with _scope_degrade_lock:
+ _scope_degrade_warned = False
+
+
def _reset_shared_bridges_for_tests() -> None:
"""Clear the process registry without exposing it as provider API."""
_shutdown_shared_bridges()
@@ -387,12 +433,27 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
vault = config.resolve_vault()
repo_root = self._repo_root()
command = self._resolve_command()
- self._bridge = _get_shared_bridge(
- vault=vault,
- repo_root=repo_root,
- command=command,
- env=self._resolve_env(),
- )
+ env = self._resolve_env()
+ if config.is_multiplexed():
+ # Resolved here, once, where Hermes has bound this profile's
+ # scope: the child and every restart of it must not consult
+ # the gateway's environment, which is the launch profile's.
+ env, identity, timeout = self._scoped_child(env)
+ self._bridge = _get_shared_bridge(
+ vault=vault,
+ repo_root=repo_root,
+ command=command,
+ env=env,
+ identity=identity,
+ timeout=timeout,
+ )
+ else:
+ self._bridge = _get_shared_bridge(
+ vault=vault,
+ repo_root=repo_root,
+ command=command,
+ env=env,
+ )
self._bridge_shared = True
try:
assert self._bridge is not None
@@ -415,6 +476,50 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
root = Path(__file__).resolve().parents[2]
return str(root) if (root / "skills").is_dir() else None
+ @staticmethod
+ def _scoped_child(
+ base: Mapping[str, str] | None,
+ ) -> tuple[dict[str, str], tuple[Any, ...], float]:
+ """Child environment, bridge identity and deadline for this profile.
+
+ Multiplexed gateways only. The child inherits the gateway's
+ environment, and the TypeScript core reads the agent name, timezone
+ and config path from it - so every profile-scoped name is removed and
+ the scope's own non-empty values are set in its place; a name the
+ scope leaves unset is resolved by the child from the config file, as
+ the plugin resolves it. The config directories
+ (:data:`config.SCOPE_FIRST_ENV`) are overridden only when the scope
+ sets them, so the child looks for the same config file the plugin
+ resolved. The deadline is fixed here (``0.0`` when
+ disabled) so a restart never reads the scope from a thread that has
+ none.
+
+ :raises config.ProfileScopeError: when no profile scope is bound.
+ """
+ env = dict(os.environ if base is None else base)
+ for name in config.PROFILE_SCOPED_ENV:
+ env.pop(name, None)
+ for name in config.PROFILE_SCOPED_ENV:
+ value = config.env_setting(name)
+ if value:
+ env[name] = value
+ for name in config.SCOPE_FIRST_ENV:
+ value = config.scope_first_setting(name)
+ if value:
+ env[name] = value
+ deadline = resolve_request_timeout()
+ timeout = 0.0 if deadline is None else deadline
+ identity = (
+ config.resolve_agent_name(),
+ config.resolve_timezone(),
+ str(config.config_path()),
+ timeout,
+ # The core derives its config, data and state directories from
+ # these, so two profiles that differ only here need two children.
+ *(env.get(name) for name in config.SCOPE_FIRST_ENV),
+ )
+ return env, identity, timeout
+
@staticmethod
def _resolve_env() -> dict[str, str] | None:
"""Environment for the MCP child, or ``None`` to inherit this process's.
@@ -584,7 +689,13 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
"""
del provider_config # the host's own store holds nothing for us
status: dict[str, Any] = dict(_resolved_config_values())
- status["config_file"] = str(config.config_path())
+ try:
+ status["config_file"] = str(config.config_path())
+ except config.ConfigReadError:
+ # A multiplexed gateway with no profile scope bound: the path
+ # cannot be resolved, so the field is skipped like any other
+ # unreadable value rather than failing the status call.
+ pass
return status
def save_config(self, values: dict[str, Any], hermes_home: str) -> None:
@@ -764,7 +875,14 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
skills_block = str(attach.get("block", "") or "")
if attach.get("enabled") and skills_block:
parts.append(skills_block)
- reminder = config.build_reminder()
+ try:
+ reminder = config.build_reminder()
+ except config.ProfileScopeError:
+ # Degrade like `_safe_call`: a turn with no bound profile scope
+ # cannot know whose identity to remind of, and failing the turn
+ # over a reminder would be worse than omitting it.
+ _warn_scope_degrade_once()
+ reminder = None
if reminder:
parts.append(reminder)
return "\n\n".join(parts)
diff --git a/pyproject.toml b/pyproject.toml
index 369c66c8..c41a284d 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.69.0"
+version = "1.70.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index d34c618d..18c75ba4 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -72,6 +72,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("writer-only", "boolean"),
flag("tool-profile", "string"),
flag("host-target", "string"),
+ flag("harness", "string"),
flag("probe", "boolean"),
flag("allow-tool", "string-array"),
flag("disable-tool", "string-array"),
diff --git a/src/cli/main.ts b/src/cli/main.ts
index a5750aee..6a106ad0 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -94,6 +94,7 @@ import {
isInstallTargetId,
type InstallTargetId,
} from "../core/runtime/host-facts.ts";
+import { HARNESS_IDS, isHarnessId, type HarnessId } from "../core/brain/scoped-rules.ts";
// ── Subcommands ─────────────────────────────────────────────────────────────
@@ -722,6 +723,22 @@ async function cmdIndex(argv: string[]): Promise<number> {
return 0;
}
+/** The C1 control range, which `JSON.stringify` leaves as raw characters. */
+const C1_CONTROL_RE = /[\u0080-\u009f]/g;
+
+/**
+ * A refused argv value as it is echoed to stderr: JSON-quoted, which
+ * escapes the C0 controls, with the C1 controls (the 8-bit CSI U+009B
+ * among them) escaped as `\uXXXX` too, so no terminal control sequence
+ * reaches the operator's screen.
+ */
+function quoteRefusedValue(value: string): string {
+ return JSON.stringify(value).replace(
+ C1_CONTROL_RE,
+ (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,
+ );
+}
+
async function cmdMcp(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, {
vault: { type: "string" },
@@ -731,6 +748,7 @@ async function cmdMcp(argv: string[]): Promise<number> {
"writer-only": { type: "boolean" },
"tool-profile": { type: "string" },
"host-target": { type: "string" },
+ harness: { type: "string" },
probe: { type: "boolean" },
json: { type: "boolean" },
transport: { type: "string", default: "stdio" },
@@ -767,16 +785,36 @@ async function cmdMcp(argv: string[]): Promise<number> {
// An unrecognised value is refused rather than dropped: silently
// ignoring it would report the ceiling as unchecked on a host that
// publishes one, which is the exact silence this flag exists to end.
+ // The refused value is echoed quoted and escaped (quoteRefusedValue),
+ // so a control character in it reaches stderr escaped.
const hostTargetFlag = flags["host-target"] as string | undefined;
if (hostTargetFlag !== undefined && !isInstallTargetId(hostTargetFlag)) {
process.stderr.write(
- `o2b mcp: invalid --host-target value: ${hostTargetFlag}; ` +
+ `o2b mcp: invalid --host-target value: ${quoteRefusedValue(hostTargetFlag)}; ` +
`expected one of: ${INSTALL_TARGET_IDS.join(", ")}\n`,
);
return 2;
}
const hostTarget = hostTargetFlag as InstallTargetId | undefined;
+ // Which harness launched this server, for the scoped standing rules
+ // (`Brain/standing-rules/harness/<id>.md`). Written by the packager into
+ // the plugin registration (Claude Code) or the bridge argv (Hermes);
+ // absent falls back to `--host-target`. Refused when unknown for the
+ // same reason `--host-target` is: a typo would silently match no file.
+ const harnessFlag = flags["harness"] as string | undefined;
+ if (harnessFlag !== undefined && !isHarnessId(harnessFlag)) {
+ process.stderr.write(
+ `o2b mcp: invalid --harness value: ${quoteRefusedValue(harnessFlag)}; ` +
+ `expected one of: ${HARNESS_IDS.join(", ")}\n`,
+ );
+ return 2;
+ }
+ const harness = harnessFlag as HarnessId | undefined;
+ // Captured once, at launch: the project scope is the directory the
+ // runtime started this server in, not wherever a later chdir points.
+ const workspaceDir = process.cwd();
+
const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
const transport = flags["transport"] as string;
if (transport !== "stdio" && transport !== "http") {
@@ -875,7 +913,7 @@ async function cmdMcp(argv: string[]): Promise<number> {
const handle = await startHttp(
{ vault, configPath: config, repoRoot },
{ host, port, apiKey, faultCounts: () => faults.counts() },
- { scope, serverName, capabilityWindow, hostTarget },
+ { scope, serverName, capabilityWindow, hostTarget, harness, workspaceDir },
);
// Log the actually-bound endpoint. With the default --port 0 the OS
// assigns an ephemeral port, so the requested `port` value ("0") would
@@ -914,7 +952,7 @@ async function cmdMcp(argv: string[]): Promise<number> {
stdio.signals = installMcpSignalDrain({ close: () => live.close() });
},
},
- { scope, serverName, capabilityWindow, hostTarget },
+ { scope, serverName, capabilityWindow, hostTarget, harness, workspaceDir },
);
return stdio.signals?.exitCode() ?? code;
} finally {
diff --git a/src/core/brain/anticipatory-cache.ts b/src/core/brain/anticipatory-cache.ts
index 5a06010b..632b7774 100644
--- a/src/core/brain/anticipatory-cache.ts
+++ b/src/core/brain/anticipatory-cache.ts
@@ -245,6 +245,8 @@ interface BuildBundleInput {
readonly agentScope: string | undefined;
/** Injected clock; the stamp's window is anchored to it. */
readonly now: Date;
+ /** Candidate filter handed to the pack (absolute paths); absent keeps every candidate. */
+ readonly visible?: (absPath: string) => boolean;
}
interface BuiltBundle {
@@ -256,6 +258,7 @@ function buildBundle(vault: string, input: BuildBundleInput): BuiltBundle {
const pack = packContext(vault, {
maxTokens: input.maxTokens,
...(input.agentScope !== undefined ? { agentScope: input.agentScope } : {}),
+ ...(input.visible !== undefined ? { visible: input.visible } : {}),
stamp: { now: input.now },
});
const signal = input.signalText?.trim() ?? "";
@@ -430,3 +433,41 @@ export function readAnticipatoryContext(
}).context,
});
}
+
+export interface BuildReaderAnticipatoryContextInput extends ReadAnticipatoryContextInput {
+ /** Latest user-visible signal steering the session hits, if any. */
+ readonly signalText?: string;
+ /** Candidate filter for one reader (absolute paths). */
+ readonly visible: (absPath: string) => boolean;
+}
+
+/**
+ * A live bundle built for one reader, outside the shared cache.
+ *
+ * The cache entry is keyed by lineage root and owner scope only, so it
+ * holds the bundle one particular reader was entitled to. A reader whose
+ * candidates are filtered must neither be served that entry (it may carry
+ * pages this reader cannot read) nor write its own filtered bundle over
+ * it (the operator would then be served a narrowed bundle). This path
+ * therefore never reads or writes the cache file and answers `miss`,
+ * which is what it is: no cached bundle answered the call.
+ */
+export function buildReaderAnticipatoryContext(
+ vault: string,
+ input: BuildReaderAnticipatoryContextInput,
+): ReadAnticipatoryContextResult {
+ const rootId = resolveRootId(vault, input.sessionId);
+ const signal = input.signalText?.trim();
+ return Object.freeze({
+ cache_state: "miss" as const,
+ root_session_id: rootId,
+ context: buildBundle(vault, {
+ sessionId: input.sessionId,
+ signalText: signal !== undefined && signal.length > 0 ? signal : undefined,
+ maxTokens: input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ agentScope: input.agentScope,
+ now: input.now,
+ visible: input.visible,
+ }).context,
+ });
+}
diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.ts
index 286cb03a..3ad562b4 100644
--- a/src/core/brain/apply-evidence.ts
+++ b/src/core/brain/apply-evidence.ts
@@ -32,6 +32,7 @@
import { existsSync } from "node:fs";
import { join, relative } from "node:path";
+import { vaultRelative } from "../path-safety.ts";
import { sanitiseTextField } from "../redactor.ts";
import {
computePayloadHash,
@@ -142,6 +143,26 @@ export interface AppendApplyEvidenceOptions {
* the default is to preserve pre-v0.10.16 behaviour.
*/
readonly role?: BrainRole;
+ /**
+ * The vault-relative paths the caller may read. A preference file it
+ * may not read is refused with {@link BrainPreferenceNotFoundError}
+ * exactly as a missing one is, before anything is written. Absent,
+ * every preference counts.
+ */
+ readonly readable?: (rel: string) => boolean;
+}
+
+/**
+ * Does `prefFilePath` name a preference the caller may record evidence
+ * against? A file the caller may not read answers as a missing one.
+ */
+export function isApplyEvidenceTargetPresent(
+ vault: string,
+ prefFilePath: string,
+ readable: ((rel: string) => boolean) | undefined,
+): boolean {
+ if (!existsSync(prefFilePath)) return false;
+ return readable === undefined || readable(vaultRelative(prefFilePath, vault));
}
export interface AppendApplyEvidenceResult {
@@ -224,7 +245,7 @@ export function appendApplyEvidence(
}
validateSlug(slug);
const prefFilePath = preferencePath(vault, slug);
- if (!existsSync(prefFilePath)) {
+ if (!isApplyEvidenceTargetPresent(vault, prefFilePath, opts.readable)) {
throw new BrainPreferenceNotFoundError(`pref-${slug}`, prefFilePath);
}
// Parse so a corrupted target produces a meaningful error rather
diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.ts
index c9aaab37..66de1a51 100644
--- a/src/core/brain/artifact-ref-view.ts
+++ b/src/core/brain/artifact-ref-view.ts
@@ -34,7 +34,7 @@ import { existsSync } from "node:fs";
import { pathIsInside, vaultRelative } from "../path-safety.ts";
import type { FrontmatterCache } from "../search/result-filters.ts";
-import { BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";
+import { BRAIN_DECISIONS_REL, BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";
import { ANCHORED_WIKILINK_RE, stripWikilinkDecoration } from "./wikilink.ts";
/** The `.md` extension every Brain artifact id resolves through. */
@@ -140,7 +140,9 @@ export const UNFILTERED_ARTIFACT_REFS: ArtifactRefView = Object.freeze({
* - `sources` (`src-<slug>.md`) and `entities` are taggable the same
* way, and `brain_search_by_source` already filters the first of them
* on the search side - so an id-shaped reference to one reaching a
- * view here and passing was the two halves disagreeing.
+ * view here and passing was the two halves disagreeing;
+ * - `decisions` (`decision-<slug>.md`) is named by id in the
+ * decision-change receipts (`[[decision-<slug>]]`).
*
* `log` is deliberately absent - a log shard is named by date, is shared
* by construction, and carries no per-page claim to read. `bases` holds
@@ -158,6 +160,7 @@ function artifactPath(vault: string, id: string): string | null {
dirs.pending,
join(vault, BRAIN_SOURCES_REL),
dirs.entities,
+ join(vault, BRAIN_DECISIONS_REL),
]) {
const abs = join(dir, `${id}${MARKDOWN_EXT}`);
// The visibility predicate speaks vault-relative POSIX paths - the
diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.ts
index 82d28dfb..8c88f87a 100644
--- a/src/core/brain/config-template.ts
+++ b/src/core/brain/config-template.ts
@@ -63,6 +63,7 @@ import {
MOST_APPLIED_WINDOW_DAYS_DEFAULT,
STANDING_RULES_MAX_CHARS_DEFAULT,
} from "./policy.ts";
+import { SCOPED_RULES_MAX_CHARS_DEFAULT } from "./scoped-rules.ts";
import {
DEFAULT_ANTICIPATORY_MAX_TOKENS,
DEFAULT_ANTICIPATORY_TTL_SECONDS,
@@ -300,6 +301,9 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f
"standing_rules_max_chars caps the operator-authored",
"Brain/standing-rules.md block, which is injected first and is",
"exempt from inject_budget_chars - hence its own number.",
+ "scoped_rules_max_chars caps the operator-authored scoped rules",
+ "under Brain/standing-rules/ (project, harness, host); that block",
+ "is charged against inject_budget_chars.",
],
emit: "commented-default",
keys: [
@@ -307,6 +311,7 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f
def("most_applied_limit", MOST_APPLIED_LIMIT_DEFAULT),
def("inject_budget_chars", INJECT_BUDGET_CHARS_DEFAULT),
def("standing_rules_max_chars", STANDING_RULES_MAX_CHARS_DEFAULT),
+ def("scoped_rules_max_chars", SCOPED_RULES_MAX_CHARS_DEFAULT),
],
},
{
diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.ts
index 2668b523..d57bf5a5 100644
--- a/src/core/brain/context-receipts.ts
+++ b/src/core/brain/context-receipts.ts
@@ -86,6 +86,11 @@ export interface ContextReceiptFilter {
readonly host?: string;
readonly sessionId?: string;
readonly limit?: number;
+ /**
+ * Receipts the caller may not see at all. They are left out before the
+ * limit is applied, so the answer is the one a store without them gives.
+ */
+ readonly exclude?: (record: ContinuityRecord) => boolean;
}
export interface ContextReceiptSummary {
@@ -221,6 +226,18 @@ export interface ContextReceiptFoldFilter {
readonly until?: string;
/** Fold bound; defaults to {@link CONTEXT_RECEIPT_FOLD_MAX_RECEIPTS}. */
readonly maxReceipts?: number;
+ /**
+ * Receipts the caller may not see at all. They are left out before the
+ * fold bound is applied, so neither `receipt_count` nor `truncated`
+ * counts them.
+ */
+ readonly exclude?: (record: ContinuityRecord) => boolean;
+ /**
+ * Receipt items the caller may not see. They leave the item figures,
+ * and a receipt they leave with no item counts in `empty_receipts`, as
+ * a receipt that never carried them would.
+ */
+ readonly excludeItem?: (item: unknown) => boolean;
}
/**
@@ -352,6 +369,7 @@ export function summarizeContextReceiptSession(
...(filter.trigger !== undefined ? { trigger: filter.trigger } : {}),
...(filter.host !== undefined ? { host: filter.host } : {}),
...(filter.sessionId !== undefined ? { sessionId: filter.sessionId } : {}),
+ ...(filter.exclude !== undefined ? { exclude: filter.exclude } : {}),
}),
)
.toReversed();
@@ -372,11 +390,13 @@ export function summarizeContextReceiptSession(
withheld += 1;
continue;
}
- const items = record.payload["items"];
- if (!Array.isArray(items)) {
+ const stored = record.payload["items"];
+ if (!Array.isArray(stored)) {
malformedReceipts += 1;
continue;
}
+ const excludeItem = filter.excludeItem;
+ const items = excludeItem === undefined ? stored : stored.filter((item) => !excludeItem(item));
if (items.length === 0) emptyReceipts += 1;
for (const raw of items) {
if (raw === null || typeof raw !== "object") continue;
@@ -464,6 +484,23 @@ function adequacySummary(
return { adequacy: { level, action, escalate: record["escalate"] === true } };
}
+/**
+ * Receipt item ids of the operator-rule blocks the SessionStart hook
+ * injects: the constitution and the scoped rules. Structural ids, never
+ * derived from content; a reader below local reach withholds them.
+ */
+export const RECEIPT_ITEM_STANDING_RULES = "standing-rules";
+export const RECEIPT_ITEM_SCOPED_RULES = "scoped-rules";
+
+/**
+ * Receipt item ids of the memory bodies the SessionStart hook charges
+ * against `inject_budget_chars` besides the scoped rules: the active and
+ * the lessons body. A receipt's budget block exists because one of them,
+ * or the scoped rules, was measured.
+ */
+export const RECEIPT_ITEM_ACTIVE_BODY = "active-body";
+export const RECEIPT_ITEM_LESSONS_BODY = "lessons-body";
+
export function isContextReceiptTrigger(value: unknown): value is ContextReceiptTrigger {
return value === "context_pack" || value === "pre_compress" || value === "session_inject";
}
@@ -480,5 +517,6 @@ function matchesReceiptFilter(record: ContinuityRecord, filter: ContextReceiptFi
if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger) return false;
if (filter.host !== undefined && payload["host"] !== filter.host) return false;
if (filter.sessionId !== undefined && payload["session_id"] !== filter.sessionId) return false;
+ if (filter.exclude !== undefined && filter.exclude(record)) return false;
return true;
}
diff --git a/src/core/brain/dead-ends.ts b/src/core/brain/dead-ends.ts
index 20b3db0b..971334b2 100644
--- a/src/core/brain/dead-ends.ts
+++ b/src/core/brain/dead-ends.ts
@@ -13,6 +13,7 @@
import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
+import { vaultRelative } from "../path-safety.ts";
import { sanitiseTextField } from "../redactor.ts";
import { parseFrontmatterText, slugify, writeFrontmatterAtomic } from "../vault.ts";
import type { FrontmatterMap } from "../types.ts";
@@ -52,6 +53,13 @@ export interface RecordDeadEndInput {
readonly now: Date;
/** Override the active-set cap (tests). */
readonly maxActive?: number;
+ /**
+ * Whether the caller may read a vault-relative page at its reach. When
+ * given, the overflow trim still counts every active dead end against
+ * the cap but archives only the readable ones: a withheld page is never
+ * moved on that caller's behalf.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface RecordDeadEndResult {
@@ -135,7 +143,7 @@ export function recordDeadEnd(vault: string, input: RecordDeadEndInput): RecordD
},
);
- const archived = trimActive(vault, input.maxActive ?? DEAD_END_MAX_ACTIVE);
+ const archived = trimActive(vault, input.maxActive ?? DEAD_END_MAX_ACTIVE, input.readable);
return Object.freeze({
entry: Object.freeze({
@@ -151,12 +159,24 @@ export function recordDeadEnd(vault: string, input: RecordDeadEndInput): RecordD
});
}
-/** Move the oldest active entries beyond the cap into `archive/`. */
-function trimActive(vault: string, maxActive: number): string[] {
+/**
+ * Move the oldest active entries beyond the cap into `archive/`. The cap
+ * counts every entry; with `readable`, an overflow entry the caller cannot
+ * read stays where it is.
+ */
+function trimActive(
+ vault: string,
+ maxActive: number,
+ readable: ((rel: string) => boolean) | undefined,
+): string[] {
const { entries } = listDeadEnds(vault);
if (entries.length <= maxActive) return [];
// `entries` is newest first; everything past the cap archives.
- const overflow = entries.slice(maxActive).toReversed();
+ const overflow = entries
+ .slice(maxActive)
+ .toReversed()
+ .filter((entry) => readable === undefined || readable(vaultRelative(entry.path, vault)));
+ if (overflow.length === 0) return [];
const archiveDir = join(deadEndsDir(vault), "archive");
mkdirSync(archiveDir, { recursive: true });
const archived: string[] = [];
diff --git a/src/core/brain/decisions/recall.ts b/src/core/brain/decisions/recall.ts
index 60d52c88..ef73386d 100644
--- a/src/core/brain/decisions/recall.ts
+++ b/src/core/brain/decisions/recall.ts
@@ -40,6 +40,8 @@ export interface RecallRatedDecisionsInput {
readonly configPath?: string;
/** Optional override of the match threshold (else the governor default). */
readonly minOverlap?: number;
+ /** The paths the caller may read; a decision it may not read is never a candidate. */
+ readonly readable?: (rel: string) => boolean;
}
export interface RecallRatedDecisionsResult {
@@ -86,7 +88,10 @@ export function recallRatedDecisions(
const minSpacingTurns = resolveDecisionRecallMinSpacingTurns(input.configPath) ?? 0;
const turn = input.turn ?? 0;
- const rated = listRatedDecisions(vault);
+ const rated = listRatedDecisions(
+ vault,
+ input.readable !== undefined ? { readable: input.readable } : {},
+ );
const candidates: RatedDecisionCandidate[] = rated.map((d) => ({
id: d.id,
rating: d.rating ?? 0,
diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.ts
index 0f66bd4a..2f9b8a94 100644
--- a/src/core/brain/decisions/receipts.ts
+++ b/src/core/brain/decisions/receipts.ts
@@ -491,6 +491,12 @@ export interface DecisionHistoryQuery {
readonly cursor?: string;
/** Page size; defaults to {@link DECISION_HISTORY_DEFAULT_LIMIT}. */
readonly limit?: number;
+ /**
+ * Keep only the receipts this answers true for, before the total and
+ * the page are taken, so a dropped receipt moves neither. Absent, every
+ * receipt is kept.
+ */
+ readonly keep?: (receipt: DecisionChangeReceipt) => boolean;
}
export interface DecisionHistoryPage {
@@ -535,7 +541,8 @@ export function queryDecisionChangeHistory(
const offset = query.cursor !== undefined ? decodeCursor(query.cursor) : 0;
if (offset < 0) throw new ReceiptError("receipt: malformed cursor");
- const all = readDecisionChangeReceipts(vault).receipts;
+ const read = readDecisionChangeReceipts(vault).receipts;
+ const all = query.keep === undefined ? read : read.filter(query.keep);
let matching = all;
if (query.subject !== undefined) {
// Read-side only: receipts store subjects in whichever shape their
diff --git a/src/core/brain/decisions/record.ts b/src/core/brain/decisions/record.ts
index c8fd7f95..f398c323 100644
--- a/src/core/brain/decisions/record.ts
+++ b/src/core/brain/decisions/record.ts
@@ -32,6 +32,7 @@ import { parseFrontmatter, slugify } from "../../vault.ts";
import { appendLogEvent } from "../log.ts";
import { addObligation } from "../obligations.ts";
import { decisionPath, decisionsDir, obligationPath, validateIsoDate } from "../paths.ts";
+import { BRAIN_DECISIONS_REL } from "../path-constants.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { jaccard, tokenise } from "../similarity.ts";
import { isoSecond } from "../time.ts";
@@ -155,7 +156,17 @@ export interface RecordDecisionResult {
readonly obligationCreated: boolean;
}
-export interface BackfillOutcomeInput {
+/**
+ * The vault-relative paths the caller may read. A decision page it may
+ * not read is answered exactly as an absent one: skipped by every list,
+ * and refused by every single-slug read or write with the absent slug's
+ * error, before anything is written. Absent, every page may be read.
+ */
+export interface DecisionReadOptions {
+ readonly readable?: (rel: string) => boolean;
+}
+
+export interface BackfillOutcomeInput extends DecisionReadOptions {
readonly slug: string;
readonly outcome: string;
readonly agent?: string;
@@ -163,7 +174,7 @@ export interface BackfillOutcomeInput {
readonly configPath?: string;
}
-export interface UpdateRatingInput {
+export interface UpdateRatingInput extends DecisionReadOptions {
readonly slug: string;
readonly rating: number;
readonly rationale?: string;
@@ -188,7 +199,7 @@ export interface SimilarDecisionQuery {
readonly excludeSlug?: string;
}
-export interface FindSimilarDecisionsOptions {
+export interface FindSimilarDecisionsOptions extends DecisionReadOptions {
readonly threshold?: number;
readonly limit?: number;
}
@@ -298,9 +309,14 @@ function render(record: Omit<DecisionRecord, "path">): string {
return lines.join("\n");
}
-function parsePage(vault: string, slug: string): DecisionRecord | null {
+function parsePage(
+ vault: string,
+ slug: string,
+ readable: DecisionReadOptions["readable"],
+): DecisionRecord | null {
const path = decisionPath(vault, slug);
if (!existsSync(path)) return null;
+ if (readable !== undefined && !readable(decisionRel(slug))) return null;
const [meta, body] = parseFrontmatter(path);
if (meta["type"] !== DECISION_TYPE) return null;
const reviewRaw = typeof meta["review_date"] === "string" ? meta["review_date"].trim() : "";
@@ -333,6 +349,11 @@ function parsePage(vault: string, slug: string): DecisionRecord | null {
});
}
+/** The vault-relative POSIX path of one decision page, as the reach predicate reads it. */
+function decisionRel(slug: string): string {
+ return `${BRAIN_DECISIONS_REL}/decision-${slug}.md`;
+}
+
// ----- Review obligation ----------------------------------------------------
function reviewObligationTitle(decisionTitle: string): string {
@@ -464,7 +485,7 @@ export function backfillOutcome(vault: string, input: BackfillOutcomeInput): Dec
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
- const prior = parsePage(vault, slug);
+ const prior = parsePage(vault, slug, input.readable);
if (prior === null) throw new DecisionError(`no decision: ${slug}`);
const outcome = sanitiseTextField(input.outcome, {
maxLen: FIELD_MAX_LEN,
@@ -516,7 +537,7 @@ export function updateRating(vault: string, input: UpdateRatingInput): DecisionR
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
- const prior = parsePage(vault, slug);
+ const prior = parsePage(vault, slug, input.readable);
if (prior === null) throw new DecisionError(`no decision: ${slug}`);
const rating = requireRating(input.rating);
const rationale =
@@ -564,8 +585,11 @@ export function updateRating(vault: string, input: UpdateRatingInput): DecisionR
* Unrated decisions are excluded - this is the rated-capture list surface,
* separate from ordinary signal/preference recall.
*/
-export function listRatedDecisions(vault: string): DecisionRecord[] {
- return listDecisions(vault)
+export function listRatedDecisions(
+ vault: string,
+ opts: DecisionReadOptions = {},
+): DecisionRecord[] {
+ return listDecisions(vault, opts)
.filter((d) => d.rating !== null)
.toSorted((a, b) => (b.rating ?? 0) - (a.rating ?? 0) || a.slug.localeCompare(b.slug));
}
@@ -574,10 +598,14 @@ export function listRatedDecisions(vault: string): DecisionRecord[] {
* Read a specific set of decisions side by side for comparison, in the
* order requested. Unknown slugs are skipped (a comparison of what exists).
*/
-export function compareDecisions(vault: string, slugs: ReadonlyArray<string>): DecisionRecord[] {
+export function compareDecisions(
+ vault: string,
+ slugs: ReadonlyArray<string>,
+ opts: DecisionReadOptions = {},
+): DecisionRecord[] {
const out: DecisionRecord[] = [];
for (const slug of slugs) {
- const page = parsePage(vault, slugify(slug));
+ const page = parsePage(vault, slugify(slug), opts.readable);
if (page !== null) out.push(page);
}
return out;
@@ -586,19 +614,23 @@ export function compareDecisions(vault: string, slugs: ReadonlyArray<string>): D
// ----- Reads ----------------------------------------------------------------
/** One decision, or null. */
-export function showDecision(vault: string, slug: string): DecisionRecord | null {
- return parsePage(vault, slugify(slug));
+export function showDecision(
+ vault: string,
+ slug: string,
+ opts: DecisionReadOptions = {},
+): DecisionRecord | null {
+ return parsePage(vault, slugify(slug), opts.readable);
}
/** Every decision, sorted by slug. */
-export function listDecisions(vault: string): DecisionRecord[] {
+export function listDecisions(vault: string, opts: DecisionReadOptions = {}): DecisionRecord[] {
const dir = decisionsDir(vault);
if (!existsSync(dir)) return [];
const out: DecisionRecord[] = [];
for (const name of readdirSync(dir)) {
if (!name.endsWith(".md") || !name.startsWith("decision-")) continue;
const slug = name.replace(/^decision-/u, "").replace(/\.md$/u, "");
- const page = parsePage(vault, slug);
+ const page = parsePage(vault, slug, opts.readable);
if (page !== null) out.push(page);
}
return out.toSorted((a, b) => a.slug.localeCompare(b.slug));
@@ -622,7 +654,10 @@ export function findSimilarDecisions(
const queryTokens = tokenise(`${query.title} ${query.chosen ?? ""}`);
if (queryTokens.size === 0) return [];
const out: SimilarDecision[] = [];
- for (const decision of listDecisions(vault)) {
+ for (const decision of listDecisions(
+ vault,
+ opts.readable !== undefined ? { readable: opts.readable } : {},
+ )) {
if (query.excludeSlug !== undefined && decision.slug === query.excludeSlug) continue;
const tokens = tokenise(`${decision.title} ${decision.chosen}`);
const score = jaccard(queryTokens, tokens);
diff --git a/src/core/brain/derived-fact.ts b/src/core/brain/derived-fact.ts
index 042e0cfa..ccc1c820 100644
--- a/src/core/brain/derived-fact.ts
+++ b/src/core/brain/derived-fact.ts
@@ -16,6 +16,7 @@
import { existsSync } from "node:fs";
+import { vaultRelative } from "../path-safety.ts";
import { loadBrainConfig, DEFAULT_BRAIN_CONFIG } from "./policy.ts";
import { preferencePath } from "./paths.ts";
import { writePreference } from "./preference.ts";
@@ -42,6 +43,12 @@ export interface DeriveFactOptions {
* config passes its own.
*/
readonly configPath?: string;
+ /**
+ * The vault-relative paths the caller may read. A premise preference it
+ * may not read is refused exactly as a missing one is, before anything
+ * is written. Absent, every preference counts.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface DeriveFactResult {
@@ -132,7 +139,11 @@ export function deriveFact(
for (const premise of input.premises) {
const slug = premiseSlug(premise);
if (!slug) throw new DeriveFactError("premise id must not be empty");
- if (!existsSync(preferencePath(vault, slug))) {
+ const premisePath = preferencePath(vault, slug);
+ if (
+ !existsSync(premisePath) ||
+ (opts.readable !== undefined && !opts.readable(vaultRelative(premisePath, vault)))
+ ) {
throw new DeriveFactError(`premise preference not found: ${JSON.stringify(premise)}`);
}
evidencedBy.push(`[[pref-${slug}]]`);
diff --git a/src/core/brain/design-note.ts b/src/core/brain/design-note.ts
index 33c712bf..56f31194 100644
--- a/src/core/brain/design-note.ts
+++ b/src/core/brain/design-note.ts
@@ -54,7 +54,7 @@ import {
type LinkCandidateManifest,
} from "./notes/link-candidates.ts";
import { ownerScopeView } from "./owner-scope-view.ts";
-import { decisionsDir } from "./paths.ts";
+import { BRAIN_TENSIONS_REL, decisionsDir } from "./paths.ts";
import {
assertResponseCheck,
registerResponseCheck,
@@ -278,13 +278,25 @@ registerResponseCheck(DESIGN_NOTE_SURFACE, (payload) => {
/**
* Read the three stores and keep what the topic reaches. Pure read; writes
* nothing, calls no model, and never fails on an empty vault.
+ *
+ * `visible` is asked about each tension and decision page by its
+ * vault-relative path before the page is scored or counted, so a page
+ * the caller may not read is matched, listed and counted exactly as an
+ * absent one (an empty store included). Absent, every page is visible.
*/
-export function designNoteGrounding(vault: string, topic: string): DesignNoteGrounding {
+export function designNoteGrounding(
+ vault: string,
+ topic: string,
+ visible?: (rel: string) => boolean,
+): DesignNoteGrounding {
const trimmed = requireTopic(topic);
const queryTokens = tokenise(trimmed);
const emptyStores: DesignNoteStore[] = [];
+ const reads = visible !== undefined ? { readable: visible } : {};
- const allTensions = listTensions(vault);
+ const allTensions = listTensions(vault).filter(
+ (record) => visible === undefined || visible(`${BRAIN_TENSIONS_REL}/tension-${record.slug}.md`),
+ );
if (allTensions.length === 0) emptyStores.push(DESIGN_NOTE_STORE.tensions);
const tensions = allTensions
.map((record) => ({ record, score: tensionScore(queryTokens, record) }))
@@ -304,11 +316,11 @@ export function designNoteGrounding(vault: string, topic: string): DesignNoteGro
// The decision store owns its own matcher; reusing it keeps one ranking
// rule for "a decision like this one" across every surface that asks.
- if (listDecisions(vault).length === 0) emptyStores.push(DESIGN_NOTE_STORE.decisions);
+ if (listDecisions(vault, reads).length === 0) emptyStores.push(DESIGN_NOTE_STORE.decisions);
const decisions = findSimilarDecisions(
vault,
{ title: trimmed },
- { threshold: DESIGN_NOTE_MATCH_THRESHOLD, limit: DESIGN_NOTE_PER_STORE_LIMIT },
+ { threshold: DESIGN_NOTE_MATCH_THRESHOLD, limit: DESIGN_NOTE_PER_STORE_LIMIT, ...reads },
).map((match) =>
Object.freeze({
id: match.id,
@@ -384,13 +396,15 @@ export function planDesignNote(
opts: PlanDesignNoteOptions,
): DesignNoteReport {
const trimmed = requireTopic(topic);
- const grounding = designNoteGrounding(vault, trimmed);
+ const ownerView = ownerScopeView(vault, opts.ownerScope);
+ const visible = (rel: string): boolean =>
+ ownerView.visible(rel) && (opts.readable?.(rel) ?? true);
+ const grounding = designNoteGrounding(vault, trimmed, visible);
const slug = slugify(trimmed);
const targetPath = posix.join(DESIGN_NOTE_DIR_REL, noteBasename(slug, opts.now));
- const ownerView = ownerScopeView(vault, opts.ownerScope);
const linkCandidates = buildLinkCandidateManifest(vault, {
query: trimmed,
- visible: (rel) => ownerView.visible(rel) && (opts.readable?.(rel) ?? true),
+ visible,
});
return Object.freeze({
topic: trimmed,
diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.ts
index e5a31a6a..52ec8222 100644
--- a/src/core/brain/diagnostics.ts
+++ b/src/core/brain/diagnostics.ts
@@ -1166,6 +1166,13 @@ export interface PlanRepairOptions {
* cannot have.
*/
readonly issues?: ReadonlyArray<DoctorIssue>;
+ /**
+ * The pages the caller may read, when the doctor runs here (no
+ * {@link issues} supplied). The checks then count and cap over those
+ * pages only, as `runDoctor` does with the same option. Absent, every
+ * page counts.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -1183,7 +1190,7 @@ export interface PlanRepairOptions {
* the same findings, each with its next-command hint.
*/
export function planRepair(vault: string, opts: PlanRepairOptions = {}): RepairPlan {
- const issues = opts.issues ?? collectDoctorIssues(vault);
+ const issues = opts.issues ?? collectDoctorIssues(vault, opts.readable);
const fixes: RepairItem[] = [];
for (const fixer of FIXERS) {
@@ -1216,8 +1223,11 @@ export function planRepair(vault: string, opts: PlanRepairOptions = {}): RepairP
}
/** The doctor's errors and warnings as one stream, in report order. */
-function collectDoctorIssues(vault: string): ReadonlyArray<DoctorIssue> {
- const doctor = runDoctor(vault);
+function collectDoctorIssues(
+ vault: string,
+ readable: ((rel: string) => boolean) | undefined,
+): ReadonlyArray<DoctorIssue> {
+ const doctor = runDoctor(vault, readable !== undefined ? { readable } : {});
return [...doctor.errors, ...doctor.warnings];
}
@@ -1271,6 +1281,14 @@ export interface ApplyRepairOptions {
* CLI) and only {@link ownerScope} bounds the plan.
*/
readonly reach?: TransportReach;
+ /**
+ * The pages the caller may read at {@link reach}. The doctor's checks
+ * count and cap over these pages before any finding exists to filter:
+ * a withheld page spends no slot of a capped warning and a withheld
+ * principle adds no concept gap, so the unfixable counts match a vault
+ * that never held them. Absent, every page counts.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/** The fields a doctor finding names artifacts in. */
@@ -1347,9 +1365,11 @@ export function applyRepair(vault: string, opts: ApplyRepairOptions): RepairOutc
// are bounded again by what each one would name, so a fix that reaches
// a withheld page through its detail is not planned either.
const plan = view.filtersNothing
- ? planRepair(vault)
+ ? planRepair(vault, opts.readable !== undefined ? { readable: opts.readable } : {})
: planRepair(vault, {
- issues: view.keep(collectDoctorIssues(vault), (i) => doctorIssueRefs(vault, i)),
+ issues: view.keep(collectDoctorIssues(vault, opts.readable), (i) =>
+ doctorIssueRefs(vault, i),
+ ),
});
const fixes = view.keep(plan.fixes, repairRefs);
const needsReview = fixes.filter((f) => !f.applicable);
diff --git a/src/core/brain/diarization.ts b/src/core/brain/diarization.ts
index 3351d3b5..408a7add 100644
--- a/src/core/brain/diarization.ts
+++ b/src/core/brain/diarization.ts
@@ -120,7 +120,9 @@ export interface DiarizationOptions {
* May the caller read the page at this vault-relative path at its
* reach? ANDed into the link-candidate filter beside the owner scope, so
* a page withheld from the caller is not offered as a citation target
- * nor counted in the manifest's total, exactly as an absent page. The
+ * nor counted in the manifest's total, exactly as an absent page. A
+ * withheld subject page answers as an unknown entity, and a withheld
+ * source page is not evidence: it is neither counted nor named. The
* MCP handler binds it to `readableAtContextReach(ctx)`; absent (the
* CLI) filters nothing beyond the owner scope.
*/
@@ -158,6 +160,11 @@ export function diarize(
status: entity.status,
};
const entityRel = toPosixRel(vault, entity.path);
+ // A subject page the caller may not read at its reach is an unknown
+ // entity, exactly as an absent one.
+ if (opts.readable !== undefined && !opts.readable(entityRel)) {
+ throw new DiarizationError(`unknown entity: ${ref.query}`);
+ }
const entityIdentity: EvidenceIdentity = Object.freeze({
path: entityRel,
kind: EVIDENCE_KIND_ENTITY,
@@ -177,6 +184,9 @@ export function diarize(
// are the behavioral signals; both are pure counts over structure.
const evidencedSources: EvidencedSource[] = [];
for (const listed of listIngestedSources(vault)) {
+ // A source page the caller may not read at its reach is neither
+ // evidence, counted nor named, exactly as an absent one.
+ if (opts.readable !== undefined && !opts.readable(listed.path)) continue;
const detail = getIngestedSource(vault, listed.path);
if (detail === null) continue;
const anchored = decomposeAtomicFacts(detail.body, { entities: [entityLike] }).some((a) =>
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 0d35a53f..d7d81914 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -44,6 +44,9 @@
*/
import { statSync } from "node:fs";
+import { relative, resolve } from "node:path";
+
+import { toPosix } from "../path-safety.ts";
import { activeBudgetPressureCheck } from "./doctor/active-budget-check.ts";
import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./doctor/check.ts";
@@ -100,6 +103,7 @@ import {
} from "./doctor/uncertainty-probes.ts";
import type { DoctorUncertainEntry, RunDoctorOptions, RunDoctorResult } from "./doctor/report.ts";
import { reportSweptSkip, sweptFailureReason, sweptPathWarning } from "./doctor/unreadable-path.ts";
+import { uncertainStream, type UncertainAdmission } from "./doctor/uncertain-stream.ts";
import type { SemanticHealthReport } from "./health/reconcile.ts";
import { brainDirs } from "./paths.ts";
import {
@@ -134,6 +138,29 @@ export type {
// ----- The registry ---------------------------------------------------------
+/** The stale-dependency check over the unbounded collector. */
+const STALE_DEPENDENCY_CHECK_UNBOUNDED = makeStaleDependencyCheck(auditStaleDependencies);
+
+/**
+ * The stale-dependency check, its collector bounded to the pages the
+ * pass may read when the context carries a predicate, so a page the
+ * caller cannot read is neither a state nor a consumer of one, and moves
+ * no count of the note or the rows it renders.
+ */
+const staleDependencyCheck: DoctorCheck = {
+ failSoft: STALE_DEPENDENCY_CHECK_UNBOUNDED.failSoft,
+ run(ctx, out) {
+ const readable = ctx.readable;
+ if (readable === undefined) {
+ STALE_DEPENDENCY_CHECK_UNBOUNDED.run(ctx, out);
+ return;
+ }
+ makeStaleDependencyCheck((vault, opts) =>
+ auditStaleDependencies(vault, { ...opts, readable }),
+ ).run(ctx, out);
+ },
+};
+
/**
* Every check the pass runs, in report order.
*
@@ -156,7 +183,7 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([
// pure kernel is the leaf both halves share, so this registry - which
// already reaches every check module and the store beneath them - is
// where the two meet without closing a loop.
- makeStaleDependencyCheck(auditStaleDependencies),
+ staleDependencyCheck,
removedToolReferenceCheck,
duplicatePreferenceCheck,
topicKeyCollisionCheck,
@@ -282,7 +309,10 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
// its three directory reads have to be able to report. Resolved before
// any check runs, an unreadable `Brain/preferences` or a `Brain/log`
// that is a regular file ended the pass with no findings at all.
- const findings: DoctorFindings = { issues: [], uncertain: [] };
+ const findings: DoctorFindings = {
+ issues: [],
+ uncertain: uncertainStream(uncertainAdmission(vault, opts.readable)),
+ };
const ctx = resolveContext(vault, opts, findings.uncertain);
for (const check of DOCTOR_CHECKS) {
if (!check.failSoft) {
@@ -308,7 +338,14 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
let semanticReport: SemanticHealthReport | undefined;
try {
const health = ctx.config ? resolveHealth(ctx.config) : BRAIN_HEALTH_DEFAULTS;
- semanticReport = checkSemanticHealth(vault, ctx.preferences, findings.issues, health, ctx.now);
+ semanticReport = checkSemanticHealth(
+ vault,
+ ctx.preferences,
+ findings.issues,
+ health,
+ ctx.now,
+ ctx.readable,
+ );
} catch {
/* doctor never throws */
}
@@ -325,6 +362,7 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
try {
instructionWarnings = checkInstructionFileCeiling(vault, {
maxLines: guardrails.instruction_file_max_lines,
+ ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
});
} catch {
/* doctor never throws */
@@ -366,6 +404,29 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
});
}
+/** The extension of the pages the reference grammar judges by path. */
+const PAGE_EXT = ".md";
+
+/**
+ * Which uncertainty entries a pass handed `readable` may report.
+ *
+ * Judged the way the handlers' reference view judges an issue's path, so
+ * the entries it keeps are the ones the view would keep after the cap: a
+ * page path is admitted only when the reader may read it, and any other
+ * path - a directory, a lock, a file outside the vault - names no page
+ * and is admitted as before. `undefined` when nothing is withheld.
+ */
+function uncertainAdmission(
+ vault: string,
+ readable: ((rel: string) => boolean) | undefined,
+): UncertainAdmission | undefined {
+ if (readable === undefined) return undefined;
+ return (entry) =>
+ entry.path === undefined ||
+ !entry.path.endsWith(PAGE_EXT) ||
+ readable(toPosix(relative(vault, resolve(vault, entry.path))));
+}
+
/**
* Resolve everything the checks read, once.
*
@@ -398,6 +459,7 @@ function resolveContext(
config,
dbPath: opts.dbPath,
configPath: opts.configPath,
+ ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
knownBasenames: collectAllBasenames(vault, {
site: CONTEXT_SITE,
consequence:
diff --git a/src/core/brain/doctor/check.ts b/src/core/brain/doctor/check.ts
index e33f565e..3872ebee 100644
--- a/src/core/brain/doctor/check.ts
+++ b/src/core/brain/doctor/check.ts
@@ -42,6 +42,12 @@ export interface DoctorCheckContext {
* answer the runtime itself would get.
*/
readonly configPath: string | undefined;
+ /**
+ * Whether the caller may read a vault-relative path, for the checks
+ * that count before any finding is filtered: a page it rejects spends
+ * no slot of a cap and moves no count. Absent means every page counts.
+ */
+ readonly readable?: (rel: string) => boolean;
/** Every valid wikilink target inside `Brain/`, keyed by basename. */
readonly knownBasenames: ReadonlySet<string>;
/**
diff --git a/src/core/brain/doctor/removed-tool-checks.ts b/src/core/brain/doctor/removed-tool-checks.ts
index 25f3a5fc..9a56b011 100644
--- a/src/core/brain/doctor/removed-tool-checks.ts
+++ b/src/core/brain/doctor/removed-tool-checks.ts
@@ -61,7 +61,7 @@ const ROOT_INSTRUCTION_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md"
*/
export const removedToolReferenceCheck: DoctorCheck = {
failSoft: true,
- run({ vault }, { issues, uncertain }) {
+ run({ vault, readable }, { issues, uncertain }) {
const candidates: string[] = [];
const dirs = brainDirs(vault);
const swept: SweptPath = {
@@ -87,6 +87,9 @@ export const removedToolReferenceCheck: DoctorCheck = {
let emitted = 0;
for (const path of candidates) {
if (emitted >= REMOVED_TOOL_MAX_WARNINGS) return;
+ // A page the caller may not read is skipped before it is read, so it
+ // spends no slot of the cap a readable page would have filled.
+ if (readable !== undefined && !readable(toPosix(relative(vault, path)))) continue;
// Every candidate was listed by the walk a moment ago, so an
// ENOENT here is a file that vanished under it.
const body = readSweptFile(path, swept, SWEEP_ORIGIN.discovered);
diff --git a/src/core/brain/doctor/report.ts b/src/core/brain/doctor/report.ts
index 55c6793e..a8149446 100644
--- a/src/core/brain/doctor/report.ts
+++ b/src/core/brain/doctor/report.ts
@@ -36,6 +36,14 @@ export interface RunDoctorOptions {
* answer the runtime being diagnosed would get.
*/
readonly configPath?: string;
+ /**
+ * Whether the caller may read a vault-relative path. Passed through to
+ * {@link DoctorCheckContext.readable}, so the counts a check computes
+ * itself (the removed-tool warning cap, the stale-dependency note) are
+ * taken over the pages the caller may read. Omitted, every page counts
+ * (the operator's own shell).
+ */
+ readonly readable?: (rel: string) => boolean;
/**
* Optional precomputed dream summary (v0.10.16). When supplied,
* the doctor runs the verification-delta helper and folds the
diff --git a/src/core/brain/doctor/semantic-health-check.ts b/src/core/brain/doctor/semantic-health-check.ts
index dc6b9464..476282a8 100644
--- a/src/core/brain/doctor/semantic-health-check.ts
+++ b/src/core/brain/doctor/semantic-health-check.ts
@@ -9,13 +9,14 @@
*/
import { existsSync, readdirSync } from "node:fs";
-import { join } from "node:path";
+import { join, relative } from "node:path";
import {
reconcileSemanticHealth,
type PreferenceForHealth,
type SemanticHealthReport,
} from "../health/reconcile.ts";
+import { toPosix } from "../../path-safety.ts";
import { brainDirs } from "../paths.ts";
import { BRAIN_HEALTH_DEFAULTS, loadBrainConfigDetailed, resolveHealth } from "../policy.ts";
import { parseSignal } from "../signal.ts";
@@ -60,6 +61,7 @@ export function computeSemanticHealth(
/** Minimal signal projection the semantic-health pass needs. */
interface SignalSignRecord {
+ readonly path: string;
readonly id: string;
readonly sign: import("../types.ts").BrainSignalSign;
readonly principle: string;
@@ -81,6 +83,7 @@ function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {
try {
const sig = parseSignal(join(dir, name));
out.push({
+ path: join(dir, name),
id: sig.id,
sign: sig.signal,
principle: sig.principle,
@@ -99,15 +102,28 @@ function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {
* shared `issues` array as warnings, and return the structured report.
* Confirmed preferences feed the contradiction and stale-claim passes;
* signal + preference principles feed the concept-gap pass.
+ *
+ * `readable`, when given, bounds every input to the records the reader
+ * may read: a withheld principle adds no term to the concept gaps, a
+ * withheld topic covers none, and a withheld preference joins no
+ * contradiction, stale claim or batch - so each finding is the one the
+ * same vault without that record would yield.
*/
export function checkSemanticHealth(
vault: string,
- prefRecords: ReadonlyArray<PreferenceRecord>,
+ allPrefRecords: ReadonlyArray<PreferenceRecord>,
issues: DoctorIssue[],
health: ResolvedBrainHealthConfig,
now: Date,
+ readable?: (rel: string) => boolean,
): SemanticHealthReport {
- const signals = readAllSignalRecords(vault);
+ const isReadable = (path: string): boolean =>
+ readable === undefined || readable(toPosix(relative(vault, path)));
+ const allSignals = readAllSignalRecords(vault);
+ const signals =
+ readable === undefined ? allSignals : allSignals.filter((s) => isReadable(s.path));
+ const prefRecords =
+ readable === undefined ? allPrefRecords : allPrefRecords.filter((r) => isReadable(r.path));
const signSignById = new Map(signals.map((s) => [s.id, s.sign]));
const preferences: PreferenceForHealth[] = prefRecords.map(({ pref }) => pref);
const corpusPrinciples = [
diff --git a/src/core/brain/doctor/uncertain-stream.ts b/src/core/brain/doctor/uncertain-stream.ts
index d970d766..ba7780c9 100644
--- a/src/core/brain/doctor/uncertain-stream.ts
+++ b/src/core/brain/doctor/uncertain-stream.ts
@@ -70,6 +70,46 @@ export function pushUncertain(
return message;
}
+/** Whether one entry may enter a stream at all. */
+export type UncertainAdmission = (entry: DoctorUncertainEntry) => boolean;
+
+/**
+ * An uncertainty stream that admits only the entries `admit` passes.
+ *
+ * The per-code cap is counted over what the stream holds, so an entry
+ * the reader may not see has to be turned away at the door: dropped only
+ * after the cap was spent, fifty withheld entries would crowd out the
+ * readable ones, and the number left would say how many were withheld.
+ * Every sink - {@link pushUncertain} and a check's own `push` - reaches
+ * the stream through `push`, so the one override covers them all.
+ */
+class AdmittingUncertainStream extends Array<DoctorUncertainEntry> {
+ /** Derived arrays (`map`, `filter`) are plain ones, with no admission of their own. */
+ static override get [Symbol.species](): ArrayConstructor {
+ return Array;
+ }
+
+ readonly #admit: UncertainAdmission;
+
+ constructor(admit: UncertainAdmission) {
+ super();
+ this.#admit = admit;
+ }
+
+ override push(...entries: DoctorUncertainEntry[]): number {
+ return super.push(...entries.filter(this.#admit));
+ }
+}
+
+/**
+ * A fresh stream: a plain array when nothing is withheld, so an
+ * unfiltered pass is unchanged, otherwise one that admits only what
+ * `admit` passes.
+ */
+export function uncertainStream(admit?: UncertainAdmission): DoctorUncertainEntry[] {
+ return admit === undefined ? [] : new AdmittingUncertainStream(admit);
+}
+
function countFor(uncertain: ReadonlyArray<DoctorUncertainEntry>, code: string): number {
let n = 0;
for (const entry of uncertain) if (entry.code === code) n += 1;
diff --git a/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.ts
index c0a0cbc4..bc83624f 100644
--- a/src/core/brain/dream-apply.ts
+++ b/src/core/brain/dream-apply.ts
@@ -187,6 +187,8 @@ function writePreferences(input: DreamApplyInput, agent: string): void {
// F5: bi-temporal validity extracted from the source signal.
...(np.valid_from ? { valid_from: np.valid_from } : {}),
...(np.valid_until ? { valid_until: np.valid_until } : {}),
+ // The strictest visibility of the records it was drafted from.
+ ...(np.visibility.length > 0 ? { visibility: np.visibility } : {}),
},
[],
{ overwrite: false },
diff --git a/src/core/brain/dream-plan-topics.ts b/src/core/brain/dream-plan-topics.ts
index 0c130170..eb74cb85 100644
--- a/src/core/brain/dream-plan-topics.ts
+++ b/src/core/brain/dream-plan-topics.ts
@@ -23,6 +23,7 @@
* Pure: no I/O, no clock beyond the `now` it is handed.
*/
+import { strictestVisibilityOf } from "../graph/visibility.ts";
import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";
import {
emptyPlan,
@@ -347,6 +348,13 @@ function planTopicWithoutActivePref(
principle: source.principle,
evidencedBy,
sign: source.signal,
+ // Drafted from every windowed signal (the principle is the dominant
+ // one's, the evidence cites them all) and quoting the superseded
+ // record's principle: the strictest of their visibilities.
+ visibility: strictestVisibilityOf([
+ ...windowedSigs.map((s) => s.visibility ?? []),
+ supersedesRecord?.visibility ?? [],
+ ]),
...deriveSignalTemporal(source, now),
...(supersedesRecord
? {
@@ -542,6 +550,12 @@ function handleSignalsOnActivePref(
principle: source.principle,
evidencedBy: opposing.map((s) => `[[${s.signal.id}]]`),
sign: oppositeSign,
+ // Drafted from the opposing signals and quoting the rebutted
+ // preference's principle: the strictest of their visibilities.
+ visibility: strictestVisibilityOf([
+ ...opposing.map((s) => s.visibility ?? []),
+ active.visibility ?? [],
+ ]),
...deriveSignalTemporal(source, now),
supersedes: activeLink,
});
diff --git a/src/core/brain/dream-plan.ts b/src/core/brain/dream-plan.ts
index 29736b5b..a1026863 100644
--- a/src/core/brain/dream-plan.ts
+++ b/src/core/brain/dream-plan.ts
@@ -106,6 +106,13 @@ export interface SignalRecord {
* pass archived because it had left the contradiction window unconsumed.
*/
readonly archived?: true;
+ /**
+ * The record's normalised `visibility:` tokens (`pageVisibility`), read by
+ * the scan. A preference the pass drafts from records carries the
+ * strictest of theirs, so a page drafted from reserved text stays
+ * reserved. Absent (or empty) means default visibility.
+ */
+ readonly visibility?: ReadonlyArray<string>;
}
export interface PreferenceRecord {
@@ -118,6 +125,13 @@ export interface PreferenceRecord {
* ancestors. `null` when the memory is a chain tip.
*/
readonly supersededBy: string | null;
+ /**
+ * The record's normalised `visibility:` tokens (`pageVisibility`), read by
+ * the scan. A preference the pass drafts from records carries the
+ * strictest of theirs, so a page drafted from reserved text stays
+ * reserved. Absent (or empty) means default visibility.
+ */
+ readonly visibility?: ReadonlyArray<string>;
}
export interface RetiredRecord {
@@ -132,6 +146,13 @@ export interface RetiredRecord {
* same (topic, scope) — see §6 of the OSB features summary.
*/
readonly user_rejected_reason?: string;
+ /**
+ * The record's normalised `visibility:` tokens (`pageVisibility`), read by
+ * the scan. A preference the pass drafts from records carries the
+ * strictest of theirs, so a page drafted from reserved text stays
+ * reserved. Absent (or empty) means default visibility.
+ */
+ readonly visibility?: ReadonlyArray<string>;
}
export interface CorruptedEntry {
@@ -256,6 +277,12 @@ export interface NewUnconfirmedPlan {
*/
readonly valid_from?: string;
readonly valid_until?: string;
+ /**
+ * The strictest `visibility:` tokens of every record the entry is drafted
+ * from (its evidencing signals and the record it supersedes). Written to
+ * the new preference's frontmatter when non-empty.
+ */
+ readonly visibility: ReadonlyArray<string>;
}
export interface RetirePlan {
diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.ts
index cc85e665..6070a716 100644
--- a/src/core/brain/dream-scan.ts
+++ b/src/core/brain/dream-scan.ts
@@ -13,6 +13,8 @@
import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
+import { pageVisibility } from "../graph/visibility.ts";
+import type { FrontmatterMap } from "../types.ts";
import { parseFrontmatter } from "../vault.ts";
import type {
CorruptedEntry,
@@ -96,6 +98,15 @@ function markdownFilesIn(dir: string): string[] {
return out;
}
+/**
+ * A record's `visibility:` tokens as a spreadable slice: `{}` for default
+ * visibility, so a record from an untagged page keeps its exact shape.
+ */
+function visibilitySlice(meta: FrontmatterMap): { visibility?: ReadonlyArray<string> } {
+ const tokens = pageVisibility(meta);
+ return tokens.length > 0 ? { visibility: Object.freeze(tokens) } : {};
+}
+
/**
* Signals from one directory. `inbox/`, `processed/` and `archived/` differ
* only in the flags they stamp on each record, so they share this walk.
@@ -113,12 +124,14 @@ function collectSignals(
try {
// Belief lifecycle suite (t_7d5a3589): a tombstoned signal is
// excluded from the dream pass so it is never re-clustered.
- if (isTombstoned(parseFrontmatter(full)[0])) continue;
+ const meta = parseFrontmatter(full)[0];
+ if (isTombstoned(meta)) continue;
signals.push({
path: full,
signal: parseSignal(full),
active,
...(archived ? { archived: true as const } : {}),
+ ...visibilitySlice(meta),
});
} catch {
corrupted.push({ path: full });
@@ -144,7 +157,12 @@ function collectPreferences(
? (rawMeta["superseded_by"] as string)
: null;
try {
- preferences.push({ path: full, pref: parsePreference(full), supersededBy });
+ preferences.push({
+ path: full,
+ pref: parsePreference(full),
+ supersededBy,
+ ...visibilitySlice(rawMeta),
+ });
} catch {
corrupted.push({ path: full });
}
@@ -182,6 +200,7 @@ function collectRetired(
principle,
...(scope ? { scope } : {}),
...(userReason ? { user_rejected_reason: userReason } : {}),
+ ...visibilitySlice(meta),
});
}
} catch {
diff --git a/src/core/brain/dream-types.ts b/src/core/brain/dream-types.ts
index 12515fa8..6e8f9ea4 100644
--- a/src/core/brain/dream-types.ts
+++ b/src/core/brain/dream-types.ts
@@ -248,4 +248,14 @@ export interface DreamOptions {
* run reads every gate from `Brain/_brain.yaml` exactly as before.
*/
readonly gates?: DreamGateOverrides;
+ /**
+ * Dry run only: plan over the records this vault-relative path test
+ * admits, as if the others were absent. A preview answered to a caller
+ * below local reach clusters, counts and routes only the signals,
+ * preferences and retired records that caller may read, so a withheld
+ * record moves no topic, count or decision in the projection. A real
+ * pass always plans over the whole vault, so passing this without
+ * `dryRun: true` throws `DreamPreviewReadableError`.
+ */
+ readonly previewReadable?: (rel: string) => boolean;
}
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index c8b02a3e..7c9a033b 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -63,7 +63,7 @@ import {
} from "./dream-apply.ts";
import { planAutoRetires } from "./dream-plan-retires.ts";
import { planTopics, topicKeyContentionWarnings } from "./dream-plan-topics.ts";
-import type { PlanState } from "./dream-plan.ts";
+import type { PlanState, ScanResult } from "./dream-plan.ts";
import { planRefresh, scanApplyEvidence, type RefreshResult } from "./dream-refresh.ts";
import { writeDreamLog } from "./dream-report.ts";
import { scanBrain } from "./dream-scan.ts";
@@ -81,7 +81,7 @@ import {
import { regenerateLessonsQuiet } from "./lessons.ts";
import { buildLinkCandidateManifest, type LinkCandidateManifest } from "./notes/link-candidates.ts";
import { gatedOwnerScopeView } from "./owner-scope-view.ts";
-import { brainDirsForWrite, dreamWorkrunPath } from "./paths.ts";
+import { brainDirsForWrite, dreamWorkrunPath, vaultRelative } from "./paths.ts";
import { loadBrainConfig } from "./policy.ts";
import { buildReconcileOutcomes } from "./reconcile-outcomes.ts";
import {
@@ -158,6 +158,33 @@ function noteProgressFaults(warnings: DreamWarning[], faults: ReadonlyArray<stri
});
}
+/** `previewReadable` was passed to a pass that is not a dry run. */
+export class DreamPreviewReadableError extends Error {
+ constructor() {
+ super("dream: previewReadable applies to a dry run only");
+ this.name = "DreamPreviewReadableError";
+ }
+}
+
+/**
+ * The scan as a caller who may read only what `admit` passes sees it:
+ * every record at a path it rejects is dropped, as if it were absent.
+ */
+function scanAsAdmitted(
+ vault: string,
+ scan: ScanResult,
+ admit: (rel: string) => boolean,
+): ScanResult {
+ const keep = (path: string): boolean => admit(vaultRelative(path, vault));
+ return {
+ ...scan,
+ signals: scan.signals.filter((r) => keep(r.path)),
+ preferences: scan.preferences.filter((r) => keep(r.path)),
+ retired: scan.retired.filter((r) => keep(r.path)),
+ corrupted: scan.corrupted.filter((r) => keep(r.path)),
+ };
+}
+
/**
* Run one consolidation pass.
*
@@ -195,6 +222,7 @@ function dreamRun(
): DreamRunSummary {
const now = opts.now ?? new Date();
const dryRun = opts.dryRun === true;
+ if (opts.previewReadable !== undefined && !dryRun) throw new DreamPreviewReadableError();
// The stage opens BEFORE the first checkpoint, not after it. A guard
// that is already past its deadline - or a signal already aborted -
// trips here, and a counter with no stage open emits nothing, so the
@@ -228,9 +256,16 @@ function dreamRun(
// the whole `Brain/` tree between two of the pass's five
// checkpoints; the stream, by contrast, is this counter's, which
// already owns a `scan` stage.
- const scan = scanBrain(vault, opts.safeguard ? { safeguard: opts.safeguard } : {});
+ const fullScan = scanBrain(vault, opts.safeguard ? { safeguard: opts.safeguard } : {});
+ const scan =
+ opts.previewReadable === undefined
+ ? fullScan
+ : scanAsAdmitted(vault, fullScan, opts.previewReadable);
progress.advance(DREAM_STAGE.scan);
- const intentReview = buildIntentReview(vault, { now });
+ const intentReview = buildIntentReview(vault, {
+ now,
+ ...(opts.previewReadable !== undefined ? { readable: opts.previewReadable } : {}),
+ });
progress.start(DREAM_STAGE.plan, scan.preferences.length);
// 1-2. Plan per-topic transitions: new unconfirmed preferences,
diff --git a/src/core/brain/expiration-set.ts b/src/core/brain/expiration-set.ts
index 989d0750..3d1ac5df 100644
--- a/src/core/brain/expiration-set.ts
+++ b/src/core/brain/expiration-set.ts
@@ -150,6 +150,13 @@ export interface SetExpirationOptions {
readonly agent?: string;
/** Injected clock, so a run stays reproducible. */
readonly now?: Date;
+ /**
+ * The vault-relative paths the caller may read. A candidate file it may
+ * not read is passed over as if it were not there, so a record withheld
+ * from the caller is refused with the unknown-id error and nothing is
+ * written to it. Absent, every candidate counts.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/** Agent recorded when the caller names none. */
@@ -239,13 +246,12 @@ export function setExpiration(
let abs: string | null = null;
for (const dir of dirs) {
const candidate = ensureInsideVault(join(dir, `${trimmed}.md`), vault);
- searched.push(
- candidate
- .slice(vault.length + 1)
- .split("\\")
- .join("/"),
- );
- if (existsSync(candidate)) {
+ const rel = candidate
+ .slice(vault.length + 1)
+ .split("\\")
+ .join("/");
+ searched.push(rel);
+ if (existsSync(candidate) && (opts.readable === undefined || opts.readable(rel))) {
abs = candidate;
break;
}
diff --git a/src/core/brain/governance/forget-plan.ts b/src/core/brain/governance/forget-plan.ts
index 290259b0..c0447d4f 100644
--- a/src/core/brain/governance/forget-plan.ts
+++ b/src/core/brain/governance/forget-plan.ts
@@ -45,7 +45,7 @@ export function buildForgetPlan(vault: string, opts: { readonly source: string }
if (!text.includes(source)) continue;
entries.push({
id: readId(path),
- path: vaultRelative(vault, path),
+ path: vaultRelative(path, vault),
kind: classify(vault, path),
action: "would-remove-source-support",
sha256: createHash("sha256").update(text, "utf8").digest("hex"),
diff --git a/src/core/brain/intent-review.ts b/src/core/brain/intent-review.ts
index e8a0c22b..45822fe5 100644
--- a/src/core/brain/intent-review.ts
+++ b/src/core/brain/intent-review.ts
@@ -32,6 +32,13 @@ export interface BrainIntentReviewReport {
export interface BuildIntentReviewOptions {
readonly now?: Date;
+ /**
+ * Vault-relative path test: when set, the review folds only the inbox
+ * signals and rejected retired records it admits, as if the others
+ * were absent, so a caller below local reach is shown no topic, count
+ * or decision a withheld record contributed to. Absent folds every one.
+ */
+ readonly readable?: (rel: string) => boolean;
}
interface SignalRecord {
@@ -50,8 +57,11 @@ export function buildIntentReview(
): BrainIntentReviewReport {
const now = options.now ?? new Date();
const config = loadBrainConfig(vault);
- const records = collectActiveSignals(vault).filter((record) =>
- isWithinWindow(record.signal.created_at, config.dream.contradiction_window_days, now),
+ const admit = options.readable;
+ const records = collectActiveSignals(vault).filter(
+ (record) =>
+ (admit === undefined || admit(record.path)) &&
+ isWithinWindow(record.signal.created_at, config.dream.contradiction_window_days, now),
);
// Clustered by RAW topic, deliberately and not yet reconciled: the dream
// pass that acts on these same signals indexes them by folded `topicKey`,
@@ -71,7 +81,7 @@ export function buildIntentReview(
topicRecords.push(record);
}
}
- const rejectedRetiredByTopic = collectRejectedRetiredSuppressors(vault);
+ const rejectedRetiredByTopic = collectRejectedRetiredSuppressors(vault, admit);
const reviews = [...byTopic.entries()]
.toSorted(([leftTopic], [rightTopic]) => leftTopic.localeCompare(rightTopic))
@@ -100,7 +110,7 @@ function collectActiveSignals(vault: string): SignalRecord[] {
const path = join(inbox, name);
try {
records.push({
- path: vaultRelative(vault, path),
+ path: vaultRelative(path, vault),
signal: parseSignal(path),
});
} catch {
@@ -112,14 +122,17 @@ function collectActiveSignals(vault: string): SignalRecord[] {
function collectRejectedRetiredSuppressors(
vault: string,
+ admit: ((rel: string) => boolean) | undefined,
): Map<string, RejectedRetiredSuppressor[]> {
const retiredDir = brainDirs(vault).retired;
const byTopic = new Map<string, RejectedRetiredSuppressor[]>();
if (!existsSync(retiredDir)) return byTopic;
for (const name of readdirSync(retiredDir).toSorted()) {
if (!name.endsWith(".md")) continue;
+ const path = join(retiredDir, name);
+ if (admit !== undefined && !admit(vaultRelative(path, vault))) continue;
try {
- const retired = parseRetired(join(retiredDir, name));
+ const retired = parseRetired(path);
if (!retired.user_rejected_reason?.trim()) continue;
const suppressor: RejectedRetiredSuppressor = {
topic: retired.topic,
diff --git a/src/core/brain/intentions.ts b/src/core/brain/intentions.ts
index de58c6d3..367f861a 100644
--- a/src/core/brain/intentions.ts
+++ b/src/core/brain/intentions.ts
@@ -11,7 +11,7 @@
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
-import { join } from "node:path";
+import { join, posix } from "node:path";
import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
@@ -51,14 +51,36 @@ export interface MoveIntentionResult {
const HISTORY_HEADER = "## History";
const HISTORY_SNIPPET_CHARS = 120;
+/** Where the active chains live, vault-relative. */
+const INTENTIONS_REL = "Brain/intentions";
+
function intentionsDir(vault: string): string {
- return join(vault, "Brain", "intentions");
+ return join(vault, INTENTIONS_REL);
}
function intentionPath(vault: string, scope: string): string {
return join(intentionsDir(vault), `${scope}.md`);
}
+/** The vault-relative page a scope label names, after the scope fold. */
+export function intentionRel(scope: string): string {
+ return posix.join(INTENTIONS_REL, `${resolveSessionScope(scope)}.md`);
+}
+
+/**
+ * The vault-relative page of a listed chain, by its file stem as it is on
+ * disk. A hand-written chain's name need not be scope-shaped, so a listing
+ * judges the file it read rather than the scope fold of its name.
+ */
+export function intentionStemRel(stem: string): string {
+ return posix.join(INTENTIONS_REL, `${stem}.md`);
+}
+
+/** `move` found no active chain for the scope. */
+export function noActiveIntentionError(scope: string): Error {
+ return new Error(`no active intention for scope: ${scope}`);
+}
+
function renderChain(chain: Omit<IntentionChain, "path">): string {
const history =
chain.history.length === 0
@@ -171,7 +193,7 @@ export function moveIntentionToHistory(
const now = input.now ?? new Date();
const activePath = intentionPath(vault, scope);
if (!existsSync(activePath)) {
- throw new Error(`no active intention for scope: ${scope}`);
+ throw noActiveIntentionError(scope);
}
const historyDir = join(intentionsDir(vault), "history");
mkdirSync(historyDir, { recursive: true });
diff --git a/src/core/brain/labels.ts b/src/core/brain/labels.ts
index 1325049d..4fd677dc 100644
--- a/src/core/brain/labels.ts
+++ b/src/core/brain/labels.ts
@@ -70,13 +70,24 @@ export interface AssignNoteLabelOptions {
readonly agent: string;
/** Injected clock for deterministic registry stamps. */
readonly now: Date;
+ /** The paths the caller may read; see {@link NoteLabelReach}. */
+ readonly readable?: NoteLabelReach;
}
export interface RemoveNoteLabelOptions {
readonly dimension: string;
readonly pack: SchemaPack;
+ /** The paths the caller may read; see {@link NoteLabelReach}. */
+ readonly readable?: NoteLabelReach;
}
+/**
+ * The vault-relative paths the caller may read. A note it may not read is
+ * refused with the error a missing note gets, before its frontmatter is
+ * read or written. Absent, every note may be labelled.
+ */
+export type NoteLabelReach = (rel: string) => boolean;
+
export interface NoteLabelResult {
/** Vault-relative path of the labelled note. */
readonly path: string;
@@ -166,7 +177,11 @@ export function assignNoteLabel(
// rewrote frontmatter anywhere in the vault regardless of the binding.
governCallerNamedWritePath(vault, relPath, LABEL_ASSIGN_SURFACE);
const assignment = validateLabelAssignment(opts.pack, opts.dimension, opts.value);
- const path = resolveNotePath(vault, relPath);
+ const path = resolveNotePath(
+ vault,
+ relPath,
+ opts.readable !== undefined ? { readable: opts.readable } : {},
+ );
const [metadata, body] = parseFrontmatter(path);
const existing = readLabels(metadata);
const kept = existing.filter((token) => !token.startsWith(`${assignment.dimension}/`));
@@ -202,7 +217,11 @@ export function removeNoteLabel(
assertStandingRulesNotTargeted(vault, relPath, LABEL_REMOVE_SURFACE);
governCallerNamedWritePath(vault, relPath, LABEL_REMOVE_SURFACE);
const dimension = normalizeSchemaToken(opts.dimension);
- const path = resolveNotePath(vault, relPath);
+ const path = resolveNotePath(
+ vault,
+ relPath,
+ opts.readable !== undefined ? { readable: opts.readable } : {},
+ );
const [metadata, body] = parseFrontmatter(path);
const existing = readLabels(metadata);
const next = existing.filter((token) => !token.startsWith(`${dimension}/`));
diff --git a/src/core/brain/lifecycle/temporal-replace.ts b/src/core/brain/lifecycle/temporal-replace.ts
index a863005b..fa1df1d0 100644
--- a/src/core/brain/lifecycle/temporal-replace.ts
+++ b/src/core/brain/lifecycle/temporal-replace.ts
@@ -135,6 +135,12 @@ export interface TemporalReplaceInput {
readonly at: string | Date;
readonly agent?: string;
readonly configPath?: string;
+ /**
+ * The vault-relative paths the caller may read. A fact it may not read
+ * is refused as a missing one, before anything is written. Absent,
+ * every fact may be written.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface TemporalReplaceResult {
@@ -163,8 +169,12 @@ export function temporalReplace(input: TemporalReplaceInput): TemporalReplaceRes
let absPred: string;
let absSucc: string;
try {
- absPred = resolveNotePath(input.vault, input.predecessor, { mustExist: true });
- absSucc = resolveNotePath(input.vault, input.successor, { mustExist: true });
+ const opts = {
+ mustExist: true,
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ };
+ absPred = resolveNotePath(input.vault, input.predecessor, opts);
+ absSucc = resolveNotePath(input.vault, input.successor, opts);
} catch (err) {
throw new TemporalReplaceError(
`temporalReplace: a fact does not resolve inside the vault: ${(err as Error).message}`,
diff --git a/src/core/brain/lifecycle/tombstone.ts b/src/core/brain/lifecycle/tombstone.ts
index f67c8cdc..60fde5a6 100644
--- a/src/core/brain/lifecycle/tombstone.ts
+++ b/src/core/brain/lifecycle/tombstone.ts
@@ -32,7 +32,7 @@ import type { FrontmatterMap } from "../../types.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
import { appendLogEvent } from "../log.ts";
import { appendDecisionChangeReceipt } from "../decisions/receipts.ts";
-import { BRAIN_ROOT_REL } from "../paths.ts";
+import { BRAIN_ROOT_REL, vaultRelative } from "../paths.ts";
import { resolveNotePath } from "../note-path.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_TOMBSTONE_STATUS } from "../types.ts";
@@ -157,6 +157,12 @@ export interface TombstoneInput {
readonly now?: Date;
/** Config path for `resolveAgentName`. Optional. */
readonly configPath?: string;
+ /**
+ * The vault-relative paths the caller may read. A target it may not
+ * read is refused as a missing one, before anything is written. Absent,
+ * every target may be written.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface TombstoneResult {
@@ -195,7 +201,10 @@ export function tombstone(input: TombstoneInput): TombstoneResult {
let abs: string;
try {
- abs = resolveNotePath(input.vault, input.path, { mustExist: true });
+ abs = resolveNotePath(input.vault, input.path, {
+ mustExist: true,
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ });
} catch (err) {
throw new TombstoneError(
`tombstone: target does not resolve inside the vault: ${(err as Error).message}`,
@@ -296,6 +305,8 @@ export interface SupersedeInput {
readonly agent?: string;
readonly now?: Date;
readonly configPath?: string;
+ /** The vault-relative paths the caller may read; see {@link TombstoneInput.readable}. */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -315,6 +326,7 @@ export function supersede(input: SupersedeInput): TombstoneResult {
...(input.agent !== undefined ? { agent: input.agent } : {}),
...(input.now !== undefined ? { now: input.now } : {}),
...(input.configPath !== undefined ? { configPath: input.configPath } : {}),
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
});
}
@@ -384,16 +396,23 @@ export function resolveChainTip(
* Build a {@link ChainLookup} over every markdown file under `Brain/`,
* keyed by bare basename. Reads each file's frontmatter once. A node
* that exists but carries no `superseded_by` resolves to a tip entry;
- * an unknown basename resolves to `null`.
+ * an unknown basename resolves to `null`. A page whose vault-relative
+ * path `readable` refuses is not indexed at all, so it reads exactly as
+ * an unknown basename; absent, every page is indexed.
*/
-export function buildChainLookup(vault: string): ChainLookup {
+export function buildChainLookup(vault: string, readable?: (rel: string) => boolean): ChainLookup {
const index = new Map<string, ChainLookupEntry>();
const root = join(vault, BRAIN_ROOT_REL);
- if (existsSync(root)) walk(root, index);
+ if (existsSync(root)) walk(vault, root, index, readable);
return (link: string): ChainLookupEntry | null => index.get(normalizeChainLink(link)) ?? null;
}
-function walk(dir: string, index: Map<string, ChainLookupEntry>): void {
+function walk(
+ vault: string,
+ dir: string,
+ index: Map<string, ChainLookupEntry>,
+ readable: ((rel: string) => boolean) | undefined,
+): void {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
@@ -404,10 +423,13 @@ function walk(dir: string, index: Map<string, ChainLookupEntry>): void {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name.startsWith(".")) continue;
- walk(full, index);
+ walk(vault, full, index, readable);
continue;
}
if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
+ // Asked before the page is parsed, so a page the caller may not read
+ // contributes nothing - not even its basename.
+ if (readable !== undefined && !readable(vaultRelative(full, vault))) continue;
let meta: FrontmatterMap;
try {
[meta] = parseFrontmatter(full);
@@ -429,7 +451,11 @@ function walk(dir: string, index: Map<string, ChainLookupEntry>): void {
export function resolveChainTipInVault(
vault: string,
start: string,
- opts: { readonly maxDepth?: number } = {},
+ opts: {
+ readonly maxDepth?: number;
+ /** The vault-relative paths the caller may read; see {@link buildChainLookup}. */
+ readonly readable?: (rel: string) => boolean;
+ } = {},
): ResolveChainTipResult {
- return resolveChainTip(start, buildChainLookup(vault), opts);
+ return resolveChainTip(start, buildChainLookup(vault, opts.readable), opts);
}
diff --git a/src/core/brain/monthly-review.ts b/src/core/brain/monthly-review.ts
index 11145803..4827ab2c 100644
--- a/src/core/brain/monthly-review.ts
+++ b/src/core/brain/monthly-review.ts
@@ -30,6 +30,13 @@ export interface BuildMonthlyReviewOptions {
readonly now?: Date;
/** Optional area labels expected to show activity in the month. */
readonly expectedAreas?: ReadonlyArray<string>;
+ /**
+ * The form of one log event the caller may see, or `null` when it may
+ * not see it at all. Applied once to the month's events before every
+ * count, so a withheld event moves none of them. Omitted, every event
+ * counts as logged (the operator's own shell).
+ */
+ readonly eventAtReach?: (ev: TemporalEvent) => TemporalEvent | null;
}
const MONTH_RE = /^\d{4}-\d{2}$/;
@@ -42,9 +49,12 @@ export function buildMonthlyReview(
const month = normalizeMonthlyReviewMonth(options.month ?? now.toISOString().slice(0, 7));
const window = monthWindow(month);
const index = buildTimelineIndex(vault, window);
- const transitions = collectTransitions(index.events);
+ const atReach = options.eventAtReach;
+ const events =
+ atReach === undefined ? index.events : index.events.flatMap((ev) => atReach(ev) ?? []);
+ const transitions = collectTransitions(events);
const retired = transitions.filter((transition) => transition.kind === "retirement").length;
- const contradictions = countContradictions(index.events);
+ const contradictions = countContradictions(events);
return Object.freeze({
schema_version: 1 as const,
@@ -52,11 +62,11 @@ export function buildMonthlyReview(
month,
window,
summary: Object.freeze({
- events: index.events.length,
+ events: events.length,
status_transitions: transitions.length,
retired,
contradictions,
- neglected_areas: Object.freeze(neglectedAreas(index.events, options.expectedAreas ?? [])),
+ neglected_areas: Object.freeze(neglectedAreas(events, options.expectedAreas ?? [])),
}),
});
}
diff --git a/src/core/brain/note-path.ts b/src/core/brain/note-path.ts
index 094df6a2..a83d8442 100644
--- a/src/core/brain/note-path.ts
+++ b/src/core/brain/note-path.ts
@@ -8,11 +8,18 @@
*/
import { existsSync, realpathSync } from "node:fs";
-import { resolve, sep } from "node:path";
+import { relative, resolve, sep } from "node:path";
export interface ResolveNotePathOptions {
/** When true (default), a missing file is an error. */
readonly mustExist?: boolean;
+ /**
+ * The vault-relative paths the caller may read. An existing note it may
+ * not read is refused with the error a missing note gets, so the
+ * refusal does not confirm the note exists. Absent, every note may be
+ * resolved.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -33,6 +40,12 @@ export function resolveNotePath(
if (opts.mustExist === false) return path;
throw new Error(`note does not exist: ${relPath}`);
}
+ if (
+ opts.readable !== undefined &&
+ !opts.readable(relative(vaultRoot, path).split(sep).join("/"))
+ ) {
+ throw new Error(`note does not exist: ${relPath}`);
+ }
// Canonicalize both sides: a symlinked vault root is fine, a
// symlinked NOTE that escapes the canonical root is not.
const realRoot = realpathSync(vaultRoot);
diff --git a/src/core/brain/notes/scaffold-stub.ts b/src/core/brain/notes/scaffold-stub.ts
index 6073353e..202e5b28 100644
--- a/src/core/brain/notes/scaffold-stub.ts
+++ b/src/core/brain/notes/scaffold-stub.ts
@@ -43,7 +43,7 @@
import { statSync } from "node:fs";
import { dirname, join, posix } from "node:path";
-import { ensureInsideVault } from "../../path-safety.ts";
+import { ensureInsideVault, vaultRelative } from "../../path-safety.ts";
import { REDACTION_PLACEHOLDER } from "../../redactor.ts";
import { requireNextStep } from "../next-step.ts";
import { SEARCH_INDEX_MISSING_CODE } from "../diagnostics.ts";
@@ -153,6 +153,13 @@ export interface ListDanglingOptions {
* pointed at it.
*/
readonly ownerScope?: string | null;
+ /**
+ * The vault-relative paths the caller may read at its reach, applied
+ * the same way as {@link ListDanglingOptions.ownerScope}: a source the
+ * caller may not read is dropped, and a target left with no source is
+ * dropped whole. Absent filters nothing.
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -212,7 +219,12 @@ export async function listDanglingTargets(
// it this way costs nothing: `listDangling` reads every unresolved
// row out of sqlite regardless and applies `limit` while grouping.
const scope = opts.ownerScope ?? null;
- const visible = await visibleTargets(vault, store.listDangling(UNBOUNDED_TARGETS), scope);
+ const visible = await visibleTargets(
+ vault,
+ store.listDangling(UNBOUNDED_TARGETS),
+ scope,
+ opts.readable,
+ );
return Object.freeze({
state: DANGLING_SCAN.measured,
targets: Object.freeze(visible.slice(0, limit)),
@@ -246,13 +258,17 @@ async function visibleTargets(
vault: string,
targets: ReadonlyArray<DanglingLinkTarget>,
scope: string | null,
+ readable: ((rel: string) => boolean) | undefined,
): Promise<ReadonlyArray<DanglingLinkTarget>> {
- if (scope === null) return targets;
+ if (scope === null && readable === undefined) return targets;
const { ownerScopeView } = await import("../owner-scope-view.ts");
- const view = ownerScopeView(vault, scope);
+ const view = scope === null ? null : ownerScopeView(vault, scope);
const kept: DanglingLinkTarget[] = [];
for (const target of targets) {
- const sources = target.sources.filter((source) => view.visible(source));
+ const sources = target.sources.filter(
+ (source) =>
+ (view === null || view.visible(source)) && (readable === undefined || readable(source)),
+ );
if (sources.length === 0) continue;
kept.push(
sources.length === target.sources.length
@@ -341,6 +357,13 @@ export interface ScaffoldStubInput {
* like any other and is attributed like one.
*/
readonly configPath?: string;
+ /**
+ * The vault-relative paths the caller may read at its reach. A source
+ * it may not read is refused exactly as a missing one, and a refusal
+ * about an occupied target names no note it may not read. Absent,
+ * every note may be read.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface ScaffoldStubResult {
@@ -382,18 +405,27 @@ function basenameOf(target: string): string {
* over-answered, and a third note makes it worse. Only `not_found` /
* `path_not_found` is a target worth materialising.
*/
-function assertMissing(vault: string, target: string): void {
+function assertMissing(
+ vault: string,
+ target: string,
+ readable: ((rel: string) => boolean) | undefined,
+): void {
+ const shown = (rel: string): boolean => readable === undefined || readable(rel);
let resolved: string | null = null;
try {
resolved = resolveNoteTitle(vault, target);
} catch (err) {
if (err instanceof NoteTitleResolutionError) {
if (err.code === "ambiguous") {
+ // Only the candidates the caller may read are named; with none, the
+ // sentence ends without an empty list.
+ const candidates = err.candidates.filter(shown);
throw new ScaffoldStubError(
"target_ambiguous",
`target "${target}" already names more than one note; ` +
- `resolve the ambiguity rather than adding a third: ${err.candidates.join(", ")}`,
- err.candidates,
+ "resolve the ambiguity rather than adding a third" +
+ (candidates.length > 0 ? `: ${candidates.join(", ")}` : ""),
+ candidates,
);
}
if (err.code === "empty_target") {
@@ -405,7 +437,8 @@ function assertMissing(vault: string, target: string): void {
}
throw new ScaffoldStubError(
"target_resolves",
- `target "${target}" already resolves to ${resolved}; there is nothing to materialise`,
+ `target "${target}" already resolves to ${shown(resolved) ? resolved : "a note"}; ` +
+ "there is nothing to materialise",
);
}
@@ -427,7 +460,11 @@ function assertMissing(vault: string, target: string): void {
* re-deriving it here would make a write depend on an index the write
* path deliberately does not consult.
*/
-function assertSourcesExist(vault: string, sources: ReadonlyArray<string>): void {
+function assertSourcesExist(
+ vault: string,
+ sources: ReadonlyArray<string>,
+ readable: ((rel: string) => boolean) | undefined,
+): void {
for (const source of sources) {
let abs: string;
try {
@@ -440,7 +477,9 @@ function assertSourcesExist(vault: string, sources: ReadonlyArray<string>): void
}
if (
!source.toLowerCase().endsWith(MARKDOWN_SUFFIX) ||
- !statSync(abs, { throwIfNoEntry: false })?.isFile()
+ !statSync(abs, { throwIfNoEntry: false })?.isFile() ||
+ // A note the caller may not read is answered as a missing one.
+ (readable !== undefined && !readable(vaultRelative(abs, vault)))
) {
throw new ScaffoldStubError(
"unknown_source",
@@ -462,11 +501,11 @@ export function scaffoldStub(vault: string, input: ScaffoldStubInput): ScaffoldS
if (target.length === 0) {
throw new ScaffoldStubError("empty_target", "scaffold target must not be empty");
}
- assertMissing(vault, target);
+ assertMissing(vault, target, input.readable);
const path = input.path ?? `${target}${MARKDOWN_SUFFIX}`;
const sources = Object.freeze([...(input.sources ?? [])].toSorted());
- assertSourcesExist(vault, sources);
+ assertSourcesExist(vault, sources, input.readable);
// Body links are the SOURCES, spelled the way a wikilink spells a note:
// the vault-relative path without its extension. Nothing else about a
// target that does not exist is known, so nothing else is written.
diff --git a/src/core/brain/obligations.ts b/src/core/brain/obligations.ts
index 04dfc822..48c63481 100644
--- a/src/core/brain/obligations.ts
+++ b/src/core/brain/obligations.ts
@@ -101,6 +101,11 @@ export interface RemoveObligationResult {
export class ObligationError extends Error {}
+/** The refusal for a slug that names no active obligation page. */
+export function noObligationError(slug: string): ObligationError {
+ return new ObligationError(`no obligation: ${slug}`);
+}
+
/** Validate and narrow an arbitrary cadence string. */
export function parseCadence(raw: string): ObligationCadence {
const value = raw.trim().toLowerCase();
@@ -281,7 +286,7 @@ export function completeObligation(vault: string, input: CompleteObligationInput
assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
const prior = parsePage(vault, slug);
- if (prior === null) throw new ObligationError(`no obligation: ${slug}`);
+ if (prior === null) throw noObligationError(slug);
const now = input.now ?? new Date();
const date = input.date ? requireIsoDate(input.date, "date") : isoDate(now);
const page = {
@@ -355,7 +360,7 @@ export function removeObligation(vault: string, slug: string): RemoveObligationR
assertVaultIdentityForWrite(vault);
const normalized = slugify(slug);
const activePath = obligationPath(vault, normalized);
- if (!existsSync(activePath)) throw new ObligationError(`no obligation: ${normalized}`);
+ if (!existsSync(activePath)) throw noObligationError(normalized);
const archiveDir = obligationsArchiveDir(vault);
mkdirSync(archiveDir, { recursive: true });
let archivePath = join(archiveDir, `${normalized}.md`);
diff --git a/src/core/brain/open-loops.ts b/src/core/brain/open-loops.ts
index ec41a743..0afcea76 100644
--- a/src/core/brain/open-loops.ts
+++ b/src/core/brain/open-loops.ts
@@ -104,6 +104,13 @@ export interface ScanOpenLoopsOptions {
readonly exclude?: ReadonlyArray<string>;
/** Per-file byte cap. Defaults to the 1 MiB `scanInline` cap. */
readonly maxFileSizeBytes?: number;
+ /**
+ * Whether the caller may read a vault-relative path. Tested before the
+ * file is read, so a page it rejects is neither read nor counted in
+ * `scannedFiles`. Omitted, every walked file is read (the operator's
+ * own shell).
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -167,6 +174,7 @@ export function scanOpenLoops(vault: string, opts: ScanOpenLoopsOptions = {}): O
let scannedFiles = 0;
for (const file of files) {
+ if (opts.readable !== undefined && !opts.readable(file.relPath)) continue;
let content: string;
try {
content = readFileSync(file.absPath, "utf8");
diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.ts
index 8433e3aa..e2a73fb1 100644
--- a/src/core/brain/path-constants.ts
+++ b/src/core/brain/path-constants.ts
@@ -224,6 +224,13 @@ export const BRAIN_COMPILED_DIGEST_RELS: ReadonlyArray<string> = Object.freeze([
* operator cannot get by editing this file.
*/
export const BRAIN_STANDING_RULES_FILE = "standing-rules.md";
+/**
+ * Directory of operator-authored SCOPED standing rules, beside the
+ * constitution file: `Brain/standing-rules/<axis>/<key>.md`, one file per
+ * resolved project, harness or host value. Read by `scoped-rules.ts`,
+ * refused to every write path by `assertStandingRulesNotTargeted`.
+ */
+export const BRAIN_SCOPED_RULES_DIR = "standing-rules";
export const BRAIN_PINNED_FILE = "pinned.md";
export const BRAIN_INDEX_FILE = "_INDEX.md";
/** Persisted claim-graph projection artifact (Belief lifecycle suite, A3). */
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index c1fbd491..317b4cb8 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -67,6 +67,7 @@ import {
BRAIN_SKILL_PROPOSALS_REJECTED_REL,
BRAIN_SNAPSHOTS_REL,
BRAIN_SOURCES_REL,
+ BRAIN_SCOPED_RULES_DIR,
BRAIN_STANDING_RULES_FILE,
BRAIN_STATE_REL,
BRAIN_TENSIONS_REL,
@@ -76,6 +77,7 @@ import {
HOOK_AUDIT_DIR,
} from "./path-constants.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import type { ScopedRuleAxis } from "./scoped-rule-axis.ts";
import type { WriteLane } from "./freeze-marker.ts";
export { ensureInsideVault, vaultRelative } from "../path-safety.ts";
@@ -270,6 +272,24 @@ export function brainStandingRulesPath(vault: string): string {
return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_STANDING_RULES_FILE), vault);
}
+/**
+ * Directory of the operator-authored scoped standing rules
+ * (`Brain/standing-rules/`). Hand-written like the constitution file and
+ * refused to every write path by `assertStandingRulesNotTargeted`.
+ */
+export function brainScopedRulesDir(vault: string): string {
+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_SCOPED_RULES_DIR), vault);
+}
+
+/**
+ * Path of one scoped rule file: `Brain/standing-rules/<axis>/<key>.md`.
+ * `key` is expected to come from `scopedRuleKey` (letters, digits and
+ * dashes only); the containment check still runs on the result.
+ */
+export function brainScopedRulePath(vault: string, axis: ScopedRuleAxis, key: string): string {
+ return ensureInsideVault(join(brainScopedRulesDir(vault), axis, `${key}.md`), vault);
+}
+
/** Path of the transient current-task scratchpad read by `brain_context`. */
export function brainPinnedPath(vault: string): string {
return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_PINNED_FILE), vault);
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index d1367bcc..43a2656e 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -78,6 +78,7 @@ export {
MOST_APPLIED_WINDOW_DAYS_DEFAULT,
MOST_APPLIED_WINDOW_DAYS_MAX,
MOST_APPLIED_WINDOW_DAYS_MIN,
+ resolveScopedRulesMaxChars,
resolveStandingRulesMaxChars,
} from "./policy/blocks/active.ts";
/**
diff --git a/src/core/brain/policy/blocks/active.ts b/src/core/brain/policy/blocks/active.ts
index ada08f1a..d067cc77 100644
--- a/src/core/brain/policy/blocks/active.ts
+++ b/src/core/brain/policy/blocks/active.ts
@@ -17,6 +17,11 @@ import {
STANDING_RULES_MAX_CHARS_MAX,
STANDING_RULES_MAX_CHARS_MIN,
} from "../../standing-rules.ts";
+import {
+ SCOPED_RULES_MAX_CHARS_DEFAULT,
+ SCOPED_RULES_MAX_CHARS_MAX,
+ SCOPED_RULES_MAX_CHARS_MIN,
+} from "../../scoped-rules.ts";
import { requireIntegerInRange } from "../field-checks.ts";
import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";
@@ -64,6 +69,7 @@ const KNOWN_KEYS = [
"most_applied_limit",
"inject_budget_chars",
"standing_rules_max_chars",
+ "scoped_rules_max_chars",
] as const;
/**
@@ -92,6 +98,13 @@ export function parseActiveBlock(ctx: BlockParseContext): BrainActiveConfig | un
STANDING_RULES_MAX_CHARS_MAX,
ctx.source,
);
+ const scopedRulesMaxChars = optionalCharCount(
+ activeMap,
+ "scoped_rules_max_chars",
+ SCOPED_RULES_MAX_CHARS_MIN,
+ SCOPED_RULES_MAX_CHARS_MAX,
+ ctx.source,
+ );
warnUnknownKeys(ctx, activeMap, KNOWN_KEYS, BLOCK);
return {
@@ -100,13 +113,14 @@ export function parseActiveBlock(ctx: BlockParseContext): BrainActiveConfig | un
...(standingRulesMaxChars !== undefined
? { standing_rules_max_chars: standingRulesMaxChars }
: {}),
+ ...(scopedRulesMaxChars !== undefined ? { scoped_rules_max_chars: scopedRulesMaxChars } : {}),
};
}
/**
* Read one optional character-count knob: absent stays absent so the
* consumer's own default applies, present is range-checked as a hard
- * error. Both knobs in this block are the same shape, and writing the
+ * error. Every count knob in this block is the same shape, and writing the
* `in`-check plus the range call twice is how the second one eventually
* gets a clamped bound the first does not have.
*/
@@ -143,6 +157,19 @@ export function resolveStandingRulesMaxChars(cfg: BrainConfig | null): number {
return cfg?.active?.standing_rules_max_chars ?? STANDING_RULES_MAX_CHARS_DEFAULT;
}
+/**
+ * Read side of `active.scoped_rules_max_chars`: the configured cap on the
+ * scoped operator rules block, or its default. Unlike the constitution's
+ * cap this block is CHARGED against `inject_budget_chars`: the SessionStart
+ * hook clamps it to what `inject_budget_chars` leaves once the block's
+ * header and notice reserve are taken (`scopedSectionCap`), so the whole
+ * block fits the budget it is charged against; `brain_context` applies the
+ * cap alone.
+ */
+export function resolveScopedRulesMaxChars(cfg: BrainConfig | null): number {
+ return cfg?.active?.scoped_rules_max_chars ?? SCOPED_RULES_MAX_CHARS_DEFAULT;
+}
+
/**
* Either key alone opts the block in; the other one falls back to its
* default, so `most_applied` is always a complete struct or absent
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index a9fbccb4..97804e68 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -151,6 +151,14 @@ export interface WritePreferenceInput {
* comparison by the shared owner-visibility model.
*/
readonly owner?: string;
+ /**
+ * Optional `visibility:` tokens (already normalised by `pageVisibility`).
+ * Emitted only when non-empty, so a default-visibility preference stays
+ * byte-identical. The dream pass stamps the strictest visibility of the
+ * signals a preference is drafted from; a rewrite that omits it keeps the
+ * file's own line through the tiered merge (it is a user-tier field).
+ */
+ readonly visibility?: ReadonlyArray<string>;
/**
* Optional provenance trust level (Knowledge Provenance suite, v1.7).
* Absent reads as `stated` (operator-asserted) for every existing
@@ -791,6 +799,9 @@ function preferenceFrontmatter(input: WritePreferenceInput, id: string): Frontma
// Freshness trend (t_ee09a6ce): stamped by the dream refresh pass;
// emitted only when supplied so legacy callers stay byte-identical.
if (input.freshness_trend?.trim()) metadata["freshness_trend"] = input.freshness_trend.trim();
+ if (input.visibility !== undefined && input.visibility.length > 0) {
+ metadata["visibility"] = [...input.visibility];
+ }
return metadata;
}
diff --git a/src/core/brain/retention.ts b/src/core/brain/retention.ts
index 14eaab55..3ce24601 100644
--- a/src/core/brain/retention.ts
+++ b/src/core/brain/retention.ts
@@ -51,7 +51,7 @@ export function buildRetentionReview(
return Object.freeze({
schema_version: 1 as const,
generated_at: now.toISOString(),
- summary: Object.freeze(summarize(recommendations)),
+ summary: Object.freeze(summarizeRetention(recommendations)),
recommendations: Object.freeze(recommendations),
});
}
@@ -121,7 +121,7 @@ function recommendRetired(
artifact_type: "retired_preference" as const,
action,
reason,
- path: vaultRelative(vault, path),
+ path: vaultRelative(path, vault),
});
}
@@ -153,11 +153,18 @@ function recommendProcessedSignal(
artifact_type: "processed_signal" as const,
action,
reason,
- path: vaultRelative(vault, path),
+ path: vaultRelative(path, vault),
});
}
-function summarize(recommendations: ReadonlyArray<RetentionRecommendation>): RetentionSummary {
+/**
+ * Count recommendations by action. Exported so a reader that keeps only
+ * some recommendations counts the ones it kept rather than shipping a
+ * summary of rows it withheld.
+ */
+export function summarizeRetention(
+ recommendations: ReadonlyArray<RetentionRecommendation>,
+): RetentionSummary {
const summary = { keep: 0, improve: 0, park: 0, prune: 0 };
for (const recommendation of recommendations) {
summary[recommendation.action] += 1;
diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.ts
index 73913edb..a9bd0200 100644
--- a/src/core/brain/review-candidates.ts
+++ b/src/core/brain/review-candidates.ts
@@ -78,6 +78,12 @@ export interface ReviewCandidatesReport {
export interface BuildReviewCandidatesOptions {
/** Wall clock for the underlying dream pass. */
readonly now?: Date;
+ /**
+ * Vault-relative path test for a caller below local reach: the dry run
+ * plans over the records it admits only (`DreamOptions.previewReadable`),
+ * so the clusters, counts and intent reviews fold no withheld record.
+ */
+ readonly readable?: (rel: string) => boolean;
/**
* When provided, annotate the report with surprisal novelty over
* the existing vec index (t_fddfe64a). Read-only; absent or
@@ -126,6 +132,7 @@ export async function buildReviewCandidates(
...(opts.now ? { now: opts.now } : {}),
...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),
...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),
+ ...(opts.readable !== undefined ? { previewReadable: opts.readable } : {}),
});
let signalNovelty: ReadonlyArray<SignalNoveltyEntry> | undefined;
diff --git a/src/core/brain/scope-identity.ts b/src/core/brain/scope-identity.ts
new file mode 100644
index 00000000..497e37b5
--- /dev/null
+++ b/src/core/brain/scope-identity.ts
@@ -0,0 +1,93 @@
+/**
+ * Server-resolved scope identity for the scoped operator rules
+ * (`scoped-rules.ts`).
+ *
+ * Every axis is derived from a fact the caller cannot name:
+ *
+ * - project: the directory holding the nearest `.o2b-vault.json`
+ * pointer that names the serving vault, written by the operator with
+ * `o2b brain project link`;
+ * - harness: the launch-time `o2b mcp --harness` option written by the
+ * packager or installer, else the install target (`--host-target`);
+ * - host: the device id, never the host name (not stable, not unique,
+ * and host names must not reach public text).
+ *
+ * Never `clientInfo`, never a tool argument, never page frontmatter.
+ */
+
+import { realpathSync } from "node:fs";
+import { basename, dirname, resolve } from "node:path";
+
+import { ConfigReadError, resolveDeviceId } from "../config.ts";
+import type { InstallTargetId } from "../runtime/host-facts.ts";
+import { findVaultPointer } from "./portability/pointer.ts";
+import { type HarnessId, scopedRuleKey } from "./scoped-rules.ts";
+
+/**
+ * Project key of a workspace directory: the basename of the directory
+ * that holds the nearest pointer naming the serving vault, keyed by
+ * `scopedRuleKey`. A pointer that names another vault, or is malformed,
+ * does not stop the walk: a repository cloned inside a linked project
+ * cannot choose or suppress that project's scope with a committed
+ * pointer. `null` for a null directory or when no pointer up the tree
+ * names the serving vault (fail closed).
+ */
+export function resolveProjectScope(
+ workspaceDir: string | null,
+ servingVault: string,
+): string | null {
+ if (workspaceDir === null) return null;
+ const serving = canonical(servingVault);
+ let probe = findVaultPointer(workspaceDir);
+ while (probe !== null) {
+ if (probe.pointer !== null && canonical(resolve(probe.dir, probe.pointer.vault)) === serving) {
+ return scopedRuleKey(basename(probe.dir));
+ }
+ const parent = dirname(probe.dir);
+ if (parent === probe.dir) return null;
+ probe = findVaultPointer(parent);
+ }
+ return null;
+}
+
+/** The real path, or the resolved path when it cannot be resolved. */
+function canonical(path: string): string {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+export interface HostScope {
+ /** The device id as a scoped-rule key, or `null` when there is none. */
+ readonly host: string | null;
+ /** True when the device id could not be read (the config is unreadable). */
+ readonly unreadable: boolean;
+}
+
+/**
+ * Host key from the device id. The empty id is the operator's explicit
+ * opt-out and is silent; an unreadable config is reported through
+ * `unreadable` so the reader can say host-scoped rules were not applied.
+ * Any other failure propagates.
+ */
+export function resolveHostScope(configPath: string | undefined): HostScope {
+ let id: string;
+ try {
+ id = resolveDeviceId(configPath);
+ } catch (err) {
+ if (err instanceof ConfigReadError) return Object.freeze({ host: null, unreadable: true });
+ throw err;
+ }
+ if (id === "") return Object.freeze({ host: null, unreadable: false });
+ return Object.freeze({ host: scopedRuleKey(id), unreadable: false });
+}
+
+/** The `--harness` value, else the install target, else `null`. */
+export function resolveHarnessScope(
+ harness: HarnessId | undefined,
+ hostTarget: InstallTargetId | undefined,
+): HarnessId | null {
+ return harness ?? hostTarget ?? null;
+}
diff --git a/src/core/brain/scoped-rule-axis.ts b/src/core/brain/scoped-rule-axis.ts
new file mode 100644
index 00000000..666b6851
--- /dev/null
+++ b/src/core/brain/scoped-rule-axis.ts
@@ -0,0 +1,31 @@
+/**
+ * The scope axes a scoped operator rule file is keyed on
+ * (`Brain/standing-rules/<axis>/<key>.md`).
+ *
+ * A leaf module with no imports: `paths.ts` types `brainScopedRulePath`
+ * with it, and `scoped-rules.ts` (which imports `paths.ts`) re-exports it,
+ * so the path helpers and the reader do not form an import cycle.
+ */
+
+/** The three scope axes a rule file can be keyed on. */
+export const SCOPED_RULE_AXIS = Object.freeze({
+ project: "project",
+ harness: "harness",
+ host: "host",
+} as const);
+
+export type ScopedRuleAxis = (typeof SCOPED_RULE_AXIS)[keyof typeof SCOPED_RULE_AXIS];
+
+/**
+ * The axes in render order, which is also the drop priority under the cap:
+ * the index is the priority, so the host file drops first.
+ */
+export const SCOPED_RULE_AXES: ReadonlyArray<ScopedRuleAxis> = Object.freeze([
+ SCOPED_RULE_AXIS.project,
+ SCOPED_RULE_AXIS.harness,
+ SCOPED_RULE_AXIS.host,
+]);
+
+export function isScopedRuleAxis(value: unknown): value is ScopedRuleAxis {
+ return typeof value === "string" && (SCOPED_RULE_AXES as ReadonlyArray<string>).includes(value);
+}
diff --git a/src/core/brain/scoped-rules.ts b/src/core/brain/scoped-rules.ts
new file mode 100644
index 00000000..92ba6098
--- /dev/null
+++ b/src/core/brain/scoped-rules.ts
@@ -0,0 +1,352 @@
+/**
+ * Scoped operator rules: `Brain/standing-rules/<axis>/<key>.md`.
+ *
+ * The constitution (`Brain/standing-rules.md`, `standing-rules.ts`) is one
+ * vault-wide file. A rule that holds for one project, one harness or one
+ * machine lives here instead, one file per resolved scope value, and is
+ * rendered below the constitution and above every recalled preference,
+ * lesson and context pack.
+ *
+ * The scope identity is resolved by the server from operator-owned or
+ * packaged facts (`scope-identity.ts`), never named by a caller. This
+ * module owns the vocabularies, the key normaliser and the reader.
+ */
+
+import { readdirSync, readFileSync } from "node:fs";
+import { join, posix } from "node:path";
+
+import { BRAIN_ROOT_REL, BRAIN_SCOPED_RULES_DIR } from "./path-constants.ts";
+import { SCOPED_RULE_AXES, SCOPED_RULE_AXIS, type ScopedRuleAxis } from "./scoped-rule-axis.ts";
+import { brainScopedRulePath, brainScopedRulesDir } from "./paths.ts";
+import { STANDING_RULES_MAX_CHARS_MAX } from "./standing-rules.ts";
+import {
+ applySectionBudget,
+ type BudgetSection,
+ type SectionTruncationReport,
+} from "./text/text-budget.ts";
+
+// ---------- Axes ----------
+
+// The axis vocabulary lives in a leaf module so that `paths.ts` can type
+// `brainScopedRulePath` without importing this reader (which imports
+// `paths.ts` and `standing-rules.ts`); it is re-exported here unchanged.
+export {
+ isScopedRuleAxis,
+ SCOPED_RULE_AXES,
+ SCOPED_RULE_AXIS,
+ type ScopedRuleAxis,
+} from "./scoped-rule-axis.ts";
+
+/** Code-authored subheading label per axis. */
+export const SCOPED_RULE_AXIS_LABEL: Readonly<Record<ScopedRuleAxis, string>> = Object.freeze({
+ project: "Project",
+ harness: "Harness",
+ host: "Host",
+});
+
+// ---------- Harnesses ----------
+
+/**
+ * Every runtime that can launch `o2b mcp`: each install target
+ * (`INSTALL_TARGET_ID`, which must equal the install adapter registry and
+ * so cannot grow) plus Claude Code, Hermes and OpenClaw, which have no
+ * install adapter. Spelled as literals rather than a spread so the
+ * vocabulary census reads the values; `scoped-rules.test.ts` asserts every
+ * install target is a member.
+ */
+export const HARNESS_ID = Object.freeze({
+ aider: "aider",
+ claudeCode: "claude-code",
+ codex: "codex",
+ copilotCli: "copilot-cli",
+ cursor: "cursor",
+ geminiCli: "gemini-cli",
+ generic: "generic",
+ grok: "grok",
+ hermes: "hermes",
+ kiro: "kiro",
+ openclaw: "openclaw",
+ opencode: "opencode",
+ pi: "pi",
+} as const);
+
+export type HarnessId = (typeof HARNESS_ID)[keyof typeof HARNESS_ID];
+
+/** The harness ids, alphabetical (the order the CLI error lists them in). */
+export const HARNESS_IDS: ReadonlyArray<HarnessId> = Object.freeze([
+ HARNESS_ID.aider,
+ HARNESS_ID.claudeCode,
+ HARNESS_ID.codex,
+ HARNESS_ID.copilotCli,
+ HARNESS_ID.cursor,
+ HARNESS_ID.geminiCli,
+ HARNESS_ID.generic,
+ HARNESS_ID.grok,
+ HARNESS_ID.hermes,
+ HARNESS_ID.kiro,
+ HARNESS_ID.openclaw,
+ HARNESS_ID.opencode,
+ HARNESS_ID.pi,
+]);
+
+export function isHarnessId(value: unknown): value is HarnessId {
+ return typeof value === "string" && (HARNESS_IDS as ReadonlyArray<string>).includes(value);
+}
+
+// ---------- Keys ----------
+
+export const SCOPED_RULE_KEY_MAX_CHARS = 64;
+
+const NON_KEY_RUN = /[^\p{L}\p{M}\p{N}]+/gu;
+
+/**
+ * File key for one scope value: NFC, lowercase, NFC again (lowercasing
+ * can decompose), every run of characters that are not a Unicode letter,
+ * combining mark or digit becomes one `-`, leading and trailing dashes
+ * removed, capped at {@link SCOPED_RULE_KEY_MAX_CHARS} code units (never
+ * half of a surrogate pair), `null` when nothing is left. No language is
+ * enumerated, so a name with no Latin character still keys, and a word
+ * written with vowel signs or diacritic marks keys whole.
+ */
+export function scopedRuleKey(value: string): string | null {
+ const folded = value.normalize("NFC").toLowerCase().normalize("NFC").replace(NON_KEY_RUN, "-");
+ const trimmed = stripDashes(capCodeUnits(stripDashes(folded), SCOPED_RULE_KEY_MAX_CHARS));
+ return trimmed === "" ? null : trimmed;
+}
+
+/** Slice to `max` code units without leaving half of a surrogate pair. */
+function capCodeUnits(value: string, max: number): string {
+ if (value.length <= max) return value;
+ const cut = value.slice(0, max);
+ const last = cut.charCodeAt(cut.length - 1);
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
+}
+
+function stripDashes(value: string): string {
+ let start = 0;
+ let end = value.length;
+ while (start < end && value[start] === "-") start += 1;
+ while (end > start && value[end - 1] === "-") end -= 1;
+ return value.slice(start, end);
+}
+
+// ---------- Cap ----------
+
+export const SCOPED_RULES_MAX_CHARS_DEFAULT = 2000;
+export const SCOPED_RULES_MAX_CHARS_MIN = 200;
+export const SCOPED_RULES_MAX_CHARS_MAX = STANDING_RULES_MAX_CHARS_MAX;
+
+// ---------- Rendering vocabulary ----------
+
+/**
+ * Code-authored header of the scoped block. It states the precedence: the
+ * constitution above outranks these rules, and these outrank every
+ * recalled preference, lesson and context pack that follows.
+ */
+export const SCOPED_RULES_HEADER =
+ "## Scoped operator rules\n\n" +
+ "The rules below are written by the operator of this vault for this project, harness or host. " +
+ "The operator standing rules above take precedence over them, and they take precedence over every recalled preference, lesson and context pack that follows.";
+
+/**
+ * Last line of the block when the device id could not be read and the
+ * host directory holds at least one rule file. No value and no path.
+ */
+export const SCOPED_RULES_HOST_UNREADABLE_NOTICE =
+ "Host-scoped rules were not applied: this device's id could not be read. Run o2b brain doctor for the cause.";
+
+/** The notice appended when the cap dropped or trimmed a file; integers only. */
+function scopedTruncationNotice(report: SectionTruncationReport): string {
+ return (
+ `_Scoped rules truncated to the configured cap: kept ${report.keptChars} of ` +
+ `${report.totalChars} characters, ${report.droppedKeys.length} file(s) dropped._`
+ );
+}
+
+/** Blank line between the header, the sections and each notice. */
+const BLOCK_SEPARATOR = "\n\n";
+
+/**
+ * Characters a caller reserves beside {@link SCOPED_RULES_HEADER} when it
+ * fits the whole block into a budget: the separators, the longest
+ * truncation notice and the host notice. The cap covers the sections only.
+ */
+export const SCOPED_RULES_NOTICE_RESERVE =
+ 3 * BLOCK_SEPARATOR.length +
+ scopedTruncationNotice({
+ droppedKeys: SCOPED_RULE_AXES,
+ keptChars: Number.MAX_SAFE_INTEGER,
+ totalChars: Number.MAX_SAFE_INTEGER,
+ trimmed: true,
+ }).length +
+ SCOPED_RULES_HOST_UNREADABLE_NOTICE.length;
+
+// ---------- Reader ----------
+
+/** The resolved value per axis; `null` matches nothing (fail closed). */
+export interface ScopedRuleIdentity {
+ readonly project: string | null;
+ readonly harness: HarnessId | null;
+ readonly host: string | null;
+}
+
+export interface ScopedRuleFile {
+ readonly axis: ScopedRuleAxis;
+ readonly key: string;
+ /** Vault-relative POSIX path, e.g. `Brain/standing-rules/project/x.md`. */
+ readonly path: string;
+ /** True when the cap dropped the file whole or trimmed its tail. */
+ readonly truncated: boolean;
+}
+
+export interface ScopedRules {
+ readonly identity: ScopedRuleIdentity;
+ readonly files: ReadonlyArray<ScopedRuleFile>;
+ /** The rendered block, `""` when nothing matched and no notice applies. */
+ readonly text: string;
+}
+
+export interface ReadScopedRulesOptions {
+ /**
+ * Character cap over the per-file sections; the header and the notices
+ * ride on top (see {@link SCOPED_RULES_NOTICE_RESERVE}).
+ */
+ readonly maxChars?: number;
+ /** The device id could not be read (`resolveHostScope().unreadable`). */
+ readonly hostUnreadable?: boolean;
+}
+
+interface MatchedFile {
+ readonly axis: ScopedRuleAxis;
+ readonly key: string;
+ readonly path: string;
+ readonly section: BudgetSection;
+}
+
+/**
+ * Read the scoped rule files matching an already-resolved identity: at
+ * most one file per axis. ENOENT and an empty file are absence; any other
+ * read failure renders an `UNAVAILABLE:` line in that file's place, built
+ * from the vault-relative path and the error code only (a Node error
+ * message carries the absolute path). Never throws for a per-file read
+ * failure, a path that leaves the vault through a symlink included. The
+ * operator's bytes are opaque: read and trimmed, nothing else.
+ */
+export function readScopedRules(
+ vault: string,
+ identity: ScopedRuleIdentity,
+ opts: ReadScopedRulesOptions = {},
+): ScopedRules {
+ const matched: MatchedFile[] = [];
+ SCOPED_RULE_AXES.forEach((axis, priority) => {
+ const value = identity[axis];
+ // Re-keyed defensively: a resolved key is a fixed point, anything else
+ // can never name a path outside its axis directory.
+ const key = value === null ? null : scopedRuleKey(value);
+ if (key === null) return;
+ const path = posix.join(BRAIN_ROOT_REL, BRAIN_SCOPED_RULES_DIR, axis, `${key}.md`);
+ const body = readRuleBody(() => brainScopedRulePath(vault, axis, key), path);
+ if (body === null) return;
+ const heading = `### ${SCOPED_RULE_AXIS_LABEL[axis]}: ${key}`;
+ matched.push({
+ axis,
+ key,
+ path,
+ section: { key: `${axis}:${key}`, priority, text: `${heading}\n\n${body}`, headLines: 1 },
+ });
+ });
+
+ const hostNotice = opts.hostUnreadable === true && hostDirHoldsRules(vault);
+ if (matched.length === 0 && !hostNotice) {
+ return Object.freeze({ identity, files: Object.freeze([]), text: "" });
+ }
+
+ let report: SectionTruncationReport | null = null;
+ const budget = applySectionBudget(
+ matched.map((file) => file.section),
+ opts.maxChars ?? SCOPED_RULES_MAX_CHARS_DEFAULT,
+ {
+ notice: (r) => {
+ report = r;
+ return scopedTruncationNotice(r);
+ },
+ },
+ );
+ const files = matched.map((file) =>
+ Object.freeze({
+ axis: file.axis,
+ key: file.key,
+ path: file.path,
+ truncated: isTruncated(file, matched, report),
+ }),
+ );
+
+ const parts = [SCOPED_RULES_HEADER];
+ if (budget.body !== "") parts.push(budget.body);
+ if (hostNotice) parts.push(SCOPED_RULES_HOST_UNREADABLE_NOTICE);
+ return Object.freeze({
+ identity,
+ files: Object.freeze(files),
+ text: parts.join(BLOCK_SEPARATOR),
+ });
+}
+
+/**
+ * Whether the cap cut this file: dropped whole, or the one kept section
+ * the budgeter trimmed (the least important kept one; priorities are
+ * unique because there is one file per axis).
+ */
+function isTruncated(
+ file: MatchedFile,
+ matched: ReadonlyArray<MatchedFile>,
+ report: SectionTruncationReport | null,
+): boolean {
+ if (report === null) return false;
+ const { droppedKeys, trimmed } = report;
+ if (droppedKeys.includes(file.section.key)) return true;
+ if (!trimmed) return false;
+ const kept = matched.filter((candidate) => !droppedKeys.includes(candidate.section.key));
+ const leastImportant = kept.reduce<MatchedFile | null>(
+ (worst, candidate) =>
+ worst === null || candidate.section.priority >= worst.section.priority ? candidate : worst,
+ null,
+ );
+ return leastImportant === file;
+}
+
+/**
+ * The trimmed body, `null` for absence, or the `UNAVAILABLE:` line. The
+ * absolute path is resolved inside the `try`: the containment check throws
+ * (with the absolute path in its message) for a file or axis folder that
+ * is a symlink leaving the vault, and that is one more per-file failure.
+ */
+function readRuleBody(absPath: () => string, relPath: string): string | null {
+ let raw: string;
+ try {
+ raw = readFileSync(absPath(), "utf8");
+ } catch (err) {
+ const code = errorCode(err);
+ if (code === "ENOENT") return null;
+ return `UNAVAILABLE: ${relPath} could not be read (${code}).`;
+ }
+ const body = raw.trim();
+ return body === "" ? null : body;
+}
+
+function errorCode(err: unknown): string {
+ const code = (err as { code?: unknown } | null)?.code;
+ if (typeof code === "string") return code;
+ const name = (err as { name?: unknown } | null)?.name;
+ return typeof name === "string" ? name : "Error";
+}
+
+/** Whether `Brain/standing-rules/host/` holds at least one `.md` file. */
+function hostDirHoldsRules(vault: string): boolean {
+ try {
+ return readdirSync(join(brainScopedRulesDir(vault), SCOPED_RULE_AXIS.host), {
+ withFileTypes: true,
+ }).some((entry) => entry.isFile() && entry.name.endsWith(".md"));
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/brain/stale-dependency.ts b/src/core/brain/stale-dependency.ts
index e664ce7d..2989e6ca 100644
--- a/src/core/brain/stale-dependency.ts
+++ b/src/core/brain/stale-dependency.ts
@@ -51,7 +51,7 @@
*/
import { readdirSync, statSync } from "node:fs";
-import { join } from "node:path";
+import { join, relative } from "node:path";
import { buildBacklinkIndex } from "./backlinks.ts";
import type { ContinuityRecord } from "./continuity/types.ts";
@@ -77,6 +77,7 @@ import { readLifecycleState } from "./lifecycle/tombstone.ts";
import { boundaryToMs, VALID_UNTIL_KEY } from "./lifecycle/temporal-replace.ts";
import { brainDirs } from "./paths.ts";
import { MS_PER_DAY } from "./time.ts";
+import { toPosix } from "../path-safety.ts";
import { parseFrontmatter } from "../vault.ts";
import { brainArtifactSlug } from "./wikilink.ts";
@@ -115,6 +116,13 @@ export interface StaleDependencyOptions {
readonly lookbackDays?: number;
/** Per-state report cap; defaults to {@link STALE_DEPENDENCY_MAX_CONSUMERS_PER_STATE}. */
readonly maxConsumersPerState?: number;
+ /**
+ * Whether the caller may read a vault-relative path. A state whose page
+ * it rejects is left out before the join and `states_changed`, so it
+ * moves no count. Omitted, every state counts (the operator's own
+ * shell).
+ */
+ readonly readable?: (rel: string) => boolean;
}
/**
@@ -182,8 +190,20 @@ export function auditStaleDependencies(
const windowSince = new Date(now.getTime() - lookbackDays * MS_PER_DAY).toISOString();
const contextReceipts = readContextReceipts(vault, windowSince);
const decisionReceipts = readDecisionCitations(vault, windowSince);
- const artifacts = walkBrainArtifacts(vault);
- const states = collectStates(vault, artifacts, now.getTime());
+ const readable = opts.readable;
+ const isReadable = (path: string): boolean =>
+ readable === undefined || readable(toPosix(relative(vault, path)));
+ // Bounded once, before both passes: a page the caller may not read is
+ // neither a state nor a consumer, so it adds to no consumer count, takes
+ // no consumer slot, and cannot hide a readable state's row by being
+ // named in it.
+ const allArtifacts = walkBrainArtifacts(vault);
+ const artifacts =
+ readable === undefined ? allArtifacts : allArtifacts.filter((a) => isReadable(a.path));
+ const allStates = collectStates(vault, artifacts, now.getTime());
+ // Retired records are read from their own folder rather than from the
+ // walk, so the states are bounded as well.
+ const states = readable === undefined ? allStates : allStates.filter((s) => isReadable(s.path));
const stateKeys = new Set(states.map((state) => state.key));
// The artifact arm runs unconditionally, and that is the point. It reads
diff --git a/src/core/brain/standing-rules.ts b/src/core/brain/standing-rules.ts
index 764c110b..4de1eea4 100644
--- a/src/core/brain/standing-rules.ts
+++ b/src/core/brain/standing-rules.ts
@@ -52,9 +52,10 @@
*/
import { readFileSync, realpathSync } from "node:fs";
-import { resolve } from "node:path";
+import { basename, dirname, join, resolve, sep } from "node:path";
-import { brainStandingRulesPath } from "./paths.ts";
+import { BRAIN_SCOPED_RULES_DIR, BRAIN_STANDING_RULES_FILE } from "./path-constants.ts";
+import { brainDirs, brainStandingRulesPath } from "./paths.ts";
import { applySectionBudget } from "./text/text-budget.ts";
/**
@@ -189,9 +190,10 @@ export class StandingRulesWriteRefusedError extends Error {
}
/**
- * Refuse a write whose target is `Brain/standing-rules.md`.
+ * Refuse a write whose target is `Brain/standing-rules.md` or any path
+ * inside the scoped rules directory `Brain/standing-rules/`.
*
- * Narrow on purpose: it names ONE file, and it is called from the write
+ * Narrow on purpose: it names one file and one directory, and it is called from the write
* paths that resolve a caller-named path without going through the
* note-target envelope that already refuses the whole `Brain/` root. It
* runs before any I/O in its callers, so a refused call also performs no
@@ -209,11 +211,62 @@ export function assertStandingRulesNotTargeted(
notePath: string,
surface: string,
): void {
- const target = brainStandingRulesPath(vault);
+ // Lexical joins, not the containment-checked helpers: a rules file or
+ // folder symlinked out of the vault must not break unrelated writes, and
+ // the canonical comparison below still refuses its own paths.
+ const brainDir = brainDirs(vault).brain;
+ const target = join(brainDir, BRAIN_STANDING_RULES_FILE);
const candidate = resolve(vault, notePath);
if (candidate === target || canonicalPath(candidate) === canonicalPath(target)) {
throw new StandingRulesWriteRefusedError(target, surface);
}
+ // The scoped rules directory (`Brain/standing-rules/`) is operator-authored
+ // too. A write usually names a file that does not exist yet, so the
+ // canonical side resolves the nearest existing ancestor and re-appends the
+ // missing tail: a new file under a symlinked folder is still caught. Both
+ // sides go through the same resolution, so a directory that does not
+ // exist yet under a symlinked vault root compares like for like.
+ const scopedDir = join(brainDir, BRAIN_SCOPED_RULES_DIR);
+ if (
+ isSameOrInside(candidate, scopedDir) ||
+ isSameOrInside(canonicalTail(candidate), canonicalTail(scopedDir))
+ ) {
+ throw new StandingRulesWriteRefusedError(candidate, surface);
+ }
+}
+
+/**
+ * The default file systems of macOS and Windows compare names without
+ * case, so there `brain/Standing-Rules/x.md` names the guarded directory.
+ * The native realpath returns the on-disk casing for the part that
+ * exists; the fold covers the tail that does not exist yet.
+ */
+const FOLD_PATH_CASE = process.platform === "darwin" || process.platform === "win32";
+
+function isSameOrInside(path: string, dir: string): boolean {
+ const p = FOLD_PATH_CASE ? path.toLowerCase() : path;
+ const d = FOLD_PATH_CASE ? dir.toLowerCase() : dir;
+ return p === d || p.startsWith(d.endsWith(sep) ? d : d + sep);
+}
+
+/**
+ * Canonical form of `path` when part of it does not exist yet: the nearest
+ * existing ancestor is canonicalized and the missing tail re-appended.
+ */
+function canonicalTail(path: string): string {
+ const missing: string[] = [];
+ let current = path;
+ for (;;) {
+ try {
+ const real = realpathSync.native(current);
+ return missing.length === 0 ? real : join(real, ...missing.toReversed());
+ } catch {
+ const parent = dirname(current);
+ if (parent === current) return path;
+ missing.push(basename(current));
+ current = parent;
+ }
+ }
}
/**
@@ -224,7 +277,7 @@ export function assertStandingRulesNotTargeted(
*/
function canonicalPath(path: string): string {
try {
- return realpathSync(path);
+ return realpathSync.native(path);
} catch {
return path;
}
diff --git a/src/core/brain/tensions.ts b/src/core/brain/tensions.ts
index aaf490b5..888a47e5 100644
--- a/src/core/brain/tensions.ts
+++ b/src/core/brain/tensions.ts
@@ -33,6 +33,8 @@ import { normalizeAgentArgument } from "../agent-identity.ts";
import { resolveAgentName } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { sanitiseTextField } from "../redactor.ts";
+import { pageVisibility, strictestVisibility } from "../graph/visibility.ts";
+import type { FrontmatterMap } from "../types.ts";
import { parseFrontmatter } from "../vault.ts";
import {
detectNoteContradictions,
@@ -164,6 +166,13 @@ export interface TensionRecord {
readonly quoteA: string;
/** Subject-bearing span quoted from {@link subjectB}. */
readonly quoteB: string;
+ /**
+ * The `visibility:` tokens the tension page carries: the stricter of
+ * its two source notes' ({@link strictestVisibility}), so a page that
+ * quotes a note is read under that note's rule. Empty is default
+ * visibility.
+ */
+ readonly visibility: ReadonlyArray<string>;
readonly path: string;
}
@@ -171,6 +180,12 @@ export interface PersistTensionOptions {
readonly agent?: string;
readonly now?: Date;
readonly configPath?: string;
+ /**
+ * The `visibility:` tokens to stamp on the page, normally the stricter
+ * of the two source notes'. Absent, a new page carries none and a
+ * refreshed page keeps what it had.
+ */
+ readonly visibility?: ReadonlyArray<string>;
}
export interface PersistTensionResult {
@@ -183,6 +198,12 @@ export interface DetectTensionsOptions extends DetectNoteContradictionsOptions {
readonly agent?: string;
readonly now?: Date;
readonly configPath?: string;
+ /**
+ * The `visibility:` tokens of the source note with this id. Each
+ * persisted tension carries the stricter of its two subjects'. Absent,
+ * no tension page carries any.
+ */
+ readonly visibilityOf?: (id: string) => ReadonlyArray<string>;
}
export interface DetectTensionsResult {
@@ -294,6 +315,9 @@ function render(record: Omit<TensionRecord, "path">): string {
lines.push(`resolution_reason: ${JSON.stringify(record.resolutionReason)}`);
}
lines.push(`agent: ${JSON.stringify(record.agent)}`);
+ if (record.visibility.length > 0) {
+ lines.push(`visibility: [${record.visibility.map((t) => JSON.stringify(t)).join(", ")}]`);
+ }
lines.push("---", "");
lines.push(`- ${record.subjectA}: ${record.quoteA}`);
lines.push(`- ${record.subjectB}: ${record.quoteB}`);
@@ -355,6 +379,7 @@ function parsePage(vault: string, slug: string): TensionRecord | null {
agent: scalarString(meta, "agent"),
quoteA: quotes.get(subjectA) ?? "",
quoteB: quotes.get(subjectB) ?? "",
+ visibility: Object.freeze(pageVisibility(meta)),
path,
});
}
@@ -422,6 +447,7 @@ export function persistTension(
detectedAt: stampedAt,
quoteA: cleanQuote(quoteLow),
quoteB: cleanQuote(quoteHigh),
+ visibility: opts.visibility ?? prior.visibility,
};
mkdirSync(tensionsDir(vault), { recursive: true });
atomicWriteFileSync(prior.path, render(next));
@@ -448,6 +474,7 @@ export function persistTension(
agent,
quoteA: cleanQuote(quoteLow),
quoteB: cleanQuote(quoteHigh),
+ visibility: opts.visibility ?? [],
};
mkdirSync(tensionsDir(vault), { recursive: true });
@@ -488,8 +515,12 @@ export function detectTensions(
const records: TensionRecord[] = [];
let created = 0;
let updated = 0;
+ const visibilityOf = opts.visibilityOf;
for (const finding of findings) {
const res = persistTension(vault, finding, {
+ ...(visibilityOf !== undefined
+ ? { visibility: strictestVisibility(visibilityOf(finding.aId), visibilityOf(finding.bId)) }
+ : {}),
...(opts.agent !== undefined ? { agent: opts.agent } : {}),
...(opts.now !== undefined ? { now: opts.now } : {}),
...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),
@@ -521,6 +552,13 @@ export interface DetectTensionsInVaultOptions {
readonly configPath?: string;
/** Byte cap per scanned file; defaults to {@link NOTE_SCAN_MAX_BYTES}. */
readonly maxFileSizeBytes?: number;
+ /**
+ * The vault-relative note paths the caller may read. A note it may not
+ * read is skipped before it is opened: it is not counted in
+ * `scannedFiles`, takes part in no pair and so names no tension.
+ * Absent, every note under the roots is read.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface DetectTensionsInVaultResult extends DetectTensionsResult {
@@ -552,8 +590,10 @@ export function detectTensionsInVault(
const rules = buildNoteWalkRules(vault);
const cap = opts.maxFileSizeBytes ?? NOTE_SCAN_MAX_BYTES;
const notes: NoteForContradiction[] = [];
+ const visibilityById = new Map<string, ReadonlyArray<string>>();
for (const file of walkMarkdownFiles(vault, roots, rules, { maxFileSizeBytes: cap })) {
- let meta: Readonly<Record<string, unknown>>;
+ if (opts.readable !== undefined && !opts.readable(file.relPath)) continue;
+ let meta: FrontmatterMap;
let body: string;
try {
[meta, body] = parseFrontmatter(file.absPath);
@@ -566,10 +606,14 @@ export function detectTensionsInVault(
const subject =
typeof rawSubject === "string" && rawSubject.trim() !== "" ? rawSubject.trim() : undefined;
notes.push({ id, ...(subject !== undefined ? { subject } : {}), text: body });
+ // Two notes may share a frontmatter id; the id then reads under the
+ // stricter of their rules.
+ visibilityById.set(id, strictestVisibility(visibilityById.get(id) ?? [], pageVisibility(meta)));
}
const result = detectTensions(vault, notes, {
jaccard: opts.jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,
+ visibilityOf: (id) => visibilityById.get(id) ?? [],
...(opts.negationMarkers !== undefined ? { negationMarkers: opts.negationMarkers } : {}),
...(opts.agent !== undefined ? { agent: opts.agent } : {}),
...(opts.now !== undefined ? { now: opts.now } : {}),
diff --git a/src/core/brain/text/text-budget.ts b/src/core/brain/text/text-budget.ts
index a1857e46..b5082420 100644
--- a/src/core/brain/text/text-budget.ts
+++ b/src/core/brain/text/text-budget.ts
@@ -31,6 +31,12 @@ export interface BudgetSection {
readonly priority: number;
/** Rendered section text, headers included. */
readonly text: string;
+ /**
+ * Leading lines (a heading) that never stand alone: a tail trim that
+ * would keep no more than these lines drops the section instead, so a
+ * heading never claims a section with nothing under it. Default 0.
+ */
+ readonly headLines?: number;
}
/**
@@ -119,16 +125,17 @@ function leastImportantIndex(kept: ReadonlyArray<KeptSection>): number {
/**
* Trim `text` from the tail at line boundaries so the result fits
* `maxChars`. Trailing blank lines left behind by the cut are removed.
- * Returns null when not even the first line fits.
+ * Returns null when not even the first line fits, or when all that would
+ * be left is the first `headLines` lines.
*/
-function trimToLines(text: string, maxChars: number): string | null {
+function trimToLines(text: string, maxChars: number, headLines = 0): string | null {
if (text.length <= maxChars) return text;
const lines = text.split("\n");
while (lines.length > 0) {
lines.pop();
while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
const candidate = lines.join("\n");
- if (candidate.length === 0) return null;
+ if (candidate.length === 0 || lines.length <= headLines) return null;
if (candidate.length <= maxChars) return candidate;
}
return null;
@@ -164,7 +171,7 @@ export function applySectionBudget(
// not even its first line fits.
if (kept.length === 1 && joinedLength(kept) > budget) {
const last = kept[0]!;
- const trimmed = trimToLines(last.text, budget);
+ const trimmed = trimToLines(last.text, budget, last.headLines);
if (trimmed === null) {
droppedKeys.push(last.key);
kept.splice(0, 1);
diff --git a/src/core/brain/today-dashboard.ts b/src/core/brain/today-dashboard.ts
index 31c24fe9..183a1f46 100644
--- a/src/core/brain/today-dashboard.ts
+++ b/src/core/brain/today-dashboard.ts
@@ -25,6 +25,7 @@
*/
import { listObligations } from "./obligations.ts";
+import { BRAIN_OBLIGATIONS_REL } from "./path-constants.ts";
import { scanOpenLoops, type OpenLoopScan } from "./open-loops.ts";
import { isoSecond } from "./time.ts";
import { buildActivityTimeline, type ActivityTimeline } from "./temporal/activity-timeline.ts";
@@ -46,6 +47,13 @@ export interface TodayDashboardOptions {
* event is shown as logged (the operator's own shell).
*/
readonly eventAtReach?: (ev: TemporalEvent) => TemporalEvent | null;
+ /**
+ * Whether the caller may read a vault-relative path. Obligation pages
+ * and open-loop notes it rejects are left out before the totals, so
+ * they move no count. Omitted, every page is listed (the operator's own
+ * shell).
+ */
+ readonly readable?: (rel: string) => boolean;
}
/** One obligation row surfaced on the dashboard. */
@@ -166,8 +174,17 @@ function computeSection<T>(
}
}
-function buildObligationsSection(vault: string, now: Date): TodayDashboardObligationsSection {
- const items = listObligations(vault, { now }).map((o) =>
+function buildObligationsSection(
+ vault: string,
+ now: Date,
+ readable: TodayDashboardOptions["readable"],
+): TodayDashboardObligationsSection {
+ const listed = listObligations(vault, { now });
+ const shown =
+ readable === undefined
+ ? listed
+ : listed.filter((o) => readable(`${BRAIN_OBLIGATIONS_REL}/${o.slug}.md`));
+ const items = shown.map((o) =>
Object.freeze({
slug: o.slug,
title: o.title,
@@ -319,13 +336,13 @@ export function buildTodayDashboard(vault: string, opts: TodayDashboardOptions):
const obligations = computeSection(
"obligations",
errors,
- () => buildObligationsSection(vault, opts.now),
+ () => buildObligationsSection(vault, opts.now, opts.readable),
EMPTY_OBLIGATIONS_SECTION,
);
const openLoops = computeSection(
"openLoops",
errors,
- () => scanOpenLoops(vault),
+ () => scanOpenLoops(vault, opts.readable === undefined ? {} : { readable: opts.readable }),
EMPTY_OPEN_LOOP_SCAN,
);
const recentActivity = computeSection(
diff --git a/src/core/brain/triggers/scan.ts b/src/core/brain/triggers/scan.ts
index d030c906..f5313526 100644
--- a/src/core/brain/triggers/scan.ts
+++ b/src/core/brain/triggers/scan.ts
@@ -15,6 +15,13 @@ import type { InsightCandidate } from "./types.ts";
export interface ScanTriggersOptions extends CreateTriggersOptions {
/** Extra candidates from other producers (synthesis, ideas). */
readonly extraCandidates?: ReadonlyArray<InsightCandidate>;
+ /**
+ * The vault-relative paths the scanning reader may read. When given,
+ * the semantic-health and retention sources run over those records
+ * only, so a withheld record yields no candidate, is counted in no
+ * total and is written into no trigger. Absent: every record.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export interface ScanTriggersResult extends CreateTriggersResult {
@@ -30,7 +37,8 @@ export interface ScanTriggersResult extends CreateTriggersResult {
export function scanTriggers(vault: string, opts: ScanTriggersOptions): ScanTriggersResult {
const candidates: InsightCandidate[] = [];
try {
- const doctor = runDoctor(vault);
+ const readable = opts.readable;
+ const doctor = runDoctor(vault, readable !== undefined ? { readable } : {});
if (doctor.semantic_health !== undefined) {
candidates.push(...candidatesFromHealth(doctor.semantic_health));
}
@@ -38,7 +46,15 @@ export function scanTriggers(vault: string, opts: ScanTriggersOptions): ScanTrig
// semantic health unavailable - skip the source
}
try {
- candidates.push(...candidatesFromRetention(buildRetentionReview(vault, { now: opts.now })));
+ const review = buildRetentionReview(vault, { now: opts.now });
+ const readable = opts.readable;
+ candidates.push(
+ ...candidatesFromRetention(
+ readable === undefined
+ ? review
+ : { ...review, recommendations: review.recommendations.filter((r) => readable(r.path)) },
+ ),
+ );
} catch {
// retention review unavailable - skip the source
}
diff --git a/src/core/brain/trust/instruction-file-ceiling.ts b/src/core/brain/trust/instruction-file-ceiling.ts
index 7218579e..9af39a4e 100644
--- a/src/core/brain/trust/instruction-file-ceiling.ts
+++ b/src/core/brain/trust/instruction-file-ceiling.ts
@@ -23,6 +23,12 @@ const TRACKED_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md", "AGENTS
export interface CheckInstructionFileCeilingOptions {
readonly maxLines: number;
+ /**
+ * The vault-relative paths the reader may read. A file it rejects is
+ * skipped before it is read, so its existence and length cross no
+ * answer. Absent: every tracked file.
+ */
+ readonly readable?: (rel: string) => boolean;
}
export function checkInstructionFileCeiling(
@@ -31,6 +37,7 @@ export function checkInstructionFileCeiling(
): ReadonlyArray<InstructionFileCeilingWarning> {
const warnings: InstructionFileCeilingWarning[] = [];
for (const name of TRACKED_FILES) {
+ if (opts.readable !== undefined && !opts.readable(name)) continue;
const absolute = join(vault, name);
if (!existsSync(absolute)) continue;
try {
diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.ts
index bdf7fb7c..94ac9417 100644
--- a/src/core/brain/trust/operator-summary.ts
+++ b/src/core/brain/trust/operator-summary.ts
@@ -19,12 +19,15 @@
*/
import { existsSync, readdirSync, statSync } from "node:fs";
-import { join } from "node:path";
+import { join, relative } from "node:path";
+
+import { toPosix } from "../../path-safety.ts";
import { runDoctor, type RunDoctorResult } from "../doctor.ts";
import type { DreamRunSummary } from "../dream.ts";
import { collectMaintenanceActions } from "../maintenance/collect.ts";
import type { ActionItem } from "../maintenance/action-scorer.ts";
+import type { DoctorIssueNaming } from "../diagnostics.ts";
import { brainDirs } from "../paths.ts";
import { BRAIN_GUARDRAIL_DEFAULTS } from "../policy.ts";
import type {
@@ -35,6 +38,7 @@ import type {
} from "../types.ts";
import {
computeVerificationDelta,
+ type VerificationDeltaEntry,
type VerificationDeltaResult,
} from "./compute-verification-delta.ts";
import { computeTrustVerdict } from "./compute-trust-verdict.ts";
@@ -83,6 +87,30 @@ export interface BuildOperatorSummaryOptions {
readonly guardrails?: ResolvedBrainGuardrailConfig;
/** Top-N cap on the maintenance action list. */
readonly topActionsN?: number;
+ /**
+ * Whether the caller may see a doctor finding. The doctor counts and
+ * the trust verdict are taken over the findings it keeps. Omitted,
+ * every finding counts (the operator's own shell).
+ */
+ readonly keepIssue?: (issue: DoctorIssueNaming) => boolean;
+ /**
+ * Whether the caller may read a vault-relative path. The digest counts
+ * only the records it may read, and the doctor pass counts its capped
+ * and pre-filter totals over them. Omitted, every record counts.
+ */
+ readonly readable?: (rel: string) => boolean;
+ /**
+ * Whether the caller may see a maintenance action. Applied before the
+ * top-N slice, so a withheld action takes no slot. Omitted, every
+ * action is ranked.
+ */
+ readonly keepAction?: (action: ActionItem) => boolean;
+ /**
+ * Whether the caller may see a verification-delta entry. The entries
+ * and their summary counts - and the trust verdict over them - are
+ * taken over the entries it keeps. Omitted, every entry counts.
+ */
+ readonly keepVerification?: (entry: VerificationDeltaEntry) => boolean;
}
const DEFAULT_TOP_ACTIONS_N = 5;
@@ -94,16 +122,24 @@ export function buildOperatorSummary(
const guardrails = opts.guardrails ?? BRAIN_GUARDRAIL_DEFAULTS;
const dreamSummary = opts.dreamSummary;
- const doctorResult = safeDoctor(vault, guardrails, dreamSummary);
+ const doctorResult = keptDoctorResult(
+ safeDoctor(vault, guardrails, dreamSummary, opts.readable),
+ opts.keepIssue,
+ );
const dreamCounts = summariseDream(dreamSummary);
- const digestCounts = collectDigestCounts(vault);
+ const digestCounts = collectDigestCounts(vault, opts.readable);
const verification = dreamSummary
- ? computeVerificationDelta(vault, dreamSummary)
+ ? keptVerification(computeVerificationDelta(vault, dreamSummary), opts.keepVerification)
: zeroVerification();
const instructionWarnings = checkInstructionFileCeiling(vault, {
maxLines: guardrails.instruction_file_max_lines,
+ ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
});
- const topActions = safeTopActions(vault, opts.topActionsN ?? DEFAULT_TOP_ACTIONS_N);
+ const topActions = safeTopActions(
+ vault,
+ opts.topActionsN ?? DEFAULT_TOP_ACTIONS_N,
+ opts.keepAction,
+ );
const trust = computeTrustVerdict({
doctorWarnings: doctorResult.warnings,
@@ -180,17 +216,52 @@ function safeDoctor(
vault: string,
guardrails: ResolvedBrainGuardrailConfig,
dreamSummary: DreamRunSummary | undefined,
+ readable: BuildOperatorSummaryOptions["readable"],
): RunDoctorResult {
try {
return runDoctor(vault, {
guardrails,
...(dreamSummary ? { dreamSummary } : {}),
+ ...(readable !== undefined ? { readable } : {}),
});
} catch {
return Object.freeze({ warnings: [], errors: [] });
}
}
+/** The doctor's warnings and errors the caller may see. */
+function keptDoctorResult(
+ result: RunDoctorResult,
+ keepIssue: BuildOperatorSummaryOptions["keepIssue"],
+): RunDoctorResult {
+ if (keepIssue === undefined) return result;
+ return Object.freeze({
+ ...result,
+ warnings: Object.freeze(result.warnings.filter(keepIssue)),
+ errors: Object.freeze(result.errors.filter(keepIssue)),
+ });
+}
+
+/** The verification entries the caller may see, with the counts taken over them. */
+function keptVerification(
+ result: VerificationDeltaResult,
+ keep: BuildOperatorSummaryOptions["keepVerification"],
+): VerificationDeltaResult {
+ if (keep === undefined) return result;
+ const entries = result.entries.filter(keep);
+ const count = (state: VerificationDeltaEntry["state"]): number =>
+ entries.filter((entry) => entry.state === state).length;
+ return Object.freeze({
+ entries: Object.freeze(entries),
+ summary: Object.freeze({
+ confirmed: count("confirmed"),
+ drift: count("drift"),
+ regression: count("regression"),
+ missing_evidence: count("missing_evidence"),
+ }),
+ });
+}
+
function summariseDream(dream: DreamRunSummary | undefined): DreamSummary {
if (dream === undefined) {
return Object.freeze({
@@ -206,21 +277,31 @@ function summariseDream(dream: DreamRunSummary | undefined): DreamSummary {
});
}
-function collectDigestCounts(vault: string): DigestSummary {
+function collectDigestCounts(
+ vault: string,
+ readable: BuildOperatorSummaryOptions["readable"],
+): DigestSummary {
const dirs = brainDirs(vault);
return Object.freeze({
- preference_count: countMarkdownFiles(dirs.preferences),
- retired_count: countMarkdownFiles(dirs.retired),
- inbox_count: countMarkdownFiles(dirs.inbox),
+ preference_count: countMarkdownFiles(vault, dirs.preferences, readable),
+ retired_count: countMarkdownFiles(vault, dirs.retired, readable),
+ inbox_count: countMarkdownFiles(vault, dirs.inbox, readable),
});
}
-function countMarkdownFiles(dir: string): number {
+function countMarkdownFiles(
+ vault: string,
+ dir: string,
+ readable: BuildOperatorSummaryOptions["readable"],
+): number {
if (!existsSync(dir)) return 0;
try {
let n = 0;
for (const name of readdirSync(dir)) {
if (!name.endsWith(".md")) continue;
+ if (readable !== undefined && !readable(toPosix(relative(vault, join(dir, name))))) {
+ continue;
+ }
try {
const s = statSync(join(dir, name));
if (s.isFile()) n += 1;
@@ -234,10 +315,15 @@ function countMarkdownFiles(dir: string): number {
}
}
-function safeTopActions(vault: string, topN: number): ReadonlyArray<ActionItem> {
+function safeTopActions(
+ vault: string,
+ topN: number,
+ keepAction: BuildOperatorSummaryOptions["keepAction"],
+): ReadonlyArray<ActionItem> {
try {
const all = collectMaintenanceActions(vault);
- return Object.freeze(all.slice(0, Math.max(0, topN)));
+ const kept = keepAction === undefined ? all : all.filter(keepAction);
+ return Object.freeze(kept.slice(0, Math.max(0, topN)));
} catch {
return Object.freeze([]);
}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 9425983a..a7ca8653 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -1536,6 +1536,13 @@ export interface BrainActiveConfig {
* STANDING_RULES_MAX_CHARS_DEFAULT from standing-rules.ts applies.
*/
readonly standing_rules_max_chars?: number;
+ /**
+ * Character cap for the operator-authored scoped rules block
+ * (`Brain/standing-rules/<axis>/<key>.md`). Unlike the constitution it
+ * is CHARGED against `inject_budget_chars`. Absent means the
+ * SCOPED_RULES_MAX_CHARS_DEFAULT from scoped-rules.ts applies.
+ */
+ readonly scoped_rules_max_chars?: number;
}
/**
diff --git a/src/core/brain/write-advisory.ts b/src/core/brain/write-advisory.ts
index 5ac08541..a1713a69 100644
--- a/src/core/brain/write-advisory.ts
+++ b/src/core/brain/write-advisory.ts
@@ -37,6 +37,8 @@
import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
+import { vaultRelative } from "../path-safety.ts";
+
import { adviseOnIncoming, type PreferenceForContradiction } from "./health/contradiction.ts";
import { appendLogEvent } from "./log.ts";
import { nextCommandField, requireNextStep, type NextCommandField } from "./next-step.ts";
@@ -79,23 +81,49 @@ export interface AdviseIncomingFeedbackParams {
readonly agent: string;
/** Injected clock for a deterministic log timestamp. Defaults to now. */
readonly now?: Date;
+ /**
+ * The vault-relative paths the caller may read. A preference it may
+ * not read is left out before scoring, so the advisory never names it.
+ * Absent, every preference counts.
+ */
+ readonly readable?: ReadablePath;
}
+/** A vault-relative path test bound to one caller. */
+type ReadablePath = (rel: string) => boolean;
+
/** The Markdown documents in `dir`, or nothing when it does not exist. */
function markdownNames(dir: string): ReadonlyArray<string> {
if (!existsSync(dir)) return [];
return readdirSync(dir).filter((name) => name.endsWith(MARKDOWN_EXT));
}
+/**
+ * The Markdown documents in `dir` the caller may read: a document it may
+ * not read is passed over as if it were not there.
+ */
+function readableMarkdownNames(
+ vault: string,
+ dir: string,
+ readable: ReadablePath | undefined,
+): ReadonlyArray<string> {
+ const names = markdownNames(dir);
+ if (readable === undefined) return names;
+ return names.filter((name) => readable(vaultRelative(join(dir, name), vault)));
+}
+
/**
* Every confirmed preference in the vault. A corrupt / mis-foldered
* preference file is skipped (that is the doctor's concern, not the write
* path's).
*/
-function loadConfirmedPrefs(vault: string): PreferenceForContradiction[] {
+function loadConfirmedPrefs(
+ vault: string,
+ readable: ReadablePath | undefined,
+): PreferenceForContradiction[] {
const dir = brainDirs(vault).preferences;
const out: PreferenceForContradiction[] = [];
- for (const name of markdownNames(dir)) {
+ for (const name of readableMarkdownNames(vault, dir, readable)) {
let pref;
try {
pref = parsePreference(join(dir, name));
@@ -116,9 +144,12 @@ function loadConfirmedPrefs(vault: string): PreferenceForContradiction[] {
function loadConfirmedScopePrefs(
vault: string,
scope: string | undefined,
+ readable: ReadablePath | undefined,
): PreferenceForContradiction[] {
const bucketKey = scope ?? UNSCOPED_BUCKET;
- return loadConfirmedPrefs(vault).filter((pref) => (pref.scope ?? UNSCOPED_BUCKET) === bucketKey);
+ return loadConfirmedPrefs(vault, readable).filter(
+ (pref) => (pref.scope ?? UNSCOPED_BUCKET) === bucketKey,
+ );
}
/**
@@ -134,7 +165,7 @@ export function adviseIncomingFeedback(
params: AdviseIncomingFeedbackParams,
): WriteConflictAdvisory | null {
try {
- const prefs = loadConfirmedScopePrefs(vault, params.scope);
+ const prefs = loadConfirmedScopePrefs(vault, params.scope, params.readable);
const advisory = adviseOnIncoming(params.principle, params.scope, prefs);
if (advisory === null) return null;
@@ -259,6 +290,12 @@ export interface AdviseUnroutableCaptureParams {
readonly agent: string;
/** Injected clock for a deterministic log timestamp. Defaults to now. */
readonly now?: Date;
+ /**
+ * The vault-relative paths the caller may read. A preference or signal
+ * it may not read adds no document to any scope. Absent, every
+ * document counts.
+ */
+ readonly readable?: ReadablePath;
}
/**
@@ -275,16 +312,19 @@ export interface AdviseUnroutableCaptureParams {
* what could not be read, so it cannot be counted; leaving it silent
* would change a ranking the operator reads with nothing to explain why.
*/
-function countScopeDocuments(vault: string): ReadonlyMap<string, number> {
+function countScopeDocuments(
+ vault: string,
+ readable: ReadablePath | undefined,
+): ReadonlyMap<string, number> {
const counts = new Map<string, number>();
const tally = (scope: string | undefined): void => {
const slug = scope?.trim();
if (!slug) return;
counts.set(slug, (counts.get(slug) ?? 0) + 1);
};
- for (const pref of loadConfirmedPrefs(vault)) tally(pref.scope);
+ for (const pref of loadConfirmedPrefs(vault, readable)) tally(pref.scope);
const inbox = brainDirs(vault).inbox;
- for (const name of markdownNames(inbox)) {
+ for (const name of readableMarkdownNames(vault, inbox, readable)) {
const path = join(inbox, name);
try {
tally(parseSignal(path).scope);
@@ -314,7 +354,7 @@ export function adviseUnroutableCapture(
): CaptureRoutingHint | null {
if (params.scope?.trim()) return null;
try {
- const candidates = [...countScopeDocuments(vault)]
+ const candidates = [...countScopeDocuments(vault, params.readable)]
.map(([scope, documents]) => Object.freeze({ scope, documents }))
.toSorted((a, b) => b.documents - a.documents || a.scope.localeCompare(b.scope));
if (candidates.length === 0) return null;
diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.ts
index c8ef7cda..97e2a1a4 100644
--- a/src/core/brain/write-batch.ts
+++ b/src/core/brain/write-batch.ts
@@ -44,6 +44,7 @@ import { DEGRADATION_CODE } from "../integrity/degradation.ts";
import { writePathAdvisoryField, type WritePathAdvisoryField } from "./write-path-advisory.ts";
import {
appendApplyEvidence,
+ isApplyEvidenceTargetPresent,
type AppendApplyEvidenceInput,
type AppendApplyEvidenceOptions,
} from "./apply-evidence.ts";
@@ -570,7 +571,7 @@ function projectOperation(
case "append_note":
return projectAppendNote(vault, operation as AppendNoteOperation, index, noteTargets, opts);
case "apply_evidence":
- return projectApplyEvidence(vault, operation as ApplyEvidenceOperation, index);
+ return projectApplyEvidence(vault, operation as ApplyEvidenceOperation, index, opts.readable);
case "append_log_line":
return projectAppendLogLine(vault, operation as AppendLogLineOperation, index);
default:
@@ -925,6 +926,7 @@ function projectApplyEvidence(
vault: string,
op: ApplyEvidenceOperation,
index: number,
+ readable: ((rel: string) => boolean) | undefined,
): PlannedOperation {
const input = op.input;
if (input === null || typeof input !== "object") {
@@ -964,7 +966,8 @@ function projectApplyEvidence(
);
}
// Existence pre-check mirrors appendApplyEvidence's own resolution so a
- // missing preference aborts the whole batch before any write happens.
+ // missing preference aborts the whole batch before any write happens. A
+ // preference the caller may not read is answered as a missing one.
const slug = prefId.startsWith("pref-") ? prefId.slice("pref-".length) : prefId;
try {
validateSlug(slug);
@@ -975,7 +978,7 @@ function projectApplyEvidence(
`operation ${index}: ${err instanceof Error ? err.message : String(err)}`,
);
}
- if (!existsSync(preferencePath(vault, slug))) {
+ if (!isApplyEvidenceTargetPresent(vault, preferencePath(vault, slug), readable)) {
throw new WriteBatchError(
"preference_not_found",
index,
@@ -985,7 +988,10 @@ function projectApplyEvidence(
}
return {
commit: () => {
- const res = appendApplyEvidence(vault, input, op.options ?? {});
+ const res = appendApplyEvidence(vault, input, {
+ ...op.options,
+ ...(readable !== undefined ? { readable } : {}),
+ });
return { kind: "apply_evidence", logged_at: res.logged_at, log_path: res.log_path };
},
};
diff --git a/src/core/graph/visibility.ts b/src/core/graph/visibility.ts
index bae7d420..0db9bec2 100644
--- a/src/core/graph/visibility.ts
+++ b/src/core/graph/visibility.ts
@@ -114,3 +114,40 @@ export function isRemotelyReadable(
if (reach === TRANSPORT_REACH.local) return true;
return !pageTags.includes(REMOTE_DENY_VISIBILITY_TOKEN);
}
+
+/**
+ * The stricter of two `visibility:` token lists (each already normalised
+ * by `pageVisibility`), for a page derived from both pages (a tension page from its two source
+ * notes, a preference the dream pass drafts from its signals).
+ *
+ * - Either list carries the reserved token: the reserved token alone,
+ * which no caller below local reach reads.
+ * - One list is empty (default visibility): the other one.
+ * - Both carry tokens: the tokens they share, so only a scope that
+ * reaches both pages reaches the derived one; when they share none, no
+ * single scope reaches both, and the reserved token is stamped.
+ */
+export function strictestVisibility(
+ a: ReadonlyArray<string>,
+ b: ReadonlyArray<string>,
+): ReadonlyArray<string> {
+ const reserved = Object.freeze([REMOTE_DENY_VISIBILITY_TOKEN]);
+ if (a.includes(REMOTE_DENY_VISIBILITY_TOKEN) || b.includes(REMOTE_DENY_VISIBILITY_TOKEN)) {
+ return reserved;
+ }
+ if (a.length === 0) return Object.freeze([...b]);
+ if (b.length === 0) return Object.freeze([...a]);
+ const shared = a.filter((t) => b.includes(t));
+ return shared.length > 0 ? Object.freeze([...new Set(shared)]) : reserved;
+}
+
+/**
+ * {@link strictestVisibility} folded over any number of token lists, for a
+ * page derived from several pages. No lists (or only default ones) give the
+ * default visibility, an empty list.
+ */
+export function strictestVisibilityOf(
+ lists: ReadonlyArray<ReadonlyArray<string>>,
+): ReadonlyArray<string> {
+ return lists.reduce<ReadonlyArray<string>>((acc, l) => strictestVisibility(acc, l), []);
+}
diff --git a/src/core/path-safety.ts b/src/core/path-safety.ts
index 2d866450..a250981f 100644
--- a/src/core/path-safety.ts
+++ b/src/core/path-safety.ts
@@ -11,6 +11,22 @@
import { existsSync, realpathSync, statSync } from "node:fs";
import { basename, dirname, join, posix, relative, resolve, sep } from "node:path";
+/** The `code` a {@link VaultEscapeError} carries, beside the errno codes of fs errors. */
+export const VAULT_ESCAPE_CODE = "ESCAPE";
+
+/**
+ * A path that leaves the vault, lexically or through a symlink. It carries
+ * a `code` the way a Node fs error does, so a reader that reports a failed
+ * read by its code names this one too rather than the bare class.
+ */
+export class VaultEscapeError extends Error {
+ readonly code = VAULT_ESCAPE_CODE;
+ constructor(message: string) {
+ super(message);
+ this.name = "VaultEscapeError";
+ }
+}
+
/**
* Throw if `target` is not the vault root or a descendant of it.
*
@@ -37,14 +53,14 @@ export function ensureInsideVault(target: string, vault: string): string {
const resolvedVault = resolve(vault);
if (!isLexicallyInside(resolvedTarget, resolvedVault)) {
- throw new Error(`path escapes vault: ${target}`);
+ throw new VaultEscapeError(`path escapes vault: ${target}`);
}
// Realpath protection only matters when the vault actually exists on
// disk — otherwise there is no symlink to follow. Pure-lexical inputs
// (used by unit tests) skip this branch and rely on step 1 above.
if (existsSync(resolvedVault) && !realpathInsideVault(resolvedTarget, resolvedVault)) {
- throw new Error(`path escapes vault via symlink: ${target}`);
+ throw new VaultEscapeError(`path escapes vault via symlink: ${target}`);
}
return resolvedTarget;
diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.ts
index 6bcecf4b..1ab11675 100644
--- a/src/core/search/visibility-surface-registry.ts
+++ b/src/core/search/visibility-surface-registry.ts
@@ -273,11 +273,15 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
{
surface: "brain_dead_ends",
kind: K.mcpTool,
- category: C.excluded,
+ category: C.covered,
reason:
- "listDeadEnds / recordDeadEnd (core/brain/dead-ends.ts) read and write Brain/dead-ends/ " +
- "notes directly via parseFrontmatterText, with no visibility check - though these are " +
- "Brain-authored records rather than general vault notes.",
+ "list keeps only the entries and parse warnings whose page readableAtContextReach(ctx) " +
+ "keeps, so a withheld dead end is absent from the answer; record writes the caller's own " +
+ "dead end and, below local reach, leaves out the ids the overflow trim archived. The trim " +
+ "still counts every active dead end against the cap but, handed the same predicate, " +
+ "archives only the readable ones, so a withheld dead end is never moved; a same-day id " +
+ "collision with a withheld dead end still takes a suffix (inherent create-collision " +
+ "residual).",
},
{
surface: "brain_claims",
@@ -302,13 +306,11 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
{
surface: "brain_labels",
kind: K.mcpTool,
- category: C.excluded,
+ category: C.covered,
reason:
- "show reads a caller-named page with parseFrontmatter and returns the caller's own path " +
- "plus its label set; at remote reach it asks reachView first and answers a reserved page " +
- "with the same refusal an absent one gets. It stays EXCLUDED because assign and remove " +
- "are write operations whose reply also carries the resulting label set, and they run no " +
- "visibility check.",
+ "show and suggest ask reachView; assign and remove resolve the page through " +
+ "resolveNotePath with readableAtContextReach(ctx), so a page the caller may not read is " +
+ "refused with 'note does not exist' before its frontmatter is read or written.",
},
{
surface: "brain_tiers",
@@ -329,8 +331,16 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"reachView, over the doctorIssueRefs each issue names (path, target, sources, message " +
"wikilinks), takes ok and trust_verdict again over the kept issues, and below local reach " +
"recounts the tier-drift warning over the rows readableAtContextReach(ctx) keeps. The " +
+ "doctor pass is handed the same predicate, so the counts its checks take before any " +
+ "issue is filtered answer at the caller's reach too: a withheld page spends no slot of " +
+ "the removed-tool warning cap or of the per-code uncertain cap, is neither a state nor a " +
+ "consumer in the stale-dependency audit, and adds no principle, topic or preference to " +
+ "the semantic-health detectors behind the concept-gap and contradiction warnings, and a " +
+ "withheld vault-root instruction file raises no ceiling warning. The " +
"repair branch hands applyRepair the caller's reach, which bounds the findings before the " +
- "plan is derived, so a withheld record is neither planned, counted nor written.",
+ "plan is derived, and the same predicate, so the checks behind the plan count and cap " +
+ "over readable pages too: a withheld record is neither planned, counted nor written, and " +
+ "the unfixable counts are those of a vault without it.",
},
{
surface: "schema_inspect",
@@ -356,10 +366,13 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
kind: K.mcpTool,
category: C.covered,
reason:
- "runs runDoctor's semantic-health pass and names preferences by id in its contradiction, " +
- "stale-claim and batch-inflation findings; each finding is kept only when every member " +
- "passes the gated owner view ANDed with reachView, and the verdict is folded again over " +
- "the kept families.",
+ "runs runDoctor's semantic-health pass handed readableAtContextReach(ctx), so the " +
+ "detectors read only the preferences and signals the caller may read: concept_gaps (a " +
+ "term and its frequency over principle text, which no reference view can judge) and the " +
+ "suppressed counts are taken over those principles and topics, and a withheld preference " +
+ "joins no contradiction, stale claim or batch. Each finding naming preferences by id is " +
+ "then kept only when every member passes the gated owner view ANDed with reachView, and " +
+ "the verdict is folded again over the kept families.",
},
{
surface: "brain_status",
@@ -375,12 +388,12 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
{
surface: "brain_maintenance",
kind: K.mcpTool,
- category: C.excluded,
+ category: C.covered,
reason:
- "the bridges and clusters lanes of this maintenance runner call discoverBridges / " +
- "detectCommunities directly in their own `run` steps, the same unfiltered vec-index and " +
- "link-graph reads brain_bridges/brain_clusters make - the response surfaces only per-lane " +
- "counts, but the reads themselves are unfiltered.",
+ "below local reach run is refused with a fixed sentence (MAINTENANCE_RUN_LOCAL_ONLY) " +
+ "before the lease or any write, because it runs the dream pass, the reindex, the bridges " +
+ "and clusters lanes and custom tasks over the whole vault; status returns the lease and " +
+ "journal only.",
},
{
surface: "brain_secrets",
@@ -405,10 +418,12 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
{
surface: "brain_diarize",
kind: K.mcpTool,
- category: C.excluded,
+ category: C.covered,
reason:
- "diarize() (core/brain/diarization.ts) returns document_set - the entity's assembled " +
- "document set from the registry and sources - with no visibility check on any member path.",
+ "diarize() is handed readableAtContextReach(ctx): a subject page the caller may not read " +
+ "answers as an unknown entity, an ingested-source page the caller may not read is neither " +
+ "evidence, counted nor named in document_set, and the link candidates are filtered by the " +
+ "same predicate beside the owner scope.",
},
{
surface: "brain_context",
@@ -457,17 +472,31 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
kind: K.mcpTool,
category: C.excluded,
reason:
- "reads the anticipatory-context cache (core/brain/anticipatory-cache.ts), which mirrors " +
- "brain_context_pack's own candidate items - no visibility check runs over the cached read.",
+ "below local reach the handler builds the bundle for the caller with the same reachView " +
+ "candidate filter brain_context_pack hands packContext, asked before ranking and " +
+ "budgeting; it neither reads nor writes the shared per-root cache entry, so a bundle " +
+ "cached for the operator is never served to a remote caller and a filtered bundle never " +
+ "replaces the operator's, and it answers cache_state miss. Session hits follow the " +
+ "session tools' <private> region model, a stated residual. Local reach is byte-identical. " +
+ "It stays EXCLUDED for the reason brain_context_pack does: the bundle carries the bodies " +
+ "of readable pages, and a readable page's body can name a reserved page in a wikilink.",
},
{
surface: "brain_context_receipts",
kind: K.mcpTool,
category: C.excluded,
reason:
- "show returns a stored receipt's full payload verbatim - the same content a prior " +
- "brain_context_pack call recorded - with no visibility re-check at read time; only a " +
- "receipt-level private/redacted flag applies, which is a different axis.",
+ "show returns a stored receipt's payload - the same content a prior brain_context_pack " +
+ "call recorded - with no visibility re-check at read time; only a receipt-level " +
+ "private/redacted flag applies, which is a different axis. Below local reach a " +
+ "SessionStart injection receipt (pack-tools.ts receiptAtReach) drops the standing-rules " +
+ "and scoped-rules items and source references and every figure that counts or measures " +
+ "them (item_count, final_text_hash, final_text_chars, total_bytes, total_tokens, " +
+ "scoped_rules_chars, budgeted_source_count), drops the budget block when no budgeted body " +
+ "is left, and summary folds without the rule items, so a degraded injection that kept " +
+ "only the rules counts as an empty receipt. A measured injection receipt whose every item " +
+ "was a rule block (isRuleOnlyInjection) is withheld whole: list and summary exclude it " +
+ "before their limit and fold bound, and show answers it as an unknown id.",
},
{
surface: "brain_event_trace",
@@ -529,10 +558,22 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"not counted), and no report snapshot is taken or delta shown; view=today renders its " +
"recent activity through the shared log-event rule (log-events-at-reach.ts via " +
"reach-events.ts) before the limit and the totals, so an event naming a withheld record " +
- "is absent and a shared dream shows only its readable transitions. Residual: the monthly " +
- "and operator views still count over the whole Brain layer (summary events, status " +
- "transitions, retired and contradiction counts; preference, retired and doctor counts " +
- "and the trust verdict), and name no id.",
+ "is absent and a shared dream shows only its readable transitions, and lists an obligation " +
+ "or an open loop only when readableAtContextReach(ctx) passes its page, tested before the " +
+ "note is read, so neither its text, its path nor the totals move; view=monthly counts the " +
+ "month's events through the same log-event rule before the transition, retirement, " +
+ "contradiction and neglected-area counts; view=operator takes its doctor counts over the " +
+ "findings the owner view ANDed with reachView keeps (the doctor pass itself handed " +
+ "readableAtContextReach(ctx), so the removed-tool and uncertain caps, the " +
+ "stale-dependency states and consumers and the semantic-health detectors count only " +
+ "readable pages), its digest counts over the preference, retired and inbox pages the " +
+ "caller may read, its instruction-file warnings over the vault-root files the caller may " +
+ "read, its top actions by target before the top-N slice, its verification entries and " +
+ "their counts by the record and page each names, and the trust verdict again over those " +
+ "kept streams. " +
+ "Residual: the operator view's dream_summary counts (dream warnings, uncertain and " +
+ "quarantined entries of the dry-run dream), and the dream warnings the trust verdict " +
+ "folds in, are still taken over the whole Brain layer and name no id.",
},
{
surface: "brain_analytics",
@@ -606,14 +647,15 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
kind: K.mcpTool,
category: C.covered,
reason:
- "the freshness detector's population comes from listVaultPages(MAINTENANCE_LANE_REACH), so " +
- "reserved pages are walked IN on purpose - a scan that stopped seeing them would diagnose a " +
- "smaller vault than the one it is diagnosing - and every finding puts its page's " +
- "vault-relative path in `targets` with a title stating a fact about it. The rule is asked " +
- "on the seam the owner rule already sits on, over what the caller is told, so a detector " +
- "registered after this one inherits it; `counts` is recomputed from the visible findings and " +
- "a withheld " +
- "id lands in `unknown_ids` exactly as one nobody issued does.",
+ "the freshness detector's population comes from listVaultPages(MAINTENANCE_LANE_REACH), " +
+ "so reserved pages are walked IN on purpose - a scan that stopped seeing them would " +
+ "diagnose a smaller vault than the one it is diagnosing - and every finding puts its " +
+ "page's vault-relative path in `targets` with a title stating a fact about it. The rule " +
+ "is asked on the seam the owner rule already sits on, over what the caller is told, so a " +
+ "detector registered after this one inherits it; `counts` is recomputed from the visible " +
+ "findings and a withheld id lands in `unknown_ids` exactly as one nobody issued does. " +
+ "refresh plans only the derived pages readableAtContextReach(ctx) keeps, so a withheld " +
+ "stale or orphaned page is neither named, re-derived nor archived.",
},
{
surface: "brain_skill_proposals",
@@ -704,6 +746,232 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"runs vault/config/plugin-manifest health checks and state-surface inventory - no note " +
"content crosses this surface; included for completeness of the file-level sweep only.",
},
+ {
+ surface: "brain_obligation",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "every operation asks readableAtContextReach(ctx) about Brain/obligations/<slug>.md " +
+ "before the page is read or written: list keeps only the obligations the caller may read, " +
+ "show answers a withheld slug as an absent one ({present: false}), and done and remove " +
+ "refuse it with the 'no obligation' error an absent slug gets, so the page is neither " +
+ "completed nor archived. Below local reach remove leaves the archive name, which steps " +
+ "past withheld archived pages, out of the answer. Residual: add over a taken slug is " +
+ "refused whoever may read the page, because creating it would replace the withheld page.",
+ },
+ {
+ surface: "brain_agenda",
+ kind: K.mcpTool,
+ category: C.excluded,
+ reason:
+ "swept in for file-level completeness because calendar-tools.ts also registers " +
+ "brain_obligation: synthesizeAgenda folds the caller-supplied calendar events into " +
+ "conflicts and focus blocks and never reads a vault page, so no note path, title or body " +
+ "crosses this surface.",
+ },
+ {
+ surface: "brain_trigger",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "scan runs scanTriggers handed readableAtContextReach(ctx), so its semantic-health and " +
+ "retention sources read only the records the caller may read: the candidates total counts " +
+ "none it may not, and a scan from a remote caller writes no trigger about a withheld " +
+ "record. Every trigger row - created, skipped, list, history - is kept only when each " +
+ "artifact it names (source_artifacts, the wikilinks in its reason, the cooldown key " +
+ "segments) passes the gated owner view ANDed with reachView, and a transition on a trigger " +
+ "the caller may not see is refused with the 'unknown trigger' error an absent id gets.",
+ },
+ {
+ surface: "brain_intention",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "list and show return intention chains - Brain-authored scope records with their text, " +
+ "history and path; the handler asks readableAtContextReach(ctx) about each chain's page, " +
+ "so below local reach a withheld chain is listed by no row, shown as absent and refused " +
+ "by move with the error an absent scope gets. set over a withheld chain is refused rather " +
+ "than read and rewritten (the one answer that cannot match an absent chain's), and move " +
+ "leaves the archive name, which steps past withheld history files, out of the answer.",
+ },
+ {
+ surface: "brain_stale_scan",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "findStaleEntries walks the preference and signal records and names each stale one by id, " +
+ "topic and vault-relative path; the handler keeps a row only when its path and id pass the " +
+ "gated owner view ANDed with reachView, so below local reach a withheld record is listed " +
+ "by no row. stale_log_files names Brain/log shards by date, which are shared by " +
+ "construction and carry no page content.",
+ },
+ {
+ surface: "brain_review_candidates",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "the dry-run dream preview runs with previewReadable bound to readableAtContextReach(ctx), " +
+ "so below local reach it clusters, counts and routes only the signals, preferences and " +
+ "retired records the caller may read: clusters_below_threshold and intent_reviews fold no " +
+ "withheld signal. would_create, would_promote, would_retire, would_supersede and " +
+ "gated_retires keep a row only when both the pref- and the ret- spelling of its id pass " +
+ "the gated owner view ANDed with reachView, and signal_novelty asks the same of each " +
+ "signal's path and id.",
+ },
+ {
+ surface: "brain_retention",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "buildRetentionReview names retired preferences and processed signals by id and " +
+ "vault-relative path; the handler keeps a recommendation only when its path and id pass " +
+ "the gated owner view ANDed with reachView, and counts the summary again over the kept " +
+ "rows, so a withheld record moves neither a row nor a count.",
+ },
+ {
+ surface: "brain_tension",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "detect hands detectTensionsInVault readableAtContextReach(ctx), so a note the caller " +
+ "may not read is skipped before it is opened: it is not counted in scanned_files, takes " +
+ "part in no pair and names no tension. A persisted tension page carries the stricter " +
+ "visibility of its two source notes (strictestVisibility), and list, verify, show and the " +
+ "confirm, dismiss and resolve transitions ask the same predicate about the tension page's " +
+ "vault-relative path, answering a withheld one as absent ('no tension') before any write.",
+ },
+ {
+ surface: "brain_lifecycle",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "tombstone, supersede and temporal-replace resolve each page argument through " +
+ "resolveNotePath with readableAtContextReach(ctx): a page the caller may not read is " +
+ "refused with the 'note does not exist' error a missing page gets, before anything is " +
+ "written. curator keeps a slice row only when its key (a page path or a memory id) passes " +
+ "the gated owner view ANDed with reachView. tip builds its chain lookup over the Brain " +
+ "pages readableAtContextReach(ctx) keeps (buildChainLookup), so a withheld id reads as " +
+ "unknown and a walk stops at it.",
+ },
+ {
+ surface: "brain_derive_fact",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "deriveFact is handed readableAtContextReach(ctx): a premise preference the caller may " +
+ "not read is refused with the missing-premise error before anything is written. A slug " +
+ "colliding with a withheld preference still refuses as existing, the inherent " +
+ "create-collision residual.",
+ },
+ {
+ surface: "brain_decision",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "every action asks readableAtContextReach(ctx) about Brain/decisions/decision-<slug>.md: " +
+ "list, compare, similar and recall skip a page the caller may not read; show, outcome and " +
+ "rate refuse it with 'no decision: <slug>' before any write; history drops receipts whose " +
+ "subject the gated owner view ANDed with reachView hides, before the total and paging. " +
+ "record over an occupied withheld slug refuses 'decision already exists', the inherent " +
+ "create-collision residual; the review obligation record opens names the decision's title " +
+ "at default visibility unless the operator reserves it too.",
+ },
+ {
+ surface: "brain_scaffold_stub",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "list drops sources the caller may not read (the owner scope ANDed with " +
+ "readableAtContextReach(ctx)) and a target left with no readable source; write refuses an " +
+ "unreadable source as unknown_source; the target_resolves and target_ambiguous refusals " +
+ "name no unreadable path. An occupied withheld target still refuses, the inherent " +
+ "create-collision residual.",
+ },
+ {
+ surface: "brain_note_lifecycle",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "swept in for file-level completeness because lifecycle-file-tools.ts also registers " +
+ "brain_scaffold_stub: rename, move, archive and delete resolve the note through the reach " +
+ "predicate and refuse a page the caller may not read with the error a missing note gets, " +
+ "before anything is read or written. A move or rename onto an occupied withheld " +
+ "destination still refuses as occupied, the inherent create-collision residual, and an " +
+ "applied move still rewrites links inside withheld pages without naming them.",
+ },
+ {
+ surface: "brain_expire",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "setExpiration is handed readableAtContextReach(ctx) and passes over a candidate file the " +
+ "caller may not read as if it were not there, so a withheld signal or preference is " +
+ "refused with the unknown-id error (ExpirationTargetNotFoundError, the same searched " +
+ "list) and nothing is written to it.",
+ },
+ {
+ surface: "brain_feedback",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "it writes the caller's own inbox signal (and, with force_confirmed, its preference) from " +
+ "the caller's arguments; the conflict advisory and the routing hint " +
+ "(adviseIncomingFeedback, adviseUnroutableCapture) score and count only the preferences " +
+ "and signals readableAtContextReach(ctx) keeps. force_confirmed over an occupied withheld " +
+ "slug still refuses with 'preference already exists', the inherent create-collision " +
+ "residual: only overwriting the page would hide it.",
+ },
+ {
+ surface: "brain_note",
+ kind: K.mcpTool,
+ category: C.excluded,
+ reason:
+ "swept in for file-level completeness because feedback-tools.ts also registers " +
+ "brain_expire: appendBrainNote appends the caller's own line to today's log and answers " +
+ "with the log path and agent; it reads no vault page.",
+ },
+ {
+ surface: "brain_observed_use",
+ kind: K.mcpTool,
+ category: C.excluded,
+ reason:
+ "swept in for file-level completeness because feedback-tools.ts also registers " +
+ "brain_expire: emitObservedUse stores the caller-supplied verdicts as one continuity " +
+ "record and answers with its id, the entry count and the timestamp; it reads no vault page.",
+ },
+ {
+ surface: "brain_apply_evidence",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "appendApplyEvidence is handed readableAtContextReach(ctx): a preference the caller may " +
+ "not read is refused with the missing-preference error (BrainPreferenceNotFoundError) " +
+ "before any write, exactly as an absent id, and the apply_evidence operation of " +
+ "brain_write_batch asks the same predicate.",
+ },
+ {
+ surface: "brain_dream",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "Below local reach only a dry run is served, planned over the records the caller may read " +
+ "as if the others were absent (previewReadable, the readableAtContextReach(ctx) " +
+ "predicate); a real pass, a single step and the staged lifecycle are refused with one " +
+ "fixed answer before anything is read or written. A preference the pass drafts carries " +
+ "the strictest visibility of the signals it is drafted from and of the record it " +
+ "supersedes or rebuts (strictestVisibilityOf), so reserved signal text never becomes a " +
+ "default-visibility preference; a refresh keeps the page's own visibility line.",
+ },
+ {
+ surface: "brain_intent_review",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "buildIntentReview folds inbox signal clusters into a topic, a decision, a signal count " +
+ "and a risk band; the handler hands it readableAtContextReach(ctx), so below local reach " +
+ "it folds only the signals and rejected retired records the caller may read, and a " +
+ "withheld one moves no topic, count or decision.",
+ },
// --- Excluded: CLI verbs, one per MCP tool above that has a CLI mirror ----
{
diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.ts
index 597cae26..d7d80c2b 100644
--- a/src/mcp/brain/admin-tools.ts
+++ b/src/mcp/brain/admin-tools.ts
@@ -10,6 +10,7 @@ import { existsSync } from "node:fs";
import { relative } from "node:path";
import { toPosix } from "../../core/path-safety.ts";
+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
import { reachView } from "../../core/brain/reach-view.ts";
import { resolveAgentName } from "../../core/config.ts";
import { resolveSearchConfig } from "../../core/search/index.ts";
@@ -28,7 +29,7 @@ import { loadSchemaPack } from "../../core/brain/schema-pack.ts";
import { listSecrets } from "../../core/brain/secrets/store.ts";
import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";
import type { ProgressSink } from "../../core/brain/progress.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { requiredStringArg, toolSafeguard } from "./shared.ts";
import { currentLease } from "../../core/brain/maintenance/lease.ts";
import { listJournal, MAINTENANCE_JOURNAL_CAP } from "../../core/brain/maintenance/journal.ts";
@@ -130,9 +131,13 @@ function toolBrainLabels(
if (typeof dimension !== "string" || dimension.trim() === "") {
throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);
}
+ // A note the caller may not read at its reach is refused as a missing
+ // one, before its frontmatter is read or written.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const reach = readable !== undefined ? { readable } : {};
try {
if (op === "remove") {
- return { ...removeNoteLabel(ctx.vault, path, { dimension, pack }) };
+ return { ...removeNoteLabel(ctx.vault, path, { dimension, pack, ...reach }) };
}
const value = args["value"];
if (typeof value !== "string" || value.trim() === "") {
@@ -143,7 +148,14 @@ function toolBrainLabels(
normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??
resolveAgentName(ctx.configPath ?? undefined);
return {
- ...assignNoteLabel(ctx.vault, path, { dimension, value, pack, agent, now: new Date() }),
+ ...assignNoteLabel(ctx.vault, path, {
+ dimension,
+ value,
+ pack,
+ agent,
+ now: new Date(),
+ ...reach,
+ }),
};
} catch (exc) {
if (exc instanceof LabelVocabularyError) {
@@ -344,6 +356,9 @@ async function toolBrainSecrets(
*/
const MAX_RETRY_TASKS = LANE_TASKS.length + CUSTOM_TASK_MAX;
+/** The refusal of a lane run below local reach; it names nothing in the vault. */
+export const MAINTENANCE_RUN_LOCAL_ONLY = "brain_maintenance: run executes at local reach only";
+
/** Quiet-window, lease-guarded heavy maintenance lane. */
async function toolBrainMaintenance(
ctx: ServerContext,
@@ -367,6 +382,16 @@ async function toolBrainMaintenance(
...(notice !== null ? { notice } : {}),
};
}
+ // A run executes the whole lane - a real dream pass that moves records,
+ // reindexing and the operator's custom tasks - over every page of the
+ // vault, so it is the operator's own operation. Below local reach it is
+ // refused with one fixed sentence, before the lease or any write, and
+ // whatever the vault holds. The test is the transport reach itself, not
+ // the owner gate: an owner-gated caller at local reach is still the
+ // operator.
+ if (contextReach(ctx) !== TRANSPORT_REACH.local) {
+ throw new MCPError(INVALID_PARAMS, MAINTENANCE_RUN_LOCAL_ONLY);
+ }
let window: DailyWindow | undefined;
const startHour = args["window_start_hour"];
const endHour = args["window_end_hour"];
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
index 2a1492f3..8b65d0cb 100644
--- a/src/mcp/brain/brief-tools.ts
+++ b/src/mcp/brain/brief-tools.ts
@@ -44,6 +44,12 @@ import {
normalizeMonthlyReviewMonth,
} from "../../core/brain/monthly-review.ts";
import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.ts";
+import type { VerificationDeltaEntry } from "../../core/brain/trust/compute-verification-delta.ts";
+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
+import { doctorIssueRefs, type DoctorIssueNaming } from "../../core/brain/diagnostics.ts";
+import type { ActionItem } from "../../core/brain/maintenance/action-scorer.ts";
+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
+import { reachView } from "../../core/brain/reach-view.ts";
import { isoDate } from "../../core/brain/time.ts";
import { captureReportDelta } from "../../core/brain/report-snapshot.ts";
import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";
@@ -404,7 +410,13 @@ async function toolBrainMonthlyReview(
throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");
}
}
- const report = buildMonthlyReview(ctx.vault, month ? { month } : {});
+ // Below local reach (or under the ownership gate) the month is counted
+ // over the events this caller may see, in the form it may see them.
+ const refs = requestRefView(ctx);
+ const report = buildMonthlyReview(ctx.vault, {
+ ...(month ? { month } : {}),
+ ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),
+ });
return {
schema_version: report.schema_version,
generated_at: report.generated_at,
@@ -492,9 +504,29 @@ async function toolBrainOperatorSummary(
dreamError = (err as Error).message ?? String(err);
}
}
+ // The doctor, digest and top-action fields - and the trust verdict over
+ // them - answer at the caller's reach, through the view brain_doctor
+ // filters its own findings and actions by, and so do the verification
+ // entries, which name the records the dream claimed. The dry-run
+ // dream's own warning, uncertain and quarantined counts are taken over
+ // the whole Brain layer and name no record.
+ const view = everyArtifactRefView(
+ gatedOwnerScopeView(ctx.vault, ctx.agentName),
+ reachView(ctx.vault, contextReach(ctx)),
+ );
+ const readable = readableAtContextReachOrUndefined(ctx);
const summary = buildOperatorSummary(ctx.vault, {
...(dreamSummary ? { dreamSummary } : {}),
...(topActionsN !== undefined ? { topActionsN } : {}),
+ ...(readable !== undefined ? { readable } : {}),
+ ...(view.filtersNothing
+ ? {}
+ : {
+ keepIssue: (issue: DoctorIssueNaming) => view.row(...doctorIssueRefs(ctx.vault, issue)),
+ keepAction: (action: ActionItem) => view.row(action.target),
+ keepVerification: (entry: VerificationDeltaEntry) =>
+ view.row(...recordRefs(entry.id), entry.path),
+ }),
});
return {
vault_path: vaultPathField(ctx),
@@ -541,9 +573,13 @@ async function toolBrainToday(
// (or under the ownership gate) it shows them as this caller may see
// them, before the limit and the totals.
const refs = requestRefView(ctx);
+ // Obligation pages and open-loop notes are listed only when the caller
+ // may read them, before the totals.
+ const readable = readableAtContextReachOrUndefined(ctx);
const dashboard = buildTodayDashboard(ctx.vault, {
now: new Date(),
...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),
+ ...(readable === undefined ? {} : { readable }),
...(lookbackDays !== undefined ? { activityLookbackDays: lookbackDays } : {}),
...(limit !== undefined ? { activityLimit: limit } : {}),
});
diff --git a/src/mcp/brain/calendar-tools.ts b/src/mcp/brain/calendar-tools.ts
index 39c5f572..7c8ff5c1 100644
--- a/src/mcp/brain/calendar-tools.ts
+++ b/src/mcp/brain/calendar-tools.ts
@@ -12,10 +12,13 @@ import {
completeObligation,
listObligations,
removeObligation,
+ noObligationError,
showObligation,
type ObligationListItem,
type ObligationPage,
} from "../../core/brain/obligations.ts";
+import { BRAIN_OBLIGATIONS_REL } from "../../core/brain/path-constants.ts";
+import { slugify } from "../../core/vault.ts";
import {
synthesizeAgenda,
type AgendaEventInput,
@@ -25,6 +28,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coerceStr, coerceStrList, unknownOperationError } from "../coerce.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
function pageJson(page: ObligationPage): Record<string, unknown> {
return {
@@ -52,21 +56,45 @@ function listItemJson(item: ObligationListItem): Record<string, unknown> {
};
}
+/** The vault-relative page of an obligation file stem, as listed (no slug fold). */
+function obligationStemRel(stem: string): string {
+ return `${BRAIN_OBLIGATIONS_REL}/${stem}.md`;
+}
+
+/** The vault-relative page a caller's slug argument names. */
+function obligationRel(slug: string): string {
+ return obligationStemRel(slugify(slug));
+}
+
function toolBrainObligation(
ctx: ServerContext,
args: Record<string, unknown>,
): Record<string, unknown> {
const operation = coerceStr(args, "operation", true)!;
+ // Every operation answers at the caller's reach: a page the caller may
+ // not read is listed, shown, completed and removed exactly as an absent
+ // one would be, so neither its text nor its existence crosses, and it
+ // is never written. `undefined` at local reach with the owner gate off.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const withheld = (slug: string): boolean =>
+ readable !== undefined && !readable(obligationRel(slug));
try {
if (operation === "list") {
const items = listObligations(ctx.vault, { overdueOnly: args["overdue"] === true });
- return { operation, obligations: items.map(listItemJson) };
+ // A listed slug is the file's own stem, which need not be slug-shaped,
+ // so its page is asked about as it is named on disk.
+ const kept =
+ readable === undefined ? items : items.filter((o) => readable(obligationStemRel(o.slug)));
+ return { operation, obligations: kept.map(listItemJson) };
}
if (operation === "add") {
const title = coerceStr(args, "title", true)!;
const cadence = coerceStr(args, "cadence", true)!;
const anchor = coerceStr(args, "anchor", false);
const notes = coerceStr(args, "notes", false);
+ // `addObligation` refuses a taken slug and never overwrites it; the
+ // refusal is the one answer that cannot match an absent page's,
+ // because creating the page would replace the withheld one.
const page = addObligation(ctx.vault, {
title,
cadence,
@@ -77,6 +105,12 @@ function toolBrainObligation(
return { operation, obligation: pageJson(page) };
}
const slug = coerceStr(args, "slug", true)!;
+ if (withheld(slug)) {
+ if (operation === "show") return { operation, slug, present: false };
+ if (operation === "done" || operation === "remove") {
+ throw noObligationError(slugify(slug));
+ }
+ }
if (operation === "show") {
const page = showObligation(ctx.vault, slug);
if (page === null) return { operation, slug, present: false };
@@ -89,6 +123,9 @@ function toolBrainObligation(
}
if (operation === "remove") {
const removed = removeObligation(ctx.vault, slug);
+ // The archive name steps past every name already taken in archive/,
+ // readable or not, so below local reach it is left out of the answer.
+ if (readable !== undefined) return { operation, slug: removed.slug };
return { operation, slug: removed.slug, archive_path: removed.archivePath };
}
} catch (err) {
diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.ts
index bd956a5b..25719809 100644
--- a/src/mcp/brain/context-tools.ts
+++ b/src/mcp/brain/context-tools.ts
@@ -15,7 +15,18 @@ import {
renderStandingRulesFailure,
type StandingRules,
} from "../../core/brain/standing-rules.ts";
-import { loadBrainConfig, resolveStandingRulesMaxChars } from "../../core/brain/policy.ts";
+import {
+ loadBrainConfig,
+ resolveScopedRulesMaxChars,
+ resolveStandingRulesMaxChars,
+} from "../../core/brain/policy.ts";
+import {
+ SCOPED_RULE_AXES,
+ readScopedRules,
+ type ScopedRuleIdentity,
+ type ScopedRules,
+} from "../../core/brain/scoped-rules.ts";
+import { resolveHostScope, resolveProjectScope } from "../../core/brain/scope-identity.ts";
import type { BrainConfig } from "../../core/brain/types.ts";
import {
regenerateActive,
@@ -370,18 +381,24 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn
// on a surface where every other path either carries the block or states
// why it could not be read.
const standing = readStandingBlock(ctx.vault);
+ // The scoped operator rules for the project, harness and host this
+ // server was launched for - local reach only, see `readScopedBlock`.
+ // Read beside the constitution, before the no-Brain return, for the
+ // same reason: the rules govern a session whatever the memory layer did.
+ const scoped = readScopedBlock(ctx);
if (!existsSync(dirs.brain)) {
return {
vault_path: vaultPathField(ctx),
present: false,
active_path: activePath,
- content: prependStandingBlock(standing, ""),
+ content: prependBlock(standing.text, prependBlock(scoped?.text ?? "", "")),
counts: EMPTY_CONTEXT_COUNTS,
generated_at: null,
pinned: serializePinnedContext(ctx, pinned),
maintenance_overdue: maintenanceOverdue,
...standingRulesField(ctx, standing),
+ ...scopedRulesField(scoped),
};
}
@@ -443,7 +460,8 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn
}
}
- content = prependStandingBlock(standing, content);
+ // Constitution first, then the scoped rules, then the memory body.
+ content = prependBlock(standing.text, prependBlock(scoped?.text ?? "", content));
content = appendPinnedToContextContent(content, pinned.content);
// Optional vault-root instruction file (v0.10.17). Absent file =
@@ -475,6 +493,7 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn
maintenance_overdue: maintenanceOverdue,
...(error ? { error } : {}),
...standingRulesField(ctx, standing),
+ ...scopedRulesField(scoped),
...(vaultInstruction
? {
vault_instruction: {
@@ -546,11 +565,94 @@ function standingRulesField(ctx: ServerContext, standing: StandingBlock): Record
};
}
-/** Put the standing block at the head of the content, or leave it alone. */
-function prependStandingBlock(standing: StandingBlock, content: string): string {
- if (standing.text.length === 0) return content;
+/** Put a block at the head of the content, or leave the content alone. */
+function prependBlock(block: string, content: string): string {
+ if (block.length === 0) return content;
const trimmed = content.trimStart();
- return trimmed.length === 0 ? `${standing.text}\n` : `${standing.text}\n\n${trimmed}`;
+ return trimmed.length === 0 ? `${block}\n` : `${block}\n\n${trimmed}`;
+}
+
+/**
+ * The scoped operator rules rendered for this server's scope, or nothing.
+ *
+ * LOCAL REACH ONLY. The scope is resolved from facts about the process
+ * that serves the call - the directory it was launched in, the harness
+ * its registration names, the device it runs on - and at remote reach
+ * none of them describes the caller. So at remote reach nothing is read
+ * at all: not the files, not the pointer, not the device id, and the
+ * answer is byte-identical whether or not any scoped file exists.
+ *
+ * The identity comes from {@link ServerContext.ruleScope} and the device
+ * id; no argument of this tool can name it (the tool takes none).
+ */
+function readScopedBlock(ctx: ServerContext): ScopedRules | null {
+ if (contextReach(ctx) !== TRANSPORT_REACH.local) return null;
+ let host: { readonly host: string | null; readonly unreadable: boolean };
+ try {
+ host = resolveHostScope(ctx.configPath ?? undefined);
+ } catch {
+ // A device id that cannot be resolved for any other reason (a config
+ // home that cannot be created, say) must not take the bootstrap
+ // surface down with it. It matches no host file, and the block says
+ // so when there is a host file it could have matched.
+ host = { host: null, unreadable: true };
+ }
+ const identity: ScopedRuleIdentity = {
+ project: resolveProjectScope(ctx.ruleScope?.workspaceDir ?? null, ctx.vault),
+ harness: ctx.ruleScope?.harness ?? null,
+ host: host.host,
+ };
+ let rules: ScopedRules;
+ try {
+ rules = readScopedRules(ctx.vault, identity, {
+ maxChars: scopedRulesMaxChars(ctx.vault),
+ hostUnreadable: host.unreadable,
+ });
+ } catch {
+ // The reader renders every per-file failure as an `UNAVAILABLE:` line
+ // and does not throw for one; anything that still escapes it must not
+ // take the constitution and the memory layer down with the scoped block.
+ return null;
+ }
+ return rules.text.length === 0 ? null : rules;
+}
+
+/**
+ * The configured cap, or its default when `_brain.yaml` cannot be read
+ * (that failure surfaces through the regenerate arm's `error` slot, as
+ * for the constitution's cap).
+ */
+function scopedRulesMaxChars(vault: string): number {
+ let cfg: BrainConfig | null = null;
+ try {
+ cfg = loadBrainConfig(vault);
+ } catch {
+ // absorbed - see above
+ }
+ return resolveScopedRulesMaxChars(cfg);
+}
+
+/**
+ * The optional `scoped_rules` key, or nothing: present only when a file
+ * matched or the host notice applies, so a vault with no scoped rules -
+ * and every remote caller - keeps today's bytes.
+ */
+function scopedRulesField(scoped: ScopedRules | null): Record<string, unknown> {
+ if (scoped === null) return {};
+ return {
+ scoped_rules: {
+ scope: {
+ project: scoped.identity.project,
+ harness: scoped.identity.harness,
+ host: scoped.identity.host,
+ },
+ files: scoped.files.map((file) => ({
+ path: file.path,
+ axis: file.axis,
+ truncated: file.truncated,
+ })),
+ },
+ };
}
// ----- brain_digest --------------------------------------------------------
@@ -622,6 +724,37 @@ const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> =
},
additionalProperties: false,
},
+ // Declared, not required: present only at local reach and only when a
+ // scoped rule file matched this server's project, harness or host (or
+ // the host notice applies), so the common path stays byte-identical.
+ scoped_rules: {
+ type: "object",
+ required: ["scope", "files"],
+ properties: {
+ scope: {
+ type: "object",
+ required: ["project", "harness", "host"],
+ // `string | null` each (empty schema, as `generated_at` above):
+ // the descriptor subset has no union type.
+ properties: { project: {}, harness: {}, host: {} },
+ additionalProperties: false,
+ },
+ files: {
+ type: "array",
+ items: {
+ type: "object",
+ required: ["path", "axis", "truncated"],
+ properties: {
+ path: { type: "string" },
+ axis: { type: "string", enum: SCOPED_RULE_AXES },
+ truncated: { type: "boolean" },
+ },
+ additionalProperties: false,
+ },
+ },
+ },
+ additionalProperties: false,
+ },
// Present only when the instruction-file read failed; see the
// "a throw is not an absence" note on the handler.
vault_instruction_error: { type: "string" },
diff --git a/src/mcp/brain/decisions-tools.ts b/src/mcp/brain/decisions-tools.ts
index f2749ee4..0449e13e 100644
--- a/src/mcp/brain/decisions-tools.ts
+++ b/src/mcp/brain/decisions-tools.ts
@@ -42,6 +42,11 @@ import {
DECISION_HISTORY_DEFAULT_LIMIT,
} from "../../core/brain/decisions/receipts.ts";
import { recallRatedDecisions } from "../../core/brain/decisions/recall.ts";
+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
+import { reachView } from "../../core/brain/reach-view.ts";
+import { contextReach } from "../tool-contract.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
const TOOL = "brain_decision";
@@ -52,6 +57,11 @@ async function toolBrainDecision(
return wrapToolErrors(TOOL, [DecisionError, ReceiptError], async () => {
const action = coerceStr(args, "action", true)!;
const agent = coerceStr(args, "agent", false) ?? undefined;
+ // A decision page the caller cannot read at its reach is answered as
+ // an absent one by every action: skipped by the lists, refused by the
+ // single-slug reads and writes with the absent slug's error.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const reads = readable !== undefined ? { readable } : {};
switch (action) {
case "record": {
@@ -105,6 +115,7 @@ async function toolBrainDecision(
);
const rationale = coerceStr(args, "rationale", false) ?? undefined;
const res = updateRating(ctx.vault, {
+ ...reads,
slug,
rating,
...(rationale ? { rationale } : {}),
@@ -114,7 +125,7 @@ async function toolBrainDecision(
}
case "compare": {
const slugs = coerceStrList(args, "slugs");
- const rows = compareDecisions(ctx.vault, slugs);
+ const rows = compareDecisions(ctx.vault, slugs, reads);
return {
action,
decisions: rows.map((d) => ({
@@ -132,6 +143,7 @@ async function toolBrainDecision(
const slug = coerceStr(args, "slug", true)!;
const outcome = coerceStr(args, "outcome", true)!;
const res = backfillOutcome(ctx.vault, {
+ ...reads,
slug,
outcome,
...(agent ? { agent } : {}),
@@ -140,7 +152,7 @@ async function toolBrainDecision(
}
case "show": {
const slug = coerceStr(args, "slug", true)!;
- const res = showDecision(ctx.vault, slug);
+ const res = showDecision(ctx.vault, slug, reads);
if (res === null) throw new DecisionError(`no decision: ${slug}`);
return {
action,
@@ -159,7 +171,9 @@ async function toolBrainDecision(
}
case "list": {
const ratedOnly = coerceBool(args, "rated");
- const all = ratedOnly ? listRatedDecisions(ctx.vault) : listDecisions(ctx.vault);
+ const all = ratedOnly
+ ? listRatedDecisions(ctx.vault, reads)
+ : listDecisions(ctx.vault, reads);
return {
action,
decisions: all.map((d) => ({
@@ -185,6 +199,7 @@ async function toolBrainDecision(
: coerceInt(args, "last_turn", 0, 0, 1_000_000);
const surfacedIds = coerceStrList(args, "surfaced_ids");
const res = recallRatedDecisions(ctx.vault, {
+ ...reads,
prompt,
turn,
state: {
@@ -214,7 +229,15 @@ async function toolBrainDecision(
args["limit"] === undefined
? DECISION_HISTORY_DEFAULT_LIMIT
: coerceInt(args, "limit", DECISION_HISTORY_DEFAULT_LIMIT, 1, 500);
+ // A receipt names its subject by decision id, page path or record
+ // id; one naming a page the caller cannot read is dropped before
+ // the total and the page are taken.
+ const view = everyArtifactRefView(
+ gatedOwnerScopeView(ctx.vault, ctx.agentName),
+ reachView(ctx.vault, contextReach(ctx)),
+ );
const page = queryDecisionChangeHistory(ctx.vault, {
+ ...(view.filtersNothing ? {} : { keep: (r) => view.visible(r.subject) }),
...(subject ? { subject } : {}),
...(cursor ? { cursor } : {}),
limit,
@@ -238,10 +261,14 @@ async function toolBrainDecision(
case "similar": {
const title = coerceStr(args, "title", true)!;
const chosen = coerceStr(args, "chosen", false) ?? undefined;
- const hits = findSimilarDecisions(ctx.vault, {
- title,
- ...(chosen ? { chosen } : {}),
- });
+ const hits = findSimilarDecisions(
+ ctx.vault,
+ {
+ title,
+ ...(chosen ? { chosen } : {}),
+ },
+ reads,
+ );
return {
action,
similar: hits.map((h) => ({
diff --git a/src/mcp/brain/derive-tools.ts b/src/mcp/brain/derive-tools.ts
index 1a02464c..ab78fd48 100644
--- a/src/mcp/brain/derive-tools.ts
+++ b/src/mcp/brain/derive-tools.ts
@@ -20,6 +20,7 @@ import { loadGuardrailsConfigSafe } from "../../core/brain/policy.ts";
import { ResponseShapeError } from "../../core/brain/response-shape.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { wrapToolErrors } from "./shared.ts";
const TOOL = "brain_derive_fact";
@@ -39,8 +40,11 @@ async function toolBrainDeriveFact(
// Shape first: the payload is validated before any field is read, so a
// structurally wrong request never reaches the premise lookup or a write.
const input = parseDeriveFactInput(args);
+ // A premise the caller may not read is refused as a missing one.
+ const readable = readableAtContextReachOrUndefined(ctx);
const res = deriveFact(ctx.vault, input, {
now: new Date(),
+ ...(readable !== undefined ? { readable } : {}),
// The ownership stamp resolves the writing identity from the
// server's own config, not from anything the caller sent.
...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.ts
index ec7f4036..efafac92 100644
--- a/src/mcp/brain/feedback-tools.ts
+++ b/src/mcp/brain/feedback-tools.ts
@@ -91,7 +91,7 @@ import {
vaultRelativeSafe,
} from "./shared.ts";
import { OPERATION } from "../../core/brain/safeguard.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
/**
* Build the slug used in the signal / preference filename. We never let
@@ -240,8 +240,12 @@ async function toolBrainFeedback(
// advisory when it closely resembles an existing rule. Computed BEFORE
// any force-confirmed write so it never matches the pref this very call
// is about to create. The write has already landed; this never blocks it.
+ // Both advisories answer at the caller's reach: a preference or signal
+ // the caller may not read is never scored, named or counted.
+ const readable = readableAtContextReachOrUndefined(ctx);
const advisory: WriteConflictAdvisory | null = adviseIncomingFeedback(ctx.vault, {
principle,
+ ...(readable !== undefined ? { readable } : {}),
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
agent,
now,
@@ -251,6 +255,7 @@ async function toolBrainFeedback(
// no scope, so no scoped recall reaches it. Non-blocking like the
// advisory, and absent entirely when this vault uses no scopes yet.
const routingHint: CaptureRoutingHint | null = adviseUnroutableCapture(ctx.vault, {
+ ...(readable !== undefined ? { readable } : {}),
...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),
agent,
now,
@@ -434,6 +439,10 @@ function scopedDreamRows<R extends string>(
};
}
+/** The one answer a caller below local reach gets for anything but a dry run. */
+const DREAM_LOCAL_REACH_ONLY =
+ "brain_dream: below local reach only action=run with dry_run is served; a real pass, a step and the staged lifecycle run at local reach only";
+
async function toolBrainDream(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -465,6 +474,16 @@ async function toolBrainDream(
// The rollup step's link candidates leave out a page the caller may not
// read at its reach, exactly as an absent page.
const readable = readableAtContextReach(ctx);
+ // Below local reach only a dry run is served, planned over the records
+ // the caller may read as if the others were absent. A real pass, a
+ // single step and the staged lifecycle move, rewrite or report records
+ // the caller may not read, so they are refused with one fixed answer
+ // before anything is read or written, whatever the vault holds.
+ const previewReadable = readableAtContextReachOrUndefined(ctx);
+ if (previewReadable !== undefined && (action !== "run" || !dryRun || stepArg)) {
+ throw new MCPError(INVALID_PARAMS, DREAM_LOCAL_REACH_ONLY);
+ }
+ const previewScope = previewReadable !== undefined ? { previewReadable } : {};
// Single-step requests (no-dead-ends, Unit E - operator surface).
// Deliberately checked before any environment work: a step the pass
@@ -641,6 +660,7 @@ async function toolBrainDream(
dryRun: true,
safeguard,
readable,
+ ...previewScope,
...(nowDate ? { now: nowDate } : {}),
...(agent ? { agentName: agent } : {}),
// Preview the run being guarded, overrides and all.
@@ -665,6 +685,7 @@ async function toolBrainDream(
dryRun,
safeguard,
readable,
+ ...previewScope,
...(nowDate ? { now: nowDate } : {}),
...(agent ? { agentName: agent } : {}),
...(gates !== undefined ? { gates } : {}),
@@ -783,9 +804,13 @@ async function toolBrainApplyEvidence(
// payload that explains what to do next, not a JSON-RPC error frame.
// v0.10.16: assert applier role at the MCP boundary so the structural
// permission gate fires before any I/O.
+ // A preference the caller may not read is refused as a missing one,
+ // before anything is written.
+ const readable = readableAtContextReachOrUndefined(ctx);
try {
const res = appendApplyEvidence(ctx.vault, input, {
role: BRAIN_ROLES.applier,
+ ...(readable !== undefined ? { readable } : {}),
});
return {
logged_at: res.logged_at,
@@ -917,9 +942,13 @@ async function toolBrainExpire(
const id = coerceStr(args, "id", true)!;
const expires = coerceStr(args, "expires", true)!;
const agent = coerceStr(args, "agent", false);
+ // A record the caller may not read is refused as an unknown id, before
+ // anything is written.
+ const readable = readableAtContextReachOrUndefined(ctx);
try {
const res = setExpiration(ctx.vault, id, expires, {
...(agent ? { agent } : {}),
+ ...(readable !== undefined ? { readable } : {}),
});
return {
id: res.id,
diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.ts
index 8f98be44..3af76df7 100644
--- a/src/mcp/brain/health-tools.ts
+++ b/src/mcp/brain/health-tools.ts
@@ -25,7 +25,7 @@ import type { DoctorIssue } from "../../core/brain/types.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBool, coerceFormat } from "../coerce.ts";
import { vaultRelativeSafe } from "./shared.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { findingRefs } from "./hygiene-tools.ts";
import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
import { reachView } from "../../core/brain/reach-view.ts";
@@ -118,6 +118,11 @@ async function toolBrainDoctor(
if (apply && !repair) {
throw new Error("brain_doctor: apply requires repair");
}
+ // The counts the checks take before any finding is filtered - the
+ // removed-tool warning cap, the stale-dependency note, the concept
+ // gaps - are taken over the pages this caller may read, in the repair
+ // preview as in the report.
+ const readable = readableAtContextReachOrUndefined(ctx);
if (repair) {
if (strict && apply) {
throw new Error("brain_doctor: cannot combine strict (read-only) with repair + apply");
@@ -134,6 +139,7 @@ async function toolBrainDoctor(
// And by the caller's reach: a record it cannot read there is
// neither planned nor written, and counts toward nothing.
reach: contextReach(ctx),
+ ...(readable !== undefined ? { readable } : {}),
});
return { format, repair: outcome };
}
@@ -146,6 +152,7 @@ async function toolBrainDoctor(
// the config this server was started against, not whatever default
// discovery would find.
...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),
+ ...(readable !== undefined ? { readable } : {}),
});
// Every issue names the artifact it is about - `path`, `target`, the
@@ -279,7 +286,13 @@ async function toolBrainHealth(
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const format = coerceFormat(args);
- const result = runDoctor(ctx.vault);
+ // The detectors run over the records this caller may read: a concept
+ // gap is a term and its frequency taken over principle TEXT, so the
+ // reference view below cannot judge it, and a withheld principle would
+ // otherwise name its own words. `undefined` at local reach with the
+ // owner gate off, so the operator's report is unchanged.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const result = runDoctor(ctx.vault, readable !== undefined ? { readable } : {});
const sh = result.semantic_health;
// Three of the four finding families name preferences by id, and the
// batch-inflation family names their topics as well
@@ -321,7 +334,8 @@ async function toolBrainHealth(
a_sign: c.aSign,
b_sign: c.bSign,
})),
- // A term and its frequency; the only family that names no artifact.
+ // A term and its frequency, taken over the principles this caller
+ // may read; the only family that names no artifact.
concept_gaps: conceptGaps.map((g) => ({
term: g.term,
frequency: g.frequency,
diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.ts
index bcd6675b..5b262f84 100644
--- a/src/mcp/brain/hygiene-tools.ts
+++ b/src/mcp/brain/hygiene-tools.ts
@@ -53,7 +53,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { enforceCountGuard, readCountGuardArgs, vaultRelativeSafe } from "./shared.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
function coerceStringArray(args: Record<string, unknown>, key: string): string[] | undefined {
const raw = args[key];
@@ -232,7 +232,21 @@ async function toolBrainHygiene(
const dryRun = coerceBool(args, "dry_run") === true;
if (mode === "refresh") {
- const plan = planRecompile(ctx.vault);
+ // A derived page the caller cannot read at its reach is treated as
+ // absent: it is neither planned, named nor re-derived or archived, so
+ // the plan and the result read as in a vault without it.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const fullPlan = planRecompile(ctx.vault);
+ const plan =
+ readable === undefined
+ ? fullPlan
+ : Object.freeze({
+ entries: Object.freeze(
+ fullPlan.entries.filter((entry) =>
+ readable(vaultRelativeSafe(ctx.vault, entry.page)),
+ ),
+ ),
+ });
const result = await executeRecompile(ctx.vault, plan, {
dryRun,
agent: resolveAgentName(ctx.configPath ?? undefined),
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
index 32788180..c4b4e90a 100644
--- a/src/mcp/brain/knowledge-tools.ts
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -76,8 +76,8 @@ import {
coerceBool,
unknownOperationError,
} from "../coerce.ts";
-import { coercePositiveInteger, toolSafeguard } from "./shared.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { coercePositiveInteger, toolSafeguard, vaultRelativeSafe } from "./shared.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
/**
* Vault-relative locations these two handlers read BY PATH, rather than
@@ -694,9 +694,17 @@ function toolBrainDeadEnds(
if (op !== "record" && op !== "list") {
throw unknownOperationError("brain_dead_ends: operation must be record|list");
}
+ // A dead-end page the caller cannot read at its reach is treated as
+ // absent: `list` leaves it out of the entries and the warnings.
+ const readable = readableAtContextReachOrUndefined(ctx);
if (op === "list") {
const { entries, warnings } = listDeadEnds(ctx.vault);
- return { entries, warnings };
+ if (readable === undefined) return { entries, warnings };
+ const shown = (path: string): boolean => readable(vaultRelativeSafe(ctx.vault, path));
+ return {
+ entries: entries.filter((entry) => shown(entry.path)),
+ warnings: warnings.filter((warning) => shown(warning.path)),
+ };
}
const approach = args["approach"];
const reason = args["reason"];
@@ -716,8 +724,17 @@ function toolBrainDeadEnds(
...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),
agent,
now: new Date(),
+ ...(readable !== undefined ? { readable } : {}),
});
- return { ok: true, id: result.entry.id, path: result.entry.path, archived: result.archived };
+ // The overflow trim walks every active dead end, so below local reach the
+ // ids it archived are left out: they would name or count withheld pages.
+ // It archives only pages the caller can read; a withheld one stays put.
+ return {
+ ok: true,
+ id: result.entry.id,
+ path: result.entry.path,
+ ...(readable === undefined ? { archived: result.archived } : {}),
+ };
}
// ----- brain_codegraph_report (t_a1e76788) -----------------------------------
diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.ts
index ebbc4ecc..99180fd9 100644
--- a/src/mcp/brain/lifecycle-file-tools.ts
+++ b/src/mcp/brain/lifecycle-file-tools.ts
@@ -47,7 +47,7 @@ import { COUNT_GUARD_WIRE_CODE, TOOL_ERROR_CODE } from "../tool-error-codes.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBoolOptional, coerceStr, unknownOperationError } from "../coerce.ts";
import { coerceNonNegativeInteger, readCountGuardArgs } from "./shared.ts";
-import { readableAtContextReach } from "./reach-readable.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
const TOOL = "brain_note_lifecycle";
@@ -277,9 +277,13 @@ async function toolBrainScaffoldStub(
// `sources` are vault-relative document paths and `target` is the
// link spelling, so an unscoped listing published both for a note
// this caller may not read (a-label-is-not-a-boundary, U3).
+ // A source the caller may not read at its reach is dropped like one
+ // outside its owner scope.
+ const readable = readableAtContextReachOrUndefined(ctx);
const scan = await listDanglingTargets(ctx.vault, {
...(limit !== undefined ? { limit } : {}),
ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,
+ ...(readable !== undefined ? { readable } : {}),
});
return {
action,
@@ -301,8 +305,12 @@ async function toolBrainScaffoldStub(
}
const apply = coerceBoolOptional(args, "apply");
+ // A source the caller may not read is refused as a missing one, and an
+ // occupied-target refusal names no note it may not read.
+ const readable = readableAtContextReachOrUndefined(ctx);
try {
const res = scaffoldStub(ctx.vault, {
+ ...(readable !== undefined ? { readable } : {}),
target,
...(path !== undefined ? { path } : {}),
sources: coerceStringArray(args, "sources"),
diff --git a/src/mcp/brain/lifecycle-tools.ts b/src/mcp/brain/lifecycle-tools.ts
index bf1a8cd5..58f92ae6 100644
--- a/src/mcp/brain/lifecycle-tools.ts
+++ b/src/mcp/brain/lifecycle-tools.ts
@@ -13,7 +13,8 @@
* core lifecycle module so the on-disk shape cannot drift.
*/
-import { curatorSlices } from "../../core/brain/lifecycle/curator.ts";
+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
+import { curatorSlices, type CuratorEntry } from "../../core/brain/lifecycle/curator.ts";
import {
temporalReplace,
TemporalReplaceError,
@@ -24,20 +25,18 @@ import {
tombstone,
TombstoneError,
} from "../../core/brain/lifecycle/tombstone.ts";
+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
+import { reachView } from "../../core/brain/reach-view.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";
import { coerceStr, unknownOperationError } from "../coerce.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { coerceNonNegativeInteger, wrapToolErrors } from "./shared.ts";
const TOOL = "brain_lifecycle";
/** Project curator slice rows into the tool's snake_cased response shape. */
-function renderCuratorRows(
- rows: ReadonlyArray<{
- key: string;
- reuse: { used: number; ignored: number; contradicted: number };
- }>,
-): Array<Record<string, unknown>> {
+function renderCuratorRows(rows: ReadonlyArray<CuratorEntry>): Array<Record<string, unknown>> {
return rows.map((r) => ({
key: r.key,
used: r.reuse.used,
@@ -53,6 +52,10 @@ async function toolBrainLifecycle(
return wrapToolErrors(TOOL, [TombstoneError, TemporalReplaceError], async () => {
const action = coerceStr(args, "action", true)!;
const agent = coerceStr(args, "agent", false) ?? undefined;
+ // Every write answers at the caller's reach: a page it may not read is
+ // refused as a missing one, before anything is written.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const reachOpt = readable !== undefined ? { readable } : {};
switch (action) {
case "tombstone": {
@@ -65,6 +68,7 @@ async function toolBrainLifecycle(
reason,
...(supersededBy ? { supersededBy } : {}),
...(agent ? { agent } : {}),
+ ...reachOpt,
});
return {
action,
@@ -84,6 +88,7 @@ async function toolBrainLifecycle(
successor,
...(reason ? { reason } : {}),
...(agent ? { agent } : {}),
+ ...reachOpt,
});
return {
action,
@@ -102,6 +107,7 @@ async function toolBrainLifecycle(
successor,
at,
...(agent ? { agent } : {}),
+ ...reachOpt,
});
return {
action,
@@ -113,7 +119,9 @@ async function toolBrainLifecycle(
}
case "tip": {
const id = coerceStr(args, "id", true)!;
- const res = resolveChainTipInVault(ctx.vault, id);
+ // A page the caller may not read is no chain node: it reads as an
+ // unknown id, and a walk never steps onto or through it.
+ const res = resolveChainTipInVault(ctx.vault, id, reachOpt);
return {
action,
tip: res.tip,
@@ -125,11 +133,19 @@ async function toolBrainLifecycle(
case "curator": {
const highUseMin = coerceNonNegativeInteger(TOOL, "high_use_min", args["high_use_min"]);
const slices = curatorSlices(ctx.vault, highUseMin !== undefined ? { highUseMin } : {});
+ // A row's key is the page path or the memory id; a row naming a
+ // page the caller may not see is left out.
+ const view = everyArtifactRefView(
+ gatedOwnerScopeView(ctx.vault, ctx.agentName),
+ reachView(ctx.vault, contextReach(ctx)),
+ );
+ const rows = (entries: ReadonlyArray<CuratorEntry>) =>
+ renderCuratorRows(view.keep(entries, (e) => [e.key]));
return {
action,
- injected_never_used: renderCuratorRows(slices.injectedNeverUsed),
- contradicted: renderCuratorRows(slices.contradicted),
- high_used: renderCuratorRows(slices.highUsed),
+ injected_never_used: rows(slices.injectedNeverUsed),
+ contradicted: rows(slices.contradicted),
+ high_used: rows(slices.highUsed),
};
}
default:
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index a5504ba4..8f52bf22 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -27,8 +27,10 @@ import { assessRecallAdequacy } from "../../core/brain/recall-adequacy.ts";
import { recordRecallAdequacyDemand } from "../../core/brain/query-demand.ts";
import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";
import {
+ buildReaderAnticipatoryContext,
readAnticipatoryContext,
refreshAnticipatoryCache,
+ type ReadAnticipatoryContextResult,
} from "../../core/brain/anticipatory-cache.ts";
import { loadBrainConfig } from "../../core/brain/policy.ts";
import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";
@@ -38,10 +40,15 @@ import {
getContextReceipt,
isContextReceiptTrigger,
listContextReceipts,
+ RECEIPT_ITEM_ACTIVE_BODY,
+ RECEIPT_ITEM_LESSONS_BODY,
+ RECEIPT_ITEM_SCOPED_RULES,
+ RECEIPT_ITEM_STANDING_RULES,
summarizeContextReceipt,
summarizeContextReceiptSession,
type ContextReceiptOptions,
} from "../../core/brain/context-receipts.ts";
+import type { ContinuityRecord } from "../../core/brain/continuity/types.ts";
import { observedReuseRates } from "../../core/brain/observed-use.ts";
import {
diffContextPreset,
@@ -347,13 +354,17 @@ async function toolBrainContextReceipts(
const host = optionalStringArg("brain_context_receipts", args, "host");
const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");
const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);
+ const local = contextReach(ctx) === TRANSPORT_REACH.local;
const receipts = listContextReceipts(ctx.vault, {
...(trigger !== undefined ? { trigger } : {}),
...(host !== undefined ? { host } : {}),
...(sessionId !== undefined ? { sessionId } : {}),
...(limit !== undefined ? { limit } : {}),
+ ...(local ? {} : { exclude: isRuleOnlyInjection }),
});
- const summaries = receipts.map(summarizeContextReceipt);
+ const summaries = receipts
+ .map((receipt) => receiptAtReach(receipt, local))
+ .map(summarizeContextReceipt);
return {
vault_path: vaultPathField(ctx),
total: summaries.length,
@@ -366,10 +377,14 @@ async function toolBrainContextReceipts(
if (id === undefined) {
throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");
}
- const receipt = getContextReceipt(ctx.vault, id);
- if (receipt === null) {
+ const local = contextReach(ctx) === TRANSPORT_REACH.local;
+ const stored = getContextReceipt(ctx.vault, id);
+ // Below local reach a receipt that recorded only the operator rules
+ // is answered as an unknown id: showing it would say rules applied.
+ if (stored === null || (!local && isRuleOnlyInjection(stored))) {
throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);
}
+ const receipt = receiptAtReach(stored, local);
return {
id: receipt.id,
kind: receipt.kind,
@@ -386,6 +401,104 @@ async function toolBrainContextReceipts(
throw unknownOperationError("brain_context_receipts: operation must be list, show, or summary");
}
+/** Predicate: a receipt item whose `id` is one of `ids`. */
+const itemIdIn =
+ (ids: ReadonlySet<string>) =>
+ (item: unknown): boolean => {
+ const id = (item as { id?: unknown } | null)?.id;
+ return typeof id === "string" && ids.has(id);
+ };
+
+/** Receipt items naming the operator-rule blocks the SessionStart hook injected. */
+const OPERATOR_RULE_ITEM_IDS: ReadonlySet<string> = new Set([
+ RECEIPT_ITEM_STANDING_RULES,
+ RECEIPT_ITEM_SCOPED_RULES,
+]);
+
+const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);
+
+/**
+ * A measured injection receipt whose every item was an operator-rule
+ * block: the hook recorded it only because rules applied (a session with
+ * no `active.md` body to inject). Below local reach it
+ * is withheld whole - left out of list and summary, refused by show -
+ * since even its empty remainder would say that rules applied.
+ */
+function isRuleOnlyInjection(record: ContinuityRecord): boolean {
+ if (record.payload["trigger"] !== "session_inject") return false;
+ // A degraded injection that served a cached body beside the rules is
+ // recorded whether or not rules applied: it stays, emptied of them. One
+ // with no cached body (`loader_source: "empty"`) exists only because the
+ // rules were injected, so it is rule-only like a measured one.
+ const injection = record.payload["injection"] as
+ | { sources_measured?: unknown; loader_source?: unknown }
+ | undefined;
+ if (injection?.sources_measured === false && injection.loader_source !== "empty") return false;
+ const items = record.payload["items"];
+ return Array.isArray(items) && items.length > 0 && items.every(isOperatorRuleItem);
+}
+
+/** Receipt items charged against the injection budget besides the scoped rules. */
+const BUDGETED_BODY_ITEM_IDS: ReadonlySet<string> = new Set([
+ RECEIPT_ITEM_ACTIVE_BODY,
+ RECEIPT_ITEM_LESSONS_BODY,
+]);
+
+const isBudgetedBodyItem = itemIdIn(BUDGETED_BODY_ITEM_IDS);
+
+/** Payload fields of an injection receipt whose figures include the operator-rule blocks. */
+const INJECTION_TOTAL_FIELDS = ["final_text_hash", "final_text_chars"] as const;
+const INJECTION_EXTRA_TOTAL_FIELDS = ["total_bytes", "total_tokens"] as const;
+const BUDGET_RULE_FIELDS = ["scoped_rules_chars", "budgeted_source_count"] as const;
+
+/**
+ * A stored receipt as the caller may see it at its reach.
+ *
+ * At local reach the record is returned unchanged. Below it, an injection
+ * receipt says nothing about the operator's standing and scoped rules:
+ * their items and source references are dropped (the remaining items
+ * re-ranked), and every figure that counts or measures them - the item
+ * count, the whole-text hash and lengths, the scoped characters and the
+ * budgeted source count - is removed, so a session that injected rules
+ * answers like one that did not.
+ */
+function receiptAtReach(record: ContinuityRecord, local: boolean): ContinuityRecord {
+ if (local || record.payload["trigger"] !== "session_inject") return record;
+ const payload: Record<string, unknown> = { ...record.payload };
+ if (Array.isArray(payload["items"])) {
+ const items = (payload["items"] as ReadonlyArray<unknown>).filter(
+ (item) => !isOperatorRuleItem(item),
+ );
+ payload["items"] = items.map((item, index) =>
+ typeof item === "object" && item !== null ? { ...item, original_rank: index + 1 } : item,
+ );
+ payload["item_count"] = items.length;
+ }
+ for (const field of INJECTION_TOTAL_FIELDS) delete payload[field];
+ const injection = payload["injection"];
+ if (typeof injection === "object" && injection !== null) {
+ const kept: Record<string, unknown> = { ...(injection as Record<string, unknown>) };
+ for (const field of INJECTION_EXTRA_TOTAL_FIELDS) delete kept[field];
+ payload["injection"] = kept;
+ }
+ const budget = payload["budget"];
+ const remaining = Array.isArray(payload["items"]) ? (payload["items"] as unknown[]) : [];
+ if (!remaining.some(isBudgetedBodyItem)) {
+ // The block exists only because the scoped rules were charged: with
+ // no budgeted body left, a receipt without the rules carries none.
+ delete payload["budget"];
+ } else if (typeof budget === "object" && budget !== null) {
+ const kept: Record<string, unknown> = { ...(budget as Record<string, unknown>) };
+ for (const field of BUDGET_RULE_FIELDS) delete kept[field];
+ payload["budget"] = kept;
+ }
+ return {
+ ...record,
+ sourceRefs: record.sourceRefs.filter((ref) => !isOperatorRuleItem(ref)),
+ payload,
+ };
+}
+
/**
* Session-scoped retrieval report (context-integrity-gates, Unit I): a
* read-only fold over receipts that already exist, joined to the
@@ -442,9 +555,13 @@ async function summarizeReceipts(
...(since !== undefined ? { since } : {}),
...(until !== undefined ? { until } : {}),
};
+ const local = contextReach(ctx) === TRANSPORT_REACH.local;
const fold = summarizeContextReceiptSession(ctx.vault, {
...window,
...(maxReceipts !== undefined ? { maxReceipts } : {}),
+ // Below local reach the operator-rule items leave the item figures,
+ // and a receipt that recorded nothing else is not folded at all.
+ ...(local ? {} : { exclude: isRuleOnlyInjection, excludeItem: isOperatorRuleItem }),
});
if (!fold.recorded) {
return {
@@ -743,6 +860,26 @@ async function toolBrainAnticipatoryContext(
}
const anticipatoryScope = coerceAgentScope(ctx, args, true);
const now = new Date();
+ // Below local reach the bundle is built for this caller with the same
+ // candidate filter `brain_context_pack` applies, and the shared cache is
+ // neither read nor written: a cached bundle may hold pages this caller
+ // cannot read, and a filtered bundle must not replace the operator's.
+ const view = reachView(ctx.vault, contextReach(ctx));
+ const remote = view.reach !== TRANSPORT_REACH.local;
+ if (remote) {
+ // A refresh takes the caller's signal exactly as the cached path does;
+ // a plain read has no cached signal to reuse here.
+ const signal = coerceBool(args, "refresh") === true ? coerceStr(args, "signal_text") : null;
+ const result = buildReaderAnticipatoryContext(ctx.vault, {
+ sessionId,
+ now,
+ visible: (abs: string) => view.visible(vaultRelative(ctx.vault, abs)),
+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
+ ...(typeof signal === "string" ? { signalText: signal } : {}),
+ });
+ return anticipatoryAnswer(result);
+ }
if (coerceBool(args, "refresh") === true) {
const signal = coerceStr(args, "signal_text");
refreshAnticipatoryCache(ctx.vault, {
@@ -761,6 +898,10 @@ async function toolBrainAnticipatoryContext(
...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
});
+ return anticipatoryAnswer(result);
+}
+
+function anticipatoryAnswer(result: ReadAnticipatoryContextResult): Record<string, unknown> {
return {
cache_state: result.cache_state,
root_session_id: result.root_session_id,
diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.ts
index c7772df1..b4ea289e 100644
--- a/src/mcp/brain/review-tools.ts
+++ b/src/mcp/brain/review-tools.ts
@@ -11,31 +11,47 @@ import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
import { findStaleEntries } from "../../core/brain/temporal/stale-watch.ts";
import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";
import { buildIntentReview } from "../../core/brain/intent-review.ts";
-import { buildRetentionReview } from "../../core/brain/retention.ts";
+import { buildRetentionReview, summarizeRetention } from "../../core/brain/retention.ts";
import { buildReviewCandidates } from "../../core/brain/review-candidates.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
+import { everyArtifactRefView, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
+import { reachView } from "../../core/brain/reach-view.ts";
import { brainArtifactSlug } from "../../core/brain/wikilink.ts";
import { OPERATION } from "../../core/brain/safeguard.ts";
import type { ProgressSink } from "../../core/brain/progress.ts";
-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";
import { vaultPathField } from "../vault-path-field.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { coerceIsoDate } from "../coerce.ts";
import { toolSafeguard } from "./shared.ts";
+/**
+ * What this caller may see over the ids and paths a review row names:
+ * the gated owner view ANDed with the reach view, so below local reach a
+ * record the caller cannot read is named by no row, exactly as an absent
+ * one is (a-label-is-not-a-boundary, U3).
+ */
+function reviewView(ctx: ServerContext): ArtifactRefView {
+ return everyArtifactRefView(
+ gatedOwnerScopeView(ctx.vault, ctx.agentName),
+ reachView(ctx.vault, contextReach(ctx)),
+ );
+}
+
async function toolBrainIntentReview(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const nowDate = coerceIsoDate(args, "now");
- const report = buildIntentReview(ctx.vault, nowDate ? { now: nowDate } : {});
- // Deliberately unfiltered, and the reason is on the record rather than
- // implied by silence (a-label-is-not-a-boundary, U3). Every row here is
- // a fold over INBOX SIGNAL clusters - a topic, a decision, a count -
- // and a signal carries no `owner:` anywhere in this product, so there
- // is no ownership claim on disk for this surface to read. A filter
- // keyed on "does a preference of this topic exist and may you see it"
- // would withhold a row whose whole content came from artifacts the
- // caller is entitled to, which is a narrowing nobody asked for.
+ // Every row is a fold over inbox signal clusters - a topic, a decision,
+ // a count - so below local reach the fold runs over the signals and
+ // rejected retired records the caller may read only, and a withheld one
+ // moves no topic, count or decision (a-label-is-not-a-boundary, U3).
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const report = buildIntentReview(ctx.vault, {
+ ...(nowDate ? { now: nowDate } : {}),
+ ...(readable !== undefined ? { readable } : {}),
+ });
return {
schema_version: report.schema_version,
generated_at: report.generated_at,
@@ -57,21 +73,22 @@ async function toolBrainRetention(
const nowDate = coerceIsoDate(args, "now");
const report = buildRetentionReview(ctx.vault, nowDate ? { now: nowDate } : {});
// Each recommendation names a retired preference or a processed signal
- // by id and by vault-relative path (a-label-is-not-a-boundary, U3).
- const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);
+ // by id and by vault-relative path (a-label-is-not-a-boundary, U3). The
+ // summary is counted again over the kept rows: a count of withheld ones
+ // would say they exist without naming them.
+ const view = reviewView(ctx);
+ const recommendations = view.keep(report.recommendations, (r) => [r.path, r.id]);
return {
schema_version: report.schema_version,
generated_at: report.generated_at,
- summary: report.summary,
- recommendations: view
- .keep(report.recommendations, (r) => [r.path, r.id])
- .map((recommendation) => ({
- id: recommendation.id,
- artifact_type: recommendation.artifact_type,
- action: recommendation.action,
- reason: recommendation.reason,
- path: recommendation.path,
- })),
+ summary: view.filtersNothing ? report.summary : summarizeRetention(recommendations),
+ recommendations: recommendations.map((recommendation) => ({
+ id: recommendation.id,
+ artifact_type: recommendation.artifact_type,
+ action: recommendation.action,
+ reason: recommendation.reason,
+ path: recommendation.path,
+ })),
};
}
@@ -93,7 +110,13 @@ async function toolBrainReviewCandidates(
} catch {
searchConfig = undefined;
}
+ // Below local reach the dry run plans over the records the caller may
+ // read only, so `clusters_below_threshold` and `intent_reviews` - folds
+ // over inbox signal clusters keyed by topic - count no withheld signal,
+ // and no withheld preference routes a cluster.
+ const readable = readableAtContextReachOrUndefined(ctx);
const report = await buildReviewCandidates(ctx.vault, {
+ ...(readable !== undefined ? { readable } : {}),
// The projection is read-only, but it runs a full dry-run
// consolidation pass to produce it - the same pass, and so the same
// budget, as `brain_dream`.
@@ -106,14 +129,11 @@ async function toolBrainReviewCandidates(
// get after the pass, so `ret-<slug>` is resolved back through the
// shared slug fold and both spellings are asked about
// (a-label-is-not-a-boundary, U3).
- const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);
+ const view = reviewView(ctx);
const bothSpellings = (id: string): ReadonlyArray<string> => {
const slug = brainArtifactSlug(id);
return [`pref-${slug}`, `ret-${slug}`];
};
- // `clusters_below_threshold` and `intent_reviews` stay unfiltered, for
- // the reason `brain_intent_review` states above: both are keyed by a
- // topic over inbox signals, and signals carry no owner.
return {
// Signal rows name an inbox signal by id AND by vault-relative path.
...(report.signal_novelty !== undefined
@@ -184,7 +204,7 @@ async function toolBrainStaleScan(
// Every stale row names its artifact by id, topic and vault-relative
// path (a-label-is-not-a-boundary, U3). Log shards are named by date
// and shared by construction, so they carry no ownership to read.
- const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);
+ const view = reviewView(ctx);
return {
vault_path: vaultPathField(ctx),
thresholds: report.thresholds,
diff --git a/src/mcp/brain/tension-tools.ts b/src/mcp/brain/tension-tools.ts
index a19763cb..420e10c4 100644
--- a/src/mcp/brain/tension-tools.ts
+++ b/src/mcp/brain/tension-tools.ts
@@ -30,10 +30,12 @@ import {
} from "../../core/brain/tensions.ts";
import { verifyTensions } from "../../core/brain/tension-verdicts.ts";
import { verdictFields } from "../../core/decision-model/pair-verdict.ts";
+import { vaultRelative } from "../../core/path-safety.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { coerceBool, coerceStr, unknownOperationError } from "../coerce.ts";
+import { readableAtContextReachOrUndefined, type ReadablePredicate } from "./reach-readable.ts";
import { wrapToolErrors } from "./shared.ts";
const TOOL = "brain_tension";
@@ -53,6 +55,36 @@ function renderRow(t: TensionRecord): Record<string, unknown> {
};
}
+/**
+ * May the caller read this tension page? The page carries the stricter
+ * `visibility:` of its two source notes, so the page's own rule is the
+ * notes' rule. `readable` undefined withholds nothing.
+ */
+function tensionReadable(
+ vault: string,
+ readable: ReadablePredicate | undefined,
+ t: TensionRecord,
+): boolean {
+ return readable === undefined || readable(vaultRelative(t.path, vault));
+}
+
+/**
+ * One tension by slug, or a typed `no tension` error when it is absent
+ * or withheld from the caller: the two answer alike, so the error does
+ * not confirm the page exists.
+ */
+function readableTension(
+ vault: string,
+ readable: ReadablePredicate | undefined,
+ slug: string,
+): TensionRecord {
+ const t = showTension(vault, slug);
+ if (t === null || !tensionReadable(vault, readable, t)) {
+ throw new TensionError(`no tension: ${slug}`);
+ }
+ return t;
+}
+
async function toolBrainTension(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -61,6 +93,13 @@ async function toolBrainTension(
const action = coerceStr(args, "action", true)!;
const agent = coerceStr(args, "agent", false) ?? undefined;
const reason = coerceStr(args, "reason", false) ?? undefined;
+ // Every action answers at the caller's reach: detect reads only the
+ // notes it may read, and a tension page it may not read is left out
+ // of list and verify and answered as absent by show and the
+ // transitions, before anything is written.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const visible = (rows: ReadonlyArray<TensionRecord>): TensionRecord[] =>
+ rows.filter((t) => tensionReadable(ctx.vault, readable, t));
switch (action) {
case "detect":
@@ -79,6 +118,7 @@ async function toolBrainTension(
const res = detectTensionsInVault(ctx.vault, {
...(jaccard !== undefined ? { jaccard } : {}),
...(agent ? { agent } : {}),
+ ...(readable !== undefined ? { readable } : {}),
});
return {
action,
@@ -91,12 +131,11 @@ async function toolBrainTension(
case "list": {
const unresolved = coerceBool(args, "unresolved");
const rows = unresolved ? listUnresolvedTensions(ctx.vault) : listTensions(ctx.vault);
- return { action, tensions: rows.map(renderRow) };
+ return { action, tensions: visible(rows).map(renderRow) };
}
case "show": {
const slug = coerceStr(args, "slug", true)!;
- const t = showTension(ctx.vault, slug);
- if (t === null) throw new TensionError(`no tension: ${slug}`);
+ const t = readableTension(ctx.vault, readable, slug);
return {
action,
...renderRow(t),
@@ -123,6 +162,7 @@ async function toolBrainTension(
: action === "dismiss"
? dismissTension
: resolveTension;
+ readableTension(ctx.vault, readable, slug);
const t = fn(ctx.vault, slug, opts);
return { action, ...renderRow(t) };
}
@@ -130,11 +170,9 @@ async function toolBrainTension(
const slug = coerceStr(args, "slug", false);
let records: TensionRecord[];
if (slug) {
- const t = showTension(ctx.vault, slug);
- if (t === null) throw new TensionError(`no tension: ${slug}`);
- records = [t];
+ records = [readableTension(ctx.vault, readable, slug)];
} else {
- records = listUnresolvedTensions(ctx.vault);
+ records = visible(listUnresolvedTensions(ctx.vault));
}
const verified = await verifyTensions(ctx.vault, records, { configPath: ctx.configPath });
return {
diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.ts
index 74021c6f..87d856a8 100644
--- a/src/mcp/brain/workspace-tools.ts
+++ b/src/mcp/brain/workspace-tools.ts
@@ -19,6 +19,8 @@ import {
parseWikilinkRich,
} from "../../core/brain/link-graph/parse-wikilink.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";
+import { reachView } from "../../core/brain/reach-view.ts";
import {
isTriggerStatus,
TRIGGER_STATUSES,
@@ -26,14 +28,19 @@ import {
type TriggerRecord,
} from "../../core/brain/triggers/types.ts";
import {
+ intentionRel,
+ intentionStemRel,
listIntentions,
moveIntentionToHistory,
+ noActiveIntentionError,
setIntention,
showIntention,
} from "../../core/brain/intentions.ts";
+import { resolveSessionScope } from "../../core/brain/session-scope.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { TOOL_ERROR_CODE } from "../tool-error-codes.ts";
-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";
+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coerceStr, unknownOperationError } from "../coerce.ts";
@@ -42,9 +49,19 @@ function toolBrainIntention(
args: Record<string, unknown>,
): Record<string, unknown> {
const operation = coerceStr(args, "operation", true)!;
+ // Every operation answers at the caller's reach: a chain the caller may
+ // not read is listed, shown and moved exactly as an absent one would be,
+ // so neither its text nor its existence crosses, and it is never
+ // written. `undefined` at local reach with the owner gate off.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const withheld = (scope: string): boolean =>
+ readable !== undefined && !readable(intentionRel(scope));
if (operation === "list") {
+ const chains = listIntentions(ctx.vault);
+ const kept =
+ readable === undefined ? chains : chains.filter((c) => readable(intentionStemRel(c.scope)));
return {
- intentions: listIntentions(ctx.vault).map((chain) => ({
+ intentions: kept.map((chain) => ({
scope: chain.scope,
version: chain.version,
updated_at: chain.updatedAt,
@@ -55,6 +72,15 @@ function toolBrainIntention(
const scope = coerceStr(args, "scope", true)!;
if (operation === "set") {
const text = coerceStr(args, "text", true)!;
+ // Setting folds the prior text into the new version's history, so an
+ // existing withheld chain is refused rather than read and rewritten.
+ // The refusal is the one answer that cannot match an absent chain's.
+ if (withheld(scope) && showIntention(ctx.vault, scope) !== null) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_intention: cannot set scope: ${resolveSessionScope(scope)}`,
+ );
+ }
const chain = setIntention(ctx.vault, {
scope,
text,
@@ -63,7 +89,7 @@ function toolBrainIntention(
return { operation, scope: chain.scope, version: chain.version, path: chain.path };
}
if (operation === "show") {
- const chain = showIntention(ctx.vault, scope);
+ const chain = withheld(scope) ? null : showIntention(ctx.vault, scope);
if (chain === null) return { operation, scope, present: false };
return {
operation,
@@ -77,7 +103,11 @@ function toolBrainIntention(
};
}
if (operation === "move") {
+ if (withheld(scope)) throw noActiveIntentionError(resolveSessionScope(scope));
const moved = moveIntentionToHistory(ctx.vault, { scope });
+ // The archive name steps past every name already taken in history/,
+ // readable or not, so below local reach it is left out of the answer.
+ if (readable !== undefined) return { operation, scope: moved.scope };
return { operation, scope: moved.scope, archive_path: moved.archivePath };
}
throw unknownOperationError("brain_intention operation must be one of: set, show, list, move");
@@ -158,11 +188,24 @@ function toolBrainTrigger(
// A trigger row is dropped WHOLE when any artifact it names is
// withheld: `reason` and `cooldown_key` repeat the same ids the
// `source_artifacts` list holds, so trimming the list alone would
- // leave the prose naming what the list no longer does.
- const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);
+ // leave the prose naming what the list no longer does. The reach view
+ // joins the owner view: below local reach a trigger naming a record
+ // the caller cannot read answers as an absent one.
+ const view = everyArtifactRefView(
+ gatedOwnerScopeView(ctx.vault, ctx.agentName),
+ reachView(ctx.vault, contextReach(ctx)),
+ );
if (operation === "scan") {
const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);
- const result = scanTriggers(ctx.vault, { now, cooldownDays });
+ // The sources run over the records this caller may read, so the
+ // `candidates` total counts none it may not, and a scan from a remote
+ // caller writes no trigger about a withheld record.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const result = scanTriggers(ctx.vault, {
+ now,
+ cooldownDays,
+ ...(readable !== undefined ? { readable } : {}),
+ });
return {
operation,
candidates: result.candidates,
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 44e79e33..6a59a90a 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -49,6 +49,7 @@ import { PROGRESS_REASON, type ProgressSink } from "../core/brain/progress.ts";
import { listResources, listResourceTemplates, readResource } from "./resources.ts";
import { buildToolTable, findTool } from "./tools.ts";
import type {
+ RuleScopeSources,
ServerContext,
ToolCapabilityReport,
ToolDefinition,
@@ -60,6 +61,8 @@ import { applyPreviewBudget } from "./preview-budget.ts";
import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "./capabilities.ts";
import { redactErrorForCaller } from "./error-redaction.ts";
import type { InstallTargetId } from "../core/runtime/host-facts.ts";
+import type { HarnessId } from "../core/brain/scoped-rules.ts";
+import { resolveHarnessScope } from "../core/brain/scope-identity.ts";
import {
resolvedTransportReach,
TRANSPORT_REACH,
@@ -86,6 +89,19 @@ export interface MCPServerRuntimeOptions {
* ceiling; absent means the ceiling is reported as unchecked.
*/
readonly hostTarget?: InstallTargetId;
+ /**
+ * The harness that launched this process, from `o2b mcp --harness` in a
+ * packaged registration. Only the scoped standing rules read it, to pick
+ * `Brain/standing-rules/harness/<id>.md`; absent falls back to
+ * {@link hostTarget}, since every install target is a harness.
+ */
+ readonly harness?: HarnessId;
+ /**
+ * The working directory this process was launched in, captured once by
+ * the CLI. The scoped standing rules resolve the project from the
+ * nearest vault pointer above it; absent means no project.
+ */
+ readonly workspaceDir?: string;
/**
* Run id grouping this process's preview artifacts under
* `Brain/.artifacts/<run-id>/`. Defaults to a per-process id;
@@ -168,6 +184,8 @@ export class MCPServer {
private readonly sendNotification: ((notification: JsonRpcNotification) => void) | undefined;
/** See {@link MCPServerRuntimeOptions.reach}; fail-closed when unminted. */
readonly reach: TransportReach;
+ /** Launch-time scope sources for the scoped standing rules. */
+ private readonly ruleScope: RuleScopeSources;
constructor(opts: MCPServerOptions, runtimeOpts: MCPServerRuntimeOptions = {}) {
this.vault = opts.vault;
@@ -186,6 +204,10 @@ export class MCPServer {
this.routeMetricsEnabled = routeMetricsGate(this.configPath ?? undefined);
this.sendNotification = runtimeOpts.sendNotification;
this.reach = resolvedTransportReach(runtimeOpts.reach);
+ this.ruleScope = Object.freeze({
+ workspaceDir: runtimeOpts.workspaceDir ?? null,
+ harness: resolveHarnessScope(runtimeOpts.harness, runtimeOpts.hostTarget),
+ });
const runId = runtimeOpts.artifactRunId ?? `run-${process.pid}-${Date.now().toString(36)}`;
this.artifactStore = new ArtifactStore({ vault: this.vault, runId });
// Best-effort housekeeping: clear prior processes' stale artifacts.
@@ -206,6 +228,7 @@ export class MCPServer {
capabilityReport: this.capabilityReport,
artifactStore: this.artifactStore,
reach: this.reach,
+ ruleScope: this.ruleScope,
// Owner-scope isolation (context-integrity-gates, Unit A): the
// only source of identity for `brain_context`, which takes no
// arguments. Resolved per access, like `resolveAgentName`'s other
diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.ts
index 1f08a74f..e1ef2325 100644
--- a/src/mcp/tool-contract.ts
+++ b/src/mcp/tool-contract.ts
@@ -17,6 +17,7 @@ import type { OutputSchema } from "./output-contract.ts";
import type { ArtifactStore } from "./artifact-store.ts";
import type { ProgressSink } from "../core/brain/progress.ts";
import type { ToolCeilingKind } from "../core/runtime/host-facts.ts";
+import type { HarnessId } from "../core/brain/scoped-rules.ts";
/**
* The tool surfaces a server process can advertise.
@@ -108,6 +109,23 @@ export interface ToolCapabilityReport {
readonly withheld: ToolCapabilityEntry[];
}
+/**
+ * The launch-time facts the scoped standing rules resolve their scope
+ * from (`src/core/brain/scope-identity.ts`), fixed per server process.
+ *
+ * Both are owned by whoever STARTED the process - the working directory
+ * it was started in and the `--harness` (or `--host-target`) its packaged
+ * registration names - and neither can be named by a caller: no tool
+ * takes a harness or a workspace argument, and
+ * `tests/core/architecture/harness-identity-census.test.ts` keeps it so.
+ */
+export interface RuleScopeSources {
+ /** The process working directory captured at launch; `null` when none was given. */
+ readonly workspaceDir: string | null;
+ /** `--harness`, else `--host-target`, else `null`. */
+ readonly harness: HarnessId | null;
+}
+
export interface ServerContext {
readonly vault: string;
readonly configPath: string | null;
@@ -149,6 +167,12 @@ export interface ServerContext {
* Optional so a manually-built context stays valid and unscoped.
*/
readonly agentName?: string;
+ /**
+ * Where the scoped standing rules look for their scope. Optional so a
+ * manually-built context stays valid; absent resolves no project and
+ * no harness, so a hand-built context matches no scoped file.
+ */
+ readonly ruleScope?: RuleScopeSources;
}
export interface ToolDefinition {
diff --git a/tests/cli/brain-dream-operator-surface.test.ts b/tests/cli/brain-dream-operator-surface.test.ts
index 30285083..08c3e007 100644
--- a/tests/cli/brain-dream-operator-surface.test.ts
+++ b/tests/cli/brain-dream-operator-surface.test.ts
@@ -35,6 +35,7 @@ import { writeSignal } from "../../src/core/brain/signal.ts";
import { BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
import { DREAM_PHASE } from "../../src/core/brain/dream-phases.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { cmdBrainDream } from "../../src/cli/brain/verbs/dream.ts";
import { runCli } from "../helpers/run-cli.ts";
@@ -105,7 +106,8 @@ function makeLinkableNotes(): string {
}
async function makeServer(): Promise<MCPServer> {
- const server = new MCPServer({ vault, configPath });
+ // A real dream pass and a single step run at local reach only.
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
diff --git a/tests/cli/mcp-harness-flag.test.ts b/tests/cli/mcp-harness-flag.test.ts
new file mode 100644
index 00000000..836f9549
--- /dev/null
+++ b/tests/cli/mcp-harness-flag.test.ts
@@ -0,0 +1,195 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { HARNESS_IDS } from "../../src/core/brain/scoped-rules.ts";
+import { writeVaultPointer } from "../../src/core/brain/portability/pointer.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+import { homeEnv } from "../helpers/platform.ts";
+import { waitForSelfHealChildren } from "../helpers/self-heal-children.ts";
+import { tempDirs } from "../helpers/temp-dir.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+/** Whole tokens: `copilot-cli` contains `pi`, so containment over ids lies. */
+function tokensOf(text: string): ReadonlySet<string> {
+ return new Set(text.split(/[^A-Za-z0-9_-]+/).filter((token) => token.length > 0));
+}
+
+describe("o2b mcp --harness", () => {
+ test("an unknown harness exits 2 with the pinned message listing every harness", async () => {
+ const res = await runCli(["mcp", "--harness", "nope"], { stdin: "" });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toBe(
+ `o2b mcp: invalid --harness value: "nope"; expected one of: ${HARNESS_IDS.join(", ")}\n`,
+ );
+ const offered = tokensOf(res.stderr);
+ for (const id of HARNESS_IDS) {
+ expect(`${id} offered: ${offered.has(id)}`).toBe(`${id} offered: true`);
+ }
+ });
+
+ test("a refused value is echoed JSON-quoted, control characters escaped", async () => {
+ // A C0 escape, a newline and the 8-bit CSI (a C1 control).
+ const value = "x\u001b[31my\nz\u009b1mw";
+ const quoted = '"x\\u001b[31my\\nz\\u009b1mw"';
+ const flags = ["--harness", "--host-target"];
+ const results = await Promise.all(
+ flags.map((flag) => runCli(["mcp", flag, value], { stdin: "" })),
+ );
+ for (const [i, flag] of flags.entries()) {
+ const res = results[i]!;
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toStartWith(`o2b mcp: invalid ${flag} value: ${quoted}; `);
+ expect(res.stderr).not.toContain("\u001b");
+ expect(res.stderr).not.toContain("\u009b");
+ expect(res.stderr.split("\n").length).toBe(2);
+ }
+ });
+
+ test("an install-target value is a valid harness", async () => {
+ const tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-harness-"));
+ try {
+ const res = await runCli(["mcp", "--probe", "--harness", "cursor"], {
+ stdin: "",
+ env: { VAULT_DIR: tmp },
+ });
+ expect(res.stderr).toBe("");
+ expect(res.returncode).toBe(0);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test("a known harness is accepted by the server start path", async () => {
+ const tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-harness-"));
+ try {
+ const res = await runCli(["mcp", "--probe", "--harness", "claude-code"], {
+ stdin: "",
+ env: { VAULT_DIR: tmp },
+ });
+ expect(res.stderr).toBe("");
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("mcp probe ok");
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("ServerContext.ruleScope", () => {
+ let vault: string;
+ let workspace: string;
+ beforeAll(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-rule-scope-vault-"));
+ workspace = mkdtempSync(join(tmpdir(), "o2b-rule-scope-ws-"));
+ });
+ afterAll(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(workspace, { recursive: true, force: true });
+ });
+
+ test("an explicit harness and workspace directory reach the context", () => {
+ const server = new MCPServer({ vault }, { harness: "codex", workspaceDir: workspace });
+ expect(server.context.ruleScope).toEqual({ workspaceDir: workspace, harness: "codex" });
+ });
+
+ test("the harness wins over the host target", () => {
+ const server = new MCPServer({ vault }, { harness: "claude-code", hostTarget: "cursor" });
+ expect(server.context.ruleScope?.harness).toBe("claude-code");
+ });
+
+ test("the host target is the fallback harness", () => {
+ const server = new MCPServer({ vault }, { hostTarget: "cursor" });
+ expect(server.context.ruleScope).toEqual({ workspaceDir: null, harness: "cursor" });
+ });
+
+ test("neither option resolves no harness and no workspace", () => {
+ const server = new MCPServer({ vault });
+ expect(server.context.ruleScope).toEqual({ workspaceDir: null, harness: null });
+ });
+});
+
+function frame(id: number | null, method: string, params: Record<string, unknown> = {}): string {
+ const body =
+ id === null ? { jsonrpc: "2.0", method, params } : { jsonrpc: "2.0", id, method, params };
+ return `${JSON.stringify(body)}\n`;
+}
+
+/**
+ * The launch options reach the served `brain_context` in a real stdio
+ * process: `--harness` (else `--host-target`) picks the harness file and
+ * the launch directory picks the project file. The in-process suites
+ * construct `MCPServer` directly and cannot see the CLI forwarding.
+ */
+describe("o2b mcp forwards the launch scope to brain_context", () => {
+ const mkTemp = tempDirs();
+ const CLI = join(import.meta.dir, "..", "..", "src", "cli", "main.ts");
+
+ async function servedContext(args: ReadonlyArray<string>): Promise<string> {
+ const root = mkTemp("o2b-mcp-harness-e2e-");
+ {
+ const vault = join(root, "vault");
+ const project = join(root, "proj-e2e");
+ const home = join(root, "home");
+ for (const dir of [join(vault, "Brain"), project, home]) mkdirSync(dir, { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ writeVaultPointer(project, vault);
+ for (const [axis, key] of [
+ ["harness", "cursor"],
+ ["project", "proj-e2e"],
+ ] as const) {
+ mkdirSync(join(vault, "Brain", "standing-rules", axis), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "standing-rules", axis, `${key}.md`),
+ `zz${axis}markerzz`,
+ );
+ }
+ const proc = Bun.spawn([process.execPath, CLI, "mcp", "--vault", vault, ...args], {
+ cwd: project,
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ ...(process.env["SYSTEMROOT"] ? { SYSTEMROOT: process.env["SYSTEMROOT"] } : {}),
+ ...homeEnv(home),
+ OPEN_SECOND_BRAIN_CONFIG: join(home, "config.yaml"),
+ O2B_DEVICE_ID: "",
+ },
+ });
+ proc.stdin.write(
+ frame(1, "initialize", {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "harness-e2e", version: "0" },
+ }) +
+ frame(null, "notifications/initialized") +
+ frame(9, "tools/call", { name: "brain_context", arguments: {} }),
+ );
+ await proc.stdin.end();
+ const stdout = await new Response(proc.stdout).text();
+ await proc.exited;
+ await waitForSelfHealChildren(vault);
+ const line = stdout.split("\n").find((l) => l.includes('"id":9'));
+ expect(line).toBeDefined();
+ const reply = JSON.parse(line ?? "{}") as {
+ result: { content: ReadonlyArray<{ text: string }> };
+ };
+ return reply.result.content[0]?.text ?? "";
+ }
+ }
+
+ test("--harness and the launch directory select their files", async () => {
+ const text = await servedContext(["--harness", "cursor"]);
+ expect(text).toContain("zzharnessmarkerzz");
+ expect(text).toContain("zzprojectmarkerzz");
+ });
+
+ test("--host-target is the harness when --harness is absent", async () => {
+ expect(await servedContext(["--host-target", "cursor"])).toContain("zzharnessmarkerzz");
+ });
+
+ test("no harness option matches no harness file", async () => {
+ expect(await servedContext([])).not.toContain("zzharnessmarkerzz");
+ });
+});
diff --git a/tests/core/architecture/harness-identity-census.test.ts b/tests/core/architecture/harness-identity-census.test.ts
new file mode 100644
index 00000000..bfdbdd9c
--- /dev/null
+++ b/tests/core/architecture/harness-identity-census.test.ts
@@ -0,0 +1,96 @@
+/**
+ * The harness a scoped rule matches is server-derived, and that is
+ * measured.
+ *
+ * The scoped standing rules render the file for the harness that
+ * LAUNCHED this server (`o2b mcp --harness`, written by the packager or
+ * installer, falling back to `--host-target`). A harness a caller could
+ * name in a tool argument would let any caller pick which operator rules
+ * it is shown, so no MCP tool input schema, in any tool scope or surface
+ * profile, may declare a property whose key spells it. The directory the layer lives in is also never advertised:
+ * a tool description naming it would point agents at a target every
+ * write path refuses.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { BRAIN_SCOPED_RULES_DIR } from "../../../src/core/brain/path-constants.ts";
+import { TOOL_SURFACE_PROFILES } from "../../../src/mcp/profiles.ts";
+import { TOOL_SCOPES, type ToolScope } from "../../../src/mcp/tool-contract.ts";
+import { buildToolTable } from "../../../src/mcp/tools.ts";
+
+/** Any property key spelling the harness, in any case or position. */
+function isHarnessKey(key: string): boolean {
+ return /harness/i.test(key);
+}
+
+/**
+ * Every live tool table a server can advertise: each tool scope, and the
+ * scope behind each named surface profile (a profile only narrows it).
+ */
+function liveToolTables(): ReadonlyArray<{ readonly label: string; readonly scope: ToolScope }> {
+ return [
+ ...TOOL_SCOPES.map((scope) => ({ label: `scope ${scope}`, scope })),
+ ...Object.entries(TOOL_SURFACE_PROFILES).map(([name, profile]) => ({
+ label: `profile ${name}`,
+ scope: profile.scope,
+ })),
+ ];
+}
+
+/** Every property key reachable from a JSON schema, with its path. */
+function schemaPropertyKeys(schema: unknown, path = ""): string[] {
+ if (typeof schema !== "object" || schema === null) return [];
+ const node = schema as Record<string, unknown>;
+ const out: string[] = [];
+ const properties = node["properties"];
+ if (typeof properties === "object" && properties !== null) {
+ for (const [key, value] of Object.entries(properties)) {
+ const here = path.length > 0 ? `${path}.${key}` : key;
+ out.push(here, ...schemaPropertyKeys(value, here));
+ }
+ }
+ for (const nested of ["items", "anyOf", "oneOf", "allOf"]) {
+ const value = node[nested];
+ if (Array.isArray(value)) {
+ for (const item of value) out.push(...schemaPropertyKeys(item, path));
+ } else {
+ out.push(...schemaPropertyKeys(value, path));
+ }
+ }
+ return out;
+}
+
+describe("no caller can name the harness", () => {
+ test("no live tool input schema declares a harness property in any scope or profile", () => {
+ const offenders: string[] = [];
+ for (const { label, scope } of liveToolTables()) {
+ for (const tool of buildToolTable(scope)) {
+ for (const keyPath of schemaPropertyKeys(tool.inputSchema)) {
+ const leaf = keyPath.split(".").at(-1) ?? keyPath;
+ if (isHarnessKey(leaf)) offenders.push(`${label}: ${tool.name}.${keyPath}`);
+ }
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test("the key check catches every spelling of the harness", () => {
+ for (const key of ["harness", "harness_id", "harnessId", "harness_name", "launch_harness"]) {
+ expect(isHarnessKey(key)).toBe(true);
+ }
+ expect(isHarnessKey("host_target")).toBe(false);
+ });
+
+ test("no tool description names the scoped rules directory", () => {
+ const needle = `${BRAIN_SCOPED_RULES_DIR}/`;
+ const offenders: string[] = [];
+ for (const tool of buildToolTable("full")) {
+ if (tool.name.includes(needle)) offenders.push(`${tool.name} (name)`);
+ if (tool.description.includes(needle)) offenders.push(`${tool.name} (description)`);
+ if (JSON.stringify(tool.inputSchema).includes(needle)) {
+ offenders.push(`${tool.name} (input schema)`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.ts
index e4f0b738..104d21f4 100644
--- a/tests/core/architecture/verdict-vocabulary-census.test.ts
+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts
@@ -413,6 +413,14 @@ import {
TOOL_CEILING_KINDS,
} from "../../../src/core/runtime/host-facts.ts";
import { CONFIG_ORIGIN, CONFIG_ORIGINS, isConfigOrigin } from "../../../src/core/validate.ts";
+import {
+ HARNESS_ID,
+ HARNESS_IDS,
+ isHarnessId,
+ isScopedRuleAxis,
+ SCOPED_RULE_AXES,
+ SCOPED_RULE_AXIS,
+} from "../../../src/core/brain/scoped-rules.ts";
import { EXPORT_FORMAT, EXPORT_FORMATS, isExportFormat } from "../../../src/core/brain/export.ts";
import {
isStateReachability,
@@ -1457,6 +1465,24 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: MANIFEST_STATUSES,
guard: isManifestStatus,
},
+ {
+ // The axis a scoped operator rule file is keyed on
+ // (`Brain/standing-rules/<axis>/<key>.md`). It reaches the
+ // `brain_context` output and orders the drop priority under the cap.
+ name: "SCOPED_RULE_AXIS",
+ values: SCOPED_RULE_AXIS,
+ members: SCOPED_RULE_AXES,
+ guard: isScopedRuleAxis,
+ },
+ {
+ // The runtimes `o2b mcp --harness` can name: every install target
+ // plus the three runtimes with no install adapter. Kept apart from
+ // INSTALL_TARGET_ID, which must equal the adapter registry.
+ name: "HARNESS_ID",
+ values: HARNESS_ID,
+ members: HARNESS_IDS,
+ guard: isHarnessId,
+ },
]);
// ---------------------------------------------------------------------------
@@ -1721,7 +1747,7 @@ const SCANNED = scanVocabularies(SOURCE_TREE);
* How many four-piece vocabularies `src/` currently holds. Measured, and
* kept as an equality rather than a floor - see the population test.
*/
-const VOCABULARY_POPULATION = 88;
+const VOCABULARY_POPULATION = 90;
const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));
describe("verdict vocabulary census", () => {
diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.ts
index c96b3f39..e5604a6a 100644
--- a/tests/core/architecture/visibility-surface-census.test.ts
+++ b/tests/core/architecture/visibility-surface-census.test.ts
@@ -276,10 +276,73 @@ const NOTE_CONTENT_PRODUCERS: ReadonlyArray<ProducerRule> = Object.freeze([
"allClaims",
],
},
+ // Obligation pages are vault pages the today view already filtered by
+ // reach while the tool that lists, shows and completes them did not.
+ {
+ specifierIncludes: "/brain/obligations.ts",
+ identifiers: ["listObligations", "showObligation"],
+ },
+ // The trigger scan folds semantic health and the retention review into
+ // queued triggers that name the records they fired on.
+ { specifierIncludes: "/brain/triggers/scan.ts", identifiers: ["scanTriggers"] },
+ // The lifecycle review readers name preferences and signals by id and
+ // vault-relative path.
+ { specifierIncludes: "/brain/temporal/stale-watch.ts", identifiers: ["findStaleEntries"] },
+ { specifierIncludes: "/brain/review-candidates.ts", identifiers: ["buildReviewCandidates"] },
+ { specifierIncludes: "/brain/retention.ts", identifiers: ["buildRetentionReview"] },
+ // A tension page quotes the two notes it pairs, the lifecycle writes
+ // and the expiration writer resolve a page or record by path or id and
+ // answer with it, and the curator rows name pages by path.
+ {
+ specifierIncludes: "/brain/tensions.ts",
+ identifiers: ["detectTensionsInVault", "listTensions", "showTension"],
+ },
+ {
+ specifierIncludes: "/brain/lifecycle/tombstone.ts",
+ identifiers: ["tombstone", "supersede", "buildChainLookup", "resolveChainTipInVault"],
+ },
+ { specifierIncludes: "/brain/lifecycle/temporal-replace.ts", identifiers: ["temporalReplace"] },
+ { specifierIncludes: "/brain/lifecycle/curator.ts", identifiers: ["curatorSlices"] },
+ { specifierIncludes: "/brain/expiration-set.ts", identifiers: ["setExpiration"] },
{
specifierIncludes: "/brain/truth/",
identifiers: ["computeTruthStateWithConflicts", "aggregateQuantities", "detectAgentCollisions"],
},
+ {
+ specifierIncludes: "/brain/decisions/record.ts",
+ identifiers: [
+ "showDecision",
+ "listDecisions",
+ "listRatedDecisions",
+ "compareDecisions",
+ "findSimilarDecisions",
+ "backfillOutcome",
+ "updateRating",
+ ],
+ },
+ { specifierIncludes: "/brain/decisions/recall.ts", identifiers: ["recallRatedDecisions"] },
+ {
+ specifierIncludes: "/brain/decisions/receipts.ts",
+ identifiers: ["queryDecisionChangeHistory"],
+ },
+ { specifierIncludes: "/brain/labels.ts", identifiers: ["assignNoteLabel", "removeNoteLabel"] },
+ {
+ specifierIncludes: "/brain/notes/scaffold-stub.ts",
+ identifiers: ["scaffoldStub", "listDanglingTargets"],
+ },
+ { specifierIncludes: "/brain/design-note.ts", identifiers: ["designNoteGrounding"] },
+ { specifierIncludes: "/brain/apply-evidence.ts", identifiers: ["appendApplyEvidence"] },
+ {
+ specifierIncludes: "/brain/write-advisory.ts",
+ identifiers: ["adviseIncomingFeedback", "adviseUnroutableCapture"],
+ },
+ { specifierIncludes: "/brain/derived-fact.ts", identifiers: ["deriveFact"] },
+ {
+ specifierIncludes: "/brain/anticipatory-cache.ts",
+ identifiers: ["readAnticipatoryContext", "buildReaderAnticipatoryContext"],
+ },
+ { specifierIncludes: "/brain/diarization.ts", identifiers: ["diarize"] },
+ { specifierIncludes: "/brain/recompile.ts", identifiers: ["planRecompile"] },
]);
/**
@@ -483,8 +546,36 @@ function reasonProblems(entries: ReadonlyArray<VisibilitySurfaceEntry>): {
* 55 before the vocabulary gained `buildConceptCluster`. The one new name
* is `brain_analytics`, whose timeline, belief-evolution and
* concept-synthesis views render log events and backlinks.
+ *
+ * 56 before the vocabulary gained the obligation readers. The two new
+ * names are `brain_obligation`, which listed and showed a withheld
+ * obligation page, and `brain_agenda` on the file-level rule.
+ *
+ * 58 before the vocabulary gained the trigger scan. The two new names
+ * are `brain_trigger`, whose scan queued and counted triggers about
+ * withheld records, and `brain_intention` on the file-level rule.
+ *
+ * 60 before the vocabulary gained the lifecycle review readers. The four
+ * new names are `brain_stale_scan`, `brain_review_candidates` and
+ * `brain_retention`, which named withheld preferences and signals by id
+ * and path, and `brain_intent_review` on the file-level rule.
+ *
+ * 64 before the vocabulary gained the tension, lifecycle and expiration
+ * producers. The eight new names are `brain_tension`, which paired and
+ * quoted withheld notes, `brain_lifecycle` and `brain_expire`, which
+ * wrote to withheld pages and records, and `brain_feedback`,
+ * `brain_apply_evidence`, `brain_dream`, `brain_note` and
+ * `brain_observed_use` on the file-level rule.
+ *
+ * 72 before the vocabulary gained the decision, label, scaffold, chain
+ * tip, design-note, evidence, advisory, derived-fact, anticipatory,
+ * diarization and recompile producers. The four new names are
+ * `brain_decision`, which showed and rewrote a withheld decision page,
+ * `brain_derive_fact` and `brain_scaffold_stub`, which accepted a
+ * withheld premise or source, and `brain_note_lifecycle` on the
+ * file-level rule.
*/
-const MCP_TOOL_POPULATION_SIZE = 56;
+const MCP_TOOL_POPULATION_SIZE = 76;
/** Measured: MCP resources + templates. */
const MCP_RESOURCE_POPULATION_SIZE = 8;
/** Measured: hand-enumerated CLI verb mirrors. */
@@ -544,27 +635,48 @@ describe("visibility surface census", () => {
expect(covered).toEqual([
"brain_agent_diff",
"brain_agent_query",
+ "brain_apply_evidence",
"brain_backlinks",
"brain_bridges",
"brain_claims",
"brain_clusters",
"brain_context",
+ "brain_dead_ends",
+ "brain_decision",
"brain_deep_synthesis",
+ "brain_derive_fact",
+ "brain_diarize",
"brain_doctor",
+ "brain_dream",
"brain_eval",
"brain_event_trace",
+ "brain_expire",
+ "brain_feedback",
"brain_file_context",
"brain_health",
"brain_hygiene",
"brain_idea_discovery",
+ "brain_intent_review",
+ "brain_intention",
+ "brain_labels",
+ "brain_lifecycle",
+ "brain_maintenance",
+ "brain_note_lifecycle",
+ "brain_obligation",
"brain_pre_compress_pack",
"brain_procedural_memory",
"brain_query",
"brain_recall_feedback",
+ "brain_retention",
+ "brain_review_candidates",
+ "brain_scaffold_stub",
"brain_search",
"brain_search_expand",
"brain_skill_proposals",
+ "brain_stale_scan",
+ "brain_tension",
"brain_tiers",
+ "brain_trigger",
"brain_unlinked_mentions",
"brain_writes",
"schema_inspect",
diff --git a/tests/core/brain.retention.test.ts b/tests/core/brain.retention.test.ts
index 31e71ef3..325719b4 100644
--- a/tests/core/brain.retention.test.ts
+++ b/tests/core/brain.retention.test.ts
@@ -4,7 +4,12 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
-import { preferencePath, processedSignalPath, signalPath } from "../../src/core/brain/paths.ts";
+import {
+ preferencePath,
+ processedSignalPath,
+ signalPath,
+ vaultRelative,
+} from "../../src/core/brain/paths.ts";
import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";
import { writeSignal } from "../../src/core/brain/signal.ts";
import { buildRetentionReview } from "../../src/core/brain/retention.ts";
@@ -81,5 +86,12 @@ describe("buildRetentionReview", () => {
expect(existsSync(processedSignal)).toBe(true);
expect(statSync(retired.path).mtimeMs).toBe(retiredMtimeBefore);
expect(statSync(processedSignal).mtimeMs).toBe(processedMtimeBefore);
+ expect(report.recommendations.map((r) => r.path)).toEqual([
+ vaultRelative(retired.path, vault),
+ vaultRelative(processedSignal, vault),
+ ]);
+ expect(report.recommendations[1]!.path).toBe(
+ "Brain/inbox/processed/sig-2026-04-01-discarded-signal.md",
+ );
});
});
diff --git a/tests/core/brain/config-template-ratchet.test.ts b/tests/core/brain/config-template-ratchet.test.ts
index 013f3d0c..3f709af0 100644
--- a/tests/core/brain/config-template-ratchet.test.ts
+++ b/tests/core/brain/config-template-ratchet.test.ts
@@ -57,6 +57,7 @@ import {
DEFAULT_ANTICIPATORY_MAX_TOKENS,
DEFAULT_ANTICIPATORY_TTL_SECONDS,
} from "../../../src/core/brain/anticipatory-cache.ts";
+import { SCOPED_RULES_MAX_CHARS_DEFAULT } from "../../../src/core/brain/scoped-rules.ts";
import type { BrainConfig } from "../../../src/core/brain/types.ts";
/**
@@ -149,6 +150,8 @@ function resolvedView(cfg: BrainConfig): Record<string, unknown> {
active_inject_budget_chars: cfg.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT,
active_standing_rules_max_chars:
cfg.active?.standing_rules_max_chars ?? STANDING_RULES_MAX_CHARS_DEFAULT,
+ active_scoped_rules_max_chars:
+ cfg.active?.scoped_rules_max_chars ?? SCOPED_RULES_MAX_CHARS_DEFAULT,
lessons: {
half_life_days: cfg.lessons?.half_life_days ?? LESSONS_HALF_LIFE_DAYS_DEFAULT,
corroboration_min: cfg.lessons?.corroboration_min ?? LESSONS_CORROBORATION_MIN_DEFAULT,
diff --git a/tests/core/brain/dream-drafted-visibility.test.ts b/tests/core/brain/dream-drafted-visibility.test.ts
new file mode 100644
index 00000000..b2974d83
--- /dev/null
+++ b/tests/core/brain/dream-drafted-visibility.test.ts
@@ -0,0 +1,216 @@
+/**
+ * A preference the dream pass drafts keeps the strictest visibility of the
+ * records it is drafted from.
+ *
+ * The pass copies a signal's principle into a new unconfirmed preference
+ * and, when it supersedes or rebuts a record, quotes that record's
+ * principle in the `supersedes` link. The new page must therefore be no
+ * more visible than any of them: drafted from a reserved signal it is
+ * reserved, from signals sharing a scope token it carries that token, and
+ * from default pages only it stays byte-identical to before (no
+ * `visibility` line). The last block runs the pass through the real
+ * MCPServer at local reach and then asks for the drafted preference at
+ * remote reach.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { dream } from "../../../src/core/brain/dream.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainConfigPath, preferencePath } from "../../../src/core/brain/paths.ts";
+import { moveToRetired, writePreference } from "../../../src/core/brain/preference.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { BRAIN_RETIRED_REASON } from "../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
+import {
+ pageVisibility,
+ REMOTE_DENY_VISIBILITY_TOKEN,
+} from "../../../src/core/graph/visibility.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+import { MCPServer } from "../../../src/mcp/server.ts";
+
+const NOW = new Date("2026-06-05T12:00:00Z");
+const SIGNAL_STAMP = "2026-06-01T10:00:00Z";
+const TOPIC = "release-notes";
+const PRINCIPLE = "Quote the private budget figure in every release note.";
+const TEAM = "team";
+
+let tmp: string;
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-visibility-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+interface Vault {
+ readonly vault: string;
+ readonly configPath: string;
+}
+
+function newVault(name: string): Vault {
+ const vault = join(tmp, name);
+ const configPath = join(tmp, `${name}.yaml`);
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ bootstrapBrain(vault, { configPath });
+ // Three agreeing signals draft a preference.
+ const yaml = readFileSync(brainConfigPath(vault), "utf8").replace(
+ /^ {2}candidate_threshold: \d+$/m,
+ " candidate_threshold: 3",
+ );
+ atomicWriteFileSync(brainConfigPath(vault), yaml);
+ return { vault, configPath };
+}
+
+/** Insert a `visibility:` line as the first frontmatter field of `path`. */
+function stampVisibility(path: string, tokens: ReadonlyArray<string>): void {
+ const text = readFileSync(path, "utf8");
+ atomicWriteFileSync(path, text.replace(/^---\n/, `---\nvisibility: [${tokens.join(", ")}]\n`));
+}
+
+function seed(
+ vault: string,
+ slug: string,
+ tokens: ReadonlyArray<string> = [],
+ stamp: string = SIGNAL_STAMP,
+): void {
+ const { path } = writeSignal(vault, {
+ topic: TOPIC,
+ signal: "positive",
+ agent: "claude",
+ principle: PRINCIPLE,
+ created_at: stamp,
+ date: stamp.slice(0, 10),
+ slug,
+ });
+ if (tokens.length > 0) stampVisibility(path, tokens);
+}
+
+function seedPreference(vault: string, slug: string): string {
+ const { path } = writePreference(vault, {
+ slug,
+ topic: TOPIC,
+ principle: "The rule of record for release notes.",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-15T00:00:00Z",
+ confirmed_at: "2026-05-08T00:00:00Z",
+ status: "confirmed",
+ evidenced_by: [],
+ applied_count: 2,
+ violated_count: 0,
+ last_evidence_at: "2026-06-01T00:00:00Z",
+ confidence: "medium",
+ });
+ return path;
+}
+
+/** Run a real pass and return the visibility tokens of the one drafted preference. */
+function draftedVisibility(vault: string): ReadonlyArray<string> {
+ const report = dream(vault, { now: NOW, agentName: "claude" });
+ expect(report.new_unconfirmed).toHaveLength(1);
+ const id = report.new_unconfirmed[0]!;
+ const path = preferencePath(vault, id.slice("pref-".length));
+ expect(readFileSync(path, "utf8")).toContain(PRINCIPLE);
+ return pageVisibility(parseFrontmatter(path)[0]);
+}
+
+describe("a drafted preference keeps its sources' strictest visibility", () => {
+ test("drafted from reserved signals, it is reserved", () => {
+ const { vault } = newVault("reserved");
+ for (const s of ["a", "b", "c"]) seed(vault, s, [REMOTE_DENY_VISIBILITY_TOKEN]);
+ expect(draftedVisibility(vault)).toEqual([REMOTE_DENY_VISIBILITY_TOKEN]);
+ });
+
+ test("one reserved signal in a mixed cluster reserves it", () => {
+ const { vault } = newVault("mixed");
+ seed(vault, "a");
+ seed(vault, "b", [TEAM]);
+ seed(vault, "c", [REMOTE_DENY_VISIBILITY_TOKEN]);
+ expect(draftedVisibility(vault)).toEqual([REMOTE_DENY_VISIBILITY_TOKEN]);
+ });
+
+ test("a scope token on one signal carries over beside default ones", () => {
+ const { vault } = newVault("scoped");
+ seed(vault, "a");
+ seed(vault, "b", [TEAM]);
+ seed(vault, "c");
+ expect(draftedVisibility(vault)).toEqual([TEAM]);
+ });
+
+ test("drafted from default signals only, it carries no visibility line", () => {
+ const { vault } = newVault("default");
+ for (const s of ["a", "b", "c"]) seed(vault, s);
+ const report = dream(vault, { now: NOW, agentName: "claude" });
+ const path = preferencePath(vault, report.new_unconfirmed[0]!.slice("pref-".length));
+ expect(readFileSync(path, "utf8")).not.toContain("visibility");
+ });
+
+ test("superseding a reserved retired record, it is reserved", () => {
+ const { vault } = newVault("supersede");
+ stampVisibility(seedPreference(vault, "old-notes"), [REMOTE_DENY_VISIBILITY_TOKEN]);
+ moveToRetired(vault, preferencePath(vault, "old-notes"), BRAIN_RETIRED_REASON.rebutted, {
+ now: new Date("2026-05-20T00:00:00Z"),
+ retired_by: "test",
+ evidenceApplied: [],
+ evidenceViolated: [],
+ });
+ for (const s of ["a", "b", "c"]) seed(vault, s);
+ expect(draftedVisibility(vault)).toEqual([REMOTE_DENY_VISIBILITY_TOKEN]);
+ });
+
+ test("rebutting a reserved preference, the drafted one is reserved", () => {
+ const { vault } = newVault("rebut");
+ stampVisibility(seedPreference(vault, "notes-rule"), [REMOTE_DENY_VISIBILITY_TOKEN]);
+ // No evidence resolves the active sign, so a unanimous batch reads as
+ // a rebuttal and drafts a `-rebut` preference that quotes the old one.
+ for (const s of ["a", "b", "c"]) seed(vault, s);
+ expect(draftedVisibility(vault)).toEqual([REMOTE_DENY_VISIBILITY_TOKEN]);
+ });
+});
+
+describe("through the MCP server", () => {
+ async function draftedOverMcp(tokens: ReadonlyArray<string>): Promise<{
+ readonly id: string;
+ readonly remote: string;
+ }> {
+ const v = newVault(tokens.length > 0 ? "mcp-reserved" : "mcp-default");
+ // The server's pass runs on the wall clock, so the signals are fresh.
+ const stamp = `${new Date().toISOString().slice(0, 19)}Z`;
+ for (const s of ["a", "b", "c"]) seed(v.vault, s, tokens, stamp);
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = v.configPath;
+ const config = { vault: v.vault, configPath: v.configPath };
+ const local = new MCPServer(config, { reach: TRANSPORT_REACH.local });
+ const run = await local.callTool("brain_dream", { action: "run" });
+ const drafted = (run["structuredContent"] ?? run) as { new_unconfirmed?: string[] };
+ const id = JSON.stringify(drafted).match(/pref-[a-z0-9-]+/)?.[0];
+ if (id === undefined) throw new Error(`the local pass drafted nothing: ${JSON.stringify(run)}`);
+ const remote = new MCPServer(config);
+ let answer: string;
+ try {
+ answer = JSON.stringify(await remote.callTool("brain_query", { preference: id }));
+ } catch (error) {
+ answer = (error as Error).message;
+ }
+ return { id, remote: answer };
+ }
+
+ test("a preference drafted locally from reserved signals is absent at remote reach", async () => {
+ const { id, remote } = await draftedOverMcp([REMOTE_DENY_VISIBILITY_TOKEN]);
+ expect(remote).not.toContain(PRINCIPLE);
+ expect(remote).toContain(`no preference or retired entry found for id '${id}'`);
+ });
+
+ test("control: drafted from default signals, a remote caller reads it", async () => {
+ const { remote } = await draftedOverMcp([]);
+ expect(remote).toContain(PRINCIPLE);
+ });
+});
diff --git a/tests/core/brain/governance-preview.test.ts b/tests/core/brain/governance-preview.test.ts
index ece90349..97fc57d3 100644
--- a/tests/core/brain/governance-preview.test.ts
+++ b/tests/core/brain/governance-preview.test.ts
@@ -48,6 +48,11 @@ describe("buildForgetPlan", () => {
true,
);
expect(plan.audit.contentIncluded).toBe(false);
+ expect(plan.entries.map((entry) => entry.path)).toEqual([
+ "Brain/inbox/sig-2026-05-31-one.md",
+ "Brain/preferences/pref-one.md",
+ "Brain/processed-archive/note.md",
+ ]);
});
});
diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.ts
index 37ec4662..1a161e89 100644
--- a/tests/core/brain/policy-active.test.ts
+++ b/tests/core/brain/policy-active.test.ts
@@ -4,7 +4,11 @@
import { describe, expect, test } from "bun:test";
import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
-import { BrainConfigError, validateBrainConfigDetailed } from "../../../src/core/brain/policy.ts";
+import {
+ BrainConfigError,
+ resolveScopedRulesMaxChars,
+ validateBrainConfigDetailed,
+} from "../../../src/core/brain/policy.ts";
function validate(yaml: string) {
return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");
@@ -154,3 +158,41 @@ describe("active.standing_rules_max_chars (silence-is-not-an-answer, U8)", () =>
expect(warnings.find((w) => w.message.includes("standing_rules_max_chars"))).toBeUndefined();
});
});
+
+describe("active.scoped_rules_max_chars (scoped operator rules)", () => {
+ test("absent → undefined, and the resolver answers the default", () => {
+ const { config } = validate(HEAD + `active:\n inject_budget_chars: 4000\n`);
+ expect(config.active?.scoped_rules_max_chars).toBeUndefined();
+ expect(resolveScopedRulesMaxChars(config)).toBe(2000);
+ expect(resolveScopedRulesMaxChars(null)).toBe(2000);
+ });
+
+ test("present → loaded and resolved", () => {
+ const { config } = validate(HEAD + `active:\n scoped_rules_max_chars: 500\n`);
+ expect(config.active?.scoped_rules_max_chars).toBe(500);
+ expect(resolveScopedRulesMaxChars(config)).toBe(500);
+ });
+
+ test("below minimum rejected with the range message naming the key", () => {
+ expect(() => validate(HEAD + `active:\n scoped_rules_max_chars: 150\n`)).toThrow(
+ /active\.scoped_rules_max_chars/,
+ );
+ expect(() => validate(HEAD + `active:\n scoped_rules_max_chars: 150\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("above maximum and non-integer rejected", () => {
+ expect(() => validate(HEAD + `active:\n scoped_rules_max_chars: 1000000\n`)).toThrow(
+ BrainConfigError,
+ );
+ expect(() => validate(HEAD + `active:\n scoped_rules_max_chars: lots\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("the key is known: it does not warn as unrecognised", () => {
+ const { warnings } = validate(HEAD + `active:\n scoped_rules_max_chars: 2000\n`);
+ expect(warnings.find((w) => w.message.includes("scoped_rules_max_chars"))).toBeUndefined();
+ });
+});
diff --git a/tests/core/brain/review-candidates.test.ts b/tests/core/brain/review-candidates.test.ts
index 3ebdb6a3..5730dda5 100644
--- a/tests/core/brain/review-candidates.test.ts
+++ b/tests/core/brain/review-candidates.test.ts
@@ -9,6 +9,7 @@ import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { dream, DreamPreviewReadableError } from "../../../src/core/brain/dream.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { dreamRunsDir } from "../../../src/core/brain/paths.ts";
import { buildReviewCandidates } from "../../../src/core/brain/review-candidates.ts";
@@ -65,4 +66,8 @@ describe("buildReviewCandidates", () => {
const b = await buildReviewCandidates(vault, { now: new Date("2026-05-27T12:00:00Z") });
expect(JSON.stringify(a)).toBe(JSON.stringify(b));
});
+
+ test("a real pass refuses a preview filter by name", () => {
+ expect(() => dream(vault, { previewReadable: () => true })).toThrow(DreamPreviewReadableError);
+ });
});
diff --git a/tests/core/brain/scope-identity.test.ts b/tests/core/brain/scope-identity.test.ts
new file mode 100644
index 00000000..a692d0b0
--- /dev/null
+++ b/tests/core/brain/scope-identity.test.ts
@@ -0,0 +1,151 @@
+/**
+ * Server-resolved scope identity for the scoped operator rules.
+ *
+ * Project: the basename of the directory holding the nearest
+ * `.o2b-vault.json` pointer. Host: the device id. Harness: the launch-time
+ * `--harness` option, else the install target. None of them is ever named
+ * by a caller.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ VAULT_POINTER_FILE,
+ writeVaultPointer,
+} from "../../../src/core/brain/portability/pointer.ts";
+import {
+ resolveHarnessScope,
+ resolveHostScope,
+ resolveProjectScope,
+} from "../../../src/core/brain/scope-identity.ts";
+import { withDeviceId } from "../../helpers/device-id.ts";
+import { tempDirs } from "../../helpers/temp-dir.ts";
+
+const mkTemp = tempDirs();
+
+describe("resolveProjectScope", () => {
+ test("a linked project resolves from a subdirectory to the key of its basename", () => {
+ const root = mkTemp("o2b-scope-project-");
+ const vault = join(root, "vault");
+ const project = join(root, "My_Project.v2");
+ const sub = join(project, "src", "deep");
+ mkdirSync(vault, { recursive: true });
+ mkdirSync(sub, { recursive: true });
+ writeVaultPointer(project, vault);
+ expect(resolveProjectScope(sub, vault)).toBe("my-project-v2");
+ expect(resolveProjectScope(project, vault)).toBe("my-project-v2");
+ });
+
+ test("no pointer, a null directory and a malformed pointer give null", () => {
+ const root = mkTemp("o2b-scope-none-");
+ const vault = join(root, "vault");
+ mkdirSync(vault, { recursive: true });
+ const bare = join(root, "bare");
+ mkdirSync(bare, { recursive: true });
+ expect(resolveProjectScope(bare, vault)).toBeNull();
+ expect(resolveProjectScope(null, vault)).toBeNull();
+
+ const broken = join(root, "broken");
+ mkdirSync(broken, { recursive: true });
+ writeFileSync(join(broken, VAULT_POINTER_FILE), "{not json");
+ expect(resolveProjectScope(broken, vault)).toBeNull();
+ });
+
+ test("a project whose name has no Latin character still keys", () => {
+ const root = mkTemp("o2b-scope-script-");
+ const vault = join(root, "vault");
+ const project = join(root, "Проект Альфа");
+ mkdirSync(vault, { recursive: true });
+ mkdirSync(project, { recursive: true });
+ writeVaultPointer(project, vault);
+ expect(resolveProjectScope(project, vault)).toBe("проект-альфа");
+ });
+
+ test("a directory whose name has no letter or digit gives null", () => {
+ const root = mkTemp("o2b-scope-dashes-");
+ const vault = join(root, "vault");
+ const project = join(root, "---");
+ mkdirSync(vault, { recursive: true });
+ mkdirSync(project, { recursive: true });
+ writeVaultPointer(project, vault);
+ expect(resolveProjectScope(project, vault)).toBeNull();
+ });
+});
+
+/** A vault and a project `client-a` linked to it. */
+function linkedTree(): { root: string; vault: string; project: string } {
+ const root = mkTemp("o2b-scope-serving-");
+ const vault = join(root, "vault");
+ const project = join(root, "client-a");
+ mkdirSync(vault, { recursive: true });
+ mkdirSync(project, { recursive: true });
+ writeVaultPointer(project, vault);
+ return { root, vault, project };
+}
+
+describe("resolveProjectScope and the serving vault", () => {
+ test("a pointer naming another vault in a subdirectory is skipped", () => {
+ const { root, vault, project } = linkedTree();
+ const other = join(root, "other-vault");
+ const clone = join(project, "vendor", "evil");
+ mkdirSync(other, { recursive: true });
+ mkdirSync(join(clone, "src"), { recursive: true });
+ writeVaultPointer(clone, other);
+ expect(resolveProjectScope(join(clone, "src"), vault)).toBe("client-a");
+ expect(resolveProjectScope(join(clone, "src"), other)).toBe("evil");
+ });
+
+ test("a malformed pointer in a subdirectory is skipped and the parent pointer wins", () => {
+ const { vault, project } = linkedTree();
+ const broken = join(project, "vendor", "broken");
+ mkdirSync(broken, { recursive: true });
+ writeFileSync(join(broken, VAULT_POINTER_FILE), "{not json");
+ expect(resolveProjectScope(broken, vault)).toBe("client-a");
+ });
+
+ test("only pointers naming another vault give null", () => {
+ const { root, project } = linkedTree();
+ const other = join(root, "other-vault");
+ mkdirSync(other, { recursive: true });
+ expect(resolveProjectScope(project, other)).toBeNull();
+ });
+});
+
+describe("resolveHostScope", () => {
+ test("a device id keys the host", () => {
+ expect(withDeviceId("aaaa0001", () => resolveHostScope(undefined))).toEqual({
+ host: "aaaa0001",
+ unreadable: false,
+ });
+ });
+
+ test("the empty device id is the explicit opt-out, not a failure", () => {
+ expect(withDeviceId("", () => resolveHostScope(undefined))).toEqual({
+ host: null,
+ unreadable: false,
+ });
+ });
+
+ test("an unreadable config is reported, not read as absent", () => {
+ // A directory in the config file's place fails the read on every
+ // platform, so no permission bit is needed.
+ const root = mkTemp("o2b-scope-host-");
+ const configPath = join(root, "config.yaml");
+ mkdirSync(configPath, { recursive: true });
+ // An invalid override falls through to the config file.
+ expect(withDeviceId("NOT A VALID ID", () => resolveHostScope(configPath))).toEqual({
+ host: null,
+ unreadable: true,
+ });
+ });
+});
+
+describe("resolveHarnessScope", () => {
+ test("the --harness value wins over the install target", () => {
+ expect(resolveHarnessScope("codex", "cursor")).toBe("codex");
+ expect(resolveHarnessScope(undefined, "cursor")).toBe("cursor");
+ expect(resolveHarnessScope(undefined, undefined)).toBeNull();
+ });
+});
diff --git a/tests/core/brain/scoped-rules-guard.test.ts b/tests/core/brain/scoped-rules-guard.test.ts
new file mode 100644
index 00000000..cd56c49f
--- /dev/null
+++ b/tests/core/brain/scoped-rules-guard.test.ts
@@ -0,0 +1,185 @@
+/**
+ * The standing-rules write guard covers the scoped directory.
+ *
+ * `Brain/standing-rules/` holds operator-authored scoped rules, so every
+ * write path that already refuses the constitution file refuses any path
+ * inside the directory too, lexically and then canonically: a file that
+ * does not exist yet, reached through a symlinked folder, is the same
+ * target.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
+import { basename, join } from "node:path";
+
+import { brainScopedRulesDir, brainStandingRulesPath } from "../../../src/core/brain/paths.ts";
+import {
+ assertStandingRulesNotTargeted,
+ StandingRulesWriteRefusedError,
+} from "../../../src/core/brain/standing-rules.ts";
+import { tempDirs } from "../../helpers/temp-dir.ts";
+
+const mkTemp = tempDirs();
+
+function vault(): string {
+ const dir = mkTemp("o2b-scoped-guard-");
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ return dir;
+}
+
+function refusal(run: () => void): StandingRulesWriteRefusedError | null {
+ try {
+ run();
+ return null;
+ } catch (err) {
+ if (err instanceof StandingRulesWriteRefusedError) return err;
+ throw err;
+ }
+}
+
+/** Symlinks need a privilege Windows CI does not grant; probe once. */
+function canSymlink(): boolean {
+ const dir = mkTemp("o2b-symlink-probe-");
+ try {
+ symlinkSync(join(dir, "missing"), join(dir, "link"), "dir");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const SYMLINKS = canSymlink();
+/** The default file systems of these platforms compare names case-insensitively. */
+const CASE_INSENSITIVE_PLATFORM = process.platform === "darwin" || process.platform === "win32";
+
+describe("assertStandingRulesNotTargeted and the scoped directory", () => {
+ test("a file inside the directory is refused with its own path", () => {
+ const v = vault();
+ const err = refusal(() =>
+ assertStandingRulesNotTargeted(v, "Brain/standing-rules/project/x.md", "test"),
+ );
+ expect(err).not.toBeNull();
+ expect(err?.name).toBe("StandingRulesWriteRefusedError");
+ expect(err?.surface).toBe("test");
+ expect(basename(err?.path ?? "")).toBe("x.md");
+ expect(err?.message).toContain("test refused: ");
+ });
+
+ test("the directory itself and a dot-dot spelling are refused", () => {
+ const v = vault();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Brain/standing-rules", "t")),
+ ).not.toBeNull();
+ expect(
+ refusal(() =>
+ assertStandingRulesNotTargeted(v, "Brain/sources/../standing-rules/host/a.md", "t"),
+ ),
+ ).not.toBeNull();
+ });
+
+ test.skipIf(!SYMLINKS)(
+ "a not-yet-existing file reached through a symlinked folder is refused",
+ () => {
+ const v = vault();
+ mkdirSync(brainScopedRulesDir(v), { recursive: true });
+ mkdirSync(join(v, "Notes"), { recursive: true });
+ symlinkSync(brainScopedRulesDir(v), join(v, "Notes", "alias"), "dir");
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Notes/alias/project/new.md", "t")),
+ ).not.toBeNull();
+ },
+ );
+
+ test.skipIf(!SYMLINKS)("a symlinked vault root does not make one path look like two", () => {
+ const real = vault();
+ const link = join(mkTemp("o2b-scoped-guard-link-"), "vault");
+ symlinkSync(real, link, "dir");
+ expect(
+ refusal(() =>
+ assertStandingRulesNotTargeted(real, join(link, "Brain/standing-rules/host/a.md"), "t"),
+ ),
+ ).not.toBeNull();
+ });
+
+ test.skipIf(!SYMLINKS)(
+ "a symlinked vault root and an in-vault alias reach a directory that does not exist yet",
+ () => {
+ const real = vault();
+ mkdirSync(join(real, "Notes"), { recursive: true });
+ symlinkSync(join(real, "Brain"), join(real, "Notes", "alias"), "dir");
+ const link = join(mkTemp("o2b-scoped-guard-link-"), "vault");
+ symlinkSync(real, link, "dir");
+ for (const root of [real, link]) {
+ expect(
+ refusal(() =>
+ assertStandingRulesNotTargeted(root, "Notes/alias/standing-rules/project/x.md", "t"),
+ ),
+ ).not.toBeNull();
+ }
+ },
+ );
+
+ test.skipIf(!SYMLINKS)(
+ "a scoped rules folder symlinked out of the vault refuses its own paths and lets other writes through",
+ () => {
+ const v = vault();
+ const outside = mkTemp("o2b-scoped-guard-outside-");
+ symlinkSync(outside, join(v, "Brain", "standing-rules"), "dir");
+ expect(refusal(() => assertStandingRulesNotTargeted(v, "Notes/a.md", "t"))).toBeNull();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Brain/standing-rules/project/x.md", "t")),
+ ).not.toBeNull();
+ },
+ );
+
+ test.skipIf(!SYMLINKS)(
+ "a constitution file symlinked out of the vault is refused and lets other writes through",
+ () => {
+ const v = vault();
+ const outside = join(mkTemp("o2b-scoped-guard-outside-"), "rules.md");
+ writeFileSync(outside, "# Rules\n");
+ symlinkSync(outside, join(v, "Brain", "standing-rules.md"), "file");
+ expect(refusal(() => assertStandingRulesNotTargeted(v, "Notes/a.md", "t"))).toBeNull();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Brain/standing-rules.md", "t")),
+ ).not.toBeNull();
+ },
+ );
+
+ test.skipIf(!CASE_INSENSITIVE_PLATFORM)(
+ "a case-variant spelling of the directory is refused where names fold",
+ () => {
+ const v = vault();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "brain/Standing-Rules/project/x.md", "t")),
+ ).not.toBeNull();
+ mkdirSync(brainScopedRulesDir(v), { recursive: true });
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "BRAIN/STANDING-RULES/host/a.md", "t")),
+ ).not.toBeNull();
+ },
+ );
+
+ test("neighbours of the directory are not refused", () => {
+ const v = vault();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Brain/standing-rules-notes.md", "t")),
+ ).toBeNull();
+ expect(
+ refusal(() => assertStandingRulesNotTargeted(v, "Notes/standing-rules/x.md", "t")),
+ ).toBeNull();
+ expect(refusal(() => assertStandingRulesNotTargeted(v, "Brain/sources/x.md", "t"))).toBeNull();
+ });
+
+ test("the constitution file is still refused with the unchanged message", () => {
+ const v = vault();
+ const err = refusal(() =>
+ assertStandingRulesNotTargeted(v, "Brain/standing-rules.md", "labels"),
+ );
+ expect(err?.path).toBe(brainStandingRulesPath(v));
+ expect(err?.message).toBe(
+ `labels refused: ${brainStandingRulesPath(v)} is the operator's standing-rules file, which this ` +
+ "surface does not rewrite",
+ );
+ });
+});
diff --git a/tests/core/brain/scoped-rules.test.ts b/tests/core/brain/scoped-rules.test.ts
new file mode 100644
index 00000000..63d8649d
--- /dev/null
+++ b/tests/core/brain/scoped-rules.test.ts
@@ -0,0 +1,394 @@
+/**
+ * Scoped operator rules: the vocabularies, the key normaliser and the
+ * paths of `Brain/standing-rules/<axis>/<key>.md`.
+ *
+ * The key normaliser keeps Unicode letters and digits so a project whose
+ * name carries no Latin character still keys; no language is enumerated.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { BRAIN_SCOPED_RULES_DIR } from "../../../src/core/brain/path-constants.ts";
+import { brainScopedRulePath, brainScopedRulesDir } from "../../../src/core/brain/paths.ts";
+import {
+ HARNESS_ID,
+ HARNESS_IDS,
+ isHarnessId,
+ isScopedRuleAxis,
+ readScopedRules,
+ SCOPED_RULE_AXES,
+ SCOPED_RULE_AXIS,
+ SCOPED_RULE_AXIS_LABEL,
+ SCOPED_RULE_KEY_MAX_CHARS,
+ SCOPED_RULES_HEADER,
+ SCOPED_RULES_HOST_UNREADABLE_NOTICE,
+ SCOPED_RULES_MAX_CHARS_DEFAULT,
+ SCOPED_RULES_MAX_CHARS_MAX,
+ SCOPED_RULES_MAX_CHARS_MIN,
+ SCOPED_RULES_NOTICE_RESERVE,
+ scopedRuleKey,
+ type ScopedRuleAxis,
+ type ScopedRuleIdentity,
+} from "../../../src/core/brain/scoped-rules.ts";
+import { STANDING_RULES_MAX_CHARS_MAX } from "../../../src/core/brain/standing-rules.ts";
+import { INSTALL_TARGET_IDS } from "../../../src/core/runtime/host-facts.ts";
+import { tempDirs } from "../../helpers/temp-dir.ts";
+
+const mkTemp = tempDirs();
+
+describe("scopedRuleKey", () => {
+ test("keeps letters and digits of any script", () => {
+ expect(scopedRuleKey("プロジェクト 2")).toBe("プロジェクト-2");
+ expect(scopedRuleKey("Έργο Άλφα")).toBe("έργο-άλφα");
+ });
+
+ test("folds case and collapses every other run to one dash", () => {
+ expect(scopedRuleKey(" My_Repo.v2 ")).toBe("my-repo-v2");
+ });
+
+ test("a name with no letter or digit has no key", () => {
+ expect(scopedRuleKey("---")).toBeNull();
+ expect(scopedRuleKey("")).toBeNull();
+ });
+
+ test("caps the key and strips a dash left at the cut", () => {
+ const long = "a".repeat(63) + "-" + "b".repeat(36);
+ const key = scopedRuleKey(long);
+ expect(key).not.toBeNull();
+ expect((key ?? "").length).toBeLessThanOrEqual(SCOPED_RULE_KEY_MAX_CHARS);
+ expect(key?.endsWith("-")).toBe(false);
+ expect(scopedRuleKey("x".repeat(100))).toBe("x".repeat(64));
+ // A letter outside the BMP at the cut is dropped whole, never halved.
+ const astral = scopedRuleKey(`${"a".repeat(63)}\u{20000}b`);
+ expect(astral).toBe("a".repeat(63));
+ });
+
+ test("keeps combining marks, so a word in an abugida or with vowel marks keys whole", () => {
+ expect(scopedRuleKey("हिन्दी")).toBe("हिन्दी");
+ expect(scopedRuleKey("مُحَمَّد")).toBe("مُحَمَّد");
+ // The lowercase of a dotted capital I is i plus a combining dot above,
+ // which NFC cannot recompose; the mark stays part of the key.
+ expect(scopedRuleKey("İstanbul")).toBe("i\u0307stanbul");
+ expect(scopedRuleKey("Café")).toBe("café");
+ expect(scopedRuleKey("café")).toBe("café");
+ expect(scopedRuleKey("Cafe\u0301")).toBe("café");
+ // A capital with no precomposed form whose lowercase has one: only an
+ // NFC pass after lowercasing gives both spellings one key.
+ expect(scopedRuleKey("T\u0308ag")).toBe("\u1e97ag");
+ expect(scopedRuleKey("\u1e97ag")).toBe("\u1e97ag");
+ });
+
+ test("normalises to NFC so composed and decomposed spellings share a key", () => {
+ expect(scopedRuleKey("Café")).toBe(scopedRuleKey("Café"));
+ });
+});
+
+describe("vocabularies", () => {
+ test("the axes in drop-priority order", () => {
+ expect([...SCOPED_RULE_AXES]).toEqual(["project", "harness", "host"]);
+ expect(SCOPED_RULE_AXIS.project).toBe("project");
+ expect(isScopedRuleAxis("host")).toBe(true);
+ expect(isScopedRuleAxis("owner")).toBe(false);
+ expect(SCOPED_RULE_AXIS_LABEL).toEqual({
+ project: "Project",
+ harness: "Harness",
+ host: "Host",
+ });
+ });
+
+ test("the harness ids are alphabetical and cover every install target", () => {
+ expect([...HARNESS_IDS]).toEqual([
+ "aider",
+ "claude-code",
+ "codex",
+ "copilot-cli",
+ "cursor",
+ "gemini-cli",
+ "generic",
+ "grok",
+ "hermes",
+ "kiro",
+ "openclaw",
+ "opencode",
+ "pi",
+ ]);
+ for (const target of INSTALL_TARGET_IDS) expect(HARNESS_IDS).toContain(target);
+ expect(HARNESS_ID.claudeCode).toBe("claude-code");
+ expect(isHarnessId("hermes")).toBe(true);
+ expect(isHarnessId("Hermes")).toBe(false);
+ });
+
+ test("the cap bounds", () => {
+ expect(SCOPED_RULES_MAX_CHARS_DEFAULT).toBe(2000);
+ expect(SCOPED_RULES_MAX_CHARS_MIN).toBe(200);
+ expect(SCOPED_RULES_MAX_CHARS_MAX).toBe(STANDING_RULES_MAX_CHARS_MAX);
+ });
+});
+
+describe("paths", () => {
+ test("the directory sits beside the constitution file under Brain/", () => {
+ const vault = mkTemp("o2b-scoped-paths-");
+ expect(BRAIN_SCOPED_RULES_DIR).toBe("standing-rules");
+ expect(brainScopedRulesDir(vault).replaceAll("\\", "/")).toEndWith("Brain/standing-rules");
+ expect(brainScopedRulePath(vault, "project", "x").replaceAll("\\", "/")).toEndWith(
+ "Brain/standing-rules/project/x.md",
+ );
+ });
+});
+
+// ---------- Reader ----------
+
+const NO_SCOPE: ScopedRuleIdentity = Object.freeze({ project: null, harness: null, host: null });
+
+function vaultWith(files: Partial<Record<string, string>>): string {
+ const vault = mkTemp("o2b-scoped-read-");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ for (const [rel, body] of Object.entries(files)) {
+ const [axis, key] = rel.split("/") as [ScopedRuleAxis, string];
+ const path = brainScopedRulePath(vault, axis, key);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, body ?? "");
+ }
+ return vault;
+}
+
+function vaultMarkers(vault: string): string[] {
+ const posixVault = vault.replaceAll("\\", "/");
+ return [vault, posixVault];
+}
+
+/** The rules read for project `x` whose file is `length` characters, at the default cap. */
+function projectRuleOf(length: number): ReturnType<typeof readScopedRules> {
+ return readScopedRules(vaultWith({ "project/x": "a".repeat(length) }), {
+ ...NO_SCOPE,
+ project: "x",
+ });
+}
+
+describe("readScopedRules", () => {
+ test("renders only the file matching the resolved value, after the header", () => {
+ const vault = vaultWith({
+ "project/x": "zzprojectxzz rule\n",
+ "project/y": "zzprojectyzz rule",
+ });
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" });
+ expect(rules.text.startsWith(SCOPED_RULES_HEADER)).toBe(true);
+ expect(rules.text).toContain("### Project: x");
+ expect(rules.text).toContain("zzprojectxzz rule");
+ expect(rules.text).not.toContain("zzprojectyzz");
+ expect(rules.text.indexOf("### Project: x")).toBeGreaterThan(SCOPED_RULES_HEADER.length - 1);
+ expect(rules.files).toEqual([
+ { axis: "project", key: "x", path: "Brain/standing-rules/project/x.md", truncated: false },
+ ]);
+ expect(rules.identity).toEqual({ project: "x", harness: null, host: null });
+ });
+
+ test("a null axis matches nothing and nothing matched renders nothing", () => {
+ const vault = vaultWith({
+ "project/x": "rule",
+ "harness/codex": "rule",
+ "host/aaaa0001": "rule",
+ });
+ const rules = readScopedRules(vault, NO_SCOPE);
+ expect(rules.text).toBe("");
+ expect(rules.files).toEqual([]);
+ });
+
+ test("an absent or empty file is absence", () => {
+ const vault = vaultWith({ "project/x": " \n\n" });
+ expect(readScopedRules(vault, { ...NO_SCOPE, project: "x", host: "aaaa0001" }).text).toBe("");
+ });
+
+ test("all three axes render in project, harness, host order", () => {
+ const vault = vaultWith({
+ "project/x": "zzp",
+ "harness/codex": "zzh",
+ "host/aaaa0001": "zzd",
+ });
+ const rules = readScopedRules(vault, { project: "x", harness: "codex", host: "aaaa0001" });
+ const at = (needle: string): number => rules.text.indexOf(needle);
+ expect(at("### Project: x")).toBeLessThan(at("### Harness: codex"));
+ expect(at("### Harness: codex")).toBeLessThan(at("### Host: aaaa0001"));
+ expect(rules.files.map((file) => file.axis)).toEqual(["project", "harness", "host"]);
+ });
+
+ test("the cap drops the host file first and the notice reports integers", () => {
+ // 96 + 2 + 100 characters fit 200 once the host section (103) is dropped.
+ const body = "r".repeat(80);
+ const vault = vaultWith({ "project/x": body, "harness/codex": body, "host/aaaa0001": body });
+ const rules = readScopedRules(
+ vault,
+ { project: "x", harness: "codex", host: "aaaa0001" },
+ { maxChars: 200 },
+ );
+ expect(rules.text).toContain("### Project: x");
+ expect(rules.text).toContain("### Harness: codex");
+ expect(rules.text).not.toContain("### Host: aaaa0001");
+ expect(rules.text).toMatch(
+ /_Scoped rules truncated to the configured cap: kept \d+ of \d+ characters, 1 file\(s\) dropped\._$/,
+ );
+ expect(rules.files.map((file) => [file.axis, file.truncated])).toEqual([
+ ["project", false],
+ ["harness", false],
+ ["host", true],
+ ]);
+ });
+
+ test("a file trimmed by the cap is marked truncated", () => {
+ const body = Array.from({ length: 40 }, (_, i) => `line ${i} of the project rules`).join("\n");
+ const vault = vaultWith({ "project/x": body });
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" }, { maxChars: 200 });
+ expect(rules.files).toEqual([
+ { axis: "project", key: "x", path: "Brain/standing-rules/project/x.md", truncated: true },
+ ]);
+ expect(rules.text).toContain("0 file(s) dropped");
+ });
+
+ test("an unreadable file renders a vault-relative UNAVAILABLE line, never the error text", () => {
+ const vault = vaultWith({});
+ // A directory in the file's place fails the read on every platform.
+ mkdirSync(brainScopedRulePath(vault, "project", "x"), { recursive: true });
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" });
+ expect(rules.text).toContain(
+ "UNAVAILABLE: Brain/standing-rules/project/x.md could not be read (EISDIR).",
+ );
+ expect(rules.files).toEqual([
+ { axis: "project", key: "x", path: "Brain/standing-rules/project/x.md", truncated: false },
+ ]);
+ for (const marker of vaultMarkers(vault)) expect(rules.text).not.toContain(marker);
+ });
+
+ test("an unreadable device id with a host file appends the host notice", () => {
+ const vault = vaultWith({ "host/bbbb0002": "zzhostzz" });
+ const alone = readScopedRules(vault, NO_SCOPE, { hostUnreadable: true });
+ expect(alone.text).toBe(`${SCOPED_RULES_HEADER}\n\n${SCOPED_RULES_HOST_UNREADABLE_NOTICE}`);
+ expect(alone.files).toEqual([]);
+
+ const withProject = vaultWith({ "project/x": "zzp", "host/bbbb0002": "zzhostzz" });
+ const both = readScopedRules(
+ withProject,
+ { ...NO_SCOPE, project: "x" },
+ { hostUnreadable: true },
+ );
+ expect(both.text.endsWith(`\n\n${SCOPED_RULES_HOST_UNREADABLE_NOTICE}`)).toBe(true);
+ expect(both.text).not.toContain("zzhostzz");
+ });
+
+ test("an unreadable device id with no host file says nothing", () => {
+ const vault = vaultWith({ "project/x": "zzp" });
+ const rules = readScopedRules(vault, NO_SCOPE, { hostUnreadable: true });
+ expect(rules.text).toBe("");
+ });
+
+ test("no rendered text carries the vault's absolute path", () => {
+ const vault = vaultWith({ "project/x": "zzp", "host/aaaa0001": "r".repeat(400) });
+ const rules = readScopedRules(
+ vault,
+ { project: "x", harness: null, host: "aaaa0001" },
+ { maxChars: 200, hostUnreadable: true },
+ );
+ for (const marker of vaultMarkers(vault)) expect(rules.text).not.toContain(marker);
+ });
+
+ test("a section whose body cannot fit is dropped whole, never left as a bare heading", () => {
+ const vault = vaultWith({ "project/x": `zzp ${"x".repeat(5000)}` });
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" }, { maxChars: 200 });
+ expect(rules.text).not.toContain("### Project: x");
+ expect(rules.text).toContain("1 file(s) dropped");
+ expect(rules.files).toEqual([
+ { axis: "project", key: "x", path: "Brain/standing-rules/project/x.md", truncated: true },
+ ]);
+ });
+
+ test("the notice reserve covers every notice the block can carry", () => {
+ // Every axis matched, the cap at its maximum and an unreadable device id.
+ const body = Array.from({ length: 4000 }, (_, i) => `line ${i}`).join("\n");
+ const vault = vaultWith({ "project/x": body, "harness/codex": body, "host/aaaa0001": body });
+ const rules = readScopedRules(
+ vault,
+ { project: "x", harness: "codex", host: null },
+ { maxChars: SCOPED_RULES_MAX_CHARS_MAX, hostUnreadable: true },
+ );
+ expect(rules.text.length).toBeLessThanOrEqual(
+ SCOPED_RULES_HEADER.length + SCOPED_RULES_MAX_CHARS_MAX + SCOPED_RULES_NOTICE_RESERVE,
+ );
+ });
+
+ test("the notice reserve covers both notices when the kept sections fill the cap", () => {
+ // One-character lines, so the cut keeps the sections within a line of
+ // the cap and both the truncation and the host notice ride on top.
+ const vault = vaultWith({
+ "project/x": "a\n".repeat(SCOPED_RULES_MAX_CHARS_DEFAULT),
+ "host/aaaa0001": "zzhostzz",
+ });
+ const rules = readScopedRules(
+ vault,
+ { ...NO_SCOPE, project: "x" },
+ { maxChars: SCOPED_RULES_MAX_CHARS_DEFAULT, hostUnreadable: true },
+ );
+ expect(rules.files[0]?.truncated).toBe(true);
+ expect(rules.text).toEndWith(SCOPED_RULES_HOST_UNREADABLE_NOTICE);
+ expect(rules.text.length).toBeLessThanOrEqual(
+ SCOPED_RULES_HEADER.length + SCOPED_RULES_MAX_CHARS_DEFAULT + SCOPED_RULES_NOTICE_RESERVE,
+ );
+ });
+
+ test("the default cap is the documented default", () => {
+ // The section is "### Project: x\n\n" (16 characters) plus the body:
+ // 100 under the default fits, 100 over it is cut. A default moved by
+ // more than 100 either way flips one of the two.
+ expect(projectRuleOf(SCOPED_RULES_MAX_CHARS_DEFAULT - 116).files[0]?.truncated).toBe(false);
+ expect(projectRuleOf(SCOPED_RULES_MAX_CHARS_DEFAULT + 100).files[0]?.truncated).toBe(true);
+ });
+
+ test("a resolved value that spells a path never leaves its axis directory", () => {
+ const vault = vaultWith({ "project/etc": "zzinsidezz" });
+ writeFileSync(join(vault, "Brain", "etc.md"), "zzoutsidezz");
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "../../etc" });
+ expect(rules.text).toContain("zzinsidezz");
+ expect(rules.text).not.toContain("zzoutsidezz");
+ expect(rules.files.map((file) => file.path)).toEqual(["Brain/standing-rules/project/etc.md"]);
+ });
+});
+
+describe("readScopedRules and a symlink leaving the vault", () => {
+ const SYMLINKS = canSymlink();
+ const ESCAPED = "UNAVAILABLE: Brain/standing-rules/project/x.md could not be read (ESCAPE).";
+
+ test.skipIf(!SYMLINKS)("a symlinked rule file renders the UNAVAILABLE line", () => {
+ const vault = vaultWith({});
+ const outside = join(mkTemp("o2b-scoped-outside-"), "x.md");
+ writeFileSync(outside, "zzoutsidezz");
+ mkdirSync(dirname(brainScopedRulePath(vault, "project", "x")), { recursive: true });
+ symlinkSync(outside, brainScopedRulePath(vault, "project", "x"), "file");
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" });
+ expect(rules.text).toContain(ESCAPED);
+ expect(rules.text).not.toContain("zzoutsidezz");
+ for (const marker of vaultMarkers(vault)) expect(rules.text).not.toContain(marker);
+ });
+
+ test.skipIf(!SYMLINKS)("a symlinked axis folder renders the UNAVAILABLE line", () => {
+ const vault = vaultWith({});
+ const outside = mkTemp("o2b-scoped-outside-");
+ writeFileSync(join(outside, "x.md"), "zzoutsidezz");
+ mkdirSync(brainScopedRulesDir(vault), { recursive: true });
+ symlinkSync(outside, join(brainScopedRulesDir(vault), "project"), "dir");
+ const rules = readScopedRules(vault, { ...NO_SCOPE, project: "x" });
+ expect(rules.text).toContain(ESCAPED);
+ expect(rules.text).not.toContain("zzoutsidezz");
+ for (const marker of vaultMarkers(vault)) expect(rules.text).not.toContain(marker);
+ });
+});
+
+/** Symlinks need a privilege Windows CI does not grant; probe once. */
+function canSymlink(): boolean {
+ const dir = mkTemp("o2b-symlink-probe-");
+ try {
+ symlinkSync(join(dir, "missing"), join(dir, "link"), "dir");
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/tests/core/brain/tensions.test.ts b/tests/core/brain/tensions.test.ts
index d701dd48..11ca5b2b 100644
--- a/tests/core/brain/tensions.test.ts
+++ b/tests/core/brain/tensions.test.ts
@@ -21,6 +21,10 @@ import {
tensionDedupKey,
tensionWarningsForContextItems,
} from "../../../src/core/brain/tensions.ts";
+import {
+ REMOTE_DENY_VISIBILITY_TOKEN as RESERVED,
+ strictestVisibility,
+} from "../../../src/core/graph/visibility.ts";
let vault: string;
@@ -201,3 +205,21 @@ describe("tensionWarningsForContextItems", () => {
expect(tensionWarningsForContextItems(vault, ["pref-tabs", "pref-spaces"]).length).toBe(0);
});
});
+
+describe("strictestVisibility", () => {
+ test("the reserved token on either side wins alone", () => {
+ expect(strictestVisibility([RESERVED, "team"], [])).toEqual([RESERVED]);
+ expect(strictestVisibility(["team"], [RESERVED])).toEqual([RESERVED]);
+ });
+
+ test("a default-visibility side takes the other side's tokens", () => {
+ expect(strictestVisibility([], ["team"])).toEqual(["team"]);
+ expect(strictestVisibility(["team"], [])).toEqual(["team"]);
+ expect(strictestVisibility([], [])).toEqual([]);
+ });
+
+ test("two tagged sides keep the shared tokens, or the reserved token when none is shared", () => {
+ expect(strictestVisibility(["team", "ops"], ["ops", "qa"])).toEqual(["ops"]);
+ expect(strictestVisibility(["team"], ["qa"])).toEqual([RESERVED]);
+ });
+});
diff --git a/tests/core/brain/today-dashboard.test.ts b/tests/core/brain/today-dashboard.test.ts
index dacf474f..ce77eb9c 100644
--- a/tests/core/brain/today-dashboard.test.ts
+++ b/tests/core/brain/today-dashboard.test.ts
@@ -219,6 +219,28 @@ describe("buildTodayDashboard - populated vault", () => {
expect(dashboard.text).toContain("- [note] shipped v1");
expect(dashboard.text).toContain("Open loops: 1");
});
+
+ test("a readable predicate leaves out the pages it rejects before the totals", () => {
+ seedFullVault();
+ const asked: string[] = [];
+ const dashboard = buildTodayDashboard(vault, {
+ now: NOW,
+ readable: (rel) => {
+ asked.push(rel);
+ return rel !== "Daily/2026-07-17.md" && rel !== "Brain/obligations/past-due.md";
+ },
+ });
+ expect(asked).toContain("Daily/2026-07-17.md");
+ expect(asked).toContain("Brain/obligations/past-due.md");
+ expect(dashboard.obligations.items.map((i) => i.slug)).toEqual(["upcoming"]);
+ expect(dashboard.openLoops.openLoops).toEqual([]);
+ expect(dashboard.openLoops.counts.scannedFiles).toBe(0);
+ expect(dashboard.totals.obligationsTotal).toBe(1);
+ expect(dashboard.totals.obligationsOverdue).toBe(0);
+ expect(dashboard.totals.openLoopsCount).toBe(0);
+ expect(dashboard.text).not.toContain("vendor");
+ expect(dashboard.text).not.toContain("Past Due");
+ });
});
describe("buildTodayDashboard - fault isolation", () => {
diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.ts
index 8eacd309..94694c6a 100644
--- a/tests/helpers/tool-probe-catalogue.ts
+++ b/tests/helpers/tool-probe-catalogue.ts
@@ -634,13 +634,16 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
{
name: "brain_dream",
calls: [
- { args: { action: "list" }, reason: REASON.aggregateOnly },
+ // Below local reach only a dry run is served; the staged lifecycle
+ // is probed at local reach, where the owner filter still applies.
+ { args: { action: "list" }, reason: REASON.aggregateOnly, reach: TRANSPORT_REACH.local },
{ args: { action: "run", dry_run: true }, reason: REASON.ownerFiltered },
- { args: { action: "stage" }, reason: REASON.ownerFiltered },
- { args: { action: "validate", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
- { args: { action: "apply", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
- { args: { action: "discard", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
- { args: { action: "retriage", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },
+ { args: { action: "stage" }, reason: REASON.ownerFiltered, reach: TRANSPORT_REACH.local },
+ ...["validate", "apply", "discard", "retriage"].map((action) => ({
+ args: { action, run_id: "run-probe-absent" },
+ reason: REASON.aggregateOnly,
+ reach: TRANSPORT_REACH.local,
+ })),
],
},
{
diff --git a/tests/hooks/active-inject-scoped-rules.test.ts b/tests/hooks/active-inject-scoped-rules.test.ts
new file mode 100644
index 00000000..31b455a5
--- /dev/null
+++ b/tests/hooks/active-inject-scoped-rules.test.ts
@@ -0,0 +1,368 @@
+/**
+ * The SessionStart hook injects the scoped operator rules for the project
+ * the session runs in (payload `cwd`, the nearest `.o2b-vault.json`
+ * pointer) and for this device, between the constitution and the
+ * budgeted memory context. Harness-scoped files are an MCP-only layer in
+ * this release: the hook has no harness signal it could trust.
+ *
+ * Each project case is an A/B probe: a vault holding another project's
+ * file injects byte-for-byte what the same vault without it injects.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { STANDING_RULES_HEADER } from "../../src/core/brain/standing-rules.ts";
+import {
+ SCOPED_RULES_HEADER,
+ SCOPED_RULES_NOTICE_RESERVE,
+ readScopedRules,
+} from "../../src/core/brain/scoped-rules.ts";
+import { budgetActiveBody } from "../../src/core/brain/active-budget.ts";
+import { writeVaultPointer } from "../../src/core/brain/portability/pointer.ts";
+import { homeEnv } from "../helpers/platform.ts";
+import { waitForSelfHealChildren } from "../helpers/self-heal-children.ts";
+
+const HOOK = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "hooks",
+ "active-inject.ts",
+);
+
+let tmp: string;
+let vault: string;
+let projectX: string;
+let projectY: string;
+let configHome: string;
+
+const MARKER = "zzscopedhookmarkerzz";
+const ACTIVE_HEAD = "# Active Brain Preferences";
+const ACTIVE_BODY = `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n${ACTIVE_HEAD}\n\n## Confirmed (1)\n\n- \`pref-foo\` — Rule body\n`;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-hook-scoped-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "standing-rules.md"), "Never force-push to main.", "utf8");
+ writeFileSync(join(vault, "Brain", "active.md"), ACTIVE_BODY, "utf8");
+ projectX = join(tmp, "proj-x");
+ projectY = join(tmp, "proj-y");
+ for (const dir of [projectX, projectY]) {
+ mkdirSync(join(dir, "src"), { recursive: true });
+ writeVaultPointer(dir, vault);
+ }
+ configHome = mkdtempSync(join(tmpdir(), "o2b-hook-scoped-cfg-"));
+});
+
+afterEach(async () => {
+ await waitForSelfHealChildren(vault);
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<string> {
+ const inherited: Record<string, string> = {
+ PATH: process.env["PATH"] ?? "",
+ ...homeEnv(configHome),
+ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",
+ VAULT_DIR: vault,
+ O2B_DEVICE_ID: "",
+ };
+ const proc = Bun.spawn(["bun", "run", HOOK], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...inherited, ...env },
+ });
+ proc.stdin.write(JSON.stringify(payload));
+ await proc.stdin.end();
+ const [stdout] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ expect(await proc.exited).toBe(0);
+ return stdout;
+}
+
+function injected(stdout: string): string {
+ return (JSON.parse(stdout) as { hookSpecificOutput: { additionalContext: string } })
+ .hookSpecificOutput.additionalContext;
+}
+
+function writeScoped(axis: "project" | "harness" | "host", key: string, body: string): string {
+ const dir = join(vault, "Brain", "standing-rules", axis);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${key}.md`);
+ writeFileSync(path, body, "utf8");
+ return path;
+}
+
+interface ReceiptRecord {
+ readonly kind: string;
+ readonly payload: Record<string, unknown>;
+}
+
+function injectionReceipts(): ReceiptRecord[] {
+ const dir = join(vault, "Brain", "log", "continuity");
+ if (!existsSync(dir)) return [];
+ const out: ReceiptRecord[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".jsonl")) continue;
+ for (const line of readFileSync(join(dir, name), "utf8").split("\n")) {
+ if (line.trim()) out.push(JSON.parse(line) as ReceiptRecord);
+ }
+ }
+ return out.filter(
+ (r) => r.kind === "context_receipt" && r.payload["trigger"] === "session_inject",
+ );
+}
+
+describe("active-inject scoped rules - project axis", () => {
+ test("another project's file leaves the injection byte-identical", async () => {
+ const payload = { hook_event_name: "SessionStart", cwd: join(projectY, "src") };
+ const path = writeScoped("project", "proj-x", MARKER);
+ const withFile = await runHook(payload);
+ rmSync(path);
+ const withoutFile = await runHook(payload);
+ expect(withFile).not.toContain(MARKER);
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("the session's project renders after the constitution and before the memory body", async () => {
+ writeScoped("project", "proj-x", MARKER);
+ const context = injected(
+ await runHook({ hook_event_name: "SessionStart", cwd: join(projectX, "src") }),
+ );
+ const standingAt = context.indexOf(STANDING_RULES_HEADER);
+ const scopedAt = context.indexOf(SCOPED_RULES_HEADER);
+ const markerAt = context.indexOf(MARKER);
+ const bodyAt = context.indexOf(ACTIVE_HEAD);
+ expect(standingAt).toBe(0);
+ expect(scopedAt).toBeGreaterThan(standingAt);
+ expect(context).toContain("### Project: proj-x");
+ expect(markerAt).toBeGreaterThan(scopedAt);
+ expect(bodyAt).toBeGreaterThan(markerAt);
+ expect(context).not.toContain(vault);
+ });
+
+ test("the scoped block is never served from the inject cache", async () => {
+ // Run in project X first so a cached body could hold X's rules, then
+ // in project Y: the cache key is vault-wide, so a cached scoped block
+ // would replay X's rules here.
+ writeScoped("project", "proj-x", MARKER);
+ await runHook({ hook_event_name: "SessionStart", cwd: projectX });
+ const inY = await runHook({ hook_event_name: "SessionStart", cwd: projectY });
+ expect(inY).not.toContain(MARKER);
+ });
+});
+
+describe("active-inject scoped rules - harness and host axes", () => {
+ test("a harness file never renders in the hook", async () => {
+ const payload = { hook_event_name: "SessionStart", cwd: projectY };
+ const path = writeScoped("harness", "claude-code", MARKER);
+ const withFile = await runHook(payload, { CLAUDE_PLUGIN_ROOT: tmp });
+ rmSync(path);
+ const withoutFile = await runHook(payload, { CLAUDE_PLUGIN_ROOT: tmp });
+ expect(withFile).not.toContain(MARKER);
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("this device's host file renders and another device's does not", async () => {
+ writeScoped("host", "bbbb0002", "zzotherdevicezz");
+ writeScoped("host", "aaaa0001", MARKER);
+ const context = injected(
+ await runHook(
+ { hook_event_name: "SessionStart", cwd: projectY },
+ { O2B_DEVICE_ID: "aaaa0001" },
+ ),
+ );
+ expect(context).toContain("### Host: aaaa0001");
+ expect(context).toContain(MARKER);
+ expect(context).not.toContain("zzotherdevicezz");
+ });
+});
+
+describe("active-inject scoped rules - budget", () => {
+ test("the scoped block is capped and subtracted from the injection budget", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nactive:\n inject_budget_chars: 1000\n scoped_rules_max_chars: 200\n",
+ "utf8",
+ );
+ // Many short lines, so the cap cuts at a real line and keeps the marker.
+ const ruleLines = Array.from({ length: 200 }, (_, i) => `- scoped rule line ${i}`);
+ writeScoped("project", "proj-x", `${MARKER}\n${ruleLines.join("\n")}`);
+ const lines = Array.from({ length: 60 }, (_, i) => `- \`pref-${i}\` — rule body number ${i}`);
+ const longActive = `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n${ACTIVE_HEAD}\n\n## Confirmed (60)\n\n${lines.join("\n")}\n`;
+ writeFileSync(join(vault, "Brain", "active.md"), longActive, "utf8");
+
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectX }));
+
+ const expected = readScopedRules(
+ vault,
+ { project: "proj-x", harness: null, host: null },
+ { maxChars: 200 },
+ );
+ expect(expected.text).toContain(MARKER);
+ expect(expected.files[0]?.truncated).toBe(true);
+ expect(context).toContain(expected.text);
+
+ const trimmedActive = longActive.slice(longActive.indexOf(ACTIVE_HEAD)).trim();
+ const activeBudget = Math.max(0, 1000 - expected.text.length);
+ expect(context.endsWith(budgetActiveBody(trimmedActive, activeBudget))).toBe(true);
+
+ const receipts = injectionReceipts();
+ expect(receipts.length).toBe(1);
+ const budget = receipts[0]!.payload["budget"] as Record<string, unknown>;
+ expect(budget["inject_budget_chars"]).toBe(1000);
+ expect(budget["scoped_rules_chars"]).toBe(expected.text.length);
+ const items = receipts[0]!.payload["items"] as ReadonlyArray<Record<string, unknown>>;
+ expect(items.map((item) => item["id"])).toContain("scoped-rules");
+ });
+
+ test("with no scoped file the receipt records zero scoped characters", async () => {
+ await runHook({ hook_event_name: "SessionStart", cwd: projectY });
+ const budget = injectionReceipts()[0]!.payload["budget"] as Record<string, unknown>;
+ expect(budget["scoped_rules_chars"]).toBe(0);
+ });
+});
+
+describe("active-inject scoped rules - gaps closed by the test audit", () => {
+ test("a cached memory body never replays another project's rules", async () => {
+ // Prime the fail-open cache in project X, then break the memory layer
+ // (a directory in active.md's place) so project Y is served the cache.
+ // A scoped block that rode inside the cached body would replay X here.
+ writeScoped("project", "proj-x", MARKER);
+ await runHook({ hook_event_name: "SessionStart", cwd: projectX });
+ rmSync(join(vault, "Brain", "active.md"));
+ mkdirSync(join(vault, "Brain", "active.md"));
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectY }));
+ expect(context).toContain(ACTIVE_HEAD);
+ expect(context).not.toContain(MARKER);
+ });
+
+ test("a payload cwd outside every linked project matches no project file", async () => {
+ const unlinked = join(tmp, "unlinked", "deep");
+ mkdirSync(unlinked, { recursive: true });
+ const payload = { hook_event_name: "SessionStart", cwd: unlinked };
+ const path = writeScoped("project", "unlinked", MARKER);
+ const withFile = await runHook(payload);
+ rmSync(path);
+ expect(withFile).not.toContain(MARKER);
+ expect(withFile).toBe(await runHook(payload));
+ });
+
+ test("an unreadable device id with a host file ends the block with the notice", async () => {
+ writeScoped("host", "aaaa0001", MARKER);
+ const configDir = join(configHome, "config-is-a-directory");
+ mkdirSync(configDir, { recursive: true });
+ const context = injected(
+ await runHook(
+ { hook_event_name: "SessionStart", cwd: projectY },
+ { O2B_DEVICE_ID: "NOT A VALID ID", OPEN_SECOND_BRAIN_CONFIG: configDir },
+ ),
+ );
+ expect(context).toContain(
+ "Host-scoped rules were not applied: this device's id could not be read.",
+ );
+ expect(context).not.toContain(MARKER);
+ expect(context).not.toContain(configDir);
+ });
+
+ test("the scoped cap never exceeds the injection budget", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nactive:\n inject_budget_chars: 1000\n",
+ "utf8",
+ );
+ // Many short lines: the budgeter cuts at a line, so a one-line body
+ // would be dropped under any cap and prove nothing.
+ const lines = Array.from({ length: 200 }, (_, i) => `- scoped rule line ${i}`);
+ writeScoped("project", "proj-x", `${MARKER}\n${lines.join("\n")}`);
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectX }));
+ // The default cap (2000) is clamped to what the budget leaves once the
+ // header and the notices are reserved.
+ const clamped = readScopedRules(
+ vault,
+ { project: "proj-x", harness: null, host: null },
+ { maxChars: 1000 - SCOPED_RULES_HEADER.length - SCOPED_RULES_NOTICE_RESERVE },
+ );
+ expect(clamped.text).toContain(MARKER);
+ expect(clamped.text.length).toBeLessThanOrEqual(1000);
+ expect(context).toContain(clamped.text);
+ });
+
+ test("the header and the notices ride inside a tight injection budget", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nactive:\n inject_budget_chars: 500\n scoped_rules_max_chars: 200\n",
+ "utf8",
+ );
+ writeScoped("project", "proj-x", `${MARKER} ${"x".repeat(5000)}`);
+ const lines = Array.from({ length: 60 }, (_, i) => `- \`pref-${i}\` — rule body number ${i}`);
+ const longActive = `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n${ACTIVE_HEAD}\n\n## Confirmed (60)\n\n${lines.join("\n")}\n`;
+ writeFileSync(join(vault, "Brain", "active.md"), longActive, "utf8");
+
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectX }));
+
+ const scopedStart = context.indexOf(SCOPED_RULES_HEADER);
+ const activeStart = context.indexOf(ACTIVE_HEAD);
+ expect(scopedStart).toBeGreaterThan(-1);
+ const scopedBlock = context.slice(scopedStart, activeStart).trimEnd();
+ // A one-line rule that cannot fit is dropped whole, never left as a
+ // bare heading, and the notice says so.
+ expect(scopedBlock).not.toContain("### Project: proj-x");
+ expect(scopedBlock).toContain("1 file(s) dropped");
+ expect(scopedBlock.length).toBeLessThanOrEqual(500);
+ // The budgeted output (the constitution excluded) stays within the
+ // budget plus the memory body's own truncation notice.
+ const budgeted = context.slice(scopedStart);
+ const trimmedActive = longActive.slice(longActive.indexOf(ACTIVE_HEAD)).trim();
+ const activeBudget = 500 - scopedBlock.length;
+ const activeOut = budgetActiveBody(trimmedActive, activeBudget);
+ expect(budgeted.endsWith(activeOut)).toBe(true);
+ const activeNotice = activeOut.slice(activeOut.lastIndexOf("\n\n") + 2);
+ expect(budgeted.length).toBeLessThanOrEqual(500 + "\n\n".length + activeNotice.length);
+ });
+
+ test("a degraded run keeps the scoped-rules item in the receipt", async () => {
+ writeScoped("project", "proj-x", MARKER);
+ await runHook({ hook_event_name: "SessionStart", cwd: projectX });
+ rmSync(join(vault, "Brain", "active.md"));
+ mkdirSync(join(vault, "Brain", "active.md"));
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectX }));
+ expect(context).toContain(MARKER);
+ const receipts = injectionReceipts();
+ expect(receipts.length).toBe(2);
+ const degraded = receipts[1]!.payload;
+ const injection = degraded["injection"] as Record<string, unknown>;
+ expect(injection["loader_source"]).not.toBe("fresh");
+ const items = degraded["items"] as ReadonlyArray<Record<string, unknown>>;
+ expect(items.map((item) => item["id"])).toEqual(["standing-rules", "scoped-rules"]);
+ });
+
+ test("with no active.md the receipt still records the scoped characters", async () => {
+ rmSync(join(vault, "Brain", "active.md"));
+ writeScoped("project", "proj-x", MARKER);
+ const context = injected(await runHook({ hook_event_name: "SessionStart", cwd: projectX }));
+ const expected = readScopedRules(vault, { project: "proj-x", harness: null, host: null });
+ expect(context).toContain(expected.text);
+ const receipts = injectionReceipts();
+ expect(receipts.length).toBe(1);
+ const budget = receipts[0]!.payload["budget"] as Record<string, unknown>;
+ expect(budget["scoped_rules_chars"]).toBe(expected.text.length);
+ });
+});
diff --git a/tests/mcp/anticipatory-context-reach.test.ts b/tests/mcp/anticipatory-context-reach.test.ts
new file mode 100644
index 00000000..881b4b90
--- /dev/null
+++ b/tests/mcp/anticipatory-context-reach.test.ts
@@ -0,0 +1,84 @@
+/**
+ * `brain_anticipatory_context` answers at the caller's reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a preference
+ * withheld from a remote caller by visibility; vault B never had it. A
+ * server with no reach minted is a remote caller: a refresh, and a read
+ * of a session whose bundle a local caller already cached, must read
+ * alike over both vaults. The local control proves the withheld
+ * preference is there to pack.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_anticipatory_context";
+const SESSION = "session-reach";
+const REFRESH = { session_id: SESSION, refresh: true, signal_text: "plan the week" };
+const PRIVATE_PRINCIPLE = "Rule withheld.";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-anticipatory-reach-"));
+ bases.push(base);
+ return buildReachLogFixture(base, withPrivate);
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+describe("brain_anticipatory_context answers at the caller's reach", () => {
+ test("remote reach: a refresh reads as in a vault without the withheld preference", async () => {
+ const withheld = await answer(fixture(true), REFRESH);
+ expect(withheld).toBe(await answer(fixture(false), REFRESH));
+ expect(withheld).toContain("cache_state");
+ expect(withheld).not.toContain(PRIVATE_PRINCIPLE);
+ });
+
+ test("remote reach: a bundle a local caller cached is not served", async () => {
+ const remoteRead = async (f: Fixture): Promise<string> => {
+ await answer(f, REFRESH, TRANSPORT_REACH.local);
+ return answer(f, { session_id: SESSION });
+ };
+ const withheld = await remoteRead(fixture(true));
+ expect(withheld).toBe(await remoteRead(fixture(false)));
+ expect(withheld).toContain("cache_state");
+ expect(withheld).not.toContain(PRIVATE_PRINCIPLE);
+ });
+
+ test("local reach: the cached bundle carries the withheld preference", async () => {
+ const f = fixture(true);
+ expect(await answer(f, REFRESH, TRANSPORT_REACH.local)).toContain(PRIVATE_PRINCIPLE);
+ expect(await answer(f, { session_id: SESSION }, TRANSPORT_REACH.local)).toContain(
+ PRIVATE_PRINCIPLE,
+ );
+ });
+});
diff --git a/tests/mcp/apply-evidence-reach.test.ts b/tests/mcp/apply-evidence-reach.test.ts
new file mode 100644
index 00000000..349645e1
--- /dev/null
+++ b/tests/mcp/apply-evidence-reach.test.ts
@@ -0,0 +1,110 @@
+/**
+ * `brain_apply_evidence` and the `apply_evidence` operation of
+ * `brain_write_batch` answer at the caller's reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a preference
+ * withheld from a remote caller by visibility; vault B never had it. A
+ * server with no reach minted is a remote caller: evidence against the
+ * withheld preference must be refused exactly as evidence against a
+ * missing one is, and no vault file may change. The local control proves
+ * the withheld preference is there to record evidence against.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_SLUG,
+ reachServer,
+ SHARED_SLUG,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const ARTIFACT = "[[Notes/artifact]]";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-apply-evidence-reach-"));
+ bases.push(base);
+ return buildReachLogFixture(base, withPrivate);
+}
+
+async function answer(
+ f: Fixture,
+ tool: string,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(tool, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every file under the vault with its bytes, so any write shows. */
+function vaultBytes(f: Fixture): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readdirSync(f.vault, { recursive: true, withFileTypes: true })) {
+ if (!entry.isFile()) continue;
+ const abs = join(entry.parentPath, entry.name);
+ out[abs] = readFileSync(abs, "utf8");
+ }
+ return out;
+}
+
+function evidenceArgs(prefId: string): Record<string, unknown> {
+ return { pref_id: prefId, artifact: ARTIFACT, result: "outdated" };
+}
+
+function batchArgs(prefId: string): Record<string, unknown> {
+ return { operations: [{ op: "apply_evidence", ...evidenceArgs(prefId) }] };
+}
+
+const ENTRY_POINTS = [
+ { tool: "brain_apply_evidence", args: evidenceArgs },
+ { tool: "brain_write_batch", args: batchArgs },
+] as const;
+
+describe("apply-evidence writers answer at the caller's reach", () => {
+ for (const { tool, args } of ENTRY_POINTS) {
+ for (const id of [`pref-${PRIVATE_SLUG}`, PRIVATE_SLUG]) {
+ test(`${tool}: remote reach refuses ${id} as a missing preference`, async () => {
+ const a = fixture(true);
+ const before = vaultBytes(a);
+ const withheld = await answer(a, tool, args(id));
+ expect(withheld).toBe(await answer(fixture(false), tool, args(id)));
+ expect(withheld).toContain(`preference not found: pref-${PRIVATE_SLUG}`);
+ expect(vaultBytes(a)).toEqual(before);
+ });
+ }
+
+ test(`${tool}: remote reach still records evidence on a readable preference`, async () => {
+ const withheld = await answer(fixture(true), tool, args(`pref-${SHARED_SLUG}`));
+ expect(withheld).toBe(await answer(fixture(false), tool, args(`pref-${SHARED_SLUG}`)));
+ expect(withheld).toContain("logged_at");
+ });
+
+ test(`${tool}: local control records evidence on the withheld preference`, async () => {
+ const a = fixture(true);
+ const local = await answer(a, tool, args(`pref-${PRIVATE_SLUG}`), TRANSPORT_REACH.local);
+ expect(local).toContain("logged_at");
+ expect(local).not.toContain("not found");
+ });
+ }
+});
diff --git a/tests/mcp/brain-calendar-tools.test.ts b/tests/mcp/brain-calendar-tools.test.ts
index 3d9b2f2c..4452aa4f 100644
--- a/tests/mcp/brain-calendar-tools.test.ts
+++ b/tests/mcp/brain-calendar-tools.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
@@ -12,7 +13,9 @@ let ctx: ServerContext;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "osb-calendar-tool-"));
mkdirSync(join(tmp, "Brain"), { recursive: true });
- ctx = { vault: tmp, configPath: null, repoRoot: null };
+ // The operator's own shell: a remote caller is answered without the
+ // archive name (tests/mcp/obligation-reach.test.ts, intention-reach).
+ ctx = { vault: tmp, configPath: null, repoRoot: null, reach: TRANSPORT_REACH.local };
});
afterEach(() => {
diff --git a/tests/mcp/brain-context-scoped-rules.test.ts b/tests/mcp/brain-context-scoped-rules.test.ts
new file mode 100644
index 00000000..b79f67d3
--- /dev/null
+++ b/tests/mcp/brain-context-scoped-rules.test.ts
@@ -0,0 +1,356 @@
+/**
+ * `brain_context` renders the scoped operator rules - one file per axis
+ * under `Brain/standing-rules/{project,harness,host}/` - for the scope the
+ * SERVER resolved, and only at local reach.
+ *
+ * Every case is an A/B probe through the real `MCPServer`: the vault with
+ * a scoped file that does not match this server's scope must answer
+ * byte-identically (after the generation stamp is normalised) to the same
+ * vault without that file. A match renders the file after the operator
+ * standing rules and before the memory body. At remote reach the layer is
+ * skipped entirely: the server's working directory and device are not the
+ * caller's, so the file must leave no trace on the wire.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import type { MCPServerRuntimeOptions } from "../../src/mcp/server.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { STANDING_RULES_HEADER } from "../../src/core/brain/standing-rules.ts";
+import {
+ SCOPED_RULES_HEADER,
+ SCOPED_RULES_HOST_UNREADABLE_NOTICE,
+} from "../../src/core/brain/scoped-rules.ts";
+import { resolveInstallationSecret } from "../../src/core/config.ts";
+import { writeVaultPointer } from "../../src/core/brain/portability/pointer.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
+
+let tmp: string;
+let vault: string;
+let projectX: string;
+let projectY: string;
+let configHome: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+const STANDING = "Never force-push to main.";
+const MARKER = "zzscopedmarkerzz keep the changelog terse";
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-scoped-"));
+ vault = join(tmp, "vault");
+ for (const dir of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", dir), { recursive: true });
+ }
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ writeFileSync(join(vault, "Brain", "standing-rules.md"), STANDING, "utf8");
+ // Two linked projects whose basenames key to `proj-x` and `proj-y`.
+ projectX = join(tmp, "proj-x");
+ projectY = join(tmp, "proj-y");
+ for (const dir of [projectX, projectY]) {
+ mkdirSync(join(dir, "src"), { recursive: true });
+ writeVaultPointer(dir, vault);
+ }
+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-scoped-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ for (const k of [
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "VAULT_DIR",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ "O2B_DEVICE_ID",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ process.env["O2B_DEVICE_ID"] = "";
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+function writeScoped(axis: "project" | "harness" | "host", key: string, body: string): string {
+ const dir = join(vault, "Brain", "standing-rules", axis);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${key}.md`);
+ writeFileSync(path, body, "utf8");
+ return path;
+}
+
+async function callContext(runtime: MCPServerRuntimeOptions): Promise<Record<string, unknown>> {
+ const server = new MCPServer({ vault, configPath }, runtime);
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "scoped-rules-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_context", arguments: {} },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(r.result.content[0]!.text);
+}
+
+/** The wire text with every generation stamp replaced, so two calls compare. */
+function normalised(out: Record<string, unknown>): string {
+ return JSON.stringify(out)
+ .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?/g, "<ts>")
+ .replaceAll("\\\\", "/");
+}
+
+/** Call once with the file present and once with it removed; both normalised. */
+async function abProbe(
+ runtime: MCPServerRuntimeOptions,
+ write: () => string,
+): Promise<{ withFile: string; withoutFile: string }> {
+ const path = write();
+ const withFile = normalised(await callContext(runtime));
+ rmSync(path);
+ const withoutFile = normalised(await callContext(runtime));
+ return { withFile, withoutFile };
+}
+
+const LOCAL = TRANSPORT_REACH.local;
+
+interface ScopedRulesKey {
+ readonly scope: {
+ readonly project: string | null;
+ readonly harness: string | null;
+ readonly host: string | null;
+ };
+ readonly files: ReadonlyArray<{ path: string; axis: string; truncated: boolean }>;
+}
+
+describe("brain_context scoped rules - project axis", () => {
+ test("a file for another project leaves the answer byte-identical", async () => {
+ const { withFile, withoutFile } = await abProbe(
+ { reach: LOCAL, workspaceDir: join(projectY, "src") },
+ () => writeScoped("project", "proj-x", MARKER),
+ );
+ expect(withFile).not.toContain("zzscopedmarkerzz");
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("the matching project renders after the standing rules and before the memory body", async () => {
+ writeScoped("project", "proj-x", MARKER);
+ const out = await callContext({ reach: LOCAL, workspaceDir: join(projectX, "src") });
+ const content = out["content"] as string;
+ const standingAt = content.indexOf(STANDING_RULES_HEADER);
+ const scopedAt = content.indexOf(SCOPED_RULES_HEADER);
+ const markerAt = content.indexOf("zzscopedmarkerzz");
+ const bodyAt = content.indexOf("# Active Brain Preferences");
+ expect(standingAt).toBe(0);
+ expect(scopedAt).toBeGreaterThan(standingAt);
+ expect(markerAt).toBeGreaterThan(scopedAt);
+ expect(content).toContain("### Project: proj-x");
+ expect(bodyAt).toBeGreaterThan(markerAt);
+ const field = out["scoped_rules"] as ScopedRulesKey;
+ expect(field.scope).toEqual({ project: "proj-x", harness: null, host: null });
+ expect(field.files).toEqual([
+ { path: "Brain/standing-rules/project/proj-x.md", axis: "project", truncated: false },
+ ]);
+ });
+
+ test("no matching file omits the key and adds no block", async () => {
+ const out = await callContext({ reach: LOCAL, workspaceDir: join(projectX, "src") });
+ expect("scoped_rules" in out).toBe(false);
+ expect(out["content"] as string).not.toContain(SCOPED_RULES_HEADER);
+ });
+
+ test("the absolute vault path never appears in the scoped block", async () => {
+ writeScoped("project", "proj-x", MARKER);
+ const out = await callContext({ reach: LOCAL, workspaceDir: projectX });
+ const content = out["content"] as string;
+ const block = content.slice(content.indexOf(SCOPED_RULES_HEADER));
+ expect(block).not.toContain(vault);
+ // JSON escapes a Windows backslash: compare against the escaped form too.
+ const field = JSON.stringify(out["scoped_rules"]);
+ expect(field).not.toContain(vault);
+ expect(field).not.toContain(JSON.stringify(vault).slice(1, -1));
+ });
+});
+
+describe("brain_context scoped rules - harness axis", () => {
+ test("a file for another harness leaves the answer byte-identical", async () => {
+ const { withFile, withoutFile } = await abProbe({ reach: LOCAL, harness: "codex" }, () =>
+ writeScoped("harness", "cursor", MARKER),
+ );
+ expect(withFile).not.toContain("zzscopedmarkerzz");
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("the launch harness renders its file", async () => {
+ writeScoped("harness", "cursor", MARKER);
+ const out = await callContext({ reach: LOCAL, harness: "cursor" });
+ expect(out["content"] as string).toContain("### Harness: cursor");
+ expect(out["content"] as string).toContain("zzscopedmarkerzz");
+ expect((out["scoped_rules"] as ScopedRulesKey).scope.harness).toBe("cursor");
+ });
+
+ test("the host target is the harness when no --harness was given", async () => {
+ writeScoped("harness", "cursor", MARKER);
+ const out = await callContext({ reach: LOCAL, hostTarget: "cursor" });
+ expect(out["content"] as string).toContain("zzscopedmarkerzz");
+ });
+});
+
+describe("brain_context scoped rules - host axis", () => {
+ test("a file for another device leaves the answer byte-identical", async () => {
+ process.env["O2B_DEVICE_ID"] = "aaaa0001";
+ const { withFile, withoutFile } = await abProbe({ reach: LOCAL }, () =>
+ writeScoped("host", "bbbb0002", MARKER),
+ );
+ expect(withFile).not.toContain("zzscopedmarkerzz");
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("this device's file renders", async () => {
+ process.env["O2B_DEVICE_ID"] = "aaaa0001";
+ writeScoped("host", "aaaa0001", MARKER);
+ const out = await callContext({ reach: LOCAL });
+ expect(out["content"] as string).toContain("### Host: aaaa0001");
+ const field = out["scoped_rules"] as ScopedRulesKey;
+ expect(field.scope.host).toBe("aaaa0001");
+ expect(field.files.map((f) => f.path)).toEqual(["Brain/standing-rules/host/aaaa0001.md"]);
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a device id that cannot be stored renders the host notice and the key",
+ async () => {
+ // The config is readable and holds no device id, and its directory
+ // cannot be written, so the first-use id cannot be persisted: the
+ // call still succeeds and says host-scoped rules were not applied.
+ delete process.env["O2B_DEVICE_ID"];
+ resolveInstallationSecret(configPath);
+ writeScoped("host", "aaaa0001", MARKER);
+ chmodSync(configHome, 0o555);
+ try {
+ const out = await callContext({ reach: LOCAL });
+ expect(out["content"] as string).toContain(SCOPED_RULES_HOST_UNREADABLE_NOTICE);
+ expect(out["content"] as string).not.toContain(MARKER);
+ const field = out["scoped_rules"] as ScopedRulesKey;
+ expect(field.scope.host).toBeNull();
+ expect(field.files).toEqual([]);
+ } finally {
+ chmodSync(configHome, 0o755);
+ }
+ },
+ );
+
+ test("the empty device id opts out silently", async () => {
+ process.env["O2B_DEVICE_ID"] = "";
+ const { withFile, withoutFile } = await abProbe({ reach: LOCAL }, () =>
+ writeScoped("host", "aaaa0001", MARKER),
+ );
+ expect(withFile).toBe(withoutFile);
+ });
+});
+
+describe("brain_context scoped rules - remote reach", () => {
+ test("a matching project file leaves no trace at remote reach", async () => {
+ const { withFile, withoutFile } = await abProbe(
+ { workspaceDir: projectX, harness: "cursor" },
+ () => writeScoped("project", "proj-x", MARKER),
+ );
+ expect(withFile).not.toContain("zzscopedmarkerzz");
+ expect(withFile).not.toContain("scoped_rules");
+ expect(withFile).toBe(withoutFile);
+ });
+
+ test("a matching harness and host file leave no trace at remote reach", async () => {
+ process.env["O2B_DEVICE_ID"] = "aaaa0001";
+ const { withFile, withoutFile } = await abProbe({ harness: "cursor" }, () => {
+ writeScoped("host", "aaaa0001", MARKER);
+ return writeScoped("harness", "cursor", MARKER);
+ });
+ // The host file is still on disk in the B arm: remove it too so the
+ // probe compares the vault with neither file against both.
+ expect(withFile).not.toContain("zzscopedmarkerzz");
+ rmSync(join(vault, "Brain", "standing-rules"), { recursive: true, force: true });
+ const bare = normalised(await callContext({ harness: "cursor" }));
+ expect(withFile).toBe(bare);
+ expect(withoutFile).toBe(bare);
+ });
+});
+
+describe("brain_context scoped rules - gaps closed by the test audit", () => {
+ test("the configured cap trims the block and marks the file truncated", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nactive:\n scoped_rules_max_chars: 200\n",
+ );
+ writeScoped("project", "proj-x", `${MARKER} ${"x".repeat(5000)}`);
+ const out = await callContext({ reach: LOCAL, workspaceDir: projectX });
+ expect(out["content"] as string).toContain("_Scoped rules truncated to the configured cap:");
+ expect((out["scoped_rules"] as ScopedRulesKey).files).toEqual([
+ { path: "Brain/standing-rules/project/proj-x.md", axis: "project", truncated: true },
+ ]);
+ });
+
+ test("remote reach with every axis matching leaves no trace", async () => {
+ process.env["O2B_DEVICE_ID"] = "aaaa0001";
+ writeScoped("project", "proj-x", MARKER);
+ writeScoped("host", "aaaa0001", MARKER);
+ writeScoped("harness", "cursor", MARKER);
+ const runtime = { workspaceDir: projectX, harness: "cursor" as const };
+ const withFiles = normalised(await callContext(runtime));
+ rmSync(join(vault, "Brain", "standing-rules"), { recursive: true, force: true });
+ expect(withFiles).not.toContain("zzscopedmarkerzz");
+ expect(withFiles).toBe(normalised(await callContext(runtime)));
+ });
+});
+
+describe("brain_context scoped rules - a symlink leaving the vault", () => {
+ test.skipIf(!canSymlink())(
+ "a symlinked axis folder renders the UNAVAILABLE line and keeps the constitution",
+ async () => {
+ const outside = mkdtempSync(join(tmp, "outside-"));
+ writeFileSync(join(outside, "proj-x.md"), "zzoutsidezz");
+ mkdirSync(join(vault, "Brain", "standing-rules"), { recursive: true });
+ symlinkSync(outside, join(vault, "Brain", "standing-rules", "project"), "dir");
+ const out = await callContext({ reach: LOCAL, workspaceDir: projectX });
+ const content = out["content"] as string;
+ expect(content).toContain(STANDING);
+ expect(content).toContain(
+ "UNAVAILABLE: Brain/standing-rules/project/proj-x.md could not be read (ESCAPE).",
+ );
+ expect(content).not.toContain("zzoutsidezz");
+ expect(content).not.toContain(vault);
+ expect(JSON.stringify(content)).not.toContain(JSON.stringify(vault).slice(1, -1));
+ },
+ );
+});
+
+/** Symlinks need a privilege Windows CI does not grant; probe once per call. */
+function canSymlink(): boolean {
+ const dir = mkdtempSync(join(tmpdir(), "o2b-symlink-probe-"));
+ try {
+ symlinkSync(join(dir, "missing"), join(dir, "link"), "dir");
+ return true;
+ } catch {
+ return false;
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
diff --git a/tests/mcp/brain-governance.test.ts b/tests/mcp/brain-governance.test.ts
index 91a6ae05..c5c8d8e2 100644
--- a/tests/mcp/brain-governance.test.ts
+++ b/tests/mcp/brain-governance.test.ts
@@ -6,7 +6,7 @@
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -16,6 +16,7 @@ import { resetFreezeMarkerCache } from "../../src/core/brain/freeze-marker.ts";
import { setSecret } from "../../src/core/brain/secrets/store.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { MAINTENANCE_RUN_LOCAL_ONLY } from "../../src/mcp/brain/admin-tools.ts";
let tmp: string;
let vault: string;
@@ -246,7 +247,8 @@ test("brain_secrets lists metadata only and refuses a non-allowlisted run", asyn
});
test("brain_maintenance run executes the lane; status reads the journal", async () => {
- const server = new MCPServer({ vault, configPath });
+ // A lane run is the operator's own operation: local reach only.
+ const server = new MCPServer({ vault, configPath }, { reach: "local" });
await initialize(server);
const ran = await call(server, "brain_maintenance", { operation: "run" });
expect(ran["verdict"]).toBe("run");
@@ -259,3 +261,40 @@ test("brain_maintenance run executes the lane; status reads the journal", async
expect(status["lease"]).toBeNull();
expect((status["journal"] as unknown[]).length).toBeGreaterThanOrEqual(2);
});
+
+test("brain_maintenance run is allowed at local reach when the owner scope gate is enforced", async () => {
+ // The guard is the transport reach, not the owner gate: a local caller
+ // with `owner_scope_delivery: fail` is still the operator.
+ const brainYaml = join(vault, "Brain", "_brain.yaml");
+ const existing = readFileSync(brainYaml, "utf8");
+ if (/^integrity:/m.test(existing)) throw new Error("fixture already has an integrity block");
+ writeFileSync(brainYaml, `${existing.trimEnd()}\nintegrity:\n owner_scope_delivery: fail\n`);
+ const server = new MCPServer({ vault, configPath }, { reach: "local" });
+ await initialize(server);
+ const ran = await call(server, "brain_maintenance", { operation: "run", force: true });
+ expect(ran["verdict"]).toBe("run");
+});
+
+/** Every file under `root` with its bytes. */
+function treeBytes(root: string, rel = ""): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
+ const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
+ if (entry.isDirectory()) Object.assign(out, treeBytes(root, child));
+ else out[child] = readFileSync(join(root, child), "utf8");
+ }
+ return out;
+}
+
+test("brain_maintenance run is refused below local reach before the lease or any write", async () => {
+ const before = treeBytes(vault);
+ const server = new MCPServer({ vault, configPath }, { reach: "remote" });
+ await initialize(server);
+ await expect(
+ call(server, "brain_maintenance", { operation: "run", force: true }),
+ ).rejects.toThrow(MAINTENANCE_RUN_LOCAL_ONLY);
+ expect(treeBytes(vault)).toEqual(before);
+ // Reading the lane's state is not a run, and stays open.
+ const status = await call(server, "brain_maintenance", { operation: "status" });
+ expect(status["lease"]).toBeNull();
+});
diff --git a/tests/mcp/brain-intention-tool.test.ts b/tests/mcp/brain-intention-tool.test.ts
index 28c2867f..d6a6ac9a 100644
--- a/tests/mcp/brain-intention-tool.test.ts
+++ b/tests/mcp/brain-intention-tool.test.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
@@ -12,7 +13,9 @@ let ctx: ServerContext;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "osb-intention-tool-"));
mkdirSync(join(tmp, "Brain"), { recursive: true });
- ctx = { vault: tmp, configPath: null, repoRoot: null };
+ // The operator's own shell: a remote caller is answered without the
+ // archive name (tests/mcp/obligation-reach.test.ts, intention-reach).
+ ctx = { vault: tmp, configPath: null, repoRoot: null, reach: TRANSPORT_REACH.local };
});
afterEach(() => {
diff --git a/tests/mcp/brain-standing-rules-uneditable.test.ts b/tests/mcp/brain-standing-rules-uneditable.test.ts
index d1064831..a3da9e73 100644
--- a/tests/mcp/brain-standing-rules-uneditable.test.ts
+++ b/tests/mcp/brain-standing-rules-uneditable.test.ts
@@ -42,7 +42,10 @@ import {
assertStandingRulesNotTargeted,
StandingRulesWriteRefusedError,
} from "../../src/core/brain/standing-rules.ts";
-import { BRAIN_STANDING_RULES_FILE } from "../../src/core/brain/path-constants.ts";
+import {
+ BRAIN_SCOPED_RULES_DIR,
+ BRAIN_STANDING_RULES_FILE,
+} from "../../src/core/brain/path-constants.ts";
let tmp: string;
let vault: string;
@@ -52,6 +55,8 @@ const savedEnv: Record<string, string | undefined> = {};
const RULES_REL = `Brain/${BRAIN_STANDING_RULES_FILE}`;
const RULES_BYTES = "Never force-push to main.\nAsk before deleting anything under Archive/.\n";
+const SCOPED_REL = `Brain/${BRAIN_SCOPED_RULES_DIR}/project/x.md`;
+const SCOPED_BYTES = "Run the project linter before every commit.\n";
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-standing-uneditable-"));
@@ -61,6 +66,8 @@ beforeEach(() => {
}
writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
writeFileSync(join(vault, RULES_REL), RULES_BYTES, "utf8");
+ mkdirSync(join(vault, "Brain", BRAIN_SCOPED_RULES_DIR, "project"), { recursive: true });
+ writeFileSync(join(vault, SCOPED_REL), SCOPED_BYTES, "utf8");
configHome = mkdtempSync(join(tmpdir(), "o2b-standing-uneditable-cfg-"));
configPath = join(configHome, "config.yaml");
for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
@@ -115,6 +122,10 @@ function onDiskBytes(): string {
return readFileSync(join(vault, RULES_REL), "utf8");
}
+function scopedOnDiskBytes(): string {
+ return readFileSync(join(vault, SCOPED_REL), "utf8");
+}
+
/** The four tools that address a note by a path the caller names. */
const CALLER_NAMED_WRITE_TOOLS: ReadonlyArray<{
readonly tool: string;
@@ -156,19 +167,23 @@ describe("Brain/standing-rules.md is uneditable through every caller-named write
expect((thrown as CreateNoteError).message).toContain(RULES_REL);
});
- test("no tool name, description, or schema property description mentions the file", () => {
+ test("no tool name, description, or schema property description mentions the file or the scoped directory", () => {
+ // The scoped directory is matched with its trailing separator: the
+ // bare stem is also the stem of the constitution file name, which the
+ // first needle already covers.
+ const needles = [BRAIN_STANDING_RULES_FILE, `${BRAIN_SCOPED_RULES_DIR}/`];
const offenders: string[] = [];
for (const tool of buildToolTable("full")) {
const places: Array<[string, string]> = [
[`${tool.name} (name)`, tool.name],
[`${tool.name} (description)`, tool.description],
];
- for (const [label, text] of places) {
- if (text.includes(BRAIN_STANDING_RULES_FILE)) offenders.push(label);
- }
for (const [prop, description] of schemaDescriptions(tool.inputSchema)) {
- if (description.includes(BRAIN_STANDING_RULES_FILE)) {
- offenders.push(`${tool.name}.${prop}`);
+ places.push([`${tool.name}.${prop}`, description]);
+ }
+ for (const [label, text] of places) {
+ for (const needle of needles) {
+ if (text.includes(needle)) offenders.push(`${label}: ${needle}`);
}
}
}
@@ -269,10 +284,72 @@ describe("brain_labels cannot rewrite the standing-rules file", () => {
test("the guard lets every other note through", () => {
// Narrow by construction: several legitimate callers write into
// `Brain/` through the same resolver (marker write-back, tombstones,
- // temporal replace), so this guard names one file and no directory.
- expect(() =>
- assertStandingRulesNotTargeted(vault, "Brain/preferences/pref-x.md", "test surface"),
- ).not.toThrow();
+ // temporal replace), so this guard names the constitution file and
+ // the scoped-rules directory beside it, and nothing else.
+ for (const other of [
+ "Brain/preferences/pref-x.md",
+ "Brain/standing-rules-notes.md",
+ "Notes/standing-rules/x.md",
+ ]) {
+ expect(() => assertStandingRulesNotTargeted(vault, other, "test surface")).not.toThrow();
+ }
+ });
+});
+
+/**
+ * The scoped operator rules (`Brain/standing-rules/<axis>/<key>.md`) are
+ * the constitution's per-project, per-harness and per-host companions and
+ * are exactly as uneditable: the four caller-named write tools inherit the
+ * `Brain/` refusal, and `brain_labels` - the one surface outside that
+ * envelope - is refused by the directory arm of the standing-rules guard.
+ */
+describe("the scoped standing-rules directory is uneditable", () => {
+ const SCOPED_WRITES: ReadonlyArray<{
+ readonly tool: string;
+ readonly args: Record<string, unknown>;
+ }> = Object.freeze([
+ { tool: "brain_create_note", args: { path: SCOPED_REL, content: "OVERWRITTEN" } },
+ { tool: "brain_update_note", args: { path: SCOPED_REL, content: "OVERWRITTEN" } },
+ { tool: "brain_append_note", args: { path: SCOPED_REL, content: "OVERWRITTEN" } },
+ {
+ tool: "brain_write_batch",
+ args: { operations: [{ op: "update_note", path: SCOPED_REL, content: "OVERWRITTEN" }] },
+ },
+ ]);
+
+ for (const { tool, args } of SCOPED_WRITES) {
+ test(`${tool} refuses a scoped rule file and leaves its bytes unchanged`, async () => {
+ const text = outcomeText(await callTool(tool, args));
+ expect(text).not.toContain("OVERWRITTEN");
+ expect(text).toContain(SCOPED_REL);
+ expect(text).toContain("Brain machinery root");
+ expect(scopedOnDiskBytes()).toBe(SCOPED_BYTES);
+ });
+ }
+
+ for (const args of [
+ { operation: "assign", path: SCOPED_REL, dimension: "status", value: "draft" },
+ { operation: "remove", path: SCOPED_REL, dimension: "status" },
+ ] as ReadonlyArray<Record<string, unknown>>) {
+ test(`brain_labels ${String(args["operation"])} is refused on a scoped rule file`, async () => {
+ const out = await callTool("brain_labels", args);
+ // Refused by the standing-rules guard, not by an incidental check
+ // (an unknown label dimension, a missing frontmatter block): the
+ // guard's own wording is what this row pins.
+ expect(out.result).toBeUndefined();
+ expect(out.error?.message ?? "").toContain("standing-rules file");
+ expect(scopedOnDiskBytes()).toBe(SCOPED_BYTES);
+ });
+ }
+
+ test("the guard refuses a scoped rule path directly", () => {
+ let thrown: unknown;
+ try {
+ assertStandingRulesNotTargeted(vault, SCOPED_REL, "test surface");
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(StandingRulesWriteRefusedError);
});
});
diff --git a/tests/mcp/brain-trust-mcp-fields.test.ts b/tests/mcp/brain-trust-mcp-fields.test.ts
index 813a20a8..97ca3d54 100644
--- a/tests/mcp/brain-trust-mcp-fields.test.ts
+++ b/tests/mcp/brain-trust-mcp-fields.test.ts
@@ -11,6 +11,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { resetVaultIdentityPins, writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
@@ -83,7 +84,8 @@ async function callTool(
describe("brain_dream MCP wrapper - trust fields", () => {
test("no-op run emits empty uncertain[] and quarantined[]", async () => {
- const server = new MCPServer({ vault, configPath });
+ // A real dream pass runs at local reach only.
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await initialize(server);
const out = await callTool(server, "brain_dream", {});
expect(out["uncertain"]).toEqual([]);
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index 1e7ddcfe..57502be4 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -25,6 +25,7 @@ import {
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
@@ -103,7 +104,8 @@ async function call(
}
function makeServer(): MCPServer {
- return new MCPServer({ vault, configPath });
+ // The operator's own shell: a real dream pass runs at local reach only.
+ return new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
}
// ---------------------------------------------------------------------------
diff --git a/tests/mcp/brief-monthly-reach.test.ts b/tests/mcp/brief-monthly-reach.test.ts
new file mode 100644
index 00000000..25623dbb
--- /dev/null
+++ b/tests/mcp/brief-monthly-reach.test.ts
@@ -0,0 +1,95 @@
+/**
+ * `brain_brief view=monthly` counts at the caller's reach.
+ *
+ * The vault pair is tests/helpers/reach-log-fixture.ts: vault A holds a
+ * reserved preference with evidence inside both the 24-hour and the
+ * 30-day windows and a reserved record a dream confirmed and retired;
+ * vault B never had either. A server with no reach minted is a remote
+ * caller: its monthly summaries over the two vaults must be identical.
+ * The events of the fixture span the last three days, so every month
+ * they touch is asked. The local control proves the reserved records
+ * are there to count.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ DAY_MS,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-brief-monthly-reach-"));
+ bases.push(base);
+ return buildReachLogFixture(base, withPrivate);
+}
+
+/** Every month the fixture's events fall in: the recent day and three days back. */
+function months(): ReadonlyArray<string> {
+ const now = Date.now();
+ const touched = [now - DAY_MS / 24, now - 3 * DAY_MS].map((ms) =>
+ new Date(ms).toISOString().slice(0, 7),
+ );
+ return [...new Set(touched)];
+}
+
+interface Summary {
+ readonly events: number;
+ readonly status_transitions: number;
+ readonly retired: number;
+ readonly contradictions: number;
+ readonly neglected_areas: ReadonlyArray<string>;
+}
+
+async function summaries(f: Fixture, reach?: TransportReach): Promise<Summary[]> {
+ const server = reachServer(f, reach);
+ const out: Summary[] = [];
+ for (const month of months()) {
+ // oxlint-disable-next-line no-await-in-loop -- one server, months in order
+ const result = (await server.callTool("brain_brief", { view: "monthly", month })) as Record<
+ string,
+ unknown
+ >;
+ const body = (result["structuredContent"] ?? result) as Record<string, unknown>;
+ out.push(body["summary"] as Summary);
+ }
+ return out;
+}
+
+function sum(list: ReadonlyArray<Summary>, key: "events" | "retired" | "contradictions"): number {
+ return list.reduce((n, s) => n + s[key], 0);
+}
+
+describe("brain_brief view=monthly counts at the caller's reach", () => {
+ test("remote reach: the reserved records move no count", async () => {
+ const b = fixture(false);
+ const remoteA = await summaries(fixture(true));
+ const remoteB = await summaries(b);
+ expect(remoteA).toEqual(remoteB);
+ // Vault B holds nothing to withhold: the remote answer is the local one.
+ expect(remoteB).toEqual(await summaries(b, TRANSPORT_REACH.local));
+ });
+
+ test("local control: the operator's own shell counts the reserved records", async () => {
+ const localA = await summaries(fixture(true), TRANSPORT_REACH.local);
+ const localB = await summaries(fixture(false), TRANSPORT_REACH.local);
+ expect(sum(localA, "events")).toBeGreaterThan(sum(localB, "events"));
+ expect(sum(localA, "retired")).toBeGreaterThan(sum(localB, "retired"));
+ expect(sum(localA, "contradictions")).toBeGreaterThan(sum(localB, "contradictions"));
+ });
+});
diff --git a/tests/mcp/brief-operator-reach.test.ts b/tests/mcp/brief-operator-reach.test.ts
new file mode 100644
index 00000000..33e82ea8
--- /dev/null
+++ b/tests/mcp/brief-operator-reach.test.ts
@@ -0,0 +1,161 @@
+/**
+ * `brain_brief view=operator` answers its doctor, digest, top-action and
+ * trust-verdict fields at the caller's reach.
+ *
+ * The vault pair is tests/helpers/reach-log-fixture.ts: vault A holds a
+ * reserved preference with evidence inside both the 24-hour and the
+ * 30-day windows and a reserved retired record; vault B never had them.
+ * Vault A also holds two withheld near-duplicate preferences, which the
+ * maintenance scan ranks as a merge action naming one of them, the
+ * doctor-count items of tests/mcp/doctor-counts-reach.test.ts (50
+ * withheld Brain pages naming a removed tool and a withheld state whose
+ * validity closed), and a vault-root AGENTS.md over the instruction-file
+ * ceiling, withheld by its frontmatter. A server with no reach minted is
+ * a remote caller: the whole masked answer over the two vaults must be
+ * identical, the verification entries the dry-run dream yields over the
+ * twins included. The dream's own warning, uncertain and quarantined
+ * counts (`dream_summary`) name no record and are a stated residual, so
+ * that one field is left out. The local control proves the withheld
+ * records are there to count.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TWIN_SLUGS = ["zzwithheld-twin-a", "zzwithheld-twin-b"] as const;
+/** The one field left out of the comparison: a stated residual that names no record. */
+const RESIDUAL = "dream_summary";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+/** A tool the product no longer ships, which the doctor reports when a page names it. */
+const REMOVED_TOOL = "brain_digest";
+const WITHHELD_PAGE_COUNT = 50;
+const WITHHELD_PAGE_PREFIX = "zzwithheld-memo";
+/** A vault-root instruction file the operator view measures against its ceiling. */
+const INSTRUCTION_FILE = "AGENTS.md";
+/** Over the default `guardrails.instruction_file_max_lines` of 200. */
+const INSTRUCTION_FILE_LINES = 250;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+/** A withheld confirmed preference whose principle its twin repeats. */
+function withheldTwin(vault: string, slug: string): void {
+ const path = writePreference(vault, {
+ slug,
+ topic: "twin",
+ principle: "Always run the formatter before every commit in this repository.",
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ });
+ const abs =
+ typeof path === "string" ? path : join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ const text = readFileSync(abs, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(
+ abs,
+ `${text.slice(0, close)}\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]${text.slice(close)}`,
+ );
+}
+
+/** The withheld items the doctor counts before any finding is filtered. */
+function withheldDoctorItems(vault: string): void {
+ const dir = join(vault, "Brain", "memos");
+ mkdirSync(dir, { recursive: true });
+ for (let i = 0; i < WITHHELD_PAGE_COUNT; i++) {
+ writeFileSync(
+ join(dir, `${WITHHELD_PAGE_PREFIX}-${String(i).padStart(2, "0")}.md`),
+ `---\n${RESERVE_LINE}\n---\n# memo ${i}\n\nCall ${REMOVED_TOOL} for the summary.\n`,
+ );
+ }
+ writeFileSync(
+ join(vault, "Brain", "zzwithheld-closed.md"),
+ `---\n${RESERVE_LINE}\nvalid_until: 2026-01-01T00:00:00Z\n---\n# closed\n`,
+ );
+}
+
+/** A withheld vault-root instruction file over the ceiling. */
+function withheldInstructionFile(vault: string): void {
+ const body = Array.from({ length: INSTRUCTION_FILE_LINES }, (_, i) => `- rule ${i}`);
+ writeFileSync(join(vault, INSTRUCTION_FILE), `---\n${RESERVE_LINE}\n---\n${body.join("\n")}\n`);
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-brief-operator-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ if (withPrivate) {
+ for (const slug of TWIN_SLUGS) withheldTwin(f.vault, slug);
+ withheldDoctorItems(f.vault);
+ withheldInstructionFile(f.vault);
+ }
+ return f;
+}
+
+async function operator(f: Fixture, reach?: TransportReach): Promise<Record<string, unknown>> {
+ const result = (await reachServer(f, reach).callTool("brain_brief", {
+ view: "operator",
+ })) as Record<string, unknown>;
+ const body = (result["structuredContent"] ?? result) as Record<string, unknown>;
+ return JSON.parse(maskVolatile(f, body)) as Record<string, unknown>;
+}
+
+/** The whole answer without the stated residual. */
+function compared(answer: Record<string, unknown>): Record<string, unknown> {
+ const { [RESIDUAL]: _residual, ...rest } = answer;
+ return rest;
+}
+
+describe("brain_brief view=operator answers at the caller's reach", () => {
+ test("remote reach: the withheld records move nothing but the stated residual", async () => {
+ const withheld = compared(await operator(fixture(true)));
+ const absent = compared(await operator(fixture(false)));
+ expect(JSON.stringify(withheld)).toBe(JSON.stringify(absent));
+ expect(JSON.stringify(withheld)).not.toContain("zzwithheld");
+ expect(withheld["instruction_file_warnings"]).toEqual([]);
+ });
+
+ test("local control: the operator's own shell counts the withheld records", async () => {
+ const a = compared(await operator(fixture(true), TRANSPORT_REACH.local));
+ const b = compared(await operator(fixture(false), TRANSPORT_REACH.local));
+ // The trust verdict moves with the fixture, so its remote comparison
+ // above is not vacuous.
+ expect(a["trust_verdict"]).not.toEqual(b["trust_verdict"]);
+ expect(JSON.stringify(a["instruction_file_warnings"])).toContain(INSTRUCTION_FILE);
+ const digestA = a["digest_summary"] as Record<string, number>;
+ const digestB = b["digest_summary"] as Record<string, number>;
+ expect(digestA["preference_count"]).toBeGreaterThan(digestB["preference_count"]!);
+ expect(digestA["retired_count"]).toBeGreaterThan(digestB["retired_count"]!);
+ const doctorA = a["doctor_summary"] as Record<string, number>;
+ const doctorB = b["doctor_summary"] as Record<string, number>;
+ expect(doctorA["warning_count"]).toBeGreaterThan(doctorB["warning_count"]!);
+ expect(JSON.stringify(a["top_actions"])).toContain("zzwithheld");
+ expect(JSON.stringify(a["verification_delta"])).toContain("zzwithheld");
+ });
+});
diff --git a/tests/mcp/context-receipts-reach.test.ts b/tests/mcp/context-receipts-reach.test.ts
new file mode 100644
index 00000000..f20b608d
--- /dev/null
+++ b/tests/mcp/context-receipts-reach.test.ts
@@ -0,0 +1,324 @@
+/**
+ * `brain_context_receipts` answers at the caller's reach for the
+ * operator rules the SessionStart hook injected.
+ *
+ * The hook records a receipt item for the standing rules and the scoped
+ * rules, the scoped characters in its budget block, and whole-injection
+ * totals that include both blocks. Below local reach none of that may say
+ * whether operator rules applied or how long they were: a vault whose
+ * sessions injected the rules answers byte-identically (receipt ids,
+ * timestamps and the vault reference masked) to the same vault without
+ * them. At local reach the rules stay visible.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { writeVaultPointer } from "../../src/core/brain/portability/pointer.ts";
+import {
+ emitContextReceipt,
+ RECEIPT_ITEM_SCOPED_RULES,
+} from "../../src/core/brain/context-receipts.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import type { MCPServerRuntimeOptions } from "../../src/mcp/server.ts";
+import { homeEnv } from "../helpers/platform.ts";
+
+const HOOK = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "hooks",
+ "active-inject.ts",
+);
+const ACTIVE_BODY =
+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n" +
+ "# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` — Rule body\n";
+const OPERATOR_RULE_IDS = ["standing-rules", "scoped-rules"];
+
+let tmp: string;
+let configHome: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-receipts-reach-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-receipts-reach-cfg-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+/** Which pages a probe vault carries. */
+interface VaultShape {
+ /** `Brain/active.md`; true unless stated. */
+ readonly active?: boolean;
+ /** The constitution, `Brain/standing-rules.md`. */
+ readonly constitution?: boolean;
+ /** A project rule under `Brain/standing-rules/project/`. */
+ readonly scoped?: boolean;
+}
+
+/** A vault and a linked project; with `rules`, a constitution and a project rule. */
+function vaultFor(
+ name: string,
+ rules: boolean,
+ shape: VaultShape = { constitution: rules, scoped: rules },
+): { vault: string; project: string } {
+ const vault = join(tmp, name, "vault");
+ const project = join(tmp, name, "proj-x");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(project, { recursive: true });
+ if (shape.active !== false) writeFileSync(join(vault, "Brain", "active.md"), ACTIVE_BODY, "utf8");
+ writeVaultPointer(project, vault);
+ if (shape.constitution === true) {
+ writeFileSync(join(vault, "Brain", "standing-rules.md"), "Never force-push to main.", "utf8");
+ }
+ if (shape.scoped === true) {
+ mkdirSync(join(vault, "Brain", "standing-rules", "project"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "standing-rules", "project", "proj-x.md"),
+ "zzscopedreceiptzz keep the changelog terse",
+ "utf8",
+ );
+ }
+ return { vault, project };
+}
+
+async function runHook(vault: string, cwd: string): Promise<void> {
+ const proc = Bun.spawn(["bun", "run", HOOK], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ ...homeEnv(configHome),
+ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",
+ VAULT_DIR: vault,
+ O2B_DEVICE_ID: "",
+ },
+ });
+ proc.stdin.write(JSON.stringify({ hook_event_name: "SessionStart", cwd }));
+ await proc.stdin.end();
+ await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ expect(await proc.exited).toBe(0);
+}
+
+async function callReceipts(
+ vault: string,
+ runtime: MCPServerRuntimeOptions,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const configPath = join(dirname(vault), "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ const server = new MCPServer({ vault, configPath }, runtime);
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "receipts-reach-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_context_receipts", arguments: args },
+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };
+ return JSON.parse(r.result.content[0]!.text);
+}
+
+/** Every answer of the tool for the one receipt the hook wrote. */
+async function answers(
+ vault: string,
+ runtime: MCPServerRuntimeOptions,
+): Promise<Record<string, unknown>> {
+ const list = await callReceipts(vault, runtime, { operation: "list" });
+ const receipts = list["receipts"] as ReadonlyArray<{ id: string }>;
+ expect(receipts.length).toBe(1);
+ const id = receipts[0]!.id;
+ const show = await callReceipts(vault, runtime, { operation: "show", id });
+ const summary = await callReceipts(vault, runtime, { operation: "summary" });
+ return JSON.parse(JSON.stringify({ list, show, summary }).replaceAll(id, "<id>"));
+}
+
+/** Every answer of the tool for whatever receipts the vault holds, ids masked. */
+async function allAnswers(vault: string, runtime: MCPServerRuntimeOptions): Promise<string> {
+ const list = await callReceipts(vault, runtime, { operation: "list" });
+ const ids = (list["receipts"] as ReadonlyArray<{ id: string }>).map((r) => r.id);
+ const shows = await Promise.all(
+ ids.map((id) => callReceipts(vault, runtime, { operation: "show", id })),
+ );
+ const summary = await callReceipts(vault, runtime, { operation: "summary" });
+ let text = JSON.stringify({ list, shows, summary });
+ for (const id of ids) text = text.replaceAll(id, "<id>");
+ return masked(JSON.parse(text));
+}
+
+/** The `show` answer for one receipt id, or the refusal it gets. */
+async function showOrRefusal(
+ vault: string,
+ runtime: MCPServerRuntimeOptions,
+ id: string,
+): Promise<string> {
+ try {
+ return masked(await callReceipts(vault, runtime, { operation: "show", id }));
+ } catch {
+ return "refused";
+ }
+}
+
+function masked(value: unknown): string {
+ return JSON.stringify(value)
+ .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?/g, "<ts>")
+ .replace(/"vault_path":"[^"]*"/g, '"vault_path":"<vault>"');
+}
+
+async function abProbe(
+ runtime: MCPServerRuntimeOptions,
+): Promise<{ withRules: Record<string, unknown>; withoutRules: Record<string, unknown> }> {
+ const a = vaultFor("a", true);
+ const b = vaultFor("b", false);
+ await runHook(a.vault, a.project);
+ await runHook(b.vault, b.project);
+ return {
+ withRules: await answers(a.vault, runtime),
+ withoutRules: await answers(b.vault, runtime),
+ };
+}
+
+describe("brain_context_receipts and the operator rules", () => {
+ test("below local reach a session that injected the rules answers like one that did not", async () => {
+ const { withRules, withoutRules } = await abProbe({});
+ for (const id of OPERATOR_RULE_IDS) expect(JSON.stringify(withRules)).not.toContain(id);
+ expect(JSON.stringify(withRules)).not.toContain("scoped_rules_chars");
+ expect(masked(withRules)).toBe(masked(withoutRules));
+ });
+
+ test("at local reach the rules stay visible", async () => {
+ const { withRules, withoutRules } = await abProbe({ reach: TRANSPORT_REACH.local });
+ const show = withRules["show"] as { payload: Record<string, unknown> };
+ const ids = (show.payload["items"] as ReadonlyArray<{ id: string }>).map((item) => item.id);
+ expect(ids).toEqual(["standing-rules", "scoped-rules", "active-body"]);
+ const budget = show.payload["budget"] as Record<string, unknown>;
+ expect(budget["scoped_rules_chars"]).toBeGreaterThan(0);
+ expect(masked(withRules)).not.toBe(masked(withoutRules));
+ });
+
+ for (const shape of [
+ { constitution: true },
+ { scoped: true },
+ { constitution: true, scoped: true },
+ ]) {
+ test(`below local reach a vault with no active.md and rules ${JSON.stringify(shape)} answers like one without them`, async () => {
+ const a = vaultFor("a", true, { active: false, ...shape });
+ const b = vaultFor("b", false, { active: false });
+ await runHook(a.vault, a.project);
+ await runHook(b.vault, b.project);
+ const withRules = await allAnswers(a.vault, {});
+ expect(withRules).toBe(await allAnswers(b.vault, {}));
+ expect(withRules).not.toContain("inject_budget_chars");
+ // The local control: the operator sees the receipt the rules left.
+ const local = await callReceipts(
+ a.vault,
+ { reach: TRANSPORT_REACH.local },
+ {
+ operation: "list",
+ },
+ );
+ expect(local["total"]).toBe(1);
+ });
+ }
+
+ test("below local reach a rule-only receipt is refused by show as an unknown id", async () => {
+ const a = vaultFor("a", true, { active: false, scoped: true });
+ await runHook(a.vault, a.project);
+ const local = await callReceipts(
+ a.vault,
+ { reach: TRANSPORT_REACH.local },
+ {
+ operation: "list",
+ },
+ );
+ const id = (local["receipts"] as ReadonlyArray<{ id: string }>)[0]!.id;
+ expect(await showOrRefusal(a.vault, {}, id)).toBe("refused");
+ expect(await showOrRefusal(a.vault, {}, "ctx-unknown")).toBe("refused");
+ expect(await showOrRefusal(a.vault, { reach: TRANSPORT_REACH.local }, id)).not.toBe("refused");
+ });
+
+ test("below local reach the budget block leaves with the last budgeted source", async () => {
+ const a = vaultFor("a", false, { active: false });
+ const b = vaultFor("b", false, { active: false });
+ const notices = { id: "runtime-notices", bytes: 10, tokens: 3 };
+ emitContextReceipt(a.vault, {
+ options: { host: "hook", trigger: "session_inject", createdAt: "2026-09-01T00:00:00Z" },
+ items: [{ id: RECEIPT_ITEM_SCOPED_RULES, bytes: 40, tokens: 10 }, notices],
+ finalText: "notices and rules",
+ budget: { inject_budget_chars: 8000, budgeted_source_count: 1, scoped_rules_chars: 40 },
+ });
+ emitContextReceipt(b.vault, {
+ options: { host: "hook", trigger: "session_inject", createdAt: "2026-09-01T00:00:00Z" },
+ items: [notices],
+ finalText: "notices",
+ });
+ const withRules = await allAnswers(a.vault, {});
+ expect(withRules).toBe(await allAnswers(b.vault, {}));
+ expect(withRules).not.toContain("inject_budget_chars");
+ expect(await allAnswers(a.vault, { reach: TRANSPORT_REACH.local })).toContain(
+ "inject_budget_chars",
+ );
+ });
+
+ test("below local reach a degraded injection that kept only the rules reads as an empty one", async () => {
+ const a = vaultFor("a", false, { active: false });
+ const b = vaultFor("b", false, { active: false });
+ const degraded = {
+ extra: {
+ injection: { hook_event: "SessionStart", loader_source: "cached", sources_measured: false },
+ },
+ };
+ const options = {
+ host: "hook",
+ trigger: "session_inject",
+ createdAt: "2026-09-01T00:00:00Z",
+ } as const;
+ emitContextReceipt(a.vault, {
+ options,
+ items: [{ id: RECEIPT_ITEM_SCOPED_RULES, bytes: 40, tokens: 10 }],
+ finalText: "cached body and rules",
+ ...degraded,
+ });
+ emitContextReceipt(b.vault, { options, items: [], finalText: "cached body", ...degraded });
+ const withRules = await allAnswers(a.vault, {});
+ expect(withRules).toBe(await allAnswers(b.vault, {}));
+ expect(withRules).toContain('"empty_receipts":1');
+ });
+
+ test("below local reach a degraded injection with no cached body and only the rules is not there", async () => {
+ const a = vaultFor("a", false, { active: false });
+ const b = vaultFor("b", false, { active: false });
+ emitContextReceipt(a.vault, {
+ options: { host: "hook", trigger: "session_inject", createdAt: "2026-09-01T00:00:00Z" },
+ items: [{ id: RECEIPT_ITEM_SCOPED_RULES, bytes: 40, tokens: 10 }],
+ finalText: "rules only",
+ extra: {
+ injection: { hook_event: "SessionStart", loader_source: "empty", sources_measured: false },
+ },
+ });
+ expect(await allAnswers(a.vault, {})).toBe(await allAnswers(b.vault, {}));
+ const local = await callReceipts(
+ a.vault,
+ { reach: TRANSPORT_REACH.local },
+ { operation: "list" },
+ );
+ expect(local["total"]).toBe(1);
+ });
+});
diff --git a/tests/mcp/dead-ends-reach.test.ts b/tests/mcp/dead-ends-reach.test.ts
new file mode 100644
index 00000000..8e782fae
--- /dev/null
+++ b/tests/mcp/dead-ends-reach.test.ts
@@ -0,0 +1,148 @@
+/**
+ * `brain_dead_ends` answers at the caller's reach.
+ *
+ * Vault A holds a dead end withheld from a remote caller by visibility
+ * beside a readable one; vault B holds only the readable one. A server
+ * with no reach minted is a remote caller: `list` must read alike over
+ * both vaults, and `record` must name no archived id nor move a withheld
+ * page into the archive when it trims the active set. The local control
+ * proves the withheld dead end is there to list.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { DEAD_END_MAX_ACTIVE, recordDeadEnd } from "../../src/core/brain/dead-ends.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_dead_ends";
+const PRIVATE_APPROACH = "Try the withheld route";
+const PRIVATE_REASON = "Withheld reason text.";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(
+ path,
+ `${text.slice(0, close)}\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]${text.slice(close)}`,
+ );
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-dead-ends-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ const now = new Date("2026-05-03T00:00:00Z");
+ recordDeadEnd(f.vault, {
+ approach: "Try the readable route",
+ reason: "Readable reason.",
+ agent: "claude",
+ now,
+ });
+ if (withPrivate) {
+ const { entry } = recordDeadEnd(f.vault, {
+ approach: PRIVATE_APPROACH,
+ reason: PRIVATE_REASON,
+ agent: "claude",
+ now,
+ });
+ reserve(entry.path);
+ }
+ return f;
+}
+
+/** A vault holding a full active set whose oldest dead end is withheld. */
+function fullFixture(): { f: Fixture; oldest: string } {
+ const base = mkdtempSync(join(tmpdir(), "o2b-dead-ends-reach-full-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ const { entry } = recordDeadEnd(f.vault, {
+ approach: PRIVATE_APPROACH,
+ reason: PRIVATE_REASON,
+ agent: "claude",
+ now: new Date("2026-01-01T00:00:00Z"),
+ });
+ reserve(entry.path);
+ for (let i = 1; i < DEAD_END_MAX_ACTIVE; i += 1) {
+ recordDeadEnd(f.vault, {
+ approach: `Readable route ${i}`,
+ reason: "Readable reason.",
+ agent: "claude",
+ now: new Date(Date.UTC(2026, 1, 1, 0, 0, i)),
+ });
+ }
+ return { f, oldest: entry.path };
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ // Paths are compared with forward slashes on every platform.
+ return maskVolatile(f, result["structuredContent"] ?? result).replaceAll("\\\\", "/");
+ } catch (error) {
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+describe("brain_dead_ends answers at the caller's reach", () => {
+ test("remote reach: list reads as in a vault without the withheld dead end", async () => {
+ const args = { operation: "list" };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain("Try the readable route");
+ expect(withheld).not.toContain(PRIVATE_REASON);
+ });
+
+ test("remote reach: record names no archived id", async () => {
+ const args = { operation: "record", approach: "A new route", reason: "New reason." };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).not.toContain("archived");
+ });
+
+ test("remote reach: the overflow trim leaves a withheld dead end in place", async () => {
+ const { f, oldest } = fullFixture();
+ const bytes = readFileSync(oldest, "utf8");
+ await answer(f, { operation: "record", approach: "A new route", reason: "New reason." });
+ expect(existsSync(oldest)).toBe(true);
+ expect(readFileSync(oldest, "utf8")).toBe(bytes);
+ });
+
+ test("local reach: the overflow trim archives the oldest dead end", async () => {
+ const { f, oldest } = fullFixture();
+ const local = await answer(
+ f,
+ { operation: "record", approach: "A new route", reason: "New reason." },
+ TRANSPORT_REACH.local,
+ );
+ expect(existsSync(oldest)).toBe(false);
+ expect(local).toContain("archived");
+ });
+
+ test("local reach: list carries the withheld dead end", async () => {
+ const local = await answer(fixture(true), { operation: "list" }, TRANSPORT_REACH.local);
+ expect(local).toContain(PRIVATE_REASON);
+ });
+});
diff --git a/tests/mcp/decision-reach.test.ts b/tests/mcp/decision-reach.test.ts
new file mode 100644
index 00000000..3a11d05f
--- /dev/null
+++ b/tests/mcp/decision-reach.test.ts
@@ -0,0 +1,184 @@
+/**
+ * `brain_decision` answers at the caller's reach.
+ *
+ * Vault A holds a rated public decision and a rated decision page withheld
+ * from a remote caller by visibility; vault B holds only the public one.
+ * A server with no reach minted is a remote caller: every action must
+ * answer over A exactly as over B (the whole masked answer), the writes
+ * must refuse the withheld slug with the absent slug's error, and the
+ * decision page, the decision-change ledger and the log must keep their
+ * bytes. The local control proves the withheld decision is there.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { recordDecision } from "../../src/core/brain/decisions/record.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_decision";
+const PUBLIC_TITLE = "Adopt the bun runtime";
+const PUBLIC_SLUG = "adopt-the-bun-runtime";
+const PRIVATE_TITLE = "Adopt the nightingale vendor";
+const PRIVATE_SLUG = "adopt-the-nightingale-vendor";
+const PRIVATE_DECISION = `Brain/decisions/decision-${PRIVATE_SLUG}.md`;
+/** The review obligation recording opens; its title names the decision, so it is reserved too. */
+const PRIVATE_REVIEW = `Brain/obligations/review-decision-${PRIVATE_SLUG}.md`;
+const RECALL_CONFIG = ["decision_recall.max_per_session: 3"];
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function record(f: Fixture, title: string, rating: number): void {
+ recordDecision(f.vault, {
+ title,
+ chosen: `${title} now`,
+ assumption: "It keeps working.",
+ reviewDate: "2027-01-01",
+ rating,
+ rationale: "Worked before.",
+ agent: "claude",
+ configPath: f.configPath,
+ });
+}
+
+function reserve(f: Fixture, rel: string): void {
+ const abs = join(f.vault, rel);
+ const text = readFileSync(abs, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ const line = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+ writeFileSync(abs, `${text.slice(0, close)}\n${line}${text.slice(close)}`);
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-decision-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false, RECALL_CONFIG);
+ record(f, PUBLIC_TITLE, 4);
+ if (withPrivate) {
+ record(f, PRIVATE_TITLE, 5);
+ reserve(f, PRIVATE_DECISION);
+ reserve(f, PRIVATE_REVIEW);
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every byte a decision write could touch: the page, the ledger shards and the log. */
+function writtenBytes(f: Fixture): Record<string, string> {
+ const out: Record<string, string> = {};
+ out[PRIVATE_DECISION] = readFileSync(join(f.vault, PRIVATE_DECISION), "utf8");
+ for (const dir of ["Brain/truth", "Brain/log"]) {
+ const abs = join(f.vault, dir);
+ if (!existsSync(abs)) continue;
+ for (const name of readdirSync(abs)) {
+ out[`${dir}/${name}`] = readFileSync(join(abs, name), "utf8");
+ }
+ }
+ return out;
+}
+
+const READS: ReadonlyArray<[string, Record<string, unknown>]> = [
+ ["show", { action: "show", slug: PRIVATE_SLUG }],
+ ["list", { action: "list" }],
+ ["list rated", { action: "list", rated: true }],
+ ["compare", { action: "compare", slugs: [PRIVATE_SLUG, PUBLIC_SLUG] }],
+ ["similar", { action: "similar", title: "Adopt the vendor runtime" }],
+ ["history", { action: "history" }],
+ ["recall", { action: "recall", prompt: "adopt the nightingale vendor runtime" }],
+];
+
+const WRITES: ReadonlyArray<[string, Record<string, unknown>]> = [
+ ["outcome", { action: "outcome", slug: PRIVATE_SLUG, outcome: "It broke." }],
+ ["rate", { action: "rate", slug: PRIVATE_SLUG, rating: 1 }],
+];
+
+describe("brain_decision answers at the caller's reach", () => {
+ for (const [name, args] of READS) {
+ test(`remote reach: ${name} answers as in a vault without the withheld decision`, async () => {
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ // The caller's own slug is echoed by an absent-slug refusal; the
+ // withheld page's text never is.
+ expect(withheld).not.toContain("nightingale vendor now");
+ expect(withheld).not.toContain('"rating":5');
+ });
+ }
+
+ for (const [name, args] of WRITES) {
+ test(`remote reach: ${name} on the withheld decision is refused as an absent slug`, async () => {
+ const a = fixture(true);
+ const before = writtenBytes(a);
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(`no decision: ${PRIVATE_SLUG}`);
+ expect(writtenBytes(a)).toEqual(before);
+ });
+ }
+
+ test("remote reach: brain_design_note grounds on no withheld decision", async () => {
+ const args = { topic: "Adopt the nightingale vendor" };
+ const call = async (f: Fixture, reach?: TransportReach) => {
+ try {
+ const result = await reachServer(f, reach).callTool("brain_design_note", args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+ };
+ const withheld = await call(fixture(true));
+ expect(withheld).toBe(await call(fixture(false)));
+ expect(withheld).not.toContain("nightingale vendor now");
+ // Local control: the operator's own plan does ground on it.
+ expect(await call(fixture(true), TRANSPORT_REACH.local)).toContain("nightingale vendor now");
+ });
+
+ test("remote reach: a readable decision still takes an outcome", async () => {
+ const args = { action: "outcome", slug: PUBLIC_SLUG, outcome: "It held." };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain('"outcome":"It held."');
+ });
+
+ test("local control: the operator's own shell reads and rates the withheld decision", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ expect(await answer(a, { action: "show", slug: PRIVATE_SLUG }, local)).toContain(
+ "nightingale vendor now",
+ );
+ expect(await answer(a, { action: "list" }, local)).toContain(PRIVATE_SLUG);
+ expect(await answer(a, { action: "history" }, local)).toContain(PRIVATE_SLUG);
+ expect(await answer(a, { action: "rate", slug: PRIVATE_SLUG, rating: 1 }, local)).toContain(
+ '"rating":1',
+ );
+ expect(readFileSync(join(a.vault, PRIVATE_DECISION), "utf8")).toContain("rating: 1");
+ });
+});
diff --git a/tests/mcp/derive-fact-reach.test.ts b/tests/mcp/derive-fact-reach.test.ts
new file mode 100644
index 00000000..e2c49e98
--- /dev/null
+++ b/tests/mcp/derive-fact-reach.test.ts
@@ -0,0 +1,113 @@
+/**
+ * `brain_derive_fact` answers at the caller's reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a preference
+ * withheld from a remote caller by visibility; vault B never had it. Both
+ * hold the same readable preference and enable derived-fact synthesis. A
+ * server with no reach minted is a remote caller: a derived fact citing
+ * the withheld preference as a premise must be refused exactly as one
+ * citing a missing preference is, and no vault file may change. The local
+ * control proves the withheld premise is there to cite.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainConfigPath } from "../../src/core/brain/paths.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_SLUG,
+ reachServer,
+ SHARED_SLUG,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_derive_fact";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-derive-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ writeFileSync(
+ brainConfigPath(f.vault),
+ "schema_version: 1\nguardrails:\n derived_fact_synthesis: true\n",
+ );
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every file under the vault with its bytes, so any write shows. */
+function vaultBytes(f: Fixture): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readdirSync(f.vault, { recursive: true, withFileTypes: true })) {
+ if (!entry.isFile()) continue;
+ const abs = join(entry.parentPath, entry.name);
+ out[abs] = readFileSync(abs, "utf8");
+ }
+ return out;
+}
+
+function derivation(premises: ReadonlyArray<string>): Record<string, unknown> {
+ return {
+ slug: "derived-probe",
+ topic: "derived-probe",
+ principle: "A conclusion drawn from the premises.",
+ premises,
+ level: "deduced",
+ };
+}
+
+describe("brain_derive_fact answers at the caller's reach", () => {
+ for (const premises of [[`pref-${PRIVATE_SLUG}`], [`pref-${SHARED_SLUG}`, PRIVATE_SLUG]]) {
+ test(`remote reach: premises ${premises.join(", ")} are refused as missing`, async () => {
+ const a = fixture(true);
+ const before = vaultBytes(a);
+ const withheld = await answer(a, derivation(premises));
+ expect(withheld).toBe(await answer(fixture(false), derivation(premises)));
+ expect(withheld).toContain("premise preference not found");
+ expect(vaultBytes(a)).toEqual(before);
+ });
+ }
+
+ test("remote reach: a readable premise still derives the fact", async () => {
+ const args = derivation([`pref-${SHARED_SLUG}`]);
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain('"id":"pref-derived-probe"');
+ });
+
+ test("local control: the operator's shell cites the withheld premise", async () => {
+ const local = await answer(
+ fixture(true),
+ derivation([`pref-${PRIVATE_SLUG}`]),
+ TRANSPORT_REACH.local,
+ );
+ expect(local).toContain('"id":"pref-derived-probe"');
+ });
+});
diff --git a/tests/mcp/diarize-reach.test.ts b/tests/mcp/diarize-reach.test.ts
new file mode 100644
index 00000000..b402986c
--- /dev/null
+++ b/tests/mcp/diarize-reach.test.ts
@@ -0,0 +1,131 @@
+/**
+ * `brain_diarize` answers at the caller's reach.
+ *
+ * Vault A holds a source page and a subject page withheld from a remote
+ * caller by visibility beside readable ones; vault B never had them. A
+ * server with no reach minted is a remote caller: the readable subject's
+ * profile must read alike over both vaults (no withheld source path,
+ * digest or count), and the withheld subject must answer as an unknown
+ * entity. The local control proves the withheld pages are there to read.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { upsertEntity } from "../../src/core/brain/entities/registry.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_diarize";
+const NOW = new Date("2026-07-19T10:00:00Z");
+const READABLE_SUBJECT = "Ada Lovelace";
+const PRIVATE_SUBJECT = "Grace Hopper";
+const PRIVATE_SOURCE = "src-letters";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function writeSourcePage(vault: string, slug: string, body: string, reserved: boolean): void {
+ const dir = join(vault, "Brain", "sources");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, `${slug}.md`),
+ [
+ "---",
+ "kind: brain-source",
+ `source_path: ${slug}.txt`,
+ "source_hash: deadbeef",
+ "created_at: 2026-07-10T00:00:00Z",
+ "updated_at: 2026-07-10T00:00:00Z",
+ ...(reserved ? [RESERVE_LINE] : []),
+ "---",
+ "",
+ body,
+ "",
+ ].join("\n"),
+ );
+}
+
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-diarize-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ upsertEntity(f.vault, {
+ category: "person",
+ name: READABLE_SUBJECT,
+ agent: "test",
+ now: NOW,
+ body: "Ada Lovelace designed an early programming method.",
+ });
+ writeSourcePage(f.vault, "src-lecture", "Ada Lovelace attended a lecture.", false);
+ if (withPrivate) {
+ writeSourcePage(f.vault, PRIVATE_SOURCE, "Ada Lovelace wrote withheld letters.", true);
+ const { entity } = upsertEntity(f.vault, {
+ category: "person",
+ name: PRIVATE_SUBJECT,
+ agent: "test",
+ now: NOW,
+ body: "Grace Hopper kept a withheld notebook.",
+ });
+ reserve(entity.path);
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+describe("brain_diarize answers at the caller's reach", () => {
+ test("remote reach: a readable subject's profile counts no withheld source", async () => {
+ const args = { entity: READABLE_SUBJECT };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).not.toContain(PRIVATE_SOURCE);
+ });
+
+ test("remote reach: a withheld subject answers as an unknown entity", async () => {
+ const args = { entity: PRIVATE_SUBJECT };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain("unknown entity");
+ });
+
+ test("local reach: the withheld source and subject are there to read", async () => {
+ const f = fixture(true);
+ const local = await answer(f, { entity: READABLE_SUBJECT }, TRANSPORT_REACH.local);
+ expect(local).toContain(PRIVATE_SOURCE);
+ const subject = await answer(f, { entity: PRIVATE_SUBJECT }, TRANSPORT_REACH.local);
+ expect(subject).toContain("withheld notebook");
+ });
+});
diff --git a/tests/mcp/doctor-counts-reach.test.ts b/tests/mcp/doctor-counts-reach.test.ts
new file mode 100644
index 00000000..6e0bf5af
--- /dev/null
+++ b/tests/mcp/doctor-counts-reach.test.ts
@@ -0,0 +1,337 @@
+/**
+ * `brain_doctor` caps its removed-tool warnings and counts the states
+ * behind its stale-dependency note at the caller's reach.
+ *
+ * Both are computed inside the doctor's checks, before the handler's
+ * own filter runs: a withheld page that spent a slot of the removed-tool
+ * cap, or a withheld retired record counted in `states_changed`, would
+ * change the answer even though no finding names it.
+ *
+ * The vault pair is tests/helpers/reach-log-fixture.ts, plus 50 readable
+ * pages naming a removed tool in both and, in vault A only, a withheld
+ * Brain page whose validity closed (a state that stopped being current)
+ * and 50 withheld pages naming the removed tool: the walk lists them in directory order, so withheld
+ * pages are among the first 50 whatever that order is. Two more pairs
+ * extend it: a readable closed state cited by a readable preference and,
+ * in vault A only, by a withheld one; and 50 readable Brain pages with a
+ * frontmatter line the scanner drops, plus 50 withheld ones in vault A
+ * only, which sort first. A server with no reach minted is a remote
+ * caller, and its whole masked answer must be the same over both vaults;
+ * the local control proves the withheld items are there to count.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ appendFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+/** A tool the product no longer ships, which the doctor reports when a page names it. */
+const REMOVED_TOOL = "brain_digest";
+const PAGE_COUNT = 50;
+const PAGE_DIR = "Brain/memos";
+const PRIVATE_PATH = "PRIVATE_PATH";
+/**
+ * Prefix of every withheld page that competes with readable pages for a
+ * 50-slot cap. The scans walk in directory order, which the filesystem
+ * decides: case-insensitive alphabetical on NTFS, where `memo-` sorts before
+ * `PRIVATE_PATH-` and the readable pages alone fill the cap. The prefix sorts
+ * before the readable names (`memo-`, `zz-draft-`) in byte order and in
+ * case-insensitive order alike, so an alphabetical walk reaches the withheld
+ * pages first and a hashed walk (ext4) interleaves them with the readable ones.
+ */
+const WITHHELD_FIRST_PREFIX = "AA-";
+const REMOVED_TOOL_CODE = "removed-tool-reference";
+const STALE_DEPENDENCY_CODE = "stale-dependency";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+/** A readable state whose validity closed, cited by the consumers below. */
+const CLOSED_STATE = "pubclosed";
+/** A consumer written before the state closed, so the citation is stale. */
+const CONSUMER_WRITTEN_AT = new Date("2025-06-01T00:00:00Z");
+/** A frontmatter line the line scanner cannot express, so it is dropped. */
+const DROPPED_LINE = "this line is not yaml";
+
+/** Which extra page pairs a fixture carries beside the removed-tool pages. */
+interface Extras {
+ /** The readable closed state and its consumers. */
+ readonly cited?: boolean;
+ /** The pages with a dropped frontmatter line. */
+ readonly dropped?: boolean;
+ /** A withheld vault-root instruction file over the ceiling (vault A only). */
+ readonly instruction?: boolean;
+}
+
+/** A vault-root instruction file the doctor measures against its ceiling. */
+const INSTRUCTION_FILE = "AGENTS.md";
+/** Over the default `guardrails.instruction_file_max_lines` of 200. */
+const INSTRUCTION_FILE_LINES = 250;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function page(index: number, reserved: boolean): string {
+ const front = reserved ? `---\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n---\n` : "";
+ return `${front}# memo ${index}\n\nCall ${REMOVED_TOOL} for the summary.\n`;
+}
+
+/** A confirmed preference citing {@link CLOSED_STATE}, written before it closed. */
+function consumer(vault: string, slug: string, principle: string, reserved: boolean): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ // Principles that share no word, so no concept gap rides along.
+ principle,
+ created_at: "2025-05-01T00:00:00Z",
+ unconfirmed_until: "2025-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2025-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2025-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ });
+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ appendFileSync(path, `\nSee [[${CLOSED_STATE}]].\n`);
+ if (reserved) {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+ }
+ utimesSync(path, CONSUMER_WRITTEN_AT, CONSUMER_WRITTEN_AT);
+}
+
+function addCited(vault: string, withPrivate: boolean): void {
+ writeFileSync(
+ join(vault, "Brain", `${CLOSED_STATE}.md`),
+ "---\nvalid_until: 2026-01-01T00:00:00Z\n---\n# closed\n",
+ );
+ consumer(vault, "consumer-public", "Keep the ledger tidy.", false);
+ if (withPrivate) {
+ consumer(vault, `${PRIVATE_PATH.toLowerCase()}-consumer`, "Archive weekly snapshots.", true);
+ }
+}
+
+function addDropped(vault: string, withPrivate: boolean): void {
+ const dir = join(vault, "Brain", "drafts");
+ mkdirSync(dir, { recursive: true });
+ for (let i = 0; i < PAGE_COUNT; i++) {
+ const n = String(i).padStart(2, "0");
+ writeFileSync(join(dir, `zz-draft-${n}.md`), `---\ntitle: d\n${DROPPED_LINE}\n---\n# d\n`);
+ if (withPrivate) {
+ writeFileSync(
+ join(dir, `${WITHHELD_FIRST_PREFIX}${PRIVATE_PATH}-${n}.md`),
+ `---\n${RESERVE_LINE}\n${DROPPED_LINE}\n---\n# d\n`,
+ );
+ }
+ }
+}
+
+function fixture(withPrivate: boolean, extras: Extras = {}): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-doctor-counts-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ const dir = join(f.vault, ...PAGE_DIR.split("/"));
+ mkdirSync(dir, { recursive: true });
+ for (let i = 0; i < PAGE_COUNT; i++) {
+ const n = String(i).padStart(2, "0");
+ writeFileSync(join(dir, `memo-${n}.md`), page(i, false));
+ if (withPrivate) {
+ writeFileSync(join(dir, `${WITHHELD_FIRST_PREFIX}${PRIVATE_PATH}-${n}.md`), page(i, true));
+ }
+ }
+ if (withPrivate) {
+ writeFileSync(
+ join(f.vault, "Brain", `${PRIVATE_PATH}-closed.md`),
+ `---\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\nvalid_until: 2026-01-01T00:00:00Z\n---\n# closed\n`,
+ );
+ }
+ if (extras.cited) addCited(f.vault, withPrivate);
+ if (extras.dropped) addDropped(f.vault, withPrivate);
+ if (extras.instruction && withPrivate) {
+ const body = Array.from({ length: INSTRUCTION_FILE_LINES }, (_, i) => `- rule ${i}`);
+ writeFileSync(
+ join(f.vault, INSTRUCTION_FILE),
+ `---\n${RESERVE_LINE}\n---\n${body.join("\n")}\n`,
+ );
+ }
+ return f;
+}
+
+interface Entry {
+ readonly code: string;
+ readonly message: string;
+}
+
+interface Report {
+ readonly warnings: ReadonlyArray<Entry>;
+ readonly uncertain?: ReadonlyArray<Entry>;
+}
+
+/** The doctor's whole answer as JSON, with the fixture's paths and instants masked. */
+async function doctorJson(f: Fixture, reach?: TransportReach): Promise<string> {
+ const result = (await reachServer(f, reach).callTool("brain_doctor", {})) as Record<
+ string,
+ unknown
+ >;
+ return maskVolatile(f, result["structuredContent"] ?? result);
+}
+
+/** The repair preview (a dry run) as JSON, with the fixture's paths and instants masked. */
+async function repairJson(f: Fixture, reach?: TransportReach): Promise<string> {
+ const result = (await reachServer(f, reach).callTool("brain_doctor", {
+ repair: true,
+ format: "json",
+ })) as Record<string, unknown>;
+ return maskVolatile(f, result["structuredContent"] ?? result);
+}
+
+interface Unfixable {
+ readonly code: string;
+ readonly count: number;
+}
+
+function unfixableCount(json: string, code: string): number | undefined {
+ const parsed = JSON.parse(json) as { repair: { unfixable: ReadonlyArray<Unfixable> } };
+ return parsed.repair.unfixable.find((u) => u.code === code)?.count;
+}
+
+async function doctor(f: Fixture, reach?: TransportReach): Promise<Report> {
+ return JSON.parse(await doctorJson(f, reach)) as Report;
+}
+
+/** The remote answers over vault A and vault B, whole and masked. */
+async function remotePair(extras: Extras = {}): Promise<readonly [string, string]> {
+ const withheld = await doctorJson(fixture(true, extras));
+ const absent = await doctorJson(fixture(false, extras));
+ return [withheld, absent];
+}
+
+function staleRows(report: Report): ReadonlyArray<string> {
+ return report.warnings.filter((w) => w.code === STALE_DEPENDENCY_CODE).map((w) => w.message);
+}
+
+function droppedLineEntries(report: Report): number {
+ return (report.uncertain ?? []).filter(
+ (u) => u.message.includes(DROPPED_LINE) || u.code === "frontmatter-line-dropped",
+ ).length;
+}
+
+function removedToolWarnings(report: Report): ReadonlyArray<string> {
+ return report.warnings
+ .filter((w) => w.code === REMOVED_TOOL_CODE)
+ .map((w) => w.message)
+ .toSorted();
+}
+
+function staleNotes(report: Report): ReadonlyArray<string> {
+ return (report.uncertain ?? [])
+ .filter((u) => u.code === STALE_DEPENDENCY_CODE)
+ .map((u) => u.message);
+}
+
+describe("brain_doctor counts at the caller's reach", () => {
+ test("remote reach: withheld pages spend no slot of the removed-tool cap", async () => {
+ const [withheld, absent] = await remotePair();
+ expect(withheld).toBe(absent);
+ expect(removedToolWarnings(JSON.parse(absent) as Report)).toHaveLength(PAGE_COUNT);
+ expect(withheld).not.toContain(PRIVATE_PATH);
+ });
+
+ test("remote reach: the repair preview spends no slot of the removed-tool cap on withheld pages", async () => {
+ const withheld = await repairJson(fixture(true));
+ const absent = await repairJson(fixture(false));
+ expect(withheld).toBe(absent);
+ expect(unfixableCount(absent, REMOVED_TOOL_CODE)).toBe(PAGE_COUNT);
+ expect(withheld).not.toContain(PRIVATE_PATH);
+ });
+
+ test("local control: the operator's repair preview over the same vault counts the withheld pages", async () => {
+ // The removed-tool count sits at the cap either way; the withheld
+ // pages show in the codes and counts the remote preview leaves out.
+ const json = await repairJson(fixture(true), TRANSPORT_REACH.local);
+ expect(unfixableCount(json, REMOVED_TOOL_CODE)).toBe(PAGE_COUNT);
+ expect(json).not.toBe(await repairJson(fixture(true)));
+ });
+
+ test("remote reach: a withheld closed state moves no stale-dependency count", async () => {
+ const [withheld, absent] = await remotePair();
+ expect(withheld).toBe(absent);
+ expect(staleNotes(JSON.parse(withheld) as Report)).toEqual([]);
+ });
+
+ test("remote reach: a withheld consumer neither counts toward nor hides a readable row", async () => {
+ const [withheld, absent] = await remotePair({ cited: true });
+ expect(withheld).toBe(absent);
+ expect(staleRows(JSON.parse(withheld) as Report)).toHaveLength(1);
+ expect(withheld).not.toContain(PRIVATE_PATH.toLowerCase());
+ });
+
+ test("remote reach: withheld pages spend no slot of the uncertain cap", async () => {
+ const [withheld, absent] = await remotePair({ dropped: true });
+ expect(withheld).toBe(absent);
+ expect(droppedLineEntries(JSON.parse(withheld) as Report)).toBe(PAGE_COUNT);
+ expect(withheld).not.toContain(PRIVATE_PATH);
+ });
+
+ test("local control: the operator's own shell counts the withheld items", async () => {
+ const a = await doctor(fixture(true), TRANSPORT_REACH.local);
+ const b = await doctor(fixture(false), TRANSPORT_REACH.local);
+ const local = removedToolWarnings(a);
+ expect(local).toHaveLength(PAGE_COUNT);
+ expect(local.join("\n")).toContain(PRIVATE_PATH);
+ expect(staleNotes(b)).toEqual([]);
+ expect(staleNotes(a).join("\n")).toContain("1 state stopped being current");
+ });
+
+ test("remote reach: a withheld instruction file raises no ceiling warning", async () => {
+ const [withheld, absent] = await remotePair({ instruction: true });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(INSTRUCTION_FILE);
+ });
+
+ // One fixture and one doctor pass per control, so no test spends more
+ // than a fraction of Bun's default 5 s per-test timeout on the Linux job.
+ test("local control: the withheld consumer is counted", async () => {
+ const cited = await doctorJson(fixture(true, { cited: true }), TRANSPORT_REACH.local);
+ expect(cited).toContain(PRIVATE_PATH.toLowerCase());
+ });
+
+ test("local control: the withheld dropped lines are counted", async () => {
+ const dropped = await doctorJson(fixture(true, { dropped: true }), TRANSPORT_REACH.local);
+ expect(dropped).toContain(PRIVATE_PATH);
+ });
+
+ test("local control: the withheld instruction file is measured", async () => {
+ const instruction = await doctorJson(
+ fixture(true, { instruction: true }),
+ TRANSPORT_REACH.local,
+ );
+ expect(instruction).toContain(INSTRUCTION_FILE);
+ });
+});
diff --git a/tests/mcp/dream-reach.test.ts b/tests/mcp/dream-reach.test.ts
new file mode 100644
index 00000000..0389bb71
--- /dev/null
+++ b/tests/mcp/dream-reach.test.ts
@@ -0,0 +1,158 @@
+/**
+ * `brain_dream` answers at the caller's reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a preference and a
+ * retired record withheld from a remote caller by visibility; here it also
+ * holds three withheld inbox signals on a topic of their own. Vault B
+ * never had any of them. Both hold the same readable preference and three
+ * readable signals on a public topic. A server with no reach minted is a
+ * remote caller: its dry run must plan as if the withheld records were
+ * absent, and a real pass, a single step and the staged lifecycle are
+ * refused with one fixed answer and leave every vault file unchanged. The
+ * local control proves the withheld records are there to plan over.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_SIGNAL_SIGN } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_SLUG,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_dream";
+const PUBLIC_TOPIC = "public-topic";
+const WITHHELD_TOPIC = "withheld-topic";
+const AGENTS = ["claude", "codex", "hermes"] as const;
+const REFUSAL = "run at local reach only";
+const MINUTE_MS = 60_000;
+/** The clock suffix of a run id: two passes moments apart differ only there. */
+const RUN_CLOCK_RE = /(dream-<T>)-\d{6}/g;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function reserveFile(abs: string): void {
+ const text = readFileSync(abs, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(
+ abs,
+ `${text.slice(0, close)}\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]${text.slice(close)}`,
+ );
+}
+
+/** Three same-sign signals from three agents: enough for a new preference. */
+function seedCluster(vault: string, topic: string): ReadonlyArray<string> {
+ // Recent captures, so the pass plans over them instead of archiving them.
+ const now = Date.now();
+ return AGENTS.map((agent, i) => {
+ const at = new Date(now - (i + 1) * MINUTE_MS).toISOString();
+ return writeSignal(vault, {
+ topic,
+ signal: BRAIN_SIGNAL_SIGN.positive,
+ agent,
+ principle: `Always follow the ${topic} rule.`,
+ created_at: `${at.slice(0, 19)}Z`,
+ date: at.slice(0, 10),
+ slug: topic,
+ }).path;
+ });
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-dream-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ seedCluster(f.vault, PUBLIC_TOPIC);
+ if (withPrivate) for (const path of seedCluster(f.vault, WITHHELD_TOPIC)) reserveFile(path);
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result).replace(RUN_CLOCK_RE, "$1");
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every file under the vault with its bytes, so any write shows. */
+function vaultBytes(f: Fixture): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readdirSync(f.vault, { recursive: true, withFileTypes: true })) {
+ if (!entry.isFile()) continue;
+ const abs = join(entry.parentPath, entry.name);
+ out[abs] = readFileSync(abs, "utf8");
+ }
+ return out;
+}
+
+const DRY_RUN = { action: "run", dry_run: true };
+
+describe("brain_dream answers at the caller's reach", () => {
+ test("remote reach: a dry run plans as if the withheld records were absent", async () => {
+ const a = fixture(true);
+ const before = vaultBytes(a);
+ const withheld = await answer(a, DRY_RUN);
+ expect(withheld).toBe(await answer(fixture(false), DRY_RUN));
+ expect(withheld).toContain(PUBLIC_TOPIC);
+ expect(withheld).not.toContain(WITHHELD_TOPIC);
+ expect(withheld).not.toContain(PRIVATE_SLUG);
+ expect(vaultBytes(a)).toEqual(before);
+ });
+
+ const REFUSED: ReadonlyArray<Record<string, unknown>> = [
+ {},
+ { action: "run" },
+ { action: "run", dry_run: true, step: "scan" },
+ { action: "run", step: "scan" },
+ { action: "stage" },
+ { action: "list" },
+ { action: "validate", run_id: "run-1" },
+ { action: "apply", run_id: "run-1" },
+ { action: "retriage", run_id: "run-1" },
+ { action: "discard", run_id: "run-1" },
+ ];
+ for (const args of REFUSED) {
+ test(`remote reach: ${JSON.stringify(args)} is refused and writes nothing`, async () => {
+ const a = fixture(true);
+ const before = vaultBytes(a);
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(REFUSAL);
+ expect(vaultBytes(a)).toEqual(before);
+ });
+ }
+
+ test("local control: the operator's dry run plans over the withheld records", async () => {
+ const local = await answer(fixture(true), DRY_RUN, TRANSPORT_REACH.local);
+ expect(local).toContain(WITHHELD_TOPIC);
+ });
+
+ test("local control: the operator's real pass still runs", async () => {
+ const local = await answer(fixture(true), { action: "run" }, TRANSPORT_REACH.local);
+ expect(local).not.toContain(REFUSAL);
+ expect(local).toContain(`pref-${WITHHELD_TOPIC}`);
+ });
+});
diff --git a/tests/mcp/dream-stage-tool.test.ts b/tests/mcp/dream-stage-tool.test.ts
index dd7165a2..43ef52fc 100644
--- a/tests/mcp/dream-stage-tool.test.ts
+++ b/tests/mcp/dream-stage-tool.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { writeSignal } from "../../src/core/brain/signal.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
let tmp: string;
@@ -47,7 +48,8 @@ afterEach(() => {
});
async function makeServer(): Promise<MCPServer> {
- const server = new MCPServer({ vault, configPath });
+ // The staged lifecycle runs at local reach only.
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
diff --git a/tests/mcp/expire-reach.test.ts b/tests/mcp/expire-reach.test.ts
new file mode 100644
index 00000000..8c3c334a
--- /dev/null
+++ b/tests/mcp/expire-reach.test.ts
@@ -0,0 +1,96 @@
+/**
+ * `brain_expire` answers at the caller's reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a preference and a
+ * retired preference withheld from a remote caller by visibility; vault B
+ * never had them. Both hold the same public preference. A server with no
+ * reach minted is a remote caller: setting an expiration on a withheld
+ * record must be refused exactly as an unknown id is, and leave the page's
+ * bytes unchanged. The local control proves the withheld records are
+ * there to write.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_PATH,
+ PRIVATE_SLUG,
+ reachServer,
+ RETIRED_SLUG,
+ SHARED_SLUG,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_expire";
+const EXPIRES = "2027-01-01";
+const RETIRED_PATH = `Brain/retired/ret-${RETIRED_SLUG}.md`;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-expire-reach-"));
+ bases.push(base);
+ return buildReachLogFixture(base, withPrivate);
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+function pageBytes(f: Fixture): ReadonlyArray<string> {
+ return [PRIVATE_PATH, RETIRED_PATH].map((rel) => readFileSync(join(f.vault, rel), "utf8"));
+}
+
+describe("brain_expire answers at the caller's reach", () => {
+ for (const id of [`pref-${PRIVATE_SLUG}`, `ret-${RETIRED_SLUG}`]) {
+ test(`remote reach: a withheld ${id} is refused as an unknown id`, async () => {
+ const a = fixture(true);
+ const before = pageBytes(a);
+ const withheld = await answer(a, { id, expires: EXPIRES });
+ expect(withheld).toBe(await answer(fixture(false), { id, expires: EXPIRES }));
+ expect(withheld).toContain("no signal or preference with id");
+ expect(pageBytes(a)).toEqual(before);
+ });
+ }
+
+ test("remote reach: a readable preference still takes the expiration", async () => {
+ const args = { id: `pref-${SHARED_SLUG}`, expires: EXPIRES };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain('"changed":true');
+ });
+
+ test("local control: the operator's own shell sets the withheld expiration", async () => {
+ const a = fixture(true);
+ const local = await answer(
+ a,
+ { id: `pref-${PRIVATE_SLUG}`, expires: EXPIRES },
+ TRANSPORT_REACH.local,
+ );
+ expect(local).toContain('"changed":true');
+ expect(readFileSync(join(a.vault, PRIVATE_PATH), "utf8")).toContain(EXPIRES);
+ });
+});
diff --git a/tests/mcp/feedback-advisory-reach.test.ts b/tests/mcp/feedback-advisory-reach.test.ts
new file mode 100644
index 00000000..b493556c
--- /dev/null
+++ b/tests/mcp/feedback-advisory-reach.test.ts
@@ -0,0 +1,101 @@
+/**
+ * The write-time advisories of `brain_feedback` answer at the caller's
+ * reach.
+ *
+ * Vault A of tests/helpers/reach-log-fixture.ts holds a confirmed
+ * preference withheld from a remote caller by visibility, and here also a
+ * withheld inbox signal on a scope of its own; vault B never had either.
+ * Both hold the same readable preference and a readable scoped signal. A
+ * server with no reach minted is a remote caller: the conflict advisory
+ * must not name the withheld preference, and the routing hint must not
+ * count the withheld scope. The local control proves both are there.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_SIGNAL_SIGN } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_SLUG,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_feedback";
+const PUBLIC_SCOPE = "public-scope";
+const WITHHELD_SCOPE = "withheld-scope";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function seedSignal(vault: string, slug: string, scope: string): string {
+ return writeSignal(vault, {
+ topic: slug,
+ signal: BRAIN_SIGNAL_SIGN.positive,
+ agent: "claude",
+ principle: `Signal ${slug}.`,
+ created_at: "2026-05-01T00:00:00Z",
+ date: "2026-05-01",
+ slug,
+ scope,
+ }).path;
+}
+
+function reserveFile(abs: string): void {
+ const text = readFileSync(abs, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(
+ abs,
+ `${text.slice(0, close)}\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]${text.slice(close)}`,
+ );
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-feedback-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ seedSignal(f.vault, "public-capture", PUBLIC_SCOPE);
+ if (withPrivate) reserveFile(seedSignal(f.vault, "withheld-capture", WITHHELD_SCOPE));
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+}
+
+/** A scope-less capture whose principle repeats the withheld rule word for word. */
+const PROBE = { topic: "probe", signal: "positive", principle: `Rule ${PRIVATE_SLUG}.` };
+
+describe("brain_feedback advisories answer at the caller's reach", () => {
+ test("remote reach: neither advisory names or counts a withheld record", async () => {
+ const withheld = await answer(fixture(true), PROBE);
+ expect(withheld).toBe(await answer(fixture(false), PROBE));
+ expect(withheld).not.toContain(`pref-${PRIVATE_SLUG}`);
+ expect(withheld).not.toContain(WITHHELD_SCOPE);
+ expect(withheld).toContain(PUBLIC_SCOPE);
+ });
+
+ test("local control: the operator's shell sees both withheld records", async () => {
+ const local = await answer(fixture(true), PROBE, TRANSPORT_REACH.local);
+ expect(local).toContain(`pref-${PRIVATE_SLUG}`);
+ expect(local).toContain(WITHHELD_SCOPE);
+ });
+});
diff --git a/tests/mcp/health-concept-gaps-reach.test.ts b/tests/mcp/health-concept-gaps-reach.test.ts
new file mode 100644
index 00000000..3d83c392
--- /dev/null
+++ b/tests/mcp/health-concept-gaps-reach.test.ts
@@ -0,0 +1,172 @@
+/**
+ * The semantic-health readers count concept gaps over the principles the
+ * caller may read.
+ *
+ * Vault A holds six confirmed preferences withheld from a remote caller
+ * by visibility, whose principles repeat one marker phrase, so the
+ * concept-gap detector reports the phrase as a recurring term no topic
+ * covers; vault B never had them. Both carry the log of
+ * tests/helpers/reach-log-fixture.ts. A server with no reach minted is a
+ * remote caller: `brain_health`, `brain_doctor` and `brain_trigger
+ * operation=scan` over the two vaults must answer identically once the
+ * volatile parts are masked. The local control proves the withheld
+ * principles are there to count.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { signalPath } from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+/** The phrase the withheld principles repeat, so it surfaces as a concept gap. */
+const MARKER = "zzquartz harbor";
+const WITHHELD_COUNT = 6;
+/** The doctor code a recurring uncovered term is reported under. */
+const CONCEPT_GAP_CODE = "concept-gap";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function withheldPreference(vault: string, index: number): void {
+ const slug = `zzgap-${index}`;
+ writePreference(vault, {
+ slug,
+ topic: `misc-${index}`,
+ principle: `Route builds via Zzquartz Harbor ${index}.`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ });
+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+/** The phrase the withheld signals repeat, so it surfaces as a concept gap. */
+const SIGNAL_MARKER = "zzbasalt quay";
+
+/** A withheld inbox signal whose principle carries {@link SIGNAL_MARKER}. */
+function withheldSignal(vault: string, index: number): void {
+ const date = "2026-05-01";
+ const slug = `zzgap-signal-${index}`;
+ writeSignal(vault, {
+ topic: `misc-signal-${index}`,
+ signal: "positive",
+ agent: "test",
+ principle: `Ship releases via Zzbasalt Quay ${index}.`,
+ created_at: `${date}T00:00:00Z`,
+ date,
+ slug,
+ });
+ const path = signalPath(vault, date, slug);
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+function fixture(withPrivate: boolean, withheldSignals = false): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-health-gaps-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ if (withPrivate) for (let i = 0; i < WITHHELD_COUNT; i++) withheldPreference(f.vault, i);
+ if (withPrivate && withheldSignals) {
+ for (let i = 0; i < WITHHELD_COUNT; i++) withheldSignal(f.vault, i);
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ tool: string,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ const result = await reachServer(f, reach).callTool(tool, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+}
+
+/** The remote answers over vault A and vault B, whole and masked. */
+async function remotePair(
+ tool: string,
+ args: Record<string, unknown>,
+): Promise<readonly [string, string]> {
+ const withheld = await answer(fixture(true), tool, args);
+ const absent = await answer(fixture(false), tool, args);
+ return [withheld, absent];
+}
+
+describe("concept gaps answer at the caller's reach", () => {
+ test("remote reach: brain_health names no term only withheld principles carry", async () => {
+ const [withheld, absent] = await remotePair("brain_health", {});
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(MARKER);
+ });
+
+ test("remote reach: brain_doctor raises no concept gap from withheld principles", async () => {
+ const [withheld, absent] = await remotePair("brain_doctor", {});
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(MARKER);
+ });
+
+ test("remote reach: the brain_doctor repair preview counts no concept gap from withheld principles", async () => {
+ const [withheld, absent] = await remotePair("brain_doctor", { repair: true, format: "json" });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(CONCEPT_GAP_CODE);
+ });
+
+ test("remote reach: brain_trigger scan counts no candidate from withheld records", async () => {
+ const [withheld, absent] = await remotePair("brain_trigger", { operation: "scan" });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain("zzgap");
+ });
+
+ test("local control: the operator's own shell sees the recurring term", async () => {
+ const a = fixture(true);
+ expect(await answer(a, "brain_health", {}, TRANSPORT_REACH.local)).toContain(MARKER);
+ expect(await answer(a, "brain_doctor", {}, TRANSPORT_REACH.local)).toContain(MARKER);
+ const preview = { repair: true, format: "json" };
+ expect(await answer(a, "brain_doctor", preview, TRANSPORT_REACH.local)).toContain(
+ CONCEPT_GAP_CODE,
+ );
+ });
+
+ test("remote reach: withheld signal principles add no concept gap", async () => {
+ const withheld = await answer(fixture(true, true), "brain_health", {});
+ const absent = await answer(fixture(false, true), "brain_health", {});
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(SIGNAL_MARKER);
+ });
+
+ test("local control: the operator's brain_health names the withheld signals' term", async () => {
+ const local = await answer(fixture(true, true), "brain_health", {}, TRANSPORT_REACH.local);
+ expect(local).toContain(SIGNAL_MARKER);
+ });
+});
diff --git a/tests/mcp/hygiene-refresh-reach.test.ts b/tests/mcp/hygiene-refresh-reach.test.ts
new file mode 100644
index 00000000..81219f90
--- /dev/null
+++ b/tests/mcp/hygiene-refresh-reach.test.ts
@@ -0,0 +1,106 @@
+/**
+ * `brain_hygiene` `refresh` answers at the caller's reach.
+ *
+ * Vault A holds a derived page withheld from a remote caller by visibility
+ * whose every recorded source is gone (an orphan the recompile plan would
+ * archive) beside a readable one; vault B holds only the readable one. A
+ * server with no reach minted is a remote caller: the plan, the dry run
+ * and the applied refresh must read alike over both vaults, and the
+ * withheld page must stay where it is, byte for byte. The local control
+ * proves the withheld page is there to plan.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_hygiene";
+const READABLE_DERIVED = "Notes/derived-readable.md";
+const PRIVATE_DERIVED = "Notes/derived-withheld.md";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function derivedPage(source: string, reserved: boolean): string {
+ return [
+ "---",
+ "title: Derived",
+ `source_paths: [${source}]`,
+ "source_hashes: [sha256:0000]",
+ ...(reserved ? [`visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`] : []),
+ "---",
+ "",
+ "Derived body.",
+ "",
+ ].join("\n");
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-hygiene-refresh-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ mkdirSync(join(f.vault, "Notes"), { recursive: true });
+ writeFileSync(join(f.vault, READABLE_DERIVED), derivedPage("Notes/gone-readable.md", false));
+ if (withPrivate) {
+ writeFileSync(join(f.vault, PRIVATE_DERIVED), derivedPage("Notes/gone-withheld.md", true));
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ // Paths are compared with forward slashes on every platform.
+ return maskVolatile(f, result["structuredContent"] ?? result).replaceAll("\\\\", "/");
+ } catch (error) {
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+describe("brain_hygiene refresh answers at the caller's reach", () => {
+ test("remote reach: the dry-run plan reads as in a vault without the withheld page", async () => {
+ const args = { mode: "refresh", dry_run: true };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(READABLE_DERIVED);
+ });
+
+ test("remote reach: an applied refresh leaves the withheld page in place", async () => {
+ const a = fixture(true);
+ const before = readFileSync(join(a.vault, PRIVATE_DERIVED), "utf8");
+ const args = { mode: "refresh" };
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(existsSync(join(a.vault, READABLE_DERIVED))).toBe(false);
+ expect(readFileSync(join(a.vault, PRIVATE_DERIVED), "utf8")).toBe(before);
+ });
+
+ test("local reach: the plan includes the withheld page", async () => {
+ const local = await answer(
+ fixture(true),
+ { mode: "refresh", dry_run: true },
+ TRANSPORT_REACH.local,
+ );
+ expect(local).toContain(PRIVATE_DERIVED);
+ });
+});
diff --git a/tests/mcp/intention-reach.test.ts b/tests/mcp/intention-reach.test.ts
new file mode 100644
index 00000000..c42c947b
--- /dev/null
+++ b/tests/mcp/intention-reach.test.ts
@@ -0,0 +1,171 @@
+/**
+ * `brain_intention` reads and writes intention chains at the caller's
+ * reach.
+ *
+ * Vault A holds an intention chain withheld from a remote caller by
+ * visibility, carrying a unique text, and a withheld archived chain of
+ * the public scope from today; vault B never had either. Both share a
+ * public chain and the log of tests/helpers/reach-log-fixture.ts. A
+ * server with no reach minted is a remote caller: `list`, `show` and
+ * `move` over the two vaults must answer identically once the volatile
+ * parts are masked, and the withheld chain must stay untouched. The local
+ * control proves the withheld chain is there to hide.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { moveIntentionToHistory, setIntention } from "../../src/core/brain/intentions.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const PRIVATE_SCOPE = "zzreservedscope";
+const PRIVATE_TEXT = "Zzreservedplan for the quarter";
+const PUBLIC_SCOPE = "public-scope";
+const PUBLIC_TEXT = "Ship the public release";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const AGENT = "claude";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+/** Insert the reserve line before the closing frontmatter fence of `path`. */
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+interface Vault extends Fixture {
+ /** The withheld chain's absolute path (vault A only). */
+ readonly privateChain: string;
+}
+
+function fixture(withPrivate: boolean): Vault {
+ const base = mkdtempSync(join(tmpdir(), "o2b-intention-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ if (withPrivate) {
+ // An earlier public-scope chain retired today and withheld: the move
+ // below must not choose its archive name around it in sight of a
+ // remote caller.
+ setIntention(f.vault, { scope: PUBLIC_SCOPE, text: PRIVATE_TEXT, agent: AGENT });
+ reserve(moveIntentionToHistory(f.vault, { scope: PUBLIC_SCOPE }).archivePath);
+ }
+ setIntention(f.vault, { scope: PUBLIC_SCOPE, text: PUBLIC_TEXT, agent: AGENT });
+ const privateChain = join(f.vault, "Brain", "intentions", `${PRIVATE_SCOPE}.md`);
+ if (withPrivate) {
+ setIntention(f.vault, { scope: PRIVATE_SCOPE, text: PRIVATE_TEXT, agent: AGENT });
+ reserve(privateChain);
+ }
+ return { ...f, privateChain };
+}
+
+/** The tool's masked answer, or the masked error message it threw. */
+async function intention(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool("brain_intention", args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (err) {
+ return `error: ${maskVolatile(f, (err as Error).message)}`;
+ }
+}
+
+describe("brain_intention answers at the caller's reach", () => {
+ test("remote reach: list, show and move answer as for an absent chain", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const before = readFileSync(a.privateChain, "utf8");
+ for (const args of [
+ { operation: "list" },
+ { operation: "show", scope: PRIVATE_SCOPE },
+ { operation: "move", scope: PRIVATE_SCOPE },
+ { operation: "move", scope: PUBLIC_SCOPE },
+ ]) {
+ // Sequential on purpose: each server reads the process-wide config
+ // variable reachServer sets, so concurrent calls would race on it.
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await intention(a, args);
+ // oxlint-disable-next-line no-await-in-loop
+ const absent = await intention(b, args);
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain("Zzreserved");
+ }
+ expect(readFileSync(a.privateChain, "utf8")).toBe(before);
+ });
+
+ test("remote reach: set over a withheld chain refuses and leaves it as it was", async () => {
+ const a = fixture(true);
+ const before = readFileSync(a.privateChain, "utf8");
+ const answer = await intention(a, { operation: "set", scope: PRIVATE_SCOPE, text: "x" });
+ expect(answer.startsWith("error: ")).toBe(true);
+ expect(answer).not.toContain("Zzreserved");
+ expect(readFileSync(a.privateChain, "utf8")).toBe(before);
+ });
+
+ test("remote reach: a readable chain is still listed, shown and updated", async () => {
+ const a = fixture(true);
+ expect(await intention(a, { operation: "list" })).toContain(PUBLIC_TEXT);
+ expect(await intention(a, { operation: "show", scope: PUBLIC_SCOPE })).toContain(PUBLIC_TEXT);
+ expect(
+ await intention(a, { operation: "set", scope: PUBLIC_SCOPE, text: "Next step" }),
+ ).toContain('"version":2');
+ });
+
+ test("local control: the operator's own shell lists, shows and archives by name", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ expect(await intention(a, { operation: "list" }, local)).toContain(PRIVATE_TEXT);
+ expect(await intention(a, { operation: "show", scope: PRIVATE_SCOPE }, local)).toContain(
+ PRIVATE_TEXT,
+ );
+ expect(await intention(a, { operation: "move", scope: PUBLIC_SCOPE }, local)).toContain(
+ "archive_path",
+ );
+ });
+
+ test("remote reach: a list judges each chain by its own file name", async () => {
+ // Hand-written chains whose file names are not scope-shaped: the
+ // readable one stays listed, the withheld one is dropped, and a name
+ // with no letters or digits does not fail the call.
+ const handWritten = (f: Fixture, from: string, to: string, text: string): string => {
+ setIntention(f.vault, { scope: from, text, agent: AGENT });
+ const dir = join(f.vault, "Brain", "intentions");
+ const target = join(dir, `${to}.md`);
+ renameSync(join(dir, `${from}.md`), target);
+ return target;
+ };
+ const build = (withPrivate: boolean): Fixture => {
+ const f = fixture(withPrivate);
+ handWritten(f, "open-plan", "Open_Plan", "Draft the open plan");
+ handWritten(f, "symbols-only", "___", "A chain named by symbols");
+ if (withPrivate) reserve(handWritten(f, "hidden-plan", "Zzreserved_Plan", PRIVATE_TEXT));
+ return f;
+ };
+ const withheld = await intention(build(true), { operation: "list" });
+ const absent = await intention(build(false), { operation: "list" });
+ expect(withheld).toBe(absent);
+ expect(withheld.startsWith("error: ")).toBe(false);
+ expect(withheld).toContain("Open_Plan");
+ expect(withheld).toContain("Draft the open plan");
+ expect(withheld).not.toContain("Zzreserved");
+ });
+});
diff --git a/tests/mcp/labels-reach.test.ts b/tests/mcp/labels-reach.test.ts
new file mode 100644
index 00000000..1b022cc9
--- /dev/null
+++ b/tests/mcp/labels-reach.test.ts
@@ -0,0 +1,119 @@
+/**
+ * `brain_labels` assign and remove answer at the caller's reach.
+ *
+ * Vault A holds a labelled note withheld from a remote caller by
+ * visibility; vault B never had it. Both declare the same label dimension
+ * and hold the same public note. A server with no reach minted is a
+ * remote caller: assigning or removing a label on the withheld note must
+ * be refused exactly as on a missing one, and leave every vault byte
+ * unchanged. The local control proves the withheld note is there to label.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_labels";
+const PUBLIC_NOTE = "Notes/public.md";
+const PRIVATE_NOTE = "Notes/withheld.md";
+const SCHEMA = [
+ "schema_version: 1",
+ "schema:",
+ " labels:",
+ " - priority=low",
+ " - priority=high",
+];
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-labels-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ writeFileSync(join(f.vault, "Brain", "_brain.yaml"), `${SCHEMA.join("\n")}\n`);
+ mkdirSync(join(f.vault, "Notes"), { recursive: true });
+ writeFileSync(join(f.vault, PUBLIC_NOTE), "---\nlabels: [priority/low]\n---\n\n# Public\n");
+ if (withPrivate) {
+ writeFileSync(
+ join(f.vault, PRIVATE_NOTE),
+ `---\nlabels: [priority/low]\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n---\n\n# Withheld\n`,
+ );
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every file under the vault with its bytes. */
+function vaultBytes(root: string, rel = ""): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
+ const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
+ if (entry.isDirectory()) Object.assign(out, vaultBytes(root, child));
+ else out[child] = readFileSync(join(root, child), "utf8");
+ }
+ return out;
+}
+
+const WRITES: ReadonlyArray<[string, Record<string, unknown>]> = [
+ ["assign", { operation: "assign", path: PRIVATE_NOTE, dimension: "priority", value: "high" }],
+ ["remove", { operation: "remove", path: PRIVATE_NOTE, dimension: "priority" }],
+];
+
+describe("brain_labels answers at the caller's reach", () => {
+ for (const [name, args] of WRITES) {
+ test(`remote reach: ${name} on the withheld note is refused as on a missing one`, async () => {
+ const a = fixture(true);
+ const before = vaultBytes(a.vault);
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(`note does not exist: ${PRIVATE_NOTE}`);
+ expect(vaultBytes(a.vault)).toEqual(before);
+ });
+ }
+
+ test("remote reach: a readable note still takes a label", async () => {
+ const args = { operation: "assign", path: PUBLIC_NOTE, dimension: "priority", value: "high" };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain('"changed":true');
+ });
+
+ test("local control: the operator's own shell labels the withheld note", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ for (const [, args] of WRITES) {
+ expect(await answer(a, args, local)).toContain('"changed":true');
+ }
+ expect(readFileSync(join(a.vault, PRIVATE_NOTE), "utf8")).not.toContain("priority/");
+ });
+});
diff --git a/tests/mcp/lifecycle-reach.test.ts b/tests/mcp/lifecycle-reach.test.ts
new file mode 100644
index 00000000..b105d194
--- /dev/null
+++ b/tests/mcp/lifecycle-reach.test.ts
@@ -0,0 +1,201 @@
+/**
+ * `brain_lifecycle` answers at the caller's reach.
+ *
+ * Both vaults carry the log of tests/helpers/reach-log-fixture.ts and two
+ * public notes. Vault A also holds a note and a preference withheld from
+ * a remote caller by visibility; vault B never had them. A server with no
+ * reach minted is a remote caller: tombstone, supersede and
+ * temporal-replace naming a withheld page must be refused exactly as a
+ * missing page is, and leave the page's bytes unchanged. The local
+ * control proves the withheld pages are there to write.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ PRIVATE_PATH as PRIVATE_PREFERENCE,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_lifecycle";
+const PRIVATE_NOTE = "Notes/zz-withheld.md";
+const PUBLIC_NOTE = "Notes/public.md";
+const OTHER_NOTE = "Notes/other.md";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const AT = "2026-06-01";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-lifecycle-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ mkdirSync(join(f.vault, "Notes"), { recursive: true });
+ writeFileSync(join(f.vault, PUBLIC_NOTE), "---\ntitle: public\n---\n# public\n");
+ writeFileSync(join(f.vault, OTHER_NOTE), "---\ntitle: other\n---\n# other\n");
+ if (withPrivate) {
+ writeFileSync(join(f.vault, PRIVATE_NOTE), `---\n${RESERVE_LINE}\n---\n# withheld\n`);
+ }
+ observedUse(f.vault, withPrivate);
+ return f;
+}
+
+/**
+ * Observed-use verdicts the curator folds: the public note is used three
+ * times; in vault A the withheld note and the withheld preference (by id)
+ * are injected and ignored, and contradicted.
+ */
+function observedUse(vault: string, withPrivate: boolean): void {
+ const used = { path: PUBLIC_NOTE, verdict: "USED" };
+ const entries: Array<Record<string, string>> = [used, used, used];
+ if (withPrivate) {
+ entries.push(
+ { path: PRIVATE_NOTE, verdict: "IGNORED" },
+ { id: "pref-withheld", verdict: "IGNORED" },
+ { path: PRIVATE_PREFERENCE, verdict: "CONTRADICTED" },
+ );
+ }
+ appendContinuityRecord(vault, {
+ kind: "recall_observed_use",
+ createdAt: "2026-08-22T10:00:00Z",
+ sourceRefs: [{ id: "reuse:session" }],
+ payload: { session_id: "sess-reuse", entries },
+ });
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Every write the tool offers, each naming a withheld page in one argument. */
+const WRITES: ReadonlyArray<Record<string, unknown>> = [
+ { action: "tombstone", path: PRIVATE_NOTE, reason: "obsolete" },
+ { action: "tombstone", path: PRIVATE_PREFERENCE, reason: "obsolete" },
+ { action: "supersede", predecessor: PRIVATE_NOTE, successor: "public" },
+ { action: "temporal-replace", predecessor: PRIVATE_NOTE, successor: PUBLIC_NOTE, at: AT },
+ { action: "temporal-replace", predecessor: PUBLIC_NOTE, successor: PRIVATE_NOTE, at: AT },
+];
+
+function pageBytes(f: Fixture): ReadonlyArray<string> {
+ return [PRIVATE_NOTE, PRIVATE_PREFERENCE, PUBLIC_NOTE].map((rel) =>
+ readFileSync(join(f.vault, rel), "utf8"),
+ );
+}
+
+describe("brain_lifecycle answers at the caller's reach", () => {
+ for (const args of WRITES) {
+ test(`remote reach: ${String(args["action"])} refuses a withheld page as a missing one (${JSON.stringify(args)})`, async () => {
+ const a = fixture(true);
+ const before = pageBytes(a);
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain("note does not exist");
+ expect(pageBytes(a)).toEqual(before);
+ });
+ }
+
+ test("remote reach: a write over readable pages still lands", async () => {
+ const args = {
+ action: "temporal-replace",
+ predecessor: PUBLIC_NOTE,
+ successor: OTHER_NOTE,
+ at: AT,
+ };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(PUBLIC_NOTE);
+ });
+
+ test("remote reach: curator leaves out the rows of withheld pages", async () => {
+ const args = { action: "curator" };
+ const withheld = await answer(fixture(true), args);
+ expect(withheld).toBe(await answer(fixture(false), args));
+ expect(withheld).toContain(PUBLIC_NOTE);
+ });
+
+ test("local control: the operator's curator lists the withheld pages", async () => {
+ const local = await answer(fixture(true), { action: "curator" }, TRANSPORT_REACH.local);
+ expect(local).toContain(PRIVATE_NOTE);
+ // The id-keyed row, apart from the row keyed by the preference's path.
+ expect(local).toContain('"key":"pref-withheld"');
+ });
+
+ test("local control: the operator's own shell tombstones the withheld page", async () => {
+ const a = fixture(true);
+ const args = { action: "tombstone", path: PRIVATE_NOTE, reason: "obsolete" };
+ expect(await answer(a, args, TRANSPORT_REACH.local)).toContain('"changed":true');
+ expect(readFileSync(join(a.vault, PRIVATE_NOTE), "utf8")).toContain("tombstoned");
+ });
+});
+
+/**
+ * `tip` walks the supersede chain over Brain pages. In vault A the public
+ * page `chain-head` points at the withheld preference, which points on to
+ * the public page `chain-tail`; vault B has the same two public pages and
+ * no withheld one. A remote walk must stop at the withheld id exactly as
+ * at an unknown one, and a tip asked of the withheld id itself must read
+ * as an unknown id.
+ */
+function chainFixture(withPrivate: boolean): Fixture {
+ const f = fixture(withPrivate);
+ const dir = join(f.vault, "Brain", "processed");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "chain-head.md"),
+ `---\nsuperseded_by: "[[pref-withheld]]"\n---\n# head\n`,
+ );
+ writeFileSync(join(dir, "chain-tail.md"), "---\ntitle: tail\n---\n# tail\n");
+ if (withPrivate) {
+ const abs = join(f.vault, PRIVATE_PREFERENCE);
+ const text = readFileSync(abs, "utf8");
+ writeFileSync(abs, text.replace("\n---\n", '\nsuperseded_by: "[[chain-tail]]"\n---\n'));
+ }
+ return f;
+}
+
+describe("brain_lifecycle tip answers at the caller's reach", () => {
+ for (const id of ["chain-head", "pref-withheld"]) {
+ test(`remote reach: tip of ${id} reads as in a vault without the withheld page`, async () => {
+ const args = { action: "tip", id };
+ const withheld = await answer(chainFixture(true), args);
+ expect(withheld).toBe(await answer(chainFixture(false), args));
+ expect(withheld).not.toContain("chain-tail");
+ });
+ }
+
+ test("local control: the operator's own walk steps through the withheld page", async () => {
+ const local = await answer(
+ chainFixture(true),
+ { action: "tip", id: "chain-head" },
+ TRANSPORT_REACH.local,
+ );
+ expect(local).toContain('"tip":"chain-tail"');
+ expect(local).toContain('"steps":2');
+ });
+});
diff --git a/tests/mcp/long-running-tools.test.ts b/tests/mcp/long-running-tools.test.ts
index 599a7f98..fe74f957 100644
--- a/tests/mcp/long-running-tools.test.ts
+++ b/tests/mcp/long-running-tools.test.ts
@@ -48,6 +48,16 @@ import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/inde
import { PROGRESS_META_KEY, PROGRESS_NOTIFICATION_METHOD } from "../../src/mcp/progress.ts";
import type { JsonRpcNotification } from "../../src/mcp/protocol.ts";
import { PROGRESS_SCHEMA } from "../../src/core/brain/progress.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+
+/**
+ * The lane, the dream pass and their stages are the operator's own
+ * operations and run at local reach only, so every server here is the
+ * operator's own shell.
+ */
+function localServer(): MCPServer {
+ return new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
+}
/** Whether sqlite-vec loaded in THIS process: the spend-surface test needs it. */
const VEC_LOADABLE = sqliteVecLoadable();
@@ -142,7 +152,7 @@ test("brain_bridges discover aborts once its deadline has passed", async () => {
await indexVault(
makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),
);
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -161,7 +171,7 @@ test("brain_clusters run aborts once its deadline has passed", async () => {
await indexVault(
makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),
);
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -176,7 +186,7 @@ test("brain_clusters run aborts once its deadline has passed", async () => {
});
test("brain_dream run aborts once its deadline has passed", async () => {
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -191,7 +201,7 @@ test("brain_dream run aborts once its deadline has passed", async () => {
});
test("brain_dream stage aborts once its deadline has passed", async () => {
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -211,7 +221,7 @@ test("brain_dream step aborts once its deadline has passed", async () => {
// over a large tree held the server's event loop for its whole
// duration. It is bounded on the same `dream` budget as every other
// branch now, and the abort names the operation rather than the step.
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -259,7 +269,7 @@ test("brain_dream step heal-enrich reports under its own stage too", async () =>
});
test("brain_maintenance names the task whose deadline tripped", async () => {
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -284,7 +294,7 @@ test("brain_maintenance names the task whose deadline tripped", async () => {
});
test("brain_review_candidates aborts once its deadline has passed", async () => {
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -299,7 +309,7 @@ test("brain_review_candidates aborts once its deadline has passed", async () =>
});
test("brain_brief view=operator names the deadline its dream pass tripped", async () => {
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const restore = jumpingClock();
@@ -326,7 +336,7 @@ test("a live clock leaves all four tools running to completion", async () => {
await indexVault(
makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),
);
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const bridges = await callRaw(server, "brain_bridges", { operation: "discover" });
@@ -357,7 +367,7 @@ test.skipIf(!VEC_LOADABLE)(
`vault: ${vault}\nagent_name: claude\nsearch_semantic_enabled: true\nembedding_provider: local\n` +
`${MAINTENANCE_EMBEDDINGS_CONFIG_KEY}: true\n`,
);
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
const res = (await server.handleRequest({
@@ -403,7 +413,7 @@ test.skipIf(!VEC_LOADABLE)(
`vault: ${vault}\nagent_name: claude\nsearch_semantic_enabled: true\nembedding_provider: local\n` +
`${MAINTENANCE_EMBEDDINGS_CONFIG_KEY}: true\n`,
);
- const server = new MCPServer({ vault, configPath });
+ const server = localServer();
await initialize(server);
// A one-hour window the current hour cannot fall in.
const start = (new Date().getUTCHours() + 2) % 24;
@@ -463,7 +473,10 @@ function stagesIn(frames: JsonRpcNotification[]): Set<string> {
function observedServer(frames: JsonRpcNotification[]): MCPServer {
return new MCPServer(
{ vault, configPath },
- { sendNotification: (notification) => frames.push(notification) },
+ {
+ reach: TRANSPORT_REACH.local,
+ sendNotification: (notification) => frames.push(notification),
+ },
);
}
diff --git a/tests/mcp/maintenance-parity-census.test.ts b/tests/mcp/maintenance-parity-census.test.ts
index a06d76b9..ad0366b6 100644
--- a/tests/mcp/maintenance-parity-census.test.ts
+++ b/tests/mcp/maintenance-parity-census.test.ts
@@ -65,6 +65,7 @@ import {
} from "../../src/core/brain/maintenance/custom-tasks.ts";
import { isOperation } from "../../src/core/brain/safeguard.ts";
import { ADMIN_TOOLS } from "../../src/mcp/brain/admin-tools.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";
import { homeEnv } from "../helpers/platform.ts";
@@ -422,7 +423,7 @@ describe("the two surfaces refuse the same values, not only the same names", ()
// lane must never START on a number the other door refuses.
expect(cli.returncode).toBe(2);
- const server = new MCPServer({ vault, configPath });
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
@@ -452,7 +453,7 @@ describe("the two surfaces refuse the same values, not only the same names", ()
// array was accepted while the schema said it could not be. After
// deduplication a longer list always names an unknown task, so it is
// refused by name, in the same words the CLI uses.
- const server = new MCPServer({ vault, configPath });
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
@@ -517,7 +518,7 @@ describe("an unknown retry name is refused by name on both surfaces", () => {
expect(cli.stderr).toContain("dreams");
for (const task of LANE_TASKS) expect(cli.stderr).toContain(task);
- const server = new MCPServer({ vault, configPath });
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
@@ -594,7 +595,7 @@ describe("declared custom tasks are retried and refused the same way on both sur
});
async function callTool(args: Record<string, unknown>) {
- const server = new MCPServer({ vault, configPath });
+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });
await server.handleRequest({
jsonrpc: JSONRPC_VERSION,
id: 1,
diff --git a/tests/mcp/obligation-reach.test.ts b/tests/mcp/obligation-reach.test.ts
new file mode 100644
index 00000000..c419444f
--- /dev/null
+++ b/tests/mcp/obligation-reach.test.ts
@@ -0,0 +1,159 @@
+/**
+ * `brain_obligation` reads and writes obligation pages at the caller's
+ * reach.
+ *
+ * Vault A holds an obligation page withheld from a remote caller by
+ * visibility, carrying a unique title; vault B never had it. Both share
+ * a public obligation and the log of tests/helpers/reach-log-fixture.ts.
+ * A server with no reach minted is a remote caller: `list`, `show`,
+ * `done` and `remove` over the two vaults must answer identically once
+ * the volatile parts are masked, and the withheld page must stay
+ * untouched. Vault A also holds a withheld archived page of the public
+ * obligation's slug, which removing the public one must not reveal. The
+ * local control proves the withheld page is there to hide.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { addObligation, removeObligation } from "../../src/core/brain/obligations.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const PRIVATE_TITLE = "Zzreservedduty";
+const PRIVATE_SLUG = "zzreservedduty";
+const PUBLIC_TITLE = "Water the plants";
+const PUBLIC_SLUG = "water-the-plants";
+const UNSLUGGED_STEM = "Feed_The_Cat";
+const UNSLUGGED_TITLE = "Feed the cat";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const AGENT = "claude";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+interface Vault extends Fixture {
+ /** The withheld page's absolute path (vault A only). */
+ readonly privatePage: string;
+}
+
+function fixture(withPrivate: boolean): Vault {
+ const base = mkdtempSync(join(tmpdir(), "o2b-obligation-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ if (withPrivate) {
+ // An earlier page of the public slug, archived and withheld.
+ addObligation(f.vault, { title: PUBLIC_TITLE, cadence: "daily", agent: AGENT });
+ reserve(removeObligation(f.vault, PUBLIC_SLUG).archivePath);
+ }
+ addObligation(f.vault, { title: PUBLIC_TITLE, cadence: "weekly", agent: AGENT });
+ const privatePage = join(f.vault, "Brain", "obligations", `${PRIVATE_SLUG}.md`);
+ if (withPrivate) {
+ addObligation(f.vault, { title: PRIVATE_TITLE, cadence: "weekly", agent: AGENT });
+ reserve(privatePage);
+ }
+ return { ...f, privatePage };
+}
+
+/** Insert the reserve line before the closing frontmatter fence of `path`. */
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+/** The tool's masked answer, or the masked error message it threw. */
+async function obligation(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool("brain_obligation", args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (err) {
+ return `error: ${maskVolatile(f, (err as Error).message)}`;
+ }
+}
+
+describe("brain_obligation answers at the caller's reach", () => {
+ test("remote reach: list, show, done and remove answer as for an absent page", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const before = readFileSync(a.privatePage, "utf8");
+ for (const args of [
+ { operation: "list" },
+ { operation: "list", overdue: true },
+ { operation: "show", slug: PRIVATE_SLUG },
+ { operation: "done", slug: PRIVATE_SLUG },
+ { operation: "remove", slug: PRIVATE_SLUG },
+ { operation: "remove", slug: PUBLIC_SLUG },
+ ]) {
+ // Sequential on purpose: each server reads the process-wide config
+ // variable reachServer sets, so concurrent calls would race on it.
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await obligation(a, args);
+ // oxlint-disable-next-line no-await-in-loop
+ const absent = await obligation(b, args);
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(PRIVATE_TITLE);
+ }
+ expect(readFileSync(a.privatePage, "utf8")).toBe(before);
+ });
+
+ test("remote reach: add over a withheld page refuses and leaves it as it was", async () => {
+ const a = fixture(true);
+ const before = readFileSync(a.privatePage, "utf8");
+ const answer = await obligation(a, {
+ operation: "add",
+ title: PRIVATE_TITLE,
+ cadence: "daily",
+ });
+ expect(answer.startsWith("error: ")).toBe(true);
+ expect(readFileSync(a.privatePage, "utf8")).toBe(before);
+ });
+
+ test("remote reach: a readable obligation is still listed, shown and completed", async () => {
+ const a = fixture(true);
+ const listed = await obligation(a, { operation: "list" });
+ expect(listed).toContain(PUBLIC_TITLE);
+ expect(await obligation(a, { operation: "show", slug: PUBLIC_SLUG })).toContain(
+ '"present":true',
+ );
+ expect(await obligation(a, { operation: "done", slug: PUBLIC_SLUG })).toContain(PUBLIC_TITLE);
+ });
+
+ test("remote reach: a readable page whose file name is not slug-shaped is still listed", async () => {
+ const a = fixture(true);
+ const dir = join(a.vault, "Brain", "obligations");
+ const page = readFileSync(join(dir, `${PUBLIC_SLUG}.md`), "utf8");
+ writeFileSync(join(dir, `${UNSLUGGED_STEM}.md`), page.replace(PUBLIC_TITLE, UNSLUGGED_TITLE));
+ expect(await obligation(a, { operation: "list" })).toContain(UNSLUGGED_TITLE);
+ });
+
+ test("local control: the operator's own shell lists and shows the withheld page", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ expect(await obligation(a, { operation: "list" }, local)).toContain(PRIVATE_TITLE);
+ expect(await obligation(a, { operation: "show", slug: PRIVATE_SLUG }, local)).toContain(
+ PRIVATE_TITLE,
+ );
+ expect(await obligation(a, { operation: "remove", slug: PUBLIC_SLUG }, local)).toContain(
+ "archive_path",
+ );
+ });
+});
diff --git a/tests/mcp/plugin-mcp-servers.test.ts b/tests/mcp/plugin-mcp-servers.test.ts
index 0c7e219e..f282e791 100644
--- a/tests/mcp/plugin-mcp-servers.test.ts
+++ b/tests/mcp/plugin-mcp-servers.test.ts
@@ -28,16 +28,22 @@ describe("Claude Code plugin MCP servers", () => {
]);
});
+ // Both registrations name the harness that launches them, so the
+ // server can match `Brain/standing-rules/harness/claude-code.md`
+ // without trusting anything a caller says about itself.
test("full server runs o2b mcp from the plugin root without alwaysLoad", () => {
const f = servers["open-second-brain"]!;
- expect(f).toEqual({ command: "${CLAUDE_PLUGIN_ROOT}/scripts/o2b", args: ["mcp"] });
+ expect(f).toEqual({
+ command: "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",
+ args: ["mcp", "--harness", "claude-code"],
+ });
expect(f.alwaysLoad).toBeUndefined();
});
- test("writer server passes --scope writer and alwaysLoad: true", () => {
+ test("writer server passes --scope writer, the harness and alwaysLoad: true", () => {
expect(servers["open-second-brain-writer"]).toEqual({
command: "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",
- args: ["mcp", "--scope", "writer"],
+ args: ["mcp", "--scope", "writer", "--harness", "claude-code"],
alwaysLoad: true,
});
});
diff --git a/tests/mcp/review-tools-reach.test.ts b/tests/mcp/review-tools-reach.test.ts
new file mode 100644
index 00000000..be9078a5
--- /dev/null
+++ b/tests/mcp/review-tools-reach.test.ts
@@ -0,0 +1,189 @@
+/**
+ * The lifecycle review readers - `brain_stale_scan`,
+ * `brain_review_candidates`, `brain_retention` and `brain_intent_review` -
+ * answer at the caller's reach.
+ *
+ * The vault pair is tests/helpers/reach-log-fixture.ts: vault A holds a
+ * reserved preference and a reserved retired record; vault B never had
+ * them. Vault A also holds two withheld preferences whose last evidence
+ * is months old, so the stale scan lists them and the dream preview
+ * would retire them, and both vaults hold one readable preference in the
+ * same state, so a remote answer is never empty. The same holds for an
+ * old processed signal the retention review recommends pruning: a
+ * withheld one in vault A, a readable one in both. The signal clusters the
+ * dream preview and the intent review fold are built the same way: vault A
+ * holds a withheld inbox signal on a topic of its own and a second one on
+ * the readable cluster's topic, which would move that cluster's count. A
+ * server with no reach minted is a remote caller: each tool's whole
+ * masked answer, and that of a `brain_trigger` scan over the retention
+ * rows, must be the same over both vaults. The local control proves the
+ * withheld records are there to list.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { processedSignalPath, signalPath } from "../../src/core/brain/paths.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ RETIRED_SLUG,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const WITHHELD_PREFIX = "zzwithheld-stale";
+const READABLE_SLUG = "public-stale";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const CLUSTER_TOPIC = "public-cluster";
+const WITHHELD_CLUSTER_TOPIC = `${WITHHELD_PREFIX}-cluster`;
+const TOOLS = [
+ "brain_stale_scan",
+ "brain_review_candidates",
+ "brain_retention",
+ "brain_intent_review",
+] as const;
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+/** Insert the reserve line before the closing frontmatter fence of `path`. */
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+/** An old processed signal, which the retention review recommends pruning. */
+function processedSignal(vault: string, slug: string, reserved: boolean): void {
+ const date = "2026-04-01";
+ writeSignal(vault, {
+ topic: slug,
+ signal: "negative",
+ agent: "test",
+ principle: `old one-off signal ${slug}`,
+ created_at: `${date}T00:00:00Z`,
+ date,
+ slug,
+ });
+ const path = processedSignalPath(vault, date, slug);
+ renameSync(signalPath(vault, date, slug), path);
+ if (reserved) reserve(path);
+}
+
+/** An inbox signal written today, so the dream preview and the intent review fold it. */
+function inboxSignal(vault: string, topic: string, slug: string, reserved: boolean): void {
+ const date = new Date().toISOString().slice(0, 10);
+ writeSignal(vault, {
+ topic,
+ signal: "positive",
+ agent: "test",
+ principle: `Prefer ${topic}.`,
+ created_at: `${date}T00:00:00Z`,
+ date,
+ slug,
+ });
+ if (reserved) reserve(signalPath(vault, date, slug));
+}
+
+/** A confirmed preference whose last evidence is months old and never logged since. */
+function stalePreference(vault: string, slug: string, reserved: boolean): void {
+ writePreference(vault, {
+ slug,
+ topic: slug,
+ principle: `Rule ${slug}.`,
+ created_at: "2026-05-01T00:00:00Z",
+ unconfirmed_until: "2026-05-08T00:00:00Z",
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [],
+ confirmed_at: "2026-05-02T00:00:00Z",
+ applied_count: 1,
+ violated_count: 0,
+ last_evidence_at: "2026-05-02T00:00:00Z",
+ confidence: BRAIN_CONFIDENCE.high,
+ confidence_value: 0.8,
+ });
+ if (reserved) reserve(join(vault, "Brain", "preferences", `pref-${slug}.md`));
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-review-tools-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ stalePreference(f.vault, READABLE_SLUG, false);
+ processedSignal(f.vault, READABLE_SLUG, false);
+ inboxSignal(f.vault, CLUSTER_TOPIC, CLUSTER_TOPIC, false);
+ if (withPrivate) {
+ inboxSignal(f.vault, WITHHELD_CLUSTER_TOPIC, WITHHELD_CLUSTER_TOPIC, true);
+ inboxSignal(f.vault, CLUSTER_TOPIC, `${WITHHELD_PREFIX}-second`, true);
+ for (const suffix of ["a", "b"]) stalePreference(f.vault, `${WITHHELD_PREFIX}-${suffix}`, true);
+ processedSignal(f.vault, `${WITHHELD_PREFIX}-signal`, true);
+ }
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ tool: string,
+ reach?: TransportReach,
+ args: Record<string, unknown> = {},
+): Promise<string> {
+ const result = await reachServer(f, reach).callTool(tool, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+}
+
+describe("the lifecycle review readers answer at the caller's reach", () => {
+ for (const tool of TOOLS) {
+ test(`remote reach: ${tool} names no withheld record`, async () => {
+ const withheld = await answer(fixture(true), tool);
+ const absent = await answer(fixture(false), tool);
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(WITHHELD_PREFIX);
+ expect(withheld).not.toContain(RETIRED_SLUG);
+ });
+ }
+
+ test("remote reach: the readable stale preference is still listed", async () => {
+ const a = fixture(true);
+ expect(await answer(a, "brain_stale_scan")).toContain(READABLE_SLUG);
+ expect(await answer(a, "brain_review_candidates")).toContain(READABLE_SLUG);
+ expect(await answer(a, "brain_retention")).toContain(READABLE_SLUG);
+ expect(await answer(a, "brain_review_candidates")).toContain(CLUSTER_TOPIC);
+ expect(await answer(a, "brain_intent_review")).toContain(CLUSTER_TOPIC);
+ });
+
+ test("local control: the operator's own shell lists the withheld records", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ expect(await answer(a, "brain_stale_scan", local)).toContain(WITHHELD_PREFIX);
+ expect(await answer(a, "brain_review_candidates", local)).toContain(WITHHELD_PREFIX);
+ expect(await answer(a, "brain_retention", local)).toContain(WITHHELD_PREFIX);
+ expect(await answer(a, "brain_intent_review", local)).toContain(WITHHELD_CLUSTER_TOPIC);
+ });
+
+ test("remote reach: a trigger scan queues nothing from a withheld retention row", async () => {
+ const scan = { operation: "scan" };
+ const withheld = await answer(fixture(true), "brain_trigger", undefined, scan);
+ const absent = await answer(fixture(false), "brain_trigger", undefined, scan);
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(WITHHELD_PREFIX);
+ });
+
+ test("remote reach: a trigger scan still queues the readable retention row", async () => {
+ const scan = { operation: "scan" };
+ expect(await answer(fixture(true), "brain_trigger", undefined, scan)).toContain(READABLE_SLUG);
+ });
+});
diff --git a/tests/mcp/scaffold-stub-reach.test.ts b/tests/mcp/scaffold-stub-reach.test.ts
new file mode 100644
index 00000000..1e9cfd83
--- /dev/null
+++ b/tests/mcp/scaffold-stub-reach.test.ts
@@ -0,0 +1,161 @@
+/**
+ * `brain_scaffold_stub` answers at the caller's reach.
+ *
+ * Vault A holds a note withheld from a remote caller by visibility, which
+ * links to a missing page; vault B never had it. Both hold the same public
+ * note with its own dangling link. A server with no reach minted is a
+ * remote caller: a withheld note named as a stub source is refused exactly
+ * as a missing one (nothing written), the dangling list carries neither
+ * the withheld note nor the target only it links to, and the refusal for a
+ * target that resolves to the withheld note does not name its path. The
+ * local control proves the withheld note is there.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import type { MCPError } from "../../src/mcp/protocol.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_scaffold_stub";
+const PUBLIC_NOTE = "Notes/public.md";
+const PRIVATE_NOTE = "Deep/withheld.md";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function write(f: Fixture, rel: string, text: string): void {
+ mkdirSync(join(f.vault, rel, ".."), { recursive: true });
+ writeFileSync(join(f.vault, rel), text);
+}
+
+async function fixture(withPrivate: boolean): Promise<Fixture> {
+ const base = mkdtempSync(join(tmpdir(), "o2b-scaffold-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, false);
+ write(f, PUBLIC_NOTE, "# Public\n\nSee [[Shared Ghost]].\n");
+ if (withPrivate) {
+ write(
+ f,
+ PRIVATE_NOTE,
+ `---\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n---\n\n# Withheld\n\nSee [[Shared Ghost]] and [[Nightingale Plan]].\n`,
+ );
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = f.configPath;
+ await indexVault(resolveSearchConfig({ vault: f.vault, configPath: f.configPath }), {
+ force: true,
+ });
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** The Markdown notes outside Brain/: what a stub write would add to. */
+function notes(root: string, rel = ""): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
+ const child = rel === "" ? entry.name : `${rel}/${entry.name}`;
+ if (entry.isDirectory()) {
+ if (!child.startsWith("Brain") && !child.startsWith(".")) out.push(...notes(root, child));
+ } else if (child.endsWith(".md")) out.push(child);
+ }
+ return out.toSorted();
+}
+
+const SOURCE_WRITES: ReadonlyArray<[string, Record<string, unknown>]> = [
+ ["plan", { action: "write", target: "Shared Ghost", sources: [PRIVATE_NOTE] }],
+ ["apply", { action: "write", target: "Shared Ghost", sources: [PRIVATE_NOTE], apply: true }],
+];
+
+describe("brain_scaffold_stub answers at the caller's reach", () => {
+ for (const [name, args] of SOURCE_WRITES) {
+ test(`remote reach: a withheld source is refused as a missing one (${name})`, async () => {
+ const a = await fixture(true);
+ const before = notes(a.vault);
+ const withheld = await answer(a, args);
+ expect(withheld).toBe(await answer(await fixture(false), args));
+ expect(withheld).toContain("is not an existing Markdown note");
+ expect(notes(a.vault)).toEqual(before);
+ });
+ }
+
+ test("remote reach: the dangling list leaves out the withheld note and its own target", async () => {
+ const args = { action: "list" };
+ const withheld = await answer(await fixture(true), args);
+ expect(withheld).toBe(await answer(await fixture(false), args));
+ expect(withheld).toContain("Shared Ghost");
+ expect(withheld).not.toContain("Nightingale");
+ });
+
+ test("remote reach: a target resolving to the withheld note does not name its path", async () => {
+ const withheld = await answer(await fixture(true), {
+ action: "write",
+ target: "Deep/withheld",
+ });
+ expect(withheld).toContain("already resolves to a note");
+ expect(withheld).not.toContain(PRIVATE_NOTE);
+ });
+
+ test("remote reach: an ambiguity among withheld notes names no candidate list", async () => {
+ const a = await fixture(false);
+ const hidden = `---\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n---\n\n# Twin\n`;
+ write(a, "Deep/twin.md", hidden);
+ write(a, "Other/twin.md", hidden);
+ // The title resolver walks the declared note roots only.
+ const brainYaml = join(a.vault, "Brain", "_brain.yaml");
+ writeFileSync(
+ brainYaml,
+ `${readFileSync(brainYaml, "utf8")}\nnotes:\n read_paths:\n - Deep\n - Other\n`,
+ );
+ let refusal: MCPError | null = null;
+ try {
+ await reachServer(a).callTool(TOOL, { action: "write", target: "twin" });
+ } catch (error) {
+ refusal = error as MCPError;
+ }
+ expect(refusal?.message).toContain("already names more than one note");
+ expect(refusal?.message.endsWith(": ")).toBe(false);
+ expect(refusal?.message).not.toContain("twin.md");
+ expect((refusal?.data as Record<string, unknown> | undefined)?.["candidates"]).toBeUndefined();
+ });
+
+ test("local control: the operator's own shell cites and lists the withheld note", async () => {
+ const a = await fixture(true);
+ const local = TRANSPORT_REACH.local;
+ expect(await answer(a, { action: "list" }, local)).toContain("Nightingale");
+ expect(await answer(a, SOURCE_WRITES[0]![1], local)).toContain('"applied":false');
+ expect(await answer(a, { action: "write", target: "Deep/withheld" }, local)).toContain(
+ PRIVATE_NOTE,
+ );
+ expect(readFileSync(join(a.vault, PRIVATE_NOTE), "utf8")).toContain("Nightingale");
+ });
+});
diff --git a/tests/mcp/tension-reach.test.ts b/tests/mcp/tension-reach.test.ts
new file mode 100644
index 00000000..70d772a6
--- /dev/null
+++ b/tests/mcp/tension-reach.test.ts
@@ -0,0 +1,183 @@
+/**
+ * `brain_tension` answers at the caller's reach.
+ *
+ * Both vaults carry the log of tests/helpers/reach-log-fixture.ts and a
+ * note corpus under `Notes/` with one public pair that contradicts itself
+ * (so a remote answer is never empty) and a public note on indentation.
+ * Vault A also holds a note withheld from a remote caller by visibility
+ * that contradicts the public indentation note; vault B never had it. A
+ * server with no reach minted is a remote caller: detect, list, show,
+ * verify and the transitions over the two vaults must answer identically
+ * once the volatile parts are masked, and a withheld tension page is
+ * neither shown nor rewritten. The local control proves the withheld
+ * tension is there to find.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ appendFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const TOOL = "brain_tension";
+/** The frontmatter id of the withheld note; a tension names its subjects by id. */
+const PRIVATE_ID = "note-zzwithheld";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+/** The line a tension page derived from the withheld note carries. */
+const STAMPED_LINE = `visibility: [${JSON.stringify(REMOTE_DENY_VISIBILITY_TOKEN)}]`;
+/** The withheld note's own wording, which a tension quotes. */
+const PRIVATE_QUOTE = "Always indent source files with tabs";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+function note(vault: string, name: string, id: string, body: string, reserved = false): void {
+ const front = [`id: ${id}`, ...(reserved ? [RESERVE_LINE] : [])].join("\n");
+ writeFileSync(join(vault, "Notes", name), `---\n${front}\n---\n${body}\n`);
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-tension-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ appendFileSync(join(f.vault, "Brain", "_brain.yaml"), "\nnotes:\n read_paths:\n - Notes\n");
+ mkdirSync(join(f.vault, "Notes"), { recursive: true });
+ note(f.vault, "spaces.md", "note-spaces", "Never indent source files with tabs.");
+ note(f.vault, "deploy-yes.md", "note-deploy-yes", "Always deploy the release branch on Fridays.");
+ note(f.vault, "deploy-no.md", "note-deploy-no", "Never deploy the release branch on Fridays.");
+ if (withPrivate) note(f.vault, "tabs.md", PRIVATE_ID, `${PRIVATE_QUOTE}.`, true);
+ return f;
+}
+
+async function answer(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool(TOOL, args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (error) {
+ // A refusal is part of the answer: it must read alike over both vaults.
+ return maskVolatile(f, { error: (error as Error).message });
+ }
+}
+
+/** Run a local detect, so the tension pages exist on disk. */
+async function detectLocally(f: Fixture): Promise<string> {
+ return answer(f, { action: "detect" }, TRANSPORT_REACH.local);
+}
+
+interface Row {
+ readonly slug: string;
+ readonly subject_a: string;
+ readonly subject_b: string;
+}
+
+/** The slug of the tension the withheld note takes part in, from a local answer on vault A. */
+function withheldSlug(localDetect: string): string {
+ const rows = (JSON.parse(localDetect) as { tensions: ReadonlyArray<Row> }).tensions;
+ const row = rows.find((r) => r.subject_a === PRIVATE_ID || r.subject_b === PRIVATE_ID);
+ if (row === undefined) throw new Error("the local detect found no withheld tension");
+ return row.slug;
+}
+
+function tensionPage(f: Fixture, slug: string): string {
+ return join(f.vault, "Brain", "tensions", `tension-${slug}.md`);
+}
+
+describe("brain_tension answers at the caller's reach", () => {
+ test("remote reach: detect neither reads nor persists a withheld note", async () => {
+ const withheld = await answer(fixture(true), { action: "detect" });
+ const absent = await answer(fixture(false), { action: "detect" });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(PRIVATE_ID);
+ expect(absent).toContain("note-deploy");
+ });
+
+ test("remote reach: list and verify leave out a tension a local detect persisted", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ await detectLocally(a);
+ await detectLocally(b);
+ for (const args of [
+ { action: "list" },
+ { action: "list", unresolved: true },
+ { action: "verify" },
+ ]) {
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await answer(a, args);
+ // oxlint-disable-next-line no-await-in-loop
+ expect(withheld).toBe(await answer(b, args));
+ expect(withheld).not.toContain(PRIVATE_ID);
+ }
+ });
+
+ test("remote reach: show and the transitions answer a withheld tension as an absent one", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const slug = withheldSlug(await detectLocally(a));
+ await detectLocally(b);
+ const page = readFileSync(tensionPage(a, slug), "utf8");
+ for (const action of ["show", "verify", "confirm", "dismiss", "resolve"]) {
+ // In turn: a transition the guard let through would change the next answer.
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await answer(a, { action, slug });
+ // oxlint-disable-next-line no-await-in-loop
+ expect(withheld).toBe(await answer(b, { action, slug }));
+ expect(withheld).toContain(`no tension: ${slug}`);
+ }
+ expect(readFileSync(tensionPage(a, slug), "utf8")).toBe(page);
+ });
+
+ test("local control: the operator's own shell sees and quotes the withheld tension", async () => {
+ const a = fixture(true);
+ const slug = withheldSlug(await detectLocally(a));
+ const shown = await answer(a, { action: "show", slug }, TRANSPORT_REACH.local);
+ expect(shown).toContain(PRIVATE_QUOTE);
+ expect(await answer(a, { action: "list" }, TRANSPORT_REACH.local)).toContain(PRIVATE_ID);
+ expect(readFileSync(tensionPage(a, slug), "utf8")).toContain(STAMPED_LINE);
+ });
+
+ test("a local re-detect restamps a tension page whose source note became reserved", async () => {
+ const a = fixture(false);
+ const b = fixture(false);
+ // The note starts at default visibility, so the first detect persists
+ // a default-visibility tension page that quotes it.
+ note(a.vault, "tabs.md", PRIVATE_ID, `${PRIVATE_QUOTE}.`);
+ const slug = withheldSlug(await detectLocally(a));
+ expect(readFileSync(tensionPage(a, slug), "utf8")).not.toContain(STAMPED_LINE);
+ // The operator reserves the note; the next local detect must carry
+ // that onto the page that quotes it.
+ note(a.vault, "tabs.md", PRIVATE_ID, `${PRIVATE_QUOTE}.`, true);
+ await detectLocally(a);
+ // Vault B never had the note; two detects keep its counts in step.
+ await detectLocally(b);
+ await detectLocally(b);
+ expect(readFileSync(tensionPage(a, slug), "utf8")).toContain(STAMPED_LINE);
+ const withheld = await answer(a, { action: "list" });
+ expect(withheld).toBe(await answer(b, { action: "list" }));
+ expect(withheld).not.toContain(PRIVATE_ID);
+ });
+});
diff --git a/tests/mcp/today-open-loops-reach.test.ts b/tests/mcp/today-open-loops-reach.test.ts
new file mode 100644
index 00000000..ea41d0f8
--- /dev/null
+++ b/tests/mcp/today-open-loops-reach.test.ts
@@ -0,0 +1,118 @@
+/**
+ * `brain_brief view=today` answers its open loops and obligations at the
+ * caller's reach.
+ *
+ * Vault A holds a note under `notes.read_paths` and an obligation page,
+ * both withheld from a remote caller by visibility, each carrying a
+ * unique marker; vault B never had either. Both share a public note with
+ * its own loop, a public obligation and the log of
+ * tests/helpers/reach-log-fixture.ts. A server with no reach minted is a
+ * remote caller: its answers over the two vaults must be identical once
+ * the volatile parts are masked. The local control proves the withheld
+ * items are there to hide.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ appendFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { addObligation } from "../../src/core/brain/obligations.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const PRIVATE_PATH = "Notes/PRIVATE_PATH.md";
+const PRIVATE_LOOP = "zzreservedloopzz";
+const PRIVATE_OBLIGATION = "Zzreservedduty";
+const PUBLIC_LOOP = "call the plumber";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const AGENT = "claude";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+/** Insert the reserve line before the closing frontmatter fence of `abs`. */
+function reserve(abs: string): void {
+ const text = readFileSync(abs, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(abs, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+function fixture(withPrivate: boolean): Fixture {
+ const base = mkdtempSync(join(tmpdir(), "o2b-today-loops-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ appendFileSync(join(f.vault, "Brain", "_brain.yaml"), "\nnotes:\n read_paths:\n - Notes\n");
+ mkdirSync(join(f.vault, "Notes"), { recursive: true });
+ writeFileSync(join(f.vault, "Notes", "open.md"), `# open\n\n@osb loop ${PUBLIC_LOOP}\n`);
+ addObligation(f.vault, { title: "Water the plants", cadence: "weekly", agent: AGENT });
+ if (withPrivate) {
+ writeFileSync(
+ join(f.vault, PRIVATE_PATH),
+ `---\n${RESERVE_LINE}\n---\n# p\n\n@osb loop ${PRIVATE_LOOP}\n`,
+ );
+ const duty = addObligation(f.vault, {
+ title: PRIVATE_OBLIGATION,
+ cadence: "weekly",
+ agent: AGENT,
+ });
+ reserve(duty.path);
+ }
+ return f;
+}
+
+async function today(f: Fixture, reach?: TransportReach): Promise<Record<string, unknown>> {
+ const result = (await reachServer(f, reach).callTool("brain_brief", {
+ view: "today",
+ })) as Record<string, unknown>;
+ return (result["structuredContent"] ?? result) as Record<string, unknown>;
+}
+
+describe("brain_brief view=today answers at the caller's reach", () => {
+ test("remote reach: the withheld loop and obligation change nothing", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const answerA = await today(a);
+ const answerB = await today(b);
+ const textA = maskVolatile(a, answerA);
+ expect(textA).not.toContain(PRIVATE_LOOP);
+ expect(textA).not.toContain("PRIVATE_PATH");
+ expect(textA.toLowerCase()).not.toContain(PRIVATE_OBLIGATION.toLowerCase());
+ expect(textA).toContain(PUBLIC_LOOP);
+ expect(textA).toBe(maskVolatile(b, answerB));
+ });
+
+ test("local control: the operator's own shell still sees both", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const local = maskVolatile(a, await today(a, TRANSPORT_REACH.local));
+ expect(local).toContain(PRIVATE_LOOP);
+ expect(local).toContain("PRIVATE_PATH");
+ expect(local.toLowerCase()).toContain(PRIVATE_OBLIGATION.toLowerCase());
+ const totals = (await today(a, TRANSPORT_REACH.local))["totals"] as Record<string, number>;
+ const totalsB = (await today(b, TRANSPORT_REACH.local))["totals"] as Record<string, number>;
+ expect(totals["openLoopsCount"]).toBe(2);
+ expect(totals["scannedFiles"]).toBe(2);
+ expect(totals["obligationsTotal"]).toBe(2);
+ expect(totalsB["openLoopsCount"]).toBe(1);
+ });
+});
diff --git a/tests/mcp/visibility-matrix.test.ts b/tests/mcp/visibility-matrix.test.ts
index e41e6ec4..8a00f7ad 100644
--- a/tests/mcp/visibility-matrix.test.ts
+++ b/tests/mcp/visibility-matrix.test.ts
@@ -498,19 +498,14 @@ const COVERED_TOOLS: ReadonlySet<string> = new Set(
* should. A surface leaving this list is the wave that covered it; a
* surface joining it is a regression, and either way the diff says so.
*
- * The list is per RECIPE rather than per tool because a tool is not one
- * classification: `brain_trigger operation=scan` names the pages it
- * queued and `brain_trigger operation=terminal` does not.
+ * The list is per RECIPE rather than per tool because a tool need not be
+ * one classification: `brain_trigger operation=scan` named the pages it
+ * queued while a transition did not, until the reach view joined its
+ * owner view and its sources ran over the readable records.
*/
const STILL_NAMED_AT_REMOTE: ReadonlySet<string> = new Set([
"brain_anticipatory_context",
"brain_context_pack",
- "brain_retention",
- "brain_scaffold_stub action=list",
- "brain_stale_scan",
- "brain_trigger operation=history",
- "brain_trigger operation=list",
- "brain_trigger operation=scan",
]);
/**
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 4f1d0d9d..3e36ede9 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -60,6 +60,7 @@ _CONFIG_ENV_KEYS = (
cfg.VAULT_DIR_ENV,
cfg.TIMEZONE_ENV,
cfg.CONFIG_PATH_ENV,
+ cfg.REQUEST_TIMEOUT_ENV,
)
@@ -1738,6 +1739,27 @@ class McpBrainBridgeTests(unittest.TestCase):
McpBrainBridge(vault="/v", spawn=spy).start()
self.assertNotIn("--repo", captured["argv"])
+ def test_argv_ends_with_the_hermes_harness(self):
+ # The server resolves its harness scope from this launch argument
+ # alone; it never trusts a name the client gives about itself.
+ cases = (
+ ({"vault": "/v", "repo_root": "/r"}, ["o2b", "mcp", "--vault", "/v", "--repo", "/r"]),
+ ({"vault": "/v"}, ["o2b", "mcp", "--vault", "/v"]),
+ ({"vault": None, "repo_root": "/r"}, ["o2b", "mcp", "--repo", "/r"]),
+ ({"vault": None}, ["o2b", "mcp"]),
+ )
+ self.assertEqual(bridge_module.HARNESS_ARGV, ("--harness", "hermes"))
+ for kwargs, head in cases:
+ with self.subTest(**kwargs):
+ captured = {}
+
+ def spy(argv):
+ captured["argv"] = argv
+ return _FakeProcess(self._handshake_frames())
+
+ McpBrainBridge(spawn=spy, **kwargs).start()
+ self.assertEqual(captured["argv"], [*head, "--harness", "hermes"])
+
def test_stop_terminates_process(self):
proc = _FakeProcess(self._handshake_frames())
bridge = McpBrainBridge(vault="/v", spawn=lambda argv: proc)
diff --git a/tests/python/test_profile_scope.py b/tests/python/test_profile_scope.py
new file mode 100644
index 00000000..651fe00a
--- /dev/null
+++ b/tests/python/test_profile_scope.py
@@ -0,0 +1,784 @@
+"""Two-mode settings for the Hermes plugin on a multiplexed gateway.
+
+A Hermes gateway with ``multiplex_profiles`` serves several profiles from one
+process, and the process environment belongs to the launch profile. Under
+multiplexing every profile-scoped setting must therefore come from the turn's
+profile scope (``agent.secret_scope``), never from ``os.environ``; without
+multiplexing the plugin must answer exactly as it always has.
+
+Hermes is not installed in CI, so a fake ``agent.secret_scope`` is injected
+through ``sys.modules``. ``config.py`` imports it lazily per call, so the stub
+takes effect without reloading anything.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import os
+import sys
+import tempfile
+import threading
+import types
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[2]
+if str(ROOT) not in sys.path:
+ sys.path.insert(0, str(ROOT))
+
+from plugins.hermes import bridge as bridge_module # noqa: E402
+from plugins.hermes import config as cfg # noqa: E402
+from plugins.hermes import provider as provider_module # noqa: E402
+from plugins.hermes.bridge import FakeBrainBridge, McpBrainBridge # noqa: E402
+from plugins.hermes.provider import OpenSecondBrainMemoryProvider # noqa: E402
+
+# Process-environment values that belong to the LAUNCH profile. None of them
+# may surface under multiplexing, in a result or in a message.
+LAUNCH_VALUES = {
+ "VAULT_DIR": "launch-vault-dir-value",
+ "VAULT_AGENT_NAME": "launch-agent-value",
+ "VAULT_TIMEZONE": "Launch/Zone",
+ "OPEN_SECOND_BRAIN_CONFIG": "launch-config-path-value.yaml",
+ "OPEN_SECOND_BRAIN_MCP_TIMEOUT": "4242",
+}
+
+_ISOLATED_ENV = (*LAUNCH_VALUES.keys(), cfg.XDG_CONFIG_HOME_ENV)
+
+
+class FakeUnscopedError(RuntimeError):
+ """Stands in for Hermes's ``UnscopedSecretError``."""
+
+
+def make_fake_scope(*, multiplexed: bool, values: dict | None = None, unbound: bool = False):
+ """A fake ``agent`` package and ``agent.secret_scope`` module.
+
+ ``reads`` records every name the plugin asked the scope for, so a test can
+ prove the scope was (or was not) consulted.
+ """
+ pkg = types.ModuleType("agent")
+ pkg.__path__ = []
+ fake = types.ModuleType("agent.secret_scope")
+ scoped_values = dict(values or {})
+ reads: list[str] = []
+
+ def is_multiplex_active() -> bool:
+ return multiplexed
+
+ def get_secret(name, default=None):
+ reads.append(name)
+ if unbound:
+ raise FakeUnscopedError(f"{name} has no bound profile scope")
+ return scoped_values.get(name, default)
+
+ fake.is_multiplex_active = is_multiplex_active
+ fake.get_secret = get_secret
+ fake.UnscopedSecretError = FakeUnscopedError
+ fake.reads = reads
+ pkg.secret_scope = fake
+ return pkg, fake
+
+
+class ScopeTestCase(unittest.TestCase):
+ """Isolates every scoped name and the XDG directory per test."""
+
+ def setUp(self):
+ self._saved = {k: os.environ.pop(k, None) for k in _ISOLATED_ENV}
+ self._tmp = tempfile.TemporaryDirectory()
+ self.tmp = Path(self._tmp.name)
+ reset = getattr(cfg, "_reset_scope_warnings_for_tests", None)
+ if reset is not None:
+ reset()
+
+ def tearDown(self):
+ for k in _ISOLATED_ENV:
+ os.environ.pop(k, None)
+ if self._saved[k] is not None:
+ os.environ[k] = self._saved[k]
+ self._tmp.cleanup()
+ reset = getattr(cfg, "_reset_scope_warnings_for_tests", None)
+ if reset is not None:
+ reset()
+
+ def install(self, fake_pair):
+ pkg, fake = fake_pair
+ return patch.dict(sys.modules, {"agent": pkg, "agent.secret_scope": fake})
+
+ def no_hermes(self):
+ # A ``None`` entry makes the import raise ImportError, whatever is on
+ # the machine running the suite.
+ return patch.dict(sys.modules, {"agent": None, "agent.secret_scope": None})
+
+ def set_launch_env(self):
+ os.environ.update(LAUNCH_VALUES)
+
+ def write_xdg_config(self, body: str) -> Path:
+ xdg = self.tmp / "xdg"
+ path = xdg / cfg.PLUGIN_NAME / cfg.CONFIG_FILENAME
+ path.parent.mkdir(parents=True)
+ path.write_text(body, encoding="utf-8")
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(xdg)
+ return path
+
+
+class ContractTests(unittest.TestCase):
+ def test_scoped_names_are_the_five_profile_settings(self):
+ self.assertEqual(
+ cfg.PROFILE_SCOPED_ENV,
+ (
+ "VAULT_DIR",
+ "VAULT_AGENT_NAME",
+ "VAULT_TIMEZONE",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ "OPEN_SECOND_BRAIN_MCP_TIMEOUT",
+ ),
+ )
+ self.assertEqual(cfg.REQUEST_TIMEOUT_ENV, "OPEN_SECOND_BRAIN_MCP_TIMEOUT")
+
+ def test_os_level_variables_are_not_scoped(self):
+ for name in ("XDG_CONFIG_HOME", "LOCALAPPDATA", "PATH", "PATHEXT", "HOME"):
+ self.assertNotIn(name, cfg.PROFILE_SCOPED_ENV)
+
+ def test_config_directories_are_scope_first(self):
+ self.assertEqual(cfg.SCOPE_FIRST_ENV, ("XDG_CONFIG_HOME", "LOCALAPPDATA"))
+
+
+class WithoutHermesTests(ScopeTestCase):
+ """(a) No ``agent.secret_scope``: today's answers."""
+
+ def test_not_multiplexed_and_process_environment_answers(self):
+ self.set_launch_env()
+ with self.no_hermes():
+ self.assertFalse(cfg.is_multiplexed())
+ self.assertEqual(cfg.resolve_agent_name(), "launch-agent-value")
+ self.assertEqual(cfg.resolve_vault(str(self.tmp)), "launch-vault-dir-value")
+ self.assertEqual(cfg.resolve_timezone(), "Launch/Zone")
+ self.assertEqual(cfg.config_path(), Path("launch-config-path-value.yaml"))
+ self.assertEqual(cfg.env_setting("VAULT_AGENT_NAME"), "launch-agent-value")
+
+ def test_empty_value_counts_as_unset(self):
+ os.environ["VAULT_AGENT_NAME"] = ""
+ with self.no_hermes():
+ self.assertIsNone(cfg.env_setting("VAULT_AGENT_NAME"))
+
+
+class BrokenScopeModuleTests(ScopeTestCase):
+ """A Hermes scope module that is present but fails to import fails closed."""
+
+ def _hermes_on_path(self, secret_scope_source: str | None):
+ """A real ``agent`` package on ``sys.path``; ``None`` omits ``secret_scope``."""
+ root = Path(tempfile.mkdtemp(prefix="hermes-src-", dir=self.tmp))
+ package = root / "agent"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text("", encoding="utf-8")
+ if secret_scope_source is not None:
+ (package / "secret_scope.py").write_text(secret_scope_source, encoding="utf-8")
+ stack = contextlib.ExitStack()
+ stack.enter_context(patch.object(sys, "path", [str(root), *sys.path]))
+ stack.enter_context(patch.dict(sys.modules))
+ for name in ("agent", "agent.secret_scope"):
+ sys.modules.pop(name, None)
+ return stack
+
+ def test_a_failing_import_refuses_scoped_reads_and_warns_once_by_type(self):
+ self.set_launch_env()
+ failures = {
+ "RuntimeError": "raise RuntimeError('launch-vault-dir-value')\n",
+ "ModuleNotFoundError": "import o2b_hermes_dependency_that_is_absent\n",
+ }
+ for type_name, source in failures.items():
+ with self.subTest(failure=type_name):
+ cfg._reset_scope_warnings_for_tests()
+ with (
+ self._hermes_on_path(source),
+ self.assertLogs("plugins.hermes.config", "WARNING") as logs,
+ ):
+ self.assertTrue(cfg.is_multiplexed())
+ with self.assertRaises(cfg.ProfileScopeError):
+ cfg.resolve_agent_name()
+ with self.assertRaises(cfg.ProfileScopeError):
+ cfg.config_path()
+ self.assertEqual(cfg.env_setting("PATH"), os.environ.get("PATH") or None)
+ failed = [
+ r.getMessage() for r in logs.records if "failed to import" in r.getMessage()
+ ]
+ self.assertEqual(len(failed), 1)
+ self.assertIn(type_name, failed[0])
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, failed[0])
+
+ def test_a_failed_import_is_tried_once_until_reset(self):
+ calls = []
+
+ def failing_import(name, *args, **kwargs):
+ calls.append(name)
+ raise ImportError("scope module is broken")
+
+ with (
+ patch.object(cfg.importlib, "import_module", side_effect=failing_import),
+ self.assertLogs("plugins.hermes.config", "WARNING"),
+ ):
+ for _ in range(2):
+ with self.assertRaises(cfg.ProfileScopeError):
+ cfg.env_setting("VAULT_AGENT_NAME")
+ self.assertEqual(calls, [cfg._SCOPE_MODULE_NAME])
+ cfg._reset_scope_warnings_for_tests()
+ with self.assertRaises(cfg.ProfileScopeError):
+ cfg.env_setting("VAULT_AGENT_NAME")
+ self.assertEqual(len(calls), 2)
+
+ def test_a_hermes_without_the_scope_module_reads_the_process_environment(self):
+ self.set_launch_env()
+ with self._hermes_on_path(None), self.assertNoLogs("plugins.hermes.config", "WARNING"):
+ self.assertFalse(cfg.is_multiplexed())
+ self.assertEqual(cfg.resolve_agent_name(), "launch-agent-value")
+
+
+class MultiplexOffTests(ScopeTestCase):
+ """(b) Hermes present, multiplexing off: the process environment wins."""
+
+ def test_process_environment_answers_and_the_scope_is_never_read(self):
+ self.set_launch_env()
+ pair = make_fake_scope(multiplexed=False, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair):
+ self.assertFalse(cfg.is_multiplexed())
+ self.assertEqual(cfg.resolve_agent_name(), "launch-agent-value")
+ self.assertEqual(cfg.resolve_vault(str(self.tmp)), "launch-vault-dir-value")
+ self.assertEqual(cfg.resolve_timezone(), "Launch/Zone")
+ self.assertEqual(cfg.config_path(), Path("launch-config-path-value.yaml"))
+ self.assertEqual(pair[1].reads, [])
+
+
+class MultiplexedScopeTests(ScopeTestCase):
+ """(c) Multiplexed with a bound scope: scoped values beat the launch env."""
+
+ def test_scoped_values_beat_conflicting_process_values(self):
+ self.set_launch_env()
+ scoped_config = self.tmp / "scoped.yaml"
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={
+ "VAULT_DIR": "scoped-vault",
+ "VAULT_AGENT_NAME": "scoped-agent",
+ "VAULT_TIMEZONE": "Europe/Paris",
+ "OPEN_SECOND_BRAIN_CONFIG": str(scoped_config),
+ "OPEN_SECOND_BRAIN_MCP_TIMEOUT": "7",
+ },
+ )
+ with self.install(pair):
+ self.assertTrue(cfg.is_multiplexed())
+ self.assertEqual(cfg.resolve_vault(str(self.tmp)), "scoped-vault")
+ self.assertEqual(cfg.resolve_agent_name(), "scoped-agent")
+ self.assertEqual(cfg.resolve_timezone(), "Europe/Paris")
+ self.assertEqual(cfg.config_path(), scoped_config)
+ self.assertEqual(cfg.env_setting("OPEN_SECOND_BRAIN_MCP_TIMEOUT"), "7")
+
+ def test_config_directories_fall_back_to_the_process_when_the_scope_has_none(self):
+ xdg = self.tmp / "xdg"
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(xdg)
+ pair = make_fake_scope(multiplexed=True)
+ with self.install(pair):
+ self.assertEqual(cfg.config_path(), xdg / cfg.PLUGIN_NAME / cfg.CONFIG_FILENAME)
+ self.assertIn(cfg.XDG_CONFIG_HOME_ENV, pair[1].reads)
+
+ def test_the_scope_config_directory_beats_the_process_one(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "launch-xdg")
+ scoped = self.tmp / "profile-xdg"
+ pair = make_fake_scope(multiplexed=True, values={"XDG_CONFIG_HOME": str(scoped)})
+ with self.install(pair):
+ self.assertEqual(cfg.config_path(), scoped / cfg.PLUGIN_NAME / cfg.CONFIG_FILENAME)
+
+ def test_the_scope_local_app_data_beats_the_process_one(self):
+ scoped = self.tmp / "profile-local"
+ with patch.dict(os.environ, {"LOCALAPPDATA": str(self.tmp / "launch-local")}):
+ pair = make_fake_scope(multiplexed=True, values={"LOCALAPPDATA": str(scoped)})
+ with self.install(pair):
+ self.assertEqual(cfg._windows_local_app_data(), scoped)
+ empty = make_fake_scope(multiplexed=True)
+ with self.install(empty):
+ self.assertEqual(cfg._windows_local_app_data(), self.tmp / "launch-local")
+ off = make_fake_scope(multiplexed=False, values={"LOCALAPPDATA": str(scoped)})
+ with self.install(off):
+ self.assertEqual(cfg._windows_local_app_data(), self.tmp / "launch-local")
+ self.assertEqual(off[1].reads, [])
+
+ def test_unbound_scope_refuses_the_config_directories(self):
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ with self.install(pair):
+ for name in cfg.SCOPE_FIRST_ENV:
+ with self.subTest(name=name), self.assertRaises(cfg.ProfileScopeError):
+ cfg.scope_first_setting(name)
+
+
+class MultiplexedEmptyScopeTests(ScopeTestCase):
+ """(d) Multiplexed, empty scope: the config chain answers, never os.environ."""
+
+ def test_falls_through_to_the_config_file(self):
+ self.set_launch_env()
+ self.write_xdg_config(
+ 'vault: "config-vault"\nagent_name: "config-agent"\ntimezone: "Asia/Tokyo"\n'
+ )
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": ""})
+ with self.install(pair):
+ self.assertEqual(cfg.resolve_vault(str(self.tmp)), "config-vault")
+ self.assertEqual(cfg.resolve_agent_name(), "config-agent")
+ self.assertEqual(cfg.resolve_timezone(), "Asia/Tokyo")
+
+ def test_falls_through_to_the_defaults(self):
+ self.set_launch_env()
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ pair = make_fake_scope(multiplexed=True)
+ with self.install(pair):
+ self.assertIsNone(cfg.resolve_vault(str(self.tmp)))
+ self.assertEqual(cfg.resolve_agent_name(), cfg.DEFAULT_AGENT)
+ self.assertIsNone(cfg.resolve_timezone())
+ self.assertIsNone(cfg.env_setting("OPEN_SECOND_BRAIN_MCP_TIMEOUT"))
+
+
+class UnboundScopeTests(ScopeTestCase):
+ """(e) Multiplexed with no scope bound: a named, value-free refusal."""
+
+ def test_resolvers_raise_profile_scope_error(self):
+ self.set_launch_env()
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ for resolver in (lambda: cfg.resolve_vault(str(self.tmp)), cfg.resolve_agent_name):
+ with self.subTest(resolver=resolver), self.install(pair):
+ with self.assertRaises(cfg.ProfileScopeError) as caught:
+ resolver()
+ exc = caught.exception
+ self.assertIsInstance(exc, cfg.ConfigReadError)
+ self.assertIsInstance(exc.__cause__, FakeUnscopedError)
+ self.assertEqual(exc.path, "")
+ self.assertEqual(exc.reason, "no profile scope bound")
+ self.assertIn(exc.name, cfg.PROFILE_SCOPED_ENV)
+ message = str(exc)
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, message)
+
+ def test_message_names_the_setting_and_the_remedy(self):
+ exc = cfg.ProfileScopeError("VAULT_AGENT_NAME")
+ self.assertEqual(exc.name, "VAULT_AGENT_NAME")
+ self.assertEqual(
+ str(exc),
+ "VAULT_AGENT_NAME cannot be resolved: this multiplexed Hermes gateway bound no "
+ "profile scope for the call, and Open Second Brain does not fall back to the "
+ "gateway's process environment, which belongs to the launch profile. Restart the "
+ "gateway (hermes gateway restart); if it persists, report it.",
+ )
+
+
+class IgnoredProcessValueWarningTests(ScopeTestCase):
+ """(c') and (g): one value-free WARNING per ignored name, once per process."""
+
+ def test_one_warning_per_ignored_name_without_its_value(self):
+ self.set_launch_env()
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair), self.assertLogs("plugins.hermes.config", "WARNING") as logs:
+ cfg.resolve_agent_name()
+ cfg.resolve_timezone()
+ messages = [record.getMessage() for record in logs.records]
+ self.assertTrue(any("VAULT_AGENT_NAME" in m for m in messages))
+ self.assertTrue(any("VAULT_TIMEZONE" in m for m in messages))
+ for message in messages:
+ self.assertIn("multiplexed gateway", message)
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, message)
+
+ def test_repeated_reads_warn_once(self):
+ os.environ["VAULT_AGENT_NAME"] = LAUNCH_VALUES["VAULT_AGENT_NAME"]
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair), self.assertLogs("plugins.hermes.config", "WARNING") as logs:
+ for _ in range(3):
+ cfg.resolve_agent_name()
+ named = [r for r in logs.records if "VAULT_AGENT_NAME" in r.getMessage()]
+ self.assertEqual(len(named), 1)
+
+ def test_no_warning_without_multiplexing_or_without_a_process_value(self):
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair), self.assertNoLogs("plugins.hermes.config", "WARNING"):
+ cfg.resolve_agent_name()
+ os.environ["VAULT_AGENT_NAME"] = "launch-agent-value"
+ off = make_fake_scope(multiplexed=False)
+ with self.install(off), self.assertNoLogs("plugins.hermes.config", "WARNING"):
+ cfg.resolve_agent_name()
+
+
+class ShadowingSourceTests(ScopeTestCase):
+ def test_multiplexed_names_the_profile_env_file(self):
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair):
+ self.assertEqual(
+ cfg.shadowing_source("agent_name"),
+ "the VAULT_AGENT_NAME setting in this Hermes profile's .env overrides the "
+ "config file",
+ )
+
+ def test_multiplexed_ignores_the_process_environment(self):
+ self.set_launch_env()
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ pair = make_fake_scope(multiplexed=True)
+ with self.install(pair):
+ self.assertIsNone(cfg.shadowing_source("agent_name"))
+
+ def test_without_multiplexing_the_text_is_unchanged(self):
+ os.environ["VAULT_AGENT_NAME"] = "launch-agent-value"
+ with self.no_hermes():
+ self.assertEqual(
+ cfg.shadowing_source("agent_name"),
+ "the VAULT_AGENT_NAME environment variable overrides the config file",
+ )
+
+
+class ConfigCommandSourceTests(ScopeTestCase):
+ def _run_config(self):
+ from plugins.hermes import cli
+
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ rc = cli._config()
+ return rc, out.getvalue(), err.getvalue()
+
+ def test_first_line_names_the_process_environment(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ with self.no_hermes():
+ rc, out, _ = self._run_config()
+ self.assertEqual(rc, 0)
+ self.assertEqual(
+ out.splitlines()[0],
+ "settings_source: process environment (this command; a gateway with "
+ "gateway.multiplex_profiles reads each profile's .env)",
+ )
+ self.assertTrue(out.splitlines()[1].startswith("config_path:"))
+
+ def test_first_line_names_the_profile_scope(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_AGENT_NAME": "scoped-agent"})
+ with self.install(pair):
+ rc, out, _ = self._run_config()
+ self.assertEqual(rc, 0)
+ lines = out.splitlines()
+ self.assertEqual(lines[0], "settings_source: profile scope (multiplexed gateway)")
+ self.assertIn("scoped-agent", out)
+
+ def test_unbound_scope_prints_the_named_error_and_exits_2(self):
+ self.set_launch_env()
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ with self.install(pair):
+ rc, out, err = self._run_config()
+ self.assertEqual(rc, 2)
+ self.assertEqual(out.splitlines()[0], "settings_source: profile scope (multiplexed gateway)")
+ self.assertIn("OPEN_SECOND_BRAIN_CONFIG cannot be resolved", err)
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, out + err)
+
+
+class StatusConfigScopeTests(ScopeTestCase):
+ def test_unbound_scope_skips_the_config_file_field(self):
+ self.set_launch_env()
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ with self.install(pair):
+ status = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge()).get_status_config({})
+ self.assertNotIn("config_file", status)
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, json.dumps(status))
+
+ def test_bound_scope_reports_the_config_file(self):
+ scoped_config = self.tmp / "scoped.yaml"
+ pair = make_fake_scope(
+ multiplexed=True, values={"OPEN_SECOND_BRAIN_CONFIG": str(scoped_config)}
+ )
+ with self.install(pair):
+ status = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge()).get_status_config({})
+ self.assertEqual(status["config_file"], str(scoped_config))
+
+
+class _HandshakeProcess:
+ """A child that answers ``initialize`` and ``tools/list`` and nothing else."""
+
+ def __init__(self):
+ frames = [
+ {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
+ {"jsonrpc": "2.0", "id": 2, "result": {"tools": []}},
+ ]
+ self.stdin = io.BytesIO()
+ self.stdout = io.BytesIO(b"".join(json.dumps(f).encode() + b"\n" for f in frames))
+ self.stderr = None
+ self.pid = 4242
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ pass
+
+ def kill(self):
+ pass
+
+ def wait(self, timeout=None):
+ return 0
+
+
+class ScopedChildEnvironmentTests(ScopeTestCase):
+ """(f) Under multiplexing each profile gets its own MCP child identity."""
+
+ def tearDown(self):
+ provider_module._reset_shared_bridges_for_tests()
+ super().tearDown()
+
+ def _initialize(self, pair, factory, overlay=None):
+ with (
+ self.install(pair),
+ patch("plugins.hermes.provider.McpBrainBridge", side_effect=factory),
+ patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
+ patch.object(
+ OpenSecondBrainMemoryProvider, "_resolve_command", return_value=("o2b", "mcp")
+ ),
+ patch.object(OpenSecondBrainMemoryProvider, "_resolve_env", return_value=overlay),
+ ):
+ OpenSecondBrainMemoryProvider().initialize("session", hermes_home=str(self.tmp))
+
+ def test_child_env_carries_the_scoped_identity_only(self):
+ self.set_launch_env()
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ built = []
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={"VAULT_DIR": "shared-vault", "VAULT_AGENT_NAME": "scoped-agent"},
+ )
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(len(built), 1)
+ env = built[0]["env"]
+ self.assertEqual(env["VAULT_AGENT_NAME"], "scoped-agent")
+ self.assertEqual(env["VAULT_DIR"], "shared-vault")
+ for name in ("VAULT_TIMEZONE", "OPEN_SECOND_BRAIN_CONFIG", "OPEN_SECOND_BRAIN_MCP_TIMEOUT"):
+ self.assertNotIn(name, env)
+ for value in LAUNCH_VALUES.values():
+ self.assertNotIn(value, env.values())
+ # The bridge never reads the deadline itself on this gateway.
+ self.assertEqual(built[0]["timeout"], bridge_module.DEFAULT_REQUEST_TIMEOUT_SECONDS)
+
+ def test_child_env_carries_the_scope_config_directory(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "launch-xdg")
+ scoped = str(self.tmp / "profile-xdg")
+ built = []
+ pair = make_fake_scope(
+ multiplexed=True, values={"VAULT_DIR": "v", "XDG_CONFIG_HOME": scoped}
+ )
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(built[0]["env"]["XDG_CONFIG_HOME"], scoped)
+
+ def test_child_env_keeps_the_process_config_directory_the_scope_lacks(self):
+ launch = str(self.tmp / "launch-xdg")
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = launch
+ built = []
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_DIR": "v"})
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(built[0]["env"]["XDG_CONFIG_HOME"], launch)
+
+ def test_overlay_path_survives_the_scoping(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ built = []
+ pair = make_fake_scope(multiplexed=True, values={"VAULT_DIR": "v"})
+ overlay = {"PATH": "/opt/bun/bin", "VAULT_AGENT_NAME": "launch-agent-value"}
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge(), overlay)
+ self.assertEqual(built[0]["env"]["PATH"], "/opt/bun/bin")
+ self.assertNotIn("VAULT_AGENT_NAME", built[0]["env"])
+
+ def test_scoped_timeout_reaches_the_bridge(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ built = []
+ for raw, expected in (("7", 7.0), ("0", 0.0)):
+ with self.subTest(raw=raw):
+ provider_module._reset_shared_bridges_for_tests()
+ built.clear()
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={"VAULT_DIR": "v", "OPEN_SECOND_BRAIN_MCP_TIMEOUT": raw},
+ )
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(built[0]["timeout"], expected)
+
+ def test_same_vault_different_agents_get_two_bridges(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ built = []
+ for agent in ("agent-one", "agent-two", "agent-one"):
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={"VAULT_DIR": "shared-vault", "VAULT_AGENT_NAME": agent},
+ )
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(
+ [kw["env"]["VAULT_AGENT_NAME"] for kw in built], ["agent-one", "agent-two"]
+ )
+
+ def test_same_config_different_config_directories_get_two_bridges(self):
+ shared = str(self.tmp / "shared-config.yaml")
+ built = []
+ for xdg in ("profile-one-xdg", "profile-two-xdg", "profile-one-xdg"):
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={
+ "VAULT_DIR": "shared-vault",
+ "VAULT_AGENT_NAME": "same-agent",
+ "OPEN_SECOND_BRAIN_CONFIG": shared,
+ "XDG_CONFIG_HOME": str(self.tmp / xdg),
+ },
+ )
+ self._initialize(pair, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(
+ [kw["env"]["XDG_CONFIG_HOME"] for kw in built],
+ [str(self.tmp / "profile-one-xdg"), str(self.tmp / "profile-two-xdg")],
+ )
+ self.assertEqual(len(provider_module._SHARED_BRIDGES), 2)
+
+ def test_without_multiplexing_env_and_sharing_are_unchanged(self):
+ os.environ["VAULT_DIR"] = "launch-vault"
+ os.environ["VAULT_AGENT_NAME"] = "launch-agent-value"
+ built = []
+ off = make_fake_scope(multiplexed=False)
+ for _ in range(2):
+ self._initialize(off, lambda **kw: built.append(kw) or FakeBrainBridge())
+ self.assertEqual(len(built), 1)
+ self.assertIsNone(built[0]["env"])
+ self.assertNotIn("timeout", built[0])
+ self.assertEqual(off[1].reads, [])
+
+
+class BridgeTimeoutFixedAtConstructionTests(ScopeTestCase):
+ """(h) A restart from a plugin-owned thread never reads the scope."""
+
+ def test_fixed_timeout_restart_never_reads_the_scope(self):
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ bridge = McpBrainBridge(vault="v", spawn=lambda argv: _HandshakeProcess(), timeout=7.0)
+ errors = []
+
+ def restart():
+ try:
+ bridge.start()
+ except Exception as exc: # noqa: BLE001 - recorded for the assertion
+ errors.append(exc)
+
+ with self.install(pair):
+ thread = threading.Thread(target=restart)
+ thread.start()
+ thread.join(5)
+ self.assertEqual(errors, [])
+ self.assertEqual(pair[1].reads, [])
+ self.assertEqual(bridge._client._timeout, 7.0)
+
+ def test_non_positive_timeout_disables_the_deadline(self):
+ bridge = McpBrainBridge(vault="v", spawn=lambda argv: _HandshakeProcess(), timeout=0.0)
+ bridge.start()
+ self.assertIsNone(bridge._client._timeout)
+
+ def test_no_timeout_argument_keeps_reading_the_environment(self):
+ os.environ["OPEN_SECOND_BRAIN_MCP_TIMEOUT"] = "45"
+ with self.no_hermes():
+ bridge = McpBrainBridge(vault="v", spawn=lambda argv: _HandshakeProcess())
+ bridge.start()
+ self.assertEqual(bridge._client._timeout, 45.0)
+
+ def test_multiplexed_timeout_reads_the_scope(self):
+ os.environ["OPEN_SECOND_BRAIN_MCP_TIMEOUT"] = "4242"
+ pair = make_fake_scope(multiplexed=True, values={"OPEN_SECOND_BRAIN_MCP_TIMEOUT": "9"})
+ with self.install(pair):
+ self.assertEqual(bridge_module.resolve_request_timeout(), 9.0)
+
+
+class RequestTimeoutValueTests(ScopeTestCase):
+ """A timeout value that is not a finite number never becomes a deadline."""
+
+ def _resolve(self, raw):
+ os.environ["OPEN_SECOND_BRAIN_MCP_TIMEOUT"] = raw
+ with self.no_hermes():
+ return bridge_module.resolve_request_timeout()
+
+ def test_nan_falls_back_to_the_default_with_a_warning(self):
+ for raw in ("nan", "NaN", "-nan"):
+ with self.subTest(raw=raw), self.assertLogs("plugins.hermes.bridge", "WARNING") as logs:
+ self.assertEqual(self._resolve(raw), bridge_module.DEFAULT_REQUEST_TIMEOUT_SECONDS)
+ self.assertEqual(len(logs.records), 1)
+
+ def test_infinity_disables_the_deadline(self):
+ for raw in ("inf", "Infinity", "-inf"):
+ with self.subTest(raw=raw), self.assertNoLogs("plugins.hermes.bridge", "WARNING"):
+ self.assertIsNone(self._resolve(raw))
+
+ def test_malformed_value_warning_never_carries_the_value(self):
+ for raw in ("launch-timeout-value", "nan"):
+ with self.subTest(raw=raw), self.assertLogs("plugins.hermes.bridge", "WARNING") as logs:
+ self._resolve(raw)
+ message = logs.records[0].getMessage()
+ self.assertIn("OPEN_SECOND_BRAIN_MCP_TIMEOUT", message)
+ self.assertNotIn(raw, message)
+
+ def test_nan_scoped_timeouts_share_one_bridge(self):
+ os.environ[cfg.XDG_CONFIG_HOME_ENV] = str(self.tmp / "absent")
+ built = []
+ try:
+ for _ in range(2):
+ pair = make_fake_scope(
+ multiplexed=True,
+ values={"VAULT_DIR": "v", "OPEN_SECOND_BRAIN_MCP_TIMEOUT": "nan"},
+ )
+ with (
+ self.install(pair),
+ patch(
+ "plugins.hermes.provider.McpBrainBridge",
+ side_effect=lambda **kw: built.append(kw) or FakeBrainBridge(),
+ ),
+ patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
+ patch.object(
+ OpenSecondBrainMemoryProvider,
+ "_resolve_command",
+ return_value=("o2b", "mcp"),
+ ),
+ patch.object(OpenSecondBrainMemoryProvider, "_resolve_env", return_value=None),
+ ):
+ OpenSecondBrainMemoryProvider().initialize("session", hermes_home=str(self.tmp))
+ finally:
+ provider_module._reset_shared_bridges_for_tests()
+ self.assertEqual(len(built), 1)
+ self.assertEqual(built[0]["timeout"], bridge_module.DEFAULT_REQUEST_TIMEOUT_SECONDS)
+
+
+class PrefetchDegradeTests(ScopeTestCase):
+ """(h) ``prefetch`` with no scope bound omits the reminder for the turn."""
+
+ def test_prefetch_degrades_and_warns_once(self):
+ # Recall the turn can still serve, so "omit the reminder" is told
+ # apart from "drop the whole turn".
+ bridge = FakeBrainBridge(
+ results={
+ "brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
+ "brain_context_pack": {
+ "structuredContent": {"generated_at": "2026-08-22"},
+ "content": [{"type": "text", "text": "SCOPED TURN RECALL"}],
+ },
+ }
+ )
+ provider = OpenSecondBrainMemoryProvider(bridge=bridge)
+ provider.initialize("session", hermes_home=str(self.tmp))
+ provider_module._reset_scope_degrade_warning_for_tests()
+ pair = make_fake_scope(multiplexed=True, unbound=True)
+ with self.install(pair), self.assertLogs("plugins.hermes.provider", "WARNING") as logs:
+ first = provider.prefetch("hello")
+ second = provider.prefetch("hello again")
+ self.assertIn("SCOPED TURN RECALL", first)
+ self.assertIn("SCOPED TURN RECALL", second)
+ degraded = [
+ r for r in logs.records if "no profile scope bound for this turn" in r.getMessage()
+ ]
+ self.assertEqual(len(degraded), 1)
+ self.assertEqual(
+ degraded[0].getMessage(),
+ "open-second-brain: no profile scope bound for this turn; the vault reminder is "
+ "omitted",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/uv.lock b/uv.lock
index dc73d279..303dffb4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.69.0"
+version = "1.70.0"
source = { editable = "." }