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: credential custody under a passphrase and a verifiable trust surface (v1.78.0) (#244)

Serg Eroshe66f9d84756ad
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a68be85c..f824009e 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.77.0",
+ "version": "1.78.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 4610d18f..387e0876 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.77.0",
+ "version": "1.78.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 a8d89b11..d29d85b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,31 @@ 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.78.0] - 2026-10-09
+
+Open Second Brain now puts credential custody under an operator passphrase and routes it by name: the vault's secrets keyfile wraps into an opt-in scrypt envelope behind a lock/unlock lifecycle, `$secret:NAME` references resolve through the custody store at every credential use site, one passphrase-encrypted bundle moves the store between installs, and every resolved credential literal is redacted at the error and config-mapping boundaries. The vault's own declarations bind its writers - composed tags must parse as Obsidian tags and a declared page vocabulary gates capture writes - and the plans an operator approves are sealed: a Claude-memory import or a brain upgrade applies exactly the approved plan or nothing. Reads name divergent session summaries, the model-answer verbs strip and name a leading think block before parsing, and a changed extraction contract reprocesses the sources it covers instead of absorbing the change as unchanged.
+
+### Added
+
+- **A passphrase-wrapped keyfile with a lock/unlock lifecycle.** `o2b brain secret unlock` wraps the store's raw 32-byte keyfile in place under a passphrase - read from stdin or `--passphrase-from-env`, never argv - into a versioned scrypt envelope (per-envelope random salt, parameters bounded to the build's cost curve) and holds the unwrapped key in memory for that one process only; `lock` clears the holder and refuses a store that was never wrapped by name, instead of recording a protection that does not exist. There is no daemon: every other invocation and the MCP server stay locked, a key-bearing operation over a locked store refuses with a named error whose prose carries no paths and whose remedy is the unlock command, and a store that still holds entries but has lost its keyfile refuses the read-only resolve by name instead of minting a fresh key over the surviving ciphertext. Both lifecycle verbs land no-values custody records and sit behind vault identity, and the help and manifest state the loss warning: a lost passphrase is unrecoverable, and every stored value stays unreadable forever.
+- **Passphrase-encrypted credential bundles.** `o2b brain secret export --out FILE` re-encrypts every entry under a key the passphrase derives through the envelope KDF (fresh salt, the parameters recorded inside the bundle) and writes one file an operator can carry between installs - names, env-var mappings and allow patterns travel in the clear past the shared egress redactor, the values do not. `secret import FILE` verifies and decrypts every value before writing anything, reuses the store's own name, env-var and allow-pattern validation, and refuses a name the store already holds unless `--replace`; both operations land no-values custody records and run behind vault identity.
+- **`$secret:NAME` references resolve at the use sites.** The custody-store-backed named-secret provider answers credential consumers store-first with environment fallback - byte-identical when no reference is used, opt-in via the vault that joins the store: the embedding registry's provider probes, the decision-model key from config resolution through the provider factory (extract pre-filter, labels, recall-inject, skills, rerank), the research pool env, the Telegram capture token and the installation secret behind the `vault_path` MCP field. A locked store or an unresolvable reference surfaces the named refusal - the decision-model key degrades into errors with no request leaving, the Telegram run fails naming the secret instead of handing the raw reference to the API, research names the refusal instead of quietly yielding an empty pool - and resolution stays read-only: no `last_used_at` stamp, no exec custody record, no store mutation. `o2b secrets list` and `status` accept `--vault <path>` and report availability from the merged provider, metadata only, a locked store still counting.
+- **Resolved credential literals are redacted at the guarded boundaries.** The MCP error boundary scrubs every occurrence of a value the vault resolved from a reference - longest value first, ahead of the truncation guard, so no cut leaves a partial credential - and the OpenClaw status tool's config mapping takes the same values into its scan; a boundary whose store is absent, empty, unreadable or locked contributes nothing and answers byte-identically to the shape-only redactor.
+- **Digest-sealed approval for import and upgrade plans.** `o2b brain import-claude-memory --dry-run` seals the adoption plan - plans, skipped entries, conflicts, unchanged rows, no wall-clock fields - and prints its digest; a non-interactive `--apply` must carry `--approval-digest` (exit 2 otherwise, mirroring the `--yes` guard, while an interactive terminal keeps the escape hatch) and lands exactly the approved plan or nothing: a stale digest refuses naming approved and current digests and stating that nothing was written, and a digest paired with `--dry-run` refuses, because a dry run computes one and does not consume one. `o2b brain upgrade` seals its plan the same way and verifies the seal first at apply, so a plan object edited after it was measured is refused before the error rows, the no-op return or the snapshot; the CLI and the self-heal worker, which apply the plan they just planned, are unchanged.
+- **Divergent session summaries are named on reads.** The single-session read (CLI and MCP) answers the latest digest plus `digest_count`, and when one session id holds several content-differing digests reports `divergent: true` beside a bounded newest-first-count, oldest-first sample of `id` / `created_at` / `content_hash` rows - never a payload echo. Divergence is reported, never merged, deleted or reconciled.
+- **A named think-block strip before CLI JSON parses.** The four model-answer verbs (extract-signals, design-note, skill-proposals page-draft, distill) parse plainly first and, on failure, strip one leading `<think>...</think>` block and retry; every strip is named on the result - a note on the ok envelope under `--json`, a note line in text - and a payload that still refuses keeps the named exit-1 refusal with the attempt named. Clean JSON is byte-identical and genuinely malformed JSON is never rescued.
+- **The extraction contract fingerprint rides in the source-ingest manifest.** The manifest records the fingerprint of the extraction contract (the schema-extractable allowlist plus the hand-bumped contract version), schema 2 with a v1 read path, and batch planning compares it against the live one: on a mismatch - a v1 manifest with no recorded contract included - byte-identical sources reprocess once under the distinct contract-changed status (`contract_changed` and `contract_changed_files` on the wire, an info line in text) instead of being absorbed as unchanged, reconcile names those sources as the gap, and the fingerprint folds into the plan id so a stale checkpoint cannot resume-skip work extracted under a different contract.
+
+### Changed
+
+- **Composed tags must parse as Obsidian tags.** Every tag the core composes into frontmatter - a preference's topic, scope and extra tags, a signal's topic and scope, the Claude-memory import's derived topic and scope - is validated against the one rule the search index and the inline detector already read (starts with a letter or underscore, continues with letters, digits, dashes, underscores or slashes, never purely numeric), and a segment that fails it refuses the write with the offending field and the rule named. Existing content cannot be refused retroactively, so an opt-in `frontmatter-tags` hygiene detector reports what the write-time gate would have rejected - one finding class, grouped per distinct value, informational, never auto-fixed.
+- **A declared page vocabulary gates capture writes.** A vault that declares `schema.page_types` in `Brain/_brain.yaml` refuses a capture whose kind it does not declare - staged captures, every inbox-drain route and the Telegram path - with a typed error naming the kind, the declared set and the remedy, before any filesystem effect: no directory is created and no allocator name is consumed. The idea route consults the gate at plan time, so a dry run previews the same refusal apply would land, and a vault with no declaration behaves byte-identically to before.
+- **Docs:** `docs/cli-reference.md` documents the lock/unlock/export/import verbs, the `--vault` join on `o2b secrets list`/`status`, `--approval-digest` on the import and the contract-changed batch-plan report; `docs/how-it-works.md` states the passphrase envelope, the references and the bundles under the custody model; the README names the release and the custody capability. The plugin mirrors follow.
+
+### Fixed
+
+- **Same-instant continuity records read in append order.** The store tie-broke rows sharing a timestamp by content-hash id, which says nothing about which of two same-instant writes landed first, so a latest-wins reader - the session-summary read among them - could answer the older take arbitrarily. Within one shard the append-only file is now the authority; ties across shards still order by shard id, because two devices' arrival orders genuinely cannot be known.
+
## [1.77.0] - 2026-10-08
Open Second Brain now keeps its claim ledger in time and correctable: a claim can carry a validity window frozen from its source at ingest, the events recall reads the ledger over an assertion-time slice, an agent's stated claims commit only when they anchor in their assertion text, and two same-slot claims with disjoint windows stand in a succession channel instead of a conflict. One correct verb discovers a correction's blast radius and retires what it touches, and every serving surface serves a retired-but-serveable record only beside its resolved, readable chain-tip correction, fail-closed. The deep relational recall arm runs under width budgets with hub skipping, walks entity co-occurrence bridges, reports per-node path provenance gated at the caller's reach, and never lets a traversal-only row outrank what the lanes matched.
@@ -8341,6 +8366,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.78.0]: https://github.com/itechmeat/open-second-brain/compare/v1.77.0...v1.78.0
[1.77.0]: https://github.com/itechmeat/open-second-brain/compare/v1.76.0...v1.77.0
[1.76.0]: https://github.com/itechmeat/open-second-brain/compare/v1.75.0...v1.76.0
[1.75.0]: https://github.com/itechmeat/open-second-brain/compare/v1.74.1...v1.75.0
diff --git a/README.md b/README.md
index 056be799..8ee8d866 100644
--- a/README.md
+++ b/README.md
@@ -104,6 +104,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).
- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).
- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](docs/cli-reference.md#knowledge-packs).
+- **Secret custody.** Credentials live encrypted in the vault's state dir behind a capability-gated store; `$secret:NAME` references resolve at the use sites, `o2b brain secret unlock` wraps the keyfile under a passphrase, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle: [custody CLI](docs/cli-reference.md#write-time-integrity-and-governance-since-v0440).
- **Today view and note markers.** `o2b brain today`, `@osb loop` and `@osb set` markers: [Brain CLI](docs/cli-reference.md#brain-observing-memory).
- **Self-inspection.** `o2b version`, `o2b install --friction` and `o2b state status` report what is installed and where state lives: [CLI reference](docs/cli-reference.md#core).
- **MCP surface.** Tools, tool profiles for hosts with tool limits, and the always-loaded writer server: [`docs/mcp.md`](docs/mcp.md).
@@ -116,7 +117,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.77.0 makes the claim ledger time-aware and correctable. A claim can carry a validity window (`o2b brain truth ingest --valid-from`/`--valid-until`, frozen from the source record when the flags are absent), `o2b brain truth events` recalls the ledger over an assertion-time slice, `o2b brain truth state` grounds an agent's stated claims with a per-claim anchoring verdict, and `o2b brain lifecycle correct` retires what a correction touches - dry run by default, with a retired record that recall can still serve answered only beside its resolved, readable correction, never alone. The deep relational recall arm now runs under width budgets with hub skipping and entity co-occurrence bridges. Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.78.0 puts credential custody under an operator passphrase. The secrets keyfile wraps into a scrypt envelope behind `o2b brain secret unlock`/`lock`, `$secret:NAME` references resolve through the custody store at the embedding, decision-model, research, Telegram and installation-secret use sites, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle. Resolved credential literals are redacted at the error and config-mapping boundaries, composed tags must parse as Obsidian tags, a declared page vocabulary gates capture writes, import and upgrade plans carry an approval digest that apply must match, and a changed extraction contract reprocesses the sources it covers. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/trust-surface-hardening/cli-output/consultant.md b/docs/brainstorm/trust-surface-hardening/cli-output/consultant.md
new file mode 100644
index 00000000..a7272155
--- /dev/null
+++ b/docs/brainstorm/trust-surface-hardening/cli-output/consultant.md
@@ -0,0 +1,30 @@
+### Variant 1: Substrate-first consolidation (shared crypto and seal modules, reject-at-write)
+
+- **Approach**: Sequence the wave around two shared modules built before their consumers. First `src/core/brain/secrets/envelope.ts`: the scrypt KDF (`scryptSync`/`timingSafeEqual` from node:crypto, explicit `N/r/p/maxmem`, random salt, parameters recorded inside a versioned envelope, wrong-passphrase detected by the GCM tag), the wrapped-keyfile format that replaces the raw 32-byte keyfile on opt-in (card 1), and the bundle envelope of card 3; card 2 then routes through the same substrate's decrypt with a read-only resolve variant so `$secret:` resolution avoids the `resolveSecretForExec` writer side (last_used_at stamp plus custody audit). Second, lift `sealManifest`/`manifestVerifies` (`src/core/state/migrate.ts:186-194`) into `src/core/integrity/digest.ts` beside `sha256Hex`/`canonicalJson` so both adoption-plan seals (card 7) and the extraction-contract fingerprint (card 9) pass through one primitive. Cards 4 and 6 reject at write time - the composers refuse tag values failing the `src/core/tags.ts` rule and capture refuses an undeclared kind before `allocateAndCreate` - and cards 5 and 8 extend the existing response envelopes additively (`digest_count`/`divergent` on both single-session reads, a `note` key on the CLI `{ ok: true }` envelope).
+- **Trade-offs**:
+ - Pros: one spelling of the KDF and one of the seal matches the DRY posture `src/core/tags.ts:8-11` already demands of the tag rule; card 3 shares the KDF with card 1 by card statement, so the substrate is load-bearing rather than speculative; rejection-before-allocation reuses the existing typed-refusal shapes (`CaptureContractError`, `SchemaVocabularyError`) and the guard ordering `store.ts:119-124` already mandates.
+ - Cons: hard rejection on topic shape breaks live MCP/CLI feedback and any lane that writes `brain/topic/foo bar` today until callers slugify; rejecting capture kinds in vaults whose packs were authored before `brain-capture` existed needs a compatibility story for the Telegram lane; the up-front substrate couples the review and landing order of three otherwise independent secrets slices.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: Independent slices (detect-only governance, dedicated divergence surfaces)
+
+- **Approach**: Ship nine vertical slices with no module extracted first: the wrapped keyfile, the bundles and the resolver each carry their own KDF/envelope code locally with convergence deferred, and cards 7 and 9 implement sealing in place. Cards 4 and 6 are detection-only: an opt-in `frontmatter-tags` hygiene detector registered through `HYGIENE_DETECTOR_IDS` (`src/core/brain/hygiene/types.ts:12-20`) and modeled on `detectTags`, plus a doctor finding for vaults whose declared `page_types` omit the kinds the build stamps; no composer or capture writer changes. Cards 5 and 8 add new dedicated surfaces - a session-summary divergences read and a payload-parse diagnostics output - leaving `brain_session_summary` get, the CLI get and the four parse sites byte-identical.
+- **Trade-offs**:
+ - Pros: zero write-path break risk - topics with spaces keep landing, Telegram captures keep flowing, every existing test pin survives untouched; each slice reviews, lands and reverts independently; no read-path consumer or test churn on the current envelopes.
+ - Cons: three private copies of envelope/KDF code is drift in exactly the layer where a mistake costs credentials, against the wave's own DRY constraint; detection-only leaves the trust surface documented rather than hardened - the silent sorted-last read at `session-summary.ts:179` stays silent on the primary surface and the agent must know to call the new one; two new surfaces cost command-manifest, help-text, census and MCP-parity work that additive keys avoid.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Forced sharing only, tiered enforcement, additive named keys
+
+- **Approach**: Share exactly what the cards force: one `src/core/brain/secrets/envelope.ts` KDF/wrapped-envelope module under cards 1 and 3 (card 3 shares the KDF with card 1 by statement), with card 2 as a separate resolver-plane slice that composes `parseSecretReference` with a read-oriented decrypt over the custody store and threads resolved literals into `EGRESS_REDACTION_OPTIONS`/`redactConfigMapping` so `redactKnownSecretValues` finally gains production callers; likewise one `sealWithDigest`/`digestVerifies` lift into `src/core/integrity/digest.ts` under cards 7 and 9. Enforcement is tiered by blast radius: card 4 rejects caller-controlled `extraTags` and slugify-or-rejects topic inside the composers (consuming the rule from `src/core/tags.ts`, never a copy), while card 6 fails open on absent config per the `readSchemaPackSource` substitution precedent (`schema-pack.ts:56`) and rejects an undeclared `kind` only when a pack explicitly declares `page_types`, with an opt-in hygiene detector as the companion for existing vaults; lock/unlock stays off MCP per the `brain_secrets` set/get refusal (admin-tools.ts:295-299). Cards 5 and 8 extend the existing envelopes additively with named tokens - `digest_count`, conditional `divergent` plus an id/hash list rather than full echoes to respect `MCP_PREVIEW_BUDGET`, a `summary-divergent`-style reason token in the `payload_mismatch`/`coverage-divergent` grammar, and a `note` key on the CLI envelope when the shared payload parser stripped a think block - and fold the pre-existing CLI serializer drift (missing `project`) into the same wave.
+- **Trade-offs**:
+ - Pros: the only centralized code is the two substrates the cards genuinely share, so review order stays slice-sized; rejection lands where the caller controls the input (extraTags) and where the vault made a declaration (page_types), matching the write-session validator's existing polarity (fail closed on declared-but-unknown at `validate.ts:181`, fail open on absent vocabulary) while detectors cover vaults that predate the declarations; additive named keys follow the conditional-key idiom, cannot trip the MCP output contract (the tool declares no outputSchema), and keep byte-identity when inactive.
+ - Cons: three enforcement polarities in one wave (reject-always on extraTags, reject-only-when-declared on capture kinds, detect-only companion) need careful documentation so operators can predict which writes refuse; the resolver's store-lock-on-config-paths question and card 3's honest `EGRESS_SITES` declaration (ciphertext defeats both `sharedRedactor` and `noVaultContent` as-is) remain open decisions inside otherwise-settled slices.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 3
+
+**Rationale**: It centralizes only the two substrates the cards force to be shared - card 3 shares its KDF with card 1 by statement, and cards 7 and 9 both reduce to `sha256Hex(canonicalJson(...))` over a canonical body - unlike Variant 1, which couples all three secrets slices up front, or Variant 2, which leaves three drifting copies of credential-critical code. Its tiered enforcement places fail-closed behavior exactly where the repo's own precedents sit (declared-vocabulary rejection with fail-open on absent config, caller-controlled-input rejection at the composers) and covers pre-existing vaults through detectors instead of breaking Telegram capture or live feedback. Additive named keys on existing envelopes are the established house grammar, preserve byte-identity when the features are inactive, and avoid Variant 2's split-surface problem where the primary single-session read stays silent.
diff --git a/docs/brainstorm/trust-surface-hardening/cli-output/prompt.md b/docs/brainstorm/trust-surface-hardening/cli-output/prompt.md
new file mode 100644
index 00000000..dfc0ef25
--- /dev/null
+++ b/docs/brainstorm/trust-surface-hardening/cli-output/prompt.md
@@ -0,0 +1,63 @@
+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
+
+Ship one release of Open Second Brain whose argument is "trust-surface hardening": every surface an operator or agent has to trust - the credential store, the write path, the read path and the resumability artifacts - states what it verified, refuses what it cannot, and names what it did. Nine tracker cards feed it. Reconnaissance against the live source has already been done and is recorded in four files that are the shared context for this brainstorm; treat their findings as fact, not conjecture, and do not re-litigate them:
+
+- ~/.cache/osb-run.Dc0T/recon-secrets.md (cards 1-3)
+- ~/.cache/osb-run.Dc0T/recon-validation.md (cards 4, 6, 7)
+- ~/.cache/osb-run.Dc0T/recon-sessions.md (cards 5, 8)
+- ~/.cache/osb-run.Dc0T/recon-ingest.md (card 9)
+
+**Card 1 (t_e6667a56) - passphrase-wrapped secret-store key.** The secret store under `src/core/brain/secrets/` encrypts values with per-value AES-256-GCM around a raw 32-byte 0600 keyfile (`crypto.ts:86-142`). The card adds an opt-in envelope: a scrypt-derived key wraps the file key, the passphrase-derived key lives only in process memory (the repo has no daemon, so every CLI invocation and the MCP server unlock separately), and `lock`/`unlock` ops join the verb switch in `src/cli/brain/verbs/secret.ts`. There is no TTY password infrastructure anywhere, so passphrases arrive via stdin or `--passphrase-from-env` following the `set` pattern; MCP keeps `brain_secrets` to `list|run` only, and the admin-tools refusal of set/get (:295-299) is the precedent for refusing unlock there too.
+
+**Card 2 (t_e5807974) - route credential consumers through the named-secret resolver.** The `$secret:NAME` syntax layer (`src/core/secret-ref.ts`) is complete but nearly inert: `resolveSecretReference` and `redactKnownSecretValues` have zero production callers while real credentials still flow from bare env vars at five sites (embeddings registry, decision-model config, research fetch, Telegram token, installation secret). The provider parameter on the resolver is the seam for a custody-store-backed provider with env fallback; the caveat is that `resolveSecretForExec` is read-shaped but a writer (last_used_at stamp plus audit), so config paths may want a read-only decrypt. Redaction wiring points at `EGRESS_REDACTION_OPTIONS`/`redactForEgress` (`src/core/egress/guard.ts`) and `redactConfigMapping`, and the egress census asserts declarations against source.
+
+**Card 3 (t_592d9e91) - passphrase-encrypted credential bundles.** Export/import credentials as a single passphrase-encrypted JSON envelope, modeled on the bank bundle (`src/core/brain/portability/bundle.ts`, schema-versioned) with knowledge-pack-style integrity, sharing the KDF and envelope format with card 1 by card statement. Declaring `--out` pulls the verb into the egress census population, so an honest `EGRESS_SITES` entry is a deliberate choice: the payload is ciphertext by construction, which defeats both the `sharedRedactor` and `noVaultContent` statuses as-is.
+
+**Card 4 (t_11ee559f) - reject or flag tags Obsidian cannot parse.** Canonical tags are composed in exactly three places with no syntax check (`composeSignalTags` signal.ts:797, `composePreferenceTags` preference.ts:808, hand-rendered import frontmatter claude-memory-render.ts:80); a topic like `foo bar` lands as `brain/topic/foo bar`, which Obsidian cannot parse. The repo already holds one index rule (`TAG_RE`, `src/core/tags.ts:29`, whose docblock reserves itself as this card's seam - validate against the rule defined there, never a copy) and one Obsidian-compatible detector rule (`hygiene/detectors/tags.ts:62`); the schema-vocab token rule rejects slashes and must not be reused. The doctor half is a frontmatter-tags hygiene detector registered via `HYGIENE_DETECTOR_IDS`/`DETECTORS`, where `tags` is registered but opt-in today.
+
+**Card 5 (t_59d4c919) - surface divergent session summaries on single-session reads.** `getSessionSummary` (`src/core/brain/session-summary.ts:173-180`) filters append-only continuity records and returns the sorted-last one silently; Syncthing replication legitimately produces content-differing records for one session. Exactly two callers exist: MCP `brain_session_summary` get (synthesis-tools.ts:125-129) and CLI `o2b brain session-summary` get. The MCP tool declares no outputSchema, so additive keys cannot trip the envelope contract; the named-reason grammar (`payload_mismatch`, `coverage-divergent`, `sync-conflict-log`) is the established vocabulary; `MCP_PREVIEW_BUDGET` applies to the serialized content, so id/hash lists beat full echoes.
+
+**Card 6 (t_151a564c) - enforce pack vocabulary on capture writes.** `writeCaptureNote` and `writeIdeaNote` stamp fixed kinds (`brain-capture`, `captured-idea`) with no vocabulary consult, while page-type enforcement exists only in the write-session/note-strict path and the signal-side `schemaVocabulary` option is dormant (no caller passes it). Absent config substitutes a default pack (`schema-pack.ts:56`) - the established fail-open - and the merged vocabulary always contains `note`, so "pack active" means declarations non-empty. Rejection must precede `allocateAndCreate` so a refused capture never consumes a name; the `kind`-vs-`type` frontmatter key mismatch is an open decision, and Telegram capture is the live lane most exposed to a compatibility break.
+
+**Card 7 (t_18fda844) - digest-sealed content adoption plans.** `sealManifest`/`manifestVerifies` (`src/core/state/migrate.ts:186-194`) seal the state-migration manifest and verify at apply and rollback; neither content-adoption surface has a binding. The Claude-memory import re-plans at apply with nothing tying the approved dry-run to what lands; brain upgrade refuses byte-level drift but trusts a caller-supplied plan object (the self-heal worker uses that seam). Generalize the seal to both plans, carry the digest through CLI output, refuse drift before the snapshot/write loop, and keep wall-clock fields out of the sealed body (migrate.ts injects `now` for this reason).
+
+**Card 8 (t_dac8bf7e) - strip reasoning think blocks before CLI JSON parse.** The MCP path is immune (protocol-parsed objects go straight into commit functions), but four CLI verbs bare-`JSON.parse` agent-authored payloads before `assertResponseShape` can run: extract-signals (:129-140), design-note (:105-113), skill-proposals (:120-125), distill (:89-102). A reasoning preamble kills them with the generic "payload must be valid JSON". A shared strip-and-note parser tries a plain parse, strips a leading think block, retries, and names the strip on the `{ ok: true }` envelope; a still-invalid payload keeps today's named exit-1 refusal. The fenced-unwrap precedent is `llm-emulation.ts:221`.
+
+**Card 9 (t_586d5d8b) - record the extraction contract in the ingest manifest.** The ingest content manifest (`src/core/brain/ingest/content-manifest.ts`, schema_version 1, path-to-sha256 entries, unknown version hard-refused) gates reprocessing in `planBatches` by content hash only, so changed extraction settings leave `unchanged` sources answering with extraction shaped by the old contract. The card persists a manifest-wide contract fingerprint (the vault's `extractable` allowlist plus a hand-bumped code constant, mirroring the `CHUNKER_VERSION` convention), compares it right after `readManifest`, folds it into `computePlanId` (the `computeSessionImportId` pattern), and reprocesses rather than mark-stale, with a typed reason token so reporting stays honest; the schema bump follows the `SUPPORTED_SCHEMA_VERSIONS` pattern so a v1 manifest degrades to one conservative reprocess instead of a hard error.
+
+Wave constraints (non-negotiable):
+
+- TypeScript on Bun; no new native or ML dependencies; node:crypto is available (scrypt, subtle). The repo pins a single runtime dependency (proper-lockfile) and treats even optional native packages cautiously, so scrypt with explicit parameters recorded in a versioned envelope is the settled KDF choice.
+- No hardcoded natural-language phrases; all strings English, other languages handled abstractly.
+- Errors surface explicitly by name; no silent fallbacks; fail-closed posture on writes; opt-in flags for behavior changes.
+- SOLID, KISS, DRY; hoist repeated literals; match surrounding idiom.
+- The kernel never calls a model.
+
+# Project context
+
+Open Second Brain is a local-first memory system for AI agents: TypeScript on Bun, surfaces are an MCP server plus an `o2b` CLI, agent state lives in SQLite via bun:sqlite, and the knowledge corpus is a markdown vault under `Brain/` with machine artifacts under `.open-second-brain/`. Recent releases shipped visibility windows, a truth layer and context delivery, and the tree now carries architecture census tests (egress census, write-site census, manifest completeness, vault-guard census) that any new verb, write site or egress destination must satisfy. The four recon files listed above are the shared context: they name the real files, line anchors, precedents and open decisions, and variants should build on them rather than re-derive them.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. The variants must take genuinely different positions on the real architectural questions of this wave, at minimum:
+
+- (a) whether cards 1, 2 and 3 share one crypto/envelope substrate module built first, or ship as three independent slices;
+- (b) how aggressive the fail-closed posture is for cards 4 and 6: reject the write, or flag-and-continue with doctor detectors;
+- (c) how cards 5 and 8 expose new information: extend the existing response envelopes additively, or add new dedicated surfaces.
+
+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/trust-surface-hardening/design.md b/docs/brainstorm/trust-surface-hardening/design.md
new file mode 100644
index 00000000..1d7812be
--- /dev/null
+++ b/docs/brainstorm/trust-surface-hardening/design.md
@@ -0,0 +1,90 @@
+# Trust-Surface Hardening — a nine-card wave making the credential store, the write path, the read path and the resumability artifacts state what they verified, refuse what they cannot, and name what they did
+
+**Status:** draft
+**Author:** Open Second Brain release wave
+**Audience:** implementation (six lanes with disjoint file ownership; see `plan.md`)
+
+## Problem statement
+
+Every surface an operator or agent has to trust is soft in one of four places: the secret store's key material sits on disk as a raw 32-byte file any same-user process can read, `$secret:NAME` config references resolve nothing because the resolver has zero production callers, and values resolved from env vars are invisible to the egress redactor. The write path lands tags Obsidian cannot parse (`brain/topic/foo bar`) and stamps capture kinds no pack vocabulary ever approved, and the read path silently returns the sorted-last session summary when several content-differing digests exist for one session. Agent-authored JSON payloads die on a generic parse error when a model prefixes a reasoning block, and the ingest manifest gates reprocessing on content bytes alone, so changed extraction settings leave `unchanged` sources answering with extraction shaped by the old contract. Each defect is fixed by making the surface state what it verified, refuse what it cannot, and name what it did — never by adding a silent fallback.
+
+## Scope
+
+Nine tracker cards, one release:
+
+- **t_e6667a56** — passphrase-wrapped secret-store key: an opt-in scrypt envelope wraps the 32-byte DEK at the existing keyfile path, with `lock`/`unlock` ops, memory-only unlock state, and named locked-store refusals.
+- **t_592d9e91** — passphrase-encrypted credential bundles: export/import the store's entries as a single passphrase-encrypted, schema-versioned JSON envelope sharing the card-1 KDF, with a declared egress destination.
+- **t_e5807974** — named-secret resolver routing: a custody-store-backed provider with env fallback behind the existing `$secret:` syntax, routed into the credential consumers, with resolved literals wired into egress redaction.
+- **t_11ee559f** — Obsidian tag syntax validation plus a doctor detector: write-time validation in the tag composers against the one rule in `src/core/tags.ts`, and an opt-in frontmatter-tags hygiene detector for existing vault content.
+- **t_151a564c** — pack vocabulary enforced on capture writes: `writeCaptureNote`/`writeIdeaNote` refuse an undeclared `kind` when the vault's pack explicitly declares `page_types`, before name allocation; fail-open on absent config per the established substitution precedent.
+- **t_59d4c919** — divergent session summaries surfaced on single-session reads: additive `digest_count`/`divergent` fields plus an id/hash list on the MCP and CLI single-session reads.
+- **t_dac8bf7e** — named think-block strip before CLI JSON parse: a shared strip-and-note parser for the four model-answer verbs; the strip is named on the success envelope, failure stays a named exit-1 refusal.
+- **t_18fda844** — digest-sealed content adoption plans: the state-migration seal generalized into `src/core/integrity/digest.ts` and applied to the Claude-memory import dry-run/apply pair and the brain-upgrade plan, including the caller-supplied-plan seam.
+- **t_586d5d8b** — extraction-contract fingerprint in the ingest manifest: a manifest-wide `contract` field, schema bump to 2 with a v1 read path, planner comparison, and plan-id folding.
+
+## Out of scope
+
+- **The link-verb half of the vocabulary card.** No `add_link` verb exists in the tree; only schema-mutation ops (`add_link_type`/`add_link_constraint`, `schema-mutate.ts`) do. Link-vocabulary enforcement has no write site to gate and is not built.
+- **Any merge policy for divergent summaries.** The continuity store stays append-only; divergence is named (`digest_count`, `divergent`, id/hash list), never merged, deleted, or reconciled.
+- **An argon2 native dependency.** The KDF is scrypt from `node:crypto`. The repo pins a single runtime dependency (`proper-lockfile`) and treats even optional native packages cautiously; argon2 would mean a native build or a new crypto package for a threat model `crypto.ts:13-17` already scopes.
+- **MCP-surface changes beyond named response extensions.** `brain_secrets` stays `list|run` (no lock/unlock/export/import over MCP, per the `admin-tools.ts:295-299` no-set/get refusal precedent); the divergence fields on `brain_session_summary` get are additive keys on an existing tool, nothing more; routing `src/core/graph/mcp-config.ts` env blocks through the resolver is deferred (open question below).
+- **Silent fallbacks of any kind.** Every fail-open posture in this wave (absent pack config, absent envelope, clean JSON, v1 manifest) is a named, documented declarative policy that predates the wave; no new path falls back quietly. A locked store never falls back to env for a name the store holds; a stripped payload is never silently accepted; a still-invalid payload never passes.
+
+## Premise verification
+
+Each card's recon was spot-checked against the live source before design. The anchors cited below were opened and verified across all four recon files, covering the crypto module, the resolver and egress planes, the tag rules and composers, the seal primitives, the session-summary read and its two surfaces, the capture writers, the manifest and planner, and the CLI parse sites. One test-path imprecision was found and is corrected under t_11ee559f. No card is refuted; nothing in the recon's load-bearing claims required correction.
+
+- **t_e6667a56 (wrapped keyfile) — confirmed.** `loadOrCreateKey` at `src/core/brain/secrets/crypto.ts:86-142` with `KEY_BYTES = 32` at :36, exclusive-create first-writer handling, per-value `encryptValue`/`decryptValue` AES-256-GCM at :144-164; op switch `set|list|rm|run` at `src/cli/brain/verbs/secret.ts:45-48`; `brain_secrets` MCP restriction docblock at `src/mcp/brain/admin-tools.ts:294-299`.
+- **t_e5807974 (resolver plane) — confirmed.** `src/core/secret-ref.ts` is 86 lines with `parseSecretReference` :27-32, `resolveSecretReference` :34-47, `redactKnownSecretValues` :67-86; `EGRESS_REDACTION_OPTIONS` at `src/core/egress/guard.ts:140-143`, `redactForEgress` at :181, `redactConfigMapping` at :241-245; `EGRESS_SITES` at `src/core/egress/registry.ts:108-343`; `o2b secrets` dispatch at `src/cli/main.ts:1270`.
+- **t_592d9e91 (credential bundles) — confirmed.** Guard/registry anchors above; census population rules verified in `tests/core/architecture/egress-census.test.ts` (rule 1 keys on declared `out`/`outdir`/`dest` parameters, and a declared site's module must be in the population — the destination flag and its registry entry must land in one commit).
+- **t_11ee559f (tag validation) — confirmed, one test-path correction.** `TAG_RE` at `src/core/tags.ts:29` with the docblock explicitly reserving itself as this card's seam ("validate against the rule defined HERE, never against a copy"); `OBSIDIAN_TAG_RE` at `src/core/brain/hygiene/detectors/tags.ts:62`; schema-vocab `TOKEN_RE` at `src/core/brain/schema-vocab.ts:38` (rejects `/`, must not be reused); composers verified at `src/core/brain/signal.ts:797-822` and `src/core/brain/preference.ts:808-825` (raw trimmed topic into `brain/topic/`); hand-rendered import frontmatter at `src/core/brain/claude-memory-render.ts:80`. Correction: recon-validation cites the signal tag-assertion tests at `tests/core/brain/signal.test.ts`; the file is actually `tests/core/brain.signal.test.ts` (dot-named convention, as recon-sessions spells `tests/core/brain.session-summary.test.ts` correctly).
+- **t_59d4c919 (divergent summaries) — confirmed.** `getSessionSummary` returns `records[records.length - 1]` unannounced at `src/core/brain/session-summary.ts:173-180`; sort by `(createdAt, id)` at :215-221; content-hash dedupe key at :139-150; MCP get at `src/mcp/brain/synthesis-tools.ts:125-129`; CLI get at `src/cli/brain/verbs/session-summary.ts:80-103`. The serializer drift is real: the MCP serializer includes `project` (`synthesis-tools.ts:84`), the CLI serializer omits it (`session-summary.ts:136-147`).
+- **t_151a564c (capture vocabulary) — confirmed.** `BRAIN_CAPTURE_KIND` at `src/core/brain/capture/capture-note.ts:52`, `writeCaptureNote` at :208, `allocateAndCreate` at :230, `parseCaptureFile` kind check at :287; `CAPTURED_IDEA_KIND` at `src/core/brain/capture/inbox-drain.ts:61`; absent-config substitution `ABSENT_SCHEMA_CONFIG_TEXT` at `src/core/brain/schema-pack.ts:56` with `readSchemaPackSource` at :78-83; write-session polarity verified at `src/core/brain/write-session/validate.ts:178-197` (fails closed when a type is named but no vocabulary, fails open when none declared).
+- **t_18fda844 (sealed plans) — confirmed.** `sealManifest`/`manifestVerifies` at `src/core/state/migrate.ts:186-194`; `sha256Hex`/`canonicalJson` in `src/core/integrity/digest.ts` (:43-45, :61-73); `planUpgrade` at `src/core/brain/upgrade.ts:116-134` returns an unsealed frozen plan; byte-drift refusal at :182-193 names `re-run --dry-run` but nothing seals a caller-supplied plan object.
+- **t_dac8bf7e (think-block strip) — confirmed.** Bare `JSON.parse` with the refusal `payload must be valid JSON` verified at `src/cli/brain/verbs/extract-signals.ts:129-140` and `src/cli/brain/verbs/design-note.ts:105-113`.
+- **t_586d5d8b (extraction-contract fingerprint) — confirmed.** `SCHEMA_VERSION = 1` at `src/core/brain/ingest/content-manifest.ts:41`, `ContentManifest` at :53-58; manifest consultation at `src/core/brain/ingest/batch-plan.ts:354-356`; `computePlanId` at `src/core/brain/ingest/checkpoint.ts:80-91` folds only the source dir plus sorted paths.
+
+## Chosen approach
+
+The consultant's three variants are reproduced verbatim in `variants.md`. The recommendation is **Variant 3 — forced sharing only, tiered enforcement, additive named keys**, and the orchestrator accepts it without override.
+
+Share exactly what the cards force: one `src/core/brain/secrets/envelope.ts` KDF/wrapped-envelope substrate under cards t_e6667a56 and t_592d9e91 (card 3 shares the KDF with card 1 by card statement), and one `sealWithDigest`/`digestVerifies` lift into `src/core/integrity/digest.ts` under cards t_18fda844 and (as a consumer of the same primitives) t_586d5d8b. Card t_e5807974 is a separate resolver-plane slice composing `parseSecretReference` with a read-oriented decrypt over the custody store, threading resolved literals into the egress guard policy so `redactKnownSecretValues` finally gains production callers. Enforcement is tiered by blast radius: tag validation rejects caller-controlled input at the composers (consuming the rule from `src/core/tags.ts`, never a copy) while capture vocabulary rejects only where the vault made a declaration, with hygiene detectors as the companion for existing vaults. Cards t_59d4c919 and t_dac8bf7e extend the existing response envelopes additively with named tokens, preserving byte-identity when the features are inactive.
+
+This variant was chosen over Variant 1 (which couples all three secrets slices behind an up-front substrate and hard-rejects live feedback topics without a compatibility story) and Variant 2 (which leaves three drifting copies of credential-critical code and leaves the primary single-session read silent). Its enforcement polarities sit exactly where the repo's own precedents sit: declared-vocabulary rejection with fail-open on absent config (`write-session/validate.ts:178-197`, `schema-pack.ts:56`), and caller-controlled-input rejection at the composers.
+
+## Design decisions
+
+- **KDF: scrypt from `node:crypto`, per-envelope random salt, stored parameters, no new dependency.** `scryptSync` with explicit `N = 2^15`, `r = 8`, `p = 1`, 32-byte output, a random 16-byte salt per envelope, and `maxmem` set explicitly; parameters are recorded inside the versioned envelope so they can migrate without breaking old stores, and an unknown `algo` or version refuses with a named error (the `readStore` bad-version precedent). Wrong-passphrase detection is free and fail-closed: the GCM auth tag over the wrapped DEK throws. `timingSafeEqual` guards any comparison. This matches the pinning posture (one runtime dependency) and the documented threat model (`crypto.ts:13-17` disclaims root/same-user attackers, against whom no passphrase KDF helps).
+- **Envelope file format and location.** New module `src/core/brain/secrets/envelope.ts`. When the operator opts in, the raw 32-byte keyfile at `<vault>/.open-second-brain/secrets/keyfile` is replaced by a schema-versioned JSON envelope `{ version, kdf: { algo: "scrypt", salt, n, r, p, maxmem }, wrapped: <EncryptedValue> }` where `wrapped` is the `encryptValue` output of the passphrase-derived key over the 32-byte DEK. The envelope file carries the same 0600/owner-only ACL discipline as the keyfile it replaces (`loadOrCreateKey` detects the envelope at the same path; the raw-keyfile branch remains the default and behaves byte-identically when no envelope exists). Opt-in is the operator's explicit wrap action, not a config key — presence of an envelope at the keyfile path is the state, and an unwrapped store needs no flag.
+- **Memory-only unlock semantics.** The passphrase arrives via stdin or `--passphrase-from-env` (there is no TTY password infrastructure in the repo; this follows the `set` op's ingestion pattern). The derived key lives only in a module-level unlock holder inside `envelope.ts`; `unlock` populates it after a verified unwrap, `lock` clears it, and the state is strictly process-local — the repo has no daemon, so every CLI invocation and the MCP server unlock separately. The passphrase is never persisted, logged, or audited; the audit trail gains `secret_locked`/`secret_unlocked` records with no values (the existing no-values audit discipline). Lock/unlock is not offered over MCP.
+- **Resolver provider interface and consumers.** `src/core/secret-resolver.ts` (Lane B) exposes a store-backed provider: it composes `parseSecretReference` with a read-oriented decrypt over the custody store — a new read-only resolve export in `src/core/brain/secrets/store.ts` (Lane A) that skips the `last_used_at` stamp and the exec audit, because `resolveSecretForExec` is read-shaped but a writer, and config reads must not take the write path. Precedence is store first, env fallback so existing setups keep working — except that a name the store holds under a locked envelope surfaces the named locked-store error rather than silently falling back to env (a silent fallback would hide the locked state). Consumers routed through the merged provider: the embeddings registry env probing, the decision-model env-key resolution, the research fetch keys, the Telegram token and installation secret in `src/core/config.ts`, and `o2b secrets status`/`list` availability. Resolution happens at use sites, not at config load, keeping plaintext spread no wider than the exec path's one-variable discipline. On the redaction side, Lane B threads a literals list from the resolver into the guard policy (`redactForEgress`, `redactConfigMapping`) and the MCP error redaction, which is what finally gives `redactKnownSecretValues` production callers.
+- **Tag validation fail-vs-flag posture per write site.** One spelling of the rule, consumed from `src/core/tags.ts` (which gains a value-level predicate derived from the documented rule — never a copy), implemented in `src/core/brain/tag-syntax.ts`. At the composers: `extraTags` entries that fail the rule are rejected with a typed, field-naming error (caller-controlled input, exactness expected); topic segments are slugified for the tag — matching what `deriveSlug` already does to the same input for the filename — and rejected only if even the slug fails the rule; scope segments are rejected, not rewritten. The Claude-memory import render path validates its derived topic/scope (already slugified today, so this is a pin, not a behavior change). The trade-off is stated honestly: a spaced topic's tag value changes from `brain/topic/foo bar` to `brain/topic/foo-bar`, which is the defect being fixed, deterministic, and consistent with the note's own filename slug. Existing vault content is covered by the new opt-in `frontmatter-tags` hygiene detector (registered through `HYGIENE_DETECTOR_IDS`/`DETECTORS`, default-off like `tags`), which flags and never auto-fixes.
+- **Capture vocabulary fail-closed rule and escape hatch.** `writeCaptureNote` and `writeIdeaNote` consult `declaredPageTypes(vault)` (new predicate beside `schema-pack.ts`, null when no pack is active — "pack active" means the config is present and declares `page_types`, since the merged vocabulary always contains `note`). When active, a stamped `kind` not in the declaration refuses with the module's typed `CaptureContractError` before `allocateAndCreate`, so a refused capture never consumes a name; the error names the kind, the declared set, and the remedy (declare the kind in `Brain/_brain.yaml`). Absent or declaration-free config fails open — the `ABSENT_SCHEMA_CONFIG_TEXT` substitution precedent, a named declarative policy rather than a silent fallback. The frontmatter key stays `kind` (judging the stamped kind against `page_types` without retyping to `type: note`), because `parseCaptureFile` reads `kind` and a retype would make captures invisible to the drain. No companion detector: the typed refusal is the guidance, and a detector for packs omitting build-stamped kinds is an open question, not committed scope.
+- **Digest-seal format for content plans.** `sealManifest`/`manifestVerifies` lift into `src/core/integrity/digest.ts` as `sealWithDigest(body)`/`digestVerifies(body, digest)` over `sha256Hex(canonicalJson(body))`; `migrate.ts` keeps thin aliases so its behavior is untouched. Sealed bodies exclude wall-clock fields (the injected-`now` rationale from `migrate.ts`). Claude-memory import: the dry-run result carries the plan digest; `--apply` accepts `--approval-digest`, recomputes the plan, seals, and compares before the snapshot/write loop, refusing drift with the `re-run --dry-run` remedy. Brain upgrade: `UpgradePlan` gains a `digest` sealed inside `planUpgrade` and verified at the top of `applyUpgrade`, closing the caller-supplied-plan seam (the self-heal worker computes its own plan, which trivially verifies). The interactive TTY prompt remains the human escape hatch for apply-without-digest; scripts must carry the digest.
+- **Divergence report response shape: extend existing envelopes, additive fields only.** A divergence-aware core read returns the sorted-latest digest plus `digest_count`, and, only when the count exceeds one, `divergent: true` plus a bounded id/`created_at`/`content_hash` list — id/hash lists rather than full payload echoes, because `MCP_PREVIEW_BUDGET` applies to the serialized content. The MCP `get` result and the CLI get `--json` object gain the same keys via the conditional-key idiom; `{ found: false }` is untouched; the tool declares no `outputSchema`, so added keys cannot trip an envelope contract. The CLI serializer's missing `project` (verified drift) is folded into the same change.
+- **Think-block strip as a named step in the result envelope.** `src/core/brain/payload-json.ts` exports a strip-and-note parser: try `JSON.parse` as-is; on failure, strip one leading `<think>...</think>` block (fenced-block unwrap following the `llm-emulation.ts` precedent), retry, and return the payload plus the strip fact (`kind`, `prefixChars`) or a named unparseable error. The four model-answer verbs (`extract-signals`, `design-note`, `skill-proposals`, `distill`) route through it; the strip fact rides the `note` key of the existing `{ ok: true }` envelope only when a strip happened, and a still-invalid payload keeps today's named exit-1 refusal, with the message naming the strip attempt. Clean JSON produces byte-identical output. The strip never rescues genuinely malformed JSON into a silent pass — it is named or it does not happen.
+- **Extraction contract fingerprint: fields and changed-contract behavior.** The manifest gains one manifest-wide field, `contract: { fingerprint: string }` — one short hex string total, not per-entry. The fingerprint is `sha256Hex(canonicalJson({ version: EXTRACT_CONTRACT_VERSION, extractable: [...sorted] })).slice(0, 16)` computed in a new small module beside the manifest, over the vault's schema `extractable` allowlist plus a hand-bumped `EXTRACT_CONTRACT_VERSION` constant (the `CHUNKER_VERSION` bump-guard convention) covering code-scoped extraction behavior; per-call options (`pre_extract`, `extensions`, `exclude`, caps) stay out, matching the session lane's scope-vs-options split. `SCHEMA_VERSION` bumps to 2 with a `SUPPORTED_SCHEMA_VERSIONS`-style read: a v1 manifest is a known previous version whose contract is treated as changed — every source reprocesses once, then the rewrite lands as v2; genuinely unknown versions still hard-refuse. `planBatches` compares fingerprints immediately after `readManifest`; on mismatch, `unchanged` sources reprocess with a distinct typed reason token so reporting distinguishes "bytes changed" from "contract changed". The fingerprint folds into `computePlanId` (the `computeSessionImportId` pattern) so a stale checkpoint cannot resume-skip work extracted under the old contract; old checkpoint files orphan harmlessly. `source-cleanup`'s direct manifest write round-trips the field.
+
+## File changes
+
+By lane (exact ownership and per-task file lists are pinned in `plan.md`; lanes never touch another lane's files):
+
+- **Lane A (secrets envelope, t_e6667a56 + t_592d9e91):** new `src/core/brain/secrets/envelope.ts`, `src/core/brain/secrets/bundle.ts`; modified `src/core/brain/secrets/crypto.ts`, `src/core/brain/secrets/store.ts`, `src/cli/brain/verbs/secret.ts`, `src/cli/command-manifest.ts`, `src/cli/help-text.ts`, `src/core/egress/registry.ts` (the bundle destination — the wave's only new egress site), and the secrets/CLI/architecture test files listed in the plan.
+- **Lane B (resolver plane, t_e5807974):** new `src/core/secret-resolver.ts`; modified `src/core/secret-ref.ts`, `src/core/search/embeddings/registry.ts`, `src/core/decision-model/config.ts`, `src/core/brain/research/research.ts`, `src/core/config.ts`, `src/cli/main.ts`, `src/core/egress/guard.ts`, `src/mcp/error-redaction.ts`, and their test files.
+- **Lane C (vault validation, t_11ee559f + t_151a564c):** new `src/core/brain/tag-syntax.ts`, `src/core/brain/hygiene/detectors/frontmatter-tags.ts`; modified `src/core/tags.ts`, `src/core/brain/signal.ts`, `src/core/brain/preference.ts`, `src/core/brain/claude-memory-render.ts`, `src/core/brain/schema-pack.ts`, `src/core/brain/capture/capture-note.ts`, `src/core/brain/capture/inbox-drain.ts`, `src/core/brain/hygiene/types.ts`, `src/core/brain/hygiene/scan.ts`, and their test files.
+- **Lane D (sealed content plans, t_18fda844):** modified `src/core/integrity/digest.ts`, `src/core/state/migrate.ts`, `src/core/brain/import-claude-memory.ts`, `src/core/brain/upgrade.ts`, `src/cli/brain/verbs/import-claude-memory.ts`, `src/cli/brain/helpers.ts`, and their test files.
+- **Lane E (sessions honesty, t_59d4c919 + t_dac8bf7e):** new `src/core/brain/payload-json.ts`; modified `src/core/brain/session-summary.ts`, `src/mcp/brain/synthesis-tools.ts`, `src/cli/brain/verbs/session-summary.ts`, `src/cli/brain/verbs/extract-signals.ts`, `src/cli/brain/verbs/design-note.ts`, `src/cli/brain/verbs/skill-proposals.ts`, `src/cli/brain/verbs/distill.ts`, and their test files.
+- **Lane F (ingest contract, t_586d5d8b):** new `src/core/brain/ingest/contract.ts`; modified `src/core/brain/ingest/content-manifest.ts`, `src/core/brain/ingest/batch-plan.ts`, `src/core/brain/ingest/checkpoint.ts`, `src/core/brain/source-cleanup.ts`, `src/mcp/brain/ingest-tools.ts`, `src/cli/brain/verbs/batch-plan.ts`, and their test files.
+
+## Risks and open questions
+
+- **Passphrase loss is unrecoverable.** A forgotten passphrase makes every stored secret permanently unreadable. The verb help and the module header must state this in plain terms; there is no recovery path and none is pretended.
+- **Multi-process unlock friction.** Every CLI invocation and the MCP server unlock separately; an agent-driven workflow hitting a locked store gets a named error and must stop, which is the point. The MCP server holding a derived key for its lifetime would weaken memory-only semantics — resolved by refusing unlock over MCP.
+- **Bundle egress honesty.** The export payload is ciphertext by construction, which defeats both the `sharedRedactor` and `noVaultContent` statuses as-is. The working choice is to run `redactForEgress` over the envelope's non-ciphertext metadata tree and declare `sharedRedactor`; the exact status wording is a deliberate decision at implementation time (Lane A2), pinned as such in the plan.
+- **Topic tag values change for spaced topics** (`brain/topic/foo bar` becomes `brain/topic/foo-bar`). Deterministic and consistent with the filename slug, but it is a visible byte change on affected writes; the tag-syntax test suite pins the before/after shapes.
+- **Capture rejections in packs authored before `brain-capture` existed.** Mitigated by the fail-open-unless-declared rule; a vault only breaks captures by explicitly declaring `page_types` without the kinds the build stamps, and the refusal names the remedy.
+- **Approval-digest UX.** An operator who applies without dry-running has no digest; interactive TTY apply stays the human escape hatch while non-interactive apply requires the digest, matching the existing `--yes` guard asymmetry.
+- **Resolver hot paths.** The read-only resolve still reads under the secrets lock; whether config-resolution frequency (embeddings expand runs per index/query) needs lock-free caching is deferred to B1's tests — correctness first, caching only if measured.
+- **Open: `src/core/graph/mcp-config.ts` resolver routing** — deferred to keep MCP-surface changes at zero in this wave; revisit once the resolver has production consumers.
+- **Open: v1-ingest-manifest one-time full reprocess** lands on every upgraded vault on first plan; acceptable (documented degradation, no error), but worth a CHANGELOG note so operators are not surprised by the first run's cost.
+- **Open: a hygiene/doctor finding for packs whose declared `page_types` omit build-stamped kinds** — useful, but not committed scope in this wave; the typed refusal already names the remedy.
diff --git a/docs/brainstorm/trust-surface-hardening/plan.md b/docs/brainstorm/trust-surface-hardening/plan.md
new file mode 100644
index 00000000..eca7bcb3
--- /dev/null
+++ b/docs/brainstorm/trust-surface-hardening/plan.md
@@ -0,0 +1,137 @@
+# Trust-Surface Hardening — implementation plan
+
+Implemented via TDD on branch `feat/trust-surface-hardening` in the worktree `~/projects/tools/osb-worktrees/cycle-20261009`. Six lanes run with **disjoint file ownership**: a lane never creates, modifies, or deletes a file another lane owns. The combined design is at `docs/brainstorm/trust-surface-hardening/design.md` (same branch).
+
+## Cross-lane contract (binding for every lane)
+
+**Path ownership.** The tables below are exhaustive. If a task seems to need a file outside its lane, stop and reconcile through the wave coordinator — do not touch the file.
+
+| Lane | Owns (source) | Owns (tests) |
+|---|---|---|
+| A | `src/core/brain/secrets/*` (envelope.ts, bundle.ts new; crypto.ts, store.ts modified), `src/cli/brain/verbs/secret.ts`, `src/cli/command-manifest.ts`, `src/cli/help-text.ts`, `src/core/egress/registry.ts` | `tests/core/brain/secrets/**`, `tests/cli/brain-secret.test.ts`, `tests/core/architecture/write-site-census.test.ts`, `tests/core/architecture/egress-census.test.ts`, `tests/cli/manifest-completeness.test.ts`, `tests/core/brain/vault-guard-census.test.ts`, `tests/core/brain/vault-identity.test.ts`, `tests/core/state/surfaces.test.ts` (secrets dir rows only) |
+| B | `src/core/secret-ref.ts`, `src/core/secret-resolver.ts` (new), `src/core/search/embeddings/registry.ts`, `src/core/decision-model/config.ts`, `src/core/brain/research/research.ts`, `src/core/config.ts`, `src/cli/main.ts`, `src/core/egress/guard.ts`, `src/mcp/error-redaction.ts` | `tests/core/secret-ref.test.ts`, `tests/core/secret-resolver.test.ts` (new), `tests/core/egress-resolved-literals.test.ts` (new), `tests/core/search/embeddings.registry.test.ts`, `tests/core/decision-model/config.test.ts`, `tests/core/brain/research/research.test.ts`, `tests/core/config-telegram-capture.test.ts`, `tests/core/config.installation-secret.test.ts` |
+| C | `src/core/tags.ts`, `src/core/brain/tag-syntax.ts` (new), `src/core/brain/signal.ts`, `src/core/brain/preference.ts`, `src/core/brain/claude-memory-render.ts`, `src/core/brain/schema-pack.ts`, `src/core/brain/capture/capture-note.ts`, `src/core/brain/capture/inbox-drain.ts`, `src/core/brain/hygiene/types.ts`, `src/core/brain/hygiene/scan.ts`, `src/core/brain/hygiene/detectors/frontmatter-tags.ts` (new) | `tests/core/brain/tag-syntax.test.ts` (new), `tests/core/brain.signal.test.ts`, `tests/core/brain.preference.test.ts`, `tests/core/brain/claude-memory-render.test.ts`, `tests/core/brain/hygiene-frontmatter-tags.test.ts` (new), `tests/core/brain/hygiene-tags.test.ts`, `tests/core/brain/hygiene-scan.test.ts`, `tests/core/brain/capture/capture-note.test.ts`, `tests/core/brain/capture/inbox-drain.test.ts`, `tests/core/brain/capture/telegram-capture.test.ts` |
+| D | `src/core/integrity/digest.ts`, `src/core/state/migrate.ts`, `src/core/brain/import-claude-memory.ts`, `src/core/brain/upgrade.ts`, `src/cli/brain/verbs/import-claude-memory.ts`, `src/cli/brain/helpers.ts` | `tests/core/integrity/digest.test.ts`, `tests/core/state/migrate.test.ts`, `tests/core/brain/import-claude-memory-orchestrator.test.ts`, `tests/core/brain/upgrade.test.ts`, `tests/core/brain/upgrade-drift.test.ts`, `tests/cli/brain-import-claude-memory.test.ts`, `tests/cli/brain-upgrade.test.ts` |
+| E | `src/core/brain/session-summary.ts`, `src/core/brain/payload-json.ts` (new), `src/mcp/brain/synthesis-tools.ts`, `src/cli/brain/verbs/session-summary.ts`, `src/cli/brain/verbs/extract-signals.ts`, `src/cli/brain/verbs/design-note.ts`, `src/cli/brain/verbs/skill-proposals.ts`, `src/cli/brain/verbs/distill.ts` | `tests/core/brain.session-summary.test.ts`, `tests/core/brain/payload-json.test.ts` (new), `tests/mcp/session-summary-tool.test.ts`, `tests/cli/brain-session-summary.test.ts` (new), `tests/cli/brain-extract-signals.test.ts`, `tests/cli/brain-design-note.test.ts`, `tests/cli/brain-skill-page-drafts.test.ts`, `tests/cli/brain-distill.test.ts` |
+| F | `src/core/brain/ingest/contract.ts` (new), `src/core/brain/ingest/content-manifest.ts`, `src/core/brain/ingest/batch-plan.ts`, `src/core/brain/ingest/checkpoint.ts`, `src/core/brain/source-cleanup.ts`, `src/mcp/brain/ingest-tools.ts`, `src/cli/brain/verbs/batch-plan.ts` | `tests/core/brain/ingest/**` (contract.test.ts new; content-manifest, batch-plan, batch-plan-extractable, checkpoint, reconcile, ingest modified), `tests/cli/brain-batch-plan-reconcile.test.ts`, `tests/mcp/ingest-plan-format-reach.test.ts` |
+
+Notes on the two deliberate ownership placements:
+
+- **Egress split.** `src/core/egress/guard.ts` is Lane B's (resolver literals wiring); `src/core/egress/registry.ts` and `tests/core/architecture/egress-census.test.ts` are Lane A's, because the credential-bundle export destination is the wave's only new egress site. The census asserts both directions (a site's module must be in the population), so Lane A's A2 lands the `--out` flag and the registry entry and the census rows in ONE commit — never split across commits.
+- **Lane A exports, Lane B consumes.** Lane A's A1 ships a read-only resolve export on `src/core/brain/secrets/store.ts` (no `last_used_at` stamp, no exec audit). Lane B's resolver calls that export through the module's public surface only; it must never edit secrets-module files.
+
+**Commit discipline.** Every lane commits with `git commit --only <paths>` — stage and commit in ONE step. Never `git add` files (shared or not) followed by a plain `git commit`; `--only` is what keeps a lane from sweeping up a sibling's in-flight work.
+
+**Format and lint before every commit.** Run `./node_modules/.bin/oxfmt` and `./node_modules/.bin/oxlint` on YOUR files only, before every commit.
+
+**The pre-commit hook checks the whole tree.** `.githooks/pre-commit` runs `bun run fmt:check` (and mirror checks) over the entire worktree, not just your paths. If it blocks on a sibling lane's transient state, wait 30 s and retry, up to 5 attempts. Never pass `--no-verify`.
+
+**Windows-safe tests.** No chmod-deny assertions without a `tests/helpers/platform.ts` skip guard (`IS_WINDOWS`, `RUNNING_AS_ROOT`, and the chmod-cannot-deny constant). Normalize path separators in every path assertion (compare on `path.sep`-normalized or forward-slash forms). The existing secrets suites already show the `IS_WINDOWS` skip pattern.
+
+**No scanner false positives.** No identifier may contain the substring `secret` immediately before a quoted value of 8+ characters (plugin scanners flag it). Use names in the `PRIVATE_PATH` / `credentialRef` style. In tests, assemble credential-shaped literals at runtime via `tests/helpers/fake-credentials.ts` instead of writing literal-looking values.
+
+**No hardcoded natural-language phrases.** All operator-facing strings are English constants hoisted next to their siblings; error and reason tokens come from closed tables, never assembled from prose; errors surface by name (stable `code`/token), never as ad-hoc sentences alone.
+
+**Opt-in flags.** Any new config flag is opt-in with defaults preserving current behavior byte-for-byte. The wave's write-path changes are card-mandated (rejection is the feature), and each is covered by its own failing-test-first proof below.
+
+## Lane A — secrets envelope (cards t_e6667a56, t_592d9e91)
+
+### Task A1 — passphrase-wrapped keyfile, lock/unlock lifecycle, read-only resolve export (t_e6667a56)
+
+- **Files**: new `src/core/brain/secrets/envelope.ts` (scrypt KDF block: explicit `N = 2^15`, `r = 8`, `p = 1`, 32-byte out, random 16-byte salt, explicit `maxmem`, `timingSafeEqual`; versioned envelope `{ version, kdf: { algo, salt, n, r, p, maxmem }, wrapped }`; module-level memory-only unlock holder with lock/unlock lifecycle); modified `src/core/brain/secrets/crypto.ts` (`loadOrCreateKey` detects an envelope at the keyfile path and unwraps via the holder; raw-keyfile branch unchanged); modified `src/core/brain/secrets/store.ts` (new read-only resolve export that decrypts a named value without the `last_used_at` stamp or exec audit — Lane B's contract; `secret_locked`/`secret_unlocked` audit actions via the existing no-values audit; every new entry point behind `assertVaultIdentityForWrite` where the sibling writers have it); modified `src/cli/brain/verbs/secret.ts` (ops `lock`, `unlock`; passphrase via stdin or `--passphrase-from-env` following the `set` ingestion pattern; wrap-on-first-unlock converts a raw keyfile); modified `src/cli/command-manifest.ts`, `src/cli/help-text.ts` (new ops modeled; loss warning stated). Tests: new `tests/core/brain/secrets/envelope.test.ts`; modified `tests/core/brain/secrets/store.test.ts` (envelope detection, locked-store named errors), `tests/core/brain/secrets/exec.test.ts` (exec under locked store), `tests/core/brain/secrets/owner-acl.test.ts` (envelope file ACL/mode, platform-guarded), `tests/core/brain/secrets/sync-exposure.test.ts` (wrapped-keyfile messaging), `tests/cli/brain-secret.test.ts` (lock/unlock ops), `tests/core/brain/vault-guard-census.test.ts`, `tests/core/brain/vault-identity.test.ts` (new entry points carry the guard), `tests/core/architecture/write-site-census.test.ts` (envelope.ts writes the keyfile path), `tests/cli/manifest-completeness.test.ts` (verify it stays green: the ratchet enumerates dispatcher switches one level deep, and `brain secret` sub-ops are parsed by the verb, so the manifest update is by hand in `src/cli/command-manifest.ts`; edit the test only if the ratchet's assertions reach the new ops).
+- **Acceptance**: `tests/core/brain/secrets/envelope.test.ts` asserts (a) wrap produces the versioned envelope at the keyfile path and the raw 32-byte DEK never appears on disk; (b) wrong passphrase fails closed via the GCM tag with a named error; (c) stored scrypt parameters round-trip and an unknown `algo`/version refuses by name; (d) unlock populates a process-local holder, `lock` clears it, and a second context over the same vault sees the named locked-store refusal; (e) the passphrase is never written anywhere under the vault (tree scan); (f) a never-wrapped store behaves byte-identically to today (regression assertions against the existing store suite's shapes). Every assertion must fail on pre-fix code (the module does not exist). Mode/ACL assertions carry the platform skip.
+- **Depends on**: none.
+
+### Task A2 — passphrase-encrypted credential bundles (t_592d9e91)
+
+- **Files**: new `src/core/brain/secrets/bundle.ts` (`exportSecretBundle` decrypts entries in memory and re-encrypts each under a key derived from the passphrase via A1's envelope; `importSecretBundle` verifies, reuses name/env-var validation, runs the vault-identity guard and the store lock, writes through `writeStore`; `schema`, `generated_at` excluded from sealed content, KDF params inside); modified `src/cli/brain/verbs/secret.ts` (ops `export`, `import`, `--out FILE` via `atomicWriteFileSync`, `--replace` for import conflicts); modified `src/core/egress/registry.ts` (single new site entry for the bundle export destination, honest redaction status over the non-ciphertext metadata tree — the deliberate wording decision, recorded in the entry's `reason`); modified `src/cli/command-manifest.ts`, `src/cli/help-text.ts`. Tests: new `tests/core/brain/secrets/bundle.test.ts`; modified `tests/cli/brain-secret.test.ts` (export/import ops), `tests/core/architecture/egress-census.test.ts` (the new site's declaration rows), `tests/core/architecture/write-site-census.test.ts` (bundle.ts write site).
+- **Acceptance**: `tests/core/brain/secrets/bundle.test.ts` asserts (a) export-then-import into a fresh vault restores names, env-var mappings, and allowlists; (b) wrong passphrase on import fails closed with a named error and writes nothing to the target store; (c) import refuses an existing name without `--replace` (exactness mirroring `removeSecret`); (d) the exported file's bytes contain none of the run-assembled credential literals from `tests/helpers/fake-credentials.ts`; (e) audit records `secret_bundle_exported`/`secret_bundle_imported` with no values; (f) unknown bundle `algo`/version refuses by name. Must fail on pre-fix code. The egress census must be green with A2's own commit (flag + entry + census rows land together).
+- **Depends on**: A1.
+
+## Lane B — resolver plane (card t_e5807974)
+
+### Task B1 — custody-store-backed provider with env fallback (t_e5807974)
+
+- **Files**: new `src/core/secret-resolver.ts` (`secretProvider(vault)` adapter composing `parseSecretReference` with Lane A's read-only resolve export; precedence store-first, env-fallback, EXCEPT a name the store holds under a locked envelope surfaces the named locked-store error — no silent env fallback; `resolveNamedSecret` for single values; metadata-only availability for `list`); modified `src/core/secret-ref.ts` only if the provider type moves beside `SecretProvider` (allowed, this lane's file). Tests: new `tests/core/secret-resolver.test.ts`.
+- **Acceptance**: `tests/core/secret-resolver.test.ts` asserts (a) a `$secret:NAME` value resolves from the custody store without stamping `last_used_at` and without emitting exec audit records; (b) env fallback resolves when the store does not hold the name; (c) a store-held name under a locked envelope produces the named locked-store error, not the env value; (d) malformed references keep the existing `SecretReferenceError` behavior; (e) resolution does not mutate the store file (byte-compare before/after). Must fail on pre-fix code (the module does not exist).
+- **Depends on**: A1 (the read-only resolve export).
+
+### Task B2 — route credential consumers through the resolver (t_e5807974)
+
+- **Files**: modified `src/core/search/embeddings/registry.ts` (`expandRegisteredProvider` probes through the merged provider), `src/core/decision-model/config.ts` (env-key resolution), `src/core/brain/research/research.ts` (fetch API keys), `src/core/config.ts` (Telegram token, installation secret), `src/cli/main.ts` (`o2b secrets status`/`list` availability from the merged provider; the exit-code contract for status stays unchanged). Tests: modified `tests/core/search/embeddings.registry.test.ts`, `tests/core/decision-model/config.test.ts`, `tests/core/brain/research/research.test.ts`, `tests/core/config-telegram-capture.test.ts`, `tests/core/config.installation-secret.test.ts`; new `tests/core/secret-resolver.test.ts` cases for merged-provider availability (same file as B1, this lane's).
+- **Acceptance**: the per-consumer suites assert that a `$secret:NAME` value in the consumer's config resolves through the store-backed provider at the use site (behavior identical to the env-provided value), that plain env values keep working byte-identically when no reference is used, and that an unresolvable reference surfaces the named resolver error instead of a silent empty value. Each consumer test must fail on pre-fix code (references resolve nothing today).
+- **Depends on**: B1.
+
+### Task B3 — egress redaction wiring for resolved values (t_e5807974)
+
+- **Files**: modified `src/core/egress/guard.ts` (the policy/`EGRESS_REDACTION_OPTIONS` composition accepts a resolved-literals list; `redactForEgress` and `redactConfigMapping` scrub them alongside the existing structural passes), `src/mcp/error-redaction.ts` (same literals on the MCP error path). Tests: new `tests/core/egress-resolved-literals.test.ts`.
+- **Acceptance**: `tests/core/egress-resolved-literals.test.ts` asserts (a) `redactForEgress` with a literals-bearing policy replaces each resolved value (longest first) with the standard marker before any truncation; (b) `redactConfigMapping` does the same; (c) with no literals the output is byte-identical to today; (d) the MCP error path scrubs resolved literals; (e) the verdict vocabulary stays within the closed census (`tests/core/architecture/verdict-vocabulary-census.test.ts` stays green untouched). Must fail on pre-fix code (literals cannot be injected today).
+- **Depends on**: B1.
+
+## Lane C — vault validation (cards t_11ee559f, t_151a564c)
+
+### Task C1 — tag syntax helper and composer enforcement (t_11ee559f, write half)
+
+- **Files**: new `src/core/brain/tag-syntax.ts` (`isObsidianTagValue` / typed field-naming error shaped like `SchemaVocabularyError`); modified `src/core/tags.ts` (the value-level predicate lives HERE, derived from the documented rule — one spelling, consumed, never copied); modified `src/core/brain/signal.ts` (`composeSignalTags`: `extraTags` entries failing the rule reject with the typed error; topic segment slugified then validated; scope segment rejected, not rewritten), `src/core/brain/preference.ts` (`composePreferenceTags`: same polarity), `src/core/brain/claude-memory-render.ts` (validate the derived topic/scope — a pin, they are slugified already). Tests: new `tests/core/brain/tag-syntax.test.ts`; modified `tests/core/brain.signal.test.ts` (new tag-syntax describe block: spaced topic yields the slugified tag, bad `extraTags` refuse with the field named, clean inputs byte-identical), `tests/core/brain.preference.test.ts` (same), `tests/core/brain/claude-memory-render.test.ts` (frontmatter tags always parse-shaped).
+- **Acceptance**: `tests/core/brain/tag-syntax.test.ts` asserts the rule against the `src/core/tags.ts` definition (accepts `/` nesting, rejects spaces and other specials, rejects leading slash and pure-numeric values) and that the predicate is imported, not redefined (a source-shape assertion). The composer tests must fail on pre-fix code (`brain/topic/foo bar` lands today).
+- **Depends on**: none.
+
+### Task C2 — frontmatter-tags hygiene detector (t_11ee559f, doctor half)
+
+- **Files**: new `src/core/brain/hygiene/detectors/frontmatter-tags.ts` (modeled on `detectTags`; reads frontmatter `tags:` via the existing frontmatter parser, which `detectTags` explicitly scopes out; findings severity `info`, proposed action review, frozen finding ids); modified `src/core/brain/hygiene/types.ts` (id registered in `HYGIENE_DETECTOR_IDS`), `src/core/brain/hygiene/scan.ts` (`DETECTORS` map entry; excluded from `DEFAULT_SCAN_IDS` — opt-in like `tags`). Tests: new `tests/core/brain/hygiene-frontmatter-tags.test.ts`; modified `tests/core/brain/hygiene-tags.test.ts` (registration pins: the new id in the closed tuple, excluded from the default sweep), `tests/core/brain/hygiene-scan.test.ts` (composition).
+- **Acceptance**: `tests/core/brain/hygiene-frontmatter-tags.test.ts` asserts (a) a note whose frontmatter `tags:` contains an unparseable value produces a finding with evidence naming the value and the rule; (b) parse-shaped tags produce nothing; (c) the detector never mutates the vault; (d) the default sweep skips it and an explicit `--detectors` subset runs it (pinning the existing two-policy mechanism). Must fail on pre-fix code (id unregistered, detector absent). Uses C1's predicate — never a local rule copy.
+- **Depends on**: C1.
+
+### Task C3 — capture vocabulary enforcement (t_151a564c)
+
+- **Files**: modified `src/core/brain/schema-pack.ts` (new `declaredPageTypes(vault)` predicate: null when no config is present, the declared `page_types` when declarations are non-empty; `loadSchemaPack` untouched); modified `src/core/brain/capture/capture-note.ts` (`writeCaptureNote` refuses an undeclared `kind` with the module's `CaptureContractError` before `allocateAndCreate`, naming the kind, the declared set, and the remedy), `src/core/brain/capture/inbox-drain.ts` (`writeIdeaNote`: same gate for `captured-idea`). Tests: modified `tests/core/brain/capture/capture-note.test.ts` (new cases: pack declaring `page_types` without `brain-capture` refuses before any file exists in the captures dir and before a name is consumed; declared set containing it passes; absent config fails open with byte-identical output), `tests/core/brain/capture/inbox-drain.test.ts` (mirror for `captured-idea`), `tests/core/brain/capture/telegram-capture.test.ts` (the typed refusal surfaces through the Telegram lane as every other contract refusal does).
+- **Acceptance**: the capture-note tests assert (a) refuse-before-allocate (the captures directory gains no file and the allocator consumes no name on refusal); (b) fail-open on absent config preserving today's behavior exactly; (c) `kind` stays the frontmatter key and `parseCaptureFile` still reads refused-then-fixed captures. Must fail on pre-fix code (no vocabulary consult exists today).
+- **Depends on**: none.
+
+## Lane D — sealed content adoption plans (card t_18fda844)
+
+### Task D1 — generalize the seal into the integrity module (t_18fda844, substrate)
+
+- **Files**: modified `src/core/integrity/digest.ts` (export `sealWithDigest(body)` and `digestVerifies(body, digest)` over `sha256Hex(canonicalJson(body))`, documented beside the persisted-digest doctrine in the module header); modified `src/core/state/migrate.ts` (`sealManifest`/`manifestVerifies` become thin aliases over the lifted primitives; behavior untouched). Tests: modified `tests/core/integrity/digest.test.ts` (seal/verify round-trip, canonical-JSON stability, tamper refusal), `tests/core/state/migrate.test.ts` (the existing digest-binding pins still hold through the aliases, including the `:200-201` recomputation pin).
+- **Acceptance**: the digest test asserts seal-then-verify round-trips and that any body mutation fails verification; the migrate pins prove the aliasing changed nothing (all existing assertions pass unmodified in shape). Must fail on pre-fix code (the exports do not exist).
+- **Depends on**: none.
+
+### Task D2 — seal the Claude-memory import plan (t_18fda844)
+
+- **Files**: modified `src/core/brain/import-claude-memory.ts` (dry-run seals the plan body — plans, skipped, conflicts, relevant inputs; wall-clock fields excluded; the result carries the digest; apply accepts an `approvalDigest` option, re-plans, seals, and compares BEFORE the snapshot/write loop, refusing drift with a typed error whose remedy names `re-run --dry-run`); modified `src/cli/brain/verbs/import-claude-memory.ts` (`--approval-digest`; non-interactive apply requires it, interactive TTY keeps the existing prompt asymmetry). Tests: modified `tests/core/brain/import-claude-memory-orchestrator.test.ts` (digest present on dry-run; apply with the correct digest lands exactly the approved plan; apply with a stale digest refuses before any write or snapshot), `tests/cli/brain-import-claude-memory.test.ts` (flag plumbing; non-interactive apply without a digest refuses by name).
+- **Acceptance**: the orchestrator test asserts a vault mutation between dry-run and apply makes apply refuse with nothing written (byte-compare the vault tree), and that a matching digest applies bit-identically to today's clean path. Must fail on pre-fix code (no digest exists, apply never refuses).
+- **Depends on**: D1.
+
+### Task D3 — seal the brain-upgrade plan (t_18fda844)
+
+- **Files**: modified `src/core/brain/upgrade.ts` (`UpgradePlan` gains `digest`; sealed inside `planUpgrade`; `applyUpgrade` verifies at the top, before the drift check and the snapshot — a caller-supplied plan failing verification gets the drift refusal shape with a distinct message); modified `src/cli/brain/helpers.ts` (`renderUpgradePlanJson` emits the digest). Tests: modified `tests/core/brain/upgrade.test.ts` (self-computed plan trivially verifies; idempotent no-op unchanged), `tests/core/brain/upgrade-drift.test.ts` (a hand-built plan with a tampered body refuses with the seal message before the byte-drift check runs), `tests/cli/brain-upgrade.test.ts` (the JSON plan output carries the digest). The self-heal worker (`src/core/maintenance/self-heal-upgrade.ts`) is deliberately NOT edited: it computes its own plan, which verifies trivially — its existing suites must stay green untouched.
+- **Acceptance**: the drift test asserts a caller-supplied, tampered plan is refused before any write (nothing on disk changes, no snapshot taken), and the upgrade test asserts the sealed plan applies bit-identically to today. Must fail on pre-fix code (plans carry no digest and are trusted as-is).
+- **Depends on**: D1.
+
+## Lane E — sessions honesty (cards t_59d4c919, t_dac8bf7e)
+
+### Task E1 — divergent session summaries on single-session reads (t_59d4c919)
+
+- **Files**: modified `src/core/brain/session-summary.ts` (new exported divergence-aware read returning the sorted-latest digest plus `digest_count`, and, when the count exceeds one, `divergent: true` plus a bounded id/`created_at`/`content_hash` list; `getSessionSummary` remains a thin wrapper so no caller changes); modified `src/mcp/brain/synthesis-tools.ts` (the `get` operation spreads the additive fields via the conditional-key idiom; `{ found: false }` untouched; id/hash lists, never full payload echoes); modified `src/cli/brain/verbs/session-summary.ts` (same fields on `--json`; one note line in text mode; the serializer gains `project`, fixing the verified CLI/MCP drift). Tests: modified `tests/core/brain.session-summary.test.ts` (two content-differing appends: the new read reports `digest_count: 2` and `divergent: true` and still returns the sorted-latest; single record reports count 1 and no `divergent` key; the existing latest-wins pins survive), `tests/mcp/session-summary-tool.test.ts` (get after two differing writes carries the additive keys; `found: false` case byte-identical); new `tests/cli/brain-session-summary.test.ts` (CLI get: `--json` fields, text note line, `project` now serialized).
+- **Acceptance**: the core test asserts divergence is computed over content-differing records for one session (a duplicate-content write still dedupes to count 1), and every response is additive — no existing key moves or disappears. Must fail on pre-fix code (no divergence read exists; the CLI serializer omits `project` today).
+- **Depends on**: none.
+
+### Task E2 — named think-block strip before CLI JSON parse (t_dac8bf7e)
+
+- **Files**: new `src/core/brain/payload-json.ts` (strip-and-note parser: plain parse first; on failure strip one leading `<think>...</think>` block — fenced-unwrap per the `llm-emulation.ts` precedent — retry, and return the payload plus the strip fact `{ kind, prefixChars }` or a named unparseable error; no I/O); modified `src/cli/brain/verbs/extract-signals.ts`, `src/cli/brain/verbs/design-note.ts`, `src/cli/brain/verbs/skill-proposals.ts`, `src/cli/brain/verbs/distill.ts` (route through the parser; `note` on the `{ ok: true }` envelope only when stripped; the still-invalid refusal names the strip attempt; exit codes unchanged). Tests: new `tests/core/brain/payload-json.test.ts`; modified `tests/cli/brain-extract-signals.test.ts`, `tests/cli/brain-design-note.test.ts`, `tests/cli/brain-skill-page-drafts.test.ts`, `tests/cli/brain-distill.test.ts` (each: a `<think>`-prefixed payload succeeds with `note` present and written items identical to the clean case; garbage still exits 1 with `ok: false`; clean JSON output is byte-identical — no `note` key).
+- **Acceptance**: `tests/core/brain/payload-json.test.ts` asserts the strip fires only after a failed plain parse, is always reported when it happens, never rescues genuinely malformed JSON (strip-then-still-invalid keeps the named error), and handles fenced and prose-prefixed shapes per the helper's contract. The verb tests must fail on pre-fix code (a think-prefixed payload exits 1 today with the generic message).
+- **Depends on**: none.
+
+## Lane F — ingest contract (card t_586d5d8b)
+
+### Task F1 — contract fingerprint and manifest field (t_586d5d8b, substrate)
+
+- **Files**: new `src/core/brain/ingest/contract.ts` (`EXTRACT_CONTRACT_VERSION` with the bump-guard comment in the `CHUNKER_VERSION` style; `computeExtractionContractFingerprint(vault)` = `sha256Hex(canonicalJson({ version, extractable sorted })).slice(0, 16)`; pure over vault config plus the constant); modified `src/core/brain/ingest/content-manifest.ts` (`SCHEMA_VERSION` to 2; `SUPPORTED_SCHEMA_VERSIONS`-style read accepting v1 with `contract` treated as changed; genuinely unknown versions still hard-refuse; manifest-wide `contract: { fingerprint }` persisted by `serializeManifest`, read by `readManifest`, written by `updateManifest` under the existing lock); modified `src/core/brain/source-cleanup.ts` (its direct manifest write round-trips the field). Tests: modified `tests/core/brain/ingest/content-manifest.test.ts` (contract field round-trip; v1 manifest reads and degrades to changed-contract; unknown version still refuses by name; cleanup preserves the field; fingerprint is stable across calls and changes when `extractable` changes or the version bumps); new `tests/core/brain/ingest/contract.test.ts` (purity: no clock, no absolute paths, no per-call options in the input).
+- **Acceptance**: the manifest test asserts a v1 fixture (no contract field) is accepted, every classification treats it as changed, and the next write lands as v2 with the fingerprint; the fingerprint tests must fail on pre-fix code (field and module do not exist).
+- **Depends on**: none.
+
+### Task F2 — planner comparison, plan-id folding, honest reporting (t_586d5d8b)
+
+- **Files**: modified `src/core/brain/ingest/batch-plan.ts` (compare fingerprints immediately after `readManifest`; on mismatch reclassify `unchanged` sources for reprocessing with a distinct typed reason token — "bytes changed" vs "contract changed"; plan-level `contractChanged` plus counts emitted conditionally); modified `src/core/brain/ingest/checkpoint.ts` (fold the fingerprint into `computePlanId`, `computeSessionImportId` style); modified `src/mcp/brain/ingest-tools.ts` (`serializeBatchPlan` conditional emission of the contract-changed fields); modified `src/cli/brain/verbs/batch-plan.ts` (surface the same reporting). Tests: modified `tests/core/brain/ingest/batch-plan.test.ts` (changed `extractable` reprocesses `unchanged` files under the distinct reason; identical contract skips as before), `tests/core/brain/ingest/batch-plan-extractable.test.ts` (gate interaction), `tests/core/brain/ingest/checkpoint.test.ts` (plan id changes when the contract changes; the old checkpoint is not consumed), `tests/core/brain/ingest/reconcile.test.ts` (gap report under a contract change), `tests/core/brain/ingest/ingest.test.ts` (integration: re-ingest after a contract change rewrites the summary page and the manifest as v2), `tests/cli/brain-batch-plan-reconcile.test.ts`, `tests/mcp/ingest-plan-format-reach.test.ts` (conditional wire emission — byte-identical when the contract is unchanged).
+- **Acceptance**: the batch-plan test asserts a contract change with identical bytes produces full reprocess plans carrying the contract-changed reason, and an unchanged contract produces byte-identical plans to today; the checkpoint test asserts a stale checkpoint cannot resume-skip under a new contract. Must fail on pre-fix code (no comparison, no fold).
+- **Depends on**: F1.
diff --git a/docs/brainstorm/trust-surface-hardening/variants.md b/docs/brainstorm/trust-surface-hardening/variants.md
new file mode 100644
index 00000000..f86392db
--- /dev/null
+++ b/docs/brainstorm/trust-surface-hardening/variants.md
@@ -0,0 +1,40 @@
+# Trust-Surface Hardening — variants
+
+The three variants below are reproduced verbatim from the consultant reply stored at `cli-output/consultant.md` (see the provenance note at the end for why that file and not `claude.md`).
+
+### Variant 1: Substrate-first consolidation (shared crypto and seal modules, reject-at-write)
+
+- **Approach**: Sequence the wave around two shared modules built before their consumers. First `src/core/brain/secrets/envelope.ts`: the scrypt KDF (`scryptSync`/`timingSafeEqual` from node:crypto, explicit `N/r/p/maxmem`, random salt, parameters recorded inside a versioned envelope, wrong-passphrase detected by the GCM tag), the wrapped-keyfile format that replaces the raw 32-byte keyfile on opt-in (card 1), and the bundle envelope of card 3; card 2 then routes through the same substrate's decrypt with a read-only resolve variant so `$secret:` resolution avoids the `resolveSecretForExec` writer side (last_used_at stamp plus custody audit). Second, lift `sealManifest`/`manifestVerifies` (`src/core/state/migrate.ts:186-194`) into `src/core/integrity/digest.ts` beside `sha256Hex`/`canonicalJson` so both adoption-plan seals (card 7) and the extraction-contract fingerprint (card 9) pass through one primitive. Cards 4 and 6 reject at write time - the composers refuse tag values failing the `src/core/tags.ts` rule and capture refuses an undeclared kind before `allocateAndCreate` - and cards 5 and 8 extend the existing response envelopes additively (`digest_count`/`divergent` on both single-session reads, a `note` key on the CLI `{ ok: true }` envelope).
+- **Trade-offs**:
+ - Pros: one spelling of the KDF and one of the seal matches the DRY posture `src/core/tags.ts:8-11` already demands of the tag rule; card 3 shares the KDF with card 1 by card statement, so the substrate is load-bearing rather than speculative; rejection-before-allocation reuses the existing typed-refusal shapes (`CaptureContractError`, `SchemaVocabularyError`) and the guard ordering `store.ts:119-124` already mandates.
+ - Cons: hard rejection on topic shape breaks live MCP/CLI feedback and any lane that writes `brain/topic/foo bar` today until callers slugify; rejecting capture kinds in vaults whose packs were authored before `brain-capture` existed needs a compatibility story for the Telegram lane; the up-front substrate couples the review and landing order of three otherwise independent secrets slices.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 2: Independent slices (detect-only governance, dedicated divergence surfaces)
+
+- **Approach**: Ship nine vertical slices with no module extracted first: the wrapped keyfile, the bundles and the resolver each carry their own KDF/envelope code locally with convergence deferred, and cards 7 and 9 implement sealing in place. Cards 4 and 6 are detection-only: an opt-in `frontmatter-tags` hygiene detector registered through `HYGIENE_DETECTOR_IDS` (`src/core/brain/hygiene/types.ts:12-20`) and modeled on `detectTags`, plus a doctor finding for vaults whose declared `page_types` omit the kinds the build stamps; no composer or capture writer changes. Cards 5 and 8 add new dedicated surfaces - a session-summary divergences read and a payload-parse diagnostics output - leaving `brain_session_summary` get, the CLI get and the four parse sites byte-identical.
+- **Trade-offs**:
+ - Pros: zero write-path break risk - topics with spaces keep landing, Telegram captures keep flowing, every existing test pin survives untouched; each slice reviews, lands and reverts independently; no read-path consumer or test churn on the current envelopes.
+ - Cons: three private copies of envelope/KDF code is drift in exactly the layer where a mistake costs credentials, against the wave's own DRY constraint; detection-only leaves the trust surface documented rather than hardened - the silent sorted-last read at `session-summary.ts:179` stays silent on the primary surface and the agent must know to call the new one; two new surfaces cost command-manifest, help-text, census and MCP-parity work that additive keys avoid.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Forced sharing only, tiered enforcement, additive named keys
+
+- **Approach**: Share exactly what the cards force: one `src/core/brain/secrets/envelope.ts` KDF/wrapped-envelope module under cards 1 and 3 (card 3 shares the KDF with card 1 by statement), with card 2 as a separate resolver-plane slice that composes `parseSecretReference` with a read-oriented decrypt over the custody store and threads resolved literals into `EGRESS_REDACTION_OPTIONS`/`redactConfigMapping` so `redactKnownSecretValues` finally gains production callers; likewise one `sealWithDigest`/`digestVerifies` lift into `src/core/integrity/digest.ts` under cards 7 and 9. Enforcement is tiered by blast radius: card 4 rejects caller-controlled `extraTags` and slugify-or-rejects topic inside the composers (consuming the rule from `src/core/tags.ts`, never a copy), while card 6 fails open on absent config per the `readSchemaPackSource` substitution precedent (`schema-pack.ts:56`) and rejects an undeclared `kind` only when a pack explicitly declares `page_types`, with an opt-in hygiene detector as the companion for existing vaults; lock/unlock stays off MCP per the `brain_secrets` set/get refusal (admin-tools.ts:295-299). Cards 5 and 8 extend the existing envelopes additively with named tokens - `digest_count`, conditional `divergent` plus an id/hash list rather than full echoes to respect `MCP_PREVIEW_BUDGET`, a `summary-divergent`-style reason token in the `payload_mismatch`/`coverage-divergent` grammar, and a `note` key on the CLI envelope when the shared payload parser stripped a think block - and fold the pre-existing CLI serializer drift (missing `project`) into the same wave.
+- **Trade-offs**:
+ - Pros: the only centralized code is the two substrates the cards genuinely share, so review order stays slice-sized; rejection lands where the caller controls the input (extraTags) and where the vault made a declaration (page_types), matching the write-session validator's existing polarity (fail closed on declared-but-unknown at `validate.ts:181`, fail open on absent vocabulary) while detectors cover vaults that predate the declarations; additive named keys follow the conditional-key idiom, cannot trip the MCP output contract (the tool declares no outputSchema), and keep byte-identity when inactive.
+ - Cons: three enforcement polarities in one wave (reject-always on extraTags, reject-only-when-declared on capture kinds, detect-only companion) need careful documentation so operators can predict which writes refuse; the resolver's store-lock-on-config-paths question and card 3's honest `EGRESS_SITES` declaration (ciphertext defeats both `sharedRedactor` and `noVaultContent` as-is) remain open decisions inside otherwise-settled slices.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Recommended: Variant 3
+
+**Rationale**: It centralizes only the two substrates the cards force to be shared - card 3 shares its KDF with card 1 by statement, and cards 7 and 9 both reduce to `sha256Hex(canonicalJson(...))` over a canonical body - unlike Variant 1, which couples all three secrets slices up front, or Variant 2, which leaves three drifting copies of credential-critical code. Its tiered enforcement places fail-closed behavior exactly where the repo's own precedents sit (declared-vocabulary rejection with fail-open on absent config, caller-controlled-input rejection at the composers) and covers pre-existing vaults through detectors instead of breaking Telegram capture or live feedback. Additive named keys on existing envelopes are the established house grammar, preserve byte-identity when the features are inactive, and avoid Variant 2's split-surface problem where the primary single-session read stays silent.
+
+## Orchestrator decision
+
+**Picked: Variant 3** — the consultant's recommendation, accepted without override. The two substrates it centralizes are exactly the ones the cards force to be shared (the secrets envelope across cards 1 and 3; the digest seal across cards 7 and 9), its enforcement polarities sit on the repo's own precedents, and its additive named keys keep every inactive feature byte-identical. The full acceptance rationale is in `design.md` ("Chosen approach"); the tiered polarities are specified per write site in "Design decisions".
+
+**Provenance note.** This wave ran in host mode: the external CLI consultant was replaced by an in-session subagent running against the same prompt (`cli-output/prompt.md`), so the reply is stored at `cli-output/consultant.md` rather than `claude.md`. The variants above are that reply, verbatim.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index fd52a8da..71e472be 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -16,7 +16,7 @@ o2b-mcp Console-script alias for `o2b mcp`, forwards all f
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 secrets list|status Inspect $secret:NAME references without printing values; `--vault <path>` joins that vault's custody store (names and availability only, never a decrypt; without the flag both commands are byte-identical to the store-less report)
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)
@@ -474,7 +474,7 @@ o2b brain idea-lineage Trace how a derived artifact was reached: observat
o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>] [--apply] [--confirm] [--expect N] [--strict] [--json] - note-FILE lifecycle; source and destination both go through the create-note path envelope. Dry-run without --apply; delete also needs --confirm. A relocation rewrites inbound [[wikilinks]] vault-wide (both path spellings always, the bare basename only when exactly one note carries it) and the receipt names how stale the search index still is; delete rewrites nothing, reports the references it strands, and returns a recoverability verdict saying the archive it took does not cover a note outside Brain/
o2b brain scaffold-stub list [--limit N] [--json] | write <target> [--path <p>] [--source <s>...] [--if-exists refuse|skip] [--apply] [--json] - unresolved wikilink targets. list reads them from the search index and refuses with a state and a next_command when that index is missing or only partially resolved, never printing an empty list for an index nobody finished resolving; write materialises a stub whose title is the target and whose body links back to its sources. A target that already resolves, or names several notes, is refused
o2b brain note-history Decompose a note's git history into episodic phases split on a commit-time gap (since v1.11.0)
-o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
+o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence; --approval-digest <hex> seals the plan - non-interactive --apply must carry the digest a prior --dry-run printed and then lands exactly the approved plan or nothing (a stale digest refuses with a re-run remedy), an entry whose name cannot land a parseable tag skips as a named row instead of aborting, and a digest paired with --dry-run refuses
```
### Time axis (since v0.10.18)
@@ -640,7 +640,7 @@ o2b brain label <path> <dimension>=<value> | --remove <dimension>
o2b brain label <path> --suggest [--dimensions a,b] - read-only advisory suggestions from the optional `labels` decision-model use; never assigns; `available: false` while the use is off; a private note is refused (see docs/decision-models/labels.md)
o2b brain attr <path> <field>=<value> | --remove <field> | --show - per-type attribute fields; an undeclared field error lists the declared fields WITH descriptions
o2b brain tiers check | restore <path> [--field F] --apply | accept <path> [--field F] - staged repair for identity-tier frontmatter hand-edits
-o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> - capability-gated custody; the value enters via stdin, never argv
+o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> | lock | unlock [--passphrase-from-env SRC] | export --out FILE [--passphrase-from-env SRC] | import FILE [--replace] [--passphrase-from-env SRC] [--vault <path>] - capability-gated custody; the value enters via stdin, never argv. `unlock` wraps the keyfile under a passphrase (read from stdin or --passphrase-from-env, never argv) and holds the key for this process only; `lock` clears that holder; `export` writes every entry as one passphrase-encrypted bundle to `--out` (values re-encrypted, names and env-var mappings travel in the clear past the shared egress redactor); `import` restores a bundle, refusing names the store already holds unless --replace
o2b brain maintenance run [--force] [--retry <task|custom:name>] [--force-cost] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream, reindex, bridges, clusters and declared custom tasks
o2b brain maintenance run --cron-template [--interval N] [--format cron|systemd] [--window H-H --tz ZONE] - print the cron or systemd recipe that schedules the lane (default interval 1h); prints and installs nothing
```
@@ -699,7 +699,7 @@ Supersession is now consumer-aware: context packs inject only the tip of a super
### Source pipeline integrity and operator tooling (since v1.34.0)
```text
-o2b brain batch-plan gains --src-subpath <rel> (scope a monorepo ingest to one subtree; escaping the source root is a typed error, and one crossing a submodule or nested checkout is refused outright; a subpath below a directory the repository itself ignores plans nothing and says so as an ignore warning), --exclude <pattern> (gitignore-style patterns through the shared ignore engine), and --reconcile (diff the plan's dispatched set against checkpoint completions and name every silently-lost source; a complete plan reports an explicit empty gap)
+o2b brain batch-plan gains --src-subpath <rel> (scope a monorepo ingest to one subtree; escaping the source root is a typed error, and one crossing a submodule or nested checkout is refused outright; a subpath below a directory the repository itself ignores plans nothing and says so as an ignore warning), --exclude <pattern> (gitignore-style patterns through the shared ignore engine), and --reconcile (diff the plan's dispatched set against checkpoint completions and name every silently-lost source; a complete plan reports an explicit empty gap); a changed extraction contract is reported rather than absorbed - byte-identical sources reprocess once with the distinct contract-changed status (contract_changed and contract_changed_files keys under --json, an info line in text), a v1 manifest with no recorded contract included
o2b brain pre-extract <file> [--json] - deterministic no-LLM code-structure extraction (classes, functions, imports, inheritance edges, and in .tsx/.jsx files uses edges to the components opening tags name, as JSON entity/edge seeds) for TypeScript, JavaScript, and Python, and Terraform (.tf, .tfvars) block seeds in address syntax (resource, data, module, variable, output, provider, locals) with depends_on and references edges and a module source as an imports seed; .tfvars yields variable names, never values; credentials in any import specifier are redacted (the userinfo of an http(s), git+http(s) or git:: specifier, a user:password pair or a bare token, and the value of a named credential query parameter such as sshkey, token or an S3 or GCS signing key, also on a specifier that is not a URL such as git@host:org/repo?sshkey=...; a conventional login such as ssh://git@ is kept, and a credential in a path segment, a fragment or an unnamed query parameter is not recognised); a specifier longer than 2048 characters is carried as the redaction placeholder; on the ingest path a source larger than 1 MiB is skipped with a reason naming the limit; relative imports are bound to files (resolved_to) only on the ingest path, which has the content manifest; unknown extensions report extracted:false with a reason, never an empty success. Terraform limits, by name: .hcl and .tf.json files, attribute values, nested blocks (lifecycle, dynamic, provisioner, connection) as entities, depends_on expressions, citations inside heredocs or template files, for_each and count expansion, moved, import, check and removed blocks, terraform {} settings and required_providers, resolution of a local module source to a directory, and a block header split across lines are not read, the items of a multi-line depends_on list are read as ordinary citations and seeded as references, not depends_on, and quotes inside an interpolation (`"${f("x")}"`) are not tracked, which can end it early and drop citations later on that line
o2b brain scan-citations [--strict] - promote structural [Source: <name>, YYYY-MM-DD] markers in note prose into dated source-citation events on the temporal timeline; dedup on normalized name + date, malformed markers are reported and skipped (--strict exits nonzero on them)
o2b brain doctor gains --repair (preview targeted fixes for doctor-detected classes: dangling workrun checkpoints, dead evidence links; dry-run default) and --repair --apply (perform the fixes idempotently, one typed doctor-repair event each); unfixable classes are reported needs-review; plain doctor and --strict stay read-only
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 5f8062bc..bb01f017 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -1603,6 +1603,8 @@ Until now almost nothing about a write into the Brain was declared: any frontmat
**Custody, not just redaction.** Secrets live as per-value AES-256-GCM ciphertext beside a 0600 keyfile in the vault-local state dir (`.open-second-brain/secrets/`), never returned by any surface. That directory carries a `.gitignore` so a vault that is a git repository never commits it; Syncthing does not read `.gitignore`, so a vault inside a Syncthing folder needs `/<path-to-vault>/.open-second-brain/secrets` in the folder's root `.stignore` - `o2b brain doctor` (`secrets-sync-exposed`) and `secret set` warn with the exact line when it is missing, and never edit `.stignore` themselves. An agent uses a credential by running an allowlisted command with the value injected into the subprocess env; captured output comes back with the value scrubbed as a known literal, the material enters only via the operator's stdin, and every operation lands a no-values audit record under `Brain/log/secret-custody/`. The threat model is stated honestly: this protects against context leakage, git exposure, and casual reads - sync exposure only once the syncer's own ignore list covers the directory - and not against root.
+**The keyfile can be wrapped under a passphrase.** `o2b brain secret unlock` verifies a passphrase (read from stdin or `--passphrase-from-env`, never argv) and - on a store whose keyfile is still raw - wraps the 32-byte key into a versioned scrypt envelope at the same path, then holds the unwrapped key in memory for that one process only; `lock` overwrites and drops it. There is no daemon: every other CLI invocation and the MCP server stay locked, and a key-bearing operation over a locked store refuses with a named error whose remedy is the unlock command (the refusal's prose carries no paths - the structured field does, for the surfaces allowed to name them). Every unlock and lock lands a no-values custody record. A credential reference, `$secret:NAME`, resolves store-first with environment fallback at the use sites that already name it (the exec allowlist, the embedding and rerank keys, the decision-model key, the Telegram capture token, the research keys); a locked store surfaces the named refusal rather than silently answering from the environment. `secret export` writes every entry as one passphrase-encrypted bundle to an operator-named file - the values re-encrypted under a key the passphrase derives, the names, env-var mappings and allowlists traveling in the clear past the shared egress redactor - and `secret import` decrypts and validates every entry (names, env-var mappings, allow patterns, all under the store's own rules) before writing anything. The honesty clause is the same for the keyfile envelope and for bundles: the passphrase is never persisted, logged or audited, and a lost one is unrecoverable - every stored value and every exported bundle stays unreadable forever, and nothing recovers them.
+
**Heavy work waits its turn.** The maintenance lane runs dream and reindex behind three gates: a tz-aware local-time window, a busy gate over recent recall telemetry, and an expiring SQLite lease in its own database so holding it never contends with the search index writer lock. Force bypasses the soft gates but never the lease, tasks run stale-first, and every attempt - including each gate refusal - lands in a bounded journal, because a lane you cannot audit is a lane you cannot trust.
## Link and recall intelligence (since v0.45.0)
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 932f28d1..e7e4a9a0 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.77.0",
+ "version": "1.78.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 99fe798b..7d7c26ca 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -3,6 +3,7 @@ var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
return this[key];
@@ -31,7 +32,38 @@ var __toESM = (mod, isNodeMode, target) => {
cache.set(mod, to);
return to;
};
+var __toCommonJS = (from) => {
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
+ if (entry)
+ return entry;
+ entry = __defProp({}, "__esModule", { value: true });
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (var key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(entry, key))
+ __defProp(entry, key, {
+ get: __accessProp.bind(from, key),
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
+ });
+ }
+ __moduleCache.set(from, entry);
+ return entry;
+};
+var __moduleCache;
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
+var __returnValue = (v) => v;
+function __exportSetter(name, newValue) {
+ this[name] = __returnValue.bind(null, newValue);
+}
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, {
+ get: all[name],
+ enumerable: true,
+ configurable: true,
+ set: __exportSetter.bind(all, name)
+ });
+};
+var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ createRequire(import.meta.url);
// node_modules/graceful-fs/polyfills.js
@@ -1554,16 +1586,6 @@ var require_proper_lockfile = __commonJS(function(exports, module) {
module.exports.checkSync = checkSync;
});
-// src/openclaw/index.ts
-import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-
-// src/core/config.ts
-var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
-import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
-import { createHmac, randomBytes } from "node:crypto";
-import { homedir as homedir2 } from "node:os";
-import { dirname as dirname2, isAbsolute, join as join3, resolve as resolve2 } from "node:path";
-
// src/core/fs-atomic.ts
import { isUtf8 } from "node:buffer";
import {
@@ -1579,8 +1601,6 @@ import {
writeSync
} from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
-var WINDOWS_TRANSIENT_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
-var WINDOWS_RENAME_RETRY_BUDGET_MS = 2000;
function sleepSync(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
@@ -1653,17 +1673,6 @@ function assertExpectedBefore(target, expected) {
if (!fileMatchesExpected(target, expected))
throw new FileDriftError(target);
}
-var FILE_DRIFT_CODE = "FILE_DRIFT";
-
-class FileDriftError extends Error {
- code = FILE_DRIFT_CODE;
- path;
- constructor(path) {
- super(`file changed since it was read: ${path}; the write was refused ` + "and the file left as it is. Re-read it and retry.");
- this.name = "FileDriftError";
- this.path = path;
- }
-}
function withTempFile(target, contents, commit, mode = 420) {
const dir = dirname(target);
mkdirSync(dir, { recursive: true });
@@ -1705,11 +1714,62 @@ function withTempFile(target, contents, commit, mode = 420) {
throw err;
}
}
+var WINDOWS_TRANSIENT_RENAME_CODES, WINDOWS_RENAME_RETRY_BUDGET_MS = 2000, FILE_DRIFT_CODE = "FILE_DRIFT", FileDriftError;
+var init_fs_atomic = __esm(() => {
+ WINDOWS_TRANSIENT_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
+ FileDriftError = class FileDriftError extends Error {
+ code = FILE_DRIFT_CODE;
+ path;
+ constructor(path) {
+ super(`file changed since it was read: ${path}; the write was refused ` + "and the file left as it is. Re-read it and retry.");
+ this.name = "FileDriftError";
+ this.path = path;
+ }
+ };
+});
+
+// src/core/secret-ref.ts
+function parseSecretReference(value) {
+ if (typeof value !== "string")
+ return null;
+ const match = SECRET_REFERENCE_RE.exec(value.trim());
+ if (!match)
+ return null;
+ return Object.freeze({ raw: value.trim(), name: match[1] });
+}
+function isSecretReferenceValue(value) {
+ return typeof value === "string" && value.trimStart().startsWith(REFERENCE_PREFIX);
+}
+function resolveSecretReference(value, provider = process.env) {
+ const ref = parseSecretReference(value);
+ if (!ref) {
+ throw new SecretReferenceError(`invalid secret reference: ${value}`, value);
+ }
+ const resolved = provider[ref.name];
+ if (!resolved) {
+ throw new SecretReferenceError(`missing secret provider value: ${ref.name}`, ref.name);
+ }
+ return resolved;
+}
+function sortedDistinctLiterals(values) {
+ return [...new Set(values)].filter((value) => value.length > 0).sort((a, b) => b.length - a.length);
+}
+var SecretReferenceError, SECRET_REFERENCE_RE, REFERENCE_PREFIX = "$secret:";
+var init_secret_ref = __esm(() => {
+ SecretReferenceError = class SecretReferenceError extends Error {
+ nameValue;
+ constructor(message, nameValue) {
+ super(message);
+ this.name = "SecretReferenceError";
+ this.nameValue = nameValue;
+ }
+ };
+ SECRET_REFERENCE_RE = /^\$secret:([A-Za-z_][A-Za-z0-9_]*)$/;
+});
// src/core/platform-dirs.ts
import { homedir } from "node:os";
import { join as join2, win32 } from "node:path";
-var APP_DIR_NAME = "open-second-brain";
function processDirsEnv() {
return { platform: process.platform, home: homedir(), env: process.env };
}
@@ -1722,18 +1782,6 @@ function nonEmpty(value) {
function windowsLocalAppData(source) {
return nonEmpty(source.env["LOCALAPPDATA"]) ?? win32.join(source.home, "AppData", "Local");
}
-var XDG_VARIABLE = Object.freeze({
- config: "XDG_CONFIG_HOME",
- data: "XDG_DATA_HOME",
- state: "XDG_STATE_HOME",
- cache: "XDG_CACHE_HOME"
-});
-var POSIX_DEFAULT = Object.freeze({
- config: [".config"],
- data: [".local", "share"],
- state: [".local", "state"],
- cache: [".cache"]
-});
function baseDir(kind, source) {
const xdg = nonEmpty(source.env[XDG_VARIABLE[kind]]);
if (xdg)
@@ -1745,9 +1793,28 @@ function baseDir(kind, source) {
function configBaseDir(source = processDirsEnv()) {
return baseDir("config", source);
}
+var APP_DIR_NAME = "open-second-brain", XDG_VARIABLE, POSIX_DEFAULT;
+var init_platform_dirs = __esm(() => {
+ XDG_VARIABLE = Object.freeze({
+ config: "XDG_CONFIG_HOME",
+ data: "XDG_DATA_HOME",
+ state: "XDG_STATE_HOME",
+ cache: "XDG_CACHE_HOME"
+ });
+ POSIX_DEFAULT = Object.freeze({
+ config: [".config"],
+ data: [".local", "share"],
+ state: [".local", "state"],
+ cache: [".cache"]
+ });
+});
// src/core/brain/portability/profiles.ts
-var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
+var import_proper_lockfile;
+var init_profiles = __esm(() => {
+ init_fs_atomic();
+ import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
+});
// src/core/fs-utils.ts
import { statSync } from "node:fs";
@@ -1765,36 +1832,43 @@ function stem(filename) {
const dot = filename.lastIndexOf(".");
return dot > 0 ? filename.slice(0, dot) : filename;
}
+var init_fs_utils = () => {};
+
+// src/core/brain/portability/pointer.ts
+var init_pointer = __esm(() => {
+ init_fs_atomic();
+ init_fs_utils();
+});
+
+// src/core/brain/wikilink.ts
+var init_wikilink = () => {};
// src/core/brain/link-graph/format-wikilink.ts
-var WIKI_LINK_FORMATS = Object.freeze([
- "preserve",
- "full",
- "short"
-]);
-var SUFFIX_INDEX_MEMO = new WeakMap;
+var WIKI_LINK_FORMATS, SUFFIX_INDEX_MEMO;
+var init_format_wikilink = __esm(() => {
+ init_wikilink();
+ WIKI_LINK_FORMATS = Object.freeze([
+ "preserve",
+ "full",
+ "short"
+ ]);
+ SUFFIX_INDEX_MEMO = new WeakMap;
+});
// src/core/config.ts
-var CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `
-`, "\r"];
-var UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze([]);
-
-class UnsupportedPlatformError extends Error {
- platform;
- constructor(platform) {
- super(`open-second-brain has no configuration layout for platform '${platform}': ` + "this build does not know where per-user configuration lives there. Set " + "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " + "to a configuration root, to choose the location yourself.");
- this.name = "UnsupportedPlatformError";
- this.platform = platform;
- }
+import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
+import { createHmac, randomBytes } from "node:crypto";
+import { homedir as homedir2 } from "node:os";
+import { dirname as dirname2, isAbsolute, join as join3, resolve as resolve2 } from "node:path";
+function installNamedSecretResolver(resolver) {
+ namedSecretResolver = resolver;
}
-
-class ConfigReadError extends Error {
- path;
- constructor(path, reason) {
- super(`failed to read plugin config ${path}: ${reason}. The file is present, so its ` + "settings are NOT in force and are not read as absent; make it readable " + `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`);
- this.name = "ConfigReadError";
- this.path = path;
+function resolveThroughNamedSecretResolver(vault, reference) {
+ const resolver = namedSecretResolver;
+ if (resolver === undefined) {
+ throw new SecretReferenceError("no named-secret resolver is installed in this process; the $secret: reference " + "cannot be resolved against the vault's custody store", reference);
}
+ return resolver.resolveNamedSecret(vault, reference);
}
function resolveDefaultConfigPath(source) {
const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
@@ -1884,7 +1958,6 @@ function setConfigValue(key, value, path) {
atomicWriteFileSync(resolved, body);
return resolved;
}
-var UNCONFIGURED_AGENT_NAME = "agent";
function resolveAgentName(configPath) {
const env = process.env["VAULT_AGENT_NAME"];
if (env)
@@ -1895,23 +1968,70 @@ function resolveAgentName(configPath) {
return value;
return UNCONFIGURED_AGENT_NAME;
}
+function isValidDeviceId(value) {
+ return DEVICE_ID_RE.test(value) && !value.startsWith("sync-conflict");
+}
+function resolveDeviceId(configPath) {
+ const env = process.env["O2B_DEVICE_ID"];
+ if (env !== undefined && (env === "" || isValidDeviceId(env)))
+ return env;
+ const resolved = configPath ?? defaultConfigPath();
+ const read = () => {
+ const value = discoverConfig(resolved).data["device_id"];
+ return value && isValidDeviceId(value) ? value : null;
+ };
+ const existing = read();
+ if (existing !== null)
+ return existing;
+ const dir = dirname2(resolved);
+ mkdirSync2(dir, { recursive: true });
+ let release;
+ try {
+ for (let attempt = 0;attempt < 10; attempt++) {
+ try {
+ release = import_proper_lockfile2.default.lockSync(dir, { stale: 1e4, realpath: false });
+ break;
+ } catch (err) {
+ if (err.code !== "ELOCKED")
+ break;
+ sleepSync(50);
+ }
+ }
+ const won = read();
+ if (won !== null)
+ return won;
+ const generated = randomBytes(4).toString("hex");
+ setConfigValue("device_id", generated, resolved);
+ return generated;
+ } finally {
+ release?.();
+ }
+}
function resolveExposeHostPaths(configPath) {
return resolveConfigFlag("OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS", "expose_host_paths", configPath);
}
-var INSTALLATION_SECRET_CONFIG_KEY = "installation_secret";
-var INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET";
-var INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;
function isValidInstallationSecret(value) {
return INSTALLATION_SECRET_RE.test(value);
}
-function resolveInstallationSecret(configPath) {
+function resolveInstallationSecret(configPath, secretsVault) {
const env = process.env[INSTALLATION_SECRET_ENV_KEY];
if (env !== undefined && isValidInstallationSecret(env))
return env;
const resolved = configPath ?? defaultConfigPath();
const read = () => {
- const value = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
- return value && isValidInstallationSecret(value) ? value : null;
+ const raw = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
+ if (isSecretReferenceValue(raw)) {
+ const reference = String(raw).trim();
+ if (secretsVault === undefined) {
+ throw new SecretReferenceError("installation_secret is a $secret: reference but no vault was passed to resolve " + "it against; pass the vault (or set O2B_INSTALLATION_SECRET to a 32-hex key)", reference);
+ }
+ const resolvedValue = resolveThroughNamedSecretResolver(secretsVault, reference);
+ if (!isValidInstallationSecret(resolvedValue)) {
+ throw new SecretReferenceError("installation_secret is a $secret: reference that resolves to a value which is " + "not a 32-hex installation key; fix the stored value - the reference in the " + "device config is never overwritten", reference);
+ }
+ return resolvedValue;
+ }
+ return raw && isValidInstallationSecret(raw) ? raw : null;
};
const existing = read();
if (existing !== null)
@@ -1940,10 +2060,8 @@ function resolveInstallationSecret(configPath) {
release?.();
}
}
-var VAULT_STORE_REF_PREFIX = "vault://";
-var VAULT_STORE_REF_HEX_LEN = 32;
function vaultStoreReference(vaultPath, configPath) {
- const key = resolveInstallationSecret(configPath);
+ const key = resolveInstallationSecret(configPath, vaultPath);
const digest = createHmac("sha256", key).update(resolve2(vaultPath)).digest("hex").slice(0, VAULT_STORE_REF_HEX_LEN);
return `${VAULT_STORE_REF_PREFIX}${digest}`;
}
@@ -1960,8 +2078,6 @@ function resolveConfigFlag(envKey, configKey, configPath) {
function isFlagOn(raw) {
return raw === "true" || raw === "1";
}
-var PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";
-var PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";
function resolvePartnerCodegraphDisabled(configPath) {
return resolveConfigFlag(PARTNER_CODEGRAPH_DISABLED_ENV, PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY, configPath);
}
@@ -1974,57 +2090,42 @@ function expandTilde(p, platform = process.platform, home = homedir2()) {
return join3(home, p.slice(2));
return p;
}
+var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";
+var init_config = __esm(() => {
+ init_fs_atomic();
+ init_secret_ref();
+ init_platform_dirs();
+ init_profiles();
+ init_pointer();
+ init_format_wikilink();
+ import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
+ CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `
+`, "\r"];
+ UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze([]);
+ UnsupportedPlatformError = class UnsupportedPlatformError extends Error {
+ platform;
+ constructor(platform) {
+ super(`open-second-brain has no configuration layout for platform '${platform}': ` + "this build does not know where per-user configuration lives there. Set " + "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " + "to a configuration root, to choose the location yourself.");
+ this.name = "UnsupportedPlatformError";
+ this.platform = platform;
+ }
+ };
+ ConfigReadError = class ConfigReadError extends Error {
+ path;
+ constructor(path, reason) {
+ super(`failed to read plugin config ${path}: ${reason}. The file is present, so its ` + "settings are NOT in force and are not read as absent; make it readable " + `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`);
+ this.name = "ConfigReadError";
+ this.path = path;
+ }
+ };
+ DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
+ INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;
+});
// src/core/redactor.ts
-var REDACTION_PLACEHOLDER = "***REDACTED***";
-var PLACEHOLDER = REDACTION_PLACEHOLDER;
-var PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
-var MAX_REDACTOR_INPUT = 1024 * 1024;
-var SCAN_TRUNCATED_SENTINEL = "***SCAN_TRUNCATED***";
-var SCAN_TRUNCATED_MARKER = `
-
-${SCAN_TRUNCATED_SENTINEL} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` + `This payload was only partially scanned — treat it as unverified and inspect the raw source before sharing.]
-`;
-var PRIVATE_OPEN_TAG_RE = /<private\b[^<>]*(?:>|(?=<)|$)/gi;
-var PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
-var SECRET_KEYS = [
- "api_key",
- "token",
- "access_token",
- "refresh_token",
- "bearer",
- "secret",
- "client_secret",
- "authorization",
- "private_key",
- "password",
- "passwd",
- "pwd",
- "credential",
- "credentials",
- "session_token"
-];
-var KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");
-var SECRET_KEY_NAME_FRAGMENTS = ["key"];
-var SECRET_KEY_NAME_RE = new RegExp(`(?:${KEY_PATTERN}|${SECRET_KEY_NAME_FRAGMENTS.join("|")})`, "i");
function isSecretKeyName(name) {
return typeof name === "string" && SECRET_KEY_NAME_RE.test(name);
}
-var ENV_RE = new RegExp(`(?<![A-Za-z0-9])(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
-var COLON_VALUE_RE = new RegExp(`(?<!")\\b(${KEY_PATTERN})([ \\t]*:[ \\t]*)("[^"]*"|'[^']*'|[^\\r\\n]+)`, "gi");
-var YAML_SECRET_BLOCK_RE = new RegExp(`^([ \\t]*)(${KEY_PATTERN})[ \\t]*:[ \\t]*(?:[|>][+-]?\\d{0,2})?[ \\t]*\\r?\\n` + "(?:\\1[ \\t]+[^\\r\\n]*\\r?\\n?)+", "gim");
-var JSON_ENTRY_RE = new RegExp(`("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`, "gi");
-var BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
-var JWT_RE = /\b(?:eyJ|eyA|ewo|ew0|ewk)[A-Za-z0-9_-]{9,65533}(?:\.[A-Za-z0-9_-]{4,65536}){2}(?![A-Za-z0-9_-])/g;
-var IPV4_OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
-var IPV4 = `${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}`;
-var BASIC_AUTH_URL_RE = /\b([a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/)([^\s/:@]{0,256}):(?!\d{1,5}\/)([^\s@]{1,4096})@/g;
-var IPV4_PORT_RE = new RegExp(`\\b${IPV4}:\\d{1,5}\\b`, "g");
-var FQDN_PORT_SOURCE_EXTS = "js|ts|tsx|jsx|py|json|rs|go|java|rb|php|c|cc|cpp|cxx|h|hpp|css|scss|sass|less|" + "html|htm|xml|yaml|yml|toml|ini|cfg|md|markdown|sh|bash|sql|vue|svelte|gradle|" + "kt|swift|scala|clj|ex|exs|erl|elm|dart|lua|pl|pm|r|jl|tf|lock|map|txt|csv|log";
-var FQDN_PORT_RE = new RegExp("\\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+(?!(" + FQDN_PORT_SOURCE_EXTS + "):\\d)[a-zA-Z]{2,63}:\\d{1,5}\\b", "g");
-var INTERNAL_HOST_RE = /\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:internal|intranet|localdomain|local|lan|corp|home)\b/gi;
-var IPV6_RE = new RegExp("(?<![\\w:.])(?:" + "(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}" + "|" + "(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}::(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{0,4}" + "|" + "::(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}" + ")(?![\\w:.])", "g");
-var IPV4_BARE_RE = new RegExp(`(?<![\\w.])${IPV4}(?![\\w.])`, "g");
function isPrivateOrReservedIPv4(ip) {
const octets = ip.split(".");
const a = Number.parseInt(octets[0] ?? "", 10);
@@ -2053,60 +2154,21 @@ function isPrivateOrReservedIPv6(ip) {
return true;
return false;
}
-var VENDOR_TOKEN_RE = new RegExp([
- "\\b(?:sk|rk|pk)[-_][A-Za-z0-9._-]{3,200}",
- "\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{6,255}",
- "\\bgithub_pat_[A-Za-z0-9_]{6,255}",
- "\\bxox[baprs]-[A-Za-z0-9-]{6,200}",
- "\\bAKIA[0-9A-Z]{16}\\b",
- "\\bAIza[0-9A-Za-z._-]{10,100}",
- "\\bglpat-[A-Za-z0-9_-]{6,100}"
-].join("|"), "g");
-var HIGH_ENTROPY_TOKEN_RE = /\b(?=[A-Za-z0-9_-]{24,200}\b)(?=[A-Za-z0-9_-]{0,199}[A-Za-z])(?=[A-Za-z0-9_-]{0,199}\d)[A-Za-z0-9_-]{24,200}\b/g;
-var CONTENT_ADDRESS_RE = /^[0-9a-fA-F]+(?:-[0-9a-fA-F]+)*$/;
function isContentAddress(run) {
return CONTENT_ADDRESS_RE.test(run);
}
-var SIGNAL_ID_RE = /^sig-\d{4}-\d{2}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/;
function isSignalId(run) {
return SIGNAL_ID_RE.test(run);
}
function isPreservedIdentifier(run) {
return isContentAddress(run) || isSignalId(run);
}
-var BASE64_SECRET_RE = new RegExp("(?<![A-Za-z0-9+/=])" + "(?=[A-Za-z0-9+/=]{32,64}(?![A-Za-z0-9+/=]))" + "(?=[A-Za-z0-9+/=]{0,63}[a-z])" + "(?=[A-Za-z0-9+/=]{0,63}[A-Z])" + "(?=[A-Za-z0-9+/=]{0,63}\\d)" + "(?=[A-Za-z0-9+/=]{0,63}[+/=])" + "[A-Za-z0-9+=][A-Za-z0-9+/=]{30,62}[A-Za-z0-9+=]", "g");
function redactBareTokens(text) {
return text.replace(VENDOR_TOKEN_RE, PLACEHOLDER).replace(BASE64_SECRET_RE, PLACEHOLDER).replace(HIGH_ENTROPY_TOKEN_RE, (run) => isPreservedIdentifier(run) ? run : PLACEHOLDER);
}
function redactUrlCredentials(text) {
return text.replace(BASIC_AUTH_URL_RE, (_m, scheme) => `${scheme}${PLACEHOLDER}@`);
}
-var CREDENTIAL_QUERY_KEYS = Object.freeze([
- "sshkey",
- "token",
- "access_token",
- "password",
- "secret",
- "signature",
- "sig",
- "key",
- "aws_access_key_id",
- "aws_access_key_secret",
- "aws_secret_access_key",
- "aws_access_token",
- "x-amz-signature",
- "x-amz-credential",
- "x-amz-security-token",
- "x-goog-signature",
- "x-goog-credential"
-]);
-var CREDENTIAL_QUERY_KEY_SET = new Set(CREDENTIAL_QUERY_KEYS);
-var TOKEN_USERINFO_SCHEMES = new Set([
- "http:",
- "https:",
- "git+http:",
- "git+https:"
-]);
function redactInfraTopology(text) {
let out = redactUrlCredentials(text);
out = out.replace(IPV4_PORT_RE, PLACEHOLDER);
@@ -2116,11 +2178,6 @@ function redactInfraTopology(text) {
out = out.replace(IPV4_BARE_RE, (match) => isPrivateOrReservedIPv4(match) ? match : PLACEHOLDER);
return out;
}
-var PLACEHOLDER_PATTERN = PLACEHOLDER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-var FRONTMATTER_BLOCK_RE = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;
-var FRONTMATTER_SCALAR_RE = new RegExp(`^([ \\t]*[^\\s#][^:\\r\\n]*:[ \\t]*)(${PLACEHOLDER_PATTERN}[^\\r\\n]*)$`, "gm");
-var FRONTMATTER_ITEM_RE = new RegExp(`^([ \\t]*-[ \\t]+)(${PLACEHOLDER_PATTERN}[^\\r\\n]*)$`, "gm");
-var FRONTMATTER_FLOW_ITEM_RE = new RegExp(`([[{,][ \\t]*)(${PLACEHOLDER_PATTERN})(?=[ \\t]*[,\\]}])`, "g");
function quoteYamlScalar(value) {
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
}
@@ -2225,11 +2282,12 @@ function scanRawOutput(text, opts = {}) {
out = quoteRedactedFrontmatter(out);
return { text: out, truncated };
}
-var IDENTIFIER_KEY_RE = /(^|[_-])(id|ids|uuid|uuids|guid|path|paths|slug|slugs|filename|filenames|basename)$/i;
+function redactRawOutput(text, opts = {}) {
+ return scanRawOutput(text, opts).text;
+}
function isIdentifierKeyName(name) {
return typeof name === "string" && IDENTIFIER_KEY_RE.test(name);
}
-var PATH_ANCHOR_RE = /^(?:[/\\]|~[/\\]|\.{1,2}[/\\]|[A-Za-z]:[/\\])/;
function isPathLikeValue(value) {
if (value.length === 0 || value.length > 4096)
return false;
@@ -2239,7 +2297,6 @@ function isPathLikeValue(value) {
return false;
return PATH_ANCHOR_RE.test(value) || !/\s/.test(value);
}
-var VENDOR_TOKEN_TEST_RE = new RegExp(VENDOR_TOKEN_RE.source);
function identifierCarriesSecret(value) {
return VENDOR_TOKEN_TEST_RE.test(value);
}
@@ -2258,7 +2315,6 @@ function keyNameCarriesSecret(name) {
function foreignIdentifierCarriesSecret(value) {
return carriesBareCredential(value);
}
-var MAX_REPORTED_IDENTIFIERS = 12;
function isPlainContainer(value) {
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
@@ -2338,143 +2394,1491 @@ function redactStructured(input, opts = {}) {
secretIdentifiers: Object.freeze([...secretIdentifiers].toSorted())
};
}
+var REDACTION_PLACEHOLDER = "***REDACTED***", PLACEHOLDER, PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***", MAX_REDACTOR_INPUT, SCAN_TRUNCATED_SENTINEL = "***SCAN_TRUNCATED***", SCAN_TRUNCATED_MARKER, PRIVATE_OPEN_TAG_RE, PRIVATE_CLOSE_TAG_RE, SECRET_KEYS, KEY_PATTERN, SECRET_KEY_NAME_FRAGMENTS, SECRET_KEY_NAME_RE, ENV_RE, COLON_VALUE_RE, YAML_SECRET_BLOCK_RE, JSON_ENTRY_RE, BEARER_RE, JWT_RE, IPV4_OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)", IPV4, BASIC_AUTH_URL_RE, IPV4_PORT_RE, FQDN_PORT_SOURCE_EXTS, FQDN_PORT_RE, INTERNAL_HOST_RE, IPV6_RE, IPV4_BARE_RE, VENDOR_TOKEN_RE, HIGH_ENTROPY_TOKEN_RE, CONTENT_ADDRESS_RE, SIGNAL_ID_RE, BASE64_SECRET_RE, CREDENTIAL_QUERY_KEYS, CREDENTIAL_QUERY_KEY_SET, TOKEN_USERINFO_SCHEMES, PLACEHOLDER_PATTERN, FRONTMATTER_BLOCK_RE, FRONTMATTER_SCALAR_RE, FRONTMATTER_ITEM_RE, FRONTMATTER_FLOW_ITEM_RE, IDENTIFIER_KEY_RE, PATH_ANCHOR_RE, VENDOR_TOKEN_TEST_RE, MAX_REPORTED_IDENTIFIERS = 12;
+var init_redactor = __esm(() => {
+ PLACEHOLDER = REDACTION_PLACEHOLDER;
+ MAX_REDACTOR_INPUT = 1024 * 1024;
+ SCAN_TRUNCATED_MARKER = `
-// src/core/egress/registry.ts
-var EGRESS_REDACTION = Object.freeze({
- sharedRedactor: "shared_redactor",
- noVaultContent: "no_vault_content",
- unscannedNetworkPayload: "unscanned_network_payload"
+${SCAN_TRUNCATED_SENTINEL} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` + `This payload was only partially scanned — treat it as unverified and inspect the raw source before sharing.]
+`;
+ PRIVATE_OPEN_TAG_RE = /<private\b[^<>]*(?:>|(?=<)|$)/gi;
+ PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
+ SECRET_KEYS = [
+ "api_key",
+ "token",
+ "access_token",
+ "refresh_token",
+ "bearer",
+ "secret",
+ "client_secret",
+ "authorization",
+ "private_key",
+ "password",
+ "passwd",
+ "pwd",
+ "credential",
+ "credentials",
+ "session_token"
+ ];
+ KEY_PATTERN = SECRET_KEYS.map((k) => k.replace(/[-_]/g, "[-_]?")).join("|");
+ SECRET_KEY_NAME_FRAGMENTS = ["key"];
+ SECRET_KEY_NAME_RE = new RegExp(`(?:${KEY_PATTERN}|${SECRET_KEY_NAME_FRAGMENTS.join("|")})`, "i");
+ ENV_RE = new RegExp(`(?<![A-Za-z0-9])(${KEY_PATTERN})(\\s*=\\s*)([^\\s\\r\\n]+)`, "gi");
+ COLON_VALUE_RE = new RegExp(`(?<!")\\b(${KEY_PATTERN})([ \\t]*:[ \\t]*)("[^"]*"|'[^']*'|[^\\r\\n]+)`, "gi");
+ YAML_SECRET_BLOCK_RE = new RegExp(`^([ \\t]*)(${KEY_PATTERN})[ \\t]*:[ \\t]*(?:[|>][+-]?\\d{0,2})?[ \\t]*\\r?\\n` + "(?:\\1[ \\t]+[^\\r\\n]*\\r?\\n?)+", "gim");
+ JSON_ENTRY_RE = new RegExp(`("(?:${KEY_PATTERN})"\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"|true|false|null|-?\\d+(?:\\.\\d+)?)`, "gi");
+ BEARER_RE = /\b(Bearer\s+)([A-Za-z0-9._\-+/=]+)/gi;
+ JWT_RE = /\b(?:eyJ|eyA|ewo|ew0|ewk)[A-Za-z0-9_-]{9,65533}(?:\.[A-Za-z0-9_-]{4,65536}){2}(?![A-Za-z0-9_-])/g;
+ IPV4 = `${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}`;
+ BASIC_AUTH_URL_RE = /\b([a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/)([^\s/:@]{0,256}):(?!\d{1,5}\/)([^\s@]{1,4096})@/g;
+ IPV4_PORT_RE = new RegExp(`\\b${IPV4}:\\d{1,5}\\b`, "g");
+ FQDN_PORT_SOURCE_EXTS = "js|ts|tsx|jsx|py|json|rs|go|java|rb|php|c|cc|cpp|cxx|h|hpp|css|scss|sass|less|" + "html|htm|xml|yaml|yml|toml|ini|cfg|md|markdown|sh|bash|sql|vue|svelte|gradle|" + "kt|swift|scala|clj|ex|exs|erl|elm|dart|lua|pl|pm|r|jl|tf|lock|map|txt|csv|log";
+ FQDN_PORT_RE = new RegExp("\\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+(?!(" + FQDN_PORT_SOURCE_EXTS + "):\\d)[a-zA-Z]{2,63}:\\d{1,5}\\b", "g");
+ INTERNAL_HOST_RE = /\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:internal|intranet|localdomain|local|lan|corp|home)\b/gi;
+ IPV6_RE = new RegExp("(?<![\\w:.])(?:" + "(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}" + "|" + "(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}::(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{0,4}" + "|" + "::(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}" + ")(?![\\w:.])", "g");
+ IPV4_BARE_RE = new RegExp(`(?<![\\w.])${IPV4}(?![\\w.])`, "g");
+ VENDOR_TOKEN_RE = new RegExp([
+ "\\b(?:sk|rk|pk)[-_][A-Za-z0-9._-]{3,200}",
+ "\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{6,255}",
+ "\\bgithub_pat_[A-Za-z0-9_]{6,255}",
+ "\\bxox[baprs]-[A-Za-z0-9-]{6,200}",
+ "\\bAKIA[0-9A-Z]{16}\\b",
+ "\\bAIza[0-9A-Za-z._-]{10,100}",
+ "\\bglpat-[A-Za-z0-9_-]{6,100}"
+ ].join("|"), "g");
+ HIGH_ENTROPY_TOKEN_RE = /\b(?=[A-Za-z0-9_-]{24,200}\b)(?=[A-Za-z0-9_-]{0,199}[A-Za-z])(?=[A-Za-z0-9_-]{0,199}\d)[A-Za-z0-9_-]{24,200}\b/g;
+ CONTENT_ADDRESS_RE = /^[0-9a-fA-F]+(?:-[0-9a-fA-F]+)*$/;
+ SIGNAL_ID_RE = /^sig-\d{4}-\d{2}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/;
+ BASE64_SECRET_RE = new RegExp("(?<![A-Za-z0-9+/=])" + "(?=[A-Za-z0-9+/=]{32,64}(?![A-Za-z0-9+/=]))" + "(?=[A-Za-z0-9+/=]{0,63}[a-z])" + "(?=[A-Za-z0-9+/=]{0,63}[A-Z])" + "(?=[A-Za-z0-9+/=]{0,63}\\d)" + "(?=[A-Za-z0-9+/=]{0,63}[+/=])" + "[A-Za-z0-9+=][A-Za-z0-9+/=]{30,62}[A-Za-z0-9+=]", "g");
+ CREDENTIAL_QUERY_KEYS = Object.freeze([
+ "sshkey",
+ "token",
+ "access_token",
+ "password",
+ "secret",
+ "signature",
+ "sig",
+ "key",
+ "aws_access_key_id",
+ "aws_access_key_secret",
+ "aws_secret_access_key",
+ "aws_access_token",
+ "x-amz-signature",
+ "x-amz-credential",
+ "x-amz-security-token",
+ "x-goog-signature",
+ "x-goog-credential"
+ ]);
+ CREDENTIAL_QUERY_KEY_SET = new Set(CREDENTIAL_QUERY_KEYS);
+ TOKEN_USERINFO_SCHEMES = new Set([
+ "http:",
+ "https:",
+ "git+http:",
+ "git+https:"
+ ]);
+ PLACEHOLDER_PATTERN = PLACEHOLDER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ FRONTMATTER_BLOCK_RE = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;
+ FRONTMATTER_SCALAR_RE = new RegExp(`^([ \\t]*[^\\s#][^:\\r\\n]*:[ \\t]*)(${PLACEHOLDER_PATTERN}[^\\r\\n]*)$`, "gm");
+ FRONTMATTER_ITEM_RE = new RegExp(`^([ \\t]*-[ \\t]+)(${PLACEHOLDER_PATTERN}[^\\r\\n]*)$`, "gm");
+ FRONTMATTER_FLOW_ITEM_RE = new RegExp(`([[{,][ \\t]*)(${PLACEHOLDER_PATTERN})(?=[ \\t]*[,\\]}])`, "g");
+ IDENTIFIER_KEY_RE = /(^|[_-])(id|ids|uuid|uuids|guid|path|paths|slug|slugs|filename|filenames|basename)$/i;
+ PATH_ANCHOR_RE = /^(?:[/\\]|~[/\\]|\.{1,2}[/\\]|[A-Za-z]:[/\\])/;
+ VENDOR_TOKEN_TEST_RE = new RegExp(VENDOR_TOKEN_RE.source);
});
-var EGRESS_REDACTION_STATUSES = Object.freeze([
- EGRESS_REDACTION.sharedRedactor,
- EGRESS_REDACTION.noVaultContent,
- EGRESS_REDACTION.unscannedNetworkPayload
-]);
-var R = EGRESS_REDACTION;
-var EGRESS_SITES = Object.freeze({
- "brain-bank-export": {
- id: "brain-bank-export",
- verb: "o2b brain bank-export",
- module: "src/cli/brain/verbs/bank-export.ts",
- redaction: R.sharedRedactor,
- reason: "the widest export in the tree: preferences, the page graph, page contracts and " + "the sources dashboard composed into one file. Redaction runs over the bundle " + "TREE and the JSON is serialised afterwards, so a note whose text happens to " + "contain a credential assignment cannot mangle the document's own quoting."
- },
- "brain-graph-export": {
- id: "brain-graph-export",
- verb: "o2b brain graph-export",
- module: "src/cli/brain/verbs/graph-export.ts",
- redaction: R.sharedRedactor,
- reason: "carries no page body, but does carry every page title, path and typed-relation " + "target - a credential pasted into a title left through here verbatim."
- },
- "brain-okf-export": {
- id: "brain-okf-export",
- verb: "o2b brain okf-export",
- module: "src/cli/brain/verbs/okf-export.ts",
- redaction: R.sharedRedactor,
- reason: "the only export that carries page bodies VERBATIM, which is its interchange " + "contract and also why it is the widest leak by volume. The manifest is redacted " + "as a tree and `okf.json` re-serialised from it; the markdown files are redacted " + "as text. A bundle whose secrets were removed is no longer a lossless round-trip " + "of the vault, and the verb says so rather than implying otherwise. What it does NOT " + "do is filter by label: a page carrying `private: true` in its frontmatter exports in " + "full, because the `<private>` region marker is this product's only content-derived " + "privacy primitive and these composers are content composers, not visibility filters."
- },
- "brain-export": {
- id: "brain-export",
- verb: "o2b brain export",
- module: "src/cli/brain/verbs/export.ts",
- redaction: R.sharedRedactor,
- reason: "preference principles are free text an agent wrote, and the llms-txt form is " + "meant to be pasted into a foreign prompt - the destination least likely to be " + "read before it is shared. One entry covers all three of the verb's formats " + "because the census keys on the MODULE and the destination is declared once, in " + "the verb: the JSON and transcript forms are redacted as TREES and serialised " + "afterwards, llms-txt as text. What proves each branch scans is a per-handler " + "check in the census, not the guard-call count - counting guards against " + "DESTINATIONS is an inequality, and this module declares one destination against " + "three guards, so a fourth handler that scanned nothing would satisfy it. The " + "transcript form is the widest of the three by far - whole recorded " + "conversations with whichever runtime wrote them, which is where a key pasted " + "into a prompt actually lives. Its records are guarded ONE AT A TIME, so a " + "single oversized turn cannot put a machine's whole corpus past the scan window, " + "and a refusal names the conversation rather than the run - by its basename, " + "except when the basename is itself the secret-shaped identifier, where it is " + "named by runtime and start instant instead. The transcript branch is also the " + "one caller that passes `foreignIdentifiers`, because its `session_id` and " + "`turn_id` were named by the harness that wrote the transcript rather than by " + "this vault, so the guard's vendor-prefix-only rule for identifiers - an " + "argument about ids this build constructs - does not cover them."
- },
- "config-export": {
- id: "config-export",
- verb: "o2b export-config",
- module: "src/cli/main.ts",
- redaction: R.sharedRedactor,
- reason: "the machine-config snapshot an operator hands to someone else when reporting a " + "problem. It used a private copy that matched five substrings against KEY NAMES " + "and never inspected a value, so a credential stored under a name that copy did " + "not recognise was written out in full."
- },
- "brain-continuity-export": {
- id: "brain-continuity-export",
- verb: "o2b brain continuity export",
- module: "src/cli/brain/verbs/continuity.ts",
- redaction: R.sharedRedactor,
- reason: "was declared as covered by its read model, which was wrong in both directions. " + "The upstream call redacts at WRITE time with the redactor's DEFAULT options, so " + "`redactTokens` and `redactUrlCredentials` were both off and a vendor key, a bare " + "high-entropy token and a `user:pass@host` URL all left through here verbatim - " + "the two flags the export boundary exists to turn on. Write-time coverage also " + "says nothing about a record already on disk or appended by another writer, since " + "the read model never re-scans. The verb now scans what it READ, which answers " + "both, and gains the truncation refusal the other five already had."
- },
- "brain-explorer-export": {
- id: "brain-explorer-export",
- verb: "o2b brain explorer --export",
- module: "src/cli/brain/verbs/explorer.ts",
- redaction: R.sharedRedactor,
- reason: "a self-contained HTML file with the whole rule graph embedded as JSON: every " + "preference and retired principle verbatim, plus each one's topic, scope and " + "provenance counts. It is the export most likely to be handed to a person rather " + "than a program - it opens in a browser - and it was the one export that never " + "scanned anything. Redaction runs over the graph TREE before the template " + "substitution, so a principle whose text contains a quote cannot disturb the " + "document. The label rule holds here too: a preference is not withheld for carrying " + "a `private` tag, because the `<private>` region marker is the only content-derived " + "privacy primitive in this product."
- },
- "brain-knowledge-pack-export": {
- id: "brain-knowledge-pack-export",
- verb: "o2b brain knowledge-pack export",
- module: "src/cli/brain/verbs/knowledge-pack.ts",
- redaction: R.sharedRedactor,
- reason: "a selected subset - preference principles and page bodies verbatim - built to be " + "handed to someone else, so it is the one export that also filters by LABEL before " + "it scans: a page declaring `visibility:`, an entry carrying `owner:`, and an " + "unreviewed `OKF Review/` candidate are blocked and named, never written. What is " + "carried is redacted as a tree (OKF manifest, preference rows) and as text (pages) " + "BEFORE the pack is sealed, so the sha256 table hashes the bytes that left and a " + "recipient's integrity check verifies the redacted copy, not the vault. Preference " + "rows leave without their evidence links and rendered body."
- },
- "search-embedding-openai-compat": {
- id: "search-embedding-openai-compat",
- verb: "o2b search index (embedding provider)",
- module: "src/core/search/embeddings/openai-compat.ts",
- redaction: R.unscannedNetworkPayload,
- reason: "the largest and most continuous egress in this product: every indexed chunk BODY " + "is POSTed verbatim to whichever endpoint the operator configured, for every " + "reindex, and nothing scans it. It is declared unscanned rather than wired to the " + "guard because redaction here would corrupt the thing being built - a vector " + "computed over a placeholder is a vector for the placeholder, so the chunk would " + "come back unfindable while the index reported success, which is a silent failure " + "where this one is at least a stated exposure. The controls that do exist are " + "the operator's: semantic search is off until an endpoint and a key are configured, " + "and the endpoint is whichever host they name, including a local one. The request " + "also carries any extra body fields the operator declared in `embedding_extra_body`, " + "verbatim, next to the owned model, input and encoding fields."
- },
- "search-embedding-zeroentropy": {
- id: "search-embedding-zeroentropy",
- verb: "o2b search index (zeroentropy provider)",
- module: "src/core/search/embeddings/zeroentropy.ts",
- redaction: R.unscannedNetworkPayload,
- reason: "the same chunk bodies as the OpenAI-compatible provider, to a second vendor's " + "embed endpoint under the same operator-configured base URL. Listed separately " + "rather than folded into one 'embedding' entry because the census keys on the " + "module, and a provider that stops being reachable from the resolver would " + "otherwise leave a declaration covering a path nobody can find."
- },
- "search-rerank-cross-encoder": {
- id: "search-rerank-cross-encoder",
- verb: "o2b search query --rerank",
- module: "src/core/search/rerank/cross-encoder.ts",
- redaction: R.unscannedNetworkPayload,
- reason: "sends the QUERY plus the candidate documents to a rerank endpoint, so it carries " + "vault text the embedding path may never have seen - the top-of-pool bodies of the " + "current result set, chosen by relevance to what the operator just asked. Unscanned " + "for the same reason as the embedding path: a reranker scoring placeholders returns " + "an order computed over text nobody wrote."
- },
- "decision-model-systemone": {
- id: "decision-model-systemone",
- verb: "decision_model_uses (for example o2b search query with search_rerank_kind: decision-model)",
- module: "src/core/decision-model/systemone.ts",
- redaction: R.sharedRedactor,
- reason: "the optional decision-model route: a masked, clipped state (for a rerank, the QUERY " + "plus the top candidate passages as P0..Pn) and the question texts, POSTed to the " + "operator's configured `/v1/systemone` endpoint. Unlike the embedding and rerank " + "paths it IS scanned: a judgment over a redacted passage is still a usable judgment, " + "so the whole body passes the shared guard and a refusal sends nothing. Pages whose " + "visibility carries the reserved `private` token, or cannot be resolved, never enter " + "the state, and `<private>` regions are stripped first. The same module sends the " + "Vercel AI Gateway `/v1/evaluate` variant (`vercel-evaluate.ts` only renames fields) " + "and the self-hosted `laya` / `openjev` presets, which default to a loopback base URL " + "where nothing leaves the machine. Off unless the operator enables it in machine " + "config AND the named key variable is set (a loopback self-hosted server needs no " + "key); a vault can opt out."
- },
- "decision-model-llm-emulation": {
- id: "decision-model-llm-emulation",
- verb: "decision_model_uses with decision_model_provider: llm-emulation",
- module: "src/core/decision-model/llm-emulation.ts",
- redaction: R.sharedRedactor,
- reason: "the optional, uncalibrated decision emulation: the same masked, clipped state and " + "question texts as the `/v1/systemone` route, POSTed as a chat completion to the " + "operator's OpenAI-compatible endpoint, which asks a GENERATIVE model for " + "probabilities only. The state and questions pass the shared guard before the body " + "is built and a refusal sends nothing; the state is fenced as untrusted content. " + "Never selected implicitly and never a fallback: it runs only when the operator names " + "this provider, every record is `calibrated: false`, and `enforce` is refused unless " + "`decision_model_allow_uncalibrated` is true."
- },
- "brain-telegram-capture": {
- id: "brain-telegram-capture",
- verb: "o2b brain telegram-run",
- module: "src/core/brain/capture/telegram-capture.ts",
- redaction: R.unscannedNetworkPayload,
- reason: "POSTs reply text to the Telegram Bot API, and the `/catchup` reply is composed " + "from vault content. The transport is built only by the CLI runner verb, so an " + "install that never starts the runner never reaches this path at all - which is " + "why it is a declared narrow exposure rather than a guard call: the bytes are a " + "chat message the operator asked to be sent, and refusing to send one because it " + "quotes a credential-shaped string would break the surface without protecting a " + "destination the operator did not already choose."
- },
- "research-external-fetch": {
- id: "research-external-fetch",
- verb: "o2b brain research",
- module: "src/core/brain/research/external-fetch.ts",
- redaction: R.unscannedNetworkPayload,
- reason: "the one transport every research provider's POST goes through, which is why it is " + "declared here rather than at the provider modules that name the endpoints and " + "never call the network themselves. What leaves is an agent-composed search query, " + "not a page body, and the path is key-gated: with no key configured every call is " + "a typed `disabled` error, so an install that never sets one has no egress here."
- },
- "install-adapter-out": {
- id: "install-adapter-out",
- verb: "o2b install --out",
- module: "src/cli/install/install.ts",
- redaction: R.noVaultContent,
- reason: "writes an adapter configuration rendered from install templates plus the " + "resolved config path. It reads no vault note and composes no vault content, so " + "there is no vault payload to scan. In population only because it names a " + "destination, which is the syntactic rule the census uses on purpose - deciding " + "'is this vault content' is what this entry is for, not what the sweep should " + "guess."
+
+// src/core/brain/path-constants.ts
+import { posix } from "node:path";
+var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;
+var init_path_constants = __esm(() => {
+ BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");
+ BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");
+ BRAIN_ARCHIVED_SIGNALS_REL = posix.join(BRAIN_INBOX_REL, "archived");
+ BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");
+ BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");
+ BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");
+ BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");
+ BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");
+ BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");
+ BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");
+ BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accept-journal");
+ BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");
+ BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");
+ BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
+ BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");
+ BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");
+ BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");
+ BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");
+ BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");
+ BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);
+ BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");
+ BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");
+ BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");
+ BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");
+ BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);
+ BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");
+ BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");
+ BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");
+ BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");
+ BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);
+ BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);
+ BRAIN_PAYLOADS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_PAYLOADS_DIR);
+ BRAIN_WRITE_IMAGES_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);
+ BRAIN_SNAPSHOT_EXCLUDED_ENTRIES = Object.freeze([
+ BRAIN_SNAPSHOTS_DIR,
+ BRAIN_ARTIFACTS_DIR
+ ]);
+ BRAIN_COMPILED_DIGEST_RELS = Object.freeze([
+ posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),
+ posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)
+ ]);
+ BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);
+ BRAIN_PAGE_LANES_REL = Object.freeze([
+ BRAIN_SOURCES_REL,
+ BRAIN_REPORTS_REL,
+ BRAIN_DISTILLATIONS_REL
+ ]);
+});
+
+// src/core/brain/ledger-shards.ts
+function shardedFileName(base, shardId, ext) {
+ if (shardId !== "" && !LEDGER_SHARD_ID_RE.test(shardId)) {
+ throw new Error(`invalid ledger shard id ${JSON.stringify(shardId)} - ` + "expected a lowercase slug matching the device_id config shape");
+ }
+ return shardId === "" ? `${base}.${ext}` : `${base}.${shardId}.${ext}`;
+}
+function resolveAppendShardId() {
+ try {
+ return resolveDeviceId();
+ } catch {
+ return "";
}
+}
+var LEDGER_SHARD_ID_RE, SYNC_CONFLICT_SHARD_PREFIX = "sync-conflict", SYNC_CONFLICT_MARKER, NAME_RE_CACHE;
+var init_ledger_shards = __esm(() => {
+ init_config();
+ init_path_constants();
+ LEDGER_SHARD_ID_RE = /^[a-z0-9-]{1,32}$/;
+ SYNC_CONFLICT_MARKER = `.${SYNC_CONFLICT_SHARD_PREFIX}-`;
+ NAME_RE_CACHE = new Map;
});
-// src/core/egress/guard.ts
-var EGRESS_OUTCOME = Object.freeze({
- released: "released",
- refusedScanTruncated: "refused_scan_truncated",
- refusedSecretIdentifier: "refused_secret_identifier"
+// src/core/reliability/audit.ts
+import { closeSync as closeSync2, fsyncSync as fsyncSync2, mkdirSync as mkdirSync3, openSync as openSync2, writeFileSync } from "node:fs";
+import { join as join4 } from "node:path";
+function appendAuditRecord(auditRoot, record) {
+ const timestamp = new Date(record.timestamp);
+ if (!Number.isFinite(timestamp.getTime())) {
+ throw new Error(`invalid audit timestamp: ${record.timestamp}`);
+ }
+ mkdirSync3(auditRoot, { recursive: true });
+ const path = join4(auditRoot, shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), JSONL_LEDGER_EXT));
+ const line = redactRawOutput(JSON.stringify(record), {
+ maxInput: Number.POSITIVE_INFINITY
+ });
+ const fileDescriptor = openSync2(path, "a", 384);
+ try {
+ writeFileSync(fileDescriptor, line + `
+`, "utf8");
+ fsyncSync2(fileDescriptor);
+ } finally {
+ closeSync2(fileDescriptor);
+ }
+ return path;
+}
+function isoWeekLabel(input) {
+ const date = new Date(Date.UTC(input.getUTCFullYear(), input.getUTCMonth(), input.getUTCDate()));
+ const dayNumber = date.getUTCDay() || 7;
+ date.setUTCDate(date.getUTCDate() + 4 - dayNumber);
+ const year = date.getUTCFullYear();
+ const yearStart = new Date(Date.UTC(year, 0, 1));
+ const week = Math.ceil(((date.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+ return `${year}-W${String(week).padStart(2, "0")}`;
+}
+var AUDIT_WEEK_SHARD_GRAMMAR;
+var init_audit = __esm(() => {
+ init_redactor();
+ init_ledger_shards();
+ AUDIT_WEEK_SHARD_GRAMMAR = Object.freeze({
+ base: "\\d{4}-W\\d{2}",
+ extensions: Object.freeze([JSONL_LEDGER_EXT])
+ });
});
-var EGRESS_OUTCOMES = Object.freeze([
- EGRESS_OUTCOME.released,
- EGRESS_OUTCOME.refusedScanTruncated,
+
+// src/core/brain/audit-dirs.ts
+var SESSION_LIFECYCLE_AUDIT_DIR = "session-lifecycle", HYGIENE_AUDIT_DIR = "hygiene", SECRET_CUSTODY_AUDIT_DIR = "secret-custody", WATCHDOG_AUDIT_DIR = "watchdog", BRAIN_LOG_AUDIT_DIRS;
+var init_audit_dirs = __esm(() => {
+ BRAIN_LOG_AUDIT_DIRS = Object.freeze([
+ SESSION_LIFECYCLE_AUDIT_DIR,
+ HYGIENE_AUDIT_DIR,
+ SECRET_CUSTODY_AUDIT_DIR,
+ WATCHDOG_AUDIT_DIR
+ ]);
+});
+
+// src/core/path-safety.ts
+import { existsSync as existsSync2, realpathSync, statSync as statSync3 } from "node:fs";
+import { basename as basename2, dirname as dirname3, join as join5, posix as posix2, relative, resolve as resolve3, sep } from "node:path";
+function ensureInsideVault(target, vault) {
+ const resolvedTarget = resolve3(target);
+ const resolvedVault = resolve3(vault);
+ if (!isLexicallyInside(resolvedTarget, resolvedVault)) {
+ throw new VaultEscapeError(`path escapes vault: ${target}`);
+ }
+ if (existsSync2(resolvedVault) && !realpathInsideVault(resolvedTarget, resolvedVault)) {
+ throw new VaultEscapeError(`path escapes vault via symlink: ${target}`);
+ }
+ return resolvedTarget;
+}
+function realpathInsideVault(target, vault) {
+ const resolvedVault = resolve3(vault);
+ if (!existsSync2(resolvedVault))
+ return true;
+ const realVault = safeRealpath(resolvedVault);
+ const realAncestor = safeRealpath(deepestExistingAncestor(resolve3(target)));
+ return isLexicallyInside(realAncestor, realVault);
+}
+function isLexicallyInside(target, root) {
+ const t = process.platform === "win32" ? target.toLowerCase() : target;
+ const r = process.platform === "win32" ? root.toLowerCase() : root;
+ return t === r || t.startsWith(r + sep);
+}
+function deepestExistingAncestor(target) {
+ let cur = target;
+ while (!existsSync2(cur)) {
+ const parent = dirname3(cur);
+ if (parent === cur)
+ return cur;
+ cur = parent;
+ }
+ return cur;
+}
+function safeRealpath(p) {
+ try {
+ return realpathSync(p);
+ } catch (err) {
+ if (err?.code === "ENOENT")
+ return p;
+ throw err;
+ }
+}
+function vaultRelative(target, vault) {
+ const rel = relative(resolve3(vault), resolve3(target));
+ return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix2.sep);
+}
+var VAULT_ESCAPE_CODE = "ESCAPE", VaultEscapeError;
+var init_path_safety = __esm(() => {
+ VaultEscapeError = class VaultEscapeError extends Error {
+ code = VAULT_ESCAPE_CODE;
+ constructor(message) {
+ super(message);
+ this.name = "VaultEscapeError";
+ }
+ };
+});
+
+// src/core/integrity/degradation.ts
+function requireNonBlank(field, value) {
+ if (value.trim().length === 0) {
+ throw new DegradationNoticeError(field, "must be a non-blank string");
+ }
+ return value;
+}
+function degradationNotice(input) {
+ const site = requireNonBlank("site", input.site);
+ const detail = requireNonBlank("detail", input.detail);
+ const path = input.path === undefined ? undefined : requireNonBlank("path", input.path);
+ return Object.freeze({
+ code: input.code,
+ site,
+ ...path !== undefined ? { path } : {},
+ detail
+ });
+}
+function emitDegradationNotice(sink, input) {
+ const notice = degradationNotice(input);
+ sink.push(notice);
+ return notice;
+}
+function formatDegradationNotice(notice) {
+ const site = collapse(notice.site);
+ const detail = collapse(notice.detail);
+ const where = notice.path === undefined ? "" : `${PATH_OPEN}${collapse(notice.path)}${PATH_CLOSE}`;
+ return `${notice.code} at ${site}${where}: ${detail}`;
+}
+function collapse(value) {
+ return value.replace(WHITESPACE_RUN_RE, " ").trim();
+}
+var DEGRADATION_CODE, DegradationNoticeError, WHITESPACE_RUN_RE, PATH_OPEN = " (", PATH_CLOSE = ")";
+var init_degradation = __esm(() => {
+ DEGRADATION_CODE = Object.freeze({
+ frontmatterLineDropped: "frontmatter-line-dropped",
+ frontmatterUnreadable: "frontmatter-unreadable",
+ vaultWalkEntrySkipped: "vault-walk-entry-skipped",
+ sessionLinkAbstained: "session-link-abstained",
+ lineageObservationDropped: "lineage-observation-dropped",
+ lineageChainBroken: "lineage-chain-broken",
+ vaultMarkerAbsent: "vault-marker-absent",
+ vaultMarkerMismatch: "vault-marker-mismatch",
+ vaultFrozen: "vault-frozen",
+ logChainBroken: "log-chain-broken"
+ });
+ DegradationNoticeError = class DegradationNoticeError extends Error {
+ field;
+ constructor(field, message) {
+ super(`degradation notice: ${field}: ${message}`);
+ this.name = "DegradationNoticeError";
+ this.field = field;
+ }
+ };
+ WHITESPACE_RUN_RE = /\s+/g;
+});
+
+// src/core/integrity/stamp.ts
+function tokenOf(tokens, field) {
+ const value = tokens[field];
+ return value === undefined ? null : value;
+}
+function compareStamps(expected, actual) {
+ const fields = [...new Set([...Object.keys(expected), ...Object.keys(actual)])].toSorted();
+ const mismatches = [];
+ for (const field of fields) {
+ const before = tokenOf(expected, field);
+ const now = tokenOf(actual, field);
+ if (before === now)
+ continue;
+ mismatches.push(Object.freeze({ field, expected: before, actual: now }));
+ }
+ return Object.freeze(mismatches);
+}
+function formatStampMismatch(mismatch) {
+ const field = collapse2(mismatch.field);
+ return `${field}: expected ${renderToken(mismatch.expected)}, actual ${renderToken(mismatch.actual)}`;
+}
+function renderToken(value) {
+ return value === null ? UNRECORDED_MARKER : JSON.stringify(collapse2(value));
+}
+function collapse2(value) {
+ return value.replace(WHITESPACE_RUN_RE2, " ").trim();
+}
+var GATE_MODE, GATE_MODES, STAMP_VERDICT, UNRECORDED_MARKER = "<unrecorded>", WHITESPACE_RUN_RE2;
+var init_stamp = __esm(() => {
+ GATE_MODE = Object.freeze({
+ off: "off",
+ warn: "warn",
+ fail: "fail"
+ });
+ GATE_MODES = Object.freeze([
+ GATE_MODE.off,
+ GATE_MODE.warn,
+ GATE_MODE.fail
+ ]);
+ STAMP_VERDICT = Object.freeze({
+ pass: "pass",
+ warn: "warn",
+ fail: "fail"
+ });
+ WHITESPACE_RUN_RE2 = /\s+/g;
+});
+
+// src/core/brain/freeze-marker.ts
+import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync4 } from "node:fs";
+import { join as join6, resolve as resolve4 } from "node:path";
+function frozenMarkerPath(vault) {
+ return ensureInsideVault(join6(vault, BRAIN_INTERNAL_STATE_REL, FROZEN_MARKER_FILE), vault);
+}
+function parseMarker(path) {
+ reloadCount += 1;
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync3(path, "utf8"));
+ } catch {
+ return UNREADABLE_MARKER;
+ }
+ if (parsed === null || typeof parsed !== "object")
+ return UNREADABLE_MARKER;
+ if (typeof parsed.frozen_at !== "string" || parsed.frozen_at === "")
+ return UNREADABLE_MARKER;
+ return Object.freeze({
+ schema: typeof parsed.schema === "number" ? parsed.schema : FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: parsed.frozen_at,
+ by: typeof parsed.by === "string" ? parsed.by : "",
+ device_id: typeof parsed.device_id === "string" ? parsed.device_id : "",
+ reason: typeof parsed.reason === "string" ? parsed.reason : ""
+ });
+}
+function readFreezeMarker(vault) {
+ const root = resolve4(vault);
+ let path = MARKER_PATHS.get(root);
+ if (path === undefined) {
+ path = frozenMarkerPath(root);
+ MARKER_PATHS.set(root, path);
+ }
+ let stat;
+ try {
+ stat = statSync4(path, { throwIfNoEntry: false });
+ } catch {
+ stat = undefined;
+ }
+ if (stat === undefined) {
+ MARKER_STAMPS.delete(root);
+ return null;
+ }
+ const cached = MARKER_STAMPS.get(root);
+ if (cached !== undefined && cached.ino === stat.ino && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) {
+ return cached.marker;
+ }
+ const marker = parseMarker(path);
+ MARKER_STAMPS.set(root, {
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ marker
+ });
+ return marker;
+}
+function vaultFrozenNotice(vault, marker) {
+ const why = marker.reason === "" ? "no reason given" : marker.reason;
+ return degradationNotice({
+ code: DEGRADATION_CODE.vaultFrozen,
+ site: SITE,
+ path: resolve4(vault),
+ detail: `refusing to write: this vault was frozen at ${marker.frozen_at} by ` + `${marker.by === "" ? "an unnamed agent" : marker.by} (${why}). ` + `Run \`${FREEZE_NEXT_COMMAND}\` to lift it`
+ });
+}
+function assertVaultNotFrozen(vault) {
+ const marker = readFreezeMarker(vault);
+ if (marker === null)
+ return;
+ throw new VaultFrozenError(vaultFrozenNotice(vault, marker), marker);
+}
+var FREEZE_MARKER_SCHEMA_VERSION = 1, FROZEN_MARKER_FILE = "frozen.json", SITE = "brain.freeze", FREEZE_NEXT_COMMAND = "o2b brain unfreeze", FREEZE_MARKER_UNREADABLE_REASON = "marker-unreadable", WRITE_LANE, VaultFrozenError, UNREADABLE_MARKER, MARKER_STAMPS, MARKER_PATHS, reloadCount = 0;
+var init_freeze_marker = __esm(() => {
+ init_path_safety();
+ init_degradation();
+ init_path_constants();
+ WRITE_LANE = Object.freeze({
+ content: "content",
+ audit: "audit"
+ });
+ VaultFrozenError = class VaultFrozenError extends Error {
+ notice;
+ frozen_at;
+ by;
+ reason;
+ next_command;
+ constructor(notice, marker) {
+ super(formatDegradationNotice(notice));
+ this.name = "VaultFrozenError";
+ this.notice = notice;
+ this.frozen_at = marker.frozen_at;
+ this.by = marker.by;
+ this.reason = marker.reason;
+ this.next_command = FREEZE_NEXT_COMMAND;
+ }
+ };
+ UNREADABLE_MARKER = Object.freeze({
+ schema: FREEZE_MARKER_SCHEMA_VERSION,
+ frozen_at: "",
+ by: "",
+ device_id: "",
+ reason: FREEZE_MARKER_UNREADABLE_REASON
+ });
+ MARKER_STAMPS = new Map;
+ MARKER_PATHS = new Map;
+});
+
+// src/core/brain/vault-identity.ts
+import { existsSync as existsSync4, readFileSync as readFileSync4, statSync as statSync5 } from "node:fs";
+import { join as join7, resolve as resolve5 } from "node:path";
+function vaultIdentityPath(vault) {
+ return ensureInsideVault(join7(vault, BRAIN_ROOT_REL, VAULT_IDENTITY_FILE), vault);
+}
+function readVaultIdentity(vault) {
+ const path = vaultIdentityPath(vault);
+ if (!existsSync4(path))
+ return null;
+ try {
+ const parsed = JSON.parse(readFileSync4(path, "utf8"));
+ if (typeof parsed.vault_id !== "string" || parsed.vault_id.length === 0)
+ return null;
+ return Object.freeze({
+ schema_version: typeof parsed.schema_version === "number" ? parsed.schema_version : VAULT_IDENTITY_SCHEMA_VERSION,
+ vault_id: parsed.vault_id,
+ created_at: typeof parsed.created_at === "string" ? parsed.created_at : ""
+ });
+ } catch {
+ return null;
+ }
+}
+function currentVaultId(root) {
+ let path = MARKER_PATHS2.get(root);
+ if (path === undefined) {
+ path = vaultIdentityPath(root);
+ MARKER_PATHS2.set(root, path);
+ }
+ let stat;
+ try {
+ stat = statSync5(path, { throwIfNoEntry: false });
+ } catch {
+ stat = undefined;
+ }
+ if (stat === undefined) {
+ MARKER_STAMPS2.delete(root);
+ return null;
+ }
+ const cached = MARKER_STAMPS2.get(root);
+ if (cached !== undefined && cached.ino === stat.ino && cached.size === stat.size && cached.mtimeMs === stat.mtimeMs) {
+ return cached.vaultId;
+ }
+ const identity = readVaultIdentity(root);
+ if (identity === null) {
+ MARKER_STAMPS2.delete(root);
+ return null;
+ }
+ MARKER_STAMPS2.set(root, {
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ vaultId: identity.vault_id
+ });
+ return identity.vault_id;
+}
+function vaultMarkerAbsentNotice(vault) {
+ const root = resolve5(vault);
+ if (currentVaultId(root) !== null)
+ return null;
+ return degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerAbsent,
+ site: SITE2,
+ path: root,
+ detail: "resolved vault root carries no identity marker; " + "run `o2b brain init` on this root if it is the intended vault"
+ });
+}
+function assertVaultIdentityForWrite(vault, sink, lane = WRITE_LANE.content) {
+ const root = resolve5(vault);
+ if (lane === WRITE_LANE.content)
+ assertVaultNotFrozen(root);
+ const vaultId = currentVaultId(root);
+ if (vaultId === null) {
+ if (sink !== undefined) {
+ const absent = vaultMarkerAbsentNotice(root);
+ if (absent !== null)
+ emitDegradationNotice(sink, absent);
+ }
+ return;
+ }
+ const pinned = PINNED_IDENTITIES.get(root);
+ if (pinned === undefined) {
+ PINNED_IDENTITIES.set(root, vaultId);
+ return;
+ }
+ if (pinned === vaultId)
+ return;
+ const mismatch = compareStamps({ [VAULT_ID_FIELD]: pinned }, { [VAULT_ID_FIELD]: vaultId })[0];
+ const evidence = mismatch;
+ throw new VaultIdentityMismatchError(degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerMismatch,
+ site: SITE2,
+ path: root,
+ detail: `refusing to write: the store at this root is not the one this process opened (${formatStampMismatch(evidence)})`
+ }), evidence);
+}
+var VAULT_IDENTITY_SCHEMA_VERSION = 1, VAULT_IDENTITY_FILE = "vault-id.json", SITE2 = "vault-identity", VAULT_ID_FIELD = "vault_id", VaultIdentityMismatchError, PINNED_IDENTITIES, MARKER_STAMPS2, MARKER_PATHS2;
+var init_vault_identity = __esm(() => {
+ init_fs_atomic();
+ init_path_safety();
+ init_degradation();
+ init_stamp();
+ init_freeze_marker();
+ init_path_constants();
+ VaultIdentityMismatchError = class VaultIdentityMismatchError extends Error {
+ notice;
+ mismatch;
+ constructor(notice, mismatch) {
+ super(formatDegradationNotice(notice));
+ this.name = "VaultIdentityMismatchError";
+ this.notice = notice;
+ this.mismatch = mismatch;
+ }
+ };
+ PINNED_IDENTITIES = new Map;
+ MARKER_STAMPS2 = new Map;
+ MARKER_PATHS2 = new Map;
+});
+
+// src/core/brain/paths.ts
+import { join as join8 } from "node:path";
+function brainDirs(vault) {
+ const brain = ensureInsideVault(join8(vault, BRAIN_ROOT_REL), vault);
+ return {
+ brain,
+ inbox: ensureInsideVault(join8(vault, BRAIN_INBOX_REL), vault),
+ processed: ensureInsideVault(join8(vault, BRAIN_PROCESSED_REL), vault),
+ archived: ensureInsideVault(join8(vault, BRAIN_ARCHIVED_SIGNALS_REL), vault),
+ pending: ensureInsideVault(join8(vault, BRAIN_PENDING_REL), vault),
+ preferences: ensureInsideVault(join8(vault, BRAIN_PREFERENCES_REL), vault),
+ retired: ensureInsideVault(join8(vault, BRAIN_RETIRED_REL), vault),
+ log: ensureInsideVault(join8(vault, BRAIN_LOG_REL), vault),
+ entities: ensureInsideVault(join8(vault, BRAIN_ENTITIES_REL), vault),
+ bases: ensureInsideVault(join8(vault, BRAIN_BASES_REL), vault),
+ snapshots: ensureInsideVault(join8(vault, BRAIN_SNAPSHOTS_REL), vault)
+ };
+}
+function brainDirsForWrite(vault, notices, lane) {
+ assertVaultIdentityForWrite(vault, notices, lane);
+ return brainDirs(vault);
+}
+var init_paths = __esm(() => {
+ init_fs_atomic();
+ init_path_safety();
+ init_ledger_shards();
+ init_path_constants();
+ init_vault_identity();
+ init_path_safety();
+ init_freeze_marker();
+ init_path_constants();
+});
+
+// src/core/brain/time.ts
+function isoSecond(d = new Date) {
+ return d.toISOString().replace(/\.\d{3}Z$/, "Z");
+}
+var init_time = () => {};
+
+// src/core/brain/secrets/value-cipher.ts
+import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";
+function encryptValue(key, plaintext) {
+ const iv = randomBytes2(IV_BYTES);
+ const cipher = createCipheriv(ALGORITHM, key, iv);
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
+ return {
+ ciphertext: ciphertext.toString("base64"),
+ iv: iv.toString("base64"),
+ tag: cipher.getAuthTag().toString("base64")
+ };
+}
+function decryptValue(key, encrypted) {
+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));
+ decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));
+ const plaintext = Buffer.concat([
+ decipher.update(Buffer.from(encrypted.ciphertext, "base64")),
+ decipher.final()
+ ]);
+ return plaintext.toString("utf8");
+}
+var ALGORITHM = "aes-256-gcm", IV_BYTES = 12;
+var init_value_cipher = () => {};
+
+// src/core/brain/secrets/owner-acl.ts
+import { spawnSync } from "node:child_process";
+import { resolve as resolve6, win32 as win322 } from "node:path";
+function system32Tool(name, env = process.env) {
+ const root = env["SystemRoot"] || env["windir"] || "C:\\Windows";
+ return win322.join(root, "System32", name);
+}
+function parseWhoamiUser(stdout) {
+ const m = /^\s*"([^"]+)","(S-1-\d+(?:-\d+)+)"\s*$/m.exec(stdout);
+ return m ? { name: m[1], sid: m[2] } : null;
+}
+function currentWindowsIdentity() {
+ if (cachedIdentity !== undefined)
+ return cachedIdentity;
+ try {
+ const proc = spawnSync(system32Tool("whoami.exe"), ["/user", "/fo", "csv", "/nh"], {
+ encoding: "utf8",
+ windowsHide: true,
+ timeout: TOOL_TIMEOUT_MS
+ });
+ cachedIdentity = proc.error === undefined && proc.status === 0 ? parseWhoamiUser(proc.stdout) : null;
+ } catch {
+ cachedIdentity = null;
+ }
+ return cachedIdentity;
+}
+function ownerOnlyAclArgv(path, sid, kind) {
+ const rights = kind === "directory" ? "(OI)(CI)F" : "F";
+ return [path, "/inheritance:r", "/grant:r", `*${sid}:${rights}`];
+}
+function restrictToOwner(path, kind, platform = process.platform, force = false) {
+ if (platform !== "win32")
+ return true;
+ const key = `${kind}:${resolve6(path).toLowerCase()}`;
+ if (!force && restricted.has(key))
+ return true;
+ let detail;
+ try {
+ const identity = currentWindowsIdentity();
+ if (identity === null) {
+ detail = "the current user's SID could not be read (whoami /user)";
+ } else {
+ let proc = spawnSync(system32Tool("icacls.exe"), [path, "/reset"], {
+ encoding: "utf8",
+ windowsHide: true,
+ timeout: TOOL_TIMEOUT_MS
+ });
+ if (proc.error === undefined && proc.status === 0) {
+ proc = spawnSync(system32Tool("icacls.exe"), [...ownerOnlyAclArgv(path, identity.sid, kind)], { encoding: "utf8", windowsHide: true, timeout: TOOL_TIMEOUT_MS });
+ }
+ if (proc.error === undefined && proc.status === 0) {
+ restricted.add(key);
+ return true;
+ }
+ detail = proc.error !== undefined ? proc.error.message : `icacls exited ${proc.status ?? proc.signal}: ${(proc.stderr || proc.stdout).trim()}`;
+ }
+ } catch (err) {
+ detail = err instanceof Error ? err.message : String(err);
+ }
+ process.stderr.write(`warning: could not restrict secrets ${kind} to the current user, ` + `it keeps its inherited ACL: ${path}: ${detail}
+`);
+ return false;
+}
+var TOOL_TIMEOUT_MS = 1e4, cachedIdentity, restricted;
+var init_owner_acl = __esm(() => {
+ restricted = new Set;
+});
+
+// src/core/brain/secrets/envelope.ts
+import { randomBytes as randomBytes3, scryptSync, timingSafeEqual } from "node:crypto";
+import { chmodSync, readFileSync as readFileSync5, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { resolve as resolve7 } from "node:path";
+function kdfCostCurveRefusal(kdf) {
+ if (kdf.n > SCRYPT_N_MAX) {
+ return `kdf n ${String(kdf.n)} exceeds this build's ceiling ${String(SCRYPT_N_MAX)}`;
+ }
+ if (kdf.r > SCRYPT_R_MAX) {
+ return `kdf r ${String(kdf.r)} exceeds this build's ceiling ${String(SCRYPT_R_MAX)}`;
+ }
+ if (kdf.p > SCRYPT_P_MAX) {
+ return `kdf p ${String(kdf.p)} exceeds this build's ceiling ${String(SCRYPT_P_MAX)}`;
+ }
+ if (kdf.maxmem > SCRYPT_MAXMEM_MAX) {
+ return `kdf maxmem ${String(kdf.maxmem)} exceeds this build's ceiling ${String(SCRYPT_MAXMEM_MAX)}`;
+ }
+ const needed = 128 * kdf.n * kdf.r;
+ if (kdf.maxmem < needed) {
+ return `kdf maxmem ${String(kdf.maxmem)} is below the ${String(needed)} bytes ` + `these n/r parameters need`;
+ }
+ return null;
+}
+function holderSlot(keyPath) {
+ const resolved = resolve7(keyPath);
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
+}
+function heldKeyOrRefusal(keyPath) {
+ const held = HELD_KEYS.get(holderSlot(keyPath));
+ if (held === undefined)
+ throw new SecretStoreLockedError(keyPath);
+ return held;
+}
+function clearHeldKey(keyPath) {
+ const slot = holderSlot(keyPath);
+ const held = HELD_KEYS.get(slot);
+ if (held !== undefined) {
+ held.fill(0);
+ HELD_KEYS.delete(slot);
+ }
+}
+function hasEnvelopeShape(parsed) {
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
+ return false;
+ const candidate = parsed;
+ if (typeof candidate.version !== "number")
+ return false;
+ const kdf = candidate.kdf;
+ if (typeof kdf !== "object" || kdf === null || typeof kdf.algo !== "string")
+ return false;
+ if (typeof kdf.salt !== "string" || typeof kdf.n !== "number")
+ return false;
+ if (typeof kdf.r !== "number" || typeof kdf.p !== "number" || typeof kdf.maxmem !== "number") {
+ return false;
+ }
+ const wrapped = candidate.wrapped;
+ return typeof wrapped === "object" && wrapped !== null && typeof wrapped.ciphertext === "string" && typeof wrapped.iv === "string" && typeof wrapped.tag === "string";
+}
+function isEnvelopeFile(keyPath) {
+ let bytes;
+ try {
+ bytes = readFileSync5(keyPath);
+ } catch {
+ return false;
+ }
+ return isEnvelopeBytes(bytes);
+}
+function isEnvelopeBytes(bytes) {
+ try {
+ return hasEnvelopeShape(JSON.parse(bytes.toString("utf8")));
+ } catch {
+ return false;
+ }
+}
+function readEnvelope(keyPath) {
+ let parsed;
+ try {
+ parsed = JSON.parse(readFileSync5(keyPath, "utf8"));
+ } catch (err) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, `not parseable as an envelope: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ if (!hasEnvelopeShape(parsed)) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, "missing fields");
+ }
+ if (parsed.version !== KEYFILE_ENVELOPE_SCHEMA_VERSION) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.version, keyPath, `version ${String(parsed.version)} is not read by this build`);
+ }
+ if (parsed.kdf.algo !== KDF_ALGO) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.kdfAlgo, keyPath, `kdf algo ${JSON.stringify(parsed.kdf.algo)} is not implemented by this build`);
+ }
+ if (!Number.isInteger(parsed.kdf.n) || parsed.kdf.n <= 0 || !Number.isInteger(parsed.kdf.r) || parsed.kdf.r <= 0 || !Number.isInteger(parsed.kdf.p) || parsed.kdf.p <= 0 || !Number.isInteger(parsed.kdf.maxmem) || parsed.kdf.maxmem <= 0) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, "kdf parameters must be positive integers");
+ }
+ const costRefusal = kdfCostCurveRefusal(parsed.kdf);
+ if (costRefusal !== null) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.kdfCost, keyPath, costRefusal);
+ }
+ return parsed;
+}
+function freshWrapKdfParams() {
+ return {
+ algo: KDF_ALGO,
+ salt: randomBytes3(SALT_BYTES).toString("base64"),
+ n: SCRYPT_N,
+ r: SCRYPT_R,
+ p: SCRYPT_P,
+ maxmem: SCRYPT_MAXMEM
+ };
+}
+function deriveWrapKey(passphrase, kdf) {
+ return scryptSync(passphrase, Buffer.from(kdf.salt, "base64"), WRAP_KEY_BYTES, {
+ N: kdf.n,
+ r: kdf.r,
+ p: kdf.p,
+ maxmem: kdf.maxmem
+ });
+}
+function unwrapWith(derived, envelope, keyPath) {
+ let plaintext;
+ try {
+ plaintext = decryptValue(derived, envelope.wrapped);
+ } catch {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.passphrase, keyPath, "the passphrase does not unwrap this envelope (wrong passphrase, or the envelope is corrupt)");
+ }
+ const dek = Buffer.from(plaintext, "base64");
+ if (dek.length !== DEK_BYTES) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, `unwrapped key material is ${String(dek.length)} bytes, expected ${String(DEK_BYTES)}`);
+ }
+ return dek;
+}
+function wrapKeyfile(keyPath, passphrase, dek) {
+ if (passphrase.length === 0) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.passphrase, keyPath, "a wrap passphrase must not be empty");
+ }
+ if (dek.length !== DEK_BYTES) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, `refusing to wrap ${String(dek.length)} bytes of key material, expected ${String(DEK_BYTES)}`);
+ }
+ const kdf = freshWrapKdfParams();
+ const envelope = {
+ version: KEYFILE_ENVELOPE_SCHEMA_VERSION,
+ kdf,
+ wrapped: encryptValue(deriveWrapKey(passphrase, kdf), dek.toString("base64"))
+ };
+ const tmp = `${keyPath}.wrap-tmp`;
+ try {
+ writeFileSync2(tmp, `${JSON.stringify(envelope, null, 2)}
+`, {
+ encoding: "utf8",
+ mode: 384
+ });
+ renameWithRetry(tmp, keyPath);
+ } catch (err) {
+ try {
+ unlinkSync2(tmp);
+ } catch {}
+ throw err;
+ }
+ restrictToOwner(keyPath, "file", process.platform, true);
+ if (process.platform !== "win32") {
+ try {
+ chmodSync(keyPath, 384);
+ } catch (err) {
+ process.stderr.write(`warning: could not re-apply owner-only mode to the wrapped keyfile: ` + `${keyPath}: ${err instanceof Error ? err.message : String(err)}
+`);
+ }
+ }
+ return envelope;
+}
+function unlockKeyfile(keyPath, passphrase) {
+ const envelope = readEnvelope(keyPath);
+ const dek = unwrapWith(deriveWrapKey(passphrase, envelope.kdf), envelope, keyPath);
+ const slot = holderSlot(keyPath);
+ const held = HELD_KEYS.get(slot);
+ if (held !== undefined && !timingSafeEqual(held, dek)) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, "the passphrase unwrapped a different key than the one this process already holds");
+ }
+ HELD_KEYS.set(slot, dek);
+ return dek;
+}
+var KEYFILE_ENVELOPE_SCHEMA_VERSION = 1, KDF_ALGO = "scrypt", WRAP_KEY_BYTES = 32, DEK_BYTES = 32, SALT_BYTES = 16, SCRYPT_N, SCRYPT_R = 8, SCRYPT_P = 1, SCRYPT_MAXMEM, SCRYPT_N_MAX, SCRYPT_R_MAX = 16, SCRYPT_P_MAX = 8, SCRYPT_MAXMEM_MAX, ENVELOPE_REFUSAL_CODES, SecretEnvelopeError, SECRET_STORE_LOCKED_CODE = "secret_store_locked", SecretStoreLockedError, SECRET_STORE_KEYFILE_MISSING_CODE = "secret_store_keyfile_missing", SecretStoreKeyfileMissingError, HELD_KEYS;
+var init_envelope = __esm(() => {
+ init_fs_atomic();
+ init_value_cipher();
+ init_owner_acl();
+ SCRYPT_N = 2 ** 15;
+ SCRYPT_MAXMEM = 128 * 1024 * 1024;
+ SCRYPT_N_MAX = 2 ** 18;
+ SCRYPT_MAXMEM_MAX = 256 * 1024 * 1024;
+ ENVELOPE_REFUSAL_CODES = Object.freeze({
+ version: "keyfile_envelope_version_refused",
+ kdfAlgo: "keyfile_envelope_kdf_algo_refused",
+ kdfCost: "keyfile_envelope_kdf_params_refused",
+ passphrase: "keyfile_envelope_passphrase_refused",
+ malformed: "keyfile_envelope_malformed"
+ });
+ SecretEnvelopeError = class SecretEnvelopeError extends Error {
+ code;
+ keyPath;
+ constructor(code, keyPath, detail) {
+ super(`keyfile envelope refused (${code}): ${detail}`);
+ this.name = "SecretEnvelopeError";
+ this.code = code;
+ this.keyPath = keyPath;
+ }
+ };
+ SecretStoreLockedError = class SecretStoreLockedError extends Error {
+ code = SECRET_STORE_LOCKED_CODE;
+ keyPath;
+ constructor(keyPath) {
+ super(`the secret store is locked (the keyfile is passphrase-wrapped): run ` + `"o2b brain secret unlock" to unwrap it for this process - the unlock ` + `applies to this process only and the passphrase is never persisted, ` + `so a key-bearing command must run in the same process that unlocked it`);
+ this.name = "SecretStoreLockedError";
+ this.keyPath = keyPath;
+ }
+ };
+ SecretStoreKeyfileMissingError = class SecretStoreKeyfileMissingError extends Error {
+ code = SECRET_STORE_KEYFILE_MISSING_CODE;
+ keyPath;
+ constructor(keyPath) {
+ super(`the secret store's keyfile is missing while the store still holds entries: ` + `refusing to mint a fresh key over them - restore the keyfile to read the stored secrets`);
+ this.name = "SecretStoreKeyfileMissingError";
+ this.keyPath = keyPath;
+ }
+ };
+ HELD_KEYS = new Map;
+});
+
+// src/core/brain/secrets/crypto.ts
+import { randomBytes as randomBytes4 } from "node:crypto";
+import {
+ chmodSync as chmodSync2,
+ closeSync as closeSync3,
+ existsSync as existsSync5,
+ mkdirSync as mkdirSync4,
+ openSync as openSync3,
+ readFileSync as readFileSync6,
+ writeFileSync as writeFileSync3,
+ writeSync as writeSync2
+} from "node:fs";
+import { dirname as dirname4, join as join9 } from "node:path";
+function ensureSyncExclusionMarker(dir) {
+ const marker = join9(dir, ".gitignore");
+ if (existsSync5(marker))
+ return;
+ try {
+ writeFileSync3(marker, SYNC_EXCLUSION_CONTENT, { encoding: "utf8", flag: "wx", mode: 384 });
+ } catch (err) {
+ if (err.code !== "EEXIST") {
+ process.stderr.write(`warning: could not write the sync-exclusion marker for the secrets directory: ` + `${marker}: ${err instanceof Error ? err.message : String(err)}
+`);
+ }
+ }
+}
+function loadOrCreateKey(keyPath) {
+ const keyDir = dirname4(keyPath);
+ if (existsSync5(keyPath)) {
+ restrictToOwner(keyDir, "directory");
+ restrictToOwner(keyPath, "file");
+ if (process.platform !== "win32") {
+ try {
+ chmodSync2(keyDir, 448);
+ chmodSync2(keyPath, 384);
+ } catch (err) {
+ process.stderr.write(`warning: could not re-apply owner-only modes to the secrets keyfile: ` + `${keyPath}: ${err instanceof Error ? err.message : String(err)}
+`);
+ }
+ }
+ ensureSyncExclusionMarker(keyDir);
+ const key2 = readFileSync6(keyPath);
+ if (isEnvelopeBytes(key2))
+ return heldKeyOrRefusal(keyPath);
+ if (key2.length !== KEY_BYTES) {
+ throw new Error(`secrets keyfile is corrupt (expected ${KEY_BYTES} bytes): ${keyPath}`);
+ }
+ return key2;
+ }
+ mkdirSync4(keyDir, { recursive: true, mode: 448 });
+ restrictToOwner(keyDir, "directory");
+ ensureSyncExclusionMarker(keyDir);
+ const key = randomBytes4(KEY_BYTES);
+ let fd;
+ try {
+ fd = openSync3(keyPath, "wx", 384);
+ } catch (exc) {
+ if (exc.code === "EEXIST")
+ return loadOrCreateKey(keyPath);
+ throw exc;
+ }
+ try {
+ writeSync2(fd, key);
+ } finally {
+ closeSync3(fd);
+ }
+ restrictToOwner(keyPath, "file");
+ return key;
+}
+var KEY_BYTES = 32, SYNC_EXCLUSION_CONTENT = `*
+!.gitignore
+`;
+var init_crypto = __esm(() => {
+ init_envelope();
+ init_owner_acl();
+ init_value_cipher();
+});
+
+// src/core/brain/secrets/store.ts
+var exports_store = {};
+__export(exports_store, {
+ SECRETS_SCHEMA_VERSION: () => SECRETS_SCHEMA_VERSION,
+ custodyTargets: () => custodyTargets,
+ isValidSecretEnvVar: () => isValidSecretEnvVar,
+ isValidSecretName: () => isValidSecretName,
+ keyPath: () => keyPath,
+ listSecrets: () => listSecrets,
+ lockSecretKeyfile: () => lockSecretKeyfile,
+ normalizeAllowPatterns: () => normalizeAllowPatterns,
+ readStore: () => readStore,
+ removeSecret: () => removeSecret,
+ resolveSecretForExec: () => resolveSecretForExec,
+ resolveSecretReadOnly: () => resolveSecretReadOnly,
+ secretsDir: () => secretsDir,
+ setSecret: () => setSecret,
+ unlockSecretKeyfile: () => unlockSecretKeyfile,
+ withSecretsLock: () => withSecretsLock,
+ writeStore: () => writeStore
+});
+import { chmodSync as chmodSync3, existsSync as existsSync6, readFileSync as readFileSync7, statSync as statSync6, writeFileSync as writeFileSync4 } from "node:fs";
+import { join as join10 } from "node:path";
+function secretsDir(vault) {
+ return join10(vault, ".open-second-brain", "secrets");
+}
+function storePath(vault) {
+ return join10(secretsDir(vault), "secrets.json");
+}
+function keyPath(vault) {
+ return join10(secretsDir(vault), "keyfile");
+}
+function isValidSecretName(name) {
+ return NAME_RE.test(name);
+}
+function isValidSecretEnvVar(envVar) {
+ return ENV_VAR_RE.test(envVar);
+}
+function normalizeAllowPatterns(patterns) {
+ return patterns.map((pattern) => {
+ const trimmed = pattern.trim();
+ if (trimmed.length === 0)
+ throw new Error("allow pattern must not be empty");
+ return trimmed;
+ });
+}
+function withSecretsLock(vault, fn) {
+ loadOrCreateKey(keyPath(vault));
+ const maxAttempts = 20;
+ let release = null;
+ let lastError;
+ for (let attempt = 0;attempt < maxAttempts && release === null; attempt++) {
+ try {
+ release = import_proper_lockfile3.default.lockSync(secretsDir(vault), { stale: 1e4, realpath: false });
+ } catch (exc) {
+ if (exc.code !== "ELOCKED")
+ throw exc;
+ lastError = exc;
+ if (attempt < maxAttempts - 1)
+ Bun.sleepSync(25);
+ }
+ }
+ if (release === null) {
+ const msg = lastError instanceof Error ? lastError.message : String(lastError);
+ throw new Error(`another writer holds the secrets store lock: ${msg}`);
+ }
+ try {
+ return fn();
+ } finally {
+ release();
+ }
+}
+function setSecret(vault, input) {
+ assertVaultIdentityForWrite(vault);
+ const name = input.name.trim().toLowerCase();
+ if (!NAME_RE.test(name)) {
+ throw new Error(`secret name must be a lowercase slug ([a-z0-9_-], starting alphanumeric): ${JSON.stringify(input.name)}`);
+ }
+ if (input.value.trim().length === 0) {
+ throw new Error("secret value must not be empty");
+ }
+ const envVar = input.envVar ?? name.toUpperCase().replace(/-/g, "_");
+ if (!ENV_VAR_RE.test(envVar)) {
+ throw new Error(`secret env var must match ${ENV_VAR_RE}: ${JSON.stringify(envVar)}`);
+ }
+ const allow = normalizeAllowPatterns(input.allow ?? []);
+ const key = loadOrCreateKey(keyPath(vault));
+ if (process.platform === "win32") {
+ const results = custodyTargets(vault).map(([path, kind]) => restrictToOwner(path, kind));
+ if (results.includes(false)) {
+ throw new Error(`refusing to store the secret: the secrets directory could not be restricted to the ` + `current user (${secretsDir(vault)}); resolve the icacls warning above and retry`);
+ }
+ }
+ const { next, existing } = withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ const current = file.secrets[name];
+ const updated = {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: {
+ ...file.secrets,
+ [name]: {
+ ...encryptValue(key, input.value),
+ env_var: envVar,
+ allow,
+ created_at: current?.created_at ?? isoSecond(input.now),
+ last_used_at: current?.last_used_at ?? null
+ }
+ }
+ };
+ writeStore(vault, updated);
+ return { next: updated, existing: current };
+ });
+ audit(vault, input, "secret_set", name, {
+ env_var: envVar,
+ allow,
+ replaced: existing !== undefined
+ });
+ return toMetadata(name, next.secrets[name]);
+}
+function listSecrets(vault) {
+ const file = readStore(vault);
+ return Object.entries(file.secrets).map(([name, stored]) => toMetadata(name, stored)).toSorted((a, b) => a.name.localeCompare(b.name));
+}
+function removeSecret(vault, name, ctx) {
+ assertVaultIdentityForWrite(vault);
+ const normalized = name.trim().toLowerCase();
+ const removed = withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ if (file.secrets[normalized] === undefined)
+ return false;
+ const secrets = { ...file.secrets };
+ delete secrets[normalized];
+ writeStore(vault, { version: SECRETS_SCHEMA_VERSION, secrets });
+ return true;
+ });
+ if (removed)
+ audit(vault, ctx, "secret_removed", normalized, {});
+ return removed;
+}
+function resolveSecretForExec(vault, name, ctx = { agent: "cli", now: new Date }) {
+ assertVaultIdentityForWrite(vault);
+ const file = readStore(vault);
+ const normalized = name.trim().toLowerCase();
+ const stored = file.secrets[normalized];
+ if (stored === undefined) {
+ throw new Error(`unknown secret "${normalized}"`);
+ }
+ const key = loadOrCreateKey(keyPath(vault));
+ const value = decryptValue(key, stored);
+ touchLastUsed(vault, normalized, ctx.now);
+ audit(vault, ctx, "secret_resolved_for_exec", normalized, { env_var: stored.env_var });
+ return { name: normalized, env_var: stored.env_var, allow: stored.allow, value };
+}
+function resolveSecretReadOnly(vault, name) {
+ const file = readStore(vault);
+ const normalized = name.trim().toLowerCase();
+ const stored = file.secrets[normalized];
+ if (stored === undefined) {
+ throw new Error(`unknown secret "${normalized}"`);
+ }
+ const kp = keyPath(vault);
+ if (!existsSync6(kp))
+ throw new SecretStoreKeyfileMissingError(kp);
+ const key = loadOrCreateKey(kp);
+ return {
+ name: normalized,
+ env_var: stored.env_var,
+ allow: stored.allow,
+ value: decryptValue(key, stored)
+ };
+}
+function unlockSecretKeyfile(vault, passphrase, ctx) {
+ assertVaultIdentityForWrite(vault);
+ const kp = keyPath(vault);
+ const wrapped = isEnvelopeFile(kp);
+ if (wrapped) {
+ unlockKeyfile(kp, passphrase);
+ } else {
+ withSecretsLock(vault, () => {
+ if (!isEnvelopeFile(kp))
+ wrapKeyfile(kp, passphrase, loadOrCreateKey(kp));
+ });
+ unlockKeyfile(kp, passphrase);
+ }
+ audit(vault, ctx, "secret_unlocked", "keyfile", { keyfile_was_wrapped: wrapped });
+}
+function lockSecretKeyfile(vault, ctx) {
+ assertVaultIdentityForWrite(vault);
+ const kp = keyPath(vault);
+ if (!isEnvelopeFile(kp)) {
+ throw new Error(`secret lock: the keyfile is not passphrase-wrapped, nothing to lock: ${kp}`);
+ }
+ clearHeldKey(kp);
+ audit(vault, ctx, "secret_locked", "keyfile", {});
+}
+function custodyTargets(vault) {
+ const targets = [
+ [secretsDir(vault), "directory"],
+ [keyPath(vault), "file"]
+ ];
+ if (existsSync6(storePath(vault)))
+ targets.push([storePath(vault), "file"]);
+ return targets;
+}
+function toMetadata(name, stored) {
+ return {
+ name,
+ env_var: stored.env_var,
+ allow: stored.allow,
+ created_at: stored.created_at,
+ last_used_at: stored.last_used_at
+ };
+}
+function readStore(vault) {
+ const path = storePath(vault);
+ if (!existsSync6(path))
+ return { version: SECRETS_SCHEMA_VERSION, secrets: {} };
+ restrictToOwner(path, "file");
+ if (process.platform !== "win32") {
+ try {
+ if ((statSync6(path).mode & 511) !== 384)
+ chmodSync3(path, 384);
+ } catch (err) {
+ process.stderr.write(`warning: could not re-apply owner-only mode to the secrets store: ` + `${path}: ${err instanceof Error ? err.message : String(err)}
+`);
+ }
+ }
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
+ if (parsed === null || typeof parsed !== "object" || parsed.version !== SECRETS_SCHEMA_VERSION) {
+ throw new Error(`secrets store is corrupt or from a newer version: ${path}`);
+ }
+ const secrets = parsed.secrets;
+ if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
+ throw new Error(`secrets store is corrupt: ${path}`);
+ }
+ return {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: { ...secrets }
+ };
+}
+function writeStore(vault, file) {
+ loadOrCreateKey(keyPath(vault));
+ const path = storePath(vault);
+ const tmp = `${path}.tmp`;
+ writeFileSync4(tmp, JSON.stringify(file, null, 2) + `
+`, { mode: 384 });
+ renameWithRetry(tmp, path);
+}
+function touchLastUsed(vault, name, now) {
+ withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ const stored = file.secrets[name];
+ if (stored === undefined)
+ return;
+ writeStore(vault, {
+ version: SECRETS_SCHEMA_VERSION,
+ secrets: { ...file.secrets, [name]: { ...stored, last_used_at: isoSecond(now) } }
+ });
+ });
+}
+function audit(vault, ctx, action, name, details) {
+ appendAuditRecord(join10(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {
+ timestamp: ctx.now.toISOString(),
+ actor: ctx.agent,
+ action,
+ target: name,
+ ok: true,
+ details
+ });
+}
+var import_proper_lockfile3, SECRETS_SCHEMA_VERSION = 1, NAME_RE, ENV_VAR_RE;
+var init_store = __esm(() => {
+ init_fs_atomic();
+ init_audit();
+ init_audit_dirs();
+ init_paths();
+ init_time();
+ init_vault_identity();
+ init_crypto();
+ init_envelope();
+ init_owner_acl();
+ import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
+ NAME_RE = /^[a-z0-9][a-z0-9_-]*$/;
+ ENV_VAR_RE = /^[A-Z_][A-Z0-9_]*$/;
+});
+
+// src/openclaw/index.ts
+init_config();
+import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
+
+// src/core/egress/guard.ts
+init_redactor();
+init_secret_ref();
+
+// src/core/egress/registry.ts
+var EGRESS_REDACTION = Object.freeze({
+ sharedRedactor: "shared_redactor",
+ noVaultContent: "no_vault_content",
+ unscannedNetworkPayload: "unscanned_network_payload"
+});
+var EGRESS_REDACTION_STATUSES = Object.freeze([
+ EGRESS_REDACTION.sharedRedactor,
+ EGRESS_REDACTION.noVaultContent,
+ EGRESS_REDACTION.unscannedNetworkPayload
+]);
+var R = EGRESS_REDACTION;
+var EGRESS_SITES = Object.freeze({
+ "brain-bank-export": {
+ id: "brain-bank-export",
+ verb: "o2b brain bank-export",
+ module: "src/cli/brain/verbs/bank-export.ts",
+ redaction: R.sharedRedactor,
+ reason: "the widest export in the tree: preferences, the page graph, page contracts and " + "the sources dashboard composed into one file. Redaction runs over the bundle " + "TREE and the JSON is serialised afterwards, so a note whose text happens to " + "contain a credential assignment cannot mangle the document's own quoting."
+ },
+ "brain-graph-export": {
+ id: "brain-graph-export",
+ verb: "o2b brain graph-export",
+ module: "src/cli/brain/verbs/graph-export.ts",
+ redaction: R.sharedRedactor,
+ reason: "carries no page body, but does carry every page title, path and typed-relation " + "target - a credential pasted into a title left through here verbatim."
+ },
+ "brain-okf-export": {
+ id: "brain-okf-export",
+ verb: "o2b brain okf-export",
+ module: "src/cli/brain/verbs/okf-export.ts",
+ redaction: R.sharedRedactor,
+ reason: "the only export that carries page bodies VERBATIM, which is its interchange " + "contract and also why it is the widest leak by volume. The manifest is redacted " + "as a tree and `okf.json` re-serialised from it; the markdown files are redacted " + "as text. A bundle whose secrets were removed is no longer a lossless round-trip " + "of the vault, and the verb says so rather than implying otherwise. What it does NOT " + "do is filter by label: a page carrying `private: true` in its frontmatter exports in " + "full, because the `<private>` region marker is this product's only content-derived " + "privacy primitive and these composers are content composers, not visibility filters."
+ },
+ "brain-export": {
+ id: "brain-export",
+ verb: "o2b brain export",
+ module: "src/cli/brain/verbs/export.ts",
+ redaction: R.sharedRedactor,
+ reason: "preference principles are free text an agent wrote, and the llms-txt form is " + "meant to be pasted into a foreign prompt - the destination least likely to be " + "read before it is shared. One entry covers all three of the verb's formats " + "because the census keys on the MODULE and the destination is declared once, in " + "the verb: the JSON and transcript forms are redacted as TREES and serialised " + "afterwards, llms-txt as text. What proves each branch scans is a per-handler " + "check in the census, not the guard-call count - counting guards against " + "DESTINATIONS is an inequality, and this module declares one destination against " + "three guards, so a fourth handler that scanned nothing would satisfy it. The " + "transcript form is the widest of the three by far - whole recorded " + "conversations with whichever runtime wrote them, which is where a key pasted " + "into a prompt actually lives. Its records are guarded ONE AT A TIME, so a " + "single oversized turn cannot put a machine's whole corpus past the scan window, " + "and a refusal names the conversation rather than the run - by its basename, " + "except when the basename is itself the secret-shaped identifier, where it is " + "named by runtime and start instant instead. The transcript branch is also the " + "one caller that passes `foreignIdentifiers`, because its `session_id` and " + "`turn_id` were named by the harness that wrote the transcript rather than by " + "this vault, so the guard's vendor-prefix-only rule for identifiers - an " + "argument about ids this build constructs - does not cover them."
+ },
+ "config-export": {
+ id: "config-export",
+ verb: "o2b export-config",
+ module: "src/cli/main.ts",
+ redaction: R.sharedRedactor,
+ reason: "the machine-config snapshot an operator hands to someone else when reporting a " + "problem. It used a private copy that matched five substrings against KEY NAMES " + "and never inspected a value, so a credential stored under a name that copy did " + "not recognise was written out in full."
+ },
+ "brain-continuity-export": {
+ id: "brain-continuity-export",
+ verb: "o2b brain continuity export",
+ module: "src/cli/brain/verbs/continuity.ts",
+ redaction: R.sharedRedactor,
+ reason: "was declared as covered by its read model, which was wrong in both directions. " + "The upstream call redacts at WRITE time with the redactor's DEFAULT options, so " + "`redactTokens` and `redactUrlCredentials` were both off and a vendor key, a bare " + "high-entropy token and a `user:pass@host` URL all left through here verbatim - " + "the two flags the export boundary exists to turn on. Write-time coverage also " + "says nothing about a record already on disk or appended by another writer, since " + "the read model never re-scans. The verb now scans what it READ, which answers " + "both, and gains the truncation refusal the other five already had."
+ },
+ "brain-explorer-export": {
+ id: "brain-explorer-export",
+ verb: "o2b brain explorer --export",
+ module: "src/cli/brain/verbs/explorer.ts",
+ redaction: R.sharedRedactor,
+ reason: "a self-contained HTML file with the whole rule graph embedded as JSON: every " + "preference and retired principle verbatim, plus each one's topic, scope and " + "provenance counts. It is the export most likely to be handed to a person rather " + "than a program - it opens in a browser - and it was the one export that never " + "scanned anything. Redaction runs over the graph TREE before the template " + "substitution, so a principle whose text contains a quote cannot disturb the " + "document. The label rule holds here too: a preference is not withheld for carrying " + "a `private` tag, because the `<private>` region marker is the only content-derived " + "privacy primitive in this product."
+ },
+ "brain-knowledge-pack-export": {
+ id: "brain-knowledge-pack-export",
+ verb: "o2b brain knowledge-pack export",
+ module: "src/cli/brain/verbs/knowledge-pack.ts",
+ redaction: R.sharedRedactor,
+ reason: "a selected subset - preference principles and page bodies verbatim - built to be " + "handed to someone else, so it is the one export that also filters by LABEL before " + "it scans: a page declaring `visibility:`, an entry carrying `owner:`, and an " + "unreviewed `OKF Review/` candidate are blocked and named, never written. What is " + "carried is redacted as a tree (OKF manifest, preference rows) and as text (pages) " + "BEFORE the pack is sealed, so the sha256 table hashes the bytes that left and a " + "recipient's integrity check verifies the redacted copy, not the vault. Preference " + "rows leave without their evidence links and rendered body."
+ },
+ "brain-secret-bundle-export": {
+ id: "brain-secret-bundle-export",
+ verb: "o2b brain secret export",
+ module: "src/cli/brain/verbs/secret.ts",
+ redaction: R.sharedRedactor,
+ reason: "the operator-named file carries every stored credential value RE-ENCRYPTED " + "under a passphrase-derived key, so the shared guard runs over the bundle's " + "METADATA INVENTORY and never over the wrapped values, whose base64 bodies a " + "structural scan could only mangle. The inventory is scanned as an ARRAY of " + "entries - a name like `api-key` as a mapping KEY is the redactor's credential-" + "assignment shape and would replace the whole entry - and the KDF block is " + "excluded, because its random salt is exactly the high-entropy shape the token " + "pass exists to catch. Allow patterns are free text and scan in full; a " + "REWRITTEN entry name or env-var mapping refuses the export, since an " + "identifier is never rewritten into the file that has to carry it. What the " + "status does NOT claim: the file's secrecy is exactly the passphrase's " + "strength against offline guessing wherever the file travels."
+ },
+ "search-embedding-openai-compat": {
+ id: "search-embedding-openai-compat",
+ verb: "o2b search index (embedding provider)",
+ module: "src/core/search/embeddings/openai-compat.ts",
+ redaction: R.unscannedNetworkPayload,
+ reason: "the largest and most continuous egress in this product: every indexed chunk BODY " + "is POSTed verbatim to whichever endpoint the operator configured, for every " + "reindex, and nothing scans it. It is declared unscanned rather than wired to the " + "guard because redaction here would corrupt the thing being built - a vector " + "computed over a placeholder is a vector for the placeholder, so the chunk would " + "come back unfindable while the index reported success, which is a silent failure " + "where this one is at least a stated exposure. The controls that do exist are " + "the operator's: semantic search is off until an endpoint and a key are configured, " + "and the endpoint is whichever host they name, including a local one. The request " + "also carries any extra body fields the operator declared in `embedding_extra_body`, " + "verbatim, next to the owned model, input and encoding fields."
+ },
+ "search-embedding-zeroentropy": {
+ id: "search-embedding-zeroentropy",
+ verb: "o2b search index (zeroentropy provider)",
+ module: "src/core/search/embeddings/zeroentropy.ts",
+ redaction: R.unscannedNetworkPayload,
+ reason: "the same chunk bodies as the OpenAI-compatible provider, to a second vendor's " + "embed endpoint under the same operator-configured base URL. Listed separately " + "rather than folded into one 'embedding' entry because the census keys on the " + "module, and a provider that stops being reachable from the resolver would " + "otherwise leave a declaration covering a path nobody can find."
+ },
+ "search-rerank-cross-encoder": {
+ id: "search-rerank-cross-encoder",
+ verb: "o2b search query --rerank",
+ module: "src/core/search/rerank/cross-encoder.ts",
+ redaction: R.unscannedNetworkPayload,
+ reason: "sends the QUERY plus the candidate documents to a rerank endpoint, so it carries " + "vault text the embedding path may never have seen - the top-of-pool bodies of the " + "current result set, chosen by relevance to what the operator just asked. Unscanned " + "for the same reason as the embedding path: a reranker scoring placeholders returns " + "an order computed over text nobody wrote."
+ },
+ "decision-model-systemone": {
+ id: "decision-model-systemone",
+ verb: "decision_model_uses (for example o2b search query with search_rerank_kind: decision-model)",
+ module: "src/core/decision-model/systemone.ts",
+ redaction: R.sharedRedactor,
+ reason: "the optional decision-model route: a masked, clipped state (for a rerank, the QUERY " + "plus the top candidate passages as P0..Pn) and the question texts, POSTed to the " + "operator's configured `/v1/systemone` endpoint. Unlike the embedding and rerank " + "paths it IS scanned: a judgment over a redacted passage is still a usable judgment, " + "so the whole body passes the shared guard and a refusal sends nothing. Pages whose " + "visibility carries the reserved `private` token, or cannot be resolved, never enter " + "the state, and `<private>` regions are stripped first. The same module sends the " + "Vercel AI Gateway `/v1/evaluate` variant (`vercel-evaluate.ts` only renames fields) " + "and the self-hosted `laya` / `openjev` presets, which default to a loopback base URL " + "where nothing leaves the machine. Off unless the operator enables it in machine " + "config AND the named key variable is set (a loopback self-hosted server needs no " + "key); a vault can opt out."
+ },
+ "decision-model-llm-emulation": {
+ id: "decision-model-llm-emulation",
+ verb: "decision_model_uses with decision_model_provider: llm-emulation",
+ module: "src/core/decision-model/llm-emulation.ts",
+ redaction: R.sharedRedactor,
+ reason: "the optional, uncalibrated decision emulation: the same masked, clipped state and " + "question texts as the `/v1/systemone` route, POSTed as a chat completion to the " + "operator's OpenAI-compatible endpoint, which asks a GENERATIVE model for " + "probabilities only. The state and questions pass the shared guard before the body " + "is built and a refusal sends nothing; the state is fenced as untrusted content. " + "Never selected implicitly and never a fallback: it runs only when the operator names " + "this provider, every record is `calibrated: false`, and `enforce` is refused unless " + "`decision_model_allow_uncalibrated` is true."
+ },
+ "brain-telegram-capture": {
+ id: "brain-telegram-capture",
+ verb: "o2b brain telegram-run",
+ module: "src/core/brain/capture/telegram-capture.ts",
+ redaction: R.unscannedNetworkPayload,
+ reason: "POSTs reply text to the Telegram Bot API, and the `/catchup` reply is composed " + "from vault content. The transport is built only by the CLI runner verb, so an " + "install that never starts the runner never reaches this path at all - which is " + "why it is a declared narrow exposure rather than a guard call: the bytes are a " + "chat message the operator asked to be sent, and refusing to send one because it " + "quotes a credential-shaped string would break the surface without protecting a " + "destination the operator did not already choose."
+ },
+ "research-external-fetch": {
+ id: "research-external-fetch",
+ verb: "o2b brain research",
+ module: "src/core/brain/research/external-fetch.ts",
+ redaction: R.unscannedNetworkPayload,
+ reason: "the one transport every research provider's POST goes through, which is why it is " + "declared here rather than at the provider modules that name the endpoints and " + "never call the network themselves. What leaves is an agent-composed search query, " + "not a page body, and the path is key-gated: with no key configured every call is " + "a typed `disabled` error, so an install that never sets one has no egress here."
+ },
+ "install-adapter-out": {
+ id: "install-adapter-out",
+ verb: "o2b install --out",
+ module: "src/cli/install/install.ts",
+ redaction: R.noVaultContent,
+ reason: "writes an adapter configuration rendered from install templates plus the " + "resolved config path. It reads no vault note and composes no vault content, so " + "there is no vault payload to scan. In population only because it names a " + "destination, which is the syntactic rule the census uses on purpose - deciding " + "'is this vault content' is what this entry is for, not what the sweep should " + "guess."
+ }
+});
+
+// src/core/egress/guard.ts
+var EGRESS_OUTCOME = Object.freeze({
+ released: "released",
+ refusedScanTruncated: "refused_scan_truncated",
+ refusedSecretIdentifier: "refused_secret_identifier"
+});
+var EGRESS_OUTCOMES = Object.freeze([
+ EGRESS_OUTCOME.released,
+ EGRESS_OUTCOME.refusedScanTruncated,
EGRESS_OUTCOME.refusedSecretIdentifier
]);
var EGRESS_REDACTION_OPTIONS = Object.freeze({
@@ -2482,11 +3886,79 @@ var EGRESS_REDACTION_OPTIONS = Object.freeze({
redactUrlCredentials: true
});
var SCAN_WINDOW_MIB = MAX_REDACTOR_INPUT / (1024 * 1024);
-function redactConfigMapping(data) {
- return redactStructured(data, EGRESS_REDACTION_OPTIONS).value;
+function composeRedactionOptions(policy) {
+ return {
+ ...EGRESS_REDACTION_OPTIONS,
+ ...policy.foreignIdentifiers === true ? { foreignIdentifiers: true } : {},
+ ...policy.resolvedLiterals === undefined ? {} : { literals: sortedDistinctLiterals(policy.resolvedLiterals) }
+ };
+}
+function redactConfigMapping(data, policy = {}) {
+ return redactStructured(data, composeRedactionOptions(policy)).value;
+}
+
+// src/core/secret-resolver.ts
+init_config();
+init_secret_ref();
+init_secret_ref();
+import { existsSync as existsSync7 } from "node:fs";
+var custodyStoreModule;
+function custodyStore() {
+ if (custodyStoreModule === undefined) {
+ custodyStoreModule = (init_store(), __toCommonJS(exports_store));
+ }
+ return custodyStoreModule;
+}
+function storeValue(vault, name) {
+ const held = custodyStore().listSecrets(vault).some((meta) => meta.name === name);
+ if (!held)
+ return;
+ return custodyStore().resolveSecretReadOnly(vault, name).value;
+}
+function secretProvider(vault) {
+ const env = process.env;
+ return new Proxy(env, {
+ get(_target, prop) {
+ if (typeof prop !== "string")
+ return;
+ return storeValue(vault, prop) ?? env[prop];
+ },
+ has(_target, prop) {
+ if (typeof prop !== "string")
+ return Reflect.has(env, prop);
+ return storeValue(vault, prop) !== undefined || Reflect.has(env, prop);
+ }
+ });
+}
+function resolveNamedSecret(vault, value) {
+ if (!isSecretReferenceValue(value))
+ return value;
+ return resolveSecretReference(value.trim(), secretProvider(vault));
+}
+function resolvedSecretLiterals(vault) {
+ const store = custodyStore();
+ let held;
+ try {
+ held = store.listSecrets(vault);
+ } catch {
+ return [];
+ }
+ if (held.length === 0)
+ return [];
+ if (!existsSync7(store.keyPath(vault)))
+ return [];
+ const out = [];
+ for (const meta of held) {
+ try {
+ out.push(store.resolveSecretReadOnly(vault, meta.name).value);
+ } catch {}
+ }
+ return out;
}
+installNamedSecretResolver({ resolveNamedSecret });
// src/core/vault-presence.ts
+init_fs_utils();
function vaultUnexaminable(vault, err) {
const reason = err?.message ?? String(err);
return {
@@ -2502,20 +3974,24 @@ function probeVaultDirectory(vault) {
}
// src/core/doctor.ts
+init_config();
+init_fs_utils();
import {
- existsSync as existsSync3,
- mkdirSync as mkdirSync3,
- openSync as openSync2,
- readFileSync as readFileSync3,
+ existsSync as existsSync9,
+ mkdirSync as mkdirSync5,
+ openSync as openSync4,
+ readFileSync as readFileSync8,
rmSync,
- writeSync as writeSync2,
- closeSync as closeSync2
+ writeSync as writeSync3,
+ closeSync as closeSync4
} from "node:fs";
-import { dirname as dirname4, join as join5 } from "node:path";
+import { dirname as dirname6, join as join12 } from "node:path";
// src/core/partner/codegraph.ts
-import { existsSync as existsSync2, readdirSync, realpathSync } from "node:fs";
-import { dirname as dirname3, join as join4, resolve as resolve3 } from "node:path";
+init_config();
+init_fs_utils();
+import { existsSync as existsSync8, readdirSync, realpathSync as realpathSync2 } from "node:fs";
+import { dirname as dirname5, join as join11, resolve as resolve8 } from "node:path";
// src/core/project-manifests.ts
var MANIFEST_ECOSYSTEM = Object.freeze({
@@ -2618,11 +4094,11 @@ function codegraphInitCommand(projectPath) {
}
function isCodeProject(dir) {
try {
- if (!existsSync2(dir))
+ if (!existsSync8(dir))
return false;
- if (!isDir(join4(dir, ".git")))
+ if (!isDir(join11(dir, ".git")))
return false;
- return CODE_MANIFEST_FILES.some((m) => existsSync2(join4(dir, m)));
+ return CODE_MANIFEST_FILES.some((m) => existsSync8(join11(dir, m)));
} catch {
return false;
}
@@ -2635,7 +4111,7 @@ function findCodeProjects(opts) {
const consider = (raw) => {
if (scanned >= limit)
return;
- const path = resolve3(raw);
+ const path = resolve8(raw);
if (seen.has(path))
return;
seen.add(path);
@@ -2646,7 +4122,7 @@ function findCodeProjects(opts) {
found.push(path);
};
consider(opts.cwd);
- const vaultParent = dirname3(resolve3(opts.vault));
+ const vaultParent = dirname5(resolve8(opts.vault));
if (isDir(vaultParent)) {
let entries = [];
try {
@@ -2658,7 +4134,7 @@ function findCodeProjects(opts) {
for (const name of entries) {
if (scanned >= limit)
break;
- consider(join4(vaultParent, name));
+ consider(join11(vaultParent, name));
}
}
for (const extra of opts.scanExtraPaths ?? []) {
@@ -2800,7 +4276,7 @@ function codegraphDisabledResult() {
};
}
function evaluateProjectStatus(project, deps) {
- const indexDir = join4(project, ".codegraph");
+ const indexDir = join11(project, ".codegraph");
let indexed;
try {
indexed = statOrAbsent(indexDir)?.isDirectory() === true;
@@ -2870,7 +4346,7 @@ function resolveRealpath(value) {
if (!value)
return null;
try {
- return realpathSync(value);
+ return realpathSync2(value);
} catch {
return value;
}
@@ -2879,7 +4355,7 @@ function resolveRealpath(value) {
// src/core/doctor.ts
var MANIFEST_FIX = "o2b update";
function checkVaultWriteable(vault) {
- if (!existsSync3(vault)) {
+ if (!existsSync9(vault)) {
return {
name: "vault_writeable",
ok: false,
@@ -2887,10 +4363,10 @@ function checkVaultWriteable(vault) {
fix: `mkdir -p "${vault}"`
};
}
- const probe = join5(vault, ".open-second-brain-doctor-test");
+ const probe = join12(vault, ".open-second-brain-doctor-test");
try {
- const fd = openSync2(probe, "w");
- closeSync2(fd);
+ const fd = openSync4(probe, "w");
+ closeSync4(fd);
rmSync(probe);
} catch (exc) {
return {
@@ -2905,12 +4381,12 @@ function checkVaultWriteable(vault) {
function checkConfigWriteable(config) {
let createdForCheck = false;
try {
- mkdirSync3(dirname4(config), { recursive: true });
- if (!existsSync3(config))
+ mkdirSync5(dirname6(config), { recursive: true });
+ if (!existsSync9(config))
createdForCheck = true;
- const fd = openSync2(config, "a");
- writeSync2(fd, "");
- closeSync2(fd);
+ const fd = openSync4(config, "a");
+ writeSync3(fd, "");
+ closeSync4(fd);
if (createdForCheck)
rmSync(config);
} catch (exc) {
@@ -2918,7 +4394,7 @@ function checkConfigWriteable(config) {
name: "config_writeable",
ok: false,
message: `cannot write config ${config}: ${exc.message ?? exc}`,
- fix: `mkdir -p "${dirname4(config)}" && chmod u+rwx "${dirname4(config)}"`
+ fix: `mkdir -p "${dirname6(config)}" && chmod u+rwx "${dirname6(config)}"`
};
}
return { name: "config_writeable", ok: true, message: `config writable: ${config}` };
@@ -2948,7 +4424,7 @@ function loadJsonManifest(path, name) {
}
let data;
try {
- data = JSON.parse(readFileSync3(path, "utf8"));
+ data = JSON.parse(readFileSync8(path, "utf8"));
} catch (exc) {
return {
result: {
@@ -3074,7 +4550,7 @@ function checkHermesManifest(path) {
}
let text;
try {
- text = readFileSync3(path, "utf8");
+ text = readFileSync8(path, "utf8");
} catch (exc) {
return {
name: "hermes_manifest",
@@ -3123,7 +4599,7 @@ function checkOpenclawManifest(path) {
}
function checkOpenclawInstallability(repoRoot) {
const results = [];
- const pkgPath = join5(repoRoot, "package.json");
+ const pkgPath = join12(repoRoot, "package.json");
const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
results.push(result);
if (!data)
@@ -3154,7 +4630,7 @@ function checkOpenclawInstallability(repoRoot) {
});
continue;
}
- const entryPath = join5(repoRoot, entry);
+ const entryPath = join12(repoRoot, entry);
const problem = manifestFileProblem(entryPath);
if (problem === null) {
results.push({
@@ -3190,10 +4666,10 @@ function doctor(opts) {
results.push(checkConfigWriteable(opts.config));
if (opts.repoRoot) {
const root = opts.repoRoot;
- results.push(checkClaudeManifest(join5(root, ".claude-plugin", "plugin.json")));
- results.push(checkCodexManifest(join5(root, ".codex-plugin", "plugin.json")));
- results.push(checkHermesManifest(join5(root, "plugins", "hermes", "plugin.yaml")));
- results.push(checkOpenclawManifest(join5(root, "openclaw.plugin.json")));
+ results.push(checkClaudeManifest(join12(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join12(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join12(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join12(root, "openclaw.plugin.json")));
results.push(...checkOpenclawInstallability(root));
}
const cg = checkCodegraph({
@@ -3208,10 +4684,10 @@ function doctor(opts) {
}
// src/core/identity-reminder.ts
-import { readFileSync as readFileSync4 } from "node:fs";
-import { dirname as dirname5, resolve as resolve4 } from "node:path";
+import { readFileSync as readFileSync9 } from "node:fs";
+import { dirname as dirname7, resolve as resolve9 } from "node:path";
import { fileURLToPath } from "node:url";
-var TEMPLATE_PATH = resolve4(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
+var TEMPLATE_PATH = resolve9(dirname7(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");
var RUNTIME_TARGET = Object.freeze({
hermes: "hermes",
openclaw: "openclaw"
@@ -3228,7 +4704,7 @@ function loadReminderTemplate() {
if (commonTemplateCache !== undefined)
return commonTemplateCache;
try {
- commonTemplateCache = readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();
+ commonTemplateCache = readFileSync9(TEMPLATE_PATH, "utf8").trimEnd();
return commonTemplateCache;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -3237,8 +4713,8 @@ function loadReminderTemplate() {
});
}
}
-var TEMPLATES_DIR = resolve4(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates");
-var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve4(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
+var TEMPLATES_DIR = resolve9(dirname7(fileURLToPath(import.meta.url)), "..", "..", "templates");
+var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve9(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));
var TEMPLATE_CACHE = new Map;
function tryReadTargetTemplate(target) {
const cached = TEMPLATE_CACHE.get(target);
@@ -3246,7 +4722,7 @@ function tryReadTargetTemplate(target) {
return cached;
let body;
try {
- body = readFileSync4(PER_TARGET_PATHS[target], "utf8").trimEnd();
+ body = readFileSync9(PER_TARGET_PATHS[target], "utf8").trimEnd();
} catch (err) {
if (err.code !== "ENOENT")
throw err;
@@ -3280,60 +4756,13 @@ function buildReminder(agent, target) {
}
// src/core/vault.ts
-import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync } from "node:fs";
-import { dirname as dirname7, join as join7, relative as relative2 } from "node:path";
-
-// src/core/integrity/degradation.ts
-var DEGRADATION_CODE = Object.freeze({
- frontmatterLineDropped: "frontmatter-line-dropped",
- frontmatterUnreadable: "frontmatter-unreadable",
- vaultWalkEntrySkipped: "vault-walk-entry-skipped",
- sessionLinkAbstained: "session-link-abstained",
- lineageObservationDropped: "lineage-observation-dropped",
- lineageChainBroken: "lineage-chain-broken",
- vaultMarkerAbsent: "vault-marker-absent",
- vaultMarkerMismatch: "vault-marker-mismatch",
- vaultFrozen: "vault-frozen",
- logChainBroken: "log-chain-broken"
-});
-
-class DegradationNoticeError extends Error {
- field;
- constructor(field, message) {
- super(`degradation notice: ${field}: ${message}`);
- this.name = "DegradationNoticeError";
- this.field = field;
- }
-}
-function requireNonBlank(field, value) {
- if (value.trim().length === 0) {
- throw new DegradationNoticeError(field, "must be a non-blank string");
- }
- return value;
-}
-function degradationNotice(input) {
- const site = requireNonBlank("site", input.site);
- const detail = requireNonBlank("detail", input.detail);
- const path = input.path === undefined ? undefined : requireNonBlank("path", input.path);
- return Object.freeze({
- code: input.code,
- site,
- ...path !== undefined ? { path } : {},
- detail
- });
-}
-function emitDegradationNotice(sink, input) {
- const notice = degradationNotice(input);
- sink.push(notice);
- return notice;
-}
-
-// src/core/path-safety.ts
-import { basename as basename2, dirname as dirname6, join as join6, posix, relative, resolve as resolve5, sep } from "node:path";
-function vaultRelative(target, vault) {
- const rel = relative(resolve5(vault), resolve5(target));
- return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);
-}
+init_wikilink();
+init_fs_atomic();
+init_fs_utils();
+init_degradation();
+init_path_safety();
+import { mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, writeFileSync as writeFileSync5 } from "node:fs";
+import { dirname as dirname8, join as join13, relative as relative2 } from "node:path";
// src/core/graph/transport-reach.ts
var TRANSPORT_REACH = Object.freeze({
@@ -3363,6 +4792,7 @@ function isRemotelyReadable(pageTags, reach) {
}
// src/core/vault.ts
+init_fs_utils();
var FRONTMATTER_RE = /^---[^\S\n]*\n([\s\S]*?)\n---\s*\n?/;
var BYTE_ORDER_MARK = 65279;
var FRONTMATTER_KEY_PATTERN = "[a-zA-Z_][a-zA-Z0-9_-]*";
@@ -3401,7 +4831,7 @@ function parseFrontmatterWithNotices(path, opts = {}) {
const site = opts.site ?? FRONTMATTER_SITE;
let text;
try {
- text = readFileSync5(path, "utf8");
+ text = readFileSync10(path, "utf8");
} catch (err) {
const notices = [];
emitDegradationNotice(notices, {
@@ -3516,7 +4946,7 @@ function walk(root, dir, skipDirs, skipFiles, out, notices) {
return;
}
for (const entry of entries) {
- const full = join7(dir, entry.name);
+ const full = join13(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
@@ -3680,9 +5110,18 @@ function deriveRuntimeAgentName(runtimeId, operatorName) {
return `${runtimeId}-${base}`;
}
+// src/openclaw/index.ts
+init_path_safety();
+
// src/mcp/vault-path-field.ts
+init_config();
+init_envelope();
+init_secret_ref();
var VAULT_PATH_OUTPUT_SCHEMA = Object.freeze({});
var CONFIG_UNREADABLE_REASON = "the device-local config could not be read, so this reference cannot be " + "resolved; call second_brain_status for the file and the remedy";
+var SECRET_STORE_LOCKED_REASON = "the vault's credential store is locked, so the installation secret " + 'reference cannot be resolved; run "o2b brain secret unlock" and retry';
+var SECRET_STORE_KEYFILE_MISSING_REASON = "the vault's credential store is missing its keyfile, so the installation " + "secret reference cannot be resolved; restore the keyfile and retry";
+var SECRET_REFERENCE_UNRESOLVED_REASON = "the installation secret is a $secret: reference the vault's credential " + "store cannot resolve; inspect the device config and the store with " + "`o2b secrets list`";
function hostPathReference(path, source) {
const configPath = source.configPath ?? undefined;
try {
@@ -3690,6 +5129,13 @@ function hostPathReference(path, source) {
} catch (err) {
if (err instanceof ConfigReadError)
return { error: CONFIG_UNREADABLE_REASON };
+ if (err instanceof SecretStoreLockedError)
+ return { error: SECRET_STORE_LOCKED_REASON };
+ if (err instanceof SecretStoreKeyfileMissingError) {
+ return { error: SECRET_STORE_KEYFILE_MISSING_REASON };
+ }
+ if (err instanceof SecretReferenceError)
+ return { error: SECRET_REFERENCE_UNRESOLVED_REASON };
throw err;
}
}
@@ -3729,7 +5175,9 @@ var openclaw_default = definePluginEntry({
config_path: discovery.path,
config_exists: discovery.exists,
config_keys: Object.keys(discovery.data).toSorted(),
- config: redactConfigMapping(discovery.data),
+ config: redactConfigMapping(discovery.data, {
+ resolvedLiterals: resolvedSecretLiterals(vault)
+ }),
vault_path: vaultPathField({ vault }),
vault_exists: presence.unexaminable ?? presence.present
};
diff --git a/package.json b/package.json
index 5c18c803..896ebf6a 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.77.0",
+ "version": "1.78.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 76e53d68..dbe55011 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.77.0"
+version: "1.78.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 6c36d364..1594e926 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.77.0",
+ "version": "1.78.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 4094271c..e22ea698 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -104,6 +104,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).
- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).
- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#knowledge-packs).
+- **Secret custody.** Credentials live encrypted in the vault's state dir behind a capability-gated store; `$secret:NAME` references resolve at the use sites, `o2b brain secret unlock` wraps the keyfile under a passphrase, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle: [custody CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#write-time-integrity-and-governance-since-v0440).
- **Today view and note markers.** `o2b brain today`, `@osb loop` and `@osb set` markers: [Brain CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#brain-observing-memory).
- **Self-inspection.** `o2b version`, `o2b install --friction` and `o2b state status` report what is installed and where state lives: [CLI reference](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#core).
- **MCP surface.** Tools, tool profiles for hosts with tool limits, and the always-loaded writer server: [`docs/mcp.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/mcp.md).
@@ -116,7 +117,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.77.0 makes the claim ledger time-aware and correctable. A claim can carry a validity window (`o2b brain truth ingest --valid-from`/`--valid-until`, frozen from the source record when the flags are absent), `o2b brain truth events` recalls the ledger over an assertion-time slice, `o2b brain truth state` grounds an agent's stated claims with a per-claim anchoring verdict, and `o2b brain lifecycle correct` retires what a correction touches - dry run by default, with a retired record that recall can still serve answered only beside its resolved, readable correction, never alone. The deep relational recall arm now runs under width budgets with hub skipping and entity co-occurrence bridges. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.78.0 puts credential custody under an operator passphrase. The secrets keyfile wraps into a scrypt envelope behind `o2b brain secret unlock`/`lock`, `$secret:NAME` references resolve through the custody store at the embedding, decision-model, research, Telegram and installation-secret use sites, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle. Resolved credential literals are redacted at the error and config-mapping boundaries, composed tags must parse as Obsidian tags, a declared page vocabulary gates capture writes, import and upgrade plans carry an approval digest that apply must match, and a changed extraction contract reprocesses the sources it covers. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 76e53d68..dbe55011 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.77.0"
+version: "1.78.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/pyproject.toml b/pyproject.toml
index e01288b0..9881f886 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.77.0"
+version = "1.78.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index b88ab1fe..bb00711d 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -108,7 +108,7 @@ Brain verbs (observing memory):
tune Self-tuning recall: grid-evaluate, persist, inspect, reset
attr Typed-page attribute fields: assign, remove, show (schema-pack declared)
tiers Frontmatter tier guard: check identity-field drift, restore or accept
- secret Capability-gated secret custody: set, list, rm, run (use w/o exposure)
+ secret Capability-gated secret custody: set, list, rm, run, lock, unlock, export, import (use w/o exposure)
maintenance Quiet-window, lease-guarded lane (dream, reindex, bridges, clusters, custom tasks)
audit Render a preference's full mutation audit trail
morning-brief Session-start summary: top prefs, open questions, recent notes
@@ -196,6 +196,66 @@ Common flags:
--help Per-verb help (run \`o2b brain <verb> --help\`)
`;
+/**
+ * `brain secret` per-op flag tables and the usage line assembled from
+ * them. One source, two surfaces: the USAGE the verb prints on a usage
+ * error and the line `o2b brain secret --help` shows are both built here,
+ * so they cannot drift apart - and an op that never documents a flag
+ * refuses it by name (via {@link secretOpAccepts}) instead of silently
+ * swallowing it while the flag's effect never happens.
+ */
+const SECRET_OP_FLAGS: Record<string, ReadonlyArray<string>> = {
+ set: ["env-var", "allow", "from-env", "agent"],
+ list: [],
+ rm: [],
+ run: ["agent"],
+ lock: [],
+ unlock: ["passphrase-from-env"],
+ export: ["out", "passphrase-from-env"],
+ import: ["replace", "passphrase-from-env"],
+};
+
+/** The usage spelling of every flag, keyed by its parsed name. */
+const SECRET_FLAG_USAGE: Record<string, string> = {
+ "env-var": "[--env-var V]",
+ allow: "[--allow PATTERN]...",
+ "from-env": "[--from-env SRC]",
+ agent: "[--agent N]",
+ "passphrase-from-env": "[--passphrase-from-env SRC]",
+ out: "--out FILE",
+ replace: "[--replace]",
+ vault: "[--vault <path>]",
+ json: "[--json]",
+};
+
+/** Every op answers `--vault` and `--json`; the rest are per-op. */
+const SECRET_COMMON_FLAGS: ReadonlyArray<string> = ["vault", "json"];
+
+/** Whether `op` documents `flag` - the parse-time acceptance contract. */
+export function secretOpAccepts(op: string, flag: string): boolean {
+ return SECRET_COMMON_FLAGS.includes(flag) || (SECRET_OP_FLAGS[op] ?? []).includes(flag);
+}
+
+function secretOpUsage(op: string, lead: string, tail = ""): string {
+ const flags = [...(SECRET_OP_FLAGS[op] ?? []), ...SECRET_COMMON_FLAGS]
+ .map((flag) => SECRET_FLAG_USAGE[flag])
+ .join(" ");
+ return `${lead} ${flags}${tail}`;
+}
+
+export const SECRET_VERB_USAGE =
+ "usage: o2b brain secret " +
+ [
+ secretOpUsage("set", "set <name>"),
+ secretOpUsage("list", "list"),
+ secretOpUsage("rm", "rm <name>"),
+ secretOpUsage("lock", "lock"),
+ secretOpUsage("unlock", "unlock"),
+ secretOpUsage("export", "export"),
+ secretOpUsage("import", "import FILE"),
+ secretOpUsage("run", "run <name>", " -- <command...>"),
+ ].join(" | ");
+
export const VERB_HELP: Record<string, string> = {
"forget-source":
"usage: o2b brain forget-source <source> [--confirm] [--include-originals] [--vault <path>] [--json]\n" +
@@ -610,7 +670,10 @@ export const VERB_HELP: Record<string, string> = {
"lists open findings; restore writes the expected value back (--apply);\n" +
"accept adopts the hand-edit as the new baseline. Nothing auto-resolves.\n",
secret:
- "usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] | list | rm <name> | run <name> [--agent N] [--vault <path>] [--json] -- <command...>\n" +
+ // Assembled from the per-op flag tables above - the same string the
+ // verb prints on a usage error, so the two surfaces cannot disagree.
+ SECRET_VERB_USAGE +
+ "\n" +
"Capability-gated secret custody under the vault-local state dir:\n" +
"per-value AES-256-GCM ciphertext, 0600 keyfile, no surface ever prints\n" +
"the value. set reads the value from stdin or --from-env (never argv);\n" +
@@ -618,7 +681,17 @@ export const VERB_HELP: Record<string, string> = {
"matches the allowlist declared at set time, and the captured output is\n" +
"redacted before it reaches the caller. Every operation lands a\n" +
"no-values record in Brain/log/secret-custody/. Protects against\n" +
- "context leakage and vault sync exposure - not against root.\n",
+ "context leakage and vault sync exposure - not against root.\n" +
+ "unlock wraps the keyfile under a passphrase (read from stdin or\n" +
+ "--passphrase-from-env, never argv) and holds the key for this process\n" +
+ "only; lock clears it, and every other process must unlock separately.\n" +
+ "export writes every entry as one passphrase-encrypted bundle to the\n" +
+ "--out file (values re-encrypted; names and env-var mappings travel in\n" +
+ "the clear past the shared egress redactor); import restores a bundle,\n" +
+ "refusing names the store already holds unless --replace is given.\n" +
+ "WARNING: a lost passphrase is unrecoverable - every stored value and\n" +
+ "every exported bundle stays unreadable forever, and nothing recovers\n" +
+ "them.\n",
maintenance:
MAINTENANCE_USAGE +
"\n" +
@@ -770,6 +843,7 @@ export const VERB_HELP: Record<string, string> = {
"always skipped.\n",
"import-claude-memory":
"usage: o2b brain import-claude-memory [--vault <path>] [--memory <path>]\n" +
+ " [--from <backend>] [--approval-digest <hex>]\n" +
" [--dry-run | --apply] [--yes] [--json]\n" +
" [--allow-arbitrary-memory-path]\n" +
"Read metadata.type:feedback entries from a Claude Code memory directory and\n" +
@@ -777,7 +851,8 @@ export const VERB_HELP: Record<string, string> = {
"Brain/.imports/claude-memory.json tracks idempotency. UPDATE preserves\n" +
"accumulated evidence fields. CONFLICT (preference exists without a manifest\n" +
"entry) exits 2 — never silent overwrites.\n" +
- "Default is --dry-run; --apply requires --yes in non-interactive mode.\n",
+ "Default is --dry-run; --apply requires --yes and --approval-digest in\n" +
+ "non-interactive mode.\n",
entity:
"usage: o2b brain entity <set|get|list|relate|archive|prune> [args]\n" +
" set <category> <name> [--alias <a>]... [--body <md>] [--confidence <c>] [--json]\n" +
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
index f6f3d5b4..2abffa2b 100644
--- a/src/cli/brain/helpers.ts
+++ b/src/cli/brain/helpers.ts
@@ -13,8 +13,9 @@
* # Layout
*
* - `./help-text.ts` — `BRAIN_HELP` + per-verb `VERB_HELP`.
- * - `./upgrade-render.ts` — `renderUpgradePlanJson`,
- * `printUpgradePlanText`,
+ * - `./upgrade-render.ts` — `renderUpgradePlanJson` (the row-level
+ * projection; this barrel wraps it to add
+ * the plan digest), `printUpgradePlanText`,
* `renderUnifiedDiff`.
* - `./query-render.ts` — text renderers for `brain query`.
* - `./rollback-prompt.ts` — `diffSummary`, `readSingleLine`.
@@ -31,9 +32,11 @@ import {
} from "../../core/config.ts";
import { formatLocalTimestamp } from "../../core/brain/present-time.ts";
import { isoSecond } from "../../core/brain/time.ts";
+import type { UpgradePlan } from "../../core/brain/upgrade.ts";
import { CliError, parseFlags, type FlagsSchema } from "../argparse.ts";
import { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
+import { renderUpgradePlanJson as renderUpgradePlanJsonRows } from "./upgrade-render.ts";
// ── Vault resolution ────────────────────────────────────────────────────────
@@ -111,11 +114,22 @@ export { ISO_8601_RE, parseOptionalIsoDate } from "../coerce.ts";
export { NO_VAULT_ERROR, normalizeFlagString } from "../helpers.ts";
export { BRAIN_HELP, MAINTENANCE_USAGE, VERB_HELP } from "./help-text.ts";
-export {
- renderUpgradePlanJson,
- printUpgradePlanText,
- renderUnifiedDiff,
-} from "./upgrade-render.ts";
+export { printUpgradePlanText, renderUnifiedDiff } from "./upgrade-render.ts";
+
+/**
+ * The plan JSON an operator reads, with its seal (t_18fda844): the
+ * digest carried from `--dry-run` to `--apply`, so what lands is what
+ * was reviewed. Emitted unconditionally - a `planUpgrade` result is
+ * always sealed - and the row projection stays in
+ * `./upgrade-render.ts` (imported above under an alias); the barrel is
+ * where the seal becomes visible, because this is the module every
+ * verb imports its renderers through.
+ */
+export function renderUpgradePlanJson(
+ plan: UpgradePlan,
+): ReturnType<typeof renderUpgradePlanJsonRows> & { digest: string } {
+ return { ...renderUpgradePlanJsonRows(plan), digest: plan.digest };
+}
export {
renderQueryPreferenceText,
renderQueryTopicText,
diff --git a/src/cli/brain/verbs/batch-plan.ts b/src/cli/brain/verbs/batch-plan.ts
index 3e8b14cd..322fe77e 100644
--- a/src/cli/brain/verbs/batch-plan.ts
+++ b/src/cli/brain/verbs/batch-plan.ts
@@ -95,6 +95,12 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {
`${plan.skipped.length} unchanged skipped` +
(plan.resumedCompleted > 0 ? `; ${plan.resumedCompleted} resumed (checkpointed)` : ""),
);
+ if (plan.contractChanged) {
+ info(
+ ` extraction contract changed: ${plan.contractChangedFiles} unchanged file(s) ` +
+ "reprocess under the new contract",
+ );
+ }
for (const b of plan.batches) {
ok(` batch ${b.index}: ${b.files.length} file(s), ${b.totalBytes} byte(s)`);
for (const f of b.files) {
diff --git a/src/cli/brain/verbs/design-note.ts b/src/cli/brain/verbs/design-note.ts
index 3d4046ab..069ff158 100644
--- a/src/cli/brain/verbs/design-note.ts
+++ b/src/cli/brain/verbs/design-note.ts
@@ -14,6 +14,9 @@
*/
import { readFileSync } from "node:fs";
+import { relative } from "node:path";
+
+import { canonicalNotePath } from "../../../core/path-safety.ts";
import {
commitDesignNote,
@@ -21,6 +24,12 @@ import {
planDesignNote,
} from "../../../core/brain/design-note.ts";
import { gatedOwnerScopeView } from "../../../core/brain/owner-scope-view.ts";
+import {
+ parsePayloadJson,
+ PayloadJsonError,
+ payloadStripNote,
+ type PayloadStrip,
+} from "../../../core/brain/payload-json.ts";
import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
import {
@@ -103,13 +112,22 @@ export async function cmdBrainDesignNote(argv: string[]): Promise<number> {
}
let payload: unknown;
+ let strip: PayloadStrip | undefined;
try {
- payload = JSON.parse(rawPayload);
- } catch {
- const message = "payload must be valid JSON";
- if (!asJson) return fail(message);
- okJson({ ok: false, message });
- return 1;
+ const parsed = parsePayloadJson(rawPayload);
+ payload = parsed.payload;
+ strip = parsed.strip;
+ } catch (error) {
+ // Reported here rather than by the ingress: at this point the mistake
+ // is the JSON the operator typed, and a path inside a payload the CLI
+ // never parsed would not tell them what to fix. A refusal after a
+ // strip attempt names the attempt (t_dac8bf7e).
+ if (error instanceof PayloadJsonError) {
+ if (!asJson) return fail(error.message);
+ okJson({ ok: false, message: error.message });
+ return 1;
+ }
+ throw error;
}
const res = commitDesignNote(vault, topic, payload, {
agent: resolveBrainAgent(flags, config),
@@ -120,14 +138,21 @@ export async function cmdBrainDesignNote(argv: string[]): Promise<number> {
ok: true,
topic: res.topic,
slug: res.slug,
- path: res.path,
+ // Vault-relative, like the distill surface and the MCP twin: the
+ // absolute host path is the operator-supplied vault prefix composed
+ // with a machine-derived subtree, and this output lands in model
+ // context.
+ path: canonicalNotePath(relative(vault, res.path)),
recommended: res.recommended,
alternative_count: res.alternativeCount,
+ // Present only when a leading <think> block was stripped (t_dac8bf7e).
+ ...(strip !== undefined ? { note: payloadStripNote(strip) } : {}),
});
return 0;
}
- ok(`wrote ${res.path}`);
+ ok(`wrote ${canonicalNotePath(relative(vault, res.path))}`);
ok(`recommended: ${res.recommended} (of ${res.alternativeCount} alternative(s))`);
+ if (strip !== undefined) ok(payloadStripNote(strip));
return 0;
} catch (err) {
const message = isNamedRefusal(err)
diff --git a/src/cli/brain/verbs/distill.ts b/src/cli/brain/verbs/distill.ts
index 4bbc052a..9a7af34d 100644
--- a/src/cli/brain/verbs/distill.ts
+++ b/src/cli/brain/verbs/distill.ts
@@ -34,6 +34,12 @@ import {
type CaptureScope,
} from "../../../core/brain/provenance/capture-scope.ts";
import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
+import {
+ parsePayloadJson,
+ PayloadJsonError,
+ payloadStripNote,
+ type PayloadStrip,
+} from "../../../core/brain/payload-json.ts";
import {
INTAKE_TRUST,
UNTRUSTED_SOURCE_FRONTMATTER_KEY,
@@ -81,24 +87,23 @@ const CLAIMS_SHAPE_HINT = "claims must be a JSON array of { text, block? } objec
* array) and hand it to the shared shape-checked ingress, so the CLI and the
* MCP tool accept exactly the same payload under exactly the same rules.
*
- * The unwrap failure is reported HERE rather than by the ingress: at this
- * point the operator's mistake is the wrapper they typed, and a path inside a
- * payload the CLI never found does not tell them what to type instead. Once a
- * list is in hand, the ingress owns every complaint about its items.
+ * The parse goes through the shared strip-and-note parser (t_dac8bf7e): a
+ * leading `<think>` block is stripped once and the fact returned, while a
+ * refusal - plain or naming the strip attempt - propagates as the
+ * {@link PayloadJsonError} the operator-input catch reports. The unwrap
+ * failure is still reported HERE rather than by the ingress: at this point
+ * the operator's mistake is the wrapper they typed, and a path inside a
+ * payload the CLI never found does not tell them what to type instead. Once
+ * a list is in hand, the ingress owns every complaint about its items.
*/
-function parseClaims(raw: string): DistillClaim[] {
- let parsed: unknown;
- try {
- parsed = JSON.parse(raw);
- } catch {
- throw new Error("claims must be valid JSON");
- }
- const payload =
+function parseClaims(raw: string): { claims: DistillClaim[]; strip?: PayloadStrip } {
+ const { payload: parsed, strip } = parsePayloadJson(raw);
+ const claims =
!Array.isArray(parsed) && parsed !== null && typeof parsed === "object"
? (parsed as { claims?: unknown }).claims
: parsed;
- if (!Array.isArray(payload)) throw new Error(CLAIMS_SHAPE_HINT);
- return parseDistillClaims(payload);
+ if (!Array.isArray(claims)) throw new Error(CLAIMS_SHAPE_HINT);
+ return { claims: parseDistillClaims(claims), ...(strip !== undefined ? { strip } : {}) };
}
/**
@@ -177,7 +182,24 @@ export async function cmdBrainDistill(argv: string[]): Promise<number> {
typeof flags["claims"] === "string"
? (flags["claims"] as string)
: readFileSync(flags["claims-file"] as string, "utf8");
- const claims = parseClaims(claimsRaw);
+ let claims: DistillClaim[];
+ let strip: PayloadStrip | undefined;
+ try {
+ const parsed = parseClaims(claimsRaw);
+ claims = parsed.claims;
+ strip = parsed.strip;
+ } catch (error) {
+ // Reported here rather than by the ingress: at this point the mistake
+ // is the JSON the operator typed, and a path inside a payload the CLI
+ // never parsed would not tell them what to fix. The refusal rides the
+ // verb's own `distill: <message>` stderr line; after a strip attempt
+ // the message names the attempt (t_dac8bf7e).
+ if (error instanceof PayloadJsonError) {
+ process.stderr.write(`distill: ${error.message}\n`);
+ return 1;
+ }
+ throw error;
+ }
// Read verbatim: the excerpt is stored byte for byte and its digest is
// taken over exactly these bytes.
const excerpt =
@@ -208,10 +230,13 @@ export async function cmdBrainDistill(argv: string[]): Promise<number> {
trust: res.trust,
capture_scope: res.captureScope,
...(res.quotes !== undefined ? { quotes: res.quotes } : {}),
+ // Present only when a leading <think> block was stripped (t_dac8bf7e).
+ ...(strip !== undefined ? { note: payloadStripNote(strip) } : {}),
});
return 0;
}
ok(successLine(res));
+ if (strip !== undefined) ok(payloadStripNote(strip));
return 0;
} catch (err) {
if (OPERATOR_ERROR_CLASSES.some((cls) => err instanceof cls)) {
diff --git a/src/cli/brain/verbs/extract-signals.ts b/src/cli/brain/verbs/extract-signals.ts
index 30d3648a..848044da 100644
--- a/src/cli/brain/verbs/extract-signals.ts
+++ b/src/cli/brain/verbs/extract-signals.ts
@@ -27,6 +27,12 @@ import {
import { resolveTokenImpactLedgerEnabled } from "../../../core/config.ts";
import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
+import {
+ parsePayloadJson,
+ PayloadJsonError,
+ payloadStripNote,
+ type PayloadStrip,
+} from "../../../core/brain/payload-json.ts";
import {
brainVerbContext,
fail,
@@ -127,16 +133,22 @@ export async function cmdBrainExtractSignals(argv: string[]): Promise<number> {
}
let payload: unknown;
+ let strip: PayloadStrip | undefined;
try {
- payload = JSON.parse(rawPayload);
- } catch {
+ const parsed = parsePayloadJson(rawPayload);
+ payload = parsed.payload;
+ strip = parsed.strip;
+ } catch (error) {
// Reported here rather than by the ingress: at this point the mistake
// is the JSON the operator typed, and a path inside a payload the CLI
- // never parsed would not tell them what to fix.
- const message = "payload must be valid JSON";
- if (!asJson) return fail(message);
- okJson({ ok: false, message });
- return 1;
+ // never parsed would not tell them what to fix. A refusal after a
+ // strip attempt names the attempt (t_dac8bf7e).
+ if (error instanceof PayloadJsonError) {
+ if (!asJson) return fail(error.message);
+ okJson({ ok: false, message: error.message });
+ return 1;
+ }
+ throw error;
}
const now = new Date();
const res = commitExtractedSignals(vault, sessionRef, payload, {
@@ -156,6 +168,8 @@ export async function cmdBrainExtractSignals(argv: string[]): Promise<number> {
deduped: res.deduped,
durability_rejected: res.durabilityRejected,
rejected: res.rejected.map((r) => ({ topic: r.topic, reason: r.reason })),
+ // Present only when a leading <think> block was stripped (t_dac8bf7e).
+ ...(strip !== undefined ? { note: payloadStripNote(strip) } : {}),
});
return 0;
}
@@ -164,6 +178,7 @@ export async function cmdBrainExtractSignals(argv: string[]): Promise<number> {
(res.staged > 0 ? ` (staged for approval)` : "") +
`, deduped ${res.deduped}, durability-rejected ${res.durabilityRejected}`,
);
+ if (strip !== undefined) ok(payloadStripNote(strip));
for (const r of res.rejected) ok(`rejected: ${r.topic} (${r.reason})`);
return 0;
} catch (err) {
diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.ts
index 87c5d4a6..e7866dda 100644
--- a/src/cli/brain/verbs/feedback.ts
+++ b/src/cli/brain/verbs/feedback.ts
@@ -1,4 +1,7 @@
import { readFileSync } from "node:fs";
+import { relative } from "node:path";
+
+import { canonicalNotePath } from "../../../core/path-safety.ts";
import {
mirrorReportFields,
mirrorSignal,
@@ -112,7 +115,15 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
try {
sigResult = writeSignal(vault, signalInput, writeOpts);
} catch (exc) {
- return fail(`failed to write signal: ${(exc as Error).message ?? exc}`);
+ const message = `failed to write signal: ${(exc as Error).message ?? exc}`;
+ // The ok:false twin a --json caller parses, matching the sibling verbs
+ // (capture, design-note); bare text on stdout-starved --json leaves
+ // automation with nothing machine-parseable.
+ if (flags["json"]) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
}
// t_936a1a61: fail-soft mirror into the shared namespace AFTER the
// primary write; surfaced only when the key is configured.
@@ -190,7 +201,12 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
{ overwrite: false, configPath: config },
);
} catch (exc) {
- return fail(`failed to force-confirm preference: ${(exc as Error).message ?? exc}`);
+ const message = `failed to force-confirm preference: ${(exc as Error).message ?? exc}`;
+ if (flags["json"]) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
}
try {
appendLogEvent(vault, {
@@ -222,7 +238,10 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
});
return 0;
}
- ok(`signal: ${sigResult.path}`);
+ // Vault-relative, matching the distill house style: the absolute host
+ // path is the operator-supplied vault prefix composed with a
+ // machine-derived subtree.
+ ok(`signal: ${canonicalNotePath(relative(vault, sigResult.path))}`);
ok(`id: ${sigResult.id}`);
if (mirror !== undefined) {
ok(`mirror: ${mirror.outcome}`);
@@ -255,7 +274,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {
emitNextStep(routingHint.code, stream);
}
if (prefResult) {
- ok(`preference: ${prefResult.path}`);
+ ok(`preference: ${canonicalNotePath(relative(vault, prefResult.path))}`);
ok(`status: confirmed`);
}
return 0;
diff --git a/src/cli/brain/verbs/import-claude-memory.ts b/src/cli/brain/verbs/import-claude-memory.ts
index 7056d58c..7bda750f 100644
--- a/src/cli/brain/verbs/import-claude-memory.ts
+++ b/src/cli/brain/verbs/import-claude-memory.ts
@@ -17,6 +17,7 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
let asJson = false;
let vaultFlag: string | undefined;
let backendId: string | undefined;
+ let approvalDigest: string | undefined;
const consumeValue = (flag: string, next: string | undefined): string | null => {
if (next === undefined || next.startsWith("--")) {
@@ -72,6 +73,12 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
yes = true;
continue;
}
+ if (a === "--approval-digest") {
+ const v = consumeValue("--approval-digest", argv[++i]);
+ if (v === null) return 2;
+ approvalDigest = v;
+ continue;
+ }
if (a === "--json") {
asJson = true;
continue;
@@ -84,6 +91,18 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
return 2;
}
+ // A dry run COMPUTES a digest; it cannot consume one. A digest paired with
+ // a dry run (the default mode included) is an operator mistake whose exit
+ // code would otherwise suggest the value was honored when it was silently
+ // dropped - refuse the pairing by name instead.
+ if (mode !== "apply" && approvalDigest !== undefined) {
+ process.stderr.write(
+ "o2b brain import-claude-memory: --approval-digest applies to --apply; " +
+ "a dry run computes a digest, it does not consume one\n",
+ );
+ return 2;
+ }
+
if (mode === "apply" && !yes && !process.stdin.isTTY) {
process.stderr.write(
"o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n",
@@ -91,6 +110,17 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
return 2;
}
+ // t_18fda844: a script that applies must apply the plan it approved.
+ // The digest comes from a prior `--dry-run`; an interactive operator
+ // keeps the human escape hatch, exactly as with `--yes`.
+ if (mode === "apply" && approvalDigest === undefined && !process.stdin.isTTY) {
+ process.stderr.write(
+ "o2b brain import-claude-memory: --apply requires --approval-digest in non-interactive " +
+ "mode (run --dry-run first, then apply with the digest it prints)\n",
+ );
+ return 2;
+ }
+
const vault = resolveBrainVault(vaultFlag, config);
try {
@@ -107,6 +137,7 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
memoryDir: memDir,
mode,
allowArbitraryMemoryPath: allowArbitrary,
+ approvalDigest,
backend,
});
if (asJson) {
@@ -115,6 +146,7 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number
}
if (mode === "dry-run") {
process.stdout.write(`plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`);
+ process.stdout.write(`approval-digest: ${res.digest}\n`);
for (const p of res.plans)
process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);
for (const s of res.skipped) process.stdout.write(` SKIP ${s.basename}: ${s.reason}\n`);
diff --git a/src/cli/brain/verbs/secret.ts b/src/cli/brain/verbs/secret.ts
index c13f32cf..5df0c6e0 100644
--- a/src/cli/brain/verbs/secret.ts
+++ b/src/cli/brain/verbs/secret.ts
@@ -1,29 +1,98 @@
/**
- * `o2b brain secret <set|list|rm|run>` (t_0b134404): capability-gated
- * secret custody. `set` ingests the value from stdin or --from-env -
- * NEVER from argv, where it would land in shell history and process
- * lists; `list` shows metadata only; `run <name> -- cmd...` injects
- * the secret into an allowlisted subprocess env and returns redacted
- * output. No surface ever prints the value.
+ * `o2b brain secret <set|list|rm|run|lock|unlock|export|import>`
+ * (t_0b134404, t_e6667a56, t_592d9e91): capability-gated secret custody.
+ * `set` ingests the value from stdin or --from-env - NEVER from argv,
+ * where it would land in shell history and process lists; `list` shows
+ * metadata only; `run <name> -- cmd...` injects the secret into an
+ * allowlisted subprocess env and returns redacted output; `unlock` wraps
+ * the keyfile under a passphrase (first unlock) and holds the key for
+ * this process only; `lock` clears that holder; `export` writes every
+ * entry as one passphrase-encrypted bundle to an operator-named `--out`,
+ * with the shared egress redactor run over the bundle's non-ciphertext
+ * metadata tree; `import` restores a bundle. No surface ever prints a
+ * value or a passphrase.
+ *
+ * A LOST PASSPHRASE IS UNRECOVERABLE: after `unlock` has wrapped the
+ * keyfile, the stored values stay unreadable forever without it - and a
+ * lost bundle passphrase loses the bundle. There is no recovery path and
+ * none is pretended.
*
* Exit codes: 0 on success (run: the subprocess exit code), 1 on an
* operational failure, 2 on usage errors.
*/
+import { readFileSync } from "node:fs";
+
import { resolveAgentName } from "../../../core/config.ts";
+import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
import { runWithSecret, SecretExecDeniedError } from "../../../core/brain/secrets/exec.ts";
-import { listSecrets, removeSecret, setSecret } from "../../../core/brain/secrets/store.ts";
+import {
+ bundleEgressScanTree,
+ bundleFromEgressScan,
+ exportSecretBundle,
+ importSecretBundle,
+} from "../../../core/brain/secrets/bundle.ts";
+import {
+ listSecrets,
+ lockSecretKeyfile,
+ removeSecret,
+ setSecret,
+ unlockSecretKeyfile,
+} from "../../../core/brain/secrets/store.ts";
import {
formatSecretsSyncExposure,
+ formatWrappedKeyfileExposure,
secretsSyncExposure,
} from "../../../core/brain/secrets/sync-exposure.ts";
+import { EGRESS_REDACTION_NOTICE, redactForEgress } from "../../../core/egress/guard.ts";
+import { SECRET_VERB_USAGE, secretOpAccepts } from "../help-text.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
import { readStdinText } from "../../stdin.ts";
-const USAGE =
- "usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] [--vault <path>] [--json] | " +
- "list [--vault <path>] [--json] | rm <name> [--vault <path>] | " +
- "run <name> [--agent N] [--vault <path>] [--json] -- <command...>";
+// Assembled from the same per-op flag tables `o2b brain secret --help`
+// renders (help-text.ts), so the two surfaces cannot drift apart.
+const USAGE = SECRET_VERB_USAGE;
+
+/** Success notes, hoisted: stdout is contract, not prose. */
+const UNLOCKED_NOTE =
+ "keyfile unlocked for this process; the passphrase is held in memory only and never written";
+const LOCKED_NOTE = "keyfile locked; this process's unlocked-key holder is cleared";
+
+/** The declared egress site of the bundle export (src/core/egress/registry.ts). */
+const BUNDLE_EGRESS_SITE = "brain-secret-bundle-export" as const;
+
+/**
+ * Ingest the passphrase the way `set` ingests a value: `--passphrase-from-env`
+ * or stdin, never argv. The passphrase must never land in shell history or a
+ * process list - it protects every stored value after the first unlock. Both
+ * routes enforce ONE blankness rule - a value that is empty after trim is not
+ * a passphrase - so `SECRET_PASS=" "` cannot wrap the keyfile the way an
+ * unset-variable accident through the stdin route cannot.
+ */
+async function ingestPassphrase(
+ op: string,
+ flags: Record<string, string | boolean | string[] | undefined>,
+): Promise<{ passphrase: string } | { exitCode: number }> {
+ const fromEnv = flags["passphrase-from-env"] as string | undefined;
+ if (fromEnv !== undefined) {
+ const value = process.env[fromEnv];
+ if (value === undefined || value.trim().length === 0) {
+ process.stderr.write(
+ `brain secret ${op}: env var ${fromEnv} is unset, empty, or blank; set it to a passphrase, or pipe the passphrase via stdin\n`,
+ );
+ return { exitCode: 2 };
+ }
+ return { passphrase: value };
+ }
+ const passphrase = (await readStdinText()).replace(/\r?\n$/, "");
+ if (passphrase.trim().length === 0) {
+ process.stderr.write(
+ `brain secret ${op}: pipe the passphrase via stdin or pass --passphrase-from-env SRC\n`,
+ );
+ return { exitCode: 2 };
+ }
+ return { passphrase };
+}
export async function cmdBrainSecret(argv: string[]): Promise<number> {
// `run <name> -- cmd...`: everything after `--` belongs to the
@@ -37,18 +106,42 @@ export async function cmdBrainSecret(argv: string[]): Promise<number> {
"env-var": { type: "string" },
allow: { type: "string-array" },
"from-env": { type: "string" },
+ "passphrase-from-env": { type: "string" },
+ out: { type: "string" },
+ replace: { type: "boolean" },
agent: { type: "string" },
json: { type: "boolean" },
});
const op = positional[0];
const asJson = flags["json"] === true;
- if (op !== "set" && op !== "list" && op !== "rm" && op !== "run") {
+ if (
+ op !== "set" &&
+ op !== "list" &&
+ op !== "rm" &&
+ op !== "run" &&
+ op !== "lock" &&
+ op !== "unlock" &&
+ op !== "export" &&
+ op !== "import"
+ ) {
process.stderr.write(`${USAGE}\n`);
return 2;
}
+ // An op that never documents a flag refuses it by name instead of
+ // silently swallowing it while its effect never happens: the parse
+ // table is op-independent, so without this check `lock
+ // --passphrase-from-env SRC` would exit 0 having read nothing.
+ for (const flag of Object.keys(flags)) {
+ if (!secretOpAccepts(op, flag)) {
+ process.stderr.write(`brain secret ${op}: unknown flag --${flag}\n${USAGE}\n`);
+ return 2;
+ }
+ }
const name = positional[1];
- if (op !== "list" && !name) {
- process.stderr.write(`brain secret ${op}: a secret name is required\n${USAGE}\n`);
+ const needsName = op === "set" || op === "rm" || op === "run" || op === "import";
+ if (needsName && !name) {
+ const what = op === "import" ? "a bundle file path is required" : "a secret name is required";
+ process.stderr.write(`brain secret ${op}: ${what}\n${USAGE}\n`);
return 2;
}
@@ -64,7 +157,9 @@ export async function cmdBrainSecret(argv: string[]): Promise<number> {
if (fromEnv !== undefined) {
const fromEnvValue = process.env[fromEnv];
if (fromEnvValue === undefined || fromEnvValue.length === 0) {
- process.stderr.write(`brain secret set: env var ${fromEnv} is unset or empty\n`);
+ process.stderr.write(
+ `brain secret set: env var ${fromEnv} is unset or empty; set it to a value, or pipe the value via stdin\n`,
+ );
return 2;
}
value = fromEnvValue;
@@ -116,6 +211,80 @@ export async function cmdBrainSecret(argv: string[]): Promise<number> {
else ok(`secret removed: ${name}`);
return 0;
}
+ case "unlock": {
+ const ingested = await ingestPassphrase("unlock", flags);
+ if ("exitCode" in ingested) return ingested.exitCode;
+ // Wrap-on-first-unlock: on a store whose keyfile is still raw,
+ // THIS is the opt-in. From then on the passphrase is the only key
+ // to every stored value, and losing it loses them.
+ unlockSecretKeyfile(vault, ingested.passphrase, { agent, now });
+ // Say what a synced folder now carries: the envelope travels to
+ // every peer, where the passphrase is the protection left.
+ const exposure = secretsSyncExposure(vault);
+ if (exposure !== null) {
+ process.stderr.write(`warning: ${formatWrappedKeyfileExposure(exposure)}\n`);
+ }
+ if (asJson) okJson({ unlocked: true });
+ else ok(UNLOCKED_NOTE);
+ return 0;
+ }
+ case "lock": {
+ lockSecretKeyfile(vault, { agent, now });
+ if (asJson) okJson({ locked: true });
+ else ok(LOCKED_NOTE);
+ return 0;
+ }
+ case "export": {
+ const out = flags["out"] as string | undefined;
+ if (out === undefined || out.length === 0) {
+ process.stderr.write(`brain secret export: --out FILE is required\n${USAGE}\n`);
+ return 2;
+ }
+ const ingested = await ingestPassphrase("export", flags);
+ if ("exitCode" in ingested) return ingested.exitCode;
+ const bundle = exportSecretBundle(vault, ingested.passphrase, { agent, now });
+ // The destination is operator-named and leaves the machine, so the
+ // shared egress guard runs before any byte is written - over the
+ // bundle's metadata inventory (see bundleEgressScanTree for what is
+ // deliberately out of the tree). A redacted allow pattern merges;
+ // a rewritten entry identifier refuses.
+ const verdict = redactForEgress(BUNDLE_EGRESS_SITE, bundleEgressScanTree(bundle));
+ if (verdict.outcome !== "released") {
+ return fail(`secret export: ${verdict.detail}`);
+ }
+ const payload = verdict.redacted ? bundleFromEgressScan(bundle, verdict.payload) : bundle;
+ atomicWriteFileSync(out, `${JSON.stringify(payload, null, 2)}\n`);
+ if (verdict.redacted) process.stderr.write(EGRESS_REDACTION_NOTICE);
+ if (asJson) okJson({ out, exported: Object.keys(bundle.entries).length });
+ else ok(`secret bundle exported: ${Object.keys(bundle.entries).length} entries -> ${out}`);
+ return 0;
+ }
+ case "import": {
+ const ingested = await ingestPassphrase("import", flags);
+ if ("exitCode" in ingested) return ingested.exitCode;
+ let bundle: unknown;
+ try {
+ bundle = JSON.parse(readFileSync(name!, "utf8"));
+ } catch (err) {
+ return fail(
+ `secret import: the bundle file is unreadable or not JSON: ${name!}: ` +
+ `${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ const result = importSecretBundle(vault, bundle, {
+ passphrase: ingested.passphrase,
+ replace: flags["replace"] === true,
+ agent,
+ now,
+ });
+ if (asJson) okJson({ imported: result.imported, replaced: result.replaced });
+ else
+ ok(
+ `secret bundle imported: ${result.imported.length} entries ` +
+ `(${result.replaced.length} replaced)`,
+ );
+ return 0;
+ }
case "run": {
if (commandArgs.length === 0) {
process.stderr.write(`brain secret run: a command is required after --\n${USAGE}\n`);
diff --git a/src/cli/brain/verbs/session-summary.ts b/src/cli/brain/verbs/session-summary.ts
index 4601a715..a0aac52a 100644
--- a/src/cli/brain/verbs/session-summary.ts
+++ b/src/cli/brain/verbs/session-summary.ts
@@ -14,10 +14,12 @@
import {
appendSessionSummary,
- getSessionSummary,
+ getSessionSummaryReport,
listSessionSummaries,
SessionSummaryError,
type SessionSummaryDigest,
+ type SessionSummaryRecordRef,
+ type SessionSummaryReport,
} from "../../../core/brain/session-summary.ts";
import { brainVerbContext, fail, parse, usageError } from "../helpers.ts";
@@ -77,6 +79,21 @@ function writeSummary(argv: string[]): number {
}
}
+/**
+ * The one note line text mode appends when the session holds more than one
+ * content-differing digest (t_59d4c919). Token-shaped so an operator can
+ * grep it; the count is the honest total, the shown digest stays the
+ * sorted-latest. Divergence is reported here, never merged away.
+ */
+function divergenceNoteLine(count: number): string {
+ return `note: digest_count=${count} divergent=true (showing the sorted-latest digest)`;
+}
+
+/** Wire shape of one divergence record: identity and hash, never a payload echo. */
+function serializeRecordRef(record: SessionSummaryRecordRef): Record<string, unknown> {
+ return { id: record.id, created_at: record.createdAt, content_hash: record.contentHash };
+}
+
function getSummary(argv: string[]): number {
const { flags } = parse(argv, {
vault: { type: "string" },
@@ -87,21 +104,38 @@ function getSummary(argv: string[]): number {
if (session.length === 0) return usageError("brain session-summary get: --session is required");
const vault = brainVerbContext(flags).vault;
- const digest = getSessionSummary(vault, session);
+ const report = getSessionSummaryReport(vault, session);
if (flags["json"] === true) {
- process.stdout.write(
- `${JSON.stringify(digest === null ? { found: false } : { found: true, digest: serialize(digest) }, null, 2)}\n`,
- );
+ process.stdout.write(`${JSON.stringify(serializeReport(report), null, 2)}\n`);
return 0;
}
- if (digest === null) {
+ if (report === null) {
process.stdout.write(`no session summary for ${session}\n`);
return 0;
}
- process.stdout.write(renderDigest(digest));
+ process.stdout.write(renderDigest(report.digest));
+ if (report.divergent === true) {
+ process.stdout.write(`${divergenceNoteLine(report.digestCount)}\n`);
+ }
return 0;
}
+/** The get envelope: additive divergence fields only when the session diverges. */
+function serializeReport(report: SessionSummaryReport | null): Record<string, unknown> {
+ if (report === null) return { found: false };
+ return {
+ found: true,
+ digest: serialize(report.digest),
+ digest_count: report.digestCount,
+ ...(report.divergent === true
+ ? {
+ divergent: true,
+ records: (report.records ?? []).map(serializeRecordRef),
+ }
+ : {}),
+ };
+}
+
function listSummaries(argv: string[]): number {
const { flags } = parse(argv, {
vault: { type: "string" },
@@ -143,6 +177,9 @@ function serialize(digest: SessionSummaryDigest): Record<string, unknown> {
next_steps: digest.nextSteps,
created_at: digest.createdAt,
...(digest.host !== undefined ? { host: digest.host } : {}),
+ // Same field the MCP serializer carries; dropping it here was the
+ // verified CLI/MCP drift (t_59d4c919).
+ ...(digest.project !== undefined ? { project: digest.project } : {}),
};
}
diff --git a/src/cli/brain/verbs/skill-proposals.ts b/src/cli/brain/verbs/skill-proposals.ts
index 391b9ad9..a1153cc3 100644
--- a/src/cli/brain/verbs/skill-proposals.ts
+++ b/src/cli/brain/verbs/skill-proposals.ts
@@ -1,7 +1,9 @@
import { readFileSync } from "node:fs";
+import { relative } from "node:path";
import { resolveSkillsDir } from "../../../core/config.ts";
import {
+ SkillPageDraftError,
commitSkillPageDraft,
planSkillPageDrafts,
} from "../../../core/brain/skill-page-drafts.ts";
@@ -14,6 +16,15 @@ import {
rejectSkillProposal,
} from "../../../core/brain/skill-proposals.ts";
import { deriveSkillUsage } from "../../../core/brain/skill-usage.ts";
+import { ResponseShapeError } from "../../../core/brain/response-shape.ts";
+import { ResponseCheckError } from "../../../core/brain/response-checks.ts";
+import {
+ parsePayloadJson,
+ PayloadJsonError,
+ payloadStripNote,
+ type PayloadStrip,
+} from "../../../core/brain/payload-json.ts";
+import { canonicalNotePath } from "../../../core/path-safety.ts";
import { CliError, brainVerbContext, failWith, parse } from "../helpers.ts";
export async function cmdBrainSkillProposals(argv: string[]): Promise<number> {
@@ -118,21 +129,59 @@ function pageDraft(argv: string[]): number {
throw new CliError("brain skill-proposals page-draft: --payload or --payload-file is required");
}
let payload: unknown;
+ let strip: PayloadStrip | undefined;
try {
- payload = JSON.parse(raw);
- } catch {
- throw new CliError("brain skill-proposals page-draft: payload must be valid JSON");
+ const parsed = parsePayloadJson(raw);
+ payload = parsed.payload;
+ strip = parsed.strip;
+ } catch (error) {
+ // Reported here rather than by the ingress: at this point the mistake
+ // is the JSON the operator typed. A refusal after a strip attempt names
+ // the attempt (t_dac8bf7e); plain garbage keeps the plain refusal.
+ if (!(error instanceof PayloadJsonError)) throw error;
+ throw new CliError(`brain skill-proposals page-draft: ${error.message}`);
}
const vault = brainVerbContext(flags).vault;
- const result = commitSkillPageDraft(vault, page, payload, { now: new Date() });
+ // The commit path's refusals are operator mistakes (a blank field, a page
+ // that is not there), not crashes: caught here and rethrown with the same
+ // stable prefix the parse path uses, so the runner never dumps a stack
+ // trace with machine-derived source paths where a refusal belongs.
+ let result: ReturnType<typeof commitSkillPageDraft>;
+ try {
+ result = commitSkillPageDraft(vault, page, payload, { now: new Date() });
+ } catch (error) {
+ if (
+ error instanceof SkillPageDraftError ||
+ error instanceof ResponseShapeError ||
+ error instanceof ResponseCheckError
+ ) {
+ throw new CliError(`brain skill-proposals page-draft: ${error.message}`);
+ }
+ throw error;
+ }
if (flags["json"]) {
- process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ process.stdout.write(
+ JSON.stringify(
+ {
+ ...result,
+ // Vault-relative, like the distill and MCP surfaces: the absolute
+ // host path is the operator-supplied vault prefix composed with a
+ // machine-derived subtree, and this output lands in model context.
+ path: canonicalNotePath(relative(vault, result.path)),
+ // Present only when a leading <think> block was stripped (t_dac8bf7e).
+ ...(strip !== undefined ? { note: payloadStripNote(strip) } : {}),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
return 0;
}
process.stdout.write(
`${result.outcome} ${result.id}` + ("reason" in result ? ` (${result.reason})` : "") + `\n`,
);
+ if (strip !== undefined) process.stdout.write(`${payloadStripNote(strip)}\n`);
return 0;
}
diff --git a/src/cli/brain/verbs/telegram-capture.ts b/src/cli/brain/verbs/telegram-capture.ts
index f12ebc16..726a5b50 100644
--- a/src/cli/brain/verbs/telegram-capture.ts
+++ b/src/cli/brain/verbs/telegram-capture.ts
@@ -45,7 +45,9 @@ export async function cmdBrainTelegramCapture(argv: string[]): Promise<number> {
// action === "run"
let token: string;
try {
- token = requireTelegramToken(resolveTelegramBotToken(config));
+ // The vault's custody store backs a `$secret:NAME` token reference; a
+ // plain token (env or config) resolves exactly as before.
+ token = requireTelegramToken(resolveTelegramBotToken(config, vault));
} catch (err) {
return fail((err as Error).message);
}
diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.ts
index aa51e3e3..f7963969 100644
--- a/src/cli/brain/verbs/upgrade.ts
+++ b/src/cli/brain/verbs/upgrade.ts
@@ -4,6 +4,7 @@ import {
BrainUpgradeError,
type UpgradePlan,
} from "../../../core/brain/upgrade.ts";
+import { basename } from "node:path";
import {
brainVerbContext,
describeErrorChain,
@@ -172,7 +173,11 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {
});
} else {
ok(`run_id: ${result.run_id}`);
- ok(`snapshot: ${result.snapshot_path}`);
+ // Vault-relative, not the resolved path: the snapshot location is
+ // machine-derived, and the file name is already pinned by the run id
+ // printed directly above. The JSON twin keeps `snapshot_path` for
+ // consumers that need the resolved location.
+ ok(`snapshot: Brain/.snapshots/${basename(result.snapshot_path)}`);
for (const p of result.files_updated) ok(` updated: ${p}`);
}
return 0;
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 3c5368d9..a32f6ed2 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -122,9 +122,13 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
[
command("list", "List $secret:NAME references found in the config", [
flag("config", "string"),
+ flag("vault", "string"),
+ flag("json", "boolean"),
]),
command("status", "Report whether each referenced secret resolves", [
flag("config", "string"),
+ flag("vault", "string"),
+ flag("json", "boolean"),
]),
],
),
@@ -303,7 +307,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("label", "Assign, remove, show or suggest controlled-vocabulary labels"),
command("attr", "Assign, remove, or show typed-page attribute fields"),
command("tiers", "Check, restore, or accept identity-field drift"),
- command("secret", "Capability-gated secret custody: set, list, rm, run"),
+ command(
+ "secret",
+ "Capability-gated secret custody: set, list, rm, run, lock, unlock, export, import",
+ ),
command(
"maintenance",
"Quiet-window, lease-guarded heavy maintenance lane",
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 6a106ad0..9558e88f 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -22,6 +22,7 @@ import {
import { BrainConfigError } from "../core/brain/policy/errors.ts";
import { EGRESS_OUTCOME, redactForEgress } from "../core/egress/guard.ts";
import { listSecretReferences } from "../core/secret-ref.ts";
+import { listNamedSecretAvailability, namedSecretAvailable } from "../core/secret-resolver.ts";
import { BRAIN_INDEX_REL } from "../core/brain/paths.ts";
import { ensureVaultCurrent } from "../core/maintenance/ensure-current.ts";
import { checkSelfHealUpgrade } from "../core/maintenance/self-heal-upgrade-state.ts";
@@ -52,6 +53,7 @@ import { installMcpFaultGuard } from "./mcp-fault-guard.ts";
import { handleVaultSubcommand } from "./vault.ts";
import {
NoVaultConfiguredError,
+ normalizeFlagString,
requireVault,
resolveSemanticConfigState,
sortedReplacer,
@@ -610,7 +612,13 @@ async function cmdExportConfig(argv: string[]): Promise<number> {
async function cmdSecrets(argv: string[]): Promise<number> {
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
- process.stdout.write("usage: o2b secrets list|status [args...]\n");
+ // The one clarification the two surfaces cannot state inline: without
+ // --vault the fallback reads the reference name itself, so a store
+ // name and its env-var spelling can disagree without either lying.
+ process.stdout.write(
+ "usage: o2b secrets list|status [args...]\n" +
+ "Without --vault, the env fallback reads the reference name verbatim, case-sensitively.\n",
+ );
return argv.length === 0 ? 2 : 0;
}
const verb = argv[0]!;
@@ -630,6 +638,7 @@ function cmdSecretsList(argv: string[]): number {
const { flags, positional } = parseFlags(argv, {
config: { type: "string" },
json: { type: "boolean" },
+ vault: { type: "string" },
});
if (positional.length > 0) {
process.stderr.write(
@@ -638,7 +647,14 @@ function cmdSecretsList(argv: string[]): number {
return 2;
}
const discovery = discoverConfig(flags["config"] as string | undefined);
- const refs = listSecretReferences(discovery.data, process.env);
+ // With `--vault`, availability joins the vault's custody store (metadata
+ // only - a locked envelope still counts); without it, the env-only
+ // lookup exactly as before.
+ const vault = normalizeFlagString(flags["vault"]);
+ const refs =
+ vault !== null
+ ? listNamedSecretAvailability(vault, discovery.data)
+ : listSecretReferences(discovery.data, process.env);
if (flags["json"]) {
process.stdout.write(
JSON.stringify(
@@ -649,6 +665,10 @@ function cmdSecretsList(argv: string[]): number {
config_key: ref.configKey,
name: ref.name,
available: ref.available,
+ // Present only on a reference the grammar cannot spell - a
+ // value that refuses at use time no matter what the store or
+ // the environment holds (additive-only row shape).
+ ...(ref.invalid === true ? { invalid: true } : {}),
})),
},
null,
@@ -658,9 +678,9 @@ function cmdSecretsList(argv: string[]): number {
return 0;
}
for (const ref of refs) {
- process.stdout.write(
- `${ref.configKey}: ${ref.name} (${ref.available ? "available" : "missing"})\n`,
- );
+ const state =
+ ref.invalid === true ? "invalid reference" : ref.available ? "available" : "missing";
+ process.stdout.write(`${ref.configKey}: ${ref.name} (${state})\n`);
}
return 0;
}
@@ -669,6 +689,7 @@ function cmdSecretsStatus(argv: string[]): number {
const { flags, positional } = parseFlags(argv, {
config: { type: "string" },
json: { type: "boolean" },
+ vault: { type: "string" },
});
if (positional.length !== 1) {
process.stderr.write("error: secrets status requires exactly one secret name\n");
@@ -676,7 +697,12 @@ function cmdSecretsStatus(argv: string[]): number {
}
void flags["config"];
const name = positional[0]!;
- const available = Boolean(process.env[name]);
+ // With `--vault`, a store-held name counts as available from metadata
+ // alone (a locked envelope still counts, no decrypt); without it, the
+ // env-only lookup exactly as before. The exit-code contract is
+ // unchanged: available exits 0, missing exits 1.
+ const vault = normalizeFlagString(flags["vault"]);
+ const available = vault !== null ? namedSecretAvailable(vault, name) : Boolean(process.env[name]);
if (flags["json"]) {
process.stdout.write(JSON.stringify({ name, available }, null, 2) + "\n");
} else {
@@ -1217,7 +1243,10 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
(rest[0] === "-h" || rest[0] === "--help") &&
command !== "aider" &&
command !== "brain" &&
- command !== "vault"
+ command !== "vault" &&
+ // `secrets` has its own two-line help (the env fallback's name read
+ // is spelled there), so the generic URL stub would only bury it.
+ command !== "secrets"
) {
process.stdout.write(`${command}: see https://github.com/itechmeat/open-second-brain\n`);
if (command === "uninstall") {
diff --git a/src/core/brain/capture/capture-note.ts b/src/core/brain/capture/capture-note.ts
index f47ff67d..08476271 100644
--- a/src/core/brain/capture/capture-note.ts
+++ b/src/core/brain/capture/capture-note.ts
@@ -47,6 +47,7 @@ import {
vaultRelative,
} from "../paths.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { declaredPageTypes } from "../schema-pack.ts";
/** Frontmatter `kind:` marker of a staged inbound capture. */
export const BRAIN_CAPTURE_KIND = "brain-capture";
@@ -115,6 +116,30 @@ function requireNonEmpty(value: string, label: string): string {
return trimmed;
}
+/** Remedy carried by every undeclared-kind refusal. */
+const DECLARE_KIND_REMEDY = "declare it in Brain/_brain.yaml under schema.page_types to accept it";
+
+/**
+ * Refuse a stamped `kind` the vault's pack does not declare
+ * (trust-surface-hardening wave; kanban t_151a564c).
+ *
+ * Consulted only where the vault made a declaration: {@link declaredPageTypes}
+ * returns `null` for an absent or declaration-free config, and that fails
+ * open - today's behavior, byte for byte. A non-null declaration that omits
+ * the kind refuses with this module's typed error naming the kind, the
+ * declared set, and the remedy. Callers run this BEFORE any filesystem
+ * effect, so a refused capture never creates a directory and never
+ * consumes an allocator name.
+ */
+export function requireDeclaredCaptureKind(vault: string, kind: string): void {
+ const declared = declaredPageTypes(vault);
+ if (declared === null || declared.includes(kind)) return;
+ throw new CaptureContractError(
+ `capture kind '${kind}' is not declared in this vault's schema.page_types ` +
+ `(declared: ${declared.join(", ")}); ${DECLARE_KIND_REMEDY}`,
+ );
+}
+
/**
* Derive the filename stem from the capture timestamp plus a short content
* hash. The date-then-time prefix makes lexical order match chronological
@@ -217,6 +242,10 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu
const guidance =
input.guidance === undefined ? null : requireNonEmpty(input.guidance, "guidance");
+ // Pack vocabulary gate (t_151a564c), before ANY filesystem effect: a
+ // refused capture creates no directory and consumes no allocator name.
+ requireDeclaredCaptureKind(vault, BRAIN_CAPTURE_KIND);
+
const dir = capturesDir(vault);
mkdirSync(dir, { recursive: true });
const { prefix, slug } = captureBaseId(body, { source, sender, capturedAt }, guidance);
diff --git a/src/core/brain/capture/inbox-drain.ts b/src/core/brain/capture/inbox-drain.ts
index ad3c98af..bdab8466 100644
--- a/src/core/brain/capture/inbox-drain.ts
+++ b/src/core/brain/capture/inbox-drain.ts
@@ -46,7 +46,13 @@ import {
stageHubSelection,
type HubPagePool,
} from "../link-graph/hub-candidates.ts";
-import { archiveCapture, listStagedCaptures, type CaptureNote } from "./capture-note.ts";
+import {
+ archiveCapture,
+ CaptureContractError,
+ listStagedCaptures,
+ requireDeclaredCaptureKind,
+ type CaptureNote,
+} from "./capture-note.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Explicit leading token that classifies a capture as an obligation. */
@@ -186,7 +192,19 @@ function planSource(vault: string, url: string, opts: DrainOptions): RoutePlan {
};
}
-function planIdea(vault: string, body: string, opts: DrainOptions): RoutePlan {
+function planIdea(vault: string, body: string, opts: DrainOptions): RoutePlan | UnroutableCapture {
+ // Pack vocabulary gate (t_151a564c), consulted at PLAN time so a dry run is
+ // a faithful preview: the idea route stamps `captured-idea`, so a vault
+ // that declares page_types without it is unroutable in BOTH modes with the
+ // same named refusal - the capture stays staged and a rerun after the
+ // operator declares the kind converges. Same gate, same refusal text, as
+ // the staging contract's own writer.
+ try {
+ requireDeclaredCaptureKind(vault, CAPTURED_IDEA_KIND);
+ } catch (err) {
+ if (!(err instanceof CaptureContractError)) throw err;
+ return new UnroutableCapture(err.message);
+ }
const slug = slugify(body);
const relPath = `${CAPTURED_NOTES_DIR_REL}/${slug}.md`;
const abs = ensureInsideVault(join(vault, relPath), vault);
@@ -196,13 +214,22 @@ function planIdea(vault: string, body: string, opts: DrainOptions): RoutePlan {
action: "note",
reason: merge ? "atomic idea (merge into existing note)" : "atomic idea (create note)",
execute: () => {
- writeIdeaNote(abs, body, opts, merge);
+ writeIdeaNote(vault, abs, body, opts, merge);
return relPath;
},
};
}
-function writeIdeaNote(abs: string, body: string, opts: DrainOptions, merge: boolean): void {
+function writeIdeaNote(
+ vault: string,
+ abs: string,
+ body: string,
+ opts: DrainOptions,
+ merge: boolean,
+): void {
+ // The declared-vocabulary gate lives in `planIdea`, the classifier, so the
+ // dry-run plan and the apply see the same refusal (t_151a564c); by execute
+ // time the route is known declared, and nothing here writes before it.
const stamp = isoSecond(opts.now);
// `ensureInsideVault` hands back a native path, so the parent comes from
// `dirname`: a hand-rolled split on "/" found no separator in a Windows
diff --git a/src/core/brain/claude-memory-paths.ts b/src/core/brain/claude-memory-paths.ts
index 507b1184..113a79b6 100644
--- a/src/core/brain/claude-memory-paths.ts
+++ b/src/core/brain/claude-memory-paths.ts
@@ -15,6 +15,26 @@ export function defaultMemoryDir(vault: string): string {
return resolve(homedir(), ".claude", "projects", slug, "memory");
}
+/**
+ * Render a path under the operator's home directory home-relative (`~/...`),
+ * any other path verbatim. The default memory location is derived from
+ * `homedir()`, so a refusal about that location must not expand the home
+ * into output - the sibling safety refusal already spells the directory as
+ * `~/.claude/projects/`, and operator-supplied arguments keep their verbatim
+ * echo.
+ */
+export function homeRelativePath(p: string): string {
+ const home = resolve(homedir());
+ const abs = resolve(p);
+ if (abs === home) return "~";
+ if (abs.startsWith(home + sep)) {
+ // Display form: forward slashes on every platform, matching the
+ // `~/.claude/projects/` spelling this refusal's siblings use.
+ return `~${abs.slice(home.length).split(sep).join("/")}`;
+ }
+ return p;
+}
+
/**
* Refuse to import from anywhere outside `~/.claude/projects/`. The
* comparison runs after `realpathSync` so a symlink pointing to a
diff --git a/src/core/brain/claude-memory-render.ts b/src/core/brain/claude-memory-render.ts
index 26fb9af5..fe7ca720 100644
--- a/src/core/brain/claude-memory-render.ts
+++ b/src/core/brain/claude-memory-render.ts
@@ -1,3 +1,5 @@
+import { requireObsidianTagValue } from "./tag-syntax.ts";
+
export interface RenderMemoryInput {
readonly name: string;
readonly description: string;
@@ -61,9 +63,16 @@ export function renderPreferenceFromMemory(input: RenderMemoryInput): string {
`claude-memory: cannot derive a slug from name ${JSON.stringify(input.name)}; rename the memory entry to include at least one alphanumeric character`,
);
}
+ // The derived topic/scope are validated against the one shared tag rule
+ // (t_11ee559f). Both are slugified by construction, so this is a pin -
+ // except a purely numeric name, whose slug still fails the rule and
+ // refuses here with the field named rather than landing an unparseable
+ // frontmatter tag. The import loop treats that refusal as a per-entry
+ // disposition - a named skip row, import continues - so one legacy
+ // MEMORY file cannot abort the whole run.
const prefId = `pref-${slug}`;
- const topic = slug;
- const scope = extractScope(input.body);
+ const topic = requireObsidianTagValue(slug, "topic");
+ const scope = requireObsidianTagValue(extractScope(input.body), "scope");
// The import lands UNDER TRIAL, not confirmed. MEMORY.md is
// session-derived - agent-writable from conversation content - so a
// poisoned entry must not become a live rule on landing; it gets the
diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.ts
index 9b514f24..70046e72 100644
--- a/src/core/brain/continuity/store.ts
+++ b/src/core/brain/continuity/store.ts
@@ -407,11 +407,14 @@ function readAllRecords(vault: string, filter: ContinuityRecordFilter = {}): Con
line++;
}
}
- return mergeShardedRows(
- rows,
- (record) => record.createdAt,
- (record) => record.id,
- );
+ // The append-only file is the authority when timestamps tie: rows the
+ // same writer appended within one timestamp precision read in append
+ // order, never in the arbitrary order of their content-hash ids (two
+ // same-instant records hash to ids whose lexical order says nothing
+ // about which was written first - "latest wins" reads would answer
+ // randomly). Cross-shard ties still order by shard id below, because
+ // two devices' arrival orders genuinely cannot be known.
+ return mergeShardedRows(rows, (record) => record.createdAt);
}
function matches(record: ContinuityRecord, filter: ContinuityRecordFilter): boolean {
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index 697cac12..e5d95b3f 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -362,6 +362,17 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
"is deliberately outside every snapshot archive, so its safety comes from the " +
"atomicity of the swap and not from a recovery point.",
},
+ "src/core/brain/secrets/envelope.ts": {
+ calls: ["renameSync", "unlinkSync"],
+ recovery: UNARCHIVED_OUTSIDE,
+ reason:
+ "wraps the plaintext keyfile into a passphrase-verified envelope through a " +
+ "tmp-plus-rename swap that lands at mode 0600, and the unlink is only the tmp " +
+ "whose wrap failed, so the displaced bytes are the keyfile the envelope just " +
+ "replaced and the wrapping passphrase re-derives the key it protects - a lost " +
+ "passphrase is the documented, permanent loss. The custody state sits outside " +
+ "every snapshot archive by design.",
+ },
// --- Two-phase accept with a journalled rollback ---------------------
"src/core/brain/skill-proposals.ts": {
diff --git a/src/core/brain/extract-signals-prefilter.ts b/src/core/brain/extract-signals-prefilter.ts
index ccf7e24f..ebbf7e9e 100644
--- a/src/core/brain/extract-signals-prefilter.ts
+++ b/src/core/brain/extract-signals-prefilter.ts
@@ -228,7 +228,7 @@ export async function planExtractSignalsPrefiltered(
): Promise<PrefilteredSignalExtractionPlan> {
const cfg = opts.decisionModel;
if (!extractPrefilterActive(cfg)) return planExtractSignals(vault, sessionId, { now: opts.now });
- const provider = opts.provider ?? makeDecisionProvider(cfg, opts.env ?? process.env);
+ const provider = opts.provider ?? makeDecisionProvider(cfg, opts.env ?? process.env, vault);
if (provider === null) return planExtractSignals(vault, sessionId, { now: opts.now });
const full = planExtractSignals(vault, sessionId, { now: opts.now, sourceTurnHint: true });
@@ -271,6 +271,7 @@ export async function planExtractSignalsPrefiltered(
{
config: cfg,
provider,
+ secretsVault: vault,
...(opts.env !== undefined ? { env: opts.env } : {}),
now: () => opts.now,
recordDetails: (response) =>
diff --git a/src/core/brain/hygiene/detectors/frontmatter-tags.ts b/src/core/brain/hygiene/detectors/frontmatter-tags.ts
new file mode 100644
index 00000000..0230b68d
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/frontmatter-tags.ts
@@ -0,0 +1,99 @@
+/**
+ * Frontmatter-tags hygiene detector (trust-surface-hardening wave;
+ * kanban t_11ee559f, doctor half).
+ *
+ * Informational audit over the frontmatter `tags:` field - the one
+ * place the inline body-tags detector (`tags.ts`) explicitly scopes
+ * out. Existing vault content cannot be refused retroactively at the
+ * composers, so this detector reports what the write-time gate would
+ * have rejected: entries failing the ONE shared tag rule
+ * (`src/core/tags.ts`, {@link isObsidianTagValue} - consumed, never a
+ * local copy). The inline-array, block-sequence, and scalar spellings
+ * of the field all parse to a list of values through the shared
+ * frontmatter reader; every value is judged, empty entries skipped
+ * (no value, no finding - the inline detector's skip-empty polarity).
+ *
+ * One finding class, `severity: "info"`, `proposed_action: "review"`,
+ * grouped per distinct value across the vault (one mechanical story,
+ * one rename): `malformed` - a stored value Obsidian's own tag rule
+ * cannot parse, so the entry is invisible to tag queries and the
+ * properties editor. Detection-only; the detector never mutates
+ * anything and never auto-fixes. Opt-in like the inline detector:
+ * registered in `HYGIENE_DETECTOR_IDS`, excluded from
+ * `DEFAULT_SCAN_IDS` (a loosely-tagged legacy vault is exactly the
+ * vault that has these, and the default sweep should not drown in
+ * them uninvited).
+ *
+ * Targets run [documents..., tag value] so the shared finding-id hash
+ * stays unique per finding (one value can live on several documents,
+ * and one document can carry several distinct values).
+ */
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { listVaultNotePaths, parseFrontmatterText } from "../../../vault.ts";
+import { isObsidianTagValue } from "../../../tags.ts";
+import { hygieneFindingId } from "./id.ts";
+import type { HygieneFinding } from "../types.ts";
+
+/** The one frontmatter field this detector audits. */
+const TAGS_FIELD = "tags";
+
+/**
+ * One mechanical story behind every finding, stated in evidence - the RULE
+ * half of it. The VALUE half is prepended by the finding itself, so the
+ * reason an operator reads names both (`"foo bar" is not a parseable ...`).
+ * Exported for the test that pins that composition.
+ */
+export const MALFORMED_REASON =
+ "is not a parseable Obsidian tag value: must start with a letter or underscore and contain only letters, numbers, dashes, underscores, or slashes (never only digits)";
+
+function compareStrings(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
+/** The field's values for one document, whatever spelling stored them. */
+function frontmatterTagValues(vault: string, path: string): string[] {
+ const content = readFileSync(join(vault, path), "utf8");
+ const [metadata] = parseFrontmatterText(content);
+ const field = metadata[TAGS_FIELD];
+ if (Array.isArray(field)) return field.filter((v) => v !== "");
+ if (typeof field === "string" && field !== "") return [field];
+ return [];
+}
+
+export function detectFrontmatterTags(vault: string): ReadonlyArray<HygieneFinding> {
+ // value -> vault-relative paths carrying it, insertion-ordered then sorted.
+ const docsByValue = new Map<string, string[]>();
+ for (const path of listVaultNotePaths(vault)) {
+ for (const value of frontmatterTagValues(vault, path)) {
+ if (isObsidianTagValue(value)) continue;
+ const paths = docsByValue.get(value) ?? [];
+ paths.push(path);
+ docsByValue.set(value, paths);
+ }
+ }
+
+ const findings: HygieneFinding[] = [];
+ for (const value of [...docsByValue.keys()].toSorted(compareStrings)) {
+ const targets = [...docsByValue.get(value)!.toSorted(compareStrings), value];
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("frontmatter-tags", targets),
+ detector: "frontmatter-tags" as const,
+ severity: "info" as const,
+ title: `Malformed frontmatter tag: ${JSON.stringify(value)} is not a parseable tag value`,
+ targets: Object.freeze(targets),
+ proposed_action: "review" as const,
+ evidence: Object.freeze({
+ class: "malformed",
+ field: TAGS_FIELD,
+ tag: value,
+ reason: `${JSON.stringify(value)} ${MALFORMED_REASON}`,
+ }),
+ }),
+ );
+ }
+ return Object.freeze(findings);
+}
diff --git a/src/core/brain/hygiene/scan.ts b/src/core/brain/hygiene/scan.ts
index 7495cf23..be6b1347 100644
--- a/src/core/brain/hygiene/scan.ts
+++ b/src/core/brain/hygiene/scan.ts
@@ -14,6 +14,7 @@ import { detectCaptureScope } from "./detectors/capture-scope.ts";
import { detectConflicts } from "./detectors/conflicts.ts";
import { detectDedup } from "./detectors/dedup.ts";
import { detectFreshness } from "./detectors/freshness.ts";
+import { detectFrontmatterTags } from "./detectors/frontmatter-tags.ts";
import { detectSlugCollisions } from "./detectors/slug-collisions.ts";
import { detectTags } from "./detectors/tags.ts";
import { detectUsefulness } from "./detectors/usefulness.ts";
@@ -34,6 +35,7 @@ const DETECTORS: Readonly<Record<HygieneDetectorId, HygieneDetector>> = Object.f
usefulness: (vault, ctx) => detectUsefulness(vault, ctx),
"slug-collisions": (vault) => detectSlugCollisions(vault),
tags: (vault) => detectTags(vault),
+ "frontmatter-tags": (vault) => detectFrontmatterTags(vault),
"capture-scope": (vault, ctx) => detectCaptureScope(vault, ctx.readable),
});
diff --git a/src/core/brain/hygiene/types.ts b/src/core/brain/hygiene/types.ts
index 119e69e4..0a413200 100644
--- a/src/core/brain/hygiene/types.ts
+++ b/src/core/brain/hygiene/types.ts
@@ -16,6 +16,7 @@ export const HYGIENE_DETECTOR_IDS = [
"usefulness",
"slug-collisions",
"tags",
+ "frontmatter-tags",
"capture-scope",
] as const;
@@ -28,9 +29,12 @@ export type HygieneDetectorId = (typeof HYGIENE_DETECTOR_IDS)[number];
* OUT of the default sweep when it is too noisy to run uninvited. One
* mechanism, two explicit policies: `slug-collisions` is default-on
* (fires only on actual same-stem groups), `tags` is opt-in (noisy on
- * vaults that tag loosely), and further noisy detectors register as
- * opt-in by staying out of this list. `capture-scope` is default-on: it
- * fires only on retrievable knowledge whose every source is url-only.
+ * vaults that tag loosely), `frontmatter-tags` is opt-in for the same
+ * reason (legacy vaults with hand-written frontmatter are exactly the
+ * vaults that hold malformed entries), and further noisy detectors
+ * register as opt-in by staying out of this list. `capture-scope` is
+ * default-on: it fires only on retrievable knowledge whose every
+ * source is url-only.
*
* Members are compile-checked against the registered tuple; a registered
* id missing here is simply default-off, never an error.
diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.ts
index 18614fc4..a09cabc5 100644
--- a/src/core/brain/import-claude-memory.ts
+++ b/src/core/brain/import-claude-memory.ts
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { basename, dirname, join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { digestVerifies, sealWithDigest } from "../integrity/digest.ts";
import { appendLogEvent } from "./log.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";
import { createSnapshot } from "./snapshot.ts";
@@ -11,11 +12,12 @@ import { DEFAULT_BRAIN_CONFIG } from "./policy/defaults.ts";
import { resolveAgentName } from "../config.ts";
import { loadManifest, saveManifest } from "./claude-memory-manifest.ts";
import { planAction, type PlannedFile } from "./claude-memory-plan.ts";
-import { assertSafeMemoryPath } from "./claude-memory-paths.ts";
+import { assertSafeMemoryPath, homeRelativePath } from "./claude-memory-paths.ts";
import { claudeMemoryBackend } from "./agent-backend/claude.ts";
import type { MemorySourceBackend } from "./agent-backend/types.ts";
import { BRAIN_PREFERENCES_REL, preferencePath } from "./paths.ts";
import { resolvedOwnerFor } from "./preference.ts";
+import { TagSyntaxError } from "./tag-syntax.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface ImportClaudeMemoryOpts {
@@ -24,6 +26,15 @@ export interface ImportClaudeMemoryOpts {
readonly mode: "dry-run" | "apply";
readonly allowArbitraryMemoryPath?: boolean;
readonly now?: Date;
+ /**
+ * The plan digest a dry run computed and an operator approved (the CLI
+ * plumbing is `--approval-digest`). Absent, apply behaves exactly as
+ * it did before approval digests existed - the interactive path's
+ * escape hatch. Present, it is checked against the freshly computed
+ * plan BEFORE the snapshot or any write, and a mismatch is an
+ * {@link ApprovalDigestError} that leaves the vault untouched.
+ */
+ readonly approvalDigest?: string;
/**
* Memory-format adapter (t_53f9f67f). Defaults to the Claude Code
* backend - byte-identical to the pre-seam behavior. Resolve via
@@ -41,6 +52,59 @@ export interface ImportClaudeMemoryResult {
readonly skippedUnchanged: ReadonlyArray<PlannedFile>;
readonly snapshotRunId: string | null;
readonly localDate: string;
+ /**
+ * The seal of the adoption plan (t_18fda844): sha256 of the plans,
+ * skips, conflicts and unchanged rows, via the integrity module's
+ * `sealWithDigest`. Wall-clock fields (`localDate`, the import
+ * timestamps) are deliberately OUTSIDE the sealed body, so a dry run
+ * and a later apply of the same content seal identically and an
+ * approval binds the plan, never the moment it was printed.
+ */
+ readonly digest: string;
+}
+
+/**
+ * The body an approval covers: what will land, what will not, and what
+ * refuses. The one spelling of "the plan", shared by the dry run that
+ * seals it and the apply that re-checks it.
+ */
+function planApprovalBody(parts: {
+ plans: ReadonlyArray<PlannedFile>;
+ skipped: ReadonlyArray<{ basename: string; reason: string }>;
+ conflicts: ReadonlyArray<PlannedFile>;
+ skippedUnchanged: ReadonlyArray<PlannedFile>;
+}): Record<string, unknown> {
+ return {
+ conflicts: parts.conflicts,
+ plans: parts.plans,
+ skipped: parts.skipped,
+ skipped_unchanged: parts.skippedUnchanged,
+ };
+}
+
+/**
+ * The apply-time refusal when the plan an operator approved no longer
+ * matches the plan this run computed. Nothing has been written and no
+ * snapshot has been taken; the remedy is a fresh dry run, whose digest
+ * is what the next apply must carry.
+ */
+export class ApprovalDigestError extends Error {
+ /** The digest the caller asked to apply against. */
+ readonly approvalDigest: string;
+ /** The digest of the plan this run just computed. */
+ readonly planDigest: string;
+
+ constructor(approvalDigest: string, planDigest: string) {
+ super(
+ `approval digest mismatch: the plan changed since the approved dry run ` +
+ `(approved ${approvalDigest}, current plan ${planDigest}); nothing was written and ` +
+ "no snapshot was taken. Re-run `o2b brain import-claude-memory --dry-run` to review " +
+ "the current plan, then apply with its digest.",
+ );
+ this.name = "ApprovalDigestError";
+ this.approvalDigest = approvalDigest;
+ this.planDigest = planDigest;
+ }
}
/**
@@ -90,7 +154,10 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
const backend = opts.backend ?? claudeMemoryBackend;
assertSafeMemoryPath(opts.memoryDir, opts.allowArbitraryMemoryPath ?? false);
if (!existsSync(opts.memoryDir)) {
- throw new Error(`memory directory not found: ${opts.memoryDir}`);
+ throw new Error(
+ `memory directory not found: ${homeRelativePath(opts.memoryDir)} ` +
+ `(pass --memory with an existing directory, or create it)`,
+ );
}
const now = opts.now ?? new Date();
const importedAt = isoSecond(now);
@@ -152,19 +219,18 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
});
return;
}
- seenPrefIds.set(prefId, entryKey);
// preferencePath adds pref- prefix itself, so pass just the slug
const prefFile = preferencePath(opts.vault, slug);
- const manifestEntry = manifest.imports[entryKey];
- const plan = planAction({
- basename: entryKey,
- prefId,
- sha256: parsed.bodySha256,
- inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,
- prefExists: existsSync(prefFile),
- });
- plans.push(plan);
- if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {
+ // Render BEFORE any plan row exists. A render that refuses THIS entry -
+ // a name whose slug fails the one shared tag rule, e.g. a purely
+ // numeric memory name (t_11ee559f) - is a per-entry data problem like a
+ // skip parse or a duplicate id: it lands a named skip row (file and
+ // rule both named) and the import continues. Rendering first keeps the
+ // refusal out of `plans`, so the sealed approval body never offers a
+ // file that would not land, and one legacy MEMORY file cannot abort the
+ // whole run with a message that names only the field.
+ let body: string;
+ try {
// This module renders its own frontmatter and writes it with
// `atomicWriteFileSync`, so it never reaches `writePreference`
// and never got the ownership stamp every other preference
@@ -174,7 +240,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
// `prefFile` is passed so an UPDATE carries the existing owner
// forward instead of re-owning the page, exactly as a rewrite
// through `writePreference` does.
- const body = backend.renderPreference({
+ body = backend.renderPreference({
name: parsed.name,
description: parsed.description,
body: parsed.body,
@@ -184,6 +250,22 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
bodySha256: parsed.bodySha256,
owner: resolvedOwnerFor(opts.vault, prefFile, undefined, undefined),
});
+ } catch (err) {
+ if (!(err instanceof TagSyntaxError)) throw err;
+ skipped.push({ basename: entryKey, reason: err.message });
+ return;
+ }
+ seenPrefIds.set(prefId, entryKey);
+ const manifestEntry = manifest.imports[entryKey];
+ const plan = planAction({
+ basename: entryKey,
+ prefId,
+ sha256: parsed.bodySha256,
+ inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,
+ prefExists: existsSync(prefFile),
+ });
+ plans.push(plan);
+ if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {
filesToWrite.push({ plan, body, sha256: parsed.bodySha256, slug });
}
});
@@ -192,6 +274,12 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
const conflicts = plans.filter((p) => p.action === "CONFLICT");
const skippedUnchanged = plans.filter((p) => p.action === "SKIP_UNCHANGED");
+ // Seal the adoption plan (t_18fda844). The apply below re-checks the
+ // operator's approval against THIS seal before the snapshot or any
+ // write, so what lands is what was approved or nothing is.
+ const approvalBody = planApprovalBody({ plans, skipped, conflicts, skippedUnchanged });
+ const planDigest = sealWithDigest(approvalBody).digest;
+
if (opts.mode === "dry-run") {
return {
mode: "dry-run",
@@ -202,9 +290,18 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
skippedUnchanged,
snapshotRunId: null,
localDate,
+ digest: planDigest,
};
}
+ // The approved plan is checked against the one just computed BEFORE
+ // the snapshot/write loop. Drift between dry run and apply is the
+ // case this exists for: a vault or memory source that moved in
+ // between must be re-reviewed, never written over.
+ if (opts.approvalDigest !== undefined && !digestVerifies(approvalBody, opts.approvalDigest)) {
+ throw new ApprovalDigestError(opts.approvalDigest, planDigest);
+ }
+
// §E design: process the non-conflict files first; throw `ConflictsError`
// at the end if any CONFLICT was detected. This matches design doc §E
// line "The run still processes the remaining files; final exit code is
@@ -292,6 +389,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe
skippedUnchanged,
snapshotRunId,
localDate,
+ digest: planDigest,
};
}
diff --git a/src/core/brain/ingest/batch-plan.ts b/src/core/brain/ingest/batch-plan.ts
index ad5e096b..e19c9475 100644
--- a/src/core/brain/ingest/batch-plan.ts
+++ b/src/core/brain/ingest/batch-plan.ts
@@ -44,7 +44,7 @@
*/
import { existsSync, readdirSync, statSync } from "node:fs";
-import { join, posix, relative } from "node:path";
+import { isAbsolute, join, posix, relative } from "node:path";
import {
buildRepositoryBaseScope,
@@ -59,6 +59,7 @@ import {
type IgnoreWarning,
} from "../../fs/ignore.ts";
import { canonicalNotePath, ensureInsideVault } from "../../path-safety.ts";
+import { computeExtractionContractFingerprint } from "./contract.ts";
import { computePlanId, readCheckpoint } from "./checkpoint.ts";
import { classifyPaths, readManifest } from "./content-manifest.ts";
import {
@@ -87,6 +88,24 @@ import {
*/
export { DEFAULT_INGESTIBLE_EXTENSIONS };
+/**
+ * The closed vocabulary of why-a-file-is-planned tokens (the wire `status`).
+ * Bytes-changed and contract-changed are deliberately DISTINCT tokens
+ * (t_586d5d8b): a source reprocessing because the extraction contract moved,
+ * not because its bytes moved, reports that fact instead of masquerading as an
+ * edit.
+ */
+export const PLANNED_FILE_STATUS = Object.freeze({
+ /** On disk, absent from the manifest. */
+ NEW: "new",
+ /** On disk, manifest bytes differ. */
+ BYTES_CHANGED: "modified",
+ /** On disk, manifest bytes identical, but the extraction contract changed. */
+ CONTRACT_CHANGED: "contract-changed",
+} as const);
+
+export type PlannedFileStatus = (typeof PLANNED_FILE_STATUS)[keyof typeof PLANNED_FILE_STATUS];
+
export interface BatchPlanOptions {
/** Hard upper bound on the summed bytes of one batch (must be > 0). */
readonly maxBatchBytes: number;
@@ -138,8 +157,8 @@ export interface PlannedFile {
readonly path: string;
/** File size in bytes (drives the byte-cap packing). */
readonly bytes: number;
- /** Why the file is being ingested: absent from / differing in the manifest. */
- readonly status: "new" | "modified";
+ /** Why the file is being ingested: see {@link PLANNED_FILE_STATUS}. */
+ readonly status: PlannedFileStatus;
/**
* The file's registered format when it is not `text` (HTML, CSV, TSV, or a
* named format a caller's `extensions` override admitted). Absent for text
@@ -206,6 +225,19 @@ export interface BatchPlan {
readonly totalFiles: number;
/** Total bytes across all batches. */
readonly totalBytes: number;
+ /**
+ * Whether the manifest's recorded extraction contract
+ * ({@link ./contract.ts}) differs from the live one - including a v1
+ * manifest, which recorded none. Every `unchanged` source reprocesses once
+ * under the new contract (see {@link PLANNED_FILE_STATUS.CONTRACT_CHANGED});
+ * an unchanged contract plans exactly as before.
+ */
+ readonly contractChanged: boolean;
+ /**
+ * How many of the planned files reprocess because the contract changed
+ * rather than their bytes. Zero unless {@link BatchPlan.contractChanged}.
+ */
+ readonly contractChangedFiles: number;
/**
* Stable id for this plan (t_ba1fa5f6), derived from the source dir and the
* full discovered path set. The key an interrupted run resumes against.
@@ -254,6 +286,17 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOpt
}
const dirRel = canonicalNotePath(sourceDir);
+ // Refuse an absolute argument BEFORE the existence check: `join` treats
+ // an absolute second operand as relative text, so `join(vault, "/abs")`
+ // nests the path inside the vault and the directory the operator can
+ // list comes out "not an existing directory" - a falsehood, and one that
+ // never states the actual contract, that the argument is vault-relative.
+ if (isAbsolute(sourceDir)) {
+ throw new Error(
+ `planBatches: source dir must be a vault-relative path inside the vault ` +
+ `(got "${sourceDir}"); rerun with the directory path relative to the vault root`,
+ );
+ }
const dirAbs = ensureInsideVault(join(vault, dirRel), vault);
if (!existsSync(dirAbs) || !statSync(dirAbs).isDirectory()) {
throw new Error(`planBatches: source dir is not an existing directory: ${sourceDir}`);
@@ -336,9 +379,12 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOpt
...partition.skipped,
];
- // The plan id keys on the FULL discovered set, so it is identical before and
- // after an interruption regardless of how many items have completed.
- const planId = computePlanId(dirRel, relPaths);
+ // The plan id keys on the FULL discovered set plus the LIVE extraction
+ // contract (t_586d5d8b), so it is identical before and after an interruption
+ // and a contract change gets a fresh id - the old checkpoint then orphans
+ // instead of resume-skipping work extracted under the old contract.
+ const contractFingerprint = computeExtractionContractFingerprint(vault);
+ const planId = computePlanId(dirRel, relPaths, contractFingerprint);
// On resume, drop items this plan's checkpoint already recorded completed
// BEFORE classification, so those items are not re-hashed at all - the
@@ -351,15 +397,25 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOpt
const toClassify = relPaths.filter((p) => !completed.has(p));
const resumedCompleted = relPaths.length - toClassify.length;
- // Consult A1's manifest: only `new`/`modified` sources are worth ingesting.
- const classification = classifyPaths(vault, toClassify, readManifest(vault));
- const skipped = [...classification.unchanged].toSorted();
+ // Consult A1's manifest, then compare its recorded extraction contract
+ // against the live one IMMEDIATELY after the read (t_586d5d8b): a manifest
+ // written under an older contract - or a v1 one, which recorded none - must
+ // not keep serving `unchanged` skips shaped by that contract.
+ const manifest = readManifest(vault);
+ const classification = classifyPaths(vault, toClassify, manifest);
+ const contractChanged =
+ manifest.contract === null || manifest.contract.fingerprint !== contractFingerprint;
// Build the planned-file list, tagging each with why it was selected, in
// sorted-by-path order so packing (and the whole plan) is deterministic.
- const status = new Map<string, "new" | "modified">();
- for (const p of classification.new) status.set(p, "new");
- for (const p of classification.modified) status.set(p, "modified");
+ // Under a changed contract the byte-identical sources reprocess too, with
+ // the distinct contract-changed token - "bytes changed" stays "modified".
+ const status = new Map<string, PlannedFileStatus>();
+ for (const p of classification.new) status.set(p, PLANNED_FILE_STATUS.NEW);
+ for (const p of classification.modified) status.set(p, PLANNED_FILE_STATUS.BYTES_CHANGED);
+ if (contractChanged) {
+ for (const p of classification.unchanged) status.set(p, PLANNED_FILE_STATUS.CONTRACT_CHANGED);
+ }
const planned: PlannedFile[] = [...status.keys()].toSorted().map((path) => {
const format = sourceFormatOf(path);
return {
@@ -377,12 +433,16 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOpt
maxBatchBytes: opts.maxBatchBytes,
maxBatchFiles: opts.maxBatchFiles,
batches,
- skipped,
+ // Nothing skips under a changed contract: every unchanged source is in the
+ // reprocessing list above, so the skip list is empty by construction.
+ skipped: contractChanged ? [] : [...classification.unchanged].toSorted(),
skippedNonExtractable,
skipReasonCounts: countSkipReasons(skippedNonExtractable),
unclassifiable: aggregateUnclassifiable(unclassifiable),
totalFiles: planned.length,
totalBytes: planned.reduce((sum, f) => sum + f.bytes, 0),
+ contractChanged,
+ contractChangedFiles: contractChanged ? classification.unchanged.length : 0,
planId,
resumedCompleted,
// Sorted so the plan is fully deterministic: the walk visits directories in
diff --git a/src/core/brain/ingest/checkpoint.ts b/src/core/brain/ingest/checkpoint.ts
index 48501142..ffa5f1be 100644
--- a/src/core/brain/ingest/checkpoint.ts
+++ b/src/core/brain/ingest/checkpoint.ts
@@ -73,11 +73,19 @@ export interface IngestCheckpoint {
}
/**
- * Deterministic plan id: a short SHA-256 hex over the canonical source dir and
- * the sorted full discovered path set. Keying on the FULL set (not the remaining
- * work) keeps the id stable across a resume even as items complete.
+ * Deterministic plan id: a short SHA-256 hex over the canonical source dir, the
+ * sorted full discovered path set, and the extraction contract
+ * ({@link ./contract.ts}) the plan runs under. Keying on the FULL set (not the
+ * remaining work) keeps the id stable across a resume even as items complete;
+ * keying on the CONTRACT means a changed contract gets a fresh id, so a stale
+ * checkpoint recorded under the old contract cannot resume-skip work extracted
+ * under the new one - the old file orphans harmlessly.
*/
-export function computePlanId(sourceDir: string, discoveredPaths: readonly string[]): string {
+export function computePlanId(
+ sourceDir: string,
+ discoveredPaths: readonly string[],
+ contractFingerprint: string,
+): string {
const dir = canonicalNotePath(sourceDir);
const paths = discoveredPaths.map((p) => canonicalNotePath(p)).toSorted();
const hash = createHash("sha256");
@@ -87,6 +95,8 @@ export function computePlanId(sourceDir: string, discoveredPaths: readonly strin
hash.update(p);
hash.update("\n");
}
+ hash.update("\0");
+ hash.update(contractFingerprint);
return hash.digest("hex").slice(0, 16);
}
diff --git a/src/core/brain/ingest/content-manifest.ts b/src/core/brain/ingest/content-manifest.ts
index 537f44ce..d115a1d9 100644
--- a/src/core/brain/ingest/content-manifest.ts
+++ b/src/core/brain/ingest/content-manifest.ts
@@ -18,6 +18,11 @@
* that case. Comparing content hashes instead means only a real byte change
* re-triggers ingestion.
*
+ * The manifest also carries ONE manifest-wide field beyond the entries: the
+ * extraction contract ({@link ./contract.ts}) the recorded state answers
+ * under, so a changed extraction contract reprocesses every source once even
+ * when its bytes did not move (t_586d5d8b).
+ *
* The manifest lives at `<vault>/.open-second-brain/ingest-manifest.json`, a
* MACHINE artifact - not curated memory, so NOT under `Brain/`. This mirrors the
* existing `<vault>/.open-second-brain/` location used by the search index and
@@ -36,9 +41,19 @@ import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { canonicalNotePath } from "../../path-safety.ts";
import { acquireLockSyncWithRetry, ingestLockRemedy } from "../sync-lockfile.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { computeExtractionContractFingerprint } from "./contract.ts";
+
+/** The schema version this module writes. Earlier versions are read, not written. */
+const SCHEMA_VERSION = 2 as const;
+
+/** Every on-disk schema version this module reads; anything else is refused. */
+type ManifestSchemaVersion = 1 | typeof SCHEMA_VERSION;
-/** Only schema version currently understood. Unknown versions are refused. */
-const SCHEMA_VERSION = 1 as const;
+/** Every schema version {@link readManifest} accepts. Anything else is refused. */
+const SUPPORTED_SCHEMA_VERSIONS: readonly ManifestSchemaVersion[] = Object.freeze([
+ 1,
+ SCHEMA_VERSION,
+]);
/** Vault-relative directory holding OSB machine artifacts (not curated memory). */
const MACHINE_ARTIFACT_DIR = ".open-second-brain";
@@ -46,14 +61,44 @@ const MACHINE_ARTIFACT_DIR = ".open-second-brain";
/** Basename of the ingest content-hash manifest. */
const MANIFEST_FILE = "ingest-manifest.json";
+/** The manifest-wide extraction-contract record (t_586d5d8b). */
+export interface ManifestContract {
+ /** {@link computeExtractionContractFingerprint} of the pass that wrote it. */
+ readonly fingerprint: string;
+}
+
/**
* The persisted manifest: a map from a canonical vault-relative source path to
- * the SHA-256 hex of its content at last ingest.
+ * the SHA-256 hex of its content at last ingest, plus the manifest-wide
+ * extraction contract the recorded state answers under.
*/
export interface ContentManifest {
- readonly schema_version: typeof SCHEMA_VERSION;
+ /**
+ * The schema version the MANIFEST FILE carries: the version actually on
+ * disk for a read file, and the current {@link SCHEMA_VERSION} for the
+ * missing-file empty manifest (no file exists, so the current shape is the
+ * honest answer). Deliberately not the write constant - an accepted v1
+ * manifest that reported itself as v2 would make every "which version is
+ * on disk" diagnostic lie about exactly the one legacy shape this module
+ * supports.
+ */
+ readonly schema_version: ManifestSchemaVersion;
/** Canonical vault-relative path → 64-char lowercase SHA-256 hex of content. */
readonly entries: Readonly<Record<string, string>>;
+ /**
+ * The extraction contract the recorded state answers under, or `null` when
+ * none is recorded - a v1 manifest written before the fingerprint existed.
+ * `null` is the changed-contract marker: every consumer treats it as
+ * "reprocess once under the live contract". The marker survives until a
+ * write that actually RECORDS EXTRACTION under the live contract
+ * ({@link updateManifest}) lands the manifest as v2 with the fingerprint;
+ * a round-tripping edit write passes the `null` back in and the file stays
+ * v1, so the owed reprocess is never forfeited by a write that reprocessed
+ * nothing. A manifest file that does not exist reads back as current-shaped
+ * under the LIVE contract - an empty manifest was never written under an
+ * older one, so nothing in it can be stale.
+ */
+ readonly contract: ManifestContract | null;
}
/** Result of classifying a set of paths against a manifest. */
@@ -123,15 +168,23 @@ export function hashPath(absPath: string): string {
}
/**
- * Read the manifest for a vault. A missing file is an empty manifest (every
- * path then classifies `new`). A corrupted file or an unknown `schema_version`
- * is a hard error - never a silent reset that would masquerade every source as
- * unchanged or force a full re-ingest without saying so.
+ * Read the manifest for a vault. A missing file is an empty, current-shaped
+ * manifest under the live contract (every path then classifies `new`). A
+ * corrupted file is a hard error, and so is an unknown `schema_version` -
+ * never a silent reset that would masquerade every source as unchanged or
+ * force a full re-ingest without saying so. A v1 manifest (a known previous
+ * version, written before the contract field existed) is accepted and reads
+ * back with `contract: null`: the changed-contract marker that makes every
+ * source reprocess once before the rewrite lands as v2.
*/
export function readManifest(vault: string): ContentManifest {
const path = manifestPath(vault);
if (!existsSync(path)) {
- return { schema_version: SCHEMA_VERSION, entries: {} };
+ return {
+ schema_version: SCHEMA_VERSION,
+ entries: {},
+ contract: { fingerprint: computeExtractionContractFingerprint(vault) },
+ };
}
const raw = readFileSync(path, "utf8");
let parsed: unknown;
@@ -145,9 +198,10 @@ export function readManifest(vault: string): ContentManifest {
}
const obj = parsed as Record<string, unknown>;
const sv = obj["schema_version"];
- if (sv !== SCHEMA_VERSION) {
+ if (!(SUPPORTED_SCHEMA_VERSIONS as readonly unknown[]).includes(sv)) {
throw new Error(
- `ingest manifest schema_version ${String(sv)} not supported (expected ${SCHEMA_VERSION}): ${path}`,
+ `ingest manifest schema_version ${String(sv)} not supported ` +
+ `(expected ${SUPPORTED_SCHEMA_VERSIONS.join(" or ")}): ${path}`,
);
}
const rawEntries = obj["entries"];
@@ -157,20 +211,42 @@ export function readManifest(vault: string): ContentManifest {
if (typeof value === "string") entries[key] = value;
}
}
- return { schema_version: SCHEMA_VERSION, entries };
+ return { schema_version: sv as ManifestSchemaVersion, entries, contract: readContractField(obj) };
+}
+
+/**
+ * The manifest's recorded contract field, or `null` when none is recorded.
+ * Only `{ fingerprint: <string> }` counts; anything else a v2 write could
+ * never have produced (and a v1 manifest never carries) degrades to `null`,
+ * the changed-contract marker - a malformed field self-heals into one
+ * reprocessing pass rather than refusing a manifest whose entries are fine.
+ */
+function readContractField(obj: Record<string, unknown>): ManifestContract | null {
+ const raw = obj["contract"];
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const fingerprint = (raw as Record<string, unknown>)["fingerprint"];
+ return typeof fingerprint === "string" ? { fingerprint } : null;
}
/**
* Serialize `entries` to the canonical manifest bytes: keys sorted so the
- * output is deterministic regardless of insertion order, `schema_version`
- * first, trailing newline.
+ * output is deterministic regardless of insertion order, `schema_version` and
+ * the contract field first, trailing newline. A `null` contract serializes
+ * the V1 shape - no contract field - so a round-tripped v1 manifest stays v1.
*/
-function serializeManifest(entries: Record<string, string>): string {
+function serializeManifest(
+ entries: Record<string, string>,
+ contract: ManifestContract | null,
+): string {
const sorted: Record<string, string> = {};
for (const key of Object.keys(entries).toSorted()) {
sorted[key] = entries[key]!;
}
- return JSON.stringify({ schema_version: SCHEMA_VERSION, entries: sorted }, null, 2) + "\n";
+ const body =
+ contract === null
+ ? { schema_version: 1, entries: sorted }
+ : { schema_version: SCHEMA_VERSION, contract, entries: sorted };
+ return JSON.stringify(body, null, 2) + "\n";
}
/**
@@ -178,12 +254,36 @@ function serializeManifest(entries: Record<string, string>): string {
* what is already on disk. Returns `true` when a write happened, `false` on a
* no-op. The byte-identity check is what makes an all-unchanged rerun rewrite
* nothing (and leaves the file's mtime alone).
+ *
+ * `contract` is what the written manifest records as the extraction contract
+ * its entries answer under:
+ *
+ * - Omitted: the LIVE contract. The writers that call without one have just
+ * recorded extraction under the current contract, so this is the one-time
+ * v1→v2 upgrade - legitimate exactly because the named paths were
+ * reprocessed under it.
+ * - A contract object: round-tripped verbatim, so an edit write cannot
+ * re-stamp entries that predate the live contract.
+ * - Explicit `null` (a v1 read): serialized back as V1, contract-less. The
+ * remaining entries were never reprocessed under any fingerprint, so the
+ * changed-contract marker must survive the write - stamping the live
+ * contract here would let them classify `unchanged` forever and silently
+ * forfeit the owed one-time reprocess (t_586d5d8b).
*/
-export function writeManifestAtomic(vault: string, entries: Record<string, string>): boolean {
+export function writeManifestAtomic(
+ vault: string,
+ entries: Record<string, string>,
+ contract?: ManifestContract | null,
+): boolean {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
const path = manifestPath(vault);
- const next = serializeManifest(entries);
+ const next = serializeManifest(
+ entries,
+ contract === undefined
+ ? { fingerprint: computeExtractionContractFingerprint(vault) }
+ : contract,
+ );
if (existsSync(path) && readFileSync(path, "utf8") === next) {
return false;
}
diff --git a/src/core/brain/ingest/contract.ts b/src/core/brain/ingest/contract.ts
new file mode 100644
index 00000000..1d9fd396
--- /dev/null
+++ b/src/core/brain/ingest/contract.ts
@@ -0,0 +1,70 @@
+/**
+ * The extraction-contract fingerprint (t_586d5d8b).
+ *
+ * The content-hash manifest ({@link ./content-manifest.ts}) gates re-ingest
+ * on BYTES alone: a source whose bytes are unchanged since its last ingest is
+ * skipped, and answers with extraction shaped by whatever contract produced
+ * its stored page - even after the extraction behavior changed. This module
+ * names that contract so the manifest can record it and the planner can
+ * refuse to skip under a changed one. The fingerprint covers everything
+ * CODE-scoped that shapes extraction: the vault's schema `extractable`
+ * allowlist plus the hand-bumped {@link EXTRACT_CONTRACT_VERSION} constant.
+ *
+ * Deliberately OUT of the fingerprint: per-call planning options
+ * (`pre_extract`, `extensions`, `exclude`, the batch caps). They shape one
+ * planning call, not the contract a stored page was extracted under - the
+ * same scope-vs-options split the session-summary lane draws.
+ *
+ * Pure: the fingerprint is a function of the vault's config text and the
+ * version constant alone - no clock, no absolute paths, no per-call options -
+ * so two peers holding the same vault config compute the same value, and a
+ * fingerprint recorded in one replica's manifest means the same contract on
+ * every other.
+ *
+ * Language-agnostic: schema tokens in, hex out; no natural-language content
+ * is inspected.
+ */
+
+import { canonicalJson, sha256Hex } from "../../integrity/digest.ts";
+import { loadSchemaPack } from "../schema-pack.ts";
+
+/**
+ * Version of the extraction contract. A stored page answers with the
+ * contract that produced it, so a change to code-scoped extraction behavior
+ * must bump this: the planner compares the manifest's recorded fingerprint
+ * against the live one and reprocesses every source once when they differ
+ * (the `CHUNKER_VERSION` bump-guard convention).
+ *
+ * 1 - the pre-fingerprint era: reprocessing was gated on content bytes
+ * alone, so no contract was ever recorded; manifests written then are
+ * read as changed.
+ * 2 - the fingerprint exists and is recorded in the ingest manifest's
+ * manifest-wide `contract` field (t_586d5d8b).
+ */
+export const EXTRACT_CONTRACT_VERSION = 2;
+
+/** Characters of the SHA-256 hex kept - short like the plan id, not a digest. */
+const FINGERPRINT_HEX_CHARS = 16;
+
+/**
+ * The pure combiner behind {@link computeExtractionContractFingerprint}: the
+ * fingerprint over a contract version and the schema `extractable` allowlist.
+ * The allowlist is sorted before hashing so its spelling order - which the
+ * schema parser preserves - cannot change the value.
+ */
+export function extractionContractFingerprint(
+ version: number,
+ extractable: readonly string[],
+): string {
+ const body = { version, extractable: [...extractable].toSorted() };
+ return sha256Hex(canonicalJson(body)).slice(0, FINGERPRINT_HEX_CHARS);
+}
+
+/**
+ * The extraction contract of `vault`: the fingerprint over this build's
+ * {@link EXTRACT_CONTRACT_VERSION} and the vault's schema `extractable`
+ * allowlist. See the module header for what is deliberately not folded in.
+ */
+export function computeExtractionContractFingerprint(vault: string): string {
+ return extractionContractFingerprint(EXTRACT_CONTRACT_VERSION, loadSchemaPack(vault).extractable);
+}
diff --git a/src/core/brain/label-suggest.ts b/src/core/brain/label-suggest.ts
index 498d8126..9e293709 100644
--- a/src/core/brain/label-suggest.ts
+++ b/src/core/brain/label-suggest.ts
@@ -234,6 +234,7 @@ export async function suggestNoteLabels(
() => questions,
{
config: cfg,
+ secretsVault: vault,
...(opts.provider !== undefined ? { provider: opts.provider } : {}),
...(opts.env !== undefined ? { env: opts.env } : {}),
recordDetails: (response) => ({
diff --git a/src/core/brain/ledger-shards.ts b/src/core/brain/ledger-shards.ts
index 425ea15e..e5197bdf 100644
--- a/src/core/brain/ledger-shards.ts
+++ b/src/core/brain/ledger-shards.ts
@@ -36,6 +36,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { resolveDeviceId } from "../config.ts";
+import { JSONL_LEDGER_EXT } from "./path-constants.ts";
/**
* The shard-id shape: the lowercase slug `resolveDeviceId` produces,
@@ -79,8 +80,13 @@ export interface LedgerShardGrammar {
readonly extensions: ReadonlyArray<string>;
}
-/** The extension every JSON Lines ledger writes, without the leading dot. */
-export const JSONL_LEDGER_EXT = "jsonl";
+/**
+ * The extension every JSON Lines ledger writes, without the leading dot.
+ * Declared in the leaf `path-constants.ts` (see its docblock for the import
+ * cycle that motivated the move) and re-exported here so every ledger keeps
+ * importing it from this module.
+ */
+export { JSONL_LEDGER_EXT };
/**
* The grammar of a JSON Lines ledger whose base is one fixed file stem
diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.ts
index e2a73fb1..64a3a1a2 100644
--- a/src/core/brain/path-constants.ts
+++ b/src/core/brain/path-constants.ts
@@ -191,6 +191,18 @@ export const DERIVED_STORE_FILE = "brain.sqlite";
*/
export const HOOK_AUDIT_DIR = "hook-audit";
+/**
+ * The extension every JSON Lines ledger writes, without the leading dot.
+ *
+ * Declared in this leaf rather than in `ledger-shards.ts` (which re-exports
+ * it, so no importer changes) because the audit writer's week-grammar
+ * constant reads it at module-evaluation time, and `ledger-shards.ts`
+ * reaches back into `config.ts` for the device id - a cycle that TDZ-aborted
+ * `audit.ts` whenever the shard grammar module was entered first. A name
+ * this many ledgers share belongs beside the other Brain file names anyway.
+ */
+export const JSONL_LEDGER_EXT = "jsonl";
+
/** Brain-internal artefact filenames at the root of `Brain/`. */
export const BRAIN_CONFIG_FILE = "_brain.yaml";
export const BRAIN_MANUAL_FILE = "_BRAIN.md";
diff --git a/src/core/brain/payload-json.ts b/src/core/brain/payload-json.ts
new file mode 100644
index 00000000..edabfa70
--- /dev/null
+++ b/src/core/brain/payload-json.ts
@@ -0,0 +1,125 @@
+/**
+ * Strip-and-note JSON parsing for model-answer payloads (t_dac8bf7e).
+ *
+ * The four model-answer verbs (`extract-signals`, `design-note`,
+ * `skill-proposals page-draft`, `distill`) receive JSON that a calling
+ * model produced. Reasoning models wrap that JSON in a leading
+ * `<think>...</think>` block; a bare `JSON.parse` refuses it and the
+ * operator gets a generic "fix your JSON" for a payload whose JSON part
+ * is fine.
+ *
+ * This module is the one shared parser: try the plain parse first; only
+ * on failure strip ONE leading `<think>` block - unwrapping a wholly
+ * fenced body per the `decision-model/llm-emulation.ts` precedent - and
+ * retry. Every strip is REPORTED: the result carries the strip fact
+ * (`kind`, `prefixChars`) so the surface can name it on the success
+ * envelope. The strip never rescues genuinely malformed JSON: a payload
+ * that still does not parse after the strip keeps a named error whose
+ * message says the strip was attempted, and a payload with no leading
+ * think block keeps the plain refusal. No I/O; pure text in, verdict out.
+ */
+
+export const THINK_BLOCK_STRIP_KIND = "think_block";
+export const FENCED_THINK_BLOCK_STRIP_KIND = "fenced_think_block";
+
+export type PayloadStripKind = typeof THINK_BLOCK_STRIP_KIND | typeof FENCED_THINK_BLOCK_STRIP_KIND;
+
+/** The fact that a leading think block had to be stripped before parsing. */
+export interface PayloadStrip {
+ readonly kind: PayloadStripKind;
+ /** Characters removed from the head of the input before the JSON body. */
+ readonly prefixChars: number;
+}
+
+export class PayloadJsonError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "PayloadJsonError";
+ }
+}
+
+/** The refusal a bare `JSON.parse` produced before this module existed. */
+export const PAYLOAD_UNPARSEABLE_MESSAGE = "payload must be valid JSON";
+
+/** Appended when a strip was attempted and the remainder still refused. */
+const STRIP_STILL_UNPARSEABLE_SUFFIX =
+ " (a leading <think> block was stripped; the remainder still did not parse)";
+
+/** The operator-facing strip fact, for a result envelope's `note` key. */
+const STRIP_NOTE_BASE = "leading <think> block stripped before JSON parse";
+
+export interface ParsedPayload {
+ readonly payload: unknown;
+ /** Present only when a leading think block had to be stripped. */
+ readonly strip?: PayloadStrip;
+}
+
+/** One LEADING think block, whitespace tolerated ahead of it. */
+const LEADING_THINK_BLOCK = /^\s*<think>[\s\S]*?<\/think>/;
+
+/**
+ * A body wholly wrapped in one code fence, the
+ * `decision-model/llm-emulation.ts` replyObject precedent verbatim.
+ */
+const WHOLLY_FENCED = /^\s*```(?:json)?\s*([\s\S]*?)\s*```\s*$/;
+
+const UNPARSEABLE: unique symbol = Symbol("payload-json.unparseable");
+
+function tryParse(text: string): unknown | typeof UNPARSEABLE {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return UNPARSEABLE;
+ }
+}
+
+/**
+ * Parse a model-answer payload, stripping one leading `<think>` block when
+ * - and only when - the plain parse fails. Throws {@link PayloadJsonError}
+ * with the plain message when nothing was stripped, and with the message
+ * naming the strip attempt when the stripped remainder still did not parse.
+ */
+export function parsePayloadJson(raw: string): ParsedPayload {
+ try {
+ return { payload: JSON.parse(raw) };
+ } catch {
+ // Only now may the strip fire; a payload the plain parse accepts is
+ // handed through untouched, think blocks and all.
+ }
+ const stripped = LEADING_THINK_BLOCK.exec(raw);
+ if (stripped === null) {
+ return refuseWithoutStrip();
+ }
+ const thinkChars = stripped[0].length;
+ const body = raw.slice(thinkChars);
+ const direct = tryParse(body);
+ if (direct !== UNPARSEABLE) {
+ return stripSucceeded({ kind: THINK_BLOCK_STRIP_KIND, prefixChars: thinkChars }, direct);
+ }
+ const fenced = WHOLLY_FENCED.exec(body);
+ if (fenced !== null) {
+ const inner = fenced[1]!;
+ const innerParsed = tryParse(inner);
+ if (innerParsed !== UNPARSEABLE) {
+ // prefixChars counts everything removed before the JSON body: the
+ // think block plus the fence opener. The closing fence is a suffix,
+ // not a prefix, and is not counted.
+ const prefixChars = thinkChars + body.indexOf(inner);
+ return stripSucceeded({ kind: FENCED_THINK_BLOCK_STRIP_KIND, prefixChars }, innerParsed);
+ }
+ }
+ throw new PayloadJsonError(PAYLOAD_UNPARSEABLE_MESSAGE + STRIP_STILL_UNPARSEABLE_SUFFIX);
+}
+
+function refuseWithoutStrip(): never {
+ throw new PayloadJsonError(PAYLOAD_UNPARSEABLE_MESSAGE);
+}
+
+function stripSucceeded(strip: PayloadStrip, payload: unknown): ParsedPayload {
+ return { payload, strip };
+}
+
+/** The `note` value a surface puts on its success envelope when a strip happened. */
+export function payloadStripNote(strip: PayloadStrip): string {
+ return `${STRIP_NOTE_BASE} (kind=${strip.kind}, prefix_chars=${strip.prefixChars})`;
+}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 97804e68..7993b5e3 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -41,8 +41,10 @@ import {
formatFrontmatter,
parseFrontmatter,
parseFrontmatterWithNotices,
+ slugify,
writeFrontmatterAtomic,
} from "../vault.ts";
+import { requireObsidianTagValue } from "./tag-syntax.ts";
import { BrainParseError } from "./parse-error.ts";
import { FrontmatterTierConflictError, mergeFrontmatterTiered } from "./frontmatter-tiers.ts";
import { loadSchemaPack } from "./schema-pack.ts";
@@ -814,12 +816,18 @@ function composePreferenceTags(input: WritePreferenceInput): string[] {
out.push(t);
}
};
+ // Composed values obey the ONE shared tag rule (`src/core/tags.ts`, via
+ // `tag-syntax.ts`), with the same polarity as the signal composer: the
+ // topic segment is slugified then validated; scope segments and
+ // `extraTags` entries are caller-controlled input, refused unrewritten
+ // with the field named.
push("brain");
push("brain/preference");
- push(`brain/topic/${input.topic.trim()}`);
- if (input.scope?.trim()) push(`brain/scope/${input.scope.trim()}`);
+ push(`brain/topic/${requireObsidianTagValue(slugify(input.topic.trim()), "topic")}`);
+ if (input.scope?.trim())
+ push(`brain/scope/${requireObsidianTagValue(input.scope.trim(), "scope")}`);
for (const t of input.extraTags ?? []) {
- if (t.trim()) push(t.trim());
+ if (t.trim()) push(requireObsidianTagValue(t.trim(), "extraTags"));
}
return out;
}
diff --git a/src/core/brain/recall-inject-decision.ts b/src/core/brain/recall-inject-decision.ts
index 256750ed..7afd071c 100644
--- a/src/core/brain/recall-inject-decision.ts
+++ b/src/core/brain/recall-inject-decision.ts
@@ -187,6 +187,7 @@ export function createRecallInjectDecisionFilter(
{
config: cfg,
timeoutMs: budgetMs,
+ secretsVault: opts.vault,
...(opts.provider !== undefined ? { provider: opts.provider } : {}),
...(opts.env !== undefined ? { env: opts.env } : {}),
recordDetails: (response, context) => {
diff --git a/src/core/brain/research/research.ts b/src/core/brain/research/research.ts
index 2cf19215..e8c19abe 100644
--- a/src/core/brain/research/research.ts
+++ b/src/core/brain/research/research.ts
@@ -31,6 +31,7 @@ import {
assertResponseShape,
} from "../response-shape.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { isSecretReferenceValue, resolveNamedSecret } from "../../secret-resolver.ts";
import { renderProvenanceSection, type Provenance } from "../provenance/provenance.ts";
import {
CAPTURE_SCOPE,
@@ -293,18 +294,33 @@ export interface ResearchPoolEnv {
readonly tavilyApiKey: string | null;
}
-/** Read the provider key envs. An injected map keeps this deterministic in tests. */
+/** Read the provider key envs. An injected map keeps this deterministic in tests.
+ * A key env value written as a `$secret:NAME` reference resolves through the
+ * custody store of `secretsVault` (store first, env fallback); without a vault
+ * the values are taken as-is, exactly as before the resolver routing existed.
+ * An unresolvable reference surfaces the named resolver error instead of
+ * quietly yielding an empty pool.
+ */
export function resolveResearchPoolEnv(
env: Readonly<Record<string, string | undefined>> = process.env,
+ secretsVault?: string,
): ResearchPoolEnv {
- const brave = env[BRAVE_API_KEY_ENV]?.trim();
- const tavily = env[TAVILY_API_KEY_ENV]?.trim();
return {
- braveApiKey: brave !== undefined && brave.length > 0 ? brave : null,
- tavilyApiKey: tavily !== undefined && tavily.length > 0 ? tavily : null,
+ braveApiKey: researchKey(env[BRAVE_API_KEY_ENV], secretsVault),
+ tavilyApiKey: researchKey(env[TAVILY_API_KEY_ENV], secretsVault),
};
}
+/** One provider key: trimmed and non-empty, with references resolved. */
+function researchKey(raw: string | undefined, secretsVault: string | undefined): string | null {
+ const trimmed = raw?.trim();
+ if (trimmed === undefined || trimmed.length === 0) return null;
+ if (secretsVault !== undefined && isSecretReferenceValue(trimmed)) {
+ return resolveNamedSecret(secretsVault, trimmed);
+ }
+ return trimmed;
+}
+
export interface BuildResearchPoolOptions {
/** Transport seam; defaults to the real fetch transport for production use. */
readonly transport?: ExternalFetchTransport;
diff --git a/src/core/brain/schema-pack.ts b/src/core/brain/schema-pack.ts
index 28b10c06..4611f121 100644
--- a/src/core/brain/schema-pack.ts
+++ b/src/core/brain/schema-pack.ts
@@ -86,6 +86,27 @@ export function loadSchemaPack(vault: string): SchemaPack {
return readSchemaPackSource(vault).pack;
}
+/**
+ * The page types this vault DECLARED, or `null` when it made no
+ * declaration (trust-surface-hardening wave; kanban t_151a564c).
+ *
+ * `null` is the fail-open answer and it covers every undeclaring shape:
+ * no config file at all, and a config that omits or empties
+ * `page_types`. A non-null answer means the config is present and names
+ * at least one page type - the one shape a writer must treat as a
+ * closed vocabulary. The merged vocabulary (see
+ * {@link resolveSchemaVocabulary}) always contains `note`, so the
+ * declared list, not the merged one, is what tells a writer whether the
+ * vault said anything at all.
+ */
+export function declaredPageTypes(vault: string): ReadonlyArray<string> | null {
+ const source = readSchemaPackSource(vault);
+ if (!source.present) return null;
+ const declared = source.pack.declarations.page_types;
+ if (declared === undefined || declared.length === 0) return null;
+ return declared;
+}
+
export function parseSchemaPack(configText: string): SchemaPack {
const lines = extractSchemaLines(configText);
const partial: Partial<Record<SchemaVocabularyCategory, ReadonlyArray<string>>> = {};
diff --git a/src/core/brain/secrets/bundle.ts b/src/core/brain/secrets/bundle.ts
new file mode 100644
index 00000000..11889d92
--- /dev/null
+++ b/src/core/brain/secrets/bundle.ts
@@ -0,0 +1,442 @@
+/**
+ * Passphrase-encrypted credential bundles (t_592d9e91).
+ *
+ * Export turns the store's entries into ONE schema-versioned envelope
+ * each entry's value re-encrypted under a key the passphrase derives
+ * through the keyfile envelope's KDF (`./envelope.ts` - same scrypt
+ * cost curve, fresh salt, parameters recorded inside the bundle). Import
+ * verifies, decrypts EVERY value before writing anything, reuses the
+ * store's name, env-var AND allow-pattern validation (so a rewritten
+ * bundle cannot land entries the store's own writer would refuse), and
+ * lands the entries through the store's lock and writer with
+ * `removeSecret`'s exactness on collisions.
+ *
+ * What the envelope carries in the clear, by design: the schema version,
+ * the wall-clock stamp, the KDF parameters, and each entry's name,
+ * env-var mapping and allowlist - the same metadata `list` exposes. What
+ * it never carries in the clear: any value, and the passphrase. The
+ * export path's egress declaration (`src/core/egress/registry.ts`) runs
+ * the shared redactor over exactly this non-ciphertext metadata tree.
+ *
+ * Honest warning, as for the keyfile envelope: the bundle's secrecy is
+ * the passphrase's strength against offline guessing wherever the file
+ * travels. A lost passphrase makes the bundle unreadable; there is no
+ * recovery path and none is pretended.
+ */
+
+import { join } from "node:path";
+
+import { appendAuditRecord } from "../../reliability/audit.ts";
+import { SECRET_CUSTODY_AUDIT_DIR } from "../audit-dirs.ts";
+import { brainDirsForWrite } from "../paths.ts";
+import { isoSecond } from "../time.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";
+import {
+ deriveWrapKey,
+ freshWrapKdfParams,
+ kdfCostCurveRefusal,
+ type EnvelopeKdfParams,
+} from "./envelope.ts";
+import {
+ isValidSecretEnvVar,
+ isValidSecretName,
+ keyPath,
+ normalizeAllowPatterns,
+ readStore,
+ SECRETS_SCHEMA_VERSION,
+ type SecretAuditContext,
+ withSecretsLock,
+ writeStore,
+} from "./store.ts";
+
+/** Bundle schema version. Bumped only on an incompatible field change. */
+export const SECRET_BUNDLE_SCHEMA_VERSION = 1;
+
+/**
+ * Closed refusal table for every named failure shape of the bundle.
+ * Errors surface by code; nothing is assembled from prose at runtime.
+ */
+export const BUNDLE_REFUSAL_CODES = Object.freeze({
+ /** The bundle's schema version is not one this build reads. */
+ version: "secret_bundle_version_refused",
+ /** The bundle names a KDF this build does not implement. */
+ kdfAlgo: "secret_bundle_kdf_algo_refused",
+ /** The stored KDF parameters exceed (or fall below) this build's cost curve. */
+ kdfCost: "secret_bundle_kdf_params_refused",
+ /** The passphrase did not decrypt the entries (wrong passphrase, corrupt). */
+ passphrase: "secret_bundle_passphrase_refused",
+ /** The file is bundle-shaped but does not parse as one. */
+ malformed: "secret_bundle_malformed",
+ /** An entry's name or env-var mapping fails the store's own validation. */
+ entry: "secret_bundle_entry_refused",
+ /** An entry collides with a name the target store already holds. */
+ nameExists: "secret_bundle_name_exists",
+} as const);
+
+export type SecretBundleRefusalCode =
+ (typeof BUNDLE_REFUSAL_CODES)[keyof typeof BUNDLE_REFUSAL_CODES];
+
+/** A named bundle refusal: the stable `code` is the contract. */
+export class SecretBundleError extends Error {
+ readonly code: SecretBundleRefusalCode;
+
+ constructor(code: SecretBundleRefusalCode, detail: string) {
+ super(`secret bundle refused (${code}): ${detail}`);
+ this.name = "SecretBundleError";
+ this.code = code;
+ }
+}
+
+/** One bundle entry: the metadata travels in the clear, the value sealed. */
+export interface SecretBundleEntry {
+ readonly env_var: string;
+ readonly allow: ReadonlyArray<string>;
+ readonly value: EncryptedValue;
+}
+
+/** The on-disk bundle envelope. */
+export interface SecretBundleFile {
+ readonly version: number;
+ /** Wall clock of the export - deliberately OUTSIDE the sealed content. */
+ readonly generated_at: string;
+ readonly kdf: EnvelopeKdfParams;
+ readonly entries: Record<string, SecretBundleEntry>;
+}
+
+/**
+ * Export every stored entry as a bundle. Reads under the store's lock for
+ * one consistent snapshot; decrypts in memory and re-encrypts each value
+ * under the bundle's own derived key. A locked store refuses with the
+ * named locked-store error - exporting needs the plaintext values, and a
+ * bundle that skipped decryption would be a lie.
+ */
+export function exportSecretBundle(
+ vault: string,
+ passphrase: string,
+ ctx: SecretAuditContext,
+): SecretBundleFile {
+ assertVaultIdentityForWrite(vault);
+ const bundle = withSecretsLock(vault, () => {
+ if (passphrase.length === 0) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.passphrase,
+ "an export passphrase must not be empty",
+ );
+ }
+ const key = loadOrCreateKey(keyPath(vault));
+ const file = readStore(vault);
+ const kdf = freshWrapKdfParams();
+ const derived = deriveWrapKey(passphrase, kdf);
+ const entries: Record<string, SecretBundleEntry> = {};
+ for (const name of Object.keys(file.secrets).toSorted()) {
+ const stored = file.secrets[name]!;
+ entries[name] = {
+ env_var: stored.env_var,
+ allow: [...stored.allow],
+ value: encryptValue(derived, decryptValue(key, stored)),
+ };
+ }
+ return {
+ version: SECRET_BUNDLE_SCHEMA_VERSION,
+ generated_at: isoSecond(ctx.now),
+ kdf,
+ entries,
+ };
+ });
+ auditBundle(vault, ctx, "secret_bundle_exported", {
+ exported: Object.keys(bundle.entries).toSorted(),
+ });
+ return bundle;
+}
+
+/**
+ * The metadata tree the egress guard scans, shaped so the scan can only
+ * help and never corrupt:
+ *
+ * - The KDF block is EXCLUDED. Its random salt is exactly the high-
+ * entropy run the bare-token pass exists to catch, so scanning it
+ * would flag every export forever over config that carries no vault
+ * content. The parameters travel in the file regardless.
+ * - Entries are an ARRAY of objects, not a name-keyed map. A name like
+ * `api-key` as a mapping KEY is the redactor's credential-assignment
+ * shape (`api_key: ...`) and would replace the whole entry; as a
+ * string leaf it is judged as text instead.
+ * - The free-text fields (allow patterns) scan in full - that is the
+ * value the guard adds here.
+ *
+ * Names and env-var mappings are IDENTIFIERS: {@link bundleFromEgressScan}
+ * refuses rather than merges if the guard rewrote one.
+ */
+export function bundleEgressScanTree(bundle: SecretBundleFile): Record<string, unknown> {
+ return {
+ version: bundle.version,
+ generated_at: bundle.generated_at,
+ entries: Object.entries(bundle.entries)
+ .toSorted(([a], [b]) => a.localeCompare(b))
+ .map(([name, entry]) => ({ name, env_var: entry.env_var, allow: [...entry.allow] })),
+ };
+}
+
+/**
+ * Rebuild the bundle from the guard's redacted scan tree, re-attaching
+ * the sealed values. The scan tree is an array in a deterministic order,
+ * so the merge is by position. A redacted ALLOW pattern merges (the
+ * export then differs from the vault, and the notice says so); a
+ * REWRITTEN name or env-var mapping refuses the export instead - an
+ * identifier is never rewritten into the file that has to carry it.
+ */
+export function bundleFromEgressScan(bundle: SecretBundleFile, scanned: unknown): SecretBundleFile {
+ const fail = (detail: string): SecretBundleError =>
+ new SecretBundleError(BUNDLE_REFUSAL_CODES.entry, detail);
+ if (typeof scanned !== "object" || scanned === null) throw fail("redacted scan is not an object");
+ const entries = (scanned as { entries?: unknown }).entries;
+ if (!Array.isArray(entries)) throw fail("redacted scan lost the entry list");
+ const original = Object.entries(bundle.entries).toSorted(([a], [b]) => a.localeCompare(b));
+ if (entries.length !== original.length) {
+ throw fail("redacted scan has a different number of entries");
+ }
+ const out: Record<string, SecretBundleEntry> = {};
+ for (const [index, [name, entry]] of original.entries()) {
+ const scannedEntry = entries[index] as { name?: unknown; env_var?: unknown; allow?: unknown };
+ if (
+ typeof scannedEntry !== "object" ||
+ scannedEntry === null ||
+ typeof scannedEntry.name !== "string" ||
+ typeof scannedEntry.env_var !== "string" ||
+ !Array.isArray(scannedEntry.allow)
+ ) {
+ throw fail(`redacted scan lost the entry for "${name}"`);
+ }
+ if (scannedEntry.name !== name || scannedEntry.env_var !== entry.env_var) {
+ throw fail(
+ `the egress redactor rewrote an entry identifier (name "${name}", env var ` +
+ `${JSON.stringify(entry.env_var)}); an identifier is never rewritten into the ` +
+ "export - rename the entry in the store, or exclude it, then re-run",
+ );
+ }
+ out[name] = {
+ env_var: entry.env_var,
+ allow: scannedEntry.allow.map(String),
+ value: entry.value,
+ };
+ }
+ return { ...bundle, entries: out };
+}
+
+export interface ImportSecretBundleInput {
+ readonly passphrase: string;
+ /** Overwrite entries whose names the target store already holds. */
+ readonly replace: boolean;
+ readonly agent: string;
+ readonly now: Date;
+}
+
+/**
+ * Import a bundle into `vault`. Every value is decrypted and every name
+ * and env-var mapping validated BEFORE anything is written, so a wrong
+ * passphrase or a malformed entry leaves the target store untouched.
+ * Without `replace`, any colliding name refuses the whole import by
+ * name; with it, exactly those entries are overwritten.
+ */
+export function importSecretBundle(
+ vault: string,
+ bundle: unknown,
+ input: ImportSecretBundleInput,
+): { imported: string[]; replaced: string[] } {
+ // Guard ahead of the first byte the import writes.
+ assertVaultIdentityForWrite(vault);
+ const parsed = parseBundle(bundle);
+ if (input.passphrase.length === 0) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.passphrase,
+ "an import passphrase must not be empty",
+ );
+ }
+ const derived = deriveWrapKey(input.passphrase, parsed.kdf);
+ const decrypted = new Map<string, { value: string; env_var: string; allow: string[] }>();
+ for (const name of Object.keys(parsed.entries).toSorted()) {
+ const entry = parsed.entries[name]!;
+ if (!isValidSecretName(name)) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.entry,
+ `entry name does not match the store's name rule: ${JSON.stringify(name)}`,
+ );
+ }
+ if (!isValidSecretEnvVar(entry.env_var)) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.entry,
+ `entry "${name}" has an env-var mapping that fails the store's rule: ` +
+ JSON.stringify(entry.env_var),
+ );
+ }
+ // The third rule `set` enforces, applied to the imported allowlist:
+ // trim each pattern, refuse empty ones. The allow list rides in the
+ // clear, so without this a rewritten bundle could land entries the
+ // store's own writer would refuse.
+ let allow: string[];
+ try {
+ allow = normalizeAllowPatterns(entry.allow);
+ } catch {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.entry,
+ `entry "${name}" has an allow pattern that fails the store's rule: ` +
+ "patterns must be non-empty",
+ );
+ }
+ let value: string;
+ try {
+ value = decryptValue(derived, entry.value);
+ } catch {
+ // The GCM tag is the passphrase check. Nothing has been written.
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.passphrase,
+ "the passphrase does not open this bundle (wrong passphrase, or the bundle is corrupt); nothing was written",
+ );
+ }
+ decrypted.set(name, { value, env_var: entry.env_var, allow });
+ }
+
+ const replaced = withSecretsLock(vault, () => {
+ const file = readStore(vault);
+ const collisions = [...decrypted.keys()].filter(
+ (name) => !input.replace && file.secrets[name] !== undefined,
+ );
+ if (collisions.length > 0) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.nameExists,
+ `the store already holds: ${collisions.join(", ")}; pass --replace to import over them`,
+ );
+ }
+ const key = loadOrCreateKey(keyPath(vault));
+ const secrets = { ...file.secrets };
+ const overwritten: string[] = [];
+ for (const [name, entry] of decrypted) {
+ const current = file.secrets[name];
+ if (current !== undefined) overwritten.push(name);
+ secrets[name] = {
+ ...encryptValue(key, entry.value),
+ env_var: entry.env_var,
+ allow: entry.allow,
+ created_at: current?.created_at ?? isoSecond(input.now),
+ last_used_at: current?.last_used_at ?? null,
+ };
+ }
+ writeStore(vault, { version: SECRETS_SCHEMA_VERSION, secrets });
+ return overwritten;
+ });
+ const imported = [...decrypted.keys()].toSorted();
+ auditBundle(vault, input, "secret_bundle_imported", { imported, replaced: replaced.toSorted() });
+ return { imported, replaced: replaced.toSorted() };
+}
+
+// ----- Internals -------------------------------------------------------------
+
+/**
+ * Strict shape read: refuse an unknown version or KDF algo BY NAME, and a
+ * file that merely looks like a bundle with the malformed code.
+ */
+function parseBundle(bundle: unknown): SecretBundleFile {
+ if (typeof bundle !== "object" || bundle === null || Array.isArray(bundle)) {
+ throw new SecretBundleError(BUNDLE_REFUSAL_CODES.malformed, "not a bundle object");
+ }
+ const candidate = bundle as Partial<SecretBundleFile>;
+ if (typeof candidate.version !== "number" || typeof candidate.generated_at !== "string") {
+ throw new SecretBundleError(BUNDLE_REFUSAL_CODES.malformed, "missing envelope fields");
+ }
+ const kdf = candidate.kdf as Partial<EnvelopeKdfParams> | undefined;
+ if (
+ typeof kdf !== "object" ||
+ kdf === null ||
+ typeof kdf.algo !== "string" ||
+ typeof kdf.salt !== "string" ||
+ typeof kdf.n !== "number" ||
+ typeof kdf.r !== "number" ||
+ typeof kdf.p !== "number" ||
+ typeof kdf.maxmem !== "number"
+ ) {
+ throw new SecretBundleError(BUNDLE_REFUSAL_CODES.malformed, "missing kdf parameters");
+ }
+ if (candidate.version !== SECRET_BUNDLE_SCHEMA_VERSION) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.version,
+ `version ${String(candidate.version)} is not read by this build`,
+ );
+ }
+ if (kdf.algo !== "scrypt") {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.kdfAlgo,
+ `kdf algo ${JSON.stringify(kdf.algo)} is not implemented by this build`,
+ );
+ }
+ if (
+ !Number.isInteger(kdf.n) ||
+ kdf.n <= 0 ||
+ !Number.isInteger(kdf.r) ||
+ kdf.r <= 0 ||
+ !Number.isInteger(kdf.p) ||
+ kdf.p <= 0 ||
+ !Number.isInteger(kdf.maxmem) ||
+ kdf.maxmem <= 0
+ ) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.malformed,
+ "kdf parameters must be positive integers",
+ );
+ }
+ // The same cost-curve bound the keyfile envelope enforces: a crafted
+ // bundle's kdf block reaches `deriveWrapKey` verbatim, and an absurd
+ // cost is refused by name before scrypt allocates.
+ const costRefusal = kdfCostCurveRefusal(kdf as EnvelopeKdfParams);
+ if (costRefusal !== null) {
+ throw new SecretBundleError(BUNDLE_REFUSAL_CODES.kdfCost, costRefusal);
+ }
+ const entries = candidate.entries;
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
+ throw new SecretBundleError(BUNDLE_REFUSAL_CODES.malformed, "missing entries");
+ }
+ for (const [name, entry] of Object.entries(entries as Record<string, unknown>)) {
+ const fields = entry as Partial<SecretBundleEntry> | null;
+ if (
+ typeof fields !== "object" ||
+ fields === null ||
+ typeof fields.env_var !== "string" ||
+ !Array.isArray(fields.allow) ||
+ // Element types are checked here, not at match time: a non-string
+ // pattern must never reach the exec allowlist matcher.
+ !fields.allow.every((pattern) => typeof pattern === "string") ||
+ typeof fields.value !== "object" ||
+ fields.value === null ||
+ typeof (fields.value as EncryptedValue).ciphertext !== "string" ||
+ typeof (fields.value as EncryptedValue).iv !== "string" ||
+ typeof (fields.value as EncryptedValue).tag !== "string"
+ ) {
+ throw new SecretBundleError(
+ BUNDLE_REFUSAL_CODES.malformed,
+ `entry "${name}" is not a complete bundle entry`,
+ );
+ }
+ }
+ return bundle as SecretBundleFile;
+}
+
+/** The no-values custody record, the same discipline as the store's ops. */
+function auditBundle(
+ vault: string,
+ ctx: SecretAuditContext,
+ action: string,
+ details: Record<string, unknown>,
+): void {
+ appendAuditRecord(joinBrainLog(vault), {
+ timestamp: ctx.now.toISOString(),
+ actor: ctx.agent,
+ action,
+ target: "bundle",
+ ok: true,
+ details,
+ });
+}
+
+function joinBrainLog(vault: string): string {
+ return join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR);
+}
diff --git a/src/core/brain/secrets/crypto.ts b/src/core/brain/secrets/crypto.ts
index 4d56edd3..f72fef3d 100644
--- a/src/core/brain/secrets/crypto.ts
+++ b/src/core/brain/secrets/crypto.ts
@@ -1,14 +1,13 @@
/**
* Secret-custody crypto kernel (write-time-integrity-governance).
*
- * Per-value AES-256-GCM from node:crypto - random 12-byte IV per
- * encryption, authentication tag verified on every decrypt, so a
- * tampered ciphertext fails closed instead of decoding garbage. The
- * 32-byte key lives in a 0600 keyfile beside the ciphertext store (an
+ * The 32-byte key lives in a 0600 keyfile beside the ciphertext store (an
* owner-only ACL on Windows, see `owner-acl.ts`); both stay under the
* vault-local state dir, which is excluded from git by a marker file and
* must be excluded from a file syncer by the operator (see
- * `SYNC_EXCLUSION_CONTENT` below).
+ * `SYNC_EXCLUSION_CONTENT` below). Values themselves are sealed through
+ * the shared per-value cipher in the leaf `value-cipher.ts`, re-exported
+ * below so every custody consumer keeps one import path.
*
* Honest threat model (documented, not implied): this protects
* against secret values entering an agent's context, against vault
@@ -17,7 +16,7 @@
* host - there is no daemon and no TPM in this design.
*/
-import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
+import { randomBytes } from "node:crypto";
import {
chmodSync,
closeSync,
@@ -30,11 +29,19 @@ import {
} from "node:fs";
import { dirname, join } from "node:path";
+import { heldKeyOrRefusal, isEnvelopeBytes } from "./envelope.ts";
import { restrictToOwner } from "./owner-acl.ts";
-const ALGORITHM = "aes-256-gcm";
+/**
+ * The per-value cipher is re-exported from the leaf `value-cipher.ts` so
+ * the custody store and the export bundle keep importing it from this
+ * module, and the envelope wraps the keyfile's DEK through the same leaf
+ * instead of importing this kernel back (a two-module cycle).
+ */
+export { decryptValue, encryptValue } from "./value-cipher.ts";
+export type { EncryptedValue } from "./value-cipher.ts";
+
const KEY_BYTES = 32;
-const IV_BYTES = 12;
/**
* The git-exclusion marker this directory carries: a vault that is a git
@@ -73,15 +80,6 @@ function ensureSyncExclusionMarker(dir: string): void {
}
}
-export interface EncryptedValue {
- /** Base64 ciphertext. */
- readonly ciphertext: string;
- /** Base64 12-byte IV, unique per encryption. */
- readonly iv: string;
- /** Base64 GCM authentication tag. */
- readonly tag: string;
-}
-
/** Load the keyfile, creating it 0600 with 32 random bytes on first use. */
export function loadOrCreateKey(keyPath: string): Buffer {
const keyDir = dirname(keyPath);
@@ -111,6 +109,13 @@ export function loadOrCreateKey(keyPath: string): Buffer {
}
ensureSyncExclusionMarker(keyDir);
const key = readFileSync(keyPath);
+ // The passphrase-wrapped envelope replaces the raw file at the SAME
+ // path and carries the same ACL discipline (all of the above applies
+ // to it unchanged). There is nothing to create and nothing to mint:
+ // the key comes from this process's unlock holder, and an empty
+ // holder is the named locked-store refusal - never a fresh random
+ // key, which would silently orphan every stored value.
+ if (isEnvelopeBytes(key)) return heldKeyOrRefusal(keyPath);
if (key.length !== KEY_BYTES) {
throw new Error(`secrets keyfile is corrupt (expected ${KEY_BYTES} bytes): ${keyPath}`);
}
@@ -140,25 +145,3 @@ export function loadOrCreateKey(keyPath: string): Buffer {
restrictToOwner(keyPath, "file");
return key;
}
-
-export function encryptValue(key: Buffer, plaintext: string): EncryptedValue {
- const iv = randomBytes(IV_BYTES);
- const cipher = createCipheriv(ALGORITHM, key, iv);
- const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
- return {
- ciphertext: ciphertext.toString("base64"),
- iv: iv.toString("base64"),
- tag: cipher.getAuthTag().toString("base64"),
- };
-}
-
-/** Decrypt one value; a wrong key or tampered payload throws. */
-export function decryptValue(key: Buffer, encrypted: EncryptedValue): string {
- const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));
- decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));
- const plaintext = Buffer.concat([
- decipher.update(Buffer.from(encrypted.ciphertext, "base64")),
- decipher.final(),
- ]);
- return plaintext.toString("utf8");
-}
diff --git a/src/core/brain/secrets/envelope.ts b/src/core/brain/secrets/envelope.ts
new file mode 100644
index 00000000..84930149
--- /dev/null
+++ b/src/core/brain/secrets/envelope.ts
@@ -0,0 +1,517 @@
+/**
+ * Passphrase-wrapped keyfile envelope (t_e6667a56).
+ *
+ * The raw 32-byte DEK at the keyfile path can be replaced by a versioned
+ * scrypt envelope that only a passphrase unwraps. Opt-in by action, not by
+ * config: the presence of an envelope at the keyfile path is the state, and
+ * an unwrapped store needs no flag and behaves byte-identically to before.
+ *
+ * The KDF is scrypt from node:crypto with explicit, stored parameters
+ * (N = 2^15, r = 8, p = 1, 32-byte output, a fresh random 16-byte salt per
+ * envelope, maxmem set explicitly) so they can migrate without breaking old
+ * stores; an unknown algo or version refuses by name. Wrong-passphrase
+ * detection is free and fail-closed: the GCM authentication tag over the
+ * wrapped DEK throws. `timingSafeEqual` guards the one comparison between
+ * two pieces of derived key material this module makes (the holder-
+ * consistency check at re-unlock).
+ *
+ * The unlocked DEK lives ONLY in a process-local, memory-only holder in
+ * this module. There is no daemon: every CLI invocation and the MCP server
+ * unlock separately, `lock` clears this process's holder, and a second
+ * context over the same vault gets the named locked-store refusal. The
+ * passphrase itself is never persisted, logged, or audited.
+ *
+ * Honest warning, stated here because there is no recovery path and none
+ * is pretended: a lost passphrase makes every stored secret permanently
+ * unreadable. Against a root or same-user attacker nothing here helps -
+ * the threat model in `crypto.ts` is unchanged.
+ */
+
+import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
+import { chmodSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+import { renameWithRetry } from "../../fs-atomic.ts";
+import { type EncryptedValue, decryptValue, encryptValue } from "./value-cipher.ts";
+import { restrictToOwner } from "./owner-acl.ts";
+
+/** Envelope schema version. Bumped only on an incompatible field change. */
+export const KEYFILE_ENVELOPE_SCHEMA_VERSION = 1;
+
+const KDF_ALGO = "scrypt";
+/** Length of the passphrase-derived wrap key (AES-256). */
+const WRAP_KEY_BYTES = 32;
+/** Length of the DEK the envelope wraps (the raw keyfile's size). */
+const DEK_BYTES = 32;
+const SALT_BYTES = 16;
+const SCRYPT_N = 2 ** 15;
+const SCRYPT_R = 8;
+const SCRYPT_P = 1;
+// 128 * N * r is the memory scrypt needs for these parameters; the default
+// ceiling sits exactly at that line, so the headroom is set explicitly.
+const SCRYPT_MAXMEM = 128 * 1024 * 1024;
+
+/**
+ * The cost CEILING this build accepts from a stored envelope or bundle.
+ * The stored parameters are honored (not re-derived) - that is what makes
+ * migration possible - but honored UNBOUNDED they are a memory-pressure
+ * knob for anyone who can write the 0600 keyfile: a hand-edited
+ * `n: 2**31` sent scryptSync off to a terabyte-scale allocation. These
+ * caps leave 8x headroom over the build's own curve (which is ~8x under
+ * them); a curve that genuinely needs more ships as a new schema version.
+ */
+const SCRYPT_N_MAX = 2 ** 18;
+const SCRYPT_R_MAX = 16;
+const SCRYPT_P_MAX = 8;
+const SCRYPT_MAXMEM_MAX = 256 * 1024 * 1024;
+
+/**
+ * Why the stored KDF parameters fall outside this build's cost curve, or
+ * null when they are within it. Runs BEFORE scrypt sees the parameters,
+ * on every stored-params reader (the keyfile envelope and the bundle
+ * alike): an absurd cost is refused by name instead of allocated, and a
+ * `maxmem` below the parameters' own `128*n*r` need is the named refusal
+ * rather than node's raw memory error.
+ */
+export function kdfCostCurveRefusal(kdf: EnvelopeKdfParams): string | null {
+ if (kdf.n > SCRYPT_N_MAX) {
+ return `kdf n ${String(kdf.n)} exceeds this build's ceiling ${String(SCRYPT_N_MAX)}`;
+ }
+ if (kdf.r > SCRYPT_R_MAX) {
+ return `kdf r ${String(kdf.r)} exceeds this build's ceiling ${String(SCRYPT_R_MAX)}`;
+ }
+ if (kdf.p > SCRYPT_P_MAX) {
+ return `kdf p ${String(kdf.p)} exceeds this build's ceiling ${String(SCRYPT_P_MAX)}`;
+ }
+ if (kdf.maxmem > SCRYPT_MAXMEM_MAX) {
+ return `kdf maxmem ${String(kdf.maxmem)} exceeds this build's ceiling ${String(SCRYPT_MAXMEM_MAX)}`;
+ }
+ const needed = 128 * kdf.n * kdf.r;
+ if (kdf.maxmem < needed) {
+ return (
+ `kdf maxmem ${String(kdf.maxmem)} is below the ${String(needed)} bytes ` +
+ `these n/r parameters need`
+ );
+ }
+ return null;
+}
+
+/** The KDF parameters recorded inside an envelope, so they can migrate. */
+export interface EnvelopeKdfParams {
+ readonly algo: string;
+ /** Base64 random salt, fresh per envelope. */
+ readonly salt: string;
+ readonly n: number;
+ readonly r: number;
+ readonly p: number;
+ readonly maxmem: number;
+}
+
+/** The on-disk keyfile envelope: `{ version, kdf, wrapped }`. */
+export interface KeyfileEnvelope {
+ readonly version: number;
+ readonly kdf: EnvelopeKdfParams;
+ /** The DEK encrypted under the passphrase-derived key. */
+ readonly wrapped: EncryptedValue;
+}
+
+/**
+ * Closed refusal table for every named failure shape of the envelope.
+ * Errors surface by code; nothing is assembled from prose at runtime.
+ */
+export const ENVELOPE_REFUSAL_CODES = Object.freeze({
+ /** The envelope's schema version is not one this build reads. */
+ version: "keyfile_envelope_version_refused",
+ /** The envelope names a KDF this build does not implement. */
+ kdfAlgo: "keyfile_envelope_kdf_algo_refused",
+ /** The stored KDF parameters exceed ( or fall below) this build's cost curve. */
+ kdfCost: "keyfile_envelope_kdf_params_refused",
+ /** The passphrase did not unwrap the DEK (wrong passphrase, or corrupt). */
+ passphrase: "keyfile_envelope_passphrase_refused",
+ /** The file is envelope-shaped but does not parse as one. */
+ malformed: "keyfile_envelope_malformed",
+} as const);
+
+export type EnvelopeRefusalCode =
+ (typeof ENVELOPE_REFUSAL_CODES)[keyof typeof ENVELOPE_REFUSAL_CODES];
+
+/** A named envelope refusal: the stable `code` is the contract. */
+export class SecretEnvelopeError extends Error {
+ readonly code: EnvelopeRefusalCode;
+ readonly keyPath: string;
+
+ constructor(code: EnvelopeRefusalCode, keyPath: string, detail: string) {
+ // Path-free by construction, like the sibling locked-store and
+ // missing-keyfile refusals: the prose travels into model context
+ // through consumers that surface error text verbatim, and the keyfile
+ // path is machine-derived - the operator named --vault, never the
+ // keyfile. The path stays on `keyPath` for callers allowed to name
+ // the file.
+ super(`keyfile envelope refused (${code}): ${detail}`);
+ this.name = "SecretEnvelopeError";
+ this.code = code;
+ this.keyPath = keyPath;
+ }
+}
+
+/** Stable code every locked-store refusal carries. */
+export const SECRET_STORE_LOCKED_CODE = "secret_store_locked";
+
+/**
+ * A key-bearing operation met a wrapped keyfile and this process holds no
+ * unlocked key for it. The remedy is the unlock op, named in the message.
+ *
+ * The remedy is honest about the surface that prints it: the unlocked key
+ * lives in this module's per-process, memory-only holder, so the unlock
+ * the message names applies to THIS process only and the passphrase is
+ * never persisted - a one-shot CLI command cannot carry the unlock into
+ * the next command, and the text says so rather than pointing at a
+ * remedy that silently cannot work across processes.
+ *
+ * The MESSAGE is path-free by construction: the prose travels into model
+ * context through consumers that surface error text verbatim (a config
+ * probe's error list, a search refusal, a CLI catch), and the keyfile
+ * path under the vault is exactly what `src/mcp/vault-path-field.ts`
+ * degrades to keep out. The structured `keyPath` field stays for the
+ * callers that legitimately name the file.
+ */
+export class SecretStoreLockedError extends Error {
+ readonly code = SECRET_STORE_LOCKED_CODE;
+ readonly keyPath: string;
+
+ constructor(keyPath: string) {
+ super(
+ `the secret store is locked (the keyfile is passphrase-wrapped): run ` +
+ `"o2b brain secret unlock" to unwrap it for this process - the unlock ` +
+ `applies to this process only and the passphrase is never persisted, ` +
+ `so a key-bearing command must run in the same process that unlocked it`,
+ );
+ this.name = "SecretStoreLockedError";
+ this.keyPath = keyPath;
+ }
+}
+
+/** Stable code every missing-keyfile refusal carries. */
+export const SECRET_STORE_KEYFILE_MISSING_CODE = "secret_store_keyfile_missing";
+
+/**
+ * A key-bearing read met a store that still holds entries whose keyfile
+ * is gone. The sibling state of the locked refusal, and resolved the same
+ * way: minting a fresh key over the surviving ciphertext would orphan
+ * every stored value silently, with no error naming the mint, so a read
+ * refuses by name and only a restored keyfile recovers the store.
+ *
+ * The MESSAGE is path-free for the same reason the locked refusal's is:
+ * the prose travels into model context through consumers that surface
+ * error text verbatim (a config probe's error list, a search refusal, a
+ * CLI catch). The structured `keyPath` field stays for the callers that
+ * legitimately name the file.
+ */
+export class SecretStoreKeyfileMissingError extends Error {
+ readonly code = SECRET_STORE_KEYFILE_MISSING_CODE;
+ readonly keyPath: string;
+
+ constructor(keyPath: string) {
+ super(
+ `the secret store's keyfile is missing while the store still holds entries: ` +
+ `refusing to mint a fresh key over them - restore the keyfile to read the stored secrets`,
+ );
+ this.name = "SecretStoreKeyfileMissingError";
+ this.keyPath = keyPath;
+ }
+}
+
+// ----- The memory-only unlock holder -----------------------------------------
+
+/**
+ * The unlocked DEK per resolved keyfile path, for this process only.
+ * Keyed by resolved path so two vaults in one process stay independent,
+ * the same keying `owner-acl.ts` uses for its idempotence set.
+ */
+const HELD_KEYS = new Map<string, Buffer>();
+
+function holderSlot(keyPath: string): string {
+ const resolved = resolve(keyPath);
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
+}
+
+/**
+ * The key unlocked for `keyPath`, or null. Reads memory only; a locked
+ * store and an empty holder are the same answer here.
+ */
+export function heldUnlockedKey(keyPath: string): Buffer | null {
+ return HELD_KEYS.get(holderSlot(keyPath)) ?? null;
+}
+
+/**
+ * The held key, or the named locked-store refusal. This is the branch
+ * `loadOrCreateKey` takes when the keyfile on disk is an envelope.
+ */
+export function heldKeyOrRefusal(keyPath: string): Buffer {
+ const held = HELD_KEYS.get(holderSlot(keyPath));
+ if (held === undefined) throw new SecretStoreLockedError(keyPath);
+ return held;
+}
+
+/** Lock: drop this process's held key, overwriting its bytes first. */
+export function clearHeldKey(keyPath: string): void {
+ const slot = holderSlot(keyPath);
+ const held = HELD_KEYS.get(slot);
+ if (held !== undefined) {
+ held.fill(0);
+ HELD_KEYS.delete(slot);
+ }
+}
+
+// ----- Envelope shape --------------------------------------------------------
+
+/**
+ * Whether `parsed` has the envelope's field shape - WITHOUT judging the
+ * version or algo, which `readEnvelope` refuses by name. Detection has to
+ * accept an envelope this build cannot read, so a future version surfaces
+ * the version refusal rather than the raw-keyfile corrupt-length error.
+ */
+function hasEnvelopeShape(parsed: unknown): parsed is KeyfileEnvelope {
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
+ const candidate = parsed as Partial<KeyfileEnvelope>;
+ if (typeof candidate.version !== "number") return false;
+ const kdf = candidate.kdf as Partial<EnvelopeKdfParams> | undefined;
+ if (typeof kdf !== "object" || kdf === null || typeof kdf.algo !== "string") return false;
+ if (typeof kdf.salt !== "string" || typeof kdf.n !== "number") return false;
+ if (typeof kdf.r !== "number" || typeof kdf.p !== "number" || typeof kdf.maxmem !== "number") {
+ return false;
+ }
+ const wrapped = candidate.wrapped as Partial<EncryptedValue> | undefined;
+ return (
+ typeof wrapped === "object" &&
+ wrapped !== null &&
+ typeof wrapped.ciphertext === "string" &&
+ typeof wrapped.iv === "string" &&
+ typeof wrapped.tag === "string"
+ );
+}
+
+/**
+ * Whether the bytes at `keyPath` are an envelope. A raw 32-byte keyfile is
+ * indistinguishable from garbage to a JSON parser, so a true here is the
+ * safe direction; a corrupt ENVELOPE (truncated JSON) reads as false and
+ * fails closed on the raw branch's corrupt-length check instead. A missing
+ * file is not an envelope - callers check state before acting on it.
+ */
+export function isEnvelopeFile(keyPath: string): boolean {
+ let bytes: Buffer;
+ try {
+ bytes = readFileSync(keyPath);
+ } catch {
+ return false;
+ }
+ return isEnvelopeBytes(bytes);
+}
+
+/** {@link isEnvelopeFile} over bytes already read. */
+export function isEnvelopeBytes(bytes: Buffer): boolean {
+ try {
+ return hasEnvelopeShape(JSON.parse(bytes.toString("utf8")));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Strict read: parse, then refuse an unknown version or KDF algo BY NAME.
+ * The parameters are validated - shape, and this build's cost curve -
+ * before scrypt sees them, so a hand-edited envelope can neither hand the
+ * KDF an absurd cost nor starve it below its own memory need.
+ */
+export function readEnvelope(keyPath: string): KeyfileEnvelope {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(readFileSync(keyPath, "utf8"));
+ } catch (err) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.malformed,
+ keyPath,
+ `not parseable as an envelope: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (!hasEnvelopeShape(parsed)) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.malformed, keyPath, "missing fields");
+ }
+ if (parsed.version !== KEYFILE_ENVELOPE_SCHEMA_VERSION) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.version,
+ keyPath,
+ `version ${String(parsed.version)} is not read by this build`,
+ );
+ }
+ if (parsed.kdf.algo !== KDF_ALGO) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.kdfAlgo,
+ keyPath,
+ `kdf algo ${JSON.stringify(parsed.kdf.algo)} is not implemented by this build`,
+ );
+ }
+ if (
+ !Number.isInteger(parsed.kdf.n) ||
+ parsed.kdf.n <= 0 ||
+ !Number.isInteger(parsed.kdf.r) ||
+ parsed.kdf.r <= 0 ||
+ !Number.isInteger(parsed.kdf.p) ||
+ parsed.kdf.p <= 0 ||
+ !Number.isInteger(parsed.kdf.maxmem) ||
+ parsed.kdf.maxmem <= 0
+ ) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.malformed,
+ keyPath,
+ "kdf parameters must be positive integers",
+ );
+ }
+ const costRefusal = kdfCostCurveRefusal(parsed.kdf);
+ if (costRefusal !== null) {
+ throw new SecretEnvelopeError(ENVELOPE_REFUSAL_CODES.kdfCost, keyPath, costRefusal);
+ }
+ return parsed;
+}
+
+// ----- Wrap and unwrap -------------------------------------------------------
+
+/** Fresh KDF parameters: a new random salt under this build's cost curve. */
+export function freshWrapKdfParams(): EnvelopeKdfParams {
+ return {
+ algo: KDF_ALGO,
+ salt: randomBytes(SALT_BYTES).toString("base64"),
+ n: SCRYPT_N,
+ r: SCRYPT_R,
+ p: SCRYPT_P,
+ maxmem: SCRYPT_MAXMEM,
+ };
+}
+
+/** Derive the wrap key with the envelope's own stored parameters. */
+export function deriveWrapKey(passphrase: string, kdf: EnvelopeKdfParams): Buffer {
+ return scryptSync(passphrase, Buffer.from(kdf.salt, "base64"), WRAP_KEY_BYTES, {
+ N: kdf.n,
+ r: kdf.r,
+ p: kdf.p,
+ maxmem: kdf.maxmem,
+ });
+}
+
+function unwrapWith(derived: Buffer, envelope: KeyfileEnvelope, keyPath: string): Buffer {
+ let plaintext: string;
+ try {
+ plaintext = decryptValue(derived, envelope.wrapped);
+ } catch {
+ // The GCM tag is the passphrase check; a mismatch fails closed here,
+ // and the refusal is named rather than a raw cipher error.
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.passphrase,
+ keyPath,
+ "the passphrase does not unwrap this envelope (wrong passphrase, or the envelope is corrupt)",
+ );
+ }
+ const dek = Buffer.from(plaintext, "base64");
+ if (dek.length !== DEK_BYTES) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.malformed,
+ keyPath,
+ `unwrapped key material is ${String(dek.length)} bytes, expected ${String(DEK_BYTES)}`,
+ );
+ }
+ return dek;
+}
+
+/**
+ * Verify a passphrase against the envelope WITHOUT populating the holder.
+ * Used where the caller wants the named refusal and nothing else.
+ */
+export function verifyKeyfilePassphrase(keyPath: string, passphrase: string): void {
+ const envelope = readEnvelope(keyPath);
+ unwrapWith(deriveWrapKey(passphrase, envelope.kdf), envelope, keyPath);
+}
+
+/**
+ * Replace the raw keyfile at `keyPath` with the envelope wrapping `dek`
+ * under `passphrase`. The swap is atomic and lands at mode 0600: a torn
+ * wrap would destroy the only copy of the DEK, and the file this replaces
+ * was owner-only, so the envelope must inherit exactly that discipline.
+ */
+export function wrapKeyfile(keyPath: string, passphrase: string, dek: Buffer): KeyfileEnvelope {
+ if (passphrase.length === 0) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.passphrase,
+ keyPath,
+ "a wrap passphrase must not be empty",
+ );
+ }
+ if (dek.length !== DEK_BYTES) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.malformed,
+ keyPath,
+ `refusing to wrap ${String(dek.length)} bytes of key material, expected ${String(DEK_BYTES)}`,
+ );
+ }
+ const kdf = freshWrapKdfParams();
+ const envelope: KeyfileEnvelope = {
+ version: KEYFILE_ENVELOPE_SCHEMA_VERSION,
+ kdf,
+ wrapped: encryptValue(deriveWrapKey(passphrase, kdf), dek.toString("base64")),
+ };
+ const tmp = `${keyPath}.wrap-tmp`;
+ try {
+ writeFileSync(tmp, `${JSON.stringify(envelope, null, 2)}\n`, {
+ encoding: "utf8",
+ mode: 0o600,
+ });
+ renameWithRetry(tmp, keyPath);
+ } catch (err) {
+ try {
+ unlinkSync(tmp);
+ } catch {
+ // The tmp may never have been created; the original error is what
+ // the caller needs.
+ }
+ throw err;
+ }
+ // The envelope now IS the keyfile: the same owner-only treatment the raw
+ // file carried. The rename replaced the file behind this path, so the
+ // restriction runs against the idempotence memo - the renamed file
+ // inherited the directory's ACL, which must not survive. `restrictToOwner`
+ // is the Windows discipline and a no-op elsewhere, where the mode below is
+ // the whole story.
+ restrictToOwner(keyPath, "file", process.platform, true);
+ if (process.platform !== "win32") {
+ try {
+ chmodSync(keyPath, 0o600);
+ } catch (err) {
+ process.stderr.write(
+ `warning: could not re-apply owner-only mode to the wrapped keyfile: ` +
+ `${keyPath}: ${err instanceof Error ? err.message : String(err)}\n`,
+ );
+ }
+ }
+ return envelope;
+}
+
+/**
+ * Unlock: verify the passphrase and hold the DEK for this process.
+ * Returns the unwrapped key. A second unlock over an already-held path
+ * must unwrap to the SAME key - the comparison is constant-time - or the
+ * refusal fires rather than silently replacing held material.
+ */
+export function unlockKeyfile(keyPath: string, passphrase: string): Buffer {
+ const envelope = readEnvelope(keyPath);
+ const dek = unwrapWith(deriveWrapKey(passphrase, envelope.kdf), envelope, keyPath);
+ const slot = holderSlot(keyPath);
+ const held = HELD_KEYS.get(slot);
+ if (held !== undefined && !timingSafeEqual(held, dek)) {
+ throw new SecretEnvelopeError(
+ ENVELOPE_REFUSAL_CODES.malformed,
+ keyPath,
+ "the passphrase unwrapped a different key than the one this process already holds",
+ );
+ }
+ HELD_KEYS.set(slot, dek);
+ return dek;
+}
diff --git a/src/core/brain/secrets/owner-acl.ts b/src/core/brain/secrets/owner-acl.ts
index 3b068cad..1da51432 100644
--- a/src/core/brain/secrets/owner-acl.ts
+++ b/src/core/brain/secrets/owner-acl.ts
@@ -117,10 +117,11 @@ export function restrictToOwner(
path: string,
kind: "file" | "directory",
platform: NodeJS.Platform = process.platform,
+ force = false,
): boolean {
if (platform !== "win32") return true;
const key = `${kind}:${resolve(path).toLowerCase()}`;
- if (restricted.has(key)) return true;
+ if (!force && restricted.has(key)) return true;
let detail: string;
try {
const identity = currentWindowsIdentity();
diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.ts
index 1b6ce46d..34847e7b 100644
--- a/src/core/brain/secrets/store.ts
+++ b/src/core/brain/secrets/store.ts
@@ -24,6 +24,13 @@ import { brainDirsForWrite } from "../paths.ts";
import { isoSecond } from "../time.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";
+import {
+ clearHeldKey,
+ isEnvelopeFile,
+ SecretStoreKeyfileMissingError,
+ unlockKeyfile as unlockKeyfileAtPath,
+ wrapKeyfile as wrapKeyfileAtPath,
+} from "./envelope.ts";
import { restrictToOwner } from "./owner-acl.ts";
export const SECRETS_SCHEMA_VERSION = 1;
@@ -78,17 +85,45 @@ function storePath(vault: string): string {
return join(secretsDir(vault), "secrets.json");
}
-function keyPath(vault: string): string {
+/** The keyfile path - exported for `./bundle.ts`'s wrap and import paths. */
+export function keyPath(vault: string): string {
return join(secretsDir(vault), "keyfile");
}
+/** The name rule `set` enforces, shared with the bundle importer. */
+export function isValidSecretName(name: string): boolean {
+ return NAME_RE.test(name);
+}
+
+/** The env-var rule `set` enforces, shared with the bundle importer. */
+export function isValidSecretEnvVar(envVar: string): boolean {
+ return ENV_VAR_RE.test(envVar);
+}
+
+/**
+ * The allow-pattern rule `set` enforces: every pattern trims, and an
+ * empty one refuses. Shared with the bundle importer, so an imported
+ * entry can never carry an allowlist the store's own writer would have
+ * refused - a crafted bundle cannot broaden exec capability into a state
+ * `secret set` cannot have produced.
+ */
+export function normalizeAllowPatterns(patterns: ReadonlyArray<string>): string[] {
+ return patterns.map((pattern) => {
+ const trimmed = pattern.trim();
+ if (trimmed.length === 0) throw new Error("allow pattern must not be empty");
+ return trimmed;
+ });
+}
+
/**
* Serialise every read-modify-write of `secrets.json` across
* processes (CLI + MCP). proper-lockfile with retries, matching the
* search store's writer-lock discipline; the keyfile creation also
- * creates the directory the lock anchors on.
+ * creates the directory the lock anchors on. Exported for
+ * `./bundle.ts`, whose import path holds the same lock around its own
+ * read-collision-write sequence.
*/
-function withSecretsLock<T>(vault: string, fn: () => T): T {
+export function withSecretsLock<T>(vault: string, fn: () => T): T {
loadOrCreateKey(keyPath(vault));
// The sync lockfile API has no retry option; spin briefly the same
// way the search store's writer lock does.
@@ -134,11 +169,7 @@ export function setSecret(vault: string, input: SetSecretInput): SecretMetadata
if (!ENV_VAR_RE.test(envVar)) {
throw new Error(`secret env var must match ${ENV_VAR_RE}: ${JSON.stringify(envVar)}`);
}
- const allow = (input.allow ?? []).map((pattern) => {
- const trimmed = pattern.trim();
- if (trimmed.length === 0) throw new Error("allow pattern must not be empty");
- return trimmed;
- });
+ const allow = normalizeAllowPatterns(input.allow ?? []);
const key = loadOrCreateKey(keyPath(vault));
// Custody is a precondition, not a stderr line: on Windows, a keyfile
@@ -252,6 +283,103 @@ export function resolveSecretForExec(
return { name: normalized, env_var: stored.env_var, allow: stored.allow, value };
}
+/**
+ * Decrypt one secret WITHOUT the exec path's write half: no `last_used_at`
+ * stamp, no custody audit record, no vault-identity guard (it writes
+ * nothing). The read-only resolve the config-side secret resolver composes
+ * with (t_e5807974): a config read must not take the write path, and it
+ * must not look like an exec. Same shape as the exec resolve's answer, so
+ * a consumer sees one secret record either way.
+ *
+ * A name the store holds under a locked envelope surfaces the named
+ * locked-store refusal, and a store whose keyfile is MISSING while entries
+ * survive surfaces the named missing-keyfile refusal - never a silent
+ * fallback in either case, which would hide the store's real state from
+ * the caller. The missing-keyfile refusal is also what keeps this resolve
+ * read-only in fact and not just in name: `loadOrCreateKey` would mint a
+ * fresh key over the surviving ciphertext, silently orphaning every
+ * stored value. An unknown name fails with the same no-enumeration error
+ * the exec resolve uses.
+ */
+export function resolveSecretReadOnly(vault: string, name: string): ResolvedSecret {
+ const file = readStore(vault);
+ const normalized = name.trim().toLowerCase();
+ const stored = file.secrets[normalized];
+ if (stored === undefined) {
+ // Same discipline as {@link resolveSecretForExec}: `list` is the
+ // discovery surface, so a wrong name learns nothing.
+ throw new Error(`unknown secret "${normalized}"`);
+ }
+ const kp = keyPath(vault);
+ if (!existsSync(kp)) throw new SecretStoreKeyfileMissingError(kp);
+ const key = loadOrCreateKey(kp);
+ return {
+ name: normalized,
+ env_var: stored.env_var,
+ allow: stored.allow,
+ value: decryptValue(key, stored),
+ };
+}
+
+/**
+ * Unlock the store's wrapped keyfile for THIS PROCESS: verify the
+ * passphrase, hold the DEK in the envelope module's memory-only holder,
+ * and land the no-values custody record. On a store whose keyfile is
+ * still raw, this IS the opt-in: the raw 32 bytes are wrapped under the
+ * passphrase on first unlock, so unlocking is what creates the envelope.
+ *
+ * The passphrase is never persisted, logged, or audited, and a lost
+ * passphrase is unrecoverable - the verb's help says so in plain terms.
+ */
+export function unlockSecretKeyfile(
+ vault: string,
+ passphrase: string,
+ ctx: SecretAuditContext,
+): void {
+ // Guard ahead of the first byte: the wrap below replaces the keyfile.
+ assertVaultIdentityForWrite(vault);
+ const kp = keyPath(vault);
+ const wrapped = isEnvelopeFile(kp);
+ if (wrapped) {
+ unlockKeyfileAtPath(kp, passphrase);
+ } else {
+ // The wrap replaces the only copy of the DEK, so it serialises
+ // through the same writer lock every other read-modify-write of the
+ // custody directory takes: two concurrent first-unlocks must not
+ // interleave on the tmp path the swap writes. The shape check runs
+ // again UNDER the lock, so the loser of the race finds the envelope
+ // the winner just wrote and takes the unlock path instead of minting
+ // over it.
+ withSecretsLock(vault, () => {
+ if (!isEnvelopeFile(kp)) wrapKeyfileAtPath(kp, passphrase, loadOrCreateKey(kp));
+ });
+ // The wrap wrote the envelope but held nothing: verify-and-hold the
+ // key here, so the first unlock leaves THIS process unlocked - an
+ // unlock that left the process locked would fail the very remedy the
+ // locked-store refusal names.
+ unlockKeyfileAtPath(kp, passphrase);
+ }
+ audit(vault, ctx, "secret_unlocked", "keyfile", { keyfile_was_wrapped: wrapped });
+}
+
+/**
+ * Lock: clear this process's held key and land the no-values custody
+ * record. Strictly process-local - there is no daemon, so every other
+ * CLI invocation and the MCP server were already locked. A store whose
+ * keyfile was never wrapped has nothing to lock, and saying `secret
+ * locked` there would record a protection that does not exist, so it
+ * refuses by name.
+ */
+export function lockSecretKeyfile(vault: string, ctx: SecretAuditContext): void {
+ assertVaultIdentityForWrite(vault);
+ const kp = keyPath(vault);
+ if (!isEnvelopeFile(kp)) {
+ throw new Error(`secret lock: the keyfile is not passphrase-wrapped, nothing to lock: ${kp}`);
+ }
+ clearHeldKey(kp);
+ audit(vault, ctx, "secret_locked", "keyfile", {});
+}
+
/**
* The paths whose owner-only protection `set` requires before it stores
* material: the directory and the keyfile, which `loadOrCreateKey` has
@@ -284,7 +412,7 @@ function toMetadata(name: string, stored: StoredSecret): SecretMetadata {
};
}
-function readStore(vault: string): SecretsFile {
+export function readStore(vault: string): SecretsFile {
const path = storePath(vault);
if (!existsSync(path)) return { version: SECRETS_SCHEMA_VERSION, secrets: {} };
// Windows: a store that came in with a copied vault may carry an ACL
@@ -321,7 +449,7 @@ function readStore(vault: string): SecretsFile {
};
}
-function writeStore(vault: string, file: SecretsFile): void {
+export function writeStore(vault: string, file: SecretsFile): void {
// Key creation also creates the 0700 directory.
loadOrCreateKey(keyPath(vault));
const path = storePath(vault);
diff --git a/src/core/brain/secrets/sync-exposure.ts b/src/core/brain/secrets/sync-exposure.ts
index bfdd5678..3df1145c 100644
--- a/src/core/brain/secrets/sync-exposure.ts
+++ b/src/core/brain/secrets/sync-exposure.ts
@@ -183,3 +183,19 @@ export function formatSecretsSyncExposure(exposure: SecretsSyncExposure): string
`${exposure.stignorePath}: ${exposure.suggestedPattern}`
);
}
+
+/**
+ * The same gap, stated for a PASSPHRASE-WRAPPED keyfile (t_e6667a56): the
+ * envelope that syncs to every peer is not the raw key material, but the
+ * passphrase is now the only thing between a peer and offline guessing,
+ * so the warning names that residual protection instead of implying the
+ * wrap removed the exposure.
+ */
+export function formatWrappedKeyfileExposure(exposure: SecretsSyncExposure): string {
+ return (
+ `the passphrase-wrapped keyfile sits inside a Syncthing folder (${exposure.folderRoot}) ` +
+ `whose ${STIGNORE_FILE} does not ignore it, so the envelope syncs to every peer and the ` +
+ `passphrase is the only protection left against offline guessing there. Add this line to ` +
+ `${exposure.stignorePath}: ${exposure.suggestedPattern}`
+ );
+}
diff --git a/src/core/brain/secrets/value-cipher.ts b/src/core/brain/secrets/value-cipher.ts
new file mode 100644
index 00000000..8140cbf5
--- /dev/null
+++ b/src/core/brain/secrets/value-cipher.ts
@@ -0,0 +1,48 @@
+/**
+ * Per-value AES-256-GCM cipher (write-time-integrity-governance).
+ *
+ * Random 12-byte IV per encryption, authentication tag verified on every
+ * decrypt, so a tampered ciphertext fails closed instead of decoding
+ * garbage. This module is the LEAF both halves of the keyfile custody
+ * share: `crypto.ts` (the keyfile kernel) and `envelope.ts` (the
+ * passphrase-wrapped keyfile) each encrypt and decrypt values through it,
+ * so neither imports the other - the static back-edge the envelope once
+ * took into the kernel closed a two-module cycle whose initialisation
+ * order is undefined.
+ */
+
+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
+
+const ALGORITHM = "aes-256-gcm";
+const IV_BYTES = 12;
+
+export interface EncryptedValue {
+ /** Base64 ciphertext. */
+ readonly ciphertext: string;
+ /** Base64 12-byte IV, unique per encryption. */
+ readonly iv: string;
+ /** Base64 GCM authentication tag. */
+ readonly tag: string;
+}
+
+export function encryptValue(key: Buffer, plaintext: string): EncryptedValue {
+ const iv = randomBytes(IV_BYTES);
+ const cipher = createCipheriv(ALGORITHM, key, iv);
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
+ return {
+ ciphertext: ciphertext.toString("base64"),
+ iv: iv.toString("base64"),
+ tag: cipher.getAuthTag().toString("base64"),
+ };
+}
+
+/** Decrypt one value; a wrong key or tampered payload throws. */
+export function decryptValue(key: Buffer, encrypted: EncryptedValue): string {
+ const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(encrypted.iv, "base64"));
+ decipher.setAuthTag(Buffer.from(encrypted.tag, "base64"));
+ const plaintext = Buffer.concat([
+ decipher.update(Buffer.from(encrypted.ciphertext, "base64")),
+ decipher.final(),
+ ]);
+ return plaintext.toString("utf8");
+}
diff --git a/src/core/brain/session-summary.ts b/src/core/brain/session-summary.ts
index 7d25c097..8e7b8dcc 100644
--- a/src/core/brain/session-summary.ts
+++ b/src/core/brain/session-summary.ts
@@ -171,12 +171,74 @@ export function appendSessionSummary(
/** Latest digest for a session, or null when none was ever written. */
export function getSessionSummary(vault: string, sessionId: string): SessionSummaryDigest | null {
+ return getSessionSummaryReport(vault, sessionId)?.digest ?? null;
+}
+
+/**
+ * How many divergence records the report samples, at most. The count is
+ * always the honest total; the sample keeps the NEWEST entries so the list
+ * reads as "the digests behind the latest answer", never a payload echo.
+ */
+export const DIVERGENCE_RECORD_SAMPLE_LIMIT = 20;
+
+/** One divergent digest, named by identity and content hash, never its payload. */
+export interface SessionSummaryRecordRef {
+ readonly id: string;
+ readonly createdAt: string;
+ readonly contentHash: string;
+}
+
+export interface SessionSummaryReport {
+ /** The sorted-latest digest - the same answer {@link getSessionSummary} gives. */
+ readonly digest: SessionSummaryDigest;
+ /** How many digests exist for this session id, dedupe applied. */
+ readonly digestCount: number;
+ /** Present, always `true`, only when `digestCount` exceeds one. */
+ readonly divergent?: true;
+ /**
+ * Bounded newest-first-sample of the session's digests, oldest first,
+ * present only alongside `divergent`.
+ */
+ readonly records?: ReadonlyArray<SessionSummaryRecordRef>;
+}
+
+/**
+ * Divergence-aware single-session read (t_59d4c919). The continuity store
+ * is append-only, so one session id can hold several content-differing
+ * digests; the plain read answers latest-wins without saying so. This read
+ * names the fact: the sorted-latest digest plus `digest_count`, and, only
+ * when the count exceeds one, `divergent: true` plus a bounded
+ * id/created_at/content_hash sample. Divergence is REPORTED here - never
+ * merged, deleted, or reconciled.
+ */
+export function getSessionSummaryReport(
+ vault: string,
+ sessionId: string,
+): SessionSummaryReport | null {
const id = sessionId.trim();
const records = sessionDigestRecords(vault).filter(
(record) => String(record.payload["session_id"] ?? "") === id,
);
if (records.length === 0) return null;
- return toDigest(records[records.length - 1]!);
+ const digestCount = records.length;
+ return Object.freeze({
+ digest: toDigest(records[records.length - 1]!),
+ digestCount,
+ ...(digestCount > 1
+ ? {
+ divergent: true as const,
+ records: Object.freeze(
+ records.slice(-DIVERGENCE_RECORD_SAMPLE_LIMIT).map((record) =>
+ Object.freeze({
+ id: record.id,
+ createdAt: record.createdAt,
+ contentHash: String(record.payload["content_hash"] ?? ""),
+ }),
+ ),
+ ),
+ }
+ : {}),
+ });
}
export interface ListSessionSummariesOptions {
@@ -213,15 +275,16 @@ export function listSessionSummaries(
}
function sessionDigestRecords(vault: string): ReadonlyArray<ContinuityRecord> {
+ // `toSorted` is stable, so records the store reads in the same
+ // created_at instant keep the store's own arrival order - the tie-break
+ // that says which of two same-instant writes was written second. An id
+ // tie-break here would order same-instant digests by content hash,
+ // which is arbitrary, and "latest wins" would answer randomly.
return listContinuityRecords(vault, { kind: KIND }).toSorted((left, right) =>
- compareByCreatedThenId(left, right),
+ left.createdAt.localeCompare(right.createdAt),
);
}
-function compareByCreatedThenId(left: ContinuityRecord, right: ContinuityRecord): number {
- return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
-}
-
function buildSourceRefs(
sessionId: string,
turnIds: ReadonlyArray<string> | undefined,
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index e9230195..00f0c16e 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -43,7 +43,8 @@ import {
type OriginChannelStamp,
} from "../origin-channel.ts";
import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";
-import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
+import { writeFrontmatterAtomic, parseFrontmatter, slugify } from "../vault.ts";
+import { requireObsidianTagValue } from "./tag-syntax.ts";
import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";
import { allocateAndCreate, brainDirsForWrite, validateIsoDate } from "./paths.ts";
import {
@@ -793,6 +794,13 @@ function readOptionalTrimmedString(
* and (optionally) per-scope tags. Any `extraTags` supplied by the
* caller are appended after dedup. We preserve insertion order so the
* file is byte-stable across writes with identical input.
+ *
+ * Every composed value obeys the ONE shared tag rule (`src/core/tags.ts`,
+ * via `tag-syntax.ts`): the topic segment is slugified - the same
+ * treatment the filename slug gets - and refused only if even the slug
+ * fails the rule; scope segments and `extraTags` entries are
+ * caller-controlled input and are refused unrewritten, with the field
+ * named (`TagSyntaxError`).
*/
function composeSignalTags(input: WriteSignalInput): string[] {
const out: string[] = [];
@@ -805,9 +813,9 @@ function composeSignalTags(input: WriteSignalInput): string[] {
};
push("brain");
push("brain/signal");
- push(`brain/topic/${input.topic.trim()}`);
+ push(`brain/topic/${requireObsidianTagValue(slugify(input.topic.trim()), "topic")}`);
if (input.scope && input.scope.trim()) {
- push(`brain/scope/${input.scope.trim()}`);
+ push(`brain/scope/${requireObsidianTagValue(input.scope.trim(), "scope")}`);
}
// Non-default source_type gets its own tag so Obsidian users can
// filter `tag:brain/source/inline` etc. `live` is the implicit
@@ -816,7 +824,7 @@ function composeSignalTags(input: WriteSignalInput): string[] {
push(`brain/source/${input.source_type}`);
}
for (const t of input.extraTags ?? []) {
- if (t.trim()) push(t.trim());
+ if (t.trim()) push(requireObsidianTagValue(t.trim(), "extraTags"));
}
return out;
}
diff --git a/src/core/brain/source-cleanup.ts b/src/core/brain/source-cleanup.ts
index 7031077b..618d26f0 100644
--- a/src/core/brain/source-cleanup.ts
+++ b/src/core/brain/source-cleanup.ts
@@ -774,10 +774,18 @@ export function deleteBySource(
}
if (manifestKey !== null && existsSync(manifestPath(vault))) {
- const entries = { ...readManifest(vault).entries };
+ const manifest = readManifest(vault);
+ const entries = { ...manifest.entries };
if (entries[manifestKey] !== undefined) {
delete entries[manifestKey];
- manifestEntryRemoved = writeManifestAtomic(vault, entries);
+ // Round-trip the contract the manifest was read with (t_586d5d8b):
+ // a cleanup that only removes an entry must not re-stamp the
+ // extraction contract the remaining entries were recorded under -
+ // and a v1 read (contract `null`) round-trips as v1, because its
+ // survivors were never reprocessed under any fingerprint. Upgrading
+ // them here would classify them `unchanged` forever and silently
+ // forfeit the owed one-time reprocess.
+ manifestEntryRemoved = writeManifestAtomic(vault, entries, manifest.contract);
}
}
} catch (err) {
diff --git a/src/core/brain/tag-syntax.ts b/src/core/brain/tag-syntax.ts
new file mode 100644
index 00000000..0ba0855b
--- /dev/null
+++ b/src/core/brain/tag-syntax.ts
@@ -0,0 +1,50 @@
+/**
+ * Tag syntax validation for COMPOSED frontmatter tags (trust-surface-
+ * hardening wave; kanban t_11ee559f).
+ *
+ * The rule itself lives in `src/core/tags.ts` (`isObsidianTagValue`,
+ * derived from the index's `TAG_RE`) - one spelling, consumed here,
+ * never redefined. This module adds the typed refusal the tag composers
+ * raise: caller-controlled input that fails the shared rule is rejected
+ * with the offending FIELD named, shaped like `SchemaVocabularyError`
+ * (stable error name plus structured `field` / `token`; the message
+ * carries the field and the rule, never an ad-hoc sentence).
+ */
+
+import { isObsidianTagValue } from "../tags.ts";
+
+export { isObsidianTagValue };
+
+/**
+ * The rule text every refusal carries, hoisted once: a tag value starts
+ * with a letter or underscore and continues with letters, numbers,
+ * dashes, underscores, or slashes - never only digits, never a leading
+ * slash, never a space or other special.
+ */
+const TAG_VALUE_RULE_TEXT =
+ "must start with a letter or underscore and contain only letters, numbers, dashes, underscores, or slashes (never only digits)";
+
+/** Typed refusal for a composed tag value that fails the shared rule. */
+export class TagSyntaxError extends Error {
+ readonly field: string;
+ readonly token: unknown;
+
+ constructor(field: string, token: unknown, message: string) {
+ super(`${field}: ${message}`);
+ this.name = "TagSyntaxError";
+ this.field = field;
+ this.token = token;
+ }
+}
+
+/**
+ * Return `value` when it satisfies the shared tag rule; otherwise throw
+ * {@link TagSyntaxError} naming `field`. Composers call this on every
+ * segment they interpolate into a tag.
+ */
+export function requireObsidianTagValue(value: string, field: string): string {
+ if (!isObsidianTagValue(value)) {
+ throw new TagSyntaxError(field, value, TAG_VALUE_RULE_TEXT);
+ }
+ return value;
+}
diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.ts
index 48a5dcc2..5c91d0e8 100644
--- a/src/core/brain/upgrade.ts
+++ b/src/core/brain/upgrade.ts
@@ -19,6 +19,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFileSync, fileMatchesExpected, isFileDrift } from "../fs-atomic.ts";
+import { digestVerifies, sealWithDigest } from "../integrity/digest.ts";
import { formatFrontmatter, parseFrontmatterText } from "../vault.ts";
import { sanitisePrinciple } from "./text/sanitize-principle.ts";
import { defaultConfigPath, resolveAgentName } from "../config.ts";
@@ -62,6 +63,15 @@ export interface UpgradePlan {
readonly pending: number;
/** Count of `status === "error"` files. */
readonly errors: number;
+ /**
+ * The plan's seal (t_18fda844): the integrity module's
+ * `sealWithDigest` over the rows, pending and errors above. Sealed
+ * inside {@link planUpgrade} and verified at the top of
+ * {@link applyUpgrade}, so a plan object edited after it was shown is
+ * refused instead of applied. The body carries no wall-clock field,
+ * so the same managed-file state seals identically on every run.
+ */
+ readonly digest: string;
}
export interface UpgradeApplyResult {
@@ -126,11 +136,7 @@ export function planUpgrade(vault: string): UpgradePlan {
];
const pending = files.filter((f) => f.status === "update").length;
const errors = files.filter((f) => f.status === "error").length;
- return Object.freeze({
- files: Object.freeze(files),
- pending,
- errors,
- });
+ return Object.freeze(sealWithDigest({ files: Object.freeze(files), pending, errors }));
}
// ----- applyUpgrade --------------------------------------------------------
@@ -140,8 +146,10 @@ export function planUpgrade(vault: string): UpgradePlan {
* {@link planUpgrade} when no plan is given.
*
* Sequence:
- * 1. Take the plan. If `errors > 0`, throw — never touch disk
- * when the schema source is malformed.
+ * 1. Take the plan. Verify its digest against its body (t_18fda844)
+ * - a caller-supplied plan that fails the seal is refused before
+ * anything about it is trusted. Then, if `errors > 0`, throw —
+ * never touch disk when the schema source is malformed.
* 2. If `pending === 0`, return early without taking a snapshot or
* appending a log row. Idempotent re-run is free.
* 3. Check every `update` row against the disk. A file that no
@@ -158,10 +166,33 @@ export function planUpgrade(vault: string): UpgradePlan {
* On any write failure mid-step we throw — the snapshot already
* persisted is the recovery path (`o2b brain rollback upgrade-<ts>`).
*/
+/**
+ * The refusal for a caller-supplied plan whose digest no longer
+ * describes its body (t_18fda844) - the seam where a plan object edited
+ * after it was shown used to be trusted as-is. Distinct from the
+ * byte-drift refusal below: nothing drifted ON DISK, the PLAN is what
+ * failed its own seal, and the remedy is the same fresh dry run.
+ */
+const UPGRADE_SEAL_REFUSAL =
+ "upgrade refused: the upgrade plan does not match its own digest, so the plan object was " +
+ "edited or assembled after it was sealed. A plan nobody measured cannot be applied. Nothing " +
+ "was written and no snapshot was taken; re-run `o2b brain upgrade --dry-run` to get a sealed " +
+ "plan, then apply it.";
+
export function applyUpgrade(vault: string, opts: ApplyUpgradeOptions = {}): UpgradeApplyResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
const plan = opts.plan ?? planUpgrade(vault);
+ // The seal is checked FIRST - before the error rows, the no-op
+ // return, the byte-drift check and the snapshot. A plan object that
+ // fails its own digest is a plan somebody edited after it was shown;
+ // its rows are not consulted at all, not even to report their errors.
+ // A self-computed plan verifies trivially, so this changes nothing
+ // for the caller who plans and applies in one breath.
+ const { digest: _digest, ...planBody } = plan;
+ if (!digestVerifies(planBody, plan.digest)) {
+ throw new BrainUpgradeError(UPGRADE_SEAL_REFUSAL);
+ }
if (plan.errors > 0) {
const messages = plan.files
.filter((f) => f.status === "error")
diff --git a/src/core/config.ts b/src/core/config.ts
index d8ec51de..f076fd84 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -15,6 +15,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
import lockfile from "proper-lockfile";
import { atomicWriteFileSync, sleepSync } from "./fs-atomic.ts";
+import { isSecretReferenceValue, SecretReferenceError } from "./secret-ref.ts";
import { APP_DIR_NAME, configBaseDir } from "./platform-dirs.ts";
import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";
import { resolvePointerVault } from "./brain/portability/pointer.ts";
@@ -26,6 +27,52 @@ import {
import type { LinkOutputFormat } from "./brain/wikilink.ts";
import type { ConfigDiscovery } from "./types.ts";
+/**
+ * The named-secret resolver port (trust-surface-hardening, t_e5807974).
+ *
+ * A `$secret:` reference in a config value resolves through the vault's
+ * custody store, whose own import neighbourhood reaches back into THIS
+ * module (store -> audit -> ledger-shards -> config), so a static import
+ * of the resolver here closed the six-module cycle config ->
+ * secret-resolver -> custody store -> audit -> ledger-shards -> config,
+ * whose initialisation order is undefined. Config is the base layer and
+ * carries only the PORT; the resolver plane is the adapter and fills it
+ * through {@link installNamedSecretResolver} when `secret-resolver.ts`
+ * loads - which every production entry (the CLI's `main.ts`, the MCP
+ * server, the OpenClaw bridge) does statically at startup, before any
+ * command dispatch.
+ */
+export interface NamedSecretResolver {
+ /** Resolve one `$secret:` reference against `vault`'s custody store. */
+ resolveNamedSecret(vault: string, value: string): string;
+}
+
+let namedSecretResolver: NamedSecretResolver | undefined;
+
+/** Fill the {@link NamedSecretResolver} port; see its docblock for the wiring. */
+export function installNamedSecretResolver(resolver: NamedSecretResolver): void {
+ namedSecretResolver = resolver;
+}
+
+/**
+ * Resolve one reference through the installed resolver. The refusal is
+ * unreachable in a wired process (see the port's docblock); failing
+ * closed by name keeps an unwired one from ever treating a stored
+ * reference as literal text - for the installation secret that mistake
+ * would self-heal a fresh key right over the reference.
+ */
+function resolveThroughNamedSecretResolver(vault: string, reference: string): string {
+ const resolver = namedSecretResolver;
+ if (resolver === undefined) {
+ throw new SecretReferenceError(
+ "no named-secret resolver is installed in this process; the $secret: reference " +
+ "cannot be resolved against the vault's custody store",
+ reference,
+ );
+ }
+ return resolver.resolveNamedSecret(vault, reference);
+}
+
const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
/**
@@ -549,7 +596,7 @@ export function isValidInstallationSecret(value: string): boolean {
return INSTALLATION_SECRET_RE.test(value);
}
-export function resolveInstallationSecret(configPath?: string): string {
+export function resolveInstallationSecret(configPath?: string, secretsVault?: string): string {
// Env override exists for deterministic tests only, and is accepted solely
// as a full 32-hex key so it can never make the secret empty or guessable.
const env = process.env[INSTALLATION_SECRET_ENV_KEY];
@@ -557,8 +604,40 @@ export function resolveInstallationSecret(configPath?: string): string {
const resolved = configPath ?? defaultConfigPath();
const read = (): string | null => {
- const value = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
- return value && isValidInstallationSecret(value) ? value : null;
+ const raw = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
+ // A persisted value written as a `$secret:NAME` reference NEVER
+ // self-heals. The reference is the operator's stored intent, and the
+ // self-heal below would mint a fresh key over it - silently
+ // destroying the reference AND rotating the HMAC key, which changes
+ // every `vault://` reference agents correlate by, with no error
+ // naming anything. So every reference outcome is either the resolved
+ // key or a named refusal: unresolvable (the store and the
+ // environment cannot answer), locked (the store refuses), resolves
+ // but not a 32-hex key (the stored value is not an installation
+ // secret), or no vault passed to resolve against. Self-heal only
+ // ever mints when NO reference exists - a missing or plain corrupt
+ // value, exactly as before.
+ if (isSecretReferenceValue(raw)) {
+ const reference = String(raw).trim();
+ if (secretsVault === undefined) {
+ throw new SecretReferenceError(
+ "installation_secret is a $secret: reference but no vault was passed to resolve " +
+ "it against; pass the vault (or set O2B_INSTALLATION_SECRET to a 32-hex key)",
+ reference,
+ );
+ }
+ const resolvedValue = resolveThroughNamedSecretResolver(secretsVault, reference);
+ if (!isValidInstallationSecret(resolvedValue)) {
+ throw new SecretReferenceError(
+ "installation_secret is a $secret: reference that resolves to a value which is " +
+ "not a 32-hex installation key; fix the stored value - the reference in the " +
+ "device config is never overwritten",
+ reference,
+ );
+ }
+ return resolvedValue;
+ }
+ return raw && isValidInstallationSecret(raw) ? raw : null;
};
const existing = read();
@@ -613,7 +692,9 @@ const VAULT_STORE_REF_HEX_LEN = 32;
* `vaultPathField` in `src/mcp/tools.ts`.
*/
export function vaultStoreReference(vaultPath: string, configPath?: string): string {
- const key = resolveInstallationSecret(configPath);
+ // The referenced vault's custody store backs a `$secret:` reference in
+ // the persisted key; a plain key resolves exactly as before.
+ const key = resolveInstallationSecret(configPath, vaultPath);
const digest = createHmac("sha256", key)
.update(resolve(vaultPath))
.digest("hex")
@@ -1494,15 +1575,23 @@ export function resolveSessionCaptureRoles(configPath?: string): SessionCaptureR
/**
* Inbound Telegram capture bot token (Knowledge intake suite, t_f8f5ef6a).
* Order: `TELEGRAM_BOT_TOKEN` env -> `telegram_bot_token` config -> null.
- * The key contains "token", so `redactConfigMapping` (src/core/egress)
- * redacts it from any config snapshot. `null` (the default) means the
- * capture runner exits with a typed error rather than starting; nothing
- * runs without an explicit token.
+ * A value written as a `$secret:NAME` reference resolves through the passed
+ * vault's custody store. The key contains "token", so `redactConfigMapping`
+ * (src/core/egress) redacts it from any config snapshot. `null` (the
+ * default) means the capture runner exits with a typed error rather than
+ * starting; nothing runs without an explicit token.
*/
-export function resolveTelegramBotToken(configPath?: string): string | null {
+export function resolveTelegramBotToken(configPath?: string, secretsVault?: string): string | null {
const env = process.env["TELEGRAM_BOT_TOKEN"]?.trim();
const raw = env || discoverConfig(configPath).data["telegram_bot_token"]?.trim();
- return raw !== undefined && raw.length > 0 ? raw : null;
+ if (raw === undefined || raw.length === 0) return null;
+ // A token written as a `$secret:NAME` reference resolves through the
+ // vault's custody store (read-only); without the vault the value is
+ // taken as-is, exactly as before the resolver routing existed.
+ if (secretsVault !== undefined && isSecretReferenceValue(raw)) {
+ return resolveThroughNamedSecretResolver(secretsVault, raw);
+ }
+ return raw;
}
/**
diff --git a/src/core/decision-model/config.ts b/src/core/decision-model/config.ts
index f0e6fb3f..e5aadf35 100644
--- a/src/core/decision-model/config.ts
+++ b/src/core/decision-model/config.ts
@@ -30,6 +30,12 @@
*/
import { assertHttpEgressEndpoint } from "../search/embeddings/http-util.ts";
+import {
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+} from "../brain/secrets/envelope.ts";
+import { SecretReferenceError } from "../secret-ref.ts";
+import { isSecretReferenceValue, resolveNamedSecret } from "../secret-resolver.ts";
import { envOrConfig } from "../validate.ts";
import {
DECISION_MODEL_USES,
@@ -134,6 +140,38 @@ function setting(
return envOrConfig(env, config, `${ENV_PREFIX}${suffix.toUpperCase()}`, key);
}
+/**
+ * The key value for presence, with reference routing. A value written as
+ * a `$secret:NAME` reference resolves through the custody store of
+ * `secretsVault` (store first, env fallback); an unresolvable reference, a
+ * store-held name under a locked envelope, or a store whose keyfile is
+ * missing while entries survive lands in `errors` as the named refusal -
+ * with the status turning `invalid` - never as a silent empty key.
+ * Without a vault the value is taken as-is, exactly as before the routing
+ * existed, and resolution still never throws.
+ */
+function resolveKeyValue(
+ raw: string | undefined,
+ secretsVault: string | null | undefined,
+ errors: string[],
+): string | undefined {
+ if (typeof raw !== "string" || secretsVault === null || secretsVault === undefined) return raw;
+ if (!isSecretReferenceValue(raw)) return raw;
+ try {
+ return resolveNamedSecret(secretsVault, raw.trim());
+ } catch (err) {
+ if (
+ err instanceof SecretReferenceError ||
+ err instanceof SecretStoreLockedError ||
+ err instanceof SecretStoreKeyfileMissingError
+ ) {
+ errors.push(err.message);
+ return undefined;
+ }
+ throw err;
+ }
+}
+
const ALL_OFF: DecisionModelUses = Object.freeze(
Object.fromEntries(DECISION_MODEL_USES.map((use) => [use, "off"])) as Record<
DecisionModelUse,
@@ -221,6 +259,12 @@ export interface ResolveDecisionModelOptions {
readonly config: Readonly<Record<string, string>>;
/** Vault whose `_brain.yaml` may opt out; null when there is none. */
readonly vault: string | null;
+ /**
+ * Vault whose custody store backs `$secret:` references in the key
+ * value; absent, a reference-shaped key value is taken as-is, exactly
+ * as before the resolver routing existed.
+ */
+ readonly secretsVault?: string | null;
/**
* Reads the vault opt-out. Injected so this module never imports the
* whole policy loader at startup; defaults to the real loader.
@@ -271,7 +315,11 @@ export function resolveDecisionModelConfig(
const envKeyValid = envKeyRaw === null || ENV_VAR_NAME_RE.test(envKeyRaw);
// An invalid name is never looked up and never reported back.
const envKey = envKeyValid ? envKeyRaw : null;
- const keyValue = envKey !== null ? env[envKey] : undefined;
+ const keyValue = resolveKeyValue(
+ envKey !== null ? env[envKey] : undefined,
+ opts.secretsVault,
+ errors,
+ );
const keyPresent = typeof keyValue === "string" && keyValue.trim() !== "";
const configuredUses = parseDecisionModelUses(setting(env, config, "uses"), []);
diff --git a/src/core/decision-model/diagnostics.ts b/src/core/decision-model/diagnostics.ts
index d54fb9aa..c65f3a83 100644
--- a/src/core/decision-model/diagnostics.ts
+++ b/src/core/decision-model/diagnostics.ts
@@ -13,6 +13,12 @@ import { CHOICE_MAX_OPTIONS } from "./answers.ts";
import { DECISION_MODEL_USES, isDecisionModelUse, type DecisionModelUse } from "./contract.ts";
import { resolveDecisionModelConfig, type ResolvedDecisionModelConfig } from "./config.ts";
import { makeDecisionProvider } from "./provider.ts";
+import type { DecisionProvider } from "./contract.ts";
+import { SecretReferenceError } from "../secret-ref.ts";
+import {
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+} from "../brain/secrets/envelope.ts";
import {
DECISION_MODEL_CALL_KIND,
emitDecisionModelCall,
@@ -147,7 +153,17 @@ export async function buildDecisionModelCheck(
opts: DecisionModelCheckOptions,
): Promise<DecisionModelCheckReport> {
const env = opts.env ?? process.env;
- const cfg = resolveDecisionModelConfig({ env, config: opts.config, vault: opts.vault });
+ // The vault's own custody store backs a `$secret:` reference in the key
+ // value: without this thread the check reported `active` for a reference
+ // it could not resolve, deferring the failure to the use site - and the
+ // ping below built a provider whose Bearer key was the raw `$secret:`
+ // literal.
+ const cfg = resolveDecisionModelConfig({
+ env,
+ config: opts.config,
+ vault: opts.vault,
+ secretsVault: opts.vault ?? undefined,
+ });
const warnings: string[] = [];
const notes: string[] = [];
const sendsData = DECISION_MODEL_USES.some((use) => cfg.uses[use] !== "off");
@@ -252,7 +268,25 @@ export async function buildDecisionModelCheck(
};
if (opts.ping !== true) return report;
- const provider = makeDecisionProvider(cfg, env);
+ // The ping resolves the key the way the real request path does (the
+ // factory re-resolves at call time). A store that locks between the
+ // config probe and here - or whose keyfile is missing while entries
+ // survive - raises the named refusal, degraded into the ping's reason,
+ // never sent as a Bearer key and never left to escape the check as an
+ // exception.
+ let provider: DecisionProvider | null;
+ try {
+ provider = makeDecisionProvider(cfg, env, opts.vault ?? undefined);
+ } catch (err) {
+ if (
+ err instanceof SecretStoreLockedError ||
+ err instanceof SecretStoreKeyfileMissingError ||
+ err instanceof SecretReferenceError
+ ) {
+ return { ...report, ping: { ok: false, reason: `not sent: ${err.message}` } };
+ }
+ throw err;
+ }
if (provider === null) {
return { ...report, ping: { ok: false, reason: `not sent: status ${cfg.status}` } };
}
diff --git a/src/core/decision-model/llm-emulation.ts b/src/core/decision-model/llm-emulation.ts
index 54eed48a..dbd83d58 100644
--- a/src/core/decision-model/llm-emulation.ts
+++ b/src/core/decision-model/llm-emulation.ts
@@ -275,10 +275,20 @@ export class LlmEmulationDecisionProvider implements DecisionProvider {
);
if (limit !== null) throw new DecisionProviderError("budget", limit);
- const verdict = redactForEgress(LLM_EMULATION_EGRESS_SITE, {
- state: req.state,
- questions: req.questions,
- });
+ // This adapter holds the resolved key it is about to send as a Bearer
+ // credential, so it is a wired boundary: the body scan also carries
+ // the key VALUE as a literal, scrubbing an occurrence that leaked
+ // into the vault text the state is built from - a quiet string the
+ // shape passes cannot see. The key is required here (no keyless
+ // route), so the literal pass always has its value.
+ const verdict = redactForEgress(
+ LLM_EMULATION_EGRESS_SITE,
+ {
+ state: req.state,
+ questions: req.questions,
+ },
+ { resolvedLiterals: [this.endpoint.apiKey] },
+ );
if (verdict.outcome !== "released") {
throw new DecisionProviderError(
"egress_refused",
diff --git a/src/core/decision-model/provider.ts b/src/core/decision-model/provider.ts
index 39505a42..e07b98ca 100644
--- a/src/core/decision-model/provider.ts
+++ b/src/core/decision-model/provider.ts
@@ -11,20 +11,37 @@
* another one, and `llm-emulation` in particular is never a fallback.
*
* The key is read here, from the environment, at call time. It is handed
- * to the adapter instance and never stored in any config object.
+ * to the adapter instance and never stored in any config object. When the
+ * caller passes `secretsVault`, a key value written as a `$secret:NAME`
+ * reference resolves through that vault's custody store at this use site
+ * (store first, env fallback) - the config resolver only probes the
+ * reference for presence, so the factory must resolve the value it
+ * actually sends. Without a vault, or with a plain value, the raw value
+ * is taken exactly as before. An unresolvable reference or a store-held
+ * name under a locked envelope raises the named resolver error rather
+ * than silently reading as no key (the same refusal `research.ts` makes).
*/
+import { resolveNamedSecret } from "../secret-resolver.ts";
import type { DecisionProvider } from "./contract.ts";
import type { ResolvedDecisionModelConfig } from "./config.ts";
export function makeDecisionProvider(
cfg: ResolvedDecisionModelConfig | null | undefined,
env: Readonly<Record<string, string | undefined>> = process.env,
+ secretsVault?: string | null,
): DecisionProvider | null {
if (cfg === null || cfg === undefined || cfg.status !== "active") return null;
if (cfg.baseUrl === null || cfg.model === null) return null;
const raw = cfg.envKey !== null ? env[cfg.envKey] : undefined;
- const apiKey = typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
+ // Reference-shaped values resolve through the custody store; `null`
+ // (no vault) and plain values pass through untouched, byte-identical
+ // to the pre-routing factory.
+ const keyValue =
+ secretsVault !== undefined && secretsVault !== null && typeof raw === "string"
+ ? resolveNamedSecret(secretsVault, raw.trim())
+ : raw;
+ const apiKey = typeof keyValue === "string" && keyValue.trim() !== "" ? keyValue.trim() : null;
// Only a loopback server whose preset allows it runs without a key.
if (apiKey === null && cfg.keyRequired !== false) return null;
const common = {
diff --git a/src/core/decision-model/run.ts b/src/core/decision-model/run.ts
index 3fbdacaf..ea2605e4 100644
--- a/src/core/decision-model/run.ts
+++ b/src/core/decision-model/run.ts
@@ -87,6 +87,12 @@ export interface RunDecisionOptions<C> {
/** Injected provider (tests). Defaults to the configured adapter. */
readonly provider?: DecisionProvider;
readonly env?: Readonly<Record<string, string | undefined>>;
+ /**
+ * Vault whose custody store backs a `$secret:NAME` key value at the use
+ * site. Absent, the key value is read from `env` exactly as before the
+ * resolver routing existed.
+ */
+ readonly secretsVault?: string | null;
/** Overrides `decision_model_timeout_ms` (e.g. a hook sub-budget). */
readonly timeoutMs?: number;
/**
@@ -120,7 +126,8 @@ export async function runDecision<C>(
const configured = decisionModelModeFor(cfg, use);
if (configured === "off" || cfg === null || cfg === undefined) return { status: "off" };
const mode = opts.modeOverride ?? configured;
- const provider = opts.provider ?? makeDecisionProvider(cfg, opts.env ?? process.env);
+ const provider =
+ opts.provider ?? makeDecisionProvider(cfg, opts.env ?? process.env, opts.secretsVault);
if (provider === null) return { status: "off" };
const now = opts.now ?? (() => new Date());
diff --git a/src/core/decision-model/systemone.ts b/src/core/decision-model/systemone.ts
index ee13d388..240ab48b 100644
--- a/src/core/decision-model/systemone.ts
+++ b/src/core/decision-model/systemone.ts
@@ -138,10 +138,20 @@ export class SystemOneDecisionProvider implements DecisionProvider {
);
if (limit !== null) throw new DecisionProviderError("budget", limit);
- const verdict = redactForEgress(SYSTEMONE_EGRESS_SITE, {
- state: req.state,
- questions: req.questions,
- });
+ // This adapter holds the resolved key it is about to send as a Bearer
+ // credential, so it is a wired boundary: the body scan also carries
+ // the key VALUE as a literal, scrubbing an occurrence that leaked
+ // into the vault text the state and questions are built from - a
+ // quiet string the shape passes cannot see. No key, no literal pass
+ // (byte-identical to the bare guard).
+ const verdict = redactForEgress(
+ SYSTEMONE_EGRESS_SITE,
+ {
+ state: req.state,
+ questions: req.questions,
+ },
+ this.endpoint.apiKey ? { resolvedLiterals: [this.endpoint.apiKey] } : {},
+ );
if (verdict.outcome !== "released") {
throw new DecisionProviderError(
"egress_refused",
diff --git a/src/core/egress/guard.ts b/src/core/egress/guard.ts
index 424e4d1b..37deb6ba 100644
--- a/src/core/egress/guard.ts
+++ b/src/core/egress/guard.ts
@@ -66,6 +66,7 @@
*/
import { MAX_REDACTOR_INPUT, redactStructured, type RedactRawOutputOptions } from "../redactor.ts";
+import { sortedDistinctLiterals } from "../secret-ref.ts";
import { EGRESS_SITES, type EgressSiteId } from "./registry.ts";
/** How a payload offered to the boundary came back. */
@@ -171,6 +172,41 @@ export interface EgressPolicy {
* is right for every vault-authored export.
*/
readonly foreignIdentifiers?: boolean;
+ /**
+ * Values already resolved from `$secret:` references at a use site
+ * (the named-secret resolver). The structural passes judge SHAPES - a
+ * key name, a vendor prefix - and a resolved credential under a quiet
+ * key name carries neither, so the boundary needs the values themselves.
+ * Each occurrence is replaced with the standard marker, longest value
+ * first so a value containing another cannot have its match destroyed
+ * and leak its head as a fragment, and before the truncation guard so
+ * no cut leaves a partial credential in the kept prefix. Absent (the
+ * default) the composition is byte-identical to the pre-literal guard.
+ *
+ * The wired boundaries are the ones that KNOW the values: the MCP
+ * error redaction and the config-mapping status surfaces feed
+ * `resolvedSecretLiterals(vault)` for the vault they serve, and the
+ * decision-model adapters pass the key they hold. A boundary that
+ * cannot know the vault must not pretend to redact: for those the
+ * option stays absent, which is the named decision, not an omission.
+ */
+ readonly resolvedLiterals?: ReadonlyArray<string>;
+}
+
+/**
+ * The one policy plus what the call site may vary. The literals pass
+ * through the shared substitution-safety ordering
+ * ({@link sortedDistinctLiterals}); the redactor applies them verbatim
+ * ahead of every pattern pass.
+ */
+function composeRedactionOptions(policy: EgressPolicy): RedactRawOutputOptions {
+ return {
+ ...EGRESS_REDACTION_OPTIONS,
+ ...(policy.foreignIdentifiers === true ? { foreignIdentifiers: true } : {}),
+ ...(policy.resolvedLiterals === undefined
+ ? {}
+ : { literals: sortedDistinctLiterals(policy.resolvedLiterals) }),
+ };
}
/**
@@ -183,10 +219,7 @@ export function redactForEgress<T>(
payload: T,
policy: EgressPolicy = {},
): EgressVerdict<T> {
- const scanned = redactStructured(payload, {
- ...EGRESS_REDACTION_OPTIONS,
- ...(policy.foreignIdentifiers === true ? { foreignIdentifiers: true } : {}),
- });
+ const scanned = redactStructured(payload, composeRedactionOptions(policy));
if (scanned.truncated) {
return {
outcome: EGRESS_OUTCOME.refusedScanTruncated,
@@ -240,6 +273,7 @@ export function redactForEgress<T>(
*/
export function redactConfigMapping(
data: Readonly<Record<string, unknown>>,
+ policy: EgressPolicy = {},
): Record<string, unknown> {
- return redactStructured(data, EGRESS_REDACTION_OPTIONS).value as Record<string, unknown>;
+ return redactStructured(data, composeRedactionOptions(policy)).value as Record<string, unknown>;
}
diff --git a/src/core/egress/registry.ts b/src/core/egress/registry.ts
index 19a9be2e..b9e2e7b9 100644
--- a/src/core/egress/registry.ts
+++ b/src/core/egress/registry.ts
@@ -225,6 +225,25 @@ export const EGRESS_SITES = Object.freeze({
"recipient's integrity check verifies the redacted copy, not the vault. Preference " +
"rows leave without their evidence links and rendered body.",
},
+ "brain-secret-bundle-export": {
+ id: "brain-secret-bundle-export",
+ verb: "o2b brain secret export",
+ module: "src/cli/brain/verbs/secret.ts",
+ redaction: R.sharedRedactor,
+ reason:
+ "the operator-named file carries every stored credential value RE-ENCRYPTED " +
+ "under a passphrase-derived key, so the shared guard runs over the bundle's " +
+ "METADATA INVENTORY and never over the wrapped values, whose base64 bodies a " +
+ "structural scan could only mangle. The inventory is scanned as an ARRAY of " +
+ "entries - a name like `api-key` as a mapping KEY is the redactor's credential-" +
+ "assignment shape and would replace the whole entry - and the KDF block is " +
+ "excluded, because its random salt is exactly the high-entropy shape the token " +
+ "pass exists to catch. Allow patterns are free text and scan in full; a " +
+ "REWRITTEN entry name or env-var mapping refuses the export, since an " +
+ "identifier is never rewritten into the file that has to carry it. What the " +
+ "status does NOT claim: the file's secrecy is exactly the passphrase's " +
+ "strength against offline guessing wherever the file travels.",
+ },
"search-embedding-openai-compat": {
id: "search-embedding-openai-compat",
verb: "o2b search index (embedding provider)",
diff --git a/src/core/integrity/digest.ts b/src/core/integrity/digest.ts
index e5058686..1782a004 100644
--- a/src/core/integrity/digest.ts
+++ b/src/core/integrity/digest.ts
@@ -21,6 +21,27 @@
* a short form slices its own result and owns that decision - and it
* never inspects natural language: text is opaque bytes on the way in and
* hex on the way out.
+ *
+ * ## The persisted-digest doctrine, and the seal built on it
+ *
+ * {@link sealWithDigest} and {@link digestVerifies} are the one way a
+ * structured record is bound to a digest over itself: the seal is
+ * `sha256Hex(canonicalJson(body))` of exactly the body given, appended to
+ * the copy that carries the `digest` field, and verification recomputes
+ * the same value over the body WITHOUT the field. The state-migration
+ * manifest sealed this way first; content adoption plans - a dry run the
+ * operator approves in one process and a later apply re-checks in
+ * another - follow, and every future sealed record joins them rather
+ * than growing a private spelling.
+ *
+ * What belongs in a sealed body follows from who re-checks it. A record
+ * whose seal must be reproducible across time - an approval compared
+ * against a re-computation - keeps wall-clock fields out of the body and
+ * injects its clock at the write instead, so the same content seals to
+ * the same digest whenever it is planned. A point-in-time record such as
+ * the migration manifest MAY bind its timestamp, because the seal there
+ * answers "are these still the bytes that were measured", and when they
+ * were measured is part of that answer.
*/
import { createHash } from "node:crypto";
@@ -71,3 +92,29 @@ export function canonicalJson(value: unknown): string {
}
return JSON.stringify(value) ?? "null";
}
+
+/**
+ * Bind a JSON body to its digest: the body with a `digest` field
+ * appended, whose value is the hash of the body WITHOUT that field.
+ *
+ * This is the persisted-digest doctrine made callable - the same shape
+ * the state-migration manifest has always written. The field is named
+ * `digest` on every sealed record, so a reader can strip it by name and
+ * re-verify with {@link digestVerifies} without knowing the record
+ * otherwise.
+ */
+export function sealWithDigest<B extends object>(body: B): B & { readonly digest: string } {
+ return { ...body, digest: sha256Hex(canonicalJson(body)) };
+}
+
+/**
+ * Whether `digest` is still the seal of `body`.
+ *
+ * `body` is the record WITHOUT its `digest` field - the same body
+ * {@link sealWithDigest} hashed. A `false` here is never repaired or
+ * resynced by a caller: a body that does not verify is a body nobody
+ * measured, and the refusal is the feature.
+ */
+export function digestVerifies(body: unknown, digest: string): boolean {
+ return sha256Hex(canonicalJson(body)) === digest;
+}
diff --git a/src/core/reliability/audit.ts b/src/core/reliability/audit.ts
index 0be1edbd..20b14e6c 100644
--- a/src/core/reliability/audit.ts
+++ b/src/core/reliability/audit.ts
@@ -8,6 +8,12 @@ import {
shardedFileName,
type LedgerShardGrammar,
} from "../brain/ledger-shards.ts";
+// The one value this module reads at module-evaluation time is declared in
+// the leaf `path-constants.ts` and re-exported by `ledger-shards.ts` (see
+// that constant's docblock for the import cycle that motivated the move).
+// Reading it through the re-export is what keeps this module safe: a
+// re-exported binding resolves to the declaring leaf module, so it is
+// initialized even when `ledger-shards.ts` itself is still mid-cycle.
/**
* The file-name layout of every per-device ISO-week audit directory:
diff --git a/src/core/search/embeddings/registry.ts b/src/core/search/embeddings/registry.ts
index 81d63aff..0e361cab 100644
--- a/src/core/search/embeddings/registry.ts
+++ b/src/core/search/embeddings/registry.ts
@@ -17,6 +17,7 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
+import { resolveMergedValue } from "../../secret-resolver.ts";
import { SearchError } from "../types.ts";
/** A registered OpenAI-compatible provider profile. */
@@ -171,6 +172,17 @@ export interface ExpandedProvider {
readonly apiKeys: ReadonlyArray<string>;
}
+/** Options for expanding a registered name against merged key sources. */
+export interface ExpandRegisteredProviderOptions {
+ /**
+ * Vault whose custody store joins the probe ahead of `env`: a probe
+ * name the store holds answers first, and a probe entry written as a
+ * `$secret:NAME` reference resolves through the same store (read-only,
+ * no usage stamp). Absent, the probe reads `env` exactly as before.
+ */
+ readonly secretsVault?: string;
+}
+
/**
* Expand a registered provider name into `openai-compat` config, resolving
* the API key(s) from the profile's `envKey` probe list (first-present
@@ -182,11 +194,16 @@ export function expandRegisteredProvider(
name: string,
registry: ReadonlyArray<ProviderProfile>,
env: Readonly<Record<string, string | undefined>>,
+ opts: ExpandRegisteredProviderOptions = {},
): ExpandedProvider | null {
const profile = registry.find((p) => p.name === name);
if (!profile) return null;
const present = envKeyList(profile.envKey)
- .map((varName) => env[varName])
+ .map((varName) =>
+ opts.secretsVault === undefined
+ ? env[varName]
+ : resolveMergedValue(opts.secretsVault, env, varName),
+ )
.filter((v): v is string => v !== undefined && v !== "");
return Object.freeze({
provider: "openai-compat" as const,
diff --git a/src/core/search/index.ts b/src/core/search/index.ts
index 297c2a29..1eb3fa26 100644
--- a/src/core/search/index.ts
+++ b/src/core/search/index.ts
@@ -39,6 +39,12 @@ import {
type EmbeddingPriceOverride,
} from "./embeddings/pricing.ts";
import { SearchError } from "./types.ts";
+import { isSecretReferenceValue, resolveNamedSecret } from "../secret-resolver.ts";
+import { SecretReferenceError } from "../secret-ref.ts";
+import {
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+} from "../brain/secrets/envelope.ts";
import type {
ResolvedEmbeddingConfig,
ResolvedFreshenConfig,
@@ -729,12 +735,45 @@ function resolveRegistryProvider(
): ExpandedProvider | null {
if (rawProvider === null || BUILTIN_PROVIDERS.has(rawProvider)) return null;
try {
- return expandRegisteredProvider(rawProvider, loadProviderRegistry(vault), env);
- } catch {
+ // The vault's custody store joins the probe (store first, reference-
+ // shaped probe entries resolved) so a registered provider's key can
+ // live in the store; without it the probe reads env exactly as before.
+ return expandRegisteredProvider(rawProvider, loadProviderRegistry(vault), env, {
+ secretsVault: vault,
+ });
+ } catch (err) {
+ // The resolver's named refusals are ANSWERS, not expansion misses: a
+ // locked store, a missing keyfile, or a malformed reference in a probe
+ // entry surfaces by name, because swallowing it here returned null and
+ // made `parseProvider` claim "not a registered provider" for a name that
+ // IS registered - with the implied remedy (fix the name) wrong. Only
+ // a genuinely broken registry file stays fail-soft.
+ if (
+ err instanceof SecretStoreLockedError ||
+ err instanceof SecretStoreKeyfileMissingError ||
+ err instanceof SecretReferenceError
+ ) {
+ throw err;
+ }
return null;
}
}
+/**
+ * Resolve one credential VALUE read from env or config for `vault`: a
+ * `$secret:NAME` reference resolves through the custody store (store
+ * first, env fallback), surfacing the same named locked/reference
+ * refusals the registry probe beside it raises; any other value passes
+ * through untouched, byte-identical to the pre-routing read. This is the
+ * routing the explicit `embedding_api_key` read and the cross-encoder
+ * rerank env-key read go through, so every key inside one resolved
+ * config resolves by one rule.
+ */
+function resolveCredentialValue(vault: string, value: string | null): string | null {
+ if (value === null || !isSecretReferenceValue(value)) return value;
+ return resolveNamedSecret(vault, value.trim());
+}
+
/**
* The names `search check` hands the credential-source report: the
* registered profile `embedding_provider` selects (by the same env-over-
@@ -857,7 +896,10 @@ export function resolveSearchConfig(opts: {
"OPEN_SECOND_BRAIN_EMBEDDING_MODEL",
"embedding_model",
);
- const explicitApiKey = envOrConfig(env, config, EMBEDDING_KEY_ENV, EMBEDDING_KEY_CONFIG);
+ const explicitApiKey = resolveCredentialValue(
+ opts.vault,
+ envOrConfig(env, config, EMBEDDING_KEY_ENV, EMBEDDING_KEY_CONFIG),
+ );
// Explicit config/env always wins over the registry profile's fields.
const baseUrl = explicitBaseUrl ?? registryExpansion?.baseUrl ?? null;
// The plain-http opt-out binds to the URL the operator wrote down: the
@@ -1048,7 +1090,13 @@ export function resolveSearchConfig(opts: {
envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_RERANK_ENV_KEY", "search_rerank_env_key") ??
rerankProfile?.envKey ??
null;
- const rerankApiKey = rerankEnvKey !== null ? (env[rerankEnvKey] ?? null) : null;
+ // Routed through the same value resolver as the explicit embedding key:
+ // a reference-shaped env value resolves through the custody store, a
+ // plain value passes byte-identically.
+ const rerankApiKey = resolveCredentialValue(
+ opts.vault,
+ rerankEnvKey !== null ? (env[rerankEnvKey] ?? null) : null,
+ );
const rerankTopK = parseInteger(
envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_RERANK_TOP_K", "search_rerank_top_k"),
DEFAULTS.rerankTopK,
diff --git a/src/core/search/rerank/decision-model.ts b/src/core/search/rerank/decision-model.ts
index 983afeb3..d9097fe4 100644
--- a/src/core/search/rerank/decision-model.ts
+++ b/src/core/search/rerank/decision-model.ts
@@ -234,6 +234,7 @@ export class DecisionModelRerankProvider implements RerankProvider {
},
{
config: this.cfg,
+ ...(this.cfg.vault !== null ? { secretsVault: this.cfg.vault } : {}),
...(this.opts.provider !== undefined ? { provider: this.opts.provider } : {}),
...(this.opts.env !== undefined ? { env: this.opts.env } : {}),
...(this.opts.modeOverride !== undefined ? { modeOverride: this.opts.modeOverride } : {}),
diff --git a/src/core/secret-ref.ts b/src/core/secret-ref.ts
index 0eb3cc98..1dcfc38d 100644
--- a/src/core/secret-ref.ts
+++ b/src/core/secret-ref.ts
@@ -7,6 +7,15 @@ export interface SecretReferenceStatus {
readonly configKey: string;
readonly name: string;
readonly available: boolean;
+ /**
+ * Present (true) only on a value that is reference-SHAPED but fails the
+ * reference grammar - `$secret:tg-token` with a dashed name the grammar
+ * cannot spell. Such a value resolves to a `SecretReferenceError` at
+ * use time no matter what the store or the environment holds, so the
+ * inspection surfaces must show it rather than silently drop it.
+ * Optional so well-formed rows keep their exact shape.
+ */
+ readonly invalid?: boolean;
}
export type SecretProvider = Readonly<Record<string, string | undefined>>;
@@ -22,6 +31,8 @@ export class SecretReferenceError extends Error {
}
const SECRET_REFERENCE_RE = /^\$secret:([A-Za-z_][A-Za-z0-9_]*)$/;
+/** The syntax prefix every named-secret reference starts with. */
+const REFERENCE_PREFIX = "$secret:";
const REDACTED = "***REDACTED***";
export function parseSecretReference(value: unknown): SecretReference | null {
@@ -31,6 +42,29 @@ export function parseSecretReference(value: unknown): SecretReference | null {
return Object.freeze({ raw: value.trim(), name: match[1]! });
}
+/**
+ * Whether a config value claims to be a reference. `$secret:` with a
+ * malformed body is still reference-shaped - it resolves to a
+ * `SecretReferenceError`, never to the literal text.
+ */
+export function isSecretReferenceValue(value: unknown): boolean {
+ return typeof value === "string" && value.trimStart().startsWith(REFERENCE_PREFIX);
+}
+
+/**
+ * The reference body of a reference-SHAPED value the grammar cannot spell
+ * (e.g. the dashed `tg-token` in `$secret:tg-token`), or null when the
+ * value is not reference-shaped at all. This is the name the runtime
+ * refusal names, so the inspection surfaces can show the same identifier
+ * the operator must fix (rename the store entry, or change the config
+ * value to a spellable reference).
+ */
+export function invalidSecretReferenceBody(value: unknown): string | null {
+ if (!isSecretReferenceValue(value)) return null;
+ const body = (value as string).trim().slice(REFERENCE_PREFIX.length);
+ return body.length > 0 ? body : null;
+}
+
export function resolveSecretReference(
value: string,
provider: SecretProvider = process.env,
@@ -53,7 +87,13 @@ export function listSecretReferences(
const out: SecretReferenceStatus[] = [];
for (const [configKey, value] of Object.entries(data)) {
const ref = parseSecretReference(value);
- if (!ref) continue;
+ if (!ref) {
+ const body = invalidSecretReferenceBody(value);
+ if (body !== null) {
+ out.push({ configKey, name: body, available: false, invalid: true });
+ }
+ continue;
+ }
out.push({
configKey,
name: ref.name,
@@ -64,21 +104,32 @@ export function listSecretReferences(
return Object.freeze(out);
}
+/**
+ * Dedupe, drop empties, and order longest-first. The order is the
+ * substitution-safety rule, not cosmetics: when one resolved value
+ * contains another, a shorter-first replacement would destroy the longer
+ * value's match and leak its head as a fragment, so every caller that
+ * substitutes literal values into text goes through this.
+ */
+export function sortedDistinctLiterals(values: Iterable<string>): string[] {
+ return [...new Set(values)]
+ .filter((value) => value.length > 0)
+ .sort((a, b) => b.length - a.length);
+}
+
export function redactKnownSecretValues(
text: string,
references: ReadonlyArray<string>,
provider: SecretProvider = process.env,
): string {
let out = text;
- const values = Array.from(
- new Set(
- references
- .map((raw) => parseSecretReference(raw))
- .filter((ref): ref is SecretReference => ref !== null)
- .map((ref) => provider[ref.name])
- .filter((value): value is string => Boolean(value)),
- ),
- ).sort((a, b) => b.length - a.length);
+ const values = sortedDistinctLiterals(
+ references
+ .map((raw) => parseSecretReference(raw))
+ .filter((ref): ref is SecretReference => ref !== null)
+ .map((ref) => provider[ref.name])
+ .filter((value): value is string => Boolean(value)),
+ );
for (const value of values) {
out = out.replaceAll(value, REDACTED);
}
diff --git a/src/core/secret-resolver.ts b/src/core/secret-resolver.ts
new file mode 100644
index 00000000..d04f9bd4
--- /dev/null
+++ b/src/core/secret-resolver.ts
@@ -0,0 +1,243 @@
+/**
+ * The named-secret resolver (trust-surface-hardening, t_e5807974).
+ *
+ * A `$secret:NAME` reference in a consumer's config resolves through the
+ * vault's custody store ahead of the process environment. Resolution is
+ * READ-ONLY: it composes `parseSecretReference` with the custody store's
+ * read-only resolve export, so a config read never stamps
+ * `last_used_at` and never appends an exec audit record - resolution
+ * must not take the write path.
+ *
+ * Precedence is store first, env fallback - EXCEPT a name the store
+ * holds under a locked envelope, which surfaces the named locked-store
+ * error rather than silently answering from the environment (a silent
+ * fallback would hide the locked state). A vault with no custody store
+ * gains no state from resolution: the metadata read creates nothing.
+ *
+ * Resolution happens at use sites, not at config load, keeping
+ * plaintext spread no wider than the exec path's one-variable
+ * discipline. The probe re-reads store metadata per lookup
+ * (correctness first); caching stays deferred until measured.
+ */
+
+import { existsSync } from "node:fs";
+
+import { installNamedSecretResolver } from "./config.ts";
+import {
+ isSecretReferenceValue,
+ parseSecretReference,
+ resolveSecretReference,
+ type SecretProvider,
+ type SecretReferenceStatus,
+ invalidSecretReferenceBody,
+} from "./secret-ref.ts";
+
+/**
+ * The `$secret:` syntax check lives in the leaf `secret-ref.ts` beside the
+ * rest of the reference grammar; re-exported here so this module's
+ * consumers keep one import path.
+ */
+export { isSecretReferenceValue } from "./secret-ref.ts";
+
+/**
+ * The custody store, joined at CALL time rather than at module load.
+ *
+ * The store's own import neighbourhood reaches back into `config.ts`
+ * (store → audit → ledger-shards → config), and `config.ts` resolves
+ * credentials through THIS module, so a static import here closed the
+ * six-module cycle whose initialisation order is undefined - it aborted
+ * `audit.ts` at module scope with a TDZ error whenever the shard-grammar
+ * module was entered first. The lazy require is the sanctioned cure (see
+ * `tests/core/architecture/import-cycles.test.ts`); the store is needed
+ * only when a reference or a probe actually resolves, and `require`
+ * caches the module after the first call.
+ */
+type CustodyStore = typeof import("./brain/secrets/store.ts");
+
+let custodyStoreModule: CustodyStore | undefined;
+
+function custodyStore(): CustodyStore {
+ if (custodyStoreModule === undefined) {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ custodyStoreModule = require("./brain/secrets/store.ts") as CustodyStore;
+ }
+ return custodyStoreModule;
+}
+
+/**
+ * The store leg of the merged provider: one name's custody answer, or
+ * undefined when the store does not hold it (the caller falls back to the
+ * environment). Probing is on demand - a name the store does not hold costs
+ * one metadata read and never decrypts; the store's plaintext is handed to
+ * the caller exactly where the value is used. A name the store holds under
+ * a locked envelope raises the named locked-store refusal, never a silent
+ * env fallback.
+ */
+function storeValue(vault: string, name: string): string | undefined {
+ const held = custodyStore()
+ .listSecrets(vault)
+ .some((meta) => meta.name === name);
+ if (!held) return undefined;
+ return custodyStore().resolveSecretReadOnly(vault, name).value;
+}
+
+/**
+ * The merged provider: custody store ahead of the process environment.
+ * Probing is on demand - a name the store does not hold costs one
+ * metadata read and never decrypts; the store's plaintext is handed to
+ * the caller exactly where the value is used.
+ */
+export function secretProvider(vault: string): SecretProvider {
+ const env = process.env;
+ return new Proxy(env as SecretProvider, {
+ get(_target, prop) {
+ if (typeof prop !== "string") return undefined;
+ return storeValue(vault, prop) ?? env[prop];
+ },
+ has(_target, prop) {
+ if (typeof prop !== "string") return Reflect.has(env, prop);
+ return storeValue(vault, prop) !== undefined || Reflect.has(env, prop);
+ },
+ });
+}
+
+/**
+ * Resolve one config value for the vault. A plain value passes through
+ * untouched; a reference resolves store-first with env fallback, and a
+ * reference that resolves nowhere keeps the existing
+ * `SecretReferenceError` behavior.
+ */
+export function resolveNamedSecret(vault: string, value: string): string {
+ if (!isSecretReferenceValue(value)) return value;
+ return resolveSecretReference(value.trim(), secretProvider(vault));
+}
+
+/**
+ * Probe one config key through the merged provider. A reference-shaped
+ * key resolves as a reference; any other key is a store-held name ahead
+ * of `env`. This is the seam the registry's env probing expands through.
+ */
+export function resolveMergedValue(
+ vault: string,
+ env: Readonly<Record<string, string | undefined>>,
+ key: string,
+): string | undefined {
+ if (isSecretReferenceValue(key)) return resolveNamedSecret(vault, key.trim());
+ return storeValue(vault, key) ?? env[key];
+}
+
+/**
+ * Whether one named secret is usable by this process: the store holds
+ * the name (metadata only - a locked envelope still counts, no
+ * decrypt), or the environment carries it. Backs `o2b secrets status`.
+ */
+export function namedSecretAvailable(vault: string, name: string): boolean {
+ return (
+ custodyStore()
+ .listSecrets(vault)
+ .some((meta) => meta.name === name) || Boolean(process.env[name])
+ );
+}
+
+/**
+ * Metadata-only availability for a config object's references: the
+ * store's name set joined with the environment, never a decrypt. The
+ * same `SecretReferenceStatus` rows `listSecretReferences` reports, so
+ * `o2b secrets list` keeps its output shape with the store joined in.
+ */
+export function listNamedSecretAvailability(
+ vault: string,
+ data: Readonly<Record<string, unknown>>,
+): ReadonlyArray<SecretReferenceStatus> {
+ const held = new Set(
+ custodyStore()
+ .listSecrets(vault)
+ .map((meta) => meta.name),
+ );
+ const out: SecretReferenceStatus[] = [];
+ for (const [configKey, value] of Object.entries(data)) {
+ const ref = parseSecretReference(value);
+ if (!ref) {
+ // A reference-SHAPED value the grammar cannot spell (a dashed store
+ // name, say) resolves to a `SecretReferenceError` at use time and
+ // can never be answered by the store or the env - report it instead
+ // of silently dropping it while `secrets status` answers the same
+ // name from metadata alone.
+ const body = invalidSecretReferenceBody(value);
+ if (body !== null) {
+ out.push({ configKey, name: body, available: false, invalid: true });
+ }
+ continue;
+ }
+ out.push({
+ configKey,
+ name: ref.name,
+ available: held.has(ref.name) || Boolean(process.env[ref.name]),
+ });
+ }
+ out.sort((a, b) => a.configKey.localeCompare(b.configKey));
+ return Object.freeze(out);
+}
+
+/**
+ * The VALUES the vault's custody store can currently answer with - the
+ * input the egress boundaries need to scrub resolved credentials (the
+ * `resolvedLiterals` option on `EgressPolicy` and the MCP error
+ * redactor's fourth parameter). This is the one production join between
+ * the store and the redactor plane; without it the literal passes were
+ * plumbed but never fed, and a resolved credential under a quiet key
+ * name stayed as invisible to the boundary as before the wave.
+ *
+ * Wired boundaries, and only these: the MCP error redaction (both the
+ * tools/call catch and the one builder every JSON-RPC error answer
+ * passes through), the config-mapping status surfaces, and the
+ * decision-model adapters that hold the key they are about to send. A
+ * boundary that cannot know the vault (the CLI export verbs run
+ * vault-scoped already but scan vault-authored content the structural
+ * passes cover) must not pretend - the absent option stays byte-
+ * identical there, and this docblock is where the next wiring decision
+ * starts.
+ *
+ * Degradation is the point: a store that is absent, empty, unreadable,
+ * LOCKED (the named locked refusal), or missing its keyfile contributes
+ * NOTHING - the boundary then answers exactly as the pre-literal
+ * redactor did. Redaction never blocks, never surfaces a refusal, and
+ * never mints: a lost keyfile is skipped rather than regenerated, so a
+ * scan leaves no custody state behind.
+ */
+export function resolvedSecretLiterals(vault: string): string[] {
+ const store = custodyStore();
+ let held: ReadonlyArray<{ readonly name: string }>;
+ try {
+ held = store.listSecrets(vault);
+ } catch {
+ // An unreadable store is not a redactable store: contribute nothing.
+ return [];
+ }
+ if (held.length === 0) return [];
+ if (!existsSync(store.keyPath(vault))) return [];
+ const out: string[] = [];
+ for (const meta of held) {
+ try {
+ out.push(store.resolveSecretReadOnly(vault, meta.name).value);
+ } catch {
+ // The locked envelope lands here (the named refusal), as does an
+ // entry that cannot be decrypted; each contributes nothing.
+ }
+ }
+ return out;
+}
+
+/**
+ * Install THIS module as the adapter behind config's resolver port (see
+ * {@link installNamedSecretResolver}). Config values carrying a
+ * `$secret:` reference resolve through the custody store from here, and
+ * the dependency points resolver -> config - the direction that keeps
+ * the six-module cycle (config -> resolver -> custody store -> audit ->
+ * ledger-shards -> config) cut. Every production entry (the CLI's
+ * `main.ts`, the MCP server, the OpenClaw bridge) imports this module
+ * statically at startup, which is what wires the port before any command
+ * dispatch; a test exercising the reference branch of a config resolver
+ * imports this module for the same side effect.
+ */
+installNamedSecretResolver({ resolveNamedSecret });
diff --git a/src/core/state/migrate.ts b/src/core/state/migrate.ts
index b2c06ac6..a8d15995 100644
--- a/src/core/state/migrate.ts
+++ b/src/core/state/migrate.ts
@@ -48,12 +48,12 @@
*
* ## What the manifest binds
*
- * Through {@link sha256Hex} and {@link canonicalJson}, the one digest
- * encoding in this project: the source type, the canonical roots, the
- * full path inventory, a byte count per file and a SHA-256 per file, and
- * a digest over all of it. A manifest that does not verify is refused
- * rather than repaired - a rollback driven by a manifest somebody edited
- * is a restore of something nobody measured.
+ * Through {@link sha256Hex} and the digest module's `canonicalJson` -
+ * the one digest encoding in this project: the source type, the
+ * canonical roots, the full path inventory, a byte count per file and a
+ * SHA-256 per file, and a digest over all of it. A manifest that does
+ * not verify is refused rather than repaired - a rollback driven by a
+ * manifest somebody edited is a restore of something nobody measured.
*
* ## What this module does NOT enumerate
*
@@ -82,7 +82,12 @@ import { homedir } from "node:os";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
-import { canonicalJson, DIGEST_ALGORITHM, sha256Hex } from "../integrity/digest.ts";
+import {
+ DIGEST_ALGORITHM,
+ digestVerifies,
+ sealWithDigest,
+ sha256Hex,
+} from "../integrity/digest.ts";
import { isWriterLockHeld } from "../search/store/writer-lock.ts";
import {
inventoryStateSurfaces,
@@ -182,15 +187,20 @@ export interface MigrationManifest {
readonly digest: string;
}
-/** Bind a manifest body to its digest. The one place either is computed. */
+/**
+ * Bind a manifest body to its digest. The one place either is computed:
+ * a thin alias over the integrity module's {@link sealWithDigest}, which
+ * is the same `sha256Hex(canonicalJson(body))` this module has always
+ * written - lifted, not changed.
+ */
function sealManifest(body: Omit<MigrationManifest, "digest">): MigrationManifest {
- return { ...body, digest: sha256Hex(canonicalJson(body)) };
+ return sealWithDigest(body);
}
/** Whether a manifest's digest still describes its body. */
function manifestVerifies(manifest: MigrationManifest): boolean {
const { digest, ...body } = manifest;
- return sha256Hex(canonicalJson(body)) === digest;
+ return digestVerifies(body, digest);
}
// ----- Planning a migration -------------------------------------------------
diff --git a/src/core/surface/skill-attach-decision.ts b/src/core/surface/skill-attach-decision.ts
index 2fc61066..7605fd7e 100644
--- a/src/core/surface/skill-attach-decision.ts
+++ b/src/core/surface/skill-attach-decision.ts
@@ -361,6 +361,7 @@ export async function buildSkillAttachmentWithDecision(
{
config: cfg,
timeoutMs: cfg.timeoutMs,
+ ...(cfg.vault !== null ? { secretsVault: cfg.vault } : {}),
...(opts.provider !== undefined ? { provider: opts.provider } : {}),
...(opts.env !== undefined ? { env: opts.env } : {}),
recordDetails: (response, context) => {
@@ -469,6 +470,7 @@ export async function buildSkillAttachmentWithDecision(
{
config: cfg,
timeoutMs: Math.max(1, deadline - clock()),
+ ...(cfg.vault !== null ? { secretsVault: cfg.vault } : {}),
...(opts.provider !== undefined ? { provider: opts.provider } : {}),
...(opts.env !== undefined ? { env: opts.env } : {}),
recordDetails: (response, context) => {
diff --git a/src/core/tags.ts b/src/core/tags.ts
index 0f19ef58..91f9e9f3 100644
--- a/src/core/tags.ts
+++ b/src/core/tags.ts
@@ -6,9 +6,10 @@
* `src/core/search/links.ts` so that both consumers - the search index
* (link-table rows) and the vault-hygiene `tags` detector - read ONE
* definition, not two spellings. This is also the seam board sibling
- * t_11ee559f (write-time tag syntax validation, not in this wave; the
- * overlap is recorded as a coordination note) must consume: it should
- * validate against the rule defined HERE, never against a copy.
+ * t_11ee559f (write-time tag syntax validation, trust-surface-hardening
+ * wave) consumes: the composers validate against the rule defined HERE
+ * ({@link isObsidianTagValue}, via `src/core/brain/tag-syntax.ts`),
+ * never against a copy.
*
* The index-side rule: `#word` where word starts with a letter/`_` and
* may contain letters, digits, dashes, underscores, and `/` for
@@ -22,11 +23,35 @@
* the stripping here keeps that cleaning one definition as well.
*/
+/**
+ * The value-level rule the index regex and the write-time predicate
+ * share, spelled ONCE below: a value starts with a letter/underscore and
+ * continues with letters, digits, dashes, underscores, and `/`
+ * (nesting). By the shared onset a value may not begin with a slash and
+ * may never be purely numeric. {@link TAG_RE} wraps this source with the
+ * prose boundary and the `#`; {@link isObsidianTagValue} matches it
+ * anchored - one spelling, two anchors.
+ */
+const TAG_VALUE_SOURCE = "[A-Za-z_][\\w\\-/]*";
+
/**
* Obsidian-style tag: #word where word starts with a letter/_ and may contain
* letters, digits, dashes, underscores, and '/' for hierarchy.
*/
-export const TAG_RE = /(^|[^\w/])#([A-Za-z_][\w\-/]*)/g;
+export const TAG_RE = new RegExp(`(^|[^\\w/])#(${TAG_VALUE_SOURCE})`, "g");
+
+/** Matches a whole tag value: the same rule TAG_RE captures, anchored. */
+const TAG_VALUE_RE = new RegExp(`^${TAG_VALUE_SOURCE}$`);
+
+/**
+ * Does `value` (WITHOUT its `#`) satisfy the one tag rule - the rule the
+ * search index extracts with, the hygiene detectors report against, and
+ * board sibling t_11ee559f validates composed tags at the write sites
+ * with (consumed via `src/core/brain/tag-syntax.ts`, never re-copied).
+ */
+export function isObsidianTagValue(value: string): boolean {
+ return TAG_VALUE_RE.test(value);
+}
// A fenced block runs from an opening line of three or more backticks or
// tildes to the first later line that starts with a run of the SAME
diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.ts
index 9ced9aae..e2de99cd 100644
--- a/src/mcp/brain/ingest-tools.ts
+++ b/src/mcp/brain/ingest-tools.ts
@@ -292,6 +292,13 @@ export function serializeBatchPlan(plan: BatchPlan): Record<string, unknown> {
total_files: plan.totalFiles,
total_bytes: plan.totalBytes,
skipped: [...plan.skipped],
+ // Only emitted when the manifest's recorded extraction contract differs
+ // from the live one (t_586d5d8b), so a plan under an unchanged contract
+ // serializes byte-identically to before. The count names how many files
+ // reprocess because of the contract rather than their bytes.
+ ...(plan.contractChanged
+ ? { contract_changed: true, contract_changed_files: plan.contractChangedFiles }
+ : {}),
// Only emitted when the extractable gate skipped something, so a plan with
// no extractable declaration serializes byte-identically to before. The
// reason is the typed token (P4) and `detail` carries the value behind
diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.ts
index 3e557f06..7dceb75a 100644
--- a/src/mcp/brain/synthesis-tools.ts
+++ b/src/mcp/brain/synthesis-tools.ts
@@ -8,10 +8,11 @@
import {
appendSessionSummary,
- getSessionSummary,
+ getSessionSummaryReport,
listSessionSummaries,
SessionSummaryError,
type SessionSummaryDigest,
+ type SessionSummaryRecordRef,
} from "../../core/brain/session-summary.ts";
import {
saveSessionCheckpoint,
@@ -84,6 +85,11 @@ function serializeDigest(digest: SessionSummaryDigest): Record<string, unknown>
};
}
+/** Wire shape of one divergence record: identity and hash, never a payload echo. */
+function serializeDivergenceRecord(record: SessionSummaryRecordRef): Record<string, unknown> {
+ return { id: record.id, created_at: record.createdAt, content_hash: record.contentHash };
+}
+
async function toolBrainSessionSummary(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -124,8 +130,23 @@ async function toolBrainSessionSummary(
if (operation === "get") {
const sessionId = requiredSessionId(args);
- const digest = getSessionSummary(ctx.vault, sessionId);
- return digest === null ? { found: false } : { found: true, digest: serializeDigest(digest) };
+ const report = getSessionSummaryReport(ctx.vault, sessionId);
+ if (report === null) return { found: false };
+ // Additive divergence fields (t_59d4c919): the count always; the
+ // divergent flag and the bounded id/hash sample only when the session
+ // holds more than one content-differing digest. `{ found: false }` is
+ // untouched.
+ return {
+ found: true,
+ digest: serializeDigest(report.digest),
+ digest_count: report.digestCount,
+ ...(report.divergent === true
+ ? {
+ divergent: true,
+ records: (report.records ?? []).map(serializeDivergenceRecord),
+ }
+ : {}),
+ };
}
// operation === "list"
diff --git a/src/mcp/error-redaction.ts b/src/mcp/error-redaction.ts
index 5999113a..029192f5 100644
--- a/src/mcp/error-redaction.ts
+++ b/src/mcp/error-redaction.ts
@@ -20,6 +20,7 @@ import { homedir, tmpdir } from "node:os";
import { TRANSPORT_REACH, type TransportReach } from "../core/graph/transport-reach.ts";
import { redactRawOutput } from "../core/redactor.ts";
+import { sortedDistinctLiterals } from "../core/secret-ref.ts";
function withRealpath(path: string): string[] {
const out = [path];
@@ -40,9 +41,31 @@ function withRealpath(path: string): string[] {
* that already holds filesystem-equivalent access - only the vault root
* is redacted, as it always was; at remote reach the home and temp roots
* are replaced too, and every root becomes a named placeholder.
+ *
+ * `resolvedLiterals` carries values already resolved from `$secret:`
+ * references at a use site (the named-secret resolver). A refused
+ * operation may name a credential in its prose - a fetch failure echoing
+ * the URL it was handed, for instance - and the shape passes behind the
+ * shared redactor cannot see a value with no vendor prefix and a quiet
+ * surrounding key. Each occurrence is scrubbed verbatim, longest value
+ * first. Omitting it (or passing an empty list) keeps the output
+ * byte-identical to the pre-literal signature.
*/
-export function redactErrorForCaller(raw: string, vault: string, reach: TransportReach): string {
- if (reach === TRANSPORT_REACH.local) return redactRawOutput(raw, { literals: [vault] });
+export function redactErrorForCaller(
+ raw: string,
+ vault: string,
+ reach: TransportReach,
+ resolvedLiterals: ReadonlyArray<string> = [],
+): string {
+ const literals = sortedDistinctLiterals(resolvedLiterals);
+ if (reach === TRANSPORT_REACH.local) {
+ // The vault goes through the same longest-first ordering as the
+ // literals: a resolved value that CONTAINS the vault path would have
+ // its match destroyed by an unsorted vault substitution first, and
+ // leak the residue - the exact failure the longest-first rule exists
+ // to prevent.
+ return redactRawOutput(raw, { literals: sortedDistinctLiterals([vault, ...literals]) });
+ }
const roots: Array<readonly [string, string]> = [];
for (const [path, label] of [
[vault, "<vault>"],
@@ -62,5 +85,7 @@ export function redactErrorForCaller(raw: string, vault: string, reach: Transpor
const escaped = root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
text = text.replace(new RegExp(`${escaped}(?=$|[\\\\/\\s'"\`:,;)\\]])`, "g"), label);
}
- return redactRawOutput(text, {});
+ // The roots keep their segment-boundary handling above; the resolved
+ // literals are ordinary substrings and go through the shared scrub.
+ return redactRawOutput(text, literals.length === 0 ? {} : { literals });
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 5a9b748b..b68834c5 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -60,6 +60,7 @@ import { ArtifactStore } from "./artifact-store.ts";
import { applyPreviewBudget } from "./preview-budget.ts";
import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "./capabilities.ts";
import { redactErrorForCaller } from "./error-redaction.ts";
+import { resolvedSecretLiterals } from "../core/secret-resolver.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";
@@ -520,7 +521,7 @@ export class MCPServer {
const message =
this.reach === TRANSPORT_REACH.local
? raw
- : redactErrorForCaller(raw, this.vault, this.reach);
+ : redactedErrorMessage(raw, this.vault, this.reach);
// ValueError/TypeError semantics in Python → tool-level error envelope.
// OSError in Python → "filesystem error" prefix. We collapse both to a
// single tool-level error since JS doesn't distinguish.
@@ -711,12 +712,27 @@ export function internalErrorResponse(
reach: TransportReach,
): JsonRpcResponse {
const raw = (exc as Error).message ?? String(exc);
- const message = redactErrorForCaller(raw, vault, reach);
+ const message = redactedErrorMessage(raw, vault, reach);
return errorResponse(requestId, INTERNAL_ERROR, `${INTERNAL_ERROR_PREFIX}${message}`, {
code: codeForError(exc),
});
}
+/**
+ * Error prose for a caller, with the vault's KNOWN credential values
+ * scrubbed. The fourth composition this redaction gained: the shapes-only
+ * passes cannot see a resolved credential under a quiet key name, and an
+ * exception is exactly where one travels (a fetch failure echoing the URL
+ * it was handed, a refusal naming the field it rejected). The values come
+ * from {@link resolvedSecretLiterals}, which contributes NOTHING when the
+ * store is absent, empty, unreadable or locked - so a boundary that
+ * cannot know the values answers byte-identically to the pre-literal
+ * redactor instead of pretending to redact.
+ */
+function redactedErrorMessage(raw: string, vault: string, reach: TransportReach): string {
+ return redactErrorForCaller(raw, vault, reach, resolvedSecretLiterals(vault));
+}
+
// Re-exports so callers that previously imported these names from
// `open_second_brain.mcp` keep working.
export { PROTOCOL_VERSION, SERVER_NAME, SERVER_VERSION, JSONRPC_VERSION };
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 0f1204d7..89dae9f4 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -23,6 +23,7 @@
import { ConfigReadError, discoverConfig } from "../core/config.ts";
import { redactConfigMapping } from "../core/egress/guard.ts";
+import { resolvedSecretLiterals } from "../core/secret-resolver.ts";
import type { ConfigDiscovery } from "../core/types.ts";
import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
@@ -175,7 +176,17 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
config_path: String(discovery.path),
config_exists: discovery.exists,
config_keys: configKeys,
- config: broken === null ? redactConfigMapping(discovery.data) : unresolvedField(broken),
+ // The mapping passes with the vault's KNOWN resolved values: a
+ // credential the custody store holds, echoed under a quiet config key
+ // the shape passes cannot see, is scrubbed by the literal pass. An
+ // absent, empty or locked store contributes nothing, and the mapping
+ // is byte-identical to the bare single-argument call.
+ config:
+ broken === null
+ ? redactConfigMapping(discovery.data, {
+ resolvedLiterals: resolvedSecretLiterals(ctx.vault),
+ })
+ : unresolvedField(broken),
vault_path: vaultPathField(ctx),
// `boolean | { error }`. Both answerable cases keep their exact literal
// - `true` when the directory is there, `false` when it is genuinely
diff --git a/src/mcp/vault-path-field.ts b/src/mcp/vault-path-field.ts
index 1477184e..e4848f0a 100644
--- a/src/mcp/vault-path-field.ts
+++ b/src/mcp/vault-path-field.ts
@@ -36,6 +36,11 @@
*/
import { ConfigReadError, resolveExposeHostPaths, vaultStoreReference } from "../core/config.ts";
+import {
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+} from "../core/brain/secrets/envelope.ts";
+import { SecretReferenceError } from "../core/secret-ref.ts";
import { escapeRegex } from "../core/strings.ts";
import type { UnresolvedField } from "../core/vault-presence.ts";
import type { OutputSchema } from "./output-contract.ts";
@@ -126,6 +131,51 @@ export const CONFIG_UNREADABLE_REASON =
"the device-local config could not be read, so this reference cannot be " +
"resolved; call second_brain_status for the file and the remedy";
+/**
+ * What the degraded field says when the installation secret resolves
+ * through the vault's custody store and the store refuses: the keyfile is
+ * passphrase-wrapped and this process holds no unlocked key.
+ *
+ * The named error's own message carries the keyfile path under the vault -
+ * the same host path this field exists to keep out of model context - so
+ * the remedy is restated here without it, exactly as
+ * {@link CONFIG_UNREADABLE_REASON} restates its remedy without the config
+ * path.
+ */
+export const SECRET_STORE_LOCKED_REASON =
+ "the vault's credential store is locked, so the installation secret " +
+ 'reference cannot be resolved; run "o2b brain secret unlock" and retry';
+
+/**
+ * What the degraded field says when the vault's credential store still
+ * holds entries but its keyfile is gone: the read-only resolve refuses
+ * rather than minting a fresh key over the surviving ciphertext.
+ *
+ * The named error's message is already path-free, but this field degrades
+ * every store refusal to its own short reason for the same reason the
+ * locked state does: the field is a path field, and its error arm is a
+ * named state, not a channel for the store's prose.
+ */
+export const SECRET_STORE_KEYFILE_MISSING_REASON =
+ "the vault's credential store is missing its keyfile, so the installation " +
+ "secret reference cannot be resolved; restore the keyfile and retry";
+
+/**
+ * What the degraded field says when the persisted installation secret is a
+ * `$secret:` reference the vault's custody store cannot answer: the name
+ * is absent from the store and the environment, or the reference is
+ * malformed.
+ *
+ * The named error's message repeats the reference name or the raw value;
+ * neither belongs in model context. The operator inspects the device
+ * config and the store through the surfaces that may name them
+ * (`second_brain_status`, `o2b secrets list`).
+ */
+export const SECRET_REFERENCE_UNRESOLVED_REASON =
+ "the installation secret is a $secret: reference the vault's credential " +
+ "store cannot resolve; inspect the device config and the store with " +
+ "`o2b secrets list`";
+
export function hostPathReference(
path: string,
source: HostPathPolicySource,
@@ -135,6 +185,11 @@ export function hostPathReference(
return resolveExposeHostPaths(configPath) ? path : vaultStoreReference(path, configPath);
} catch (err) {
if (err instanceof ConfigReadError) return { error: CONFIG_UNREADABLE_REASON };
+ if (err instanceof SecretStoreLockedError) return { error: SECRET_STORE_LOCKED_REASON };
+ if (err instanceof SecretStoreKeyfileMissingError) {
+ return { error: SECRET_STORE_KEYFILE_MISSING_REASON };
+ }
+ if (err instanceof SecretReferenceError) return { error: SECRET_REFERENCE_UNRESOLVED_REASON };
throw err;
}
}
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index 4df6282c..901abaf2 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -13,6 +13,7 @@ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import { discoverConfig, resolveAgentName } from "../core/config.ts";
import { redactConfigMapping } from "../core/egress/guard.ts";
+import { resolvedSecretLiterals } from "../core/secret-resolver.ts";
import { probeVaultDirectory } from "../core/vault-presence.ts";
import { doctor } from "../core/doctor.ts";
import { buildReminder } from "../core/identity-reminder.ts";
@@ -94,7 +95,13 @@ export default definePluginEntry({
config_path: discovery.path,
config_exists: discovery.exists,
config_keys: Object.keys(discovery.data).toSorted(),
- config: redactConfigMapping(discovery.data),
+ config: redactConfigMapping(discovery.data, {
+ // The vault's known resolved values join the scan: a custody-
+ // store credential under a quiet config key is scrubbed here
+ // exactly as the primary runtime's status tool scrubs it. A
+ // locked or absent store contributes nothing.
+ resolvedLiterals: resolvedSecretLiterals(vault),
+ }),
vault_path: vaultPathField({ vault }),
vault_exists: presence.unexaminable ?? presence.present,
};
diff --git a/tests/cli/brain-batch-plan-reconcile.test.ts b/tests/cli/brain-batch-plan-reconcile.test.ts
index b60a906d..60b22c0c 100644
--- a/tests/cli/brain-batch-plan-reconcile.test.ts
+++ b/tests/cli/brain-batch-plan-reconcile.test.ts
@@ -10,6 +10,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
+import { hashFile, manifestPath } from "../../src/core/brain/ingest/content-manifest.ts";
import { runCli } from "../helpers/run-cli.ts";
let vault: string;
@@ -59,3 +60,50 @@ describe("o2b brain batch-plan --reconcile", () => {
expect(plan.reconcile).toBeUndefined();
});
});
+
+/** Write a v1 (pre-fingerprint era) manifest recording `rel`'s live hash. */
+function writeV1Manifest(rel: string): void {
+ const path = manifestPath(vault);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(
+ path,
+ JSON.stringify({ schema_version: 1, entries: { [rel]: hashFile(join(vault, rel)) } }),
+ "utf8",
+ );
+}
+
+describe("o2b brain batch-plan — extraction contract reporting (t_586d5d8b)", () => {
+ test("--json surfaces the contract change with the contract-changed status", async () => {
+ write("Docs/a.md");
+ writeV1Manifest("Docs/a.md");
+ const res = await runCli(["brain", "batch-plan", "Docs", "--json"], { env: ENV() });
+ expect(res.returncode).toBe(0);
+ const plan = JSON.parse(res.stdout) as {
+ contract_changed?: boolean;
+ contract_changed_files?: number;
+ batches: Array<{ files: Array<{ path: string; bytes: number; status: string }> }>;
+ };
+ expect(plan.contract_changed).toBe(true);
+ expect(plan.contract_changed_files).toBe(1);
+ expect(plan.batches[0]!.files[0]).toEqual({
+ path: "Docs/a.md",
+ bytes: "content\n".length,
+ status: "contract-changed",
+ });
+ });
+
+ test("an unchanged contract emits no contract keys (byte-identical shape)", async () => {
+ write("Docs/a.md");
+ const res = await runCli(["brain", "batch-plan", "Docs", "--json"], { env: ENV() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).not.toContain("contract_changed");
+ });
+
+ test("text mode reports the contract change", async () => {
+ write("Docs/a.md");
+ writeV1Manifest("Docs/a.md");
+ const res = await runCli(["brain", "batch-plan", "Docs"], { env: ENV() });
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("extraction contract changed");
+ });
+});
diff --git a/tests/cli/brain-batch-plan-scoping.test.ts b/tests/cli/brain-batch-plan-scoping.test.ts
index 11a5c1cc..9c71824a 100644
--- a/tests/cli/brain-batch-plan-scoping.test.ts
+++ b/tests/cli/brain-batch-plan-scoping.test.ts
@@ -35,6 +35,26 @@ function write(rel: string): void {
const ENV = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+describe("o2b brain batch-plan source-dir contract", () => {
+ test("an absolute source dir refuses with the vault-relative contract, not a false non-existence", async () => {
+ // S20: the absolute argument was joined INSIDE the vault path, so a
+ // directory the operator had just listed was refused as missing - and
+ // the message never stated the real contract, that the argument is
+ // vault-relative.
+ write("sources/note.md");
+ const res = await runCli(["brain", "batch-plan", join(vault, "sources")], {
+ env: ENV(),
+ });
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain(
+ "planBatches: source dir must be a vault-relative path inside the vault " +
+ `(got "${join(vault, "sources")}")`,
+ );
+ expect(res.stderr).toContain("rerun with the directory path relative to the vault root");
+ expect(res.stderr).not.toContain("is not an existing directory");
+ });
+});
+
describe("o2b brain batch-plan scoping flags", () => {
test("--src-subpath restricts discovery to the subtree", async () => {
write("mono/pkg/a/one.md");
diff --git a/tests/cli/brain-design-note.test.ts b/tests/cli/brain-design-note.test.ts
index 0da94c25..52c251bf 100644
--- a/tests/cli/brain-design-note.test.ts
+++ b/tests/cli/brain-design-note.test.ts
@@ -11,11 +11,11 @@
* 4. A missing topic is a usage error (exit 2), and the verb has its own
* `--help`.
* 5. The MCP tool answers over the same core, both phases, and the path
- * it reports is vault-relative - no MCP response carries the
- * absolute host path.
+ * it reports is vault-relative - no MCP response or CLI output carries
+ * the absolute host path.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -107,8 +107,19 @@ test("the commit phase --json names the note and its one recommendation", async
expect(payload.ok).toBe(true);
expect(payload.recommended).toBe("option-1");
expect(payload.alternative_count).toBe(2);
- expect(existsSync(payload.path)).toBe(true);
- expect(payload.path).toContain(join("Brain", "decisions"));
+ // Vault-relative, matching the distill house style and the MCP twin:
+ // the absolute host path is the operator-supplied vault prefix composed
+ // with a machine-derived subtree, and neither belongs in output that
+ // lands in model context.
+ expect(payload.path).toMatch(/^Brain[/\\]decisions[/\\]/);
+ expect(existsSync(join(vault, payload.path))).toBe(true);
+});
+
+test("text mode names the note vault-relative on the wrote line", async () => {
+ const r = await run([TOPIC, "--payload", JSON.stringify(note(false, true))]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toMatch(/^wrote Brain[/\\]decisions[/\\]design-/m);
+ expect(r.stdout).not.toContain(tmp);
});
test("a payload recommending nothing exits 1, names the count, and writes nothing", async () => {
@@ -155,9 +166,8 @@ test("the MCP tool answers both phases over the same core", async () => {
};
expect(committed.phase).toBe("commit");
expect(committed.recommended).toBe("option-0");
- // Vault-relative on the MCP surface, and the response carries the host
- // path nowhere - an MCP payload lands in model context. The CLI keeps
- // the absolute path it has always printed; that one runs on the host.
+ // Vault-relative on both surfaces, and neither response carries the host
+ // path - the CLI's output and an MCP payload alike land in model context.
expect(committed.path).toMatch(/^Brain[/\\]decisions[/\\]/);
expect(existsSync(join(vault, committed.path))).toBe(true);
expect(JSON.stringify(committed)).not.toContain(vault);
@@ -171,3 +181,58 @@ test("is a full-tier tool, absent from the writer surface", () => {
expect(buildToolTable("full").find((t) => t.name === "brain_design_note")).toBeDefined();
expect(buildToolTable("writer").find((t) => t.name === "brain_design_note")).toBeUndefined();
});
+
+describe("think-block strip (t_dac8bf7e)", () => {
+ test("a <think>-prefixed payload succeeds, names the strip, and commits the same note", async () => {
+ const r = await run([
+ TOPIC,
+ "--payload",
+ `<think>weighing the options</think>${JSON.stringify(note(false, true))}`,
+ "--json",
+ ]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ note?: string;
+ recommended: string;
+ path: string;
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.note).toContain("<think>");
+ expect(payload.recommended).toBe("option-1");
+ expect(existsSync(join(vault, payload.path))).toBe(true);
+ });
+
+ test("text mode names the strip too - never a silent strip", async () => {
+ const r = await run([
+ TOPIC,
+ "--payload",
+ `<think>weighing the options</think>${JSON.stringify(note(false, true))}`,
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("<think>");
+ });
+
+ test("garbage still exits 1 with the plain ok:false refusal", async () => {
+ const r = await run([TOPIC, "--payload", "not json", "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toBe("payload must be valid JSON");
+ });
+
+ test("a payload that still does not parse after the strip names the attempt and exits 1", async () => {
+ const r = await run([TOPIC, "--payload", "<think>r</think>not json", "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain("<think>");
+ });
+
+ test("a clean payload's --json output carries no note key", async () => {
+ const r = await run([TOPIC, "--payload", JSON.stringify(note(false, true)), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect("note" in payload).toBe(false);
+ });
+});
diff --git a/tests/cli/brain-distill.test.ts b/tests/cli/brain-distill.test.ts
index d8cf247d..5469f999 100644
--- a/tests/cli/brain-distill.test.ts
+++ b/tests/cli/brain-distill.test.ts
@@ -19,6 +19,7 @@ import { join } from "node:path";
import { nestedCommand } from "../../src/cli/command-manifest.ts";
import { readExcerptSection } from "../../src/core/brain/provenance/capture-scope.ts";
import { BRAIN_DISTILLATIONS_REL } from "../../src/core/brain/path-constants.ts";
+import { PAYLOAD_UNPARSEABLE_MESSAGE } from "../../src/core/brain/payload-json.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -302,3 +303,65 @@ describe("o2b brain distill - quote check and capture scope", () => {
expect(names).toContain("excerpt-file");
});
});
+
+describe("o2b brain distill - think-block strip (t_dac8bf7e)", () => {
+ test("a <think>-prefixed claims payload succeeds, names the strip, and distills the same claims", async () => {
+ const claims = `<think>weighing the spans</think>${JSON.stringify([
+ { text: "First atomic claim.", block: "abc" },
+ ])}`;
+ const res = await runCli(
+ ["brain", "distill", "Articles/src.md", "--claims", claims, "--vault", vault, "--json"],
+ { env },
+ );
+ expect(res.returncode).toBe(0);
+ const out = JSON.parse(res.stdout) as {
+ claim_count: number;
+ distillation_path: string;
+ note?: string;
+ };
+ expect(out.claim_count).toBe(1);
+ expect(out.note).toContain("<think>");
+ expect(existsSync(join(vault, out.distillation_path))).toBe(true);
+ });
+
+ test("the human line names the strip too - never a silent strip", async () => {
+ const claims = `<think>weighing the spans</think>${JSON.stringify([{ text: "A claim." }])}`;
+ const res = await runCli(
+ ["brain", "distill", "Articles/src.md", "--claims", claims, "--vault", vault],
+ { env },
+ );
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("<think>");
+ });
+
+ test("garbage claims still exit 1 with the plain refusal", async () => {
+ const res = await distillWithClaims("not json");
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toBe(`distill: ${PAYLOAD_UNPARSEABLE_MESSAGE}\n`);
+ });
+
+ test("claims that still do not parse after the strip name the attempt and exit 1", async () => {
+ const res = await distillWithClaims("<think>r</think>not json");
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("<think>");
+ });
+
+ test("clean claims output carries no note key", async () => {
+ const res = await runCli(
+ [
+ "brain",
+ "distill",
+ "Articles/src.md",
+ "--claims",
+ JSON.stringify([{ text: "A claim." }]),
+ "--vault",
+ vault,
+ "--json",
+ ],
+ { env },
+ );
+ expect(res.returncode).toBe(0);
+ const out = JSON.parse(res.stdout) as Record<string, unknown>;
+ expect("note" in out).toBe(false);
+ });
+});
diff --git a/tests/cli/brain-extract-signals.test.ts b/tests/cli/brain-extract-signals.test.ts
index 3db9a8b0..77adef6b 100644
--- a/tests/cli/brain-extract-signals.test.ts
+++ b/tests/cli/brain-extract-signals.test.ts
@@ -11,7 +11,7 @@
* 5. The verb has its own `--help`, not a dump of the whole brain help.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -133,3 +133,57 @@ test("--help prints the verb's own usage", async () => {
expect(r.stdout.startsWith("usage:")).toBe(true);
expect(r.stdout).toContain("o2b brain extract-signals");
});
+
+describe("think-block strip (t_dac8bf7e)", () => {
+ test("a <think>-prefixed payload succeeds, names the strip, and writes the clean case's items", async () => {
+ const r = await run([
+ SESSION,
+ "--payload",
+ `<think>weighing the turns</think>${JSON.stringify({ items: [ITEM] })}`,
+ "--json",
+ ]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ ok: boolean;
+ note?: string;
+ written: Array<{ id: string; topic: string }>;
+ };
+ expect(payload.ok).toBe(true);
+ expect(payload.note).toContain("<think>");
+ // Identical to the clean case's pinned written items.
+ expect(payload.written.map((w) => w.topic)).toEqual(["heading-style"]);
+ });
+
+ test("text mode names the strip too - never a silent strip", async () => {
+ const r = await run([
+ SESSION,
+ "--payload",
+ `<think>weighing the turns</think>${JSON.stringify({ items: [ITEM] })}`,
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("<think>");
+ });
+
+ test("garbage still exits 1 with the plain ok:false refusal", async () => {
+ const r = await run([SESSION, "--payload", "not json", "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toBe("payload must be valid JSON");
+ });
+
+ test("a payload that still does not parse after the strip names the attempt and exits 1", async () => {
+ const r = await run([SESSION, "--payload", "<think>r</think>not json", "--json"]);
+ expect(r.returncode).toBe(1);
+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain("<think>");
+ });
+
+ test("a clean payload's --json output carries no note key", async () => {
+ const r = await run([SESSION, "--payload", JSON.stringify({ items: [ITEM] }), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect("note" in payload).toBe(false);
+ });
+});
diff --git a/tests/cli/brain-feedback-routing-hint.test.ts b/tests/cli/brain-feedback-routing-hint.test.ts
index be60c858..6b9f880c 100644
--- a/tests/cli/brain-feedback-routing-hint.test.ts
+++ b/tests/cli/brain-feedback-routing-hint.test.ts
@@ -182,6 +182,47 @@ describe("o2b brain feedback - unroutable-capture routing hint", () => {
});
});
+describe("o2b brain feedback - success line and refusal envelope", () => {
+ test("the signal success line names the artifact vault-relative", async () => {
+ // S22: the line printed the operator-supplied vault prefix composed
+ // with the machine-derived inbox subtree - the same class of composed
+ // echo the distill surface renders vault-relative.
+ const out = await record();
+ expect(out.returncode).toBe(0);
+ const line = /^signal: (.+)$/m.exec(out.stdout)!;
+ expect(line[1]).toMatch(/^Brain[/\\]inbox[/\\]sig-/);
+ expect(existsSync(join(vault, line[1]!))).toBe(true);
+ expect(out.stdout).not.toContain(tmp);
+ });
+
+ test("a refused write in --json mode returns the ok:false envelope, not bare text", async () => {
+ // S22 nit: the text-adjacent refusal was correct but nothing
+ // machine-parseable reached stdout, unlike the sibling verbs'
+ // {ok:false, message} twin.
+ const out = await runCli(
+ [
+ "brain",
+ "feedback",
+ "--topic",
+ "unrouted",
+ "--signal",
+ "positive",
+ "--principle",
+ "recorded where it belongs",
+ "--scope",
+ "1-not-a-scope",
+ "--json",
+ ],
+ { env: env() },
+ );
+ expect(out.returncode).toBe(1);
+ const payload = JSON.parse(out.stdout) as { ok: boolean; message: string };
+ expect(payload.ok).toBe(false);
+ expect(payload.message).toContain("failed to write signal");
+ expect(payload.message).toContain("scope:");
+ });
+});
+
/** The `id: <sig-...>` line the verb prints, read back for file assertions. */
function bareIdOf(stdout: string): string {
const match = /^id: (sig-[\w.-]+)$/m.exec(stdout);
diff --git a/tests/cli/brain-import-claude-memory.test.ts b/tests/cli/brain-import-claude-memory.test.ts
index d989c95c..83cd52b7 100644
--- a/tests/cli/brain-import-claude-memory.test.ts
+++ b/tests/cli/brain-import-claude-memory.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
@@ -39,7 +39,9 @@ describe("o2b brain import-claude-memory CLI", () => {
rmSync(mem, { recursive: true });
});
- test("--apply writes files and exits 0", async () => {
+ test("--apply with the approved digest writes files and exits 0", async () => {
+ // t_18fda844: non-interactive apply carries the digest a prior
+ // --dry-run printed, so what lands is what was approved.
const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli2-"));
const vault = join(tmp, "vault");
const config = join(tmp, "config.yaml");
@@ -52,6 +54,22 @@ describe("o2b brain import-claude-memory CLI", () => {
"---\nname: a\ndescription: A.\nmetadata:\n type: feedback\n---\n\nb.\n",
"utf8",
);
+ const dry = await runCli(
+ [
+ "brain",
+ "import-claude-memory",
+ "--vault",
+ vault,
+ "--memory",
+ mem,
+ "--dry-run",
+ "--json",
+ "--allow-arbitrary-memory-path",
+ ],
+ { env },
+ );
+ expect(dry.returncode).toBe(0);
+ const digest = (JSON.parse(dry.stdout) as { digest: string }).digest;
const res = await runCli(
[
"brain",
@@ -62,6 +80,8 @@ describe("o2b brain import-claude-memory CLI", () => {
mem,
"--apply",
"--yes",
+ "--approval-digest",
+ digest,
"--allow-arbitrary-memory-path",
],
{ env },
@@ -70,7 +90,7 @@ describe("o2b brain import-claude-memory CLI", () => {
expect(existsSync(join(vault, "Brain", "preferences", "pref-a.md"))).toBe(true);
rmSync(tmp, { recursive: true });
rmSync(mem, { recursive: true });
- });
+ }, 20000);
test("--apply + --dry-run is rejected", async () => {
const res = await runCli([
@@ -134,3 +154,244 @@ describe("o2b brain import-claude-memory CLI", () => {
rmSync(tmp, { recursive: true });
});
});
+
+/**
+ * A temp vault plus a memory dir holding the given files, wired through one
+ * config env. Shared by the digest and per-entry-disposition describes; kept
+ * at module scope so the linter does not flag re-scoped helpers.
+ */
+function setupImport(
+ tmpPrefix: string,
+ memoryFiles: Record<string, string>,
+): { tmp: string; vault: string; mem: string; env: Record<string, string> } {
+ const tmp = mkdtempSync(join(tmpdir(), tmpPrefix));
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };
+ const mem = join(tmp, "memory");
+ mkdirSync(mem, { recursive: true });
+ for (const [name, bytes] of Object.entries(memoryFiles)) {
+ writeFileSync(join(mem, name), bytes, "utf8");
+ }
+ return { tmp, vault, mem, env };
+}
+
+/** A minimal Claude feedback memory file with the given name/description. */
+function feedbackMd(name: string, description: string): string {
+ return `---\nname: ${name}\ndescription: ${description}.\nmetadata:\n type: feedback\n---\n\nbody.\n`;
+}
+
+const baseArgs = (vault: string, mem: string): string[] => [
+ "brain",
+ "import-claude-memory",
+ "--vault",
+ vault,
+ "--memory",
+ mem,
+ "--allow-arbitrary-memory-path",
+];
+
+describe("o2b brain import-claude-memory --approval-digest (t_18fda844)", () => {
+ test("non-interactive --apply without a digest refuses by name, before any write", async () => {
+ const s = setupImport("o2b-cm-cli-nodigest-", { "feedback_a.md": feedbackMd("a", "A") });
+ try {
+ await runCli(["init", "--vault", s.vault, "--name", "Test"], { env: s.env });
+ await runCli(["brain", "init", "--vault", s.vault], { env: s.env });
+ const res = await runCli([...baseArgs(s.vault, s.mem), "--apply", "--yes"], { env: s.env });
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("--approval-digest");
+ expect(existsSync(join(s.vault, "Brain", "preferences", "pref-a.md"))).toBe(false);
+ } finally {
+ rmSync(s.tmp, { recursive: true, force: true });
+ }
+ });
+
+ test("the dry-run JSON exposes the digest and apply with it lands the plan", async () => {
+ const s = setupImport("o2b-cm-cli-digest-", { "feedback_a.md": feedbackMd("a", "A") });
+ try {
+ await runCli(["init", "--vault", s.vault, "--name", "Test"], { env: s.env });
+ await runCli(["brain", "init", "--vault", s.vault], { env: s.env });
+ const dry = await runCli([...baseArgs(s.vault, s.mem), "--dry-run", "--json"], {
+ env: s.env,
+ });
+ expect(dry.returncode).toBe(0);
+ const plan = JSON.parse(dry.stdout) as {
+ digest: string;
+ plans: Array<{ basename: string; prefId: string; action: string }>;
+ };
+ expect(plan.digest).toMatch(/^[0-9a-f]{64}$/);
+ expect(plan.plans).toEqual([
+ { basename: "feedback_a.md", prefId: "pref-a", action: "CREATE" },
+ ]);
+
+ const apply = await runCli(
+ [...baseArgs(s.vault, s.mem), "--apply", "--yes", "--approval-digest", plan.digest],
+ { env: s.env },
+ );
+ expect(apply.returncode).toBe(0);
+ expect(existsSync(join(s.vault, "Brain", "preferences", "pref-a.md"))).toBe(true);
+ } finally {
+ rmSync(s.tmp, { recursive: true, force: true });
+ }
+ }, 20000);
+
+ test("--approval-digest paired with --dry-run refuses the conflicting pairing", async () => {
+ // A dry run COMPUTES a digest; it cannot consume one. Accepting and
+ // dropping the value would let a mis-piped script read a successful
+ // dry-run exit code as "the digest was honored".
+ const s = setupImport("o2b-cm-cli-digestdryrun-", { "feedback_a.md": feedbackMd("a", "A") });
+ try {
+ await runCli(["init", "--vault", s.vault, "--name", "Test"], { env: s.env });
+ await runCli(["brain", "init", "--vault", s.vault], { env: s.env });
+ const res = await runCli(
+ [...baseArgs(s.vault, s.mem), "--dry-run", "--approval-digest", "f".repeat(64)],
+ { env: s.env },
+ );
+ expect(res.returncode).toBe(2);
+ expect(res.stderr).toContain("--approval-digest");
+ expect(res.stderr).toContain("--apply");
+ expect(existsSync(join(s.vault, "Brain", "preferences", "pref-a.md"))).toBe(false);
+ } finally {
+ rmSync(s.tmp, { recursive: true, force: true });
+ }
+ });
+
+ test("apply with a stale digest refuses with the re-run remedy and writes nothing", async () => {
+ const s = setupImport("o2b-cm-cli-staledigest-", { "feedback_a.md": feedbackMd("a", "A") });
+ try {
+ await runCli(["init", "--vault", s.vault, "--name", "Test"], { env: s.env });
+ await runCli(["brain", "init", "--vault", s.vault], { env: s.env });
+ const dry = await runCli([...baseArgs(s.vault, s.mem), "--dry-run", "--json"], {
+ env: s.env,
+ });
+ const plan = JSON.parse(dry.stdout) as { digest: string };
+ // The approved plan goes stale: the target preference appears.
+ writeFileSync(join(s.vault, "Brain", "preferences", "pref-a.md"), "hand-made\n", "utf8");
+ const apply = await runCli(
+ [...baseArgs(s.vault, s.mem), "--apply", "--yes", "--approval-digest", plan.digest],
+ { env: s.env },
+ );
+ expect(apply.returncode).toBe(1);
+ expect(apply.stderr).toContain("approval digest mismatch");
+ expect(apply.stderr).toContain("o2b brain import-claude-memory --dry-run");
+ expect(readFileSync(join(s.vault, "Brain", "preferences", "pref-a.md"), "utf8")).toBe(
+ "hand-made\n",
+ );
+ } finally {
+ rmSync(s.tmp, { recursive: true, force: true });
+ }
+ }, 20000);
+});
+
+describe("o2b brain import-claude-memory — per-entry disposition (t_11ee559f)", () => {
+ test("a numeric memory name skips its own row with the file and rule named; the other entries land", async () => {
+ // One well-named entry and one whose name slugifies to a purely numeric
+ // topic - exactly the value the shared tag rule refuses.
+ const s = setupImport("o2b-cm-cli-numericskip-", {
+ "feedback_good.md": feedbackMd("good-feedback", "Good"),
+ "feedback_2024.md": feedbackMd("2024", "Numeric"),
+ });
+ try {
+ await runCli(["init", "--vault", s.vault, "--name", "Test"], { env: s.env });
+ await runCli(["brain", "init", "--vault", s.vault], { env: s.env });
+ const dry = await runCli([...baseArgs(s.vault, s.mem), "--dry-run", "--json"], {
+ env: s.env,
+ });
+ expect(dry.returncode).toBe(0);
+ const plan = JSON.parse(dry.stdout) as {
+ digest: string;
+ plans: Array<{ basename: string; prefId: string; action: string }>;
+ skipped: Array<{ basename: string; reason: string }>;
+ };
+ // The good entry is planned; the numeric one is a named skip row, and
+ // no contradictory plan row exists for it.
+ expect(plan.plans).toEqual([
+ { basename: "feedback_good.md", prefId: "pref-good-feedback", action: "CREATE" },
+ ]);
+ expect(plan.skipped).toHaveLength(1);
+ expect(plan.skipped[0]!.basename).toBe("feedback_2024.md");
+ expect(plan.skipped[0]!.reason).toContain("topic:");
+ expect(plan.skipped[0]!.reason).toContain("must start with a letter or underscore");
+ expect(plan.skipped[0]!.reason).toContain("never only digits");
+ expect(plan.digest).toMatch(/^[0-9a-f]{64}$/);
+
+ const apply = await runCli(
+ [...baseArgs(s.vault, s.mem), "--apply", "--yes", "--approval-digest", plan.digest],
+ { env: s.env },
+ );
+ expect(apply.returncode).toBe(0);
+ expect(existsSync(join(s.vault, "Brain", "preferences", "pref-good-feedback.md"))).toBe(true);
+ expect(existsSync(join(s.vault, "Brain", "preferences", "pref-2024.md"))).toBe(false);
+ } finally {
+ rmSync(s.tmp, { recursive: true, force: true });
+ }
+ }, 20000);
+});
+
+describe("o2b brain import-claude-memory — help and not-found refusals", () => {
+ test("verb help names --approval-digest and --from and states the full apply requirement", async () => {
+ // S10: the usage line listed every flag the verb silently accepts
+ // except the two the scripted path actually needs, and the closing
+ // sentence promised --yes alone, contradicting the refusal the verb
+ // itself prints in non-interactive mode.
+ const res = await runCli(["brain", "import-claude-memory", "--help"]);
+ expect(res.returncode).toBe(0);
+ expect(res.stdout).toContain("[--from <backend>]");
+ expect(res.stdout).toContain("[--approval-digest <hex>]");
+ expect(res.stdout).toContain(
+ "--apply requires --yes and --approval-digest in\nnon-interactive mode",
+ );
+ });
+
+ test("missing --memory directory refusal names the remedy", async () => {
+ // S9: the refusal stopped at the missing path, leaving the operator to
+ // guess whether to create it or repoint --memory.
+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli-missing-"));
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };
+ try {
+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });
+ await runCli(["brain", "init", "--vault", vault], { env });
+ const res = await runCli(
+ [
+ "brain",
+ "import-claude-memory",
+ "--vault",
+ vault,
+ "--memory",
+ join(tmp, "nowhere"),
+ "--allow-arbitrary-memory-path",
+ ],
+ { env },
+ );
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("memory directory not found");
+ expect(res.stderr).toContain("(pass --memory with an existing directory, or create it)");
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
+ test("default-discovery miss names the location home-relative, not absolute", async () => {
+ // S9: the default location is derived from homedir(), so the refusal
+ // must not expand the operator's home into output - the sibling
+ // refusal already spells the directory as ~/.claude/projects/.
+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli-home-"));
+ const vault = join(tmp, "vault");
+ const config = join(tmp, "config.yaml");
+ const home = mkdtempSync(join(tmpdir(), "o2b-cm-cli-home-dir-"));
+ const env = { OPEN_SECOND_BRAIN_CONFIG: config, HOME: home };
+ try {
+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });
+ await runCli(["brain", "init", "--vault", vault], { env });
+ const res = await runCli(["brain", "import-claude-memory", "--vault", vault], { env });
+ expect(res.returncode).toBe(1);
+ expect(res.stderr).toContain("memory directory not found: ~/.claude/projects/");
+ expect(res.stderr).not.toContain(home);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/tests/cli/brain-secret.test.ts b/tests/cli/brain-secret.test.ts
index 7ee38398..5545e772 100644
--- a/tests/cli/brain-secret.test.ts
+++ b/tests/cli/brain-secret.test.ts
@@ -5,11 +5,12 @@
* removes irrecoverably.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -113,3 +114,307 @@ test("set without stdin value or --from-env is a usage error", async () => {
expect(result.returncode).toBe(2);
expect(result.stderr).toContain("stdin");
});
+
+test("unlock wraps the raw keyfile; a fresh process sees the locked refusal until re-unlock", async () => {
+ await runCli(["brain", "secret", "set", "api-key", "--vault", vault], {
+ stdin: "sk-lock-test-13579\n",
+ });
+ const keyfile = join(vault, ".open-second-brain", "secrets", "keyfile");
+ expect(readFileSync(keyfile).length).toBe(32);
+
+ const passphrase = fakeCredential("cli-unlock", "-pass", "-42");
+ const unlock = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(unlock.returncode).toBe(0);
+ expect(unlock.stdout).toContain("unlocked");
+ // The raw 32 bytes are gone: the keyfile is a JSON envelope now.
+ expect(readFileSync(keyfile, "utf8").startsWith("{")).toBe(true);
+
+ // A fresh process holds no unlocked key: the store refuses by name, and
+ // the remedy it names is honest about the surface that prints it - the
+ // unlock applies to one process and the passphrase is never persisted,
+ // so a one-shot command cannot carry the unlock into the next command.
+ const locked = await runCli(["brain", "secret", "set", "other", "--vault", vault], {
+ stdin: "sk-other-24680\n",
+ });
+ expect(locked.returncode).toBe(1);
+ expect(locked.stderr).toContain("locked");
+ expect(locked.stderr).toContain("o2b brain secret unlock");
+ expect(locked.stderr).toContain("this process only");
+ expect(locked.stderr).toContain("never persisted");
+
+ // The right passphrase unlocks again; a wrong one refuses by name.
+ const again = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(again.returncode).toBe(0);
+ const wrong = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: `${fakeCredential("no-such", "-pass", "-42")}\n`,
+ });
+ expect(wrong.returncode).toBe(1);
+ expect(wrong.stderr).toContain("passphrase");
+}, 20000);
+
+test("lock refuses a store that was never wrapped, creating nothing; lock after unlock reports cleared", async () => {
+ const lock = await runCli(["brain", "secret", "lock", "--vault", vault]);
+ expect(lock.returncode).toBe(1);
+ expect(lock.stderr).toContain("not passphrase-wrapped");
+ // Locking must not mint a keyfile or the secrets directory.
+ expect(existsSync(join(vault, ".open-second-brain", "secrets"))).toBe(false);
+
+ const passphrase = fakeCredential("cli-lock", "-pass", "-42");
+ const unlock = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(unlock.returncode).toBe(0);
+ const locked = await runCli(["brain", "secret", "lock", "--vault", vault, "--json"]);
+ expect(locked.returncode).toBe(0);
+ expect(JSON.parse(locked.stdout)).toMatchObject({ locked: true });
+});
+
+test("unlock without a passphrase is a usage error", async () => {
+ const result = await runCli(["brain", "secret", "unlock", "--vault", vault], { stdin: "" });
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain("passphrase");
+});
+
+test("a blank --passphrase-from-env value is the usage error a blank stdin passphrase is", async () => {
+ // The stdin ingestion refuses a passphrase that is empty after trim; the
+ // env ingestion enforces the SAME rule, so `SECRET_PASS=" "` cannot wrap
+ // the keyfile under what is almost certainly an unset-variable accident.
+ const result = await runCli(
+ [
+ "brain",
+ "secret",
+ "unlock",
+ "--vault",
+ vault,
+ "--passphrase-from-env",
+ "O2B_TEST_BLANK_PASSPHRASE",
+ ],
+ { env: { O2B_TEST_BLANK_PASSPHRASE: " " } },
+ );
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain("passphrase");
+ // The refusal precedes any custody effect: nothing was wrapped or minted.
+ expect(existsSync(join(vault, ".open-second-brain", "secrets"))).toBe(false);
+});
+
+test("export --out writes the bundle; import restores it; collisions need --replace", async () => {
+ await runCli(
+ [
+ "brain",
+ "secret",
+ "set",
+ "api-key",
+ "--env-var",
+ "MY_API_KEY",
+ "--allow",
+ "bun -e *",
+ "--vault",
+ vault,
+ ],
+ { stdin: "sk-cli-bundle-2468\n" },
+ );
+ const bundlePath = join(tmp, "bundle.json");
+ const passphrase = fakeCredential("cli-bundle", "-pass", "-42");
+ const exported = await runCli(
+ ["brain", "secret", "export", "--out", bundlePath, "--vault", vault],
+ { stdin: `${passphrase}\n` },
+ );
+ expect(exported.returncode).toBe(0);
+ // The bundle bytes carry neither the value nor the passphrase.
+ const bundleRaw = readFileSync(bundlePath, "utf8");
+ expect(bundleRaw).not.toContain("sk-cli-bundle-2468");
+ expect(bundleRaw).not.toContain(passphrase);
+ expect(bundleRaw).toContain("api-key");
+
+ const fresh = join(tmp, "fresh-vault");
+ mkdirSync(join(fresh, "Brain"), { recursive: true });
+ const imported = await runCli(["brain", "secret", "import", bundlePath, "--vault", fresh], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(imported.returncode).toBe(0);
+ const list = await runCli(["brain", "secret", "list", "--vault", fresh, "--json"]);
+ expect(JSON.parse(list.stdout).secrets[0]).toMatchObject({
+ name: "api-key",
+ env_var: "MY_API_KEY",
+ allow: ["bun -e *"],
+ });
+
+ // The same import again refuses the existing name by name; --replace lands.
+ const again = await runCli(["brain", "secret", "import", bundlePath, "--vault", fresh], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(again.returncode).toBe(1);
+ expect(again.stderr).toContain("api-key");
+ const replaced = await runCli(
+ ["brain", "secret", "import", bundlePath, "--vault", fresh, "--replace"],
+ { stdin: `${passphrase}\n` },
+ );
+ expect(replaced.returncode).toBe(0);
+
+ // A wrong passphrase writes nothing to a fresh vault.
+ const empty = join(tmp, "empty-vault");
+ mkdirSync(join(empty, "Brain"), { recursive: true });
+ const wrong = await runCli(["brain", "secret", "import", bundlePath, "--vault", empty], {
+ stdin: `${fakeCredential("no-such", "-pass", "-42")}\n`,
+ });
+ expect(wrong.returncode).toBe(1);
+ expect(wrong.stderr).toContain("passphrase");
+ expect(existsSync(join(empty, ".open-second-brain", "secrets", "secrets.json"))).toBe(false);
+});
+
+describe("secret refusals and help accuracy", () => {
+ test("an unset --passphrase-from-env var names both ingestion routes", async () => {
+ // S1/S3/S4: the refusal named the variable but no remedy and no other
+ // route, while the sibling empty-stdin refusal names both.
+ const r = await runCli(
+ [
+ "brain",
+ "secret",
+ "unlock",
+ "--passphrase-from-env",
+ "OSB_TEST_MISSING_PW",
+ "--vault",
+ vault,
+ ],
+ { stdin: "" },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("env var OSB_TEST_MISSING_PW is unset, empty, or blank");
+ expect(r.stderr).toContain("set it to a passphrase, or pipe the passphrase via stdin");
+ });
+
+ test("an unset --from-env var on set names both ingestion routes", async () => {
+ const r = await runCli(
+ ["brain", "secret", "set", "env-one", "--from-env", "OSB_TEST_MISSING_PW", "--vault", vault],
+ { stdin: "" },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("env var OSB_TEST_MISSING_PW is unset or empty");
+ expect(r.stderr).toContain("set it to a value, or pipe the value via stdin");
+ });
+
+ test("a wrong unlock passphrase refuses without naming the keyfile path", async () => {
+ // S1: the sibling locked-store and missing-keyfile refusals are
+ // path-free because the prose travels into model context; this one
+ // leaked the machine-derived keyfile path the operator never supplied
+ // (they named --vault, not the keyfile).
+ await runCli(["brain", "secret", "set", "api-key", "--vault", vault], {
+ stdin: "sk-pathfree-11223\n",
+ });
+ const unlock = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: "right-pass-12345\n",
+ });
+ expect(unlock.returncode).toBe(0);
+ const wrong = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: "wrong-pass-67890\n",
+ });
+ expect(wrong.returncode).toBe(1);
+ expect(wrong.stderr).toContain("keyfile_envelope_passphrase_refused");
+ expect(wrong.stderr).toContain("does not unwrap this envelope");
+ expect(wrong.stderr).not.toContain(join(vault, ".open-second-brain"));
+ expect(wrong.stderr).not.toContain(tmp);
+ });
+
+ test("an import collision names the --replace flag", async () => {
+ // S4: collisions were named, but the literal flag never was, leaving
+ // the spelling for the operator to guess.
+ await runCli(["brain", "secret", "set", "dup-key", "--vault", vault], {
+ stdin: "sk-collision-33445\n",
+ });
+ const bundlePath = join(tmp, "collision-bundle.json");
+ const passphrase = fakeCredential("cli-collision", "-pass", "-42");
+ const exported = await runCli(
+ ["brain", "secret", "export", "--out", bundlePath, "--vault", vault],
+ { stdin: `${passphrase}\n` },
+ );
+ expect(exported.returncode).toBe(0);
+ const again = await runCli(["brain", "secret", "import", bundlePath, "--vault", vault], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(again.returncode).toBe(1);
+ expect(again.stderr).toContain("the store already holds: dup-key");
+ expect(again.stderr).toContain("pass --replace to import over them");
+ });
+
+ test("the --help usage line and the usage-error line agree, and name every op's flags", async () => {
+ // S7a: --help showed a shorter usage line than the USAGE constant the
+ // usage-error path prints - two surfaces, two truths.
+ const help = await runCli(["brain", "secret", "--help"]);
+ expect(help.returncode).toBe(0);
+ const usageError = await runCli(["brain", "secret", "no-such-op"]);
+ expect(usageError.returncode).toBe(2);
+ const helpUsage = /^usage: .+$/m.exec(help.stdout)![0]!;
+ const errorUsage = /^usage: .+$/m.exec(usageError.stderr)![0]!;
+ expect(helpUsage).toBe(errorUsage);
+ expect(helpUsage).toContain(
+ "set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] [--vault <path>] [--json]",
+ );
+ expect(helpUsage).toContain("list [--vault <path>] [--json]");
+ expect(helpUsage).toContain("rm <name> [--vault <path>]");
+ expect(helpUsage).toContain("lock [--vault <path>]");
+ expect(helpUsage).toContain("unlock [--passphrase-from-env SRC] [--vault <path>]");
+ expect(helpUsage).toContain("export --out FILE [--passphrase-from-env SRC] [--vault <path>]");
+ expect(helpUsage).toContain(
+ "import FILE [--replace] [--passphrase-from-env SRC] [--vault <path>]",
+ );
+ expect(helpUsage).toContain("run <name> [--agent N] [--vault <path>] [--json] -- <command...>");
+ });
+
+ test("an op refuses flags it never documents, by name", async () => {
+ // S7b: the parse table was op-independent, so lock swallowed
+ // --passphrase-from-env (and its env read never happened) with exit 0.
+ const r = await runCli([
+ "brain",
+ "secret",
+ "lock",
+ "--passphrase-from-env",
+ "OSB_TEST_MISSING_PW",
+ "--vault",
+ vault,
+ ]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("brain secret lock: unknown flag --passphrase-from-env");
+ expect(r.stderr).toContain("usage: o2b brain secret");
+ });
+
+ test("run still accepts its own flags and refuses another op's", async () => {
+ await runCli(["brain", "secret", "set", "run-flag", "--allow", "bun -e *", "--vault", vault], {
+ stdin: "sk-runflag-44556\n",
+ });
+ const ok = await runCli([
+ "brain",
+ "secret",
+ "run",
+ "run-flag",
+ "--agent",
+ "tester",
+ "--vault",
+ vault,
+ "--",
+ "bun",
+ "-e",
+ "process.exit(0)",
+ ]);
+ expect(ok.returncode).toBe(0);
+ const refused = await runCli([
+ "brain",
+ "secret",
+ "run",
+ "run-flag",
+ "--out",
+ "somewhere",
+ "--vault",
+ vault,
+ "--",
+ "bun",
+ "-e",
+ "process.exit(0)",
+ ]);
+ expect(refused.returncode).toBe(2);
+ expect(refused.stderr).toContain("brain secret run: unknown flag --out");
+ });
+});
diff --git a/tests/cli/brain-session-summary.test.ts b/tests/cli/brain-session-summary.test.ts
new file mode 100644
index 00000000..61d322f4
--- /dev/null
+++ b/tests/cli/brain-session-summary.test.ts
@@ -0,0 +1,163 @@
+/**
+ * `o2b brain session-summary get` (trust-surface-hardening, t_59d4c919).
+ * Claims pinned here:
+ *
+ * 1. `get --json` carries the digest plus the additive `digest_count`, and
+ * the divergence keys (`divergent`, `records`) only when more than one
+ * content-differing digest exists for the session.
+ * 2. The divergence records are an id/created_at/content_hash list, never
+ * a payload echo.
+ * 3. The CLI serializer now carries `project`, matching the MCP serializer
+ * (the verified drift).
+ * 4. Text mode appends exactly one note line when the session diverges,
+ * and stays byte-identical when it does not.
+ * 5. `found: false` is byte-identical to the pre-change envelope.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendSessionSummary } from "../../src/core/brain/session-summary.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+function run(args: ReadonlyArray<string>) {
+ return runCli(["brain", "session-summary", ...args, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },
+ });
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-session-summary-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+test("get --json carries the digest plus digest_count for a single record", async () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-one",
+ request: "Add a structured session summary",
+ decisions: ["Reuse the continuity store"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const r = await run(["get", "--session", "sess-one", "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ found: boolean;
+ digest: Record<string, unknown>;
+ digest_count: number;
+ };
+ expect(payload.found).toBe(true);
+ expect(payload.digest.id).toBe(digest.id);
+ expect(payload.digest.session_id).toBe("sess-one");
+ expect(payload.digest.request).toBe("Add a structured session summary");
+ expect(payload.digest_count).toBe(1);
+ expect("divergent" in payload).toBe(false);
+ expect("records" in payload).toBe(false);
+});
+
+test("get --json after two differing writes carries the divergence keys and the latest digest", async () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-div",
+ decisions: ["older decision"],
+ createdAt: "2026-06-14T09:00:00.000Z",
+ });
+ const newer = appendSessionSummary(vault, {
+ sessionId: "sess-div",
+ decisions: ["newer decision"],
+ createdAt: "2026-06-14T11:00:00.000Z",
+ });
+ const r = await run(["get", "--session", "sess-div", "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ found: boolean;
+ digest: Record<string, unknown>;
+ digest_count: number;
+ divergent?: boolean;
+ records?: Array<Record<string, unknown>>;
+ };
+ expect(payload.found).toBe(true);
+ expect(payload.digest.id).toBe(newer.id);
+ expect(payload.digest_count).toBe(2);
+ expect(payload.divergent).toBe(true);
+ // The additive key set is frozen: no key may appear or disappear from the
+ // divergent envelope silently (the single-record envelope carries exactly
+ // found/digest/digest_count; divergence adds exactly these two).
+ expect(Object.keys(payload).toSorted()).toEqual([
+ "digest",
+ "digest_count",
+ "divergent",
+ "found",
+ "records",
+ ]);
+ expect(payload.records?.length).toBe(2);
+ for (const record of payload.records ?? []) {
+ expect(typeof record["id"]).toBe("string");
+ expect(typeof record["created_at"]).toBe("string");
+ expect(typeof record["content_hash"]).toBe("string");
+ }
+ // id/hash lists, never a payload echo.
+ expect(JSON.stringify(payload.records)).not.toContain("newer decision");
+});
+
+test("get --json serializes project, matching the MCP serializer", async () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-proj",
+ project: "alpha",
+ decisions: ["scoped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const r = await run(["get", "--session", "sess-proj", "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as { digest: Record<string, unknown> };
+ expect(payload.digest["project"]).toBe("alpha");
+});
+
+test("text mode get appends exactly one note line when the session diverges", async () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-text",
+ decisions: ["older decision"],
+ createdAt: "2026-06-14T09:00:00.000Z",
+ });
+ appendSessionSummary(vault, {
+ sessionId: "sess-text",
+ decisions: ["newer decision"],
+ createdAt: "2026-06-14T11:00:00.000Z",
+ });
+ const r = await run(["get", "--session", "sess-text"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("session sess-text");
+ expect(r.stdout).toContain("newer decision");
+ const noteLines = r.stdout.split("\n").filter((line) => line.includes("divergent=true"));
+ expect(noteLines.length).toBe(1);
+ expect(noteLines[0]).toContain("digest_count=2");
+});
+
+test("text mode get for a single record stays free of a divergence note", async () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-plain",
+ decisions: ["one decision"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const r = await run(["get", "--session", "sess-plain"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("one decision");
+ expect(r.stdout).not.toContain("divergent");
+});
+
+test("get for an unknown session --json prints exactly the found:false envelope", async () => {
+ const r = await run(["get", "--session", "missing", "--json"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toBe(`${JSON.stringify({ found: false }, null, 2)}\n`);
+});
diff --git a/tests/cli/brain-skill-page-drafts.test.ts b/tests/cli/brain-skill-page-drafts.test.ts
index 635f646e..6a7b8119 100644
--- a/tests/cli/brain-skill-page-drafts.test.ts
+++ b/tests/cli/brain-skill-page-drafts.test.ts
@@ -12,7 +12,7 @@
* skills root.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
+import { afterEach, beforeEach, 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";
@@ -109,8 +109,40 @@ test("page-draft --json stages a pending proposal inside the vault", async () =>
expect(r.returncode).toBe(0);
const payload = JSON.parse(r.stdout) as { outcome: string; slug: string; path: string };
expect(payload.outcome).toBe("created");
- expect(payload.path.startsWith(join(vault, "Brain"))).toBe(true);
- expect(existsSync(join(skillsRoot, DRAFT.name, "SKILL.md"))).toBe(false);
+ // Vault-relative, like the distill and MCP surfaces: the absolute host
+ // path is the vault prefix (operator-supplied) composed with a
+ // machine-derived subtree, and output that lands in model context
+ // carries neither.
+ expect(payload.path.startsWith("Brain/skill-proposals/pending/")).toBe(true);
+ expect(existsSync(join(vault, payload.path))).toBe(true);
+});
+
+test("a blank required payload field refuses with the stable prefix and no stack trace", async () => {
+ // S17: a core refusal on the commit path escaped uncaught, and the
+ // runner dumped a raw stack trace with machine-derived source paths -
+ // no stable prefix, no refusal an agent could match on.
+ const r = await run([
+ "page-draft",
+ PAGE,
+ "--payload",
+ JSON.stringify({ ...DRAFT, description: "" }),
+ ]);
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("brain skill-proposals page-draft:");
+ expect(r.stderr).toContain("$.description");
+ expect(r.stderr).toContain("must be a non-empty string");
+ expect(r.stderr).not.toContain("\n at ");
+ expect(r.stderr).not.toContain("response-shape.ts");
+});
+
+test("a page that does not exist refuses with the stable prefix and no stack trace", async () => {
+ const r = await run(["page-draft", "notes/absent-page.md", "--payload", JSON.stringify(DRAFT)]);
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain(
+ "brain skill-proposals page-draft: no such vault page: notes/absent-page.md",
+ );
+ expect(r.stderr).not.toContain("\n at ");
+ expect(r.stderr).not.toContain("skill-page-drafts.ts");
});
test("page-draft without a payload is a usage error", async () => {
@@ -144,3 +176,51 @@ test("the MCP tool plans, drafts, and accepts into the configured skills root",
expect(accepted.skillPath).toBe(skillFile);
expect(readFileSync(skillFile, "utf8")).toContain(`name: ${DRAFT.name}`);
});
+
+describe("page-draft think-block strip (t_dac8bf7e)", () => {
+ test("a <think>-prefixed payload succeeds, names the strip, and stages the same draft", async () => {
+ const r = await run([
+ "page-draft",
+ PAGE,
+ "--payload",
+ `<think>shaping the draft</think>${JSON.stringify(DRAFT)}`,
+ "--json",
+ ]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as { outcome: string; slug: string; note?: string };
+ expect(payload.outcome).toBe("created");
+ expect(payload.note).toContain("<think>");
+ // Staged inside the vault only - the SKILL.md is still not materialized.
+ expect(existsSync(join(skillsRoot, DRAFT.name, "SKILL.md"))).toBe(false);
+ });
+
+ test("text mode names the strip too - never a silent strip", async () => {
+ const r = await run([
+ "page-draft",
+ PAGE,
+ "--payload",
+ `<think>shaping the draft</think>${JSON.stringify(DRAFT)}`,
+ ]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("<think>");
+ });
+
+ test("garbage still refuses with the plain message", async () => {
+ const r = await run(["page-draft", PAGE, "--payload", "not json", "--json"]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("brain skill-proposals page-draft: payload must be valid JSON");
+ });
+
+ test("a payload that still does not parse after the strip names the attempt", async () => {
+ const r = await run(["page-draft", PAGE, "--payload", "<think>r</think>not json", "--json"]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain("<think>");
+ });
+
+ test("a clean payload's --json output carries no note key", async () => {
+ const r = await run(["page-draft", PAGE, "--payload", JSON.stringify(DRAFT), "--json"]);
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;
+ expect("note" in payload).toBe(false);
+ });
+});
diff --git a/tests/cli/brain-telegram-capture.test.ts b/tests/cli/brain-telegram-capture.test.ts
index 461c59a0..4aceffb3 100644
--- a/tests/cli/brain-telegram-capture.test.ts
+++ b/tests/cli/brain-telegram-capture.test.ts
@@ -43,6 +43,26 @@ test("run without a configured token exits with a typed error", async () => {
expect(res.stderr.toLowerCase()).toContain("token");
});
+const ABSENT_TG_TOKEN_REF = "$secret:absent_tg_token";
+
+test("a $secret: token reference resolves through the vault's custody store", async () => {
+ // The name is absent from the vault's store and the environment, so the
+ // resolver refuses BY NAME before any transport is built - the raw
+ // reference never reaches the Telegram API as a token (and this test
+ // never touches the network).
+ writeFileSync(
+ config,
+ `vault: "${vault}"\ntelegram_bot_token: "${ABSENT_TG_TOKEN_REF}"\n`,
+ "utf8",
+ );
+ const res = await runCli(["brain", "telegram-capture", "run"], {
+ env: env({ TELEGRAM_BOT_TOKEN: "" }),
+ });
+ expect(res.returncode).not.toBe(0);
+ expect(res.stderr).toContain("absent_tg_token");
+ expect(res.stderr).not.toContain("$secret:");
+});
+
test("catchup renders staged captures without needing a token or network", async () => {
writeCaptureNote(vault, {
body: "first captured idea",
diff --git a/tests/cli/brain-upgrade.test.ts b/tests/cli/brain-upgrade.test.ts
index 82624294..21e81c4a 100644
--- a/tests/cli/brain-upgrade.test.ts
+++ b/tests/cli/brain-upgrade.test.ts
@@ -89,6 +89,12 @@ describe("brain upgrade", () => {
expect(r.returncode).toBe(0);
expect(r.stdout).toMatch(/run_id: upgrade-/);
expect(r.stdout).toContain("Brain/_BRAIN.md");
+ // The snapshot line names the artifact vault-relative: the absolute
+ // location is machine-derived (state the vault never supplied), and
+ // the run id printed directly above already pins the file name.
+ const runId = /run_id: (upgrade-\S+)/.exec(r.stdout)![1]!;
+ expect(r.stdout).toContain(`snapshot: Brain/.snapshots/${runId}.tar.zst`);
+ expect(r.stdout).not.toContain(tmp);
// Post-apply: the file is now the canonical template body, not
// the stale copy.
const body = readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8");
@@ -167,6 +173,22 @@ describe("brain upgrade", () => {
);
});
+ test("--json --dry-run carries the plan digest (t_18fda844)", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");
+ const first = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(first.returncode).toBe(0);
+ const payload = JSON.parse(first.stdout) as { digest: string };
+ expect(payload.digest).toMatch(/^[0-9a-f]{64}$/);
+ // The seal binds the plan, not the moment it was rendered.
+ const second = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run", "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect((JSON.parse(second.stdout) as { digest: string }).digest).toBe(payload.digest);
+ });
+
test("a missing _BRAIN.md renders as an update from absent (text and JSON)", async () => {
await bootstrap();
rmSync(join(vault, "Brain", "_BRAIN.md"), { force: true });
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index 6fcaf90f..6c1cc316 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -452,6 +452,68 @@ describe("secrets", () => {
available: false,
});
});
+
+ test("list reports a reference-shaped value the grammar cannot spell as invalid", async () => {
+ // S5/S6 dashed-name asymmetry: the store accepts `tg-token` but the
+ // reference grammar cannot spell a dash, so the reference can never
+ // resolve (it throws `invalid secret reference` at use time). The
+ // inspection surface must show that instead of silently dropping the
+ // row while `secrets status` answers from the store metadata.
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, 'probe_dash: "$secret:tg-token"\n');
+ const vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+
+ const withVault = await runCli(
+ ["secrets", "list", "--config", config, "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(withVault.returncode).toBe(0);
+ expect(JSON.parse(withVault.stdout).secrets).toEqual([
+ { config_key: "probe_dash", name: "tg-token", available: false, invalid: true },
+ ]);
+ const withVaultText = await runCli(["secrets", "list", "--config", config, "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(withVaultText.stdout).toContain("probe_dash: tg-token (invalid reference)");
+
+ // The env-only surface answers for the same value: a reference that
+ // can never resolve is not "absent", it is broken.
+ const envOnly = await runCli(["secrets", "list", "--config", config, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(envOnly.returncode).toBe(0);
+ expect(JSON.parse(envOnly.stdout).secrets).toEqual([
+ { config_key: "probe_dash", name: "tg-token", available: false, invalid: true },
+ ]);
+ });
+
+ test("well-formed reference rows carry no invalid key (additive-only shape)", async () => {
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, `github_token: ${JSON.stringify(GITHUB_REF)}\n`);
+ const r = await runCli(["secrets", "list", "--config", config, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ const row = (JSON.parse(r.stdout).secrets as Array<Record<string, unknown>>)[0]!;
+ expect("invalid" in row).toBe(false);
+ });
+
+ test("--help prints the usage line, not the generic URL stub", async () => {
+ const r = await runCli(["secrets", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("usage: o2b secrets list|status");
+ expect(r.stdout).not.toContain("see https://");
+ });
+
+ test("help states the env fallback's verbatim, case-sensitive name read", async () => {
+ const r = await runCli(["secrets", "--help"]);
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain(
+ "Without --vault, the env fallback reads the reference name verbatim",
+ );
+ expect(r.stdout).toContain("case-sensitively");
+ });
});
describe("mcp subcommand", () => {
diff --git a/tests/core/architecture/egress-census.test.ts b/tests/core/architecture/egress-census.test.ts
index acaa0d2f..cb9ead14 100644
--- a/tests/core/architecture/egress-census.test.ts
+++ b/tests/core/architecture/egress-census.test.ts
@@ -441,6 +441,26 @@ describe("egress site census", () => {
});
});
+describe("the credential-bundle export site (t_592d9e91)", () => {
+ const BUNDLE_SITE: EgressSite = EGRESS_SITES["brain-secret-bundle-export"];
+
+ test("is declared over the verb that names the destination", () => {
+ expect(BUNDLE_SITE.id).toBe("brain-secret-bundle-export");
+ expect(BUNDLE_SITE.module).toBe("src/cli/brain/verbs/secret.ts");
+ expect(BUNDLE_SITE.verb).toBe("o2b brain secret export");
+ // The payload is ciphertext by construction, so the declaration is
+ // the honest middle: the shared guard runs over the envelope's
+ // NON-ciphertext metadata tree, never over the wrapped values.
+ expect(BUNDLE_SITE.redaction).toBe(EGRESS_REDACTION.sharedRedactor);
+ });
+
+ test("the verb declares the --out destination and the guard call stands beside it", () => {
+ const text = moduleText(BUNDLE_SITE.module);
+ expect(DESTINATION_FLAG_RE.test(text)).toBe(true);
+ expect(EGRESS_GUARD_CALL_RE.test(text)).toBe(true);
+ });
+});
+
describe("the census cannot pass by finding nothing", () => {
/**
* Run the REAL census over the real tree plus one synthetic module, and
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index 9eb85d62..293142a7 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -793,6 +793,17 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
"`chmodSync` re-applies that 0600 on load to a store that arrived with a copied " +
"or restored vault, the same custody repair the keyfile beside it gets.",
},
+ "src/core/brain/secrets/envelope.ts": {
+ categories: [C.machineArtifact],
+ calls: ["chmodSync", "renameSync", "unlinkSync", "writeFileSync"],
+ reason:
+ "replaces the raw keyfile with the passphrase-wrapped envelope via " +
+ "tmp-plus-rename at mode 0600, the custody-boundary twin of the store " +
+ "row beside it: a torn wrap would destroy the only copy of the key, so " +
+ "the swap is atomic and the shared writer's 0644 default is wrong here. " +
+ "The unlink clears the tmp when the rename is refused; `chmodSync` " +
+ "re-asserts the 0600 on the envelope the keyfile it replaced carried.",
+ },
"src/core/brain/truth/store.ts": {
categories: [C.appendOnlyLedger, C.machineArtifact, C.retentionDelete],
calls: ["appendFileSync", "rmSync", "writeFileSync"],
@@ -1235,8 +1246,12 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);
* temp storage and removes the tree when the run ends.
* 76 -> 77: `src/core/search/freshen.ts` claims and releases the
* freshen-on-read claim (an exclusive create) in `.open-second-brain/`.
+ *
+ * 77 -> 78: `src/core/brain/secrets/envelope.ts` replaces the raw keyfile
+ * with the passphrase-wrapped envelope (tmp-plus-rename at 0600), the
+ * custody-boundary twin of the store and keyfile rows beside it.
*/
-const DIRECT_WRITE_ROWS = 77;
+const DIRECT_WRITE_ROWS = 78;
/**
* Measured modules reaching a write through a shared helper. An equality.
@@ -1305,8 +1320,12 @@ const DIRECT_WRITE_ROWS = 77;
*
* 110 -> 111: `src/core/brain/lifecycle/correction.ts` retires the corrected
* record through `writeFrontmatterAtomic`.
+ *
+ * 111 -> 112: `src/cli/brain/verbs/secret.ts` writes the exported
+ * credential bundle to the operator-named `--out` through
+ * `atomicWriteFileSync` (an egress destination, not a vault note).
*/
-const SHARED_HELPER_ROWS = 111;
+const SHARED_HELPER_ROWS = 112;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1378,8 +1397,9 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(
* 73 -> 74: the automatic-upgrade lock and marker removal (state, not notes).
* 74 -> 75: the doctor self-test's throwaway-store writes (temp storage).
* 75 -> 76: the freshen-on-read claim and its release (state, not notes).
+ * 76 -> 77: the secrets keyfile envelope swap (custody bytes, not notes).
*/
-const UNSTAMPED_DIRECT_ROWS = 76;
+const UNSTAMPED_DIRECT_ROWS = 77;
/**
* Shared-helper write sites the stamp does not reach, measured the same
@@ -1395,9 +1415,11 @@ const UNSTAMPED_DIRECT_ROWS = 76;
* the session focus writes through the shared atomic text writer. 106 -> 107:
* the freshen-on-read state file writes through the shared atomic writer.
* 107 -> 108: the correction sweep retires its target's frontmatter through
- * the shared atomic frontmatter writer.
+ * the shared atomic frontmatter writer. 108 -> 109: the credential-bundle
+ * export writes the operator-named `--out` through the shared atomic writer
+ * (an egress destination, and no origin stamp on exports).
*/
-const UNSTAMPED_SHARED_ROWS = 108;
+const UNSTAMPED_SHARED_ROWS = 109;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain.preference.test.ts b/tests/core/brain.preference.test.ts
index 4f377451..3f9ccf48 100644
--- a/tests/core/brain.preference.test.ts
+++ b/tests/core/brain.preference.test.ts
@@ -12,6 +12,7 @@ import {
type WritePreferenceInput,
} from "../../src/core/brain/preference.ts";
import { brainDirs, preferencePath, retiredPath } from "../../src/core/brain/paths.ts";
+import { TagSyntaxError } from "../../src/core/brain/tag-syntax.ts";
let tmp: string;
@@ -496,3 +497,54 @@ describe("moveToRetired carries _-prefixed shape forward (§24)", () => {
expect(raw).toMatch(/^_status: retired$/m);
});
});
+
+// ── t_11ee559f: composed tags obey the one shared tag rule ───────────────────
+
+describe("writePreference — tag syntax (t_11ee559f)", () => {
+ test("a spaced topic yields the slugified tag; the topic field stays as typed", () => {
+ const res = writePreference(tmp, basePrefInput({ topic: "foo bar", slug: "spaced-topic" }));
+ const parsed = parsePreference(res.path);
+ expect(parsed.topic).toBe("foo bar");
+ expect(parsed.tags).toContain("brain/topic/foo-bar");
+ const raw = readFileSync(res.path, "utf8");
+ expect(raw).toContain("brain/topic/foo-bar");
+ expect(raw).not.toContain("brain/topic/foo bar");
+ });
+
+ test("a topic that even slugified fails the rule refuses, naming the field", () => {
+ let thrown: unknown;
+ try {
+ writePreference(tmp, basePrefInput({ topic: "2024 retrospective", slug: "numeric-topic" }));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).field).toBe("topic");
+ });
+
+ test("a bad extraTags entry refuses, naming the field, and writes no file", () => {
+ let thrown: unknown;
+ try {
+ writePreference(tmp, basePrefInput({ extraTags: ["not a tag"] }));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).field).toBe("extraTags");
+ expect(existsSync(preferencePath(tmp, "no-internal-abbrev"))).toBe(false);
+ });
+
+ test("a scope segment is rejected unrewritten, naming the field", () => {
+ expect(() => writePreference(tmp, basePrefInput({ scope: "two words" }))).toThrow(
+ TagSyntaxError,
+ );
+ });
+
+ test("clean inputs keep the incumbent tags line byte-for-byte", () => {
+ const res = writePreference(tmp, basePrefInput());
+ const raw = readFileSync(res.path, "utf8");
+ expect(raw).toContain(
+ "tags: [brain, brain/preference, brain/topic/no-internal-abbrev, brain/scope/writing]",
+ );
+ });
+});
diff --git a/tests/core/brain.session-summary.test.ts b/tests/core/brain.session-summary.test.ts
index fe2460f2..f3b45cbe 100644
--- a/tests/core/brain.session-summary.test.ts
+++ b/tests/core/brain.session-summary.test.ts
@@ -6,9 +6,12 @@ import { join } from "node:path";
import {
appendSessionSummary,
+ DIVERGENCE_RECORD_SAMPLE_LIMIT,
getSessionSummary,
+ getSessionSummaryReport,
listSessionSummaries,
SessionSummaryError,
+ type SessionSummaryRecordRef,
} from "../../src/core/brain/session-summary.ts";
import {
resolveSessionScope,
@@ -121,6 +124,97 @@ describe("byte-identical when unused", () => {
});
});
+describe("divergence-aware read (t_59d4c919)", () => {
+ test("two content-differing digests for one session report count 2, divergent, and the sorted-latest", () => {
+ const older = appendSessionSummary(vault, {
+ sessionId: "sess-div",
+ decisions: ["older decision"],
+ createdAt: "2026-06-14T09:00:00.000Z",
+ });
+ const newer = appendSessionSummary(vault, {
+ sessionId: "sess-div",
+ decisions: ["newer decision"],
+ createdAt: "2026-06-14T11:00:00.000Z",
+ });
+
+ const report = getSessionSummaryReport(vault, "sess-div");
+ expect(report).not.toBeNull();
+ // The read still answers with the sorted-latest digest.
+ expect(report!.digest.id).toBe(newer.id);
+ expect(report!.digest.decisions).toEqual(["newer decision"]);
+ expect(report!.digestCount).toBe(2);
+ expect(report!.divergent).toBe(true);
+ const records = report!.records ?? [];
+ expect(records.map((r) => r.id)).toEqual([older.id, newer.id]);
+ for (const record of records as ReadonlyArray<SessionSummaryRecordRef>) {
+ expect(typeof record.createdAt).toBe("string");
+ expect(record.contentHash.length).toBeGreaterThan(0);
+ }
+ // Divergence is computed over content-differing records.
+ expect(new Set(records.map((r) => r.contentHash)).size).toBe(2);
+ });
+
+ test("a single digest reports count 1 and carries no divergent key", () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-one",
+ decisions: ["the only decision"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const report = getSessionSummaryReport(vault, "sess-one");
+ expect(report).not.toBeNull();
+ expect(report!.digestCount).toBe(1);
+ expect("divergent" in report!).toBe(false);
+ expect("records" in report!).toBe(false);
+ // Additive only: the report's own key set is pinned.
+ expect(Object.keys(report!).toSorted()).toEqual(["digest", "digestCount"]);
+ });
+
+ test("a duplicate-content re-append still dedupes to count 1 (no divergence)", () => {
+ const input = {
+ sessionId: "sess-dup-report",
+ decisions: ["one decision"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ } as const;
+ appendSessionSummary(vault, input);
+ appendSessionSummary(vault, input);
+ const report = getSessionSummaryReport(vault, "sess-dup-report");
+ expect(report!.digestCount).toBe(1);
+ expect("divergent" in report!).toBe(false);
+ });
+
+ test("an unknown session still reads as null", () => {
+ expect(getSessionSummaryReport(vault, "never")).toBeNull();
+ });
+
+ test("getSessionSummary stays a thin wrapper over the report's digest", () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-wrap",
+ decisions: ["wrapped"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const report = getSessionSummaryReport(vault, "sess-wrap");
+ expect(getSessionSummary(vault, "sess-wrap")!.id).toBe(report!.digest.id);
+ });
+
+ test("the divergence record list is bounded to the newest entries", () => {
+ const total = DIVERGENCE_RECORD_SAMPLE_LIMIT + 2;
+ let last: { id: string } | null = null;
+ for (let i = 0; i < total; i++) {
+ last = appendSessionSummary(vault, {
+ sessionId: "sess-bound",
+ decisions: [`decision-${i}`],
+ createdAt: `2026-06-14T00:${String(i).padStart(2, "0")}:00.000Z`,
+ });
+ }
+ const report = getSessionSummaryReport(vault, "sess-bound");
+ expect(report!.digestCount).toBe(total);
+ const records = report!.records ?? [];
+ expect(records.length).toBe(DIVERGENCE_RECORD_SAMPLE_LIMIT);
+ // The newest records are the ones kept, oldest first within the sample.
+ expect(records[records.length - 1]!.id).toBe(last!.id);
+ });
+});
+
describe("project scope (Task 18)", () => {
test("carries the project, normalized by the shared session-scope slug rule", () => {
const digest = appendSessionSummary(vault, {
diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.ts
index 9d50d731..781a3e48 100644
--- a/tests/core/brain.signal.test.ts
+++ b/tests/core/brain.signal.test.ts
@@ -9,6 +9,7 @@ import {
writeSignal,
type WriteSignalInput,
} from "../../src/core/brain/signal.ts";
+import { TagSyntaxError } from "../../src/core/brain/tag-syntax.ts";
let tmp: string;
@@ -295,25 +296,45 @@ describe("writeSignal — a lost race retries instead of dropping the event (#16
});
describe("writeSignal — sanitisation (§7)", () => {
- test("redacts secrets in principle / scope / raw", () => {
+ test("redacts secrets in principle / raw", () => {
const r = writeSignal(
tmp,
baseInput({
slug: "sec",
principle: "do not put api_key=hunter2 anywhere",
- scope: "writing token: abcd",
raw: 'config = {"client_secret": "shhh"}',
}),
);
const round = parseSignal(r.path);
expect(round.principle).toContain("***REDACTED***");
expect(round.principle).not.toContain("hunter2");
- expect(round.scope).toContain("***REDACTED***");
- expect(round.scope).not.toContain("abcd");
expect(round.raw).toContain("***REDACTED***");
expect(round.raw).not.toContain("shhh");
});
+ test("a secret-bearing scope refuses at the tag gate, carrying the REDACTED value", () => {
+ // t_11ee559f: a scope segment is refused unrewritten when it fails the
+ // tag rule, so a spaced scope can no longer land a broken tag - even
+ // one whose spaces surround a redacted credential. Sanitisation runs
+ // first, so the refusal token carries the redacted value and the raw
+ // secret reaches neither disk nor the error.
+ let thrown: unknown;
+ try {
+ writeSignal(
+ tmp,
+ baseInput({
+ slug: "sec-scope",
+ scope: "writing token: abcd",
+ }),
+ );
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).token).not.toContain("abcd");
+ expect(existsSync(join(tmp, "Brain", "inbox", "sig-2026-05-14-sec-scope.md"))).toBe(false);
+ });
+
test("strips C0 controls and folds U+2028/U+2029 in principle", () => {
// U+2028 = line separator. C0 byte 0x07 (BEL) should be stripped.
const r = writeSignal(
@@ -418,3 +439,54 @@ describe("writeSignal — capture-extension fields (§9/§16)", () => {
).toThrow(/source_type/);
});
});
+
+// ── t_11ee559f: composed tags obey the one shared tag rule ───────────────────
+
+describe("writeSignal — tag syntax (t_11ee559f)", () => {
+ test("a spaced topic yields the slugified tag; the topic field stays as typed", () => {
+ const r = writeSignal(tmp, baseInput({ topic: "foo bar", slug: "spaced-topic" }));
+ const parsed = parseSignal(r.path);
+ expect(parsed.topic).toBe("foo bar");
+ expect(parsed.tags).toContain("brain/topic/foo-bar");
+ const raw = readFileSync(r.path, "utf8");
+ expect(raw).toContain("brain/topic/foo-bar");
+ expect(raw).not.toContain("brain/topic/foo bar");
+ });
+
+ test("a topic that even slugified fails the rule refuses, naming the field", () => {
+ let thrown: unknown;
+ try {
+ writeSignal(tmp, baseInput({ topic: "2024 retrospective", slug: "numeric-topic" }));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).field).toBe("topic");
+ });
+
+ test("a bad extraTags entry refuses, naming the field, and writes no file", () => {
+ let thrown: unknown;
+ try {
+ writeSignal(tmp, baseInput({ extraTags: ["not a tag"] }));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).field).toBe("extraTags");
+ expect(existsSync(join(tmp, "Brain", "inbox", "sig-2026-05-14-no-internal-abbrev.md"))).toBe(
+ false,
+ );
+ });
+
+ test("a scope segment is rejected unrewritten, naming the field", () => {
+ expect(() => writeSignal(tmp, baseInput({ scope: "two words" }))).toThrow(TagSyntaxError);
+ });
+
+ test("clean inputs keep the incumbent tags line byte-for-byte", () => {
+ const r = writeSignal(tmp, baseInput());
+ const raw = readFileSync(r.path, "utf8");
+ expect(raw).toContain(
+ "tags: [brain, brain/signal, brain/topic/no-internal-abbrev, brain/scope/writing]",
+ );
+ });
+});
diff --git a/tests/core/brain/capture/capture-note.test.ts b/tests/core/brain/capture/capture-note.test.ts
index c156a43c..430f2bbe 100644
--- a/tests/core/brain/capture/capture-note.test.ts
+++ b/tests/core/brain/capture/capture-note.test.ts
@@ -7,8 +7,17 @@
* archive path helpers, and the read/write/list/archive functions.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
-import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -245,3 +254,105 @@ test("empty guidance is refused by name rather than stored as an empty section",
writeCaptureNote(vault, { body: "text", provenance: prov(), guidance: " " }),
).toThrow(CaptureContractError);
});
+
+// ── t_151a564c: the stamped kind obeys a declared page_types vocabulary ──────
+
+describe("writeCaptureNote — declared page_types vocabulary (t_151a564c)", () => {
+ function writeConfig(pageTypes: string[] | null): void {
+ if (pageTypes === null) return;
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ `schema:\n page_types: [${pageTypes.join(", ")}]\n`,
+ "utf8",
+ );
+ }
+
+ test("a pack declaring page_types without brain-capture refuses before any file exists and before a name is consumed", () => {
+ writeConfig(["note"]);
+ let thrown: unknown;
+ try {
+ writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(CaptureContractError);
+ // The refusal precedes every filesystem effect: the captures directory
+ // is never created, so no file landed and no allocator name was consumed.
+ expect(existsSync(capturesDir(vault))).toBe(false);
+ });
+
+ test("the refusal leaves an existing staging area untouched", () => {
+ writeCaptureNote(vault, { body: "earlier capture", provenance: prov() });
+ writeConfig(["note"]);
+ expect(() => writeCaptureNote(vault, { body: "a second capture", provenance: prov() })).toThrow(
+ CaptureContractError,
+ );
+ const staged = listStagedCaptures(vault);
+ expect(staged).toHaveLength(1);
+ expect(staged[0]!.body).toBe("earlier capture");
+ });
+
+ test("the refusal names the kind, the declared set, and the remedy", () => {
+ writeConfig(["note"]);
+ let thrown: unknown;
+ try {
+ writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ } catch (err) {
+ thrown = err;
+ }
+ const message = (thrown as CaptureContractError).message;
+ expect(message).toContain("brain-capture");
+ expect(message).toContain("note");
+ expect(message).toContain("_brain.yaml");
+ });
+
+ test("a declared set containing brain-capture passes", () => {
+ writeConfig(["note", "brain-capture"]);
+ const note = writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ expect(listStagedCaptures(vault)).toHaveLength(1);
+ expect(readCaptureNote(vault, note.id)!.body).toBe("capture a thought");
+ });
+
+ test("absent config fails open with byte-identical output", () => {
+ writeConfig(null);
+ const open = writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ const declaredVault = mkdtempSync(join(tmpdir(), "osb-capture-note-declared-"));
+ try {
+ mkdirSync(join(declaredVault, "Brain"), { recursive: true });
+ writeFileSync(
+ join(declaredVault, "Brain", "_brain.yaml"),
+ "schema:\n page_types: [note, brain-capture]\n",
+ "utf8",
+ );
+ const gated = writeCaptureNote(declaredVault, {
+ body: "capture a thought",
+ provenance: prov(),
+ });
+ expect(readFileSync(join(vault, open.path), "utf8")).toBe(
+ readFileSync(join(declaredVault, gated.path), "utf8"),
+ );
+ } finally {
+ rmSync(declaredVault, { recursive: true, force: true });
+ }
+ });
+
+ test("a config without a page_types declaration fails open", () => {
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ const note = writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ expect(readCaptureNote(vault, note.id)!.provenance.source).toBe("telegram");
+ });
+
+ test("the kind stays the frontmatter key and a refused-then-fixed capture reads back", () => {
+ writeConfig(["note"]);
+ expect(() =>
+ writeCaptureNote(vault, { body: "capture a thought", provenance: prov() }),
+ ).toThrow(CaptureContractError);
+ // The operator declares the kind; the same capture now lands and the
+ // contract's reader still round-trips it through the `kind` key.
+ writeConfig(["note", "brain-capture"]);
+ const note = writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });
+ const read = readCaptureNote(vault, note.id)!;
+ expect(read.body).toBe("capture a thought");
+ expect(read.provenance.capturedAt).toBe("2026-07-19T12:00:00Z");
+ });
+});
diff --git a/tests/core/brain/capture/inbox-drain.test.ts b/tests/core/brain/capture/inbox-drain.test.ts
index 5b210b13..ee428620 100644
--- a/tests/core/brain/capture/inbox-drain.test.ts
+++ b/tests/core/brain/capture/inbox-drain.test.ts
@@ -8,7 +8,7 @@
* default and writes nothing; a rerun after apply is a no-op.
*/
-import { afterEach, beforeEach, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
existsSync,
mkdirSync,
@@ -22,6 +22,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import {
+ CAPTURED_IDEA_KIND,
CAPTURE_OBLIGATION_MARKER,
CAPTURED_NOTES_DIR_REL,
drainInbox,
@@ -173,3 +174,79 @@ test("an obligation marker defaults the cadence when none is given", () => {
expect(report.items[0]!.action).toBe("open-obligation");
expect(listObligations(vault, { now: NOW }).map((o) => o.title)).toContain("tidy the desk");
});
+
+// ── t_151a564c: the drained idea's stamped kind obeys a declared vocabulary ──
+
+describe("writeIdeaNote — declared page_types vocabulary (t_151a564c)", () => {
+ function writeConfig(pageTypes: string[] | null): void {
+ if (pageTypes === null) return;
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ `schema:\n page_types: [${pageTypes.join(", ")}]\n`,
+ "utf8",
+ );
+ }
+
+ function seedIdea(): void {
+ writeCaptureNote(vault, { body: "a standalone atomic idea", provenance: prov(1) });
+ }
+
+ test("a pack declaring page_types without captured-idea refuses the route and leaves the capture staged", () => {
+ seedIdea();
+ writeConfig(["note"]);
+ const report = drainInbox(vault, { apply: true, agent: "tester", now: NOW });
+ expect(report.routed).toBe(0);
+ expect(report.items).toHaveLength(1);
+ const item = report.items[0]!;
+ expect(item.classification).toBe("unroutable");
+ expect(item.reason).toContain("captured-idea");
+ expect(item.reason).toContain("_brain.yaml");
+ // No idea note landed and the capture is still staged for a rerun
+ // after the operator declares the kind.
+ expect(existsSync(join(vault, CAPTURED_NOTES_DIR_REL))).toBe(false);
+ expect(listStagedCaptures(vault)).toHaveLength(1);
+ });
+
+ test("the dry-run plan reports the same declared-vocabulary refusal apply will", () => {
+ // The refusal is deterministic from config, so the preview must show it:
+ // a dry run that calls the idea route routable while apply refuses it
+ // per item is a report the operator cannot act on.
+ seedIdea();
+ writeConfig(["note"]);
+ const report = drainInbox(vault, { apply: false, agent: "tester", now: NOW });
+ expect(report.mode).toBe("dry-run");
+ expect(report.routed).toBe(0);
+ expect(report.unroutable).toBe(1);
+ const item = report.items[0]!;
+ expect(item.classification).toBe("unroutable");
+ expect(item.action).toBe("skip");
+ expect(item.routed).toBe(false);
+ expect(item.reason).toContain("captured-idea");
+ expect(item.reason).toContain("_brain.yaml");
+ // Nothing written, capture still staged.
+ expect(existsSync(join(vault, CAPTURED_NOTES_DIR_REL))).toBe(false);
+ expect(listStagedCaptures(vault)).toHaveLength(1);
+ });
+
+ test("a declared set containing captured-idea routes as before", () => {
+ seedIdea();
+ writeConfig(["note", "captured-idea"]);
+ const report = drainInbox(vault, { apply: true, agent: "tester", now: NOW });
+ expect(report.routed).toBe(1);
+ expect(report.items[0]!.classification).toBe("idea");
+ expect(existsSync(join(vault, CAPTURED_NOTES_DIR_REL))).toBe(true);
+ expect(listStagedCaptures(vault)).toHaveLength(0);
+ });
+
+ test("absent config fails open and the idea note is byte-shaped as today", () => {
+ seedIdea();
+ const report = drainInbox(vault, { apply: true, agent: "tester", now: NOW });
+ expect(report.routed).toBe(1);
+ const dir = join(vault, CAPTURED_NOTES_DIR_REL);
+ const files = readdirSync(dir);
+ expect(files).toHaveLength(1);
+ const raw = readFileSync(join(dir, files[0]!), "utf8");
+ expect(raw).toContain(`kind: ${CAPTURED_IDEA_KIND}`);
+ expect(raw).toContain("a standalone atomic idea");
+ });
+});
diff --git a/tests/core/brain/capture/telegram-capture.test.ts b/tests/core/brain/capture/telegram-capture.test.ts
index dd45d757..417d86f3 100644
--- a/tests/core/brain/capture/telegram-capture.test.ts
+++ b/tests/core/brain/capture/telegram-capture.test.ts
@@ -9,7 +9,7 @@
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -23,6 +23,7 @@ import {
type TelegramUpdate,
} from "../../../../src/core/brain/capture/telegram-capture.ts";
import {
+ CaptureContractError,
listStagedCaptures,
readCatchupWatermark,
} from "../../../../src/core/brain/capture/capture-note.ts";
@@ -310,3 +311,22 @@ test("two capture hosts append to their own decision shards (t_774dea61)", () =>
expect(existsSync(join(logDir, "capture-decisions.b.jsonl"))).toBe(true);
expect(existsSync(join(logDir, "capture-decisions.jsonl"))).toBe(false);
});
+
+// ── t_151a564c: the typed vocabulary refusal surfaces through this lane ──────
+
+test("a pack declaring page_types without brain-capture surfaces the contract refusal", () => {
+ // The vault made a declaration that omits the kind this lane stamps, so
+ // the capture contract refuses - and the refusal surfaces here exactly as
+ // every other contract refusal does: the named CaptureContractError, with
+ // no capture written behind it.
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema:\n page_types: [note]\n", "utf8");
+ let thrown: unknown;
+ try {
+ handleCaptureUpdate(vault, textUpdate(1, "100", "an idea worth keeping"), baseOpts());
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(CaptureContractError);
+ expect((thrown as Error).name).toBe("CaptureContractError");
+ expect(listStagedCaptures(vault)).toHaveLength(0);
+});
diff --git a/tests/core/brain/claude-memory-render.test.ts b/tests/core/brain/claude-memory-render.test.ts
index 7e524233..d5eef7d2 100644
--- a/tests/core/brain/claude-memory-render.test.ts
+++ b/tests/core/brain/claude-memory-render.test.ts
@@ -3,6 +3,7 @@ import {
renderPreferenceFromMemory,
slugifyMemoryName,
} from "../../../src/core/brain/claude-memory-render.ts";
+import { TagSyntaxError, isObsidianTagValue } from "../../../src/core/brain/tag-syntax.ts";
describe("renderPreferenceFromMemory", () => {
test("emits frontmatter + body + Origin block, under trial (t_sec_memory_trial)", () => {
@@ -77,3 +78,56 @@ describe("slugifyMemoryName", () => {
expect(slugifyMemoryName("--hello--")).toBe("hello");
});
});
+
+// ── t_11ee559f: the rendered frontmatter tags always parse-shaped ────────────
+
+describe("renderPreferenceFromMemory — tag syntax (t_11ee559f)", () => {
+ const baseRender = (
+ overrides: Partial<Parameters<typeof renderPreferenceFromMemory>[0]> = {},
+ ) => {
+ const input = {
+ name: "no-em-dashes",
+ description: "No em-dashes in Russian writing for this user.",
+ body: "Body text.",
+ memoryPath: "/m.md",
+ importedAt: "2026-05-18T10:00:00Z",
+ unconfirmedUntil: "2026-06-01T10:00:00Z",
+ bodySha256: "a".repeat(64),
+ ...overrides,
+ };
+ return input;
+ };
+
+ test("every frontmatter tags value is parse-shaped for messy names and scopes", () => {
+ const out = renderPreferenceFromMemory(
+ baseRender({
+ name: "Phase-by-phase approval: don't conflate plan/code",
+ body: "First line.\nscope: testing\nrest.",
+ }),
+ );
+ const tagsLine = out.split("\n").find((line) => line.startsWith("tags:"));
+ expect(tagsLine).toBeDefined();
+ const values = tagsLine!
+ .slice("tags: [".length, tagsLine!.lastIndexOf("]"))
+ .split(", ")
+ .map((v) => v.trim());
+ expect(values).toEqual([
+ "brain",
+ "brain/preference",
+ "brain/topic/phase-by-phase-approval-don-t-conflate-plan-code",
+ "brain/scope/testing",
+ ]);
+ for (const value of values) expect(isObsidianTagValue(value)).toBe(true);
+ });
+
+ test("a name that slugifies to a purely numeric topic refuses, naming the field", () => {
+ let thrown: unknown;
+ try {
+ renderPreferenceFromMemory(baseRender({ name: "2024" }));
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ expect((thrown as TagSyntaxError).field).toBe("topic");
+ });
+});
diff --git a/tests/core/brain/hygiene-frontmatter-tags.test.ts b/tests/core/brain/hygiene-frontmatter-tags.test.ts
new file mode 100644
index 00000000..77b6a009
--- /dev/null
+++ b/tests/core/brain/hygiene-frontmatter-tags.test.ts
@@ -0,0 +1,209 @@
+/**
+ * Frontmatter-tags hygiene detector (trust-surface-hardening wave;
+ * kanban t_11ee559f, doctor half).
+ *
+ * The doctor-half companion to the write-time tag validation: existing
+ * vault content cannot be retroactively refused at a composer, so this
+ * detector audits the frontmatter `tags:` field - the one place the
+ * inline-tags detector explicitly scopes OUT - against the ONE shared
+ * tag rule (`src/core/tags.ts`, `isObsidianTagValue`). Findings are
+ * informational, review-actioned, and never auto-fixed. The detector is
+ * opt-in: registered but excluded from `DEFAULT_SCAN_IDS`, exactly like
+ * the inline `tags` detector.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { isObsidianTagValue } from "../../../src/core/tags.ts";
+import { runHygieneScan } from "../../../src/core/brain/hygiene/scan.ts";
+import { hygieneFindingId } from "../../../src/core/brain/hygiene/detectors/id.ts";
+import {
+ MALFORMED_REASON,
+ detectFrontmatterTags,
+} from "../../../src/core/brain/hygiene/detectors/frontmatter-tags.ts";
+import type { HygieneFinding } from "../../../src/core/brain/hygiene/types.ts";
+
+let vault: string;
+
+const NOW = new Date("2026-06-10T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-fm-tags-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeNote(rel: string, frontmatter: string, body = "clean body"): void {
+ const abs = join(vault, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, `---\n${frontmatter}\n---\n\n${body}\n`, "utf8");
+}
+
+function findings(): HygieneFinding[] {
+ return [...detectFrontmatterTags(vault)];
+}
+
+/** Recursive [relative path -> bytes] snapshot, for the read-only pin. */
+function treeSnapshot(dir: string, prefix = ""): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const entry of readdirSync(dir)) {
+ const abs = join(dir, entry);
+ const rel = prefix === "" ? entry : `${prefix}/${entry}`;
+ if (statSync(abs).isDirectory()) {
+ for (const [k, v] of treeSnapshot(abs, rel)) out.set(k, v);
+ } else {
+ out.set(rel, readFileSync(abs, "utf8"));
+ }
+ }
+ return out;
+}
+
+describe("frontmatter-tags detector - malformed values", () => {
+ test("a frontmatter tags entry the shared rule rejects produces a finding naming the value and the rule", () => {
+ writeNote("Brain/notes/a.md", 'tags: [brain, "foo bar"]');
+ const malformed = findings();
+ expect(malformed).toHaveLength(1);
+ const finding = malformed[0]!;
+ expect(finding.detector).toBe("frontmatter-tags");
+ expect(finding.severity).toBe("info");
+ expect(finding.proposed_action).toBe("review");
+ expect(finding.evidence.tag).toBe("foo bar");
+ expect(finding.evidence.field).toBe("tags");
+ // Acceptance C2(a): the finding's evidence names BOTH the offending
+ // value and the rule - a reason that said only "check this" would not
+ // be reviewable without re-deriving why the value is malformed.
+ expect(finding.evidence.reason).toBe(`"foo bar" ${MALFORMED_REASON}`);
+ expect(finding.evidence.reason).toContain("foo bar");
+ expect(finding.evidence.reason).toContain("must start with a letter or underscore");
+ expect(finding.evidence.reason).toContain("never only digits");
+ expect(finding.targets).toEqual(["Brain/notes/a.md", "foo bar"]);
+ expect(finding.title).toContain("foo bar");
+ expect(finding.id).toBe(hygieneFindingId("frontmatter-tags", finding.targets));
+ });
+
+ test("a purely numeric or slash-onset entry is malformed too", () => {
+ writeNote("Brain/notes/a.md", "tags: [2024, /leading, ok-tag]");
+ const values = findings()
+ .map((f) => f.evidence.tag)
+ .toSorted();
+ expect(values).toEqual(["/leading", "2024"]);
+ });
+
+ test("the block-sequence form of the field is audited like the inline form", () => {
+ writeNote("Brain/notes/a.md", "kind: note\ntags:\n - brain\n - bad tag");
+ const malformed = findings();
+ expect(malformed).toHaveLength(1);
+ expect(malformed[0]!.evidence.tag).toBe("bad tag");
+ });
+
+ test("a scalar tags value is audited as the one-element list it parses to", () => {
+ writeNote("Brain/notes/a.md", "tags: also bad");
+ expect(findings().map((f) => f.evidence.tag)).toEqual(["also bad"]);
+ });
+
+ test("the same malformed value across documents is one finding; distinct values stay distinct", () => {
+ writeNote("Brain/notes/a.md", "tags: [shared bad]");
+ writeNote("Brain/notes/b.md", "tags: [shared bad]");
+ writeNote("Brain/notes/c.md", "tags: [other bad]");
+ const malformed = findings();
+ expect(malformed).toHaveLength(2);
+ const grouped = malformed.find((f) => f.evidence.tag === "shared bad");
+ expect(grouped!.targets).toEqual(["Brain/notes/a.md", "Brain/notes/b.md", "shared bad"]);
+ });
+
+ test("empty entries are not values and are not reported", () => {
+ writeNote("Brain/notes/a.md", "tags: [brain, , /bad]");
+ const malformed = findings();
+ expect(malformed).toHaveLength(1);
+ expect(malformed[0]!.evidence.tag).toBe("/bad");
+ });
+
+ test("findings are stable across runs and sorted by value", () => {
+ writeNote("Brain/notes/a.md", "tags: [zz bad, aa bad]");
+ const first = findings();
+ const second = findings();
+ expect(first.map((f) => f.id)).toEqual(second.map((f) => f.id));
+ expect(first.map((f) => f.evidence.tag)).toEqual(["aa bad", "zz bad"]);
+ });
+});
+
+describe("frontmatter-tags detector - parse-shaped tags", () => {
+ test("nested, underscore-onset, and dashed values produce nothing", () => {
+ writeNote("Brain/notes/a.md", "tags: [brain, brain/preference, _under, Foo_1-b/c]");
+ expect(findings()).toHaveLength(0);
+ });
+
+ test("a note without a tags field produces nothing", () => {
+ writeNote("Brain/notes/a.md", "kind: note");
+ expect(findings()).toHaveLength(0);
+ });
+
+ test("body hash-like tokens are out of scope (the inline detector owns prose)", () => {
+ writeNote("Brain/notes/a.md", "kind: note", "body with #2024notes and #ok-tag");
+ expect(findings()).toHaveLength(0);
+ });
+
+ test("an empty vault produces nothing", () => {
+ expect(findings()).toHaveLength(0);
+ });
+});
+
+describe("frontmatter-tags detector - read-only and shared rule", () => {
+ test("the detector never mutates the vault", () => {
+ writeNote("Brain/notes/a.md", "tags: [bad tag, ok]");
+ const before = treeSnapshot(vault);
+ findings();
+ runHygieneScan(vault, { detectors: ["frontmatter-tags"], now: NOW });
+ expect(treeSnapshot(vault)).toEqual(before);
+ });
+
+ test("the detector consumes the ONE shared predicate, never a local copy", () => {
+ const source = readFileSync(
+ join(import.meta.dir, "../../../src/core/brain/hygiene/detectors/frontmatter-tags.ts"),
+ "utf8",
+ );
+ expect(source).toMatch(/from "\.\.\/\.\.\/\.\.\/tags\.ts"/);
+ expect(source).toContain("isObsidianTagValue");
+ // A local redefinition would need a regex construction or the rule's
+ // own onset charset; neither may appear in the detector.
+ expect(source).not.toContain("new RegExp");
+ expect(source).not.toContain("[A-Za-z_]");
+ // Behavioral agreement: every value this suite saw judged malformed
+ // is one the shared predicate rejects, and vice versa.
+ const malformedSeen = ["foo bar", "2024", "/leading"];
+ const parseShapedSeen = ["brain", "brain/preference", "_under"];
+ for (const value of malformedSeen) expect(isObsidianTagValue(value)).toBe(false);
+ for (const value of parseShapedSeen) expect(isObsidianTagValue(value)).toBe(true);
+ });
+});
+
+describe("frontmatter-tags scan integration", () => {
+ test("the default sweep skips the detector (opt-in like tags)", () => {
+ writeNote("Brain/notes/a.md", "tags: [bad tag]");
+ const report = runHygieneScan(vault, { now: NOW });
+ expect(report.detectors_run).not.toContain("frontmatter-tags");
+ expect(report.counts["frontmatter-tags"]).toBeUndefined();
+ expect(report.findings.find((f) => f.detector === "frontmatter-tags")).toBeUndefined();
+ });
+
+ test("an explicit subset runs the detector alone", () => {
+ writeNote("Brain/notes/a.md", "tags: [bad tag]");
+ const report = runHygieneScan(vault, { detectors: ["frontmatter-tags"], now: NOW });
+ expect(report.detectors_run).toEqual(["frontmatter-tags"]);
+ expect(report.counts["frontmatter-tags"]).toBe(1);
+ expect(report.errors).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/hygiene-scan.test.ts b/tests/core/brain/hygiene-scan.test.ts
index 7dac1556..36e282c5 100644
--- a/tests/core/brain/hygiene-scan.test.ts
+++ b/tests/core/brain/hygiene-scan.test.ts
@@ -156,6 +156,21 @@ describe("scan composition", () => {
expect(report.generated_at).toBe(NOW.toISOString());
});
+ test("an explicit subset composes the two opt-in tag detectors (t_11ee559f)", () => {
+ writePref("never-recalled", "2026-01-01T00:00:00Z");
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-fm.md"),
+ "---\nid: pref-fm\ntags: [bad tag]\n---\n\nbody\n",
+ "utf8",
+ );
+ const report = runHygieneScan(vault, { detectors: ["tags", "frontmatter-tags"], now: NOW });
+ expect(report.detectors_run).toEqual(["tags", "frontmatter-tags"]);
+ expect(report.counts["frontmatter-tags"]).toBe(1);
+ expect(report.counts.tags).toBe(0);
+ expect(report.findings.filter((f) => f.detector === "frontmatter-tags")).toHaveLength(1);
+ expect(report.errors).toHaveLength(0);
+ });
+
test("finding ids are deterministic across runs", () => {
writePref("never-recalled", "2026-01-01T00:00:00Z");
const first = runHygieneScan(vault, { detectors: ["usefulness"], now: NOW });
diff --git a/tests/core/brain/hygiene-tags.test.ts b/tests/core/brain/hygiene-tags.test.ts
index 7b4c36ae..cf58d212 100644
--- a/tests/core/brain/hygiene-tags.test.ts
+++ b/tests/core/brain/hygiene-tags.test.ts
@@ -8,8 +8,10 @@
* rule rejects (reported as the diff: the index will never match them);
* inconsistent - the same tag differing by case or hierarchy depth;
* orphan - a tag value on exactly one document. Frontmatter `tags:`
- * arrays are OUT of scope (recorded refusal), and the detector is
- * opt-in: registered but excluded from `DEFAULT_SCAN_IDS`.
+ * arrays are OUT of scope here (recorded refusal) - the trust-surface-
+ * hardening wave gives them their own opt-in `frontmatter-tags`
+ * detector - and this detector is opt-in too: registered but excluded
+ * from `DEFAULT_SCAN_IDS`.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
@@ -234,6 +236,10 @@ describe("tags scan integration", () => {
expect(HYGIENE_DETECTOR_IDS).toContain("tags");
});
+ test("the frontmatter sibling is registered in the closed tuple (t_11ee559f)", () => {
+ expect(HYGIENE_DETECTOR_IDS).toContain("frontmatter-tags");
+ });
+
test("the default sweep excludes tags (opt-in only)", () => {
writeNote("Brain/notes/a.md", "#2024notes malformed");
const report = runHygieneScan(vault, { now: NOW });
@@ -242,6 +248,14 @@ describe("tags scan integration", () => {
expect(report.findings.find((f) => f.detector === "tags")).toBeUndefined();
});
+ test("the default sweep excludes the frontmatter sibling too (t_11ee559f)", () => {
+ writeNote("Brain/notes/fm.md", "body", "tags: [bad tag]");
+ const report = runHygieneScan(vault, { now: NOW });
+ expect(report.detectors_run).not.toContain("frontmatter-tags");
+ expect(report.counts["frontmatter-tags"]).toBeUndefined();
+ expect(report.findings.find((f) => f.detector === "frontmatter-tags")).toBeUndefined();
+ });
+
test("an explicit subset runs tags alone", () => {
writeNote("Brain/notes/a.md", "#2024notes malformed");
const report = runHygieneScan(vault, { detectors: ["tags"], now: NOW });
diff --git a/tests/core/brain/import-claude-memory-orchestrator.test.ts b/tests/core/brain/import-claude-memory-orchestrator.test.ts
index e785b1ed..7a63444d 100644
--- a/tests/core/brain/import-claude-memory-orchestrator.test.ts
+++ b/tests/core/brain/import-claude-memory-orchestrator.test.ts
@@ -1,10 +1,14 @@
import { describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, relative, sep } from "node:path";
-import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";
+import {
+ ApprovalDigestError,
+ importClaudeMemory,
+} from "../../../src/core/brain/import-claude-memory.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { sha256Hex } from "../../../src/core/integrity/digest.ts";
function setupVault(): string {
const v = mkdtempSync(join(tmpdir(), "o2b-cm-orch-"));
@@ -37,59 +41,241 @@ describe("importClaudeMemory", () => {
test("dry-run reports plan, performs no writes", () => {
const vault = setupVault();
const mem = setupMemory();
- const res = importClaudeMemory({
- vault,
- memoryDir: mem,
- mode: "dry-run",
- allowArbitraryMemoryPath: true,
- });
- expect(res.plans.map((p) => p.action).toSorted()).toEqual(["CREATE", "CREATE"]);
- expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlier
- expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(false);
- rmSync(vault, { recursive: true });
- rmSync(mem, { recursive: true });
+ try {
+ const res = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ });
+ expect(res.plans.map((p) => p.action).toSorted()).toEqual(["CREATE", "CREATE"]);
+ expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlier
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(false);
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
});
test("apply writes preferences, manifest, and log event", () => {
const vault = setupVault();
const mem = setupMemory();
- const res = importClaudeMemory({
- vault,
- memoryDir: mem,
- mode: "apply",
- allowArbitraryMemoryPath: true,
- now: new Date("2026-05-18T10:00:00Z"),
- });
- expect(res.applied.length).toBe(2);
- expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(true);
- expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-b.md"))).toBe(true);
- const manifest = JSON.parse(
- readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"),
- );
- expect(Object.keys(manifest.imports).toSorted()).toEqual(["feedback_a.md", "feedback_b.md"]);
- const log = readFileSync(join(vault, "Brain", "log", res.localDate + ".md"), "utf8");
- expect(log).toContain("import-claude-memory");
- expect(log).toContain("created: 2");
- rmSync(vault, { recursive: true });
- rmSync(mem, { recursive: true });
+ try {
+ const res = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ expect(res.applied.length).toBe(2);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-b.md"))).toBe(true);
+ const manifest = JSON.parse(
+ readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"),
+ );
+ expect(Object.keys(manifest.imports).toSorted()).toEqual(["feedback_a.md", "feedback_b.md"]);
+ const log = readFileSync(join(vault, "Brain", "log", res.localDate + ".md"), "utf8");
+ expect(log).toContain("import-claude-memory");
+ expect(log).toContain("created: 2");
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
});
test("second apply with no change → SKIP_UNCHANGED, zero writes", () => {
const vault = setupVault();
const mem = setupMemory();
- importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });
- const before = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");
- const res2 = importClaudeMemory({
- vault,
- memoryDir: mem,
- mode: "apply",
- allowArbitraryMemoryPath: true,
- });
- expect(res2.applied.length).toBe(0);
- expect(res2.skippedUnchanged.length).toBe(2);
- const after = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");
- expect(after).toBe(before);
- rmSync(vault, { recursive: true });
- rmSync(mem, { recursive: true });
+ try {
+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });
+ const before = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");
+ const res2 = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ });
+ expect(res2.applied.length).toBe(0);
+ expect(res2.skippedUnchanged.length).toBe(2);
+ const after = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");
+ expect(after).toBe(before);
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
+ });
+});
+
+/**
+ * Forward-slash relative paths hashed, so the comparison is stable on
+ * every host. Empty prefixes match everything.
+ */
+function treeDigests(root: string, prefixes: ReadonlyArray<string> = [""]): string {
+ const rows: string[] = [];
+ const visit = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
+ a.name < b.name ? -1 : 1,
+ )) {
+ const abs = join(dir, entry.name);
+ const rel = relative(root, abs).split(sep).join("/");
+ if (entry.isDirectory()) visit(abs);
+ else if (prefixes.some((p) => rel === p || rel.startsWith(`${p}/`)))
+ rows.push(`${rel} ${sha256Hex(readFileSync(abs))}`);
+ }
+ };
+ if (existsSync(root)) visit(root);
+ return rows.join("\n");
+}
+
+describe("importClaudeMemory approval digest (t_18fda844)", () => {
+ // What the operator approves and the apply lands: the preference
+ // files and the imports manifest. (The `.snapshots` archives are
+ // excluded: they encode the vault's absolute path and the host's
+ // file metadata, so their bytes differ across directories even when
+ // the run is behaviorally identical - snapshot EXISTENCE is asserted
+ // instead.)
+ const WRITES = ["Brain/preferences", "Brain/.imports"] as const;
+
+ test("dry-run carries a plan digest that excludes wall-clock fields", () => {
+ const vault = setupVault();
+ const mem = setupMemory();
+ try {
+ const morning = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ const later = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ now: new Date("2027-01-01T23:59:59Z"),
+ });
+ expect(morning.digest).toMatch(/^[0-9a-f]{64}$/);
+ // The same content planned on another day seals to the same digest:
+ // an approval must bind the plan, never the moment it was printed.
+ expect(later.digest).toBe(morning.digest);
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
+ });
+
+ test("apply with the approval digest lands exactly the approved plan", () => {
+ const vault = setupVault();
+ const mem = setupMemory();
+ try {
+ const dry = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ });
+ const res = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ approvalDigest: dry.digest,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ const approved = dry.plans
+ .filter((p) => p.action !== "CONFLICT" && p.action !== "SKIP_UNCHANGED")
+ .map((p) => `${p.action} ${p.prefId}`)
+ .toSorted();
+ expect(res.applied.map((p) => `${p.action} ${p.prefId}`).toSorted()).toEqual(approved);
+ expect(res.digest).toBe(dry.digest);
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
+ });
+
+ test("a vault mutation after the dry run makes apply refuse before any write", () => {
+ const vault = setupVault();
+ const mem = setupMemory();
+ try {
+ const dry = importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ });
+ // The mutation flips rule-a's CREATE into a CONFLICT, so the
+ // re-computed plan no longer matches the approved one.
+ writeFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "hand-made\n", "utf8");
+ const before = treeDigests(vault);
+
+ let refusal: ApprovalDigestError | null = null;
+ try {
+ importClaudeMemory({
+ vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ approvalDigest: dry.digest,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ } catch (err) {
+ expect(err).toBeInstanceOf(ApprovalDigestError);
+ refusal = err as ApprovalDigestError;
+ }
+ expect(refusal).not.toBeNull();
+ expect(refusal!.message).toContain("--dry-run");
+ expect(treeDigests(vault)).toBe(before);
+ } finally {
+ rmSync(vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
+ });
+
+ test("apply with the approval digest is byte-identical to today's clean path", () => {
+ // One memory source, two identical vaults: the digest-gated apply
+ // and today's apply must land the same bytes. (The rendered
+ // preference carries the memory file's absolute path, so the two
+ // runs must share the source for a byte comparison to be meaningful
+ // at all - the digests, by contrast, agree even across sources.)
+ const mem = setupMemory();
+ const approved = { vault: setupVault() };
+ const legacy = { vault: setupVault() };
+ try {
+ const dry = importClaudeMemory({
+ vault: approved.vault,
+ memoryDir: mem,
+ mode: "dry-run",
+ allowArbitraryMemoryPath: true,
+ });
+ importClaudeMemory({
+ vault: approved.vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ approvalDigest: dry.digest,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ importClaudeMemory({
+ vault: legacy.vault,
+ memoryDir: mem,
+ mode: "apply",
+ allowArbitraryMemoryPath: true,
+ now: new Date("2026-05-18T10:00:00Z"),
+ });
+ for (const prefix of WRITES) {
+ expect(treeDigests(approved.vault, [prefix])).toBe(treeDigests(legacy.vault, [prefix]));
+ }
+ // Both runs took the pre-apply snapshot; only its archive bytes
+ // differ, because they encode each vault's absolute path.
+ expect(readdirSync(join(approved.vault, "Brain", ".snapshots")).toSorted()).toEqual(
+ readdirSync(join(legacy.vault, "Brain", ".snapshots")).toSorted(),
+ );
+ } finally {
+ rmSync(approved.vault, { recursive: true });
+ rmSync(legacy.vault, { recursive: true });
+ rmSync(mem, { recursive: true });
+ }
});
});
diff --git a/tests/core/brain/ingest/batch-plan-extractable.test.ts b/tests/core/brain/ingest/batch-plan-extractable.test.ts
index a414ed62..560da99c 100644
--- a/tests/core/brain/ingest/batch-plan-extractable.test.ts
+++ b/tests/core/brain/ingest/batch-plan-extractable.test.ts
@@ -11,6 +11,7 @@ import { tmpdir } from "node:os";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { updateManifest } from "../../../../src/core/brain/ingest/content-manifest.ts";
import { planBatches } from "../../../../src/core/brain/ingest/batch-plan.ts";
let vault: string;
@@ -84,3 +85,20 @@ describe("extractable gate in planBatches", () => {
expect(after).toBe(before);
});
});
+
+describe("extractable gate × contract change (t_586d5d8b)", () => {
+ test("a changed contract reprocesses an extractable page and still gates a non-extractable one", () => {
+ page("Sources/a.md", "paper");
+ page("Sources/b.md", "memo");
+ setExtractable(["paper", "memo"]); // both extractable
+ updateManifest(vault, ["Sources/a.md", "Sources/b.md"]);
+ setExtractable(["paper"]); // the contract changes; memo pages now gate out
+
+ const plan = planBatches(vault, "Sources", CAPS);
+ // a.md: unchanged bytes, changed contract, still extractable → reprocess.
+ expect(plannedPaths(plan)).toEqual(["Sources/a.md"]);
+ expect(plan.batches[0]!.files[0]!.status).toBe("contract-changed");
+ // b.md: the gate excludes it before any contract question arises.
+ expect(plan.skippedNonExtractable.map((s) => s.path)).toEqual(["Sources/b.md"]);
+ });
+});
diff --git a/tests/core/brain/ingest/batch-plan-git-discovery.test.ts b/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
index fc6a38f4..4cf5df7b 100644
--- a/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
+++ b/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
@@ -16,6 +16,7 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { planBatches } from "../../../../src/core/brain/ingest/batch-plan.ts";
import { computePlanId } from "../../../../src/core/brain/ingest/checkpoint.ts";
+import { computeExtractionContractFingerprint } from "../../../../src/core/brain/ingest/contract.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
@@ -283,7 +284,13 @@ describe("byte-identical no-git path", () => {
expect(plannedPaths(plan)).toEqual(["mono/a.md", "mono/sub/b.md"]);
// Pinned against the documented derivation rather than against the walk, so
// the assertion cannot drift with the discovery implementation.
- expect(plan.planId).toBe(computePlanId(SOURCE, ["mono/a.md", "mono/sub/b.md"]));
+ expect(plan.planId).toBe(
+ computePlanId(
+ SOURCE,
+ ["mono/a.md", "mono/sub/b.md"],
+ computeExtractionContractFingerprint(vault),
+ ),
+ );
expect(plan.ignoreWarnings).toEqual([]);
});
diff --git a/tests/core/brain/ingest/batch-plan.test.ts b/tests/core/brain/ingest/batch-plan.test.ts
index 71d0b027..87b4e1f2 100644
--- a/tests/core/brain/ingest/batch-plan.test.ts
+++ b/tests/core/brain/ingest/batch-plan.test.ts
@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
-import { updateManifest } from "../../../../src/core/brain/ingest/content-manifest.ts";
+import { hashFile, updateManifest } from "../../../../src/core/brain/ingest/content-manifest.ts";
import {
DEFAULT_INGESTIBLE_EXTENSIONS as PLANNER_DEFAULT_EXTENSIONS,
planBatches,
@@ -435,3 +435,104 @@ describe("planBatches — source formats", () => {
expect(PLANNER_DEFAULT_EXTENSIONS).toBe(DEFAULT_INGESTIBLE_EXTENSIONS);
});
});
+
+describe("planBatches — extraction contract (t_586d5d8b)", () => {
+ test("a changed contract reprocesses `unchanged` files with the distinct reason", () => {
+ page("Inbox/a.md", "paper");
+ setExtractable(["paper"]);
+ updateManifest(vault, ["Inbox/a.md"]); // stamped under the live contract
+ // Widen the allowlist: the contract changes while the file's bytes and
+ // its gate outcome stay exactly the same.
+ setExtractable(["paper", "memo"]);
+
+ const plan = planBatches(vault, "Inbox", CAPS);
+ expect(plan.contractChanged).toBe(true);
+ expect(plan.contractChangedFiles).toBe(1);
+ expect(plan.skipped).toEqual([]); // nothing skips under a changed contract
+ expect(allPlannedPaths(plan)).toEqual(["Inbox/a.md"]);
+ expect(plan.batches[0]!.files[0]!.status).toBe("contract-changed");
+ });
+
+ test("bytes-changed and contract-changed stay distinct tokens in one plan", () => {
+ page("Inbox/same.md", "paper");
+ page("Inbox/edited.md", "paper");
+ setExtractable(["paper"]);
+ updateManifest(vault, ["Inbox/same.md", "Inbox/edited.md"]);
+ writeFileSync(
+ join(vault, "Inbox/edited.md"),
+ "---\ntitle: edited\nschema_type: paper\n---\n\nnew body\n",
+ "utf8",
+ );
+ setExtractable(["paper", "memo"]);
+
+ const plan = planBatches(vault, "Inbox", CAPS);
+ const byStatus = new Map(
+ plan.batches.flatMap((b) => b.files.map((f) => [f.status, f.path] as const)),
+ );
+ expect(byStatus.get("modified")).toBe("Inbox/edited.md"); // bytes changed
+ expect(byStatus.get("contract-changed")).toBe("Inbox/same.md"); // contract only
+ expect(plan.contractChangedFiles).toBe(1);
+ });
+
+ test("a v1 manifest (never contract-stamped) reprocesses unchanged bytes once", () => {
+ page("Inbox/a.md", "paper");
+ setExtractable(["paper"]);
+ const manifest = join(vault, ".open-second-brain", "ingest-manifest.json");
+ mkdirSync(join(manifest, ".."), { recursive: true });
+ writeFileSync(
+ manifest,
+ JSON.stringify({
+ schema_version: 1,
+ entries: { "Inbox/a.md": hashFile(join(vault, "Inbox", "a.md")) },
+ }),
+ "utf8",
+ );
+
+ const plan = planBatches(vault, "Inbox", CAPS);
+ expect(plan.contractChanged).toBe(true);
+ expect(plan.batches[0]!.files[0]!.status).toBe("contract-changed");
+ });
+
+ test("an unchanged contract skips exactly as before and emits no contract keys", () => {
+ page("Inbox/a.md", "paper");
+ setExtractable(["paper"]);
+ updateManifest(vault, ["Inbox/a.md"]);
+
+ const plan = planBatches(vault, "Inbox", CAPS);
+ expect(plan.contractChanged).toBe(false);
+ expect(plan.contractChangedFiles).toBe(0);
+ expect(plan.skipped).toEqual(["Inbox/a.md"]);
+ expect(JSON.stringify(serializeBatchPlan(plan))).not.toContain("contract_changed");
+ });
+
+ test("serializeBatchPlan emits the contract fields only when the contract changed", () => {
+ page("Inbox/a.md", "paper");
+ setExtractable(["paper"]);
+ updateManifest(vault, ["Inbox/a.md"]);
+ setExtractable(["paper", "memo"]);
+
+ const wire = serializeBatchPlan(planBatches(vault, "Inbox", CAPS));
+ expect(wire["contract_changed"]).toBe(true);
+ expect(wire["contract_changed_files"]).toBe(1);
+ });
+
+ test("resume does not consume a checkpoint recorded under the old contract", () => {
+ page("Inbox/a.md", "paper");
+ setExtractable(["paper"]);
+ updateManifest(vault, ["Inbox/a.md"]);
+ const before = planBatches(vault, "Inbox", CAPS);
+ recordCompleted(
+ vault,
+ before.planId,
+ "Inbox",
+ ["Inbox/a.md"],
+ new Date("2026-06-13T12:00:00Z"),
+ );
+
+ setExtractable(["paper", "memo"]); // the contract, hence the plan id, changes
+ const resumed = planBatches(vault, "Inbox", { ...CAPS, resume: true });
+ expect(resumed.planId).not.toBe(before.planId);
+ expect(resumed.resumedCompleted).toBe(0); // the old checkpoint cannot resume-skip
+ expect(resumed.batches[0]!.files[0]!.status).toBe("contract-changed");
+ });
+});
diff --git a/tests/core/brain/ingest/checkpoint.test.ts b/tests/core/brain/ingest/checkpoint.test.ts
index 984191df..11b16d51 100644
--- a/tests/core/brain/ingest/checkpoint.test.ts
+++ b/tests/core/brain/ingest/checkpoint.test.ts
@@ -18,22 +18,47 @@ function setupVault(): string {
const AT = new Date("2026-07-10T08:00:00Z");
+/** Contract fingerprints for the plan-id fold: two values a contract change can move between. */
+const CONTRACT_FP_A = "contract-fp-a";
+const CONTRACT_FP_B = "contract-fp-b";
+
afterEach(() => {
delete process.env["OSB_INGEST_NO_CHECKPOINT"];
});
describe("computePlanId", () => {
test("is stable regardless of discovered-path order", () => {
- const a = computePlanId("docs", ["docs/b.md", "docs/a.md"]);
- const b = computePlanId("docs", ["docs/a.md", "docs/b.md"]);
+ const a = computePlanId("docs", ["docs/b.md", "docs/a.md"], CONTRACT_FP_A);
+ const b = computePlanId("docs", ["docs/a.md", "docs/b.md"], CONTRACT_FP_A);
expect(a).toBe(b);
expect(a).toMatch(/^[0-9a-f]{16}$/);
});
test("differs when the source dir or the path set differs", () => {
- const base = computePlanId("docs", ["docs/a.md"]);
- expect(computePlanId("notes", ["docs/a.md"])).not.toBe(base);
- expect(computePlanId("docs", ["docs/a.md", "docs/b.md"])).not.toBe(base);
+ const base = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
+ expect(computePlanId("notes", ["docs/a.md"], CONTRACT_FP_A)).not.toBe(base);
+ expect(computePlanId("docs", ["docs/a.md", "docs/b.md"], CONTRACT_FP_A)).not.toBe(base);
+ });
+
+ test("differs when the extraction contract differs (t_586d5d8b)", () => {
+ const base = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
+ expect(computePlanId("docs", ["docs/a.md"], CONTRACT_FP_B)).not.toBe(base);
+ });
+});
+
+describe("plan id × extraction contract (t_586d5d8b)", () => {
+ test("a checkpoint recorded under one contract is invisible to the next", () => {
+ const vault = setupVault();
+ try {
+ const oldId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
+ recordCompleted(vault, oldId, "docs", ["docs/a.md"], AT);
+ expect(readCheckpoint(vault, oldId)).not.toBeNull();
+
+ const newId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_B);
+ expect(readCheckpoint(vault, newId)).toBeNull(); // the old checkpoint cannot resume-skip
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
});
});
@@ -41,7 +66,7 @@ describe("recordCompleted / readCheckpoint", () => {
test("unions items across calls and reports them sorted", () => {
const vault = setupVault();
try {
- const planId = computePlanId("docs", ["docs/a.md", "docs/b.md", "docs/c.md"]);
+ const planId = computePlanId("docs", ["docs/a.md", "docs/b.md", "docs/c.md"], CONTRACT_FP_A);
recordCompleted(vault, planId, "docs", ["docs/b.md"], AT);
recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);
const cp = readCheckpoint(vault, planId);
@@ -57,7 +82,7 @@ describe("recordCompleted / readCheckpoint", () => {
test("re-recording the same set is a byte-identity no-op", () => {
const vault = setupVault();
try {
- const planId = computePlanId("docs", ["docs/a.md"]);
+ const planId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
expect(recordCompleted(vault, planId, "docs", ["docs/a.md"], AT)).toBe(true);
const before = readFileSync(checkpointPath(vault, planId), "utf8");
const later = new Date("2026-07-10T09:00:00Z");
@@ -72,7 +97,7 @@ describe("recordCompleted / readCheckpoint", () => {
test("a corrupt checkpoint throws rather than silently resetting", () => {
const vault = setupVault();
try {
- const planId = computePlanId("docs", ["docs/a.md"]);
+ const planId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
const path = checkpointPath(vault, planId);
recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);
writeFileSync(path, "{ not json", "utf8");
@@ -85,7 +110,7 @@ describe("recordCompleted / readCheckpoint", () => {
test("an unknown schema_version throws", () => {
const vault = setupVault();
try {
- const planId = computePlanId("docs", ["docs/a.md"]);
+ const planId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
const path = checkpointPath(vault, planId);
recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);
writeFileSync(path, JSON.stringify({ schema_version: 99, completed: [] }), "utf8");
@@ -109,7 +134,7 @@ describe("clearCheckpoint", () => {
test("removes the checkpoint file and reports whether it existed", () => {
const vault = setupVault();
try {
- const planId = computePlanId("docs", ["docs/a.md"]);
+ const planId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);
expect(existsSync(checkpointPath(vault, planId))).toBe(true);
expect(clearCheckpoint(vault, planId)).toBe(true);
@@ -127,7 +152,7 @@ describe("OSB_INGEST_NO_CHECKPOINT opt-out", () => {
try {
process.env["OSB_INGEST_NO_CHECKPOINT"] = "1";
expect(checkpointingEnabled()).toBe(false);
- const planId = computePlanId("docs", ["docs/a.md"]);
+ const planId = computePlanId("docs", ["docs/a.md"], CONTRACT_FP_A);
expect(recordCompleted(vault, planId, "docs", ["docs/a.md"], AT)).toBe(false);
expect(existsSync(checkpointPath(vault, planId))).toBe(false);
expect(readCheckpoint(vault, planId)).toBeNull();
diff --git a/tests/core/brain/ingest/content-manifest.test.ts b/tests/core/brain/ingest/content-manifest.test.ts
index 7f6c9357..d1249c03 100644
--- a/tests/core/brain/ingest/content-manifest.test.ts
+++ b/tests/core/brain/ingest/content-manifest.test.ts
@@ -14,6 +14,7 @@ import { tmpdir } from "node:os";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";
+import { computeExtractionContractFingerprint } from "../../../../src/core/brain/ingest/contract.ts";
import {
classifyPaths,
hashFile,
@@ -23,6 +24,8 @@ import {
updateManifest,
writeManifestAtomic,
} from "../../../../src/core/brain/ingest/content-manifest.ts";
+import { planBatches } from "../../../../src/core/brain/ingest/batch-plan.ts";
+import { deleteBySource } from "../../../../src/core/brain/source-cleanup.ts";
let vault: string;
let configHome: string;
@@ -151,6 +154,165 @@ describe("manifest persistence", () => {
// Different entries → write.
expect(writeManifestAtomic(vault, { "a.md": "y".repeat(64) })).toBe(true);
});
+
+ test("an unknown schema_version is still refused by name", () => {
+ writeManifestBytes(JSON.stringify({ schema_version: 999, entries: {} }));
+ expect(() => readManifest(vault)).toThrow(/ingest manifest schema_version 999 not supported/);
+ });
+});
+
+/** Write raw bytes as the content manifest, for the versioned-fixture cases. */
+function writeManifestBytes(bytes: string): void {
+ const path = manifestPath(vault);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, bytes, "utf8");
+}
+
+describe("extraction contract (t_586d5d8b)", () => {
+ test("the manifest records the contract fingerprint and reads it back", () => {
+ writeSource("a.md", "a");
+ updateManifest(vault, ["a.md"]);
+
+ const manifest = readManifest(vault);
+ expect(manifest.contract).toEqual({
+ fingerprint: computeExtractionContractFingerprint(vault),
+ });
+
+ // The field is on disk, manifest-wide, under the bumped schema version.
+ const onDisk = JSON.parse(readFileSync(manifestPath(vault), "utf8")) as {
+ schema_version: number;
+ contract: { fingerprint: string } | null;
+ };
+ expect(onDisk.schema_version).toBe(2);
+ expect(onDisk.contract?.fingerprint).toBe(computeExtractionContractFingerprint(vault));
+ });
+
+ test("the fingerprint is stable across calls and sensitive to its inputs", () => {
+ // Stable across calls: the recording is deterministic, not clocked.
+ expect(computeExtractionContractFingerprint(vault)).toBe(
+ computeExtractionContractFingerprint(vault),
+ );
+ // Sensitive to the allowlist: changing `extractable` changes the contract.
+ const before = computeExtractionContractFingerprint(vault);
+ writeSource("Brain/_brain.yaml", "schema_version: 1\nschema:\n extractable:\n - paper\n");
+ expect(computeExtractionContractFingerprint(vault)).not.toBe(before);
+ });
+
+ test("a v1 manifest (no contract field) is accepted and degrades to changed-contract", () => {
+ writeManifestBytes(JSON.stringify({ schema_version: 1, entries: { "a.md": "z".repeat(64) } }));
+ const manifest = readManifest(vault);
+ expect(manifest.entries["a.md"]).toBe("z".repeat(64));
+ expect(manifest.contract).toBeNull();
+ });
+
+ test("readManifest reports the schema version the FILE carries, not the write version", () => {
+ // No file yet: the current shape is the honest answer (nothing older exists).
+ expect(readManifest(vault).schema_version).toBe(2);
+
+ // An accepted v1 manifest must report itself as v1 - a diagnostic asking
+ // "which version is on disk" gets the truth, not the write constant.
+ writeManifestBytes(JSON.stringify({ schema_version: 1, entries: {} }));
+ expect(readManifest(vault).schema_version).toBe(1);
+
+ writeManifestBytes(
+ JSON.stringify({ schema_version: 2, entries: {}, contract: { fingerprint: "f".repeat(64) } }),
+ );
+ expect(readManifest(vault).schema_version).toBe(2);
+ });
+
+ test("an explicitly-null contract writes the v1 shape; the omitted form stays the live upgrade", () => {
+ // Explicit null is a v1 read being round-tripped: it serializes back as
+ // v1, contract-less, keeping the changed-contract marker alive.
+ writeManifestAtomic(vault, { "a.md": "z".repeat(64) }, null);
+ const onDisk = JSON.parse(readFileSync(manifestPath(vault), "utf8")) as {
+ schema_version: number;
+ contract?: unknown;
+ };
+ expect(onDisk.schema_version).toBe(1);
+ expect("contract" in onDisk).toBe(false);
+ expect(readManifest(vault).contract).toBeNull();
+
+ // Omitted is the post-extraction write: it records the LIVE contract
+ // and lands as v2 - the one-time upgrade a real reprocessing pass makes true.
+ writeManifestAtomic(vault, { "a.md": "z".repeat(64) });
+ const upgraded = JSON.parse(readFileSync(manifestPath(vault), "utf8")) as {
+ schema_version: number;
+ contract: { fingerprint: string } | null;
+ };
+ expect(upgraded.schema_version).toBe(2);
+ expect(upgraded.contract?.fingerprint).toBe(computeExtractionContractFingerprint(vault));
+ });
+
+ test("a v1 manifest's next write lands as v2 with the fingerprint", () => {
+ writeSource("a.md", "a");
+ writeManifestBytes(
+ JSON.stringify({ schema_version: 1, entries: { "a.md": hashFile(join(vault, "a.md")) } }),
+ );
+ expect(readManifest(vault).contract).toBeNull();
+
+ updateManifest(vault, ["a.md"]);
+ const manifest = readManifest(vault);
+ expect(manifest.schema_version).toBe(2);
+ expect(manifest.contract).toEqual({
+ fingerprint: computeExtractionContractFingerprint(vault),
+ });
+ });
+
+ test("cleanup preserves the recorded contract (the direct write round-trips the field)", () => {
+ writeSource("doc.md", "the source bytes");
+ updateManifest(vault, ["doc.md"]);
+ const recorded = readManifest(vault).contract;
+
+ const plan = deleteBySource(vault, "doc.md", { confirm: true });
+ expect(plan.manifestEntryRemoved).toBe(true);
+
+ const after = readManifest(vault);
+ expect(after.entries["doc.md"]).toBeUndefined();
+ expect(after.contract).toEqual(recorded);
+ });
+
+ test("cleanup on a not-yet-reprocessed v1 manifest keeps the owed contract-changed reprocess", () => {
+ // The v1 manifest's remaining entry was extracted under the
+ // pre-fingerprint contract and never reprocessed. A cleanup that
+ // upgraded the file to v2 under the live contract would classify it
+ // `unchanged` forever - the owed one-time reprocess forfeited, silently.
+ writeSource("Inbox/a.md", "doomed source");
+ writeSource("Inbox/b.md", "surviving source");
+ writeManifestBytes(
+ JSON.stringify({
+ schema_version: 1,
+ entries: {
+ "Inbox/a.md": hashFile(join(vault, "Inbox", "a.md")),
+ "Inbox/b.md": hashFile(join(vault, "Inbox", "b.md")),
+ },
+ }),
+ );
+
+ const plan = deleteBySource(vault, "Inbox/a.md", { confirm: true });
+ expect(plan.manifestEntryRemoved).toBe(true);
+
+ // The round-trip is lossless: still the v1 shape, contract-less, so the
+ // changed-contract marker survives until a real reprocessing write.
+ const onDisk = JSON.parse(readFileSync(manifestPath(vault), "utf8")) as {
+ schema_version: number;
+ contract?: unknown;
+ };
+ expect(onDisk.schema_version).toBe(1);
+ expect("contract" in onDisk).toBe(false);
+ const after = readManifest(vault);
+ expect(after.contract).toBeNull();
+ expect(after.entries["Inbox/b.md"]).toBeDefined();
+
+ // The owed reprocess is still owed: the surviving byte-identical source
+ // reprocesses as contract-changed, never as an `unchanged` skip. (The
+ // deleted source itself is still on disk - originals go only with
+ // includeOriginals - and classifies `new` again, which is correct.)
+ const batches = planBatches(vault, "Inbox", { maxBatchBytes: 10_000, maxBatchFiles: 100 });
+ expect(batches.contractChanged).toBe(true);
+ expect(batches.skipped).toEqual([]);
+ const survivor = batches.batches.flatMap((b) => b.files).find((f) => f.path === "Inbox/b.md");
+ expect(survivor?.status).toBe("contract-changed");
+ });
});
describe("ingestSource integration", () => {
diff --git a/tests/core/brain/ingest/contract.test.ts b/tests/core/brain/ingest/contract.test.ts
new file mode 100644
index 00000000..0d707204
--- /dev/null
+++ b/tests/core/brain/ingest/contract.test.ts
@@ -0,0 +1,100 @@
+/**
+ * The extraction-contract fingerprint (t_586d5d8b). The manifest gates
+ * re-ingest on bytes alone, so changed extraction settings left `unchanged`
+ * sources answering with extraction shaped by the old contract. The
+ * fingerprint names the contract so the manifest can record it and the
+ * planner can refuse to skip under a changed one. These tests pin the
+ * fingerprint's PURITY: no clock, no absolute paths, no per-call options -
+ * the vault's config text and the version constant are the whole input, so a
+ * recorded fingerprint means the same contract on every machine.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ EXTRACT_CONTRACT_VERSION,
+ computeExtractionContractFingerprint,
+ extractionContractFingerprint,
+} from "../../../../src/core/brain/ingest/contract.ts";
+import { tempDirs } from "../../../helpers/temp-dir.ts";
+
+const mkTemp = tempDirs();
+
+function vaultWithSchema(schemaBlock: string | null): string {
+ const vault = mkTemp("o2b-contract-vault-");
+ if (schemaBlock !== null) {
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), schemaBlock, "utf8");
+ }
+ return vault;
+}
+
+describe("computeExtractionContractFingerprint", () => {
+ test("is 16 lowercase hex characters", () => {
+ const fp = computeExtractionContractFingerprint(vaultWithSchema(null));
+ expect(fp).toMatch(/^[0-9a-f]{16}$/);
+ });
+
+ test("is stable across calls - no clock in the input", () => {
+ const vault = vaultWithSchema(null);
+ expect(computeExtractionContractFingerprint(vault)).toBe(
+ computeExtractionContractFingerprint(vault),
+ );
+ });
+
+ test("is free of absolute paths: two vaults with identical config fingerprint identically", () => {
+ // Different temp dirs, byte-identical config text: the only way the two
+ // fingerprints can match is if no absolute path leaks into the digest.
+ const schema = "schema_version: 1\nschema:\n extractable:\n - paper\n";
+ const a = vaultWithSchema(schema);
+ const b = vaultWithSchema(schema);
+ expect(computeExtractionContractFingerprint(a)).toBe(computeExtractionContractFingerprint(b));
+ });
+
+ test("takes no per-call options: the vault is the only argument", () => {
+ // Purity pinned at the signature: options like `pre_extract`,
+ // `extensions`, `exclude` and the batch caps shape one planning call, not
+ // the contract a stored page was extracted under, so none is accepted.
+ expect(computeExtractionContractFingerprint.length).toBe(1);
+ });
+
+ test("changes when the extractable allowlist changes", () => {
+ const bare = computeExtractionContractFingerprint(vaultWithSchema(null));
+ const withAllowlist = computeExtractionContractFingerprint(
+ vaultWithSchema("schema_version: 1\nschema:\n extractable:\n - paper\n"),
+ );
+ const wider = computeExtractionContractFingerprint(
+ vaultWithSchema("schema_version: 1\nschema:\n extractable:\n - paper\n - memo\n"),
+ );
+ expect(withAllowlist).not.toBe(bare);
+ expect(wider).not.toBe(withAllowlist);
+ });
+
+ test("is insensitive to the allowlist's spelling order (sorted before hashing)", () => {
+ const one = computeExtractionContractFingerprint(
+ vaultWithSchema("schema_version: 1\nschema:\n extractable:\n - memo\n - paper\n"),
+ );
+ const two = computeExtractionContractFingerprint(
+ vaultWithSchema("schema_version: 1\nschema:\n extractable:\n - paper\n - memo\n"),
+ );
+ expect(one).toBe(two);
+ });
+});
+
+describe("extractionContractFingerprint (the pure combiner)", () => {
+ const ALLOWLIST = ["memo", "paper"];
+
+ test("changes when the contract version bumps", () => {
+ const current = extractionContractFingerprint(EXTRACT_CONTRACT_VERSION, ALLOWLIST);
+ const bumped = extractionContractFingerprint(EXTRACT_CONTRACT_VERSION + 1, ALLOWLIST);
+ expect(bumped).not.toBe(current);
+ });
+
+ test("sorts the allowlist before hashing", () => {
+ expect(extractionContractFingerprint(1, ALLOWLIST)).toBe(
+ extractionContractFingerprint(1, [...ALLOWLIST].reverse()),
+ );
+ });
+});
diff --git a/tests/core/brain/ingest/ingest.test.ts b/tests/core/brain/ingest/ingest.test.ts
index fd89906e..a656346e 100644
--- a/tests/core/brain/ingest/ingest.test.ts
+++ b/tests/core/brain/ingest/ingest.test.ts
@@ -26,7 +26,8 @@ import {
PRE_EXTRACT_MAX_SOURCE_BYTES,
readSourceBounded,
} from "../../../../src/core/brain/ingest/ingest.ts";
-import { manifestPath } from "../../../../src/core/brain/ingest/content-manifest.ts";
+import { manifestPath, hashBytes } from "../../../../src/core/brain/ingest/content-manifest.ts";
+import { computeExtractionContractFingerprint } from "../../../../src/core/brain/ingest/contract.ts";
import { computePlanId, readCheckpoint } from "../../../../src/core/brain/ingest/checkpoint.ts";
let vault: string;
@@ -138,7 +139,11 @@ describe("ingestSource", () => {
test("planId records the ingested vault-file source into the plan checkpoint (t_ba1fa5f6)", () => {
// The checkpoint is only recorded for a real vault file, so materialize it.
seedSourceFile();
- const planId = computePlanId("Articles", ["Articles/restaking-primer.md"]);
+ const planId = computePlanId(
+ "Articles",
+ ["Articles/restaking-primer.md"],
+ computeExtractionContractFingerprint(vault),
+ );
ingestSource(vault, INPUT, { agent: "claude", now: NOW, planId });
const cp = readCheckpoint(vault, planId);
expect(cp?.completed).toEqual(["Articles/restaking-primer.md"]);
@@ -146,7 +151,11 @@ describe("ingestSource", () => {
test("without planId no checkpoint is written", () => {
seedSourceFile();
- const planId = computePlanId("Articles", ["Articles/restaking-primer.md"]);
+ const planId = computePlanId(
+ "Articles",
+ ["Articles/restaking-primer.md"],
+ computeExtractionContractFingerprint(vault),
+ );
ingestSource(vault, INPUT, { agent: "claude", now: NOW });
expect(readCheckpoint(vault, planId)).toBeNull();
});
@@ -442,3 +451,31 @@ describe("readSourceBounded", () => {
});
});
});
+
+describe("ingestSource — extraction contract (t_586d5d8b)", () => {
+ test("ingesting under a v1 manifest rewrites the summary and lands the manifest as v2", () => {
+ seedSourceFile();
+ // Pre-fingerprint era manifest: the source's live hash recorded, no
+ // contract. The ingest records the source under the live contract, so the
+ // manifest it rewrites must land as v2 stamped with the fingerprint.
+ writeManifestBytes(
+ JSON.stringify({
+ schema_version: 1,
+ entries: {
+ [INPUT.sourcePath]: hashBytes(readFileSync(join(vault, INPUT.sourcePath))),
+ },
+ }),
+ );
+
+ const res = ingestSource(vault, INPUT, { agent: "claude", now: NOW });
+ expect(res.created).toBe(true);
+ expect(readSummary(res.summaryPath)).toContain("kind: brain-source");
+
+ const onDisk = JSON.parse(readFileSync(manifestPath(vault), "utf8")) as {
+ schema_version: number;
+ contract: { fingerprint: string } | null;
+ };
+ expect(onDisk.schema_version).toBe(2);
+ expect(onDisk.contract?.fingerprint).toBe(computeExtractionContractFingerprint(vault));
+ });
+});
diff --git a/tests/core/brain/ingest/reconcile.test.ts b/tests/core/brain/ingest/reconcile.test.ts
index 0744a7f3..e9407c3f 100644
--- a/tests/core/brain/ingest/reconcile.test.ts
+++ b/tests/core/brain/ingest/reconcile.test.ts
@@ -208,3 +208,30 @@ describe("reconcilePlan - the post-import read-back census", () => {
expect(report.census.outcome).toBe("complete");
});
});
+
+describe("reconcilePlan under a contract change (t_586d5d8b)", () => {
+ test("a live contract change turns an ingested source into a named gap", () => {
+ write("Docs/a.md", "---\ntitle: a\nschema_type: paper\n---\n\nbody\n");
+ const allowlist = (tokens: string[]): string =>
+ `schema_version: 1\nschema:\n page_types:\n${tokens.map((t) => ` - ${t}`).join("\n")}\n` +
+ ` extractable:\n${tokens.map((t) => ` - ${t}`).join("\n")}\n`;
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), allowlist(["paper"]), "utf8");
+
+ const first = planBatches(vault, "Docs", CAPS);
+ ingest("Docs/a.md", first.planId);
+ // Under the contract the ingest ran under, the plan reconciles clean.
+ expect(reconcilePlan(vault, planBatches(vault, "Docs", CAPS)).complete).toBe(true);
+
+ // Widen the allowlist: the live contract changes, the plan id changes with
+ // it, and the old checkpoint cannot vouch for work extracted under the old
+ // contract - the source is named as never ingested until it reprocesses.
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), allowlist(["paper", "memo"]), "utf8");
+ const changed = planBatches(vault, "Docs", CAPS);
+ expect(changed.planId).not.toBe(first.planId);
+
+ const report = reconcilePlan(vault, changed);
+ expect(report.dispatched).toEqual(["Docs/a.md"]);
+ expect(report.missing).toEqual(["Docs/a.md"]);
+ expect(report.complete).toBe(false);
+ });
+});
diff --git a/tests/core/brain/payload-json.test.ts b/tests/core/brain/payload-json.test.ts
new file mode 100644
index 00000000..36e903df
--- /dev/null
+++ b/tests/core/brain/payload-json.test.ts
@@ -0,0 +1,120 @@
+/**
+ * `payload-json` (trust-surface-hardening, t_dac8bf7e): the strip-and-note
+ * parser the four model-answer verbs share. Claims pinned here:
+ *
+ * 1. A clean payload parses as-is and carries NO strip fact - the strip
+ * fires only after a failed plain parse.
+ * 2. A leading `<think>...</think>` block is stripped and the fact is
+ * always reported (`kind`, `prefixChars`), for the prose-prefixed and
+ * the fenced-body shapes.
+ * 3. The strip never rescues genuinely malformed JSON: strip-then-still-
+ * invalid keeps the named error, and the message names the strip
+ * attempt; plain garbage keeps the plain refusal.
+ * 4. Only ONE leading block is stripped, and only when it is leading.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ FENCED_THINK_BLOCK_STRIP_KIND,
+ parsePayloadJson,
+ PayloadJsonError,
+ payloadStripNote,
+ PAYLOAD_UNPARSEABLE_MESSAGE,
+ THINK_BLOCK_STRIP_KIND,
+} from "../../../src/core/brain/payload-json.ts";
+
+function parseFailing(raw: string): PayloadJsonError {
+ try {
+ parsePayloadJson(raw);
+ } catch (error) {
+ if (error instanceof PayloadJsonError) return error;
+ throw error;
+ }
+ throw new Error(`expected a PayloadJsonError for ${JSON.stringify(raw)}`);
+}
+
+describe("parsePayloadJson", () => {
+ test("a clean payload parses as-is and carries no strip fact", () => {
+ const parsed = parsePayloadJson('{"a":1}');
+ expect(parsed.payload).toEqual({ a: 1 });
+ expect("strip" in parsed).toBe(false);
+ });
+
+ test("the strip fires only after a failed plain parse", () => {
+ // The think block sits INSIDE a valid JSON string: the plain parse
+ // succeeds, so no strip may fire.
+ const raw = JSON.stringify({ text: "<think>not stripped</think>" });
+ const parsed = parsePayloadJson(raw);
+ expect(parsed.payload).toEqual({ text: "<think>not stripped</think>" });
+ expect("strip" in parsed).toBe(false);
+ });
+
+ test("a prose-prefixed think block is stripped and the fact named", () => {
+ const think = "<think>reasoning about the answer</think>";
+ const parsed = parsePayloadJson(`${think}{"a":1}`);
+ expect(parsed.payload).toEqual({ a: 1 });
+ expect(parsed.strip).toEqual({ kind: THINK_BLOCK_STRIP_KIND, prefixChars: think.length });
+ });
+
+ test("leading whitespace counts into the stripped prefix", () => {
+ const head = "\n <think>r</think>";
+ const parsed = parsePayloadJson(`${head} {"a":1}`);
+ expect(parsed.payload).toEqual({ a: 1 });
+ expect(parsed.strip?.kind).toBe(THINK_BLOCK_STRIP_KIND);
+ expect(parsed.strip?.prefixChars).toBe(head.length);
+ });
+
+ test("a think block ahead of a fenced body strips the prefix and names the fenced kind", () => {
+ const think = "<think>deliberating</think>";
+ const raw = `${think}\n\`\`\`json\n{"a":1}\n\`\`\`\n`;
+ const parsed = parsePayloadJson(raw);
+ expect(parsed.payload).toEqual({ a: 1 });
+ expect(parsed.strip?.kind).toBe(FENCED_THINK_BLOCK_STRIP_KIND);
+ // prefixChars counts every character removed before the JSON body.
+ expect(parsed.strip?.prefixChars).toBe(raw.indexOf('{"a":1}'));
+ });
+
+ test("a multi-line think body stops at the first closing tag", () => {
+ const think = '<think>line one\n{ "not": "json" }\nline two</think>';
+ const parsed = parsePayloadJson(`${think}{"ok":true}`);
+ expect(parsed.payload).toEqual({ ok: true });
+ expect(parsed.strip?.prefixChars).toBe(think.length);
+ });
+
+ test("a fenced body with no think block is not this module's rescue", () => {
+ // The module strips think blocks; a bare fenced payload was refused
+ // before this module existed and still is, with the plain message.
+ const error = parseFailing('```json\n{"a":1}\n```');
+ expect(error.message).toBe(PAYLOAD_UNPARSEABLE_MESSAGE);
+ });
+
+ test("a think block that is not leading is not stripped", () => {
+ const error = parseFailing('{"a":1}<think>x</think>');
+ expect(error.message).toBe(PAYLOAD_UNPARSEABLE_MESSAGE);
+ });
+
+ test("strip-then-still-invalid keeps the named error and names the strip attempt", () => {
+ const error = parseFailing("<think>reasoning</think>not json at all");
+ expect(error.name).toBe("PayloadJsonError");
+ expect(error.message).toContain(PAYLOAD_UNPARSEABLE_MESSAGE);
+ expect(error.message).toContain("<think>");
+ });
+
+ test("plain garbage keeps the plain refusal with no strip mention", () => {
+ const error = parseFailing("not json");
+ expect(error.message).toBe(PAYLOAD_UNPARSEABLE_MESSAGE);
+ expect(error.message).not.toContain("stripped");
+ });
+
+ test("only one leading block is stripped", () => {
+ const error = parseFailing('<think>a</think><think>b</think>{"a":1}');
+ expect(error.message).toContain("<think>");
+ });
+});
+
+test("the strip note names the kind and the prefix size", () => {
+ expect(payloadStripNote({ kind: THINK_BLOCK_STRIP_KIND, prefixChars: 24 })).toBe(
+ "leading <think> block stripped before JSON parse (kind=think_block, prefix_chars=24)",
+ );
+});
diff --git a/tests/core/brain/research/research.test.ts b/tests/core/brain/research/research.test.ts
index 4d8c41de..8e2e0aa8 100644
--- a/tests/core/brain/research/research.test.ts
+++ b/tests/core/brain/research/research.test.ts
@@ -11,10 +11,16 @@ import { tmpdir } from "node:os";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { setSecret } from "../../../../src/core/brain/secrets/store.ts";
+import { SecretReferenceError } from "../../../../src/core/secret-ref.ts";
import {
writeResearchReport,
ResearchValidationError,
+ resolveResearchPoolEnv,
+ BRAVE_API_KEY_ENV,
+ TAVILY_API_KEY_ENV,
} from "../../../../src/core/brain/research/research.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
let vault: string;
let configHome: string;
@@ -103,3 +109,40 @@ describe("writeResearchReport", () => {
expect(second.reportPath).toBe(first.reportPath);
});
});
+
+// ----- Provider keys through the custody store (t_e5807974 / B2) -------------
+//
+// A provider key env value may be a `$secret:NAME` reference; with the
+// custody vault passed it resolves store-first at pool wiring time. Plain
+// env values keep today's path byte-identically, and an unresolvable
+// reference surfaces the named resolver error instead of quietly yielding
+// an empty pool.
+
+describe("resolveResearchPoolEnv", () => {
+ const STORED_BRAVE_KEY = fakeCredential("stored-", "brave-5f9a");
+ const NOW = new Date("2026-06-13T12:00:00Z");
+
+ test("a reference as a provider key resolves through the custody store", () => {
+ setSecret(vault, { name: "brave_key", value: STORED_BRAVE_KEY, agent: "tester", now: NOW });
+ const resolved = resolveResearchPoolEnv(
+ { [BRAVE_API_KEY_ENV]: "$secret:brave_key", [TAVILY_API_KEY_ENV]: "" },
+ vault,
+ );
+ expect(resolved.braveApiKey).toBe(STORED_BRAVE_KEY);
+ expect(resolved.tavilyApiKey).toBeNull();
+ });
+
+ test("plain env values pass through byte-identically", () => {
+ const resolved = resolveResearchPoolEnv(
+ { [BRAVE_API_KEY_ENV]: " b ", [TAVILY_API_KEY_ENV]: "t" },
+ vault,
+ );
+ expect(resolved).toEqual({ braveApiKey: "b", tavilyApiKey: "t" });
+ });
+
+ test("an unresolvable reference throws the named resolver error", () => {
+ expect(() =>
+ resolveResearchPoolEnv({ [BRAVE_API_KEY_ENV]: "$secret:absent_name" }, vault),
+ ).toThrow(SecretReferenceError);
+ });
+});
diff --git a/tests/core/brain/secrets/bundle.test.ts b/tests/core/brain/secrets/bundle.test.ts
new file mode 100644
index 00000000..ec8f205e
--- /dev/null
+++ b/tests/core/brain/secrets/bundle.test.ts
@@ -0,0 +1,335 @@
+/**
+ * Passphrase-encrypted credential bundles (t_592d9e91): export the
+ * store's entries as a single schema-versioned envelope whose values are
+ * re-encrypted under a key the passphrase derives through the keyfile
+ * envelope's KDF, and import one back - into this vault or a fresh one -
+ * with exactness on name collisions and nothing written on a refusal.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ BUNDLE_REFUSAL_CODES,
+ bundleEgressScanTree,
+ bundleFromEgressScan,
+ exportSecretBundle,
+ importSecretBundle,
+ SECRET_BUNDLE_SCHEMA_VERSION,
+ SecretBundleError,
+} from "../../../../src/core/brain/secrets/bundle.ts";
+import {
+ listSecrets,
+ resolveSecretReadOnly,
+ secretsDir,
+ setSecret,
+} from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
+
+const NOW = new Date("2026-06-05T10:00:00Z");
+const LATER = new Date("2026-06-05T11:00:00Z");
+const CTX = { agent: "tester", now: NOW };
+const PASSPHRASE = fakeCredential("bundle-pass", "-phrase-", "42");
+const WRONG_PASSPHRASE = fakeCredential("bundle-wrong", "-phrase-", "42");
+const VALUE_A = fakeCredential("sk-bundle-", "alpha-9f8e7d6c");
+const VALUE_B = fakeCredential("tok-bundle-", "beta-5a5a5a5a");
+
+let vault: string;
+let other: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-bundle-"));
+ other = mkdtempSync(join(tmpdir(), "o2b-bundle-other-"));
+ for (const root of [vault, other]) mkdirSync(join(root, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(other, { recursive: true, force: true });
+});
+
+function seed(root: string): void {
+ setSecret(root, {
+ name: "alpha-key",
+ value: VALUE_A,
+ envVar: "ALPHA_KEY",
+ allow: ["curl *"],
+ agent: "tester",
+ now: NOW,
+ });
+ setSecret(root, {
+ name: "beta-key",
+ value: VALUE_B,
+ envVar: "BETA_KEY",
+ allow: [],
+ agent: "tester",
+ now: NOW,
+ });
+}
+
+describe("the credential bundle", () => {
+ test("export then import into a fresh vault restores names, env vars and allowlists", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ const result = importSecretBundle(other, bundle, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ expect(result.imported.toSorted()).toEqual(["alpha-key", "beta-key"]);
+ expect(result.replaced).toEqual([]);
+ const restored = listSecrets(other);
+ expect(restored).toHaveLength(2);
+ expect(restored.find((s) => s.name === "alpha-key")).toMatchObject({
+ env_var: "ALPHA_KEY",
+ allow: ["curl *"],
+ });
+ expect(restored.find((s) => s.name === "beta-key")).toMatchObject({
+ env_var: "BETA_KEY",
+ allow: [],
+ });
+ expect(resolveSecretReadOnly(other, "alpha-key").value).toBe(VALUE_A);
+ expect(resolveSecretReadOnly(other, "beta-key").value).toBe(VALUE_B);
+ });
+
+ test("a wrong passphrase refuses by name and writes nothing to the target store", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ try {
+ importSecretBundle(other, bundle, {
+ passphrase: WRONG_PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ throw new Error("expected the passphrase refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(BUNDLE_REFUSAL_CODES.passphrase);
+ }
+ expect(listSecrets(other)).toHaveLength(0);
+ expect(existsSync(join(secretsDir(other), "secrets.json"))).toBe(false);
+ });
+
+ test("import refuses an existing name without --replace; --replace overwrites exactly", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ const older = fakeCredential("older", "-value-", "1");
+ setSecret(other, {
+ name: "alpha-key",
+ value: older,
+ envVar: "OLD_KEY",
+ allow: [],
+ agent: "tester",
+ now: NOW,
+ });
+ try {
+ importSecretBundle(other, bundle, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ throw new Error("expected the collision refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(BUNDLE_REFUSAL_CODES.nameExists);
+ expect((err as SecretBundleError).message).toContain("alpha-key");
+ }
+ // Exactness: the refused import changed nothing.
+ expect(resolveSecretReadOnly(other, "alpha-key").value).toBe(older);
+ expect(listSecrets(other)).toHaveLength(1);
+
+ const result = importSecretBundle(other, bundle, {
+ passphrase: PASSPHRASE,
+ replace: true,
+ agent: "tester",
+ now: LATER,
+ });
+ expect(result.replaced).toEqual(["alpha-key"]);
+ expect(result.imported.toSorted()).toEqual(["alpha-key", "beta-key"]);
+ expect(resolveSecretReadOnly(other, "alpha-key").value).toBe(VALUE_A);
+ expect(listSecrets(other)).toHaveLength(2);
+ });
+
+ test("import validates allow patterns exactly as `set` refuses them", () => {
+ // The allow list rides in the clear, so a bundle rewritten in transit
+ // cannot land entries the store's own writer would refuse - and a
+ // non-string pattern cannot reach the exec allowlist matcher.
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX) as unknown as {
+ entries: Record<string, { allow: unknown[] }>;
+ };
+ for (const bad of [[""], [" "]]) {
+ const tampered = structuredClone(bundle);
+ tampered.entries["beta-key"]!.allow = bad;
+ try {
+ importSecretBundle(other, tampered, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ throw new Error(`expected the allow-pattern refusal for ${JSON.stringify(bad)}`);
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(BUNDLE_REFUSAL_CODES.entry);
+ }
+ expect(listSecrets(other)).toHaveLength(0);
+ }
+ const typed = structuredClone(bundle);
+ typed.entries["beta-key"]!.allow = [42];
+ expect(() =>
+ importSecretBundle(other, typed, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ }),
+ ).toThrow(SecretBundleError);
+ expect(listSecrets(other)).toHaveLength(0);
+ // A valid pattern trims exactly as `set` trims it.
+ const padded = structuredClone(bundle);
+ padded.entries["beta-key"]!.allow = [" curl * "];
+ importSecretBundle(other, padded, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ expect(listSecrets(other).find((s) => s.name === "beta-key")?.allow).toEqual(["curl *"]);
+ });
+
+ test("the exported bytes carry none of the values or the passphrase; KDF rides inside", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ const serialized = JSON.stringify(bundle);
+ expect(serialized).not.toContain(VALUE_A);
+ expect(serialized).not.toContain(VALUE_B);
+ expect(serialized).not.toContain(PASSPHRASE);
+ // Schema version and wall clock top the envelope; the KDF parameters
+ // travel inside it so old exports stay readable as the cost curve moves.
+ expect(bundle.version).toBe(SECRET_BUNDLE_SCHEMA_VERSION);
+ expect(typeof bundle.generated_at).toBe("string");
+ expect(bundle.kdf.algo).toBe("scrypt");
+ expect(bundle.kdf.n).toBe(2 ** 15);
+ // The egress scan tree is exactly the non-ciphertext inventory: names
+ // and mappings visible to the guard as an ARRAY (never credential-
+ // shaped mapping keys), the kdf salt excluded, values absent.
+ const scanTree = bundleEgressScanTree(bundle);
+ const scanned = JSON.stringify(scanTree);
+ expect(scanned).toContain("alpha-key");
+ expect(scanned).toContain("ALPHA_KEY");
+ expect(scanned).not.toContain("ciphertext");
+ expect(scanned).not.toContain("salt");
+ const scannedEntries = scanTree.entries as Array<{ name: string }>;
+ expect(scannedEntries.map((e) => e.name).toSorted()).toEqual(["alpha-key", "beta-key"]);
+ // The merge re-attaches the sealed values; a clean scan round-trips.
+ const merged = bundleFromEgressScan(bundle, scanTree);
+ expect(merged.entries["alpha-key"]!.value).toEqual(bundle.entries["alpha-key"]!.value);
+ });
+
+ test("the merge refuses when the guard rewrote an entry identifier", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ const scanTree = bundleEgressScanTree(bundle) as {
+ entries: Array<Record<string, unknown>>;
+ };
+ scanTree.entries[0]!["name"] = fakeCredential("rewritten", "-name-", "9");
+ try {
+ bundleFromEgressScan(bundle, scanTree);
+ throw new Error("expected the identifier-rewrite refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(BUNDLE_REFUSAL_CODES.entry);
+ }
+ });
+
+ test("audit records the export and the import with no values", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ importSecretBundle(other, bundle, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ for (const [root, action] of [
+ [vault, "secret_bundle_exported"],
+ [other, "secret_bundle_imported"],
+ ] as const) {
+ const auditDir = join(root, "Brain", "log", "secret-custody");
+ const raw = readdirSync(auditDir)
+ .map((f) => readFileSync(join(auditDir, f), "utf8"))
+ .join("");
+ const lines = raw
+ .split("\n")
+ .filter((l) => l.trim().length > 0)
+ .map((l) => JSON.parse(l) as { action: string });
+ expect(lines.map((l) => l.action)).toContain(action);
+ expect(raw).not.toContain(VALUE_A);
+ expect(raw).not.toContain(PASSPHRASE);
+ }
+ });
+
+ test("an unknown bundle version or kdf algo refuses by name", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ for (const [field, mutate, code] of [
+ [
+ "version",
+ (b: Record<string, unknown>) => void (b["version"] = (b["version"] as number) + 1),
+ BUNDLE_REFUSAL_CODES.version,
+ ],
+ [
+ "algo",
+ (b: Record<string, unknown>) =>
+ void ((b["kdf"] as Record<string, unknown>)["algo"] = "argon2id"),
+ BUNDLE_REFUSAL_CODES.kdfAlgo,
+ ],
+ ] as const) {
+ const tampered = JSON.parse(JSON.stringify(bundle)) as Record<string, unknown>;
+ mutate(tampered);
+ try {
+ importSecretBundle(other, tampered, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ throw new Error(`expected the ${field} refusal`);
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(code);
+ }
+ }
+ expect(listSecrets(other)).toHaveLength(0);
+ });
+
+ test("a crafted kdf cost block refuses by name before scrypt allocates", () => {
+ seed(vault);
+ const bundle = exportSecretBundle(vault, PASSPHRASE, CTX);
+ // The bundle's kdf block rides in the clear, so a rewritten one is
+ // the same unbounded-cost knob a hand-edited keyfile envelope is;
+ // the same build curve bounds it.
+ const absurd = JSON.parse(JSON.stringify(bundle)) as Record<string, unknown>;
+ (absurd["kdf"] as Record<string, unknown>)["n"] = 2 ** 31;
+ (absurd["kdf"] as Record<string, unknown>)["maxmem"] = 10 ** 12;
+ try {
+ importSecretBundle(other, absurd, {
+ passphrase: PASSPHRASE,
+ replace: false,
+ agent: "tester",
+ now: LATER,
+ });
+ throw new Error("expected the kdf-cost refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretBundleError);
+ expect((err as SecretBundleError).code).toBe(BUNDLE_REFUSAL_CODES.kdfCost);
+ }
+ expect(listSecrets(other)).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/secrets/envelope.test.ts b/tests/core/brain/secrets/envelope.test.ts
new file mode 100644
index 00000000..b99ebb7c
--- /dev/null
+++ b/tests/core/brain/secrets/envelope.test.ts
@@ -0,0 +1,210 @@
+/**
+ * Passphrase-wrapped keyfile envelope (t_e6667a56): the raw 32-byte DEK
+ * at the keyfile path can be replaced by a versioned scrypt envelope that
+ * only a passphrase unwraps, with a process-local, memory-only unlock
+ * holder and named refusals for every failure shape.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { readdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ clearHeldKey,
+ ENVELOPE_REFUSAL_CODES,
+ heldKeyOrRefusal,
+ heldUnlockedKey,
+ isEnvelopeFile,
+ readEnvelope,
+ SecretEnvelopeError,
+ SecretStoreLockedError,
+ unlockKeyfile,
+ verifyKeyfilePassphrase,
+ wrapKeyfile,
+} from "../../../../src/core/brain/secrets/envelope.ts";
+import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
+import { secretsDir } from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
+
+const KEY_BYTES = 32;
+const PASSPHRASE = fakeCredential("wrap-pass", "phrase-", "42");
+const WRONG_PASSPHRASE = fakeCredential("wrong-pass", "phrase-", "42");
+
+let vault: string;
+let keyPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-envelope-"));
+ keyPath = join(secretsDir(vault), "keyfile");
+ loadOrCreateKey(keyPath);
+});
+
+afterEach(() => {
+ clearHeldKey(keyPath);
+ rmSync(vault, { recursive: true, force: true });
+});
+
+/** Every file under the vault, as path + bytes. */
+function vaultFiles(): ReadonlyArray<readonly [string, Buffer]> {
+ const out: Array<readonly [string, Buffer]> = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else out.push([abs, readFileSync(abs)]);
+ }
+ };
+ walk(vault);
+ return out;
+}
+
+describe("the keyfile envelope", () => {
+ test("wrap replaces the raw keyfile with the versioned envelope; the raw DEK never appears on disk", () => {
+ const dek = loadOrCreateKey(keyPath);
+ expect(dek.length).toBe(KEY_BYTES);
+
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+
+ const raw = readFileSync(keyPath);
+ expect(isEnvelopeFile(keyPath)).toBe(true);
+ const envelope = readEnvelope(keyPath);
+ expect(envelope.version).toBe(1);
+ expect(envelope.kdf.algo).toBe("scrypt");
+ expect(envelope.kdf.n).toBe(2 ** 15);
+ expect(envelope.kdf.r).toBe(8);
+ expect(envelope.kdf.p).toBe(1);
+ expect(envelope.kdf.maxmem).toBeGreaterThan(128 * 2 ** 15 * 8);
+ expect(Buffer.from(envelope.kdf.salt, "base64")).toHaveLength(16);
+ expect(envelope.wrapped.ciphertext.length).toBeGreaterThan(0);
+ // The envelope is a JSON document now, not 32 raw bytes, and the DEK
+ // bytes appear nowhere in it (the wrapped body is ciphertext under a
+ // key the passphrase derives).
+ expect(raw.length).not.toBe(KEY_BYTES);
+ expect(raw.includes(dek)).toBe(false);
+ // A fresh load sees the envelope, not the old raw file.
+ expect(() => loadOrCreateKey(keyPath)).toThrow(SecretStoreLockedError);
+ });
+
+ test("a wrong passphrase fails closed via the GCM tag with the named error", () => {
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+ clearHeldKey(keyPath);
+
+ expect(() => verifyKeyfilePassphrase(keyPath, WRONG_PASSPHRASE)).toThrow(SecretEnvelopeError);
+ try {
+ verifyKeyfilePassphrase(keyPath, WRONG_PASSPHRASE);
+ throw new Error("expected the passphrase refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretEnvelopeError);
+ expect((err as SecretEnvelopeError).code).toBe(ENVELOPE_REFUSAL_CODES.passphrase);
+ }
+ expect(heldUnlockedKey(keyPath)).toBeNull();
+ });
+
+ test("stored scrypt parameters round-trip; an unknown algo or version refuses by name", () => {
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+ const envelope = readEnvelope(keyPath);
+ expect(envelope.kdf.n).toBe(2 ** 15);
+ expect(envelope.kdf.r).toBe(8);
+ expect(envelope.kdf.p).toBe(1);
+
+ for (const [field, mutate, code] of [
+ [
+ "version",
+ (e: Record<string, unknown>) => void (e["version"] = (e["version"] as number) + 1),
+ ENVELOPE_REFUSAL_CODES.version,
+ ],
+ [
+ "algo",
+ (e: Record<string, unknown>) =>
+ void ((e["kdf"] as Record<string, unknown>)["algo"] = "argon2id"),
+ ENVELOPE_REFUSAL_CODES.kdfAlgo,
+ ],
+ ] as const) {
+ const tampered = JSON.parse(readFileSync(keyPath, "utf8")) as Record<string, unknown>;
+ mutate(tampered);
+ const path = join(secretsDir(vault), `tampered-${field}.json`);
+ writeFileSync(path, JSON.stringify(tampered));
+ try {
+ readEnvelope(path);
+ throw new Error(`expected the ${field} refusal`);
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretEnvelopeError);
+ expect((err as SecretEnvelopeError).code).toBe(code);
+ }
+ }
+ });
+
+ test("unlock populates the process-local holder; lock clears it; a second context sees the refusal", () => {
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+ clearHeldKey(keyPath);
+
+ expect(heldUnlockedKey(keyPath)).toBeNull();
+ const unlocked = unlockKeyfile(keyPath, PASSPHRASE);
+ expect(unlocked.equals(dek)).toBe(true);
+ expect(heldUnlockedKey(keyPath)!.equals(dek)).toBe(true);
+ // The operational loader now serves the held key without touching disk.
+ expect(loadOrCreateKey(keyPath).equals(dek)).toBe(true);
+
+ clearHeldKey(keyPath);
+ expect(heldUnlockedKey(keyPath)).toBeNull();
+ expect(() => heldKeyOrRefusal(keyPath)).toThrow(SecretStoreLockedError);
+ // A second context over the same vault (holder empty, envelope on
+ // disk) gets the named locked-store refusal, not a minted key.
+ expect(() => loadOrCreateKey(keyPath)).toThrow(SecretStoreLockedError);
+ });
+
+ test("a hand-edited envelope whose kdf cost exceeds this build's curve refuses by name", () => {
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+ // n = 2**31 would send scryptSync off to a terabyte-scale allocation
+ // before this fix: validation checked positivity only.
+ const absurd = JSON.parse(readFileSync(keyPath, "utf8")) as Record<string, unknown>;
+ (absurd["kdf"] as Record<string, unknown>)["n"] = 2 ** 31;
+ (absurd["kdf"] as Record<string, unknown>)["maxmem"] = 10 ** 12;
+ const absurdPath = join(secretsDir(vault), "tampered-absurd-cost.json");
+ writeFileSync(absurdPath, JSON.stringify(absurd));
+ try {
+ verifyKeyfilePassphrase(absurdPath, PASSPHRASE);
+ throw new Error("expected the kdf-cost refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretEnvelopeError);
+ expect((err as SecretEnvelopeError).code).toBe(ENVELOPE_REFUSAL_CODES.kdfCost);
+ }
+ // A stored maxmem SMALLER than the parameters' own need used to
+ // surface as node's raw "memory limit exceeded" instead of the named
+ // refusal.
+ const starved = JSON.parse(readFileSync(keyPath, "utf8")) as Record<string, unknown>;
+ (starved["kdf"] as Record<string, unknown>)["maxmem"] = 1024;
+ const starvedPath = join(secretsDir(vault), "tampered-starved-maxmem.json");
+ writeFileSync(starvedPath, JSON.stringify(starved));
+ try {
+ verifyKeyfilePassphrase(starvedPath, PASSPHRASE);
+ throw new Error("expected the kdf-cost refusal");
+ } catch (err) {
+ expect(err).toBeInstanceOf(SecretEnvelopeError);
+ expect((err as SecretEnvelopeError).code).toBe(ENVELOPE_REFUSAL_CODES.kdfCost);
+ }
+ });
+
+ test("the passphrase is never written anywhere under the vault", () => {
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, PASSPHRASE, dek);
+ unlockKeyfile(keyPath, PASSPHRASE);
+
+ for (const [, bytes] of vaultFiles()) {
+ expect(bytes.includes(PASSPHRASE)).toBe(false);
+ }
+ });
+
+ test("a never-wrapped store keeps today's raw keyfile behavior", () => {
+ const dek = loadOrCreateKey(keyPath);
+ expect(isEnvelopeFile(keyPath)).toBe(false);
+ // The second load returns the same bytes; the file stays 32 raw bytes.
+ expect(loadOrCreateKey(keyPath).equals(dek)).toBe(true);
+ expect(readFileSync(keyPath).length).toBe(KEY_BYTES);
+ });
+});
diff --git a/tests/core/brain/secrets/exec.test.ts b/tests/core/brain/secrets/exec.test.ts
index 562194d3..f2f88294 100644
--- a/tests/core/brain/secrets/exec.test.ts
+++ b/tests/core/brain/secrets/exec.test.ts
@@ -11,12 +11,17 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
+import {
+ SecretStoreLockedError,
+ wrapKeyfile,
+} from "../../../../src/core/brain/secrets/envelope.ts";
import {
matchesAllowlist,
runWithSecret,
SecretExecDeniedError,
} from "../../../../src/core/brain/secrets/exec.ts";
-import { setSecret } from "../../../../src/core/brain/secrets/store.ts";
+import { secretsDir, setSecret } from "../../../../src/core/brain/secrets/store.ts";
import { fakeCredential } from "../../../helpers/fake-credentials.ts";
const NOW = new Date("2026-06-05T10:00:00Z");
@@ -214,4 +219,27 @@ describe("runWithSecret", () => {
const result = await runWithSecret(vault, "api-key", ["bun", "-e", "process.exit(3)"], CTX);
expect(result.exitCode).toBe(3);
});
+
+ test("exec under a locked store refuses by name before the allowlist is consulted", async () => {
+ setSecret(vault, {
+ name: "api-key",
+ value: "sk-redact-me-12345",
+ allow: ["bun -e *"],
+ agent: "tester",
+ now: NOW,
+ });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(keyPath, fakeCredential("exec-wrap", "-phrase-", "42"), loadOrCreateKey(keyPath));
+ await expect(runWithSecret(vault, "api-key", ["echo", "hi"], CTX)).rejects.toThrow(
+ SecretStoreLockedError,
+ );
+ // No exec decision was reached, so no exec record lands: the refusal is
+ // the custody lock's, not the allowlist's.
+ const auditDir = join(vault, "Brain", "log", "secret-custody");
+ const raw = readdirSync(auditDir)
+ .map((f) => readFileSync(join(auditDir, f), "utf8"))
+ .join("");
+ expect(raw).not.toContain("secret_exec_started");
+ expect(raw).not.toContain("secret_exec_denied");
+ });
});
diff --git a/tests/core/brain/secrets/owner-acl.test.ts b/tests/core/brain/secrets/owner-acl.test.ts
index 24ab049b..5a2bac56 100644
--- a/tests/core/brain/secrets/owner-acl.test.ts
+++ b/tests/core/brain/secrets/owner-acl.test.ts
@@ -29,12 +29,14 @@ import {
system32Tool,
} from "../../../../src/core/brain/secrets/owner-acl.ts";
import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
+import { wrapKeyfile } from "../../../../src/core/brain/secrets/envelope.ts";
import {
custodyTargets,
listSecrets,
secretsDir,
setSecret,
} from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
import { IS_WINDOWS } from "../../../helpers/platform.ts";
const SID = "S-1-5-21-1111111111-2222222222-3333333333-1001";
@@ -244,6 +246,19 @@ describe.skipIf(!IS_WINDOWS)("the secrets keyfile ACL on Windows", () => {
expect(others(join(dir, "secrets.json"))).toEqual([]);
});
+ test("the wrapped keyfile grants the current user alone after the envelope replaces it", () => {
+ const dir = secretsDir(vault);
+ const keyPath = join(dir, "keyfile");
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, fakeCredential("acl-wrap", "-phrase-", "42"), dek);
+ const identity = currentWindowsIdentity();
+ expect(identity).not.toBeNull();
+ const principal = identity!.name.toLowerCase();
+ const entries = aclEntries(keyPath);
+ expect(lower(entries).filter((e) => e.includes("(i)"))).toEqual([]);
+ expect(withoutMachineAdmins(entries)).toEqual([`${principal}:(f)`]);
+ });
+
test("a failed icacls warns and leaves the caller running", () => {
const writes: string[] = [];
const spy = spyOn(process.stderr, "write").mockImplementation((chunk) => {
@@ -312,4 +327,12 @@ describe.skipIf(IS_WINDOWS)("keyfile modes and the sync-exclusion marker on POSI
loadOrCreateKey(join(secretsDir(vault), "keyfile"));
expect(readFileSync(marker, "utf8")).toBe("*\n!.gitignore\n");
});
+
+ test("the wrapped keyfile keeps owner-only modes after the envelope replaces it", () => {
+ const keyPath = join(secretsDir(vault), "keyfile");
+ const dek = loadOrCreateKey(keyPath);
+ wrapKeyfile(keyPath, fakeCredential("acl-wrap", "-phrase-", "42"), dek);
+ expect(statSync(keyPath).mode & 0o777).toBe(0o600);
+ expect(statSync(secretsDir(vault)).mode & 0o777).toBe(0o700);
+ });
});
diff --git a/tests/core/brain/secrets/store.test.ts b/tests/core/brain/secrets/store.test.ts
index 8ffaaeb2..70be2aad 100644
--- a/tests/core/brain/secrets/store.test.ts
+++ b/tests/core/brain/secrets/store.test.ts
@@ -7,17 +7,39 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import lockfile from "proper-lockfile";
+import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
+import {
+ clearHeldKey,
+ heldUnlockedKey,
+ isEnvelopeFile,
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+ unlockKeyfile,
+ wrapKeyfile,
+} from "../../../../src/core/brain/secrets/envelope.ts";
import {
listSecrets,
removeSecret,
resolveSecretForExec,
+ resolveSecretReadOnly,
setSecret,
secretsDir,
+ unlockSecretKeyfile,
} from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
import { IS_WINDOWS } from "../../../helpers/platform.ts";
const NOW = new Date("2026-06-05T10:00:00Z");
@@ -131,3 +153,175 @@ describe("setSecret / listSecrets / removeSecret", () => {
expect(JSON.stringify(lines)).not.toContain("sk-super-secret-value");
});
});
+
+describe("a wrapped store (t_e6667a56)", () => {
+ const PASSPHRASE = fakeCredential("store-wrap", "-phrase-", "42");
+
+ function wrap(): string {
+ const keyPath = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(keyPath, PASSPHRASE, loadOrCreateKey(keyPath));
+ return keyPath;
+ }
+
+ test("metadata stays readable while locked; every key-bearing op refuses by name", () => {
+ set();
+ const keyPath = wrap();
+ expect(listSecrets(vault)).toHaveLength(1);
+ expect(() =>
+ setSecret(vault, { name: "second", value: "v", agent: "tester", now: NOW }),
+ ).toThrow(SecretStoreLockedError);
+ expect(() => resolveSecretForExec(vault, "embed-key")).toThrow(SecretStoreLockedError);
+ expect(() => resolveSecretReadOnly(vault, "embed-key")).toThrow(SecretStoreLockedError);
+ expect(() => removeSecret(vault, "embed-key", { agent: "tester", now: NOW })).toThrow(
+ SecretStoreLockedError,
+ );
+ // Cleanup: the holder stays empty; clear is a no-op but explicit.
+ clearHeldKey(keyPath);
+ });
+
+ test("an unknown name fails without enumerating the stored set, even while locked", () => {
+ set();
+ wrap();
+ expect(() => resolveSecretReadOnly(vault, "ghost")).toThrow(/unknown secret "ghost"/);
+ expect(() => resolveSecretReadOnly(vault, "ghost")).not.toThrow(/embed-key/);
+ });
+
+ test("the read-only resolve decrypts without the last_used_at stamp or an exec audit record", () => {
+ set();
+ expect(resolveSecretReadOnly(vault, "embed-key").value).toBe("sk-super-secret-value");
+ const storeRaw = readFileSync(join(secretsDir(vault), "secrets.json"), "utf8");
+ expect(storeRaw).toContain('"last_used_at": null');
+ const auditDir = join(vault, "Brain", "log", "secret-custody");
+ const actions = readdirSync(auditDir)
+ .flatMap((f) => readFileSync(join(auditDir, f), "utf8").split("\n"))
+ .filter((l) => l.trim().length > 0)
+ .map((l) => (JSON.parse(l) as { action: string }).action);
+ expect(actions).not.toContain("secret_resolved_for_exec");
+ });
+
+ test("after unlock the held key serves both resolves; only the exec resolve stamps", () => {
+ set();
+ const keyPath = wrap();
+ unlockKeyfile(keyPath, PASSPHRASE);
+ expect(resolveSecretReadOnly(vault, "embed-key").value).toBe("sk-super-secret-value");
+ const unstamped = readFileSync(join(secretsDir(vault), "secrets.json"), "utf8");
+ expect(unstamped).toContain('"last_used_at": null');
+ expect(resolveSecretForExec(vault, "embed-key").value).toBe("sk-super-secret-value");
+ const stamped = readFileSync(join(secretsDir(vault), "secrets.json"), "utf8");
+ expect(stamped).not.toContain('"last_used_at": null');
+ clearHeldKey(keyPath);
+ });
+});
+
+describe("unlock/lock lifecycle", () => {
+ const PASSPHRASE = fakeCredential("lifecycle-wrap-", "phrase-3f08");
+
+ test("the FIRST unlock on a raw keyfile leaves this process unlocked", () => {
+ // The wrap-on-first-unlock writes the envelope but used to hold
+ // nothing: the same process - the one the verb's success note
+ // addresses, and the one the locked-store remedy sends to `unlock` -
+ // still read as locked afterwards.
+ set();
+ unlockSecretKeyfile(vault, PASSPHRASE, { agent: "tester", now: NOW });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ expect(isEnvelopeFile(keyPath)).toBe(true);
+ expect(heldUnlockedKey(keyPath)).not.toBeNull();
+ expect(resolveSecretReadOnly(vault, "embed-key").value).toBe("sk-super-secret-value");
+ clearHeldKey(keyPath);
+ });
+
+ test("the first-unlock wrap holds the store writer lock", () => {
+ // Every other read-modify-write of the custody directory serialises
+ // through the writer lock; the wrap that replaces the only copy of
+ // the DEK must too, so two racers cannot interleave on the shared
+ // tmp path. Holding the lock the way a concurrent first unlock
+ // would, the wrap refuses instead of proceeding.
+ set();
+ const release = lockfile.lockSync(secretsDir(vault), { stale: 10_000, realpath: false });
+ try {
+ expect(() => unlockSecretKeyfile(vault, PASSPHRASE, { agent: "tester", now: NOW })).toThrow(
+ /secrets store lock/,
+ );
+ expect(isEnvelopeFile(join(secretsDir(vault), "keyfile"))).toBe(false);
+ } finally {
+ void release();
+ }
+ // With the lock free, the same call wraps AND unlocks this process.
+ unlockSecretKeyfile(vault, PASSPHRASE, { agent: "tester", now: NOW });
+ expect(isEnvelopeFile(join(secretsDir(vault), "keyfile"))).toBe(true);
+ clearHeldKey(join(secretsDir(vault), "keyfile"));
+ });
+
+ test("a second unlock over the winner's envelope unlocks instead of failing locked", () => {
+ // The shape check re-runs UNDER the writer lock, so the loser of a
+ // wrap race - the keyfile it saw as raw is an envelope by the time it
+ // holds the lock - takes the unlock path with its own passphrase check
+ // rather than minting over the winner's envelope or refusing it
+ // locked. Sequenced here as the second of two awaited unlocks: the
+ // interleaving itself is pinned by the writer-lock test above.
+ set();
+ unlockSecretKeyfile(vault, PASSPHRASE, { agent: "tester", now: NOW });
+ // A second unlock over the now-wrapped store with the SAME
+ // passphrase succeeds and keeps the same key held.
+ unlockSecretKeyfile(vault, PASSPHRASE, { agent: "tester", now: NOW });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ expect(resolveSecretReadOnly(vault, "embed-key").value).toBe("sk-super-secret-value");
+ clearHeldKey(keyPath);
+ });
+
+ test("the locked-store refusal names the remedy without the keyfile path", () => {
+ // The refusal travels into model context through consumers that
+ // surface error prose (a config-probe error list, a search refusal);
+ // the path under the vault is exactly what
+ // `src/mcp/vault-path-field.ts` degrades to keep out. The remedy is
+ // named; the structured `keyPath` field stays for the callers that
+ // may name it.
+ set();
+ const keyPath = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(keyPath, PASSPHRASE, loadOrCreateKey(keyPath));
+ try {
+ let refusal: unknown;
+ try {
+ resolveSecretReadOnly(vault, "embed-key");
+ throw new Error("expected the locked-store refusal");
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal).toBeInstanceOf(SecretStoreLockedError);
+ const message = (refusal as Error).message;
+ expect(message).not.toContain(keyPath);
+ expect(message).toContain("o2b brain secret unlock");
+ } finally {
+ clearHeldKey(keyPath);
+ }
+ });
+
+ test("a missing keyfile over held entries refuses by name instead of minting", () => {
+ // The read-only resolve composes loadOrCreateKey, which CREATES a fresh
+ // key on first use. Over a store that still holds entries, that mint
+ // silently orphaned every stored value - the resolve answered a raw
+ // cipher error and left a new keyfile on disk, with nothing naming the
+ // destruction. The named refusal is the locked refusal's sibling state,
+ // and it must be equally path-free in the prose that travels into model
+ // context.
+ set();
+ const keyPath = join(secretsDir(vault), "keyfile");
+ const storeBefore = readFileSync(join(secretsDir(vault), "secrets.json"), "utf8");
+ rmSync(keyPath);
+ let refusal: unknown;
+ try {
+ resolveSecretReadOnly(vault, "embed-key");
+ throw new Error("expected the missing-keyfile refusal");
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal).toBeInstanceOf(SecretStoreKeyfileMissingError);
+ expect((refusal as { code: string }).code).toBe("secret_store_keyfile_missing");
+ const message = (refusal as Error).message;
+ expect(message).not.toContain(keyPath);
+ // The refusal left no custody state behind: no keyfile was minted, and
+ // the stored ciphertext is exactly as it was.
+ expect(existsSync(keyPath)).toBe(false);
+ expect(readFileSync(join(secretsDir(vault), "secrets.json"), "utf8")).toBe(storeBefore);
+ });
+});
diff --git a/tests/core/brain/secrets/sync-exposure.test.ts b/tests/core/brain/secrets/sync-exposure.test.ts
index 48eda222..ebf3115a 100644
--- a/tests/core/brain/secrets/sync-exposure.test.ts
+++ b/tests/core/brain/secrets/sync-exposure.test.ts
@@ -12,6 +12,7 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
+ readdirSync,
readFileSync,
realpathSync,
rmSync,
@@ -24,8 +25,12 @@ import { join } from "node:path";
import { runDoctor } from "../../../../src/core/brain/doctor.ts";
import { SECRETS_SYNC_EXPOSED_CODE } from "../../../../src/core/brain/doctor/secrets-sync-check.ts";
import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
-import { secretsSyncExposure } from "../../../../src/core/brain/secrets/sync-exposure.ts";
+import {
+ formatWrappedKeyfileExposure,
+ secretsSyncExposure,
+} from "../../../../src/core/brain/secrets/sync-exposure.ts";
import { secretsDir } from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
import { runCli } from "../../../helpers/run-cli.ts";
let tmp: string;
@@ -145,6 +150,45 @@ test("secret set warns on stderr when a Syncthing folder would carry the keyfile
expect(again.stderr).not.toContain(".stignore");
});
+describe("wrapped-keyfile messaging (t_e6667a56)", () => {
+ test("the wrapped message names the passphrase as the only protection left on a peer", () => {
+ const message = formatWrappedKeyfileExposure({
+ folderRoot: join(tmp, "sync"),
+ stignorePath: join(tmp, "sync", ".stignore"),
+ suggestedPattern: "/.open-second-brain/secrets",
+ });
+ expect(message).toContain("passphrase");
+ expect(message).toContain(".stignore");
+ expect(message).toContain("/.open-second-brain/secrets");
+ });
+
+ test("unlock warns when a Syncthing folder would carry the wrapped keyfile", async () => {
+ syncthingFolder(vault, null);
+ const set = await runCli(["brain", "secret", "set", "api-key", "--vault", vault], {
+ stdin: "sk-sync-wrap-1\n",
+ });
+ expect(set.returncode).toBe(0);
+ const passphrase = fakeCredential("wrap-pass", "-sync", "-42");
+ const unlock = await runCli(["brain", "secret", "unlock", "--vault", vault], {
+ stdin: `${passphrase}\n`,
+ });
+ expect(unlock.returncode).toBe(0);
+ expect(unlock.stderr).toContain("passphrase-wrapped");
+ expect(unlock.stderr).toContain(".stignore");
+ expect(existsSync(join(vault, ".stignore"))).toBe(false);
+ // And a peer holding the wrapped keyfile has the ciphertext only: the
+ // passphrase itself appears nowhere on disk.
+ const walk = (dir: string): string =>
+ readdirSync(dir, { withFileTypes: true })
+ .map((e) => {
+ const abs = join(dir, e.name);
+ return e.isDirectory() ? walk(abs) : readFileSync(abs, "utf8");
+ })
+ .join("");
+ expect(walk(vault)).not.toContain(passphrase);
+ });
+});
+
describe("a vault reached through a symbolic link", () => {
// Syncthing walks real directories. A vault opened as `<tmp>/linked`,
// a link to `<tmp>/sync/notes/vault` inside a Syncthing folder, is
diff --git a/tests/core/brain/tag-syntax.test.ts b/tests/core/brain/tag-syntax.test.ts
new file mode 100644
index 00000000..468958cd
--- /dev/null
+++ b/tests/core/brain/tag-syntax.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Tag syntax helper (trust-surface-hardening wave; kanban t_11ee559f).
+ *
+ * The write-time predicate judges a composed tag VALUE against the ONE
+ * shared rule defined in `src/core/tags.ts` (`isObsidianTagValue`,
+ * derived from `TAG_RE`). These tests pin three things:
+ *
+ * 1. the rule itself: `/` nesting accepted, spaces and other specials
+ * rejected, leading slash rejected, pure-numeric values rejected;
+ * 2. the predicate is DERIVED from the index rule, not a parallel
+ * spelling: over a battery of values it agrees exactly with what
+ * `TAG_RE` captures, and `tag-syntax.ts` imports the shared
+ * predicate rather than redefining it;
+ * 3. the typed refusal is shaped like `SchemaVocabularyError`: a stable
+ * error name plus structured `field` / `token`, the field named so
+ * a caller knows which input to fix.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { TAG_RE, isObsidianTagValue as sharedPredicate } from "../../../src/core/tags.ts";
+import {
+ TagSyntaxError,
+ isObsidianTagValue,
+ requireObsidianTagValue,
+} from "../../../src/core/brain/tag-syntax.ts";
+
+describe("isObsidianTagValue — the one shared rule", () => {
+ test("accepts plain, nested, and underscore-onset values", () => {
+ expect(isObsidianTagValue("brain")).toBe(true);
+ expect(isObsidianTagValue("brain/signal")).toBe(true);
+ expect(isObsidianTagValue("a/b/c")).toBe(true);
+ expect(isObsidianTagValue("_under")).toBe(true);
+ expect(isObsidianTagValue("Foo_1-b/c")).toBe(true);
+ });
+
+ test("rejects spaces and other specials", () => {
+ expect(isObsidianTagValue("foo bar")).toBe(false);
+ expect(isObsidianTagValue("foo bar/baz")).toBe(false);
+ expect(isObsidianTagValue("foo.bar")).toBe(false);
+ expect(isObsidianTagValue("foo+bar")).toBe(false);
+ expect(isObsidianTagValue("")).toBe(false);
+ });
+
+ test("rejects a leading slash and pure-numeric values", () => {
+ expect(isObsidianTagValue("/leading")).toBe(false);
+ expect(isObsidianTagValue("2024")).toBe(false);
+ expect(isObsidianTagValue("2024-notes")).toBe(false);
+ });
+
+ test("the predicate agrees exactly with what TAG_RE captures (derived, not copied)", () => {
+ const battery = [
+ "brain",
+ "brain/signal",
+ "a/b/c",
+ "_under",
+ "Foo_1-b/c",
+ "foo bar",
+ "foo bar/baz",
+ "foo.bar",
+ "/leading",
+ "2024",
+ "2024-notes",
+ "",
+ "trail-",
+ "UPPER",
+ ];
+ for (const value of battery) {
+ const match = TAG_RE.exec(`x #${value}`);
+ TAG_RE.lastIndex = 0;
+ const captured = match !== null && match[2] === value;
+ expect(isObsidianTagValue(value)).toBe(captured);
+ }
+ });
+});
+
+describe("the predicate is shared, never redefined", () => {
+ test("tag-syntax.ts hands back the very function src/core/tags.ts defines", () => {
+ expect(isObsidianTagValue).toBe(sharedPredicate);
+ });
+
+ test("source shape: tag-syntax.ts imports the rule and spells no rule of its own", () => {
+ const source = readFileSync(
+ join(import.meta.dir, "../../../src/core/brain/tag-syntax.ts"),
+ "utf8",
+ );
+ expect(source).toMatch(/from "\.\.\/tags\.ts"/);
+ // A redefinition would need either a regex construction or the
+ // index rule's own onset charset; neither may appear here.
+ expect(source).not.toContain("new RegExp");
+ expect(source).not.toContain("[A-Za-z_]");
+ });
+});
+
+describe("requireObsidianTagValue / TagSyntaxError", () => {
+ test("a valid value passes through unchanged", () => {
+ expect(requireObsidianTagValue("brain/topic/x", "topic")).toBe("brain/topic/x");
+ });
+
+ test("an invalid value throws with the error name and the field named", () => {
+ let thrown: unknown;
+ try {
+ requireObsidianTagValue("foo bar", "extraTags");
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(TagSyntaxError);
+ const err = thrown as TagSyntaxError;
+ expect(err.name).toBe("TagSyntaxError");
+ expect(err.field).toBe("extraTags");
+ expect(err.token).toBe("foo bar");
+ // The message names the FIELD and the rule; the offending token rides
+ // the structured `token` property (SchemaVocabularyError's shape).
+ expect(err.message).toBe(
+ "extraTags: must start with a letter or underscore and contain only " +
+ "letters, numbers, dashes, underscores, or slashes (never only digits)",
+ );
+ });
+});
diff --git a/tests/core/brain/upgrade-drift.test.ts b/tests/core/brain/upgrade-drift.test.ts
index 59fd4e98..9fa30f19 100644
--- a/tests/core/brain/upgrade-drift.test.ts
+++ b/tests/core/brain/upgrade-drift.test.ts
@@ -26,8 +26,10 @@ import {
BrainUpgradeError,
applyUpgrade,
planUpgrade,
+ type UpgradeFilePlan,
type UpgradePlan,
} from "../../../src/core/brain/upgrade.ts";
+import { sealWithDigest } from "../../../src/core/integrity/digest.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
let vault: string;
@@ -65,6 +67,16 @@ function snapshotCount(): number {
return listSnapshots(vault).snapshots.length;
}
+/**
+ * A plan a caller recomputed for its own rows: the body changes, so the
+ * seal must be recomputed with it. This is what an honest caller does;
+ * the seal test below covers the dishonest one who skips it.
+ */
+function reseal(plan: UpgradePlan, files: ReadonlyArray<UpgradeFilePlan>): UpgradePlan {
+ const { digest: _stale, ...body } = plan;
+ return Object.freeze(sealWithDigest({ ...body, files: Object.freeze(files) }));
+}
+
/**
* A plan with both managed files pending: a stale manual, and a config with
* its trailing `snapshots:` block cut. The cut pins the default layout, so
@@ -132,12 +144,12 @@ describe("applyUpgrade applies the plan it is handed", () => {
test("the given plan's bytes are written, not a re-plan", () => {
writeFileSync(brainManualPath(vault), "stale\n");
const plan = planUpgrade(vault);
- const shown: UpgradePlan = Object.freeze({
- ...plan,
- files: plan.files.map((f) =>
+ const shown = reseal(
+ plan,
+ plan.files.map((f) =>
f.path === "Brain/_BRAIN.md" ? Object.freeze({ ...f, after: "the shown body\n" }) : f,
),
- });
+ );
const res = applyUpgrade(vault, { plan: shown, agent: "test-agent" });
expect(res.files_updated).toEqual(["Brain/_BRAIN.md"]);
expect(readFileSync(brainManualPath(vault), "utf8")).toBe("the shown body\n");
@@ -186,6 +198,53 @@ describe("a managed file holding invalid UTF-8", () => {
});
});
+describe("a caller-supplied plan that does not verify (t_18fda844)", () => {
+ test("a tampered plan is refused by its seal BEFORE the byte-drift check", () => {
+ writeFileSync(brainManualPath(vault), "stale\n");
+ const plan = planUpgrade(vault);
+ // The plan was edited after it was sealed and never re-sealed: the
+ // carried digest describes a different body.
+ const { digest: _carried, ...body } = plan;
+ const tampered: UpgradePlan = Object.freeze({
+ ...body,
+ files: body.files.map((f) =>
+ f.path === "Brain/_BRAIN.md" ? Object.freeze({ ...f, after: "tampered\n" }) : f,
+ ),
+ digest: plan.digest,
+ });
+ // Real disk drift too, so the ORDER of the two refusals is what the
+ // assertion observes: the seal is checked first.
+ writeFileSync(brainManualPath(vault), "hand edit after the plan\n");
+ const before = snapshotCount();
+
+ const err = upgradeError(() => applyUpgrade(vault, { plan: tampered, agent: "test-agent" }));
+
+ expect(err.runId).toBeNull();
+ expect(err.drifted).toEqual([]);
+ expect(err.message).toContain("digest");
+ expect(err.message).not.toContain("changed on disk");
+ expect(err.message).toContain("o2b brain upgrade --dry-run");
+ expect(snapshotCount()).toBe(before);
+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("hand edit after the plan\n");
+ });
+
+ test("a plan whose digest is missing is refused the same way", () => {
+ writeFileSync(brainManualPath(vault), "stale\n");
+ const plan = planUpgrade(vault);
+ const { digest: _none, ...unsealed } = plan;
+ const before = snapshotCount();
+
+ const err = upgradeError(() =>
+ applyUpgrade(vault, { plan: unsealed as UpgradePlan, agent: "test-agent" }),
+ );
+
+ expect(err.runId).toBeNull();
+ expect(err.message).toContain("digest");
+ expect(snapshotCount()).toBe(before);
+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("stale\n");
+ });
+});
+
describe("drift found before the snapshot", () => {
test("a hand edit after the plan refuses with drifted, no snapshot, the edit survives", () => {
writeFileSync(brainManualPath(vault), "stale\n");
diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.ts
index b7cfff7c..24b20086 100644
--- a/tests/core/brain/upgrade.test.ts
+++ b/tests/core/brain/upgrade.test.ts
@@ -17,6 +17,7 @@ import { join } from "node:path";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { applyUpgrade, mergeBrainYaml, planUpgrade } from "../../../src/core/brain/upgrade.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { digestVerifies } from "../../../src/core/integrity/digest.ts";
import { brainConfigPath, brainManualPath } from "../../../src/core/brain/paths.ts";
import { listSnapshots } from "../../../src/core/brain/snapshot.ts";
@@ -149,6 +150,16 @@ describe("planUpgrade", () => {
}
});
+ test("the plan is sealed: its digest describes exactly its own body (t_18fda844)", () => {
+ const plan = planUpgrade(vault);
+ expect(plan.digest).toMatch(/^[0-9a-f]{64}$/);
+ const { digest: _digest, ...body } = plan;
+ expect(digestVerifies(body, plan.digest)).toBe(true);
+ // The seal binds the plan content, not the moment it was planned.
+ const replan = planUpgrade(vault);
+ expect(replan.digest).toBe(plan.digest);
+ });
+
test("file ordering is _brain.yaml, _BRAIN.md", () => {
const plan = planUpgrade(vault);
expect(plan.files.map((f) => f.path)).toEqual(["Brain/_brain.yaml", "Brain/_BRAIN.md"]);
diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.ts
index a0f16c04..3454cc38 100644
--- a/tests/core/brain/vault-guard-census.test.ts
+++ b/tests/core/brain/vault-guard-census.test.ts
@@ -103,6 +103,11 @@ const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({
"src/core/brain/secrets/crypto.ts":
"takes a keyfile path, not a vault. The three public entry points in " +
"`secrets/store.ts` that reach it are guarded ahead of their first byte.",
+ "src/core/brain/secrets/envelope.ts":
+ "takes a keyfile path, not a vault, like its sibling `crypto.ts`. The " +
+ "vault-level entry points in `secrets/store.ts` that reach it (the " +
+ "wrap-on-first-unlock and the lock) are guarded ahead of their first " +
+ "byte, and the holder lookups write nothing at all.",
"src/core/brain/sync-lockfile.ts":
"lock primitive over a caller-supplied path; the writers that acquire it " +
"are guarded at their own entry points.",
diff --git a/tests/core/brain/vault-identity.test.ts b/tests/core/brain/vault-identity.test.ts
index a05f5915..b5fe9416 100644
--- a/tests/core/brain/vault-identity.test.ts
+++ b/tests/core/brain/vault-identity.test.ts
@@ -45,6 +45,7 @@ import {
import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
import { appendEditHistory } from "../../../src/core/brain/health/edit-history.ts";
import { recordThesis } from "../../../src/core/brain/health/thesis.ts";
+import { exportSecretBundle, importSecretBundle } from "../../../src/core/brain/secrets/bundle.ts";
import { applyHygienePlan } from "../../../src/core/brain/hygiene/apply.ts";
import type { HygienePlan } from "../../../src/core/brain/hygiene/plan.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
@@ -78,10 +79,13 @@ import { writeRollupLedger } from "../../../src/core/brain/rollup-ladder.ts";
import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
import { applySchemaMutations } from "../../../src/core/brain/schema-mutate.ts";
import {
+ lockSecretKeyfile,
removeSecret,
resolveSecretForExec,
setSecret,
+ unlockSecretKeyfile,
} from "../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
import { writeSignal } from "../../../src/core/brain/signal.ts";
import { retireSignal } from "../../../src/core/brain/signal-retire.ts";
import { learnSkillProposals } from "../../../src/core/brain/skill-proposals.ts";
@@ -267,6 +271,12 @@ describe("the guard fires on Brain write paths", () => {
now: NOW,
} as const;
+ const WRAP_PASSPHRASE = fakeCredential("guard-wrap", "-phrase-", "42");
+ const BUNDLE_PASSPHRASE = fakeCredential("guard-bundle", "-phrase-", "42");
+
+ /** The bundle the importGuard entry hands to the writer, built in the seed. */
+ let bundleForGuard: ReturnType<typeof exportSecretBundle>;
+
const GUARD_PAGE_REL = posix.join("notes", "guard-page.md");
function guardPagePath(vaultRoot: string): string {
@@ -637,6 +647,48 @@ describe("the guard fires on Brain write paths", () => {
write: (v) =>
void resolveSecretForExec(v, SECRET_INPUT.name, { agent: "test-agent", now: NOW }),
},
+ {
+ // The wrap-on-first-unlock conversion: writes the envelope over the
+ // raw keyfile and lands the unlock custody record.
+ name: "unlockSecretKeyfile",
+ seed: (v) => void setSecret(v, SECRET_INPUT),
+ write: (v) => void unlockSecretKeyfile(v, WRAP_PASSPHRASE, { agent: "test-agent", now: NOW }),
+ },
+ {
+ // lock clears the holder and lands the locked custody record; on a
+ // never-wrapped store the refusal still comes from the guard, ahead
+ // of any keyfile read.
+ name: "lockSecretKeyfile",
+ write: (v) => void lockSecretKeyfile(v, { agent: "test-agent", now: NOW }),
+ },
+ {
+ // The bundle export appends its custody record and reads ciphertext;
+ // the guard sits ahead of the first byte.
+ name: "exportSecretBundle",
+ seed: (v) => void setSecret(v, SECRET_INPUT),
+ write: (v) =>
+ void exportSecretBundle(v, BUNDLE_PASSPHRASE, { agent: "test-agent", now: NOW }),
+ },
+ {
+ // The bundle import writes entries under the store's lock and lands
+ // its custody record. The bundle itself is built in the seed, so the
+ // write's first byte is the import's, not the export's.
+ name: "importSecretBundle",
+ seed: (v) => {
+ setSecret(v, SECRET_INPUT);
+ bundleForGuard = exportSecretBundle(v, BUNDLE_PASSPHRASE, {
+ agent: "test-agent",
+ now: NOW,
+ });
+ },
+ write: (v) =>
+ void importSecretBundle(v, bundleForGuard, {
+ passphrase: BUNDLE_PASSPHRASE,
+ replace: true,
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
{
name: "applySchemaMutations",
write: async (v) => {
diff --git a/tests/core/config-telegram-capture.test.ts b/tests/core/config-telegram-capture.test.ts
index b9a10855..1c3ac2ac 100644
--- a/tests/core/config-telegram-capture.test.ts
+++ b/tests/core/config-telegram-capture.test.ts
@@ -5,20 +5,30 @@
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { setSecret } from "../../src/core/brain/secrets/store.ts";
import { resolveTelegramBotToken, resolveTelegramCaptureAllowlist } from "../../src/core/config.ts";
import { redactConfigMapping } from "../../src/core/egress/guard.ts";
+import { SecretReferenceError } from "../../src/core/secret-ref.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+// The entry scripts load the named-secret resolver at startup, which is
+// what fills config's resolver port; the `$secret:` cases below need the
+// same wiring in this process.
+import "../../src/core/secret-resolver.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
let tmp: string;
+let custodyVault: string;
const saved: Record<string, string | undefined> = {};
const ENV_KEYS = ["TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ALLOWLIST"] as const;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), "o2b-telegram-config-"));
+ custodyVault = mkdtempSync(join(tmpdir(), "o2b-telegram-custody-"));
+ mkdirSync(join(custodyVault, "Brain"), { recursive: true });
for (const k of ENV_KEYS) {
saved[k] = process.env[k];
delete process.env[k];
@@ -27,6 +37,7 @@ beforeEach(() => {
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
+ rmSync(custodyVault, { recursive: true, force: true });
for (const k of ENV_KEYS) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
@@ -75,3 +86,52 @@ test("redactConfigMapping hides the bot token but keeps the allowlist", () => {
expect(out["telegram_bot_token"]).toBe(REDACTION_PLACEHOLDER);
expect(out["telegram_chat_allowlist"]).toBe("100");
});
+
+const STORED_TOKEN_REF = "$secret:telegram_bot_token";
+const ABSENT_TOKEN_REF = "$secret:absent_name";
+
+// ----- Token through the custody store (trust-surface-hardening, B2) ---------
+//
+// A token written as a `$secret:NAME` reference resolves through the vault's
+// custody store when the caller passes it; plain tokens keep today's path
+// byte-identically, and an unresolvable reference refuses with the named
+// resolver error instead of silently starting with the reference string.
+
+const STORED_TOKEN = fakeCredential("stored-", "tg-token-61be");
+const TOKEN_NOW = new Date("2026-06-05T10:00:00Z");
+
+function storeBotToken(): void {
+ setSecret(custodyVault, {
+ name: "telegram_bot_token",
+ value: STORED_TOKEN,
+ agent: "tester",
+ now: TOKEN_NOW,
+ });
+}
+
+test("a reference token resolves through the custody store from config", () => {
+ storeBotToken();
+ expect(
+ resolveTelegramBotToken(cfg(`telegram_bot_token: "${STORED_TOKEN_REF}"\n`), custodyVault),
+ ).toBe(STORED_TOKEN);
+});
+
+test("a reference token resolves through the custody store from env", () => {
+ storeBotToken();
+ process.env["TELEGRAM_BOT_TOKEN"] = STORED_TOKEN_REF;
+ expect(resolveTelegramBotToken(cfg("vault: /x\n"), custodyVault)).toBe(STORED_TOKEN);
+});
+
+test("a plain token keeps resolving byte-identically with a custody vault passed", () => {
+ expect(resolveTelegramBotToken(cfg("telegram_bot_token: abc123\n"), custodyVault)).toBe("abc123");
+ process.env["TELEGRAM_BOT_TOKEN"] = "env-token";
+ expect(resolveTelegramBotToken(cfg("telegram_bot_token: abc123\n"), custodyVault)).toBe(
+ "env-token",
+ );
+});
+
+test("an unresolvable reference token refuses with the named resolver error", () => {
+ expect(() =>
+ resolveTelegramBotToken(cfg(`telegram_bot_token: "${ABSENT_TOKEN_REF}"\n`), custodyVault),
+ ).toThrow(SecretReferenceError);
+});
diff --git a/tests/core/config.installation-secret.test.ts b/tests/core/config.installation-secret.test.ts
index 0ef2c8db..dd7b09a3 100644
--- a/tests/core/config.installation-secret.test.ts
+++ b/tests/core/config.installation-secret.test.ts
@@ -10,11 +10,18 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
-import { createHmac } from "node:crypto";
+import { createHmac, randomBytes } from "node:crypto";
import { join, resolve } from "node:path";
+import { setSecret, secretsDir } from "../../src/core/brain/secrets/store.ts";
+import { loadOrCreateKey } from "../../src/core/brain/secrets/crypto.ts";
+import {
+ clearHeldKey,
+ SecretStoreLockedError,
+ wrapKeyfile,
+} from "../../src/core/brain/secrets/envelope.ts";
import {
INSTALLATION_SECRET_ENV_KEY,
isValidInstallationSecret,
@@ -23,6 +30,15 @@ import {
VAULT_STORE_REF_PREFIX,
} from "../../src/core/config.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { SecretReferenceError } from "../../src/core/secret-ref.ts";
+// The entry scripts load the named-secret resolver at startup, which is
+// what fills config's resolver port; the `$secret:` cases below need the
+// same wiring in this process.
+import "../../src/core/secret-resolver.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const INSTALLED_REF = "$secret:installation_secret";
+const ABSENT_REF = "$secret:absent_name";
/** A stored value of the wrong shape: not 32 lowercase hex characters. */
const CORRUPT_VALUE = "not-a-valid-secret";
@@ -33,6 +49,7 @@ let configHome: string;
let configPath: string;
let savedSecret: string | undefined;
let savedDeviceId: string | undefined;
+const custodyVaults: string[] = [];
beforeEach(() => {
configHome = mkdtempSync(join(tmpdir(), "o2b-install-secret-"));
@@ -44,6 +61,7 @@ beforeEach(() => {
afterEach(() => {
rmSync(configHome, { recursive: true, force: true });
+ for (const vault of custodyVaults.splice(0)) rmSync(vault, { recursive: true, force: true });
if (savedSecret === undefined) delete process.env[INSTALLATION_SECRET_ENV_KEY];
else process.env[INSTALLATION_SECRET_ENV_KEY] = savedSecret;
if (savedDeviceId === undefined) delete process.env["O2B_DEVICE_ID"];
@@ -96,6 +114,84 @@ describe("resolveInstallationSecret", () => {
expect(isValidInstallationSecret("0123456789ABCDEF0123456789ABCDEF")).toBe(false); // uppercase
expect(isValidInstallationSecret("0123456789abcdef0123456789abcdefff")).toBe(false); // too long
});
+
+ // ----- Reference routing (trust-surface-hardening, t_e5807974 / B2) --------
+ //
+ // A persisted value written as a `$secret:NAME` reference resolves through
+ // the custody store of the vault the caller passes. Plain values keep
+ // today's path byte-identically, and an unresolvable reference refuses
+ // with the named resolver error instead of self-healing a fresh key over
+ // the reference (which would silently change every vault:// reference).
+ describe("reference routing", () => {
+ const STORED_KEY = randomBytes(16).toString("hex");
+ const NOW = new Date("2026-06-05T10:00:00Z");
+
+ function storeInstallationKey(value: string = STORED_KEY): string {
+ const vault = mkdtempSync(join(tmpdir(), "o2b-install-custody-"));
+ custodyVaults.push(vault);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ setSecret(vault, {
+ name: "installation_secret",
+ value,
+ agent: "tester",
+ now: NOW,
+ });
+ return vault;
+ }
+
+ test("a reference value resolves through the custody store", () => {
+ const vault = storeInstallationKey();
+ atomicWriteFileSync(configPath, `installation_secret: "${INSTALLED_REF}"\n`);
+ expect(resolveInstallationSecret(configPath, vault)).toBe(STORED_KEY);
+ });
+
+ test("an unresolvable reference refuses with the named error, never self-heals", () => {
+ const vault = storeInstallationKey();
+ atomicWriteFileSync(configPath, `installation_secret: "${ABSENT_REF}"\n`);
+ expect(() => resolveInstallationSecret(configPath, vault)).toThrow(SecretReferenceError);
+ // The reference is still in the config: no fresh key was written over it.
+ expect(readFileSync(configPath, "utf8")).toContain("absent_name");
+ });
+
+ test("a reference that resolves to a non-key value refuses by name, never self-heals", () => {
+ // The reference RESOLVES - the store answers - but what it answers
+ // is not a 32-hex key. This is the case the shipped code got wrong:
+ // the invalid value read as a miss and the self-heal minted a fresh
+ // key over the persisted reference.
+ const vault = storeInstallationKey("not-a-32-hex-key");
+ atomicWriteFileSync(configPath, `installation_secret: "${INSTALLED_REF}"\n`);
+ expect(() => resolveInstallationSecret(configPath, vault)).toThrow(SecretReferenceError);
+ // The reference survives untouched, and the HMAC input never rotated.
+ expect(readFileSync(configPath, "utf8")).toContain("$secret:installation_secret");
+ });
+
+ test("a persisted reference refuses by name when no vault is available, never self-heals", () => {
+ // The exported signature allows omitting the vault; that must turn
+ // into the named refusal, not into a fresh key over the reference.
+ atomicWriteFileSync(configPath, `installation_secret: "${INSTALLED_REF}"\n`);
+ expect(() => resolveInstallationSecret(configPath)).toThrow(SecretReferenceError);
+ expect(readFileSync(configPath, "utf8")).toContain("$secret:installation_secret");
+ });
+
+ test("a reference that resolves to a locked store-held key refuses by name", () => {
+ const vault = storeInstallationKey();
+ // Wrap the keyfile and drop this process's holder: the store is
+ // locked, so the reference cannot resolve.
+ const kp = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(kp, fakeCredential("install-wrap-", "phrase-8e31"), loadOrCreateKey(kp));
+ clearHeldKey(kp);
+ atomicWriteFileSync(configPath, `installation_secret: "${INSTALLED_REF}"\n`);
+ expect(() => resolveInstallationSecret(configPath, vault)).toThrow(SecretStoreLockedError);
+ expect(readFileSync(configPath, "utf8")).toContain("$secret:installation_secret");
+ });
+
+ test("plain values keep resolving byte-identically with a vault passed", () => {
+ const vault = storeInstallationKey();
+ const secret = resolveInstallationSecret(configPath);
+ expect(resolveInstallationSecret(configPath, vault)).toBe(secret);
+ expect(secret).toMatch(HEX32);
+ });
+ });
});
describe("vaultStoreReference (keyed HMAC)", () => {
@@ -145,4 +241,22 @@ describe("vaultStoreReference (keyed HMAC)", () => {
expect(withEmptyDevice).toBe(withRealDevice);
expect(withEmptyDevice).toBe(KAT_REF);
});
+
+ test("threads the referenced vault so a reference key resolves through its custody store", () => {
+ const vault = mkdtempSync(join(tmpdir(), "o2b-install-custody-"));
+ custodyVaults.push(vault);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const storedKey = randomBytes(16).toString("hex");
+ setSecret(vault, {
+ name: "installation_secret",
+ value: storedKey,
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+ atomicWriteFileSync(configPath, `installation_secret: "${INSTALLED_REF}"\n`);
+ const expected =
+ VAULT_STORE_REF_PREFIX +
+ createHmac("sha256", storedKey).update(resolve(vault)).digest("hex").slice(0, 32);
+ expect(vaultStoreReference(vault, configPath)).toBe(expected);
+ });
});
diff --git a/tests/core/decision-model/config.test.ts b/tests/core/decision-model/config.test.ts
index b79083ee..b2d68e1d 100644
--- a/tests/core/decision-model/config.test.ts
+++ b/tests/core/decision-model/config.test.ts
@@ -13,8 +13,20 @@ import {
decisionModelModeFor,
resolveDecisionModelConfig,
} from "../../../src/core/decision-model/config.ts";
+import { setSecret, secretsDir } from "../../../src/core/brain/secrets/store.ts";
+import {
+ clearHeldKey,
+ SecretStoreLockedError,
+ wrapKeyfile,
+} from "../../../src/core/brain/secrets/envelope.ts";
+import { loadOrCreateKey } from "../../../src/core/brain/secrets/crypto.ts";
+import { SecretReferenceError } from "../../../src/core/secret-ref.ts";
+import { makeDecisionProvider } from "../../../src/core/decision-model/provider.ts";
+import { buildDecisionModelCheck } from "../../../src/core/decision-model/diagnostics.ts";
+import type { DecisionRequest } from "../../../src/core/decision-model/contract.ts";
import { loadBrainConfigDetailed } from "../../../src/core/brain/policy.ts";
-import { FAKE_DECISION_KEY } from "../../helpers/fake-credentials.ts";
+import { startFakeSystemOne } from "../../helpers/fake-decision-provider.ts";
+import { FAKE_DECISION_KEY, fakeCredential } from "../../helpers/fake-credentials.ts";
const KEY_VAR = "O2B_TEST_DECISION_MODEL_KEY";
const ENABLED = {
@@ -254,3 +266,280 @@ describe("vault opt-out", () => {
expect(cfg.status).toBe("disabled_by_vault");
});
});
+
+// ----- Key resolution through the custody store (t_e5807974 / B2) ------------
+//
+// The value of the variable `decision_model_env_key` names may itself be a
+// `$secret:NAME` reference; with `secretsVault` set it resolves through the
+// custody store at resolution time. Resolution still never throws: an
+// unresolvable reference lands in `errors` (status `invalid`) instead of
+// silently reading as an unset key, and a plain value keeps today's path.
+
+describe("decision-model key through the custody store", () => {
+ const STORED_DM_KEY = fakeCredential("stored-dm-", "key-88ac");
+ const REF_VALUE = "$secret:dm_key";
+ const NOW = new Date("2026-06-05T10:00:00Z");
+
+ function tempCustodyVault(): string {
+ const vault = mkdtempSync(join(tmpdir(), "osb-dm-custody-"));
+ dirs.push(vault);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ return vault;
+ }
+
+ test("a reference as the key value resolves through the store and activates", () => {
+ const vault = tempCustodyVault();
+ setSecret(vault, { name: "dm_key", value: STORED_DM_KEY, agent: "tester", now: NOW });
+ const cfg = resolveDecisionModelConfig({
+ env: { [KEY_VAR]: REF_VALUE } as NodeJS.ProcessEnv,
+ config: ENABLED,
+ vault: null,
+ secretsVault: vault,
+ });
+ expect(cfg.status).toBe("active");
+ expect(cfg.keyPresent).toBe(true);
+ expect(cfg.errors).toEqual([]);
+ });
+
+ test("a plain key value keeps resolving exactly as before", () => {
+ const vault = tempCustodyVault();
+ const without = resolveDecisionModelConfig({ env: WITH_KEY, config: ENABLED, vault: null });
+ const withVaultOpt = resolveDecisionModelConfig({
+ env: WITH_KEY,
+ config: ENABLED,
+ vault: null,
+ secretsVault: vault,
+ });
+ expect(withVaultOpt).toEqual(without);
+ expect(withVaultOpt.status).toBe("active");
+ });
+
+ test("an unresolvable reference is a named error, not a silent empty key", () => {
+ const vault = tempCustodyVault();
+ const cfg = resolveDecisionModelConfig({
+ env: { [KEY_VAR]: "$secret:absent_name" } as NodeJS.ProcessEnv,
+ config: ENABLED,
+ vault: null,
+ secretsVault: vault,
+ });
+ expect(cfg.status).toBe("invalid");
+ expect(cfg.keyPresent).toBe(false);
+ expect(cfg.errors.join("\n")).toContain("absent_name");
+ });
+});
+
+// ----- The diagnostics surface joins the custody store ----------------------
+//
+// `o2b decision-model check` builds its report and its ping. Without the
+// custody thread, a reference-shaped key value reported `active`
+// everywhere and the ping built a provider whose Bearer key was the raw
+// `$secret:NAME` literal - the doctor could probe an endpoint with it.
+
+function diagnosticsCustodyVault(): string {
+ const vault = mkdtempSync(join(tmpdir(), "osb-dm-check-"));
+ dirs.push(vault);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ return vault;
+}
+
+describe("decision-model check (diagnostics) through the custody store", () => {
+ const NOW = new Date("2026-06-05T10:00:00Z");
+ const REF_ENV = { [KEY_VAR]: "$secret:dm_key" } as NodeJS.ProcessEnv;
+ const CHECK_KEY = fakeCredential("stored-dm-check-", "key-4c02");
+
+ test("a reference the store resolves activates the check and the ping sends the resolved key", async () => {
+ const vault = diagnosticsCustodyVault();
+ setSecret(vault, { name: "dm_key", value: CHECK_KEY, agent: "tester", now: NOW });
+ const fake = await startFakeSystemOne();
+ try {
+ const report = await buildDecisionModelCheck({
+ env: REF_ENV,
+ config: { ...ENABLED, decision_model_base_url: fake.url },
+ vault,
+ ping: true,
+ });
+ expect(report.status).toBe("active");
+ expect(report.key_set).toBe(true);
+ expect(report.ping?.ok).toBe(true);
+ expect(fake.requests).toHaveLength(1);
+ expect(fake.requests[0]!.headers["authorization"]).toBe(`Bearer ${CHECK_KEY}`);
+ } finally {
+ await fake.close();
+ }
+ });
+
+ test("an unresolvable reference degrades the check to invalid with the named error", async () => {
+ const vault = diagnosticsCustodyVault();
+ const report = await buildDecisionModelCheck({
+ env: { [KEY_VAR]: "$secret:absent_name" } as NodeJS.ProcessEnv,
+ config: ENABLED,
+ vault,
+ });
+ // Before the custody thread this reported `active` with key_set true,
+ // deferring the failure to the use site.
+ expect(report.status).toBe("invalid");
+ expect(report.key_set).toBe(false);
+ expect(report.errors.join("\n")).toContain("absent_name");
+ });
+
+ test("a locked store degrades the ping to the named state and never sends the raw literal", async () => {
+ const vault = diagnosticsCustodyVault();
+ setSecret(vault, { name: "dm_key", value: CHECK_KEY, agent: "tester", now: NOW });
+ const kp = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(kp, fakeCredential("dm-check-", "phrase-5f27"), loadOrCreateKey(kp));
+ clearHeldKey(kp);
+ const fake = await startFakeSystemOne();
+ try {
+ const report = await buildDecisionModelCheck({
+ env: REF_ENV,
+ config: { ...ENABLED, decision_model_base_url: fake.url },
+ vault,
+ ping: true,
+ });
+ expect(report.status).toBe("invalid");
+ expect(report.errors.join("\n")).toContain("locked");
+ expect(report.ping?.ok).toBe(false);
+ // The decisive assertion: no request left for the endpoint, so the
+ // raw `$secret:` literal never went out as a Bearer key.
+ expect(fake.requests).toHaveLength(0);
+ } finally {
+ await fake.close();
+ clearHeldKey(kp);
+ }
+ });
+
+ test("a missing keyfile degrades the ping by name instead of minting over the store", async () => {
+ // The locked refusal's sibling state on the same factory path: the
+ // read-only resolve now refuses a store whose keyfile is gone while
+ // entries survive, and the check degrades it into the ping's reason
+ // exactly like the locked state.
+ const vault = diagnosticsCustodyVault();
+ setSecret(vault, { name: "dm_key", value: CHECK_KEY, agent: "tester", now: NOW });
+ rmSync(join(secretsDir(vault), "keyfile"));
+ const fake = await startFakeSystemOne();
+ try {
+ const report = await buildDecisionModelCheck({
+ env: REF_ENV,
+ config: { ...ENABLED, decision_model_base_url: fake.url },
+ vault,
+ ping: true,
+ });
+ expect(report.status).toBe("invalid");
+ expect(report.errors.join("\n")).toContain("missing");
+ expect(report.ping?.ok).toBe(false);
+ expect(fake.requests).toHaveLength(0);
+ } finally {
+ await fake.close();
+ }
+ });
+});
+
+// ----- The provider factory resolves the key at the use site -----------------
+//
+// Config resolution only PROBES a `$secret:NAME` reference for presence;
+// the factory re-reads the raw variable at call time, so it must resolve
+// the reference itself when handed the vault. A loopback fake records the
+// `authorization` header, which is the only honest witness of what the
+// adapter would actually send.
+
+function factoryCustodyVault(): string {
+ const vault = mkdtempSync(join(tmpdir(), "osb-dm-factory-"));
+ dirs.push(vault);
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ return vault;
+}
+
+/** Active config for the reference env value, pointed at an explicit base URL. */
+function activeReferenceConfig(baseUrl: string) {
+ return resolveDecisionModelConfig({
+ env: { [KEY_VAR]: "$secret:dm_key" } as NodeJS.ProcessEnv,
+ config: { ...ENABLED, decision_model_base_url: baseUrl },
+ vault: null,
+ secretsVault: undefined,
+ });
+}
+
+describe("decision-model provider factory through the custody store", () => {
+ const STORED_DM_KEY = fakeCredential("stored-dm-", "key-99be");
+ const NOW = new Date("2026-06-05T10:00:00Z");
+ const REQUEST: DecisionRequest = {
+ use: "rerank",
+ state: { query: "q", passages: { P0: "alpha" } },
+ questions: { yes: { type: "noul", instructions: "Does `passages.P0` help?" } },
+ };
+
+ test("a reference key value reaches the adapter resolved, not raw", async () => {
+ const vault = factoryCustodyVault();
+ setSecret(vault, { name: "dm_key", value: STORED_DM_KEY, agent: "tester", now: NOW });
+ const fake = await startFakeSystemOne();
+ try {
+ const cfg = activeReferenceConfig(fake.url);
+ expect(cfg.status).toBe("active");
+ const provider = makeDecisionProvider(
+ cfg,
+ { [KEY_VAR]: "$secret:dm_key" } as NodeJS.ProcessEnv,
+ vault,
+ );
+ expect(provider).not.toBeNull();
+ await provider!.decide(REQUEST, { timeoutMs: 2000 });
+ expect(fake.requests[0]!.headers["authorization"]).toBe(`Bearer ${STORED_DM_KEY}`);
+ } finally {
+ await fake.close();
+ }
+ });
+
+ test("without a vault the raw value is sent exactly as before", async () => {
+ const fake = await startFakeSystemOne();
+ try {
+ const cfg = activeReferenceConfig(fake.url);
+ const provider = makeDecisionProvider(cfg, {
+ [KEY_VAR]: "$secret:dm_key",
+ } as NodeJS.ProcessEnv);
+ expect(provider).not.toBeNull();
+ await provider!.decide(REQUEST, { timeoutMs: 2000 });
+ expect(fake.requests[0]!.headers["authorization"]).toBe("Bearer $secret:dm_key");
+ } finally {
+ await fake.close();
+ }
+ });
+
+ test("a plain key value is byte-identical with and without a vault", async () => {
+ const vault = factoryCustodyVault();
+ const fake = await startFakeSystemOne();
+ try {
+ const cfg = resolveDecisionModelConfig({
+ env: { [KEY_VAR]: FAKE_DECISION_KEY } as NodeJS.ProcessEnv,
+ config: { ...ENABLED, decision_model_base_url: fake.url },
+ vault: null,
+ });
+ expect(cfg.status).toBe("active");
+ const env = { [KEY_VAR]: FAKE_DECISION_KEY } as NodeJS.ProcessEnv;
+ await makeDecisionProvider(cfg, env)!.decide(REQUEST, { timeoutMs: 2000 });
+ await makeDecisionProvider(cfg, env, vault)!.decide(REQUEST, { timeoutMs: 2000 });
+ expect(fake.requests[0]!.headers["authorization"]).toBe(`Bearer ${FAKE_DECISION_KEY}`);
+ expect(fake.requests[1]!.headers["authorization"]).toBe(`Bearer ${FAKE_DECISION_KEY}`);
+ } finally {
+ await fake.close();
+ }
+ });
+
+ test("an unresolvable reference raises the named resolver error at the use site", () => {
+ const vault = factoryCustodyVault();
+ const cfg = activeReferenceConfig("http://127.0.0.1:9");
+ expect(() =>
+ makeDecisionProvider(cfg, { [KEY_VAR]: "$secret:absent_name" } as NodeJS.ProcessEnv, vault),
+ ).toThrow(SecretReferenceError);
+ });
+
+ test("a store-held name under a locked envelope raises the named locked error", () => {
+ const vault = factoryCustodyVault();
+ setSecret(vault, { name: "dm_key", value: STORED_DM_KEY, agent: "tester", now: NOW });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(keyPath, fakeCredential("dm-wrap", "-phrase-", "42"), loadOrCreateKey(keyPath));
+ clearHeldKey(keyPath);
+ const cfg = activeReferenceConfig("http://127.0.0.1:9");
+ expect(() =>
+ makeDecisionProvider(cfg, { [KEY_VAR]: "$secret:dm_key" } as NodeJS.ProcessEnv, vault),
+ ).toThrow(SecretStoreLockedError);
+ });
+});
diff --git a/tests/core/decision-model/llm-emulation.test.ts b/tests/core/decision-model/llm-emulation.test.ts
index a5d12577..35caf7a9 100644
--- a/tests/core/decision-model/llm-emulation.test.ts
+++ b/tests/core/decision-model/llm-emulation.test.ts
@@ -18,7 +18,12 @@ import {
resetDecisionSpendCache,
} from "../../../src/core/decision-model/record.ts";
import { runDecision } from "../../../src/core/decision-model/run.ts";
-import { FAKE_DECISION_KEY, FAKE_VENDOR_KEY } from "../../helpers/fake-credentials.ts";
+import {
+ FAKE_DECISION_KEY,
+ FAKE_VENDOR_KEY,
+ fakeCredential,
+} from "../../helpers/fake-credentials.ts";
+import { REDACTION_PLACEHOLDER } from "../../../src/core/redactor.ts";
import { startFakeSystemOne, type FakeSystemOne } from "../../helpers/fake-decision-provider.ts";
import { createTempVault } from "../../helpers/search-fixtures.ts";
@@ -180,6 +185,30 @@ describe("llm-emulation adapter", () => {
expect(user.split("</untrusted_source>")).toHaveLength(2);
});
+ test("the prompt scrubs an occurrence of the bearer key itself (wired resolved literal)", async () => {
+ server.setReply(() => chatReply({ yes: { p: 0.5 } }));
+ // A quiet key the shape passes cannot see, leaked into the vault text
+ // the state was built from: the adapter always knows the key it is
+ // about to send, so its egress scan carries it as a resolved literal.
+ const quiet = fakeCredential("quiet-key-", "gamma-delta");
+ const leaked = new LlmEmulationDecisionProvider({
+ name: "llm-emulation",
+ baseUrl: `${server.url}/v1`,
+ model: "fake-chat-1",
+ envKey: KEY_VAR,
+ apiKey: quiet,
+ timeoutMs: 2000,
+ });
+ await leaked.decide(
+ { use: "rerank", state: `echo ${quiet}`, questions: { yes: REQUEST.questions["yes"]! } },
+ { timeoutMs: 2000 },
+ );
+ const user2 = (server.requests[0]!.body as { messages: Array<{ content: string }> })
+ .messages[1]!.content;
+ expect(user2).not.toContain(quiet);
+ expect(user2).toContain(REDACTION_PLACEHOLDER);
+ });
+
test("an endpoint that refuses response_format gets the schema in the prompt", async () => {
server.setReply((_req, i) =>
i === 0
diff --git a/tests/core/decision-model/systemone.test.ts b/tests/core/decision-model/systemone.test.ts
index 6ffe049e..9e009516 100644
--- a/tests/core/decision-model/systemone.test.ts
+++ b/tests/core/decision-model/systemone.test.ts
@@ -14,6 +14,8 @@ import {
SystemOneDecisionProvider,
} from "../../../src/core/decision-model/systemone.ts";
import { FAKE_DECISION_KEY, FAKE_VENDOR_KEY } from "../../helpers/fake-credentials.ts";
+import { REDACTION_PLACEHOLDER } from "../../../src/core/redactor.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
import {
answerAll,
startFakeSystemOne,
@@ -90,6 +92,40 @@ describe("systemone adapter", () => {
expect(res.stateHash).toMatch(/^[0-9a-f]{64}$/);
});
+ test("the request body scrubs an occurrence of the bearer key itself (wired resolved literal)", async () => {
+ server.setReply(() => ({
+ json: {
+ model: "m",
+ answers: {
+ rel_0: { type: "noul", noul: 0.9 },
+ pick: { type: "choice", choice: "a", probabilities: { a: 0.9, b: 0.1 }, confidence: 0.8 },
+ level: { type: "score", score: 1, probabilities: { "0": 0.5, "1": 0.5, "2": 0 } },
+ },
+ },
+ }));
+ // A quiet key the shape passes cannot see, leaked into the vault text
+ // the state was built from: the adapter knows the value it is about
+ // to send as the Bearer credential, so its egress scan carries that
+ // value as a resolved literal.
+ const quiet = fakeCredential("quiet-key-", "alpha-bravo");
+ const leaked = new SystemOneDecisionProvider({
+ name: "compatible",
+ baseUrl: server.url,
+ model: "fake-model-1",
+ envKey: "QUIET_KEY_VAR",
+ apiKey: quiet,
+ calibrated: true,
+ timeoutMs: 2000,
+ });
+ await leaked.decide(
+ { ...REQUEST, state: { query: `echo ${quiet}`, passages: { P0: "alpha" } } },
+ { timeoutMs: 2000 },
+ );
+ const body = JSON.stringify(server.requests[0]!.body);
+ expect(body).not.toContain(quiet);
+ expect(body).toContain(REDACTION_PLACEHOLDER);
+ });
+
test("an invalid item is marked invalid without failing the batch", async () => {
server.setReply(() => ({
json: {
@@ -158,9 +194,17 @@ describe("systemone adapter", () => {
server.setReply(() => ({ status: 429, headers: { "retry-after": "30" } }));
const started = Date.now();
const err = await decideError(1000);
+ // The structural witnesses carry the pin: honoring the 30s retry-after
+ // would blow the 1000ms decide deadline first, so the refusal would
+ // surface as a timeout, not as this named 429, and no second request
+ // would exist either way. The elapsed bound below therefore only has to
+ // separate "did not sleep for the retry-after" (>=30s) from a slow
+ // machine, so it sits an order of magnitude under the wait it refuses
+ // to wait instead of at the decide deadline, where scheduler jitter
+ // alone could flake it.
expect(err.reason).toBe("http_429");
expect(server.requests).toHaveLength(1);
- expect(Date.now() - started).toBeLessThan(1000);
+ expect(Date.now() - started).toBeLessThan(10_000);
});
test("529 twice is retried at most once", async () => {
diff --git a/tests/core/egress-resolved-literals.test.ts b/tests/core/egress-resolved-literals.test.ts
new file mode 100644
index 00000000..724c3e0a
--- /dev/null
+++ b/tests/core/egress-resolved-literals.test.ts
@@ -0,0 +1,138 @@
+/**
+ * Resolved-literal redaction on the egress paths (trust-surface-
+ * hardening, t_e5807974 / Lane B3).
+ *
+ * A `$secret:NAME` reference resolves to a value the structural passes
+ * cannot see: the value is an opaque string whose key may say nothing
+ * (`note:`) and whose shape may carry no vendor prefix. Once such a value
+ * is resolved at a use site, every path that carries its carrier outward
+ * - the egress guard and the MCP error redactor - must scrub the literal
+ * itself, longest first, before the truncation guard can cut a fragment
+ * of it into the kept prefix.
+ *
+ * Every credential-shaped string below is assembled at runtime via the
+ * fake-credentials helper, so no source line carries a literal shaped
+ * like a real credential.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { redactConfigMapping, redactForEgress } from "../../src/core/egress/guard.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import {
+ MAX_REDACTOR_INPUT,
+ REDACTION_PLACEHOLDER,
+ SCAN_TRUNCATED_MARKER,
+ redactStructured,
+} from "../../src/core/redactor.ts";
+import { redactErrorForCaller } from "../../src/mcp/error-redaction.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+// Two overlapping placeholder credentials: SHORT is a suffix of LONG, so
+// a shortest-first substitution would destroy LONG's match and leak its
+// head as a fragment. Neither is vendor-shaped or digit-bearing, so the
+// structural passes leave both alone and the test isolates the literal
+// mechanism.
+const LONG_VALUE = fakeCredential("alpha-bravo-", "charlie-delta-echo");
+const SHORT_VALUE = fakeCredential("charlie-delta-", "echo");
+
+const VAULT = fakeCredential("/tmp/", "vault-under-test");
+
+describe("redactForEgress with resolved literals", () => {
+ test("replaces each resolved value with the standard marker, longest first", () => {
+ const verdict = redactForEgress(
+ "config-export",
+ { note: `see ${LONG_VALUE} then ${SHORT_VALUE} end` },
+ { resolvedLiterals: [SHORT_VALUE, LONG_VALUE] },
+ );
+ expect(verdict.outcome).toBe("released");
+ if (verdict.outcome !== "released") return;
+ expect(verdict.payload).toEqual({
+ note: `see ${REDACTION_PLACEHOLDER} then ${REDACTION_PLACEHOLDER} end`,
+ });
+ expect(verdict.redacted).toBe(true);
+ });
+
+ test("scrubs before the scan window truncates and still refuses the payload", () => {
+ // SHORT_VALUE's head would survive in the kept prefix if the literal
+ // scrub ran after the truncation cut.
+ const pad = "p".repeat(MAX_REDACTOR_INPUT - 4);
+ const verdict = redactForEgress(
+ "config-export",
+ { note: pad + LONG_VALUE },
+ { resolvedLiterals: [LONG_VALUE] },
+ );
+ expect(verdict.outcome).toBe("refused_scan_truncated");
+ });
+
+ test("with no literals the composition is byte-identical to the bare policy", () => {
+ const payload = { note: `see ${LONG_VALUE} end`, count: 2 };
+ const bare = redactStructured(payload, { redactTokens: true, redactUrlCredentials: true });
+ for (const policy of [{}, { resolvedLiterals: [] }]) {
+ const verdict = redactForEgress("config-export", payload, policy);
+ expect(verdict.outcome).toBe("released");
+ if (verdict.outcome !== "released") return;
+ expect(verdict.payload).toEqual(bare.value as typeof payload);
+ expect(verdict.redacted).toBe(bare.redacted);
+ }
+ });
+});
+
+describe("redactConfigMapping with resolved literals", () => {
+ test("replaces each resolved value with the standard marker, longest first", () => {
+ const out = redactConfigMapping(
+ { note: `see ${LONG_VALUE} then ${SHORT_VALUE} end` },
+ { resolvedLiterals: [SHORT_VALUE, LONG_VALUE] },
+ );
+ expect(out).toEqual({
+ note: `see ${REDACTION_PLACEHOLDER} then ${REDACTION_PLACEHOLDER} end`,
+ });
+ });
+
+ test("scrubs before the scan window truncates a leaf", () => {
+ // The straddling leaf: if the literal scrub ran after the truncation
+ // cut, the kept prefix would end with the head of LONG_VALUE as a
+ // fragment. A leaf wholly inside the window proves the marker itself.
+ const straddling = "p".repeat(MAX_REDACTOR_INPUT - 4) + LONG_VALUE;
+ const out = redactConfigMapping(
+ { head: LONG_VALUE, tail: straddling },
+ { resolvedLiterals: [LONG_VALUE] },
+ );
+ const tail = String(out["tail"]);
+ expect(tail.includes(LONG_VALUE.slice(0, 8))).toBe(false);
+ expect(tail.includes(SCAN_TRUNCATED_MARKER)).toBe(true);
+ expect(out["head"]).toBe(REDACTION_PLACEHOLDER);
+ });
+
+ test("with no literals the output is byte-identical to today's single-argument call", () => {
+ const data = { note: `see ${LONG_VALUE} end`, keep: "kept" };
+ expect(redactConfigMapping(data, {})).toEqual(redactConfigMapping(data));
+ expect(redactConfigMapping(data, { resolvedLiterals: [] })).toEqual(redactConfigMapping(data));
+ });
+});
+
+describe("MCP error redaction with resolved literals", () => {
+ test("local reach scrubs resolved literals beside the vault root", () => {
+ const raw = `read failed at ${VAULT}/notes/x.md: ${LONG_VALUE} refused`;
+ const out = redactErrorForCaller(raw, VAULT, TRANSPORT_REACH.local, [LONG_VALUE]);
+ expect(out.includes(LONG_VALUE)).toBe(false);
+ expect(out.includes(REDACTION_PLACEHOLDER)).toBe(true);
+ expect(out.includes(`${VAULT}/notes/x.md`)).toBe(false);
+ });
+
+ test("remote reach scrubs resolved literals beside the root placeholders", () => {
+ const raw = `read failed at ${VAULT}/notes/x.md: ${LONG_VALUE} refused`;
+ const out = redactErrorForCaller(raw, VAULT, TRANSPORT_REACH.remote, [LONG_VALUE]);
+ expect(out.includes(LONG_VALUE)).toBe(false);
+ expect(out.includes("<vault>/notes/x.md")).toBe(true);
+ });
+
+ test("without literals the output is byte-identical to the three-argument call", () => {
+ const raw = `read failed at ${VAULT}/notes/x.md: details`;
+ for (const reach of [TRANSPORT_REACH.local, TRANSPORT_REACH.remote]) {
+ expect(redactErrorForCaller(raw, VAULT, reach, [])).toBe(
+ redactErrorForCaller(raw, VAULT, reach),
+ );
+ }
+ });
+});
diff --git a/tests/core/integrity/digest.test.ts b/tests/core/integrity/digest.test.ts
index df7f4043..26122229 100644
--- a/tests/core/integrity/digest.test.ts
+++ b/tests/core/integrity/digest.test.ts
@@ -18,7 +18,12 @@ import { createHash } from "node:crypto";
import { describe, expect, test } from "bun:test";
-import { canonicalJson, sha256Hex } from "../../../src/core/integrity/digest.ts";
+import {
+ canonicalJson,
+ digestVerifies,
+ sealWithDigest,
+ sha256Hex,
+} from "../../../src/core/integrity/digest.ts";
/** Independently recomputed, so the test does not restate the implementation. */
function referenceSha256(input: string | Uint8Array): string {
@@ -122,3 +127,80 @@ describe("canonicalJson", () => {
expect(sha256Hex(canonicalJson({ b: 1, a: 2 }))).toBe(sha256Hex(canonicalJson({ a: 2, b: 1 })));
});
});
+
+describe("sealWithDigest / digestVerifies", () => {
+ // The shape every caller of the seal shares: a body of plain JSON
+ // values, bound by one digest appended beside it.
+ interface ExampleBody {
+ readonly name: string;
+ readonly entries: ReadonlyArray<{ path: string; bytes: number }>;
+ readonly total: number;
+ }
+ const body: ExampleBody = {
+ name: "plan",
+ entries: [
+ { path: "a.md", bytes: 3 },
+ { path: "b.md", bytes: 5 },
+ ],
+ total: 8,
+ };
+
+ test("seal-then-verify round-trips", () => {
+ const sealed = sealWithDigest(body);
+ expect(sealed.digest).toBe(sha256Hex(canonicalJson(body)));
+ expect(digestVerifies(body, sealed.digest)).toBe(true);
+ });
+
+ test("the sealed value is the body plus the digest, nothing else moved", () => {
+ expect(sealWithDigest(body)).toEqual({ ...body, digest: sha256Hex(canonicalJson(body)) });
+ });
+
+ test("the digest is insensitive to key order in the sealed body", () => {
+ const reordered = {
+ total: body.total,
+ entries: body.entries.map((e) => ({ bytes: e.bytes, path: e.path })),
+ name: body.name,
+ };
+ expect(sealWithDigest(body).digest).toBe(sealWithDigest(reordered).digest);
+ });
+
+ test("any body mutation fails verification", () => {
+ const sealed = sealWithDigest(body);
+ const mutations: Array<ExampleBody> = [
+ { ...body, name: "plan " },
+ { ...body, total: 9 },
+ { ...body, entries: [...body.entries, { path: "c.md", bytes: 1 }] },
+ {
+ ...body,
+ entries: [
+ { path: "b.md", bytes: 5 },
+ { path: "a.md", bytes: 3 },
+ ],
+ },
+ {
+ ...body,
+ entries: [
+ { path: "a.md", bytes: 4 },
+ { path: "b.md", bytes: 5 },
+ ],
+ },
+ ];
+ const survivors = mutations.filter((candidate) => digestVerifies(candidate, sealed.digest));
+ expect(survivors.map((s) => canonicalJson(s)).join("\n")).toBe("");
+ });
+
+ test("verification refuses a digest from a different body", () => {
+ const other = sealWithDigest({ ...body, total: 9 });
+ expect(digestVerifies(body, other.digest)).toBe(false);
+ });
+
+ test("the digest is lowercase hex of the declared length", () => {
+ const sealed = sealWithDigest(body);
+ expect(sealed.digest).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("omits undefined entries from the sealed body exactly as canonicalJson does", () => {
+ const withOptional = sealWithDigest({ a: 1, b: undefined });
+ expect(withOptional.digest).toBe(sealWithDigest({ a: 1 }).digest);
+ });
+});
diff --git a/tests/core/search/embeddings.registry.test.ts b/tests/core/search/embeddings.registry.test.ts
index efa20fe4..91118a5c 100644
--- a/tests/core/search/embeddings.registry.test.ts
+++ b/tests/core/search/embeddings.registry.test.ts
@@ -1,8 +1,17 @@
-import { test, expect, beforeEach, afterEach } from "bun:test";
-import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { test, expect, beforeEach, afterEach, describe } from "bun:test";
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { setSecret, secretsDir } from "../../../src/core/brain/secrets/store.ts";
+import { loadOrCreateKey } from "../../../src/core/brain/secrets/crypto.ts";
+import {
+ clearHeldKey,
+ wrapKeyfile,
+ SecretStoreKeyfileMissingError,
+ SecretStoreLockedError,
+} from "../../../src/core/brain/secrets/envelope.ts";
+import { resolveSearchConfig } from "../../../src/core/search/index.ts";
import {
loadProviderRegistry,
addProviderProfile,
@@ -13,6 +22,7 @@ import {
RESERVED_PROVIDER_NAMES,
} from "../../../src/core/search/embeddings/registry.ts";
import { SearchError } from "../../../src/core/search/types.ts";
+import { SecretReferenceError } from "../../../src/core/secret-ref.ts";
import { fakeCredential } from "../../helpers/fake-credentials.ts";
const NIM_KEY = fakeCredential("secret-", "123");
@@ -135,3 +145,220 @@ test("a malformed registry file degrades to empty, never throws", () => {
writeFileSync(providerRegistryPath(vault), "{ not json");
expect(loadProviderRegistry(vault)).toEqual([]);
});
+
+// ----- Custody-store probing (trust-surface-hardening, t_e5807974 / B2) ------
+//
+// The probe map is the merged provider: a name the custody store holds
+// answers ahead of the environment, and a probe entry written as a
+// `$secret:NAME` reference resolves through the same store. Resolution is
+// read-only (no `last_used_at` stamp, no store mutation), and with no
+// store entry and no reference the probing is byte-identical to the
+// plain-env behavior.
+
+const STORED_PROBE_KEY = fakeCredential("stored-", "probe-8d31");
+const EMBED_KEY_REF = "$secret:embed_key";
+const ABSENT_EMBED_REF = "$secret:absent_name";
+const SPACED_EMBED_REF = "$secret:has space";
+const ENV_PROBE_KEY = fakeCredential("env-", "probe-2e77");
+const LOCK_PASSPHRASE = fakeCredential("registry-wrap-", "phrase-71bd");
+const PROBE_NOW = new Date("2026-06-05T10:00:00Z");
+/** The fixture profile, pointed at the probe name the store entry uses. */
+const probeProfile = { ...nim, envKey: "embed_key" };
+
+function storeProbeKey(name = "embed_key"): void {
+ setSecret(vault, { name, value: STORED_PROBE_KEY, agent: "tester", now: PROBE_NOW });
+}
+
+/** A machine config selecting `provider`, so the resolver expands the registry. */
+function configWithProvider(provider: string, extra = ""): string {
+ const configPath = join(vault, "machine-config.yaml");
+ writeFileSync(configPath, `embedding_provider: "${provider}"\n${extra}`, "utf8");
+ return configPath;
+}
+
+function withEnvKey(name: string, value: string, run: () => void): void {
+ const saved = process.env[name];
+ process.env[name] = value;
+ try {
+ run();
+ } finally {
+ if (saved === undefined) delete process.env[name];
+ else process.env[name] = saved;
+ }
+}
+
+test("a store-held probe name answers ahead of the environment", () => {
+ storeProbeKey();
+ withEnvKey("embed_key", ENV_PROBE_KEY, () => {
+ const expanded = expandRegisteredProvider("nvidia-nim", [probeProfile], process.env, {
+ secretsVault: vault,
+ });
+ expect(expanded?.apiKey).toBe(STORED_PROBE_KEY);
+ expect(expanded?.apiKeys).toEqual([STORED_PROBE_KEY]);
+ });
+});
+
+test("a probe entry written as a reference resolves through the store", () => {
+ storeProbeKey();
+ const expanded = expandRegisteredProvider(
+ "nvidia-nim",
+ [{ ...nim, envKey: EMBED_KEY_REF }],
+ {},
+ { secretsVault: vault },
+ );
+ expect(expanded?.apiKey).toBe(STORED_PROBE_KEY);
+});
+
+test("plain env probing is byte-identical with and without a custody vault", () => {
+ withEnvKey("embed_key", ENV_PROBE_KEY, () => {
+ const plain = expandRegisteredProvider("nvidia-nim", [probeProfile], process.env);
+ const routed = expandRegisteredProvider("nvidia-nim", [probeProfile], process.env, {
+ secretsVault: vault,
+ });
+ expect(routed).toEqual(plain);
+ expect(routed?.apiKey).toBe(ENV_PROBE_KEY);
+ });
+});
+
+test("an unresolvable reference probe surfaces the named resolver error", () => {
+ expect(() =>
+ expandRegisteredProvider(
+ "nvidia-nim",
+ [{ ...nim, envKey: ABSENT_EMBED_REF }],
+ {},
+ { secretsVault: vault },
+ ),
+ ).toThrow(SecretReferenceError);
+});
+
+test("resolution through the probe does not mutate the custody store", () => {
+ storeProbeKey();
+ const storePath = join(vault, ".open-second-brain", "secrets", "secrets.json");
+ const before = readFileSync(storePath, "utf8");
+ expandRegisteredProvider("nvidia-nim", [probeProfile], process.env, { secretsVault: vault });
+ expect(readFileSync(storePath, "utf8")).toBe(before);
+});
+
+// ----- The search config resolver joins the custody store (t_e5807974) -------
+//
+// `resolveRegistryProvider` hands `expandRegisteredProvider` the vault, so
+// a registered `embedding_provider` resolves its key through
+// `resolveSearchConfig` itself - not only when the registry module is
+// called directly.
+
+describe("resolveSearchConfig probes a registered provider through the store", () => {
+ test("a store-held key name answers through the full config resolution", () => {
+ addProviderProfile(vault, probeProfile);
+ storeProbeKey();
+ // An env value under the same name makes the precedence claim, not
+ // just the resolution claim: the store answers ahead of the
+ // environment through the full config resolution too.
+ withEnvKey("embed_key", ENV_PROBE_KEY, () => {
+ const cfg = resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") });
+ expect(cfg.semantic.provider).toBe("openai-compat");
+ expect(cfg.semantic.apiKey).toBe(STORED_PROBE_KEY);
+ expect(cfg.semantic.apiKeys).toEqual([STORED_PROBE_KEY]);
+ });
+ });
+
+ test("a reference-shaped envKey resolves through the full config resolution", () => {
+ addProviderProfile(vault, { ...probeProfile, envKey: EMBED_KEY_REF });
+ storeProbeKey();
+ const cfg = resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") });
+ expect(cfg.semantic.apiKey).toBe(STORED_PROBE_KEY);
+ });
+
+ test("a plain env key resolves identically through the vault-joined probe", () => {
+ addProviderProfile(vault, probeProfile);
+ withEnvKey("embed_key", ENV_PROBE_KEY, () => {
+ const cfg = resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") });
+ expect(cfg.semantic.apiKey).toBe(ENV_PROBE_KEY);
+ });
+ });
+
+ test("a locked store behind the probe surfaces the named locked error, not 'not a registered provider'", () => {
+ // The swallowing catch used to convert the resolver's named refusal
+ // into a null expansion, so `parseProvider` then claimed the name was
+ // not registered - for a name that IS registered, with the remedy
+ // (fix the provider name) pointing the wrong way.
+ addProviderProfile(vault, probeProfile);
+ storeProbeKey();
+ const kp = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(kp, LOCK_PASSPHRASE, loadOrCreateKey(kp));
+ clearHeldKey(kp);
+ try {
+ expect(() =>
+ resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") }),
+ ).toThrow(SecretStoreLockedError);
+ } finally {
+ clearHeldKey(kp);
+ }
+ });
+
+ test("a malformed reference probe surfaces the named reference error through the full resolution", () => {
+ addProviderProfile(vault, { ...probeProfile, envKey: SPACED_EMBED_REF });
+ expect(() =>
+ resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") }),
+ ).toThrow(SecretReferenceError);
+ });
+
+ test("a missing keyfile behind the probe surfaces the named refusal, not 'not a registered provider'", () => {
+ // The missing-keyfile refusal is the locked refusal's sibling state on
+ // the same probe path, so it propagates for the same reason: a
+ // fail-soft null here would misreport a registered provider as
+ // unregistered, with the remedy pointing the wrong way.
+ addProviderProfile(vault, probeProfile);
+ storeProbeKey();
+ rmSync(join(secretsDir(vault), "keyfile"));
+ expect(() =>
+ resolveSearchConfig({ vault, configPath: configWithProvider("nvidia-nim") }),
+ ).toThrow(SecretStoreKeyfileMissingError);
+ });
+
+ test("the explicit embedding_api_key resolves a $secret: reference like its siblings", () => {
+ // The explicit key used to pass a reference through verbatim - a
+ // dead endpoint auth with nothing naming why - while the registry
+ // probe beside it resolved.
+ storeProbeKey();
+ const cfg = resolveSearchConfig({
+ vault,
+ configPath: configWithProvider(
+ "openai-compat",
+ `embedding_base_url: "https://embed.example/v1"\nembedding_api_key: "${EMBED_KEY_REF}"\n`,
+ ),
+ });
+ expect(cfg.semantic.provider).toBe("openai-compat");
+ expect(cfg.semantic.apiKey).toBe(STORED_PROBE_KEY);
+ expect(cfg.semantic.apiKeys).toEqual([STORED_PROBE_KEY]);
+ });
+
+ test("the cross-encoder rerank env key resolves a $secret: reference like its siblings", () => {
+ storeProbeKey();
+ withEnvKey("rerank_key_var", EMBED_KEY_REF, () => {
+ const cfg = resolveSearchConfig({
+ vault,
+ configPath: configWithProvider(
+ "openai-compat",
+ `search_rerank_enabled: "true"\nsearch_rerank_env_key: rerank_key_var\n`,
+ ),
+ });
+ expect(cfg.rerank.enabled).toBe(true);
+ expect(cfg.rerank.apiKey).toBe(STORED_PROBE_KEY);
+ });
+ });
+
+ test("a plain explicit and rerank key pass through byte-identically", () => {
+ withEnvKey("rerank_key_var", ENV_PROBE_KEY, () => {
+ const cfg = resolveSearchConfig({
+ vault,
+ configPath: configWithProvider(
+ "openai-compat",
+ `embedding_api_key: "${ENV_PROBE_KEY}"\n` +
+ `search_rerank_enabled: "true"\nsearch_rerank_env_key: rerank_key_var\n`,
+ ),
+ });
+ expect(cfg.semantic.apiKey).toBe(ENV_PROBE_KEY);
+ expect(cfg.rerank.apiKey).toBe(ENV_PROBE_KEY);
+ });
+ });
+});
diff --git a/tests/core/secret-resolver.test.ts b/tests/core/secret-resolver.test.ts
new file mode 100644
index 00000000..e06991e6
--- /dev/null
+++ b/tests/core/secret-resolver.test.ts
@@ -0,0 +1,197 @@
+/**
+ * The named-secret resolver (trust-surface-hardening, t_e5807974 /
+ * Lane B1): a custody-store-backed SecretProvider with env fallback
+ * behind the existing `$secret:` syntax.
+ *
+ * Precedence is store first, env fallback - EXCEPT a name the store
+ * holds under a locked envelope, which surfaces the named locked-store
+ * error rather than silently answering from the environment (a silent
+ * fallback would hide the locked state). Resolution is read-only: no
+ * `last_used_at` stamp, no exec audit record, no store-file mutation -
+ * config reads must not take the write path. A vault with no custody
+ * store gains no state from resolution at all.
+ *
+ * Every credential-shaped string below is assembled at runtime via the
+ * fake-credentials helper.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { listSecrets, secretsDir, setSecret } from "../../src/core/brain/secrets/store.ts";
+import { lockSecretKeyfile, unlockSecretKeyfile } from "../../src/core/brain/secrets/store.ts";
+import { SecretReferenceError } from "../../src/core/secret-ref.ts";
+import {
+ listNamedSecretAvailability,
+ resolveNamedSecret,
+ secretProvider,
+} from "../../src/core/secret-resolver.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const NOW = new Date("2026-06-05T10:00:00Z");
+const STORE_VALUE = fakeCredential("store", "-value-", "42f1c9");
+const ENV_VALUE = fakeCredential("env", "-value-", "77b3d0");
+const REF = "$secret:embed_key";
+
+let vault: string;
+const savedEnv: Record<string, string | undefined> = {};
+const ENV_KEYS = ["embed_key", "fallback_key"] as const;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-secret-resolver-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ for (const key of ENV_KEYS) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ for (const key of ENV_KEYS) {
+ if (savedEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = savedEnv[key];
+ }
+});
+
+function storeBytes(): string {
+ return readFileSync(join(secretsDir(vault), "secrets.json"), "utf8");
+}
+
+function custodyAuditRecords(): number {
+ const dir = join(vault, "Brain", "log", "secret-custody");
+ if (!existsSync(dir)) return 0;
+ return readdirSync(dir).reduce(
+ (n, entry) => n + readFileSync(join(dir, entry), "utf8").split("\n").filter(Boolean).length,
+ 0,
+ );
+}
+
+function setStoreKey(): void {
+ setSecret(vault, { name: "embed_key", value: STORE_VALUE, agent: "tester", now: NOW });
+}
+
+describe("resolveNamedSecret", () => {
+ test("resolves a store-held reference without stamping use or emitting exec audit", () => {
+ setStoreKey();
+ const before = storeBytes();
+ const auditsBefore = custodyAuditRecords();
+
+ expect(resolveNamedSecret(vault, REF)).toBe(STORE_VALUE);
+
+ expect(storeBytes()).toBe(before);
+ expect(custodyAuditRecords()).toBe(auditsBefore);
+ expect(listSecrets(vault)[0]?.last_used_at).toBeNull();
+ });
+
+ test("falls back to the environment when the store does not hold the name", () => {
+ process.env["embed_key"] = ENV_VALUE;
+ expect(resolveNamedSecret(vault, REF)).toBe(ENV_VALUE);
+ });
+
+ test("a locked store surfaces the named locked error, never the env value", () => {
+ setStoreKey();
+ process.env["embed_key"] = ENV_VALUE;
+ lockVaultStoreForTest();
+ try {
+ expect(() => resolveNamedSecret(vault, REF)).toThrow(/locked/);
+ } finally {
+ unlockVaultStoreForTest();
+ }
+ expect(resolveNamedSecret(vault, REF)).toBe(STORE_VALUE);
+ });
+
+ test("malformed references keep the existing SecretReferenceError behavior", () => {
+ setStoreKey();
+ expect(() => resolveNamedSecret(vault, "$secret:has space")).toThrow(SecretReferenceError);
+ expect(() => resolveNamedSecret(vault, "$secret:absent_name")).toThrow(SecretReferenceError);
+ expect(() => resolveNamedSecret(vault, REF)).not.toThrow();
+ });
+
+ test("a plain value passes through untouched", () => {
+ const plain = fakeCredential("plain", "-inline-value");
+ expect(resolveNamedSecret(vault, plain)).toBe(plain);
+ });
+});
+
+describe("secretProvider", () => {
+ test("store entries answer by name and shadow the environment", () => {
+ setStoreKey();
+ process.env["embed_key"] = ENV_VALUE;
+ expect(secretProvider(vault)["embed_key"]).toBe(STORE_VALUE);
+ });
+
+ test("env names answer when the store does not hold them", () => {
+ process.env["embed_key"] = ENV_VALUE;
+ expect(secretProvider(vault)["embed_key"]).toBe(ENV_VALUE);
+ });
+
+ test("resolution through the provider does not mutate the store file", () => {
+ setStoreKey();
+ const before = storeBytes();
+ void secretProvider(vault)["embed_key"];
+ expect(storeBytes()).toBe(before);
+ });
+
+ test("an absent name reads as undefined, like any env-shaped provider", () => {
+ expect(secretProvider(vault)["absent_name"]).toBeUndefined();
+ });
+
+ test("a vault without a custody store gains no state from resolution", () => {
+ process.env["embed_key"] = ENV_VALUE;
+ expect(existsSync(secretsDir(vault))).toBe(false);
+ expect(resolveNamedSecret(vault, REF)).toBe(ENV_VALUE);
+ expect(existsSync(secretsDir(vault))).toBe(false);
+ });
+});
+
+describe("listNamedSecretAvailability", () => {
+ test("reports availability from store metadata and env without decrypting", () => {
+ setStoreKey();
+ process.env["fallback_key"] = ENV_VALUE;
+ const before = storeBytes();
+ const availability = listNamedSecretAvailability(vault, {
+ env_ref: "$secret:fallback_key",
+ missing_ref: "$secret:absent_name",
+ store_ref: "$secret:embed_key",
+ });
+ expect(availability).toEqual([
+ { configKey: "env_ref", name: "fallback_key", available: true },
+ { configKey: "missing_ref", name: "absent_name", available: false },
+ { configKey: "store_ref", name: "embed_key", available: true },
+ ]);
+ expect(storeBytes()).toBe(before);
+ expect(listSecrets(vault)[0]?.last_used_at).toBeNull();
+ });
+
+ test("a store-held name stays available under a locked envelope (metadata only)", () => {
+ setStoreKey();
+ lockVaultStoreForTest();
+ try {
+ const availability = listNamedSecretAvailability(vault, { ref: "$secret:embed_key" });
+ expect(availability).toEqual([{ configKey: "ref", name: "embed_key", available: true }]);
+ } finally {
+ unlockVaultStoreForTest();
+ }
+ });
+});
+
+// ----- Locked-store helpers --------------------------------------------------
+//
+// Lane A's lock lifecycle over the store's public surface: the first
+// unlock wraps a raw keyfile under the passphrase and holds the key for
+// this process; the lock op clears it, so a store-held name under a
+// locked envelope answers with the named locked refusal.
+
+const VAULT_PASSPHRASE = fakeCredential("vault-", "passphrase-9d11c2");
+
+function lockVaultStoreForTest(): void {
+ unlockSecretKeyfile(vault, VAULT_PASSPHRASE, { agent: "tester", now: NOW });
+ lockSecretKeyfile(vault, { agent: "tester", now: NOW });
+}
+
+function unlockVaultStoreForTest(): void {
+ unlockSecretKeyfile(vault, VAULT_PASSPHRASE, { agent: "tester", now: NOW });
+}
diff --git a/tests/core/state/migrate.test.ts b/tests/core/state/migrate.test.ts
index 65514cc3..00650f55 100644
--- a/tests/core/state/migrate.test.ts
+++ b/tests/core/state/migrate.test.ts
@@ -41,7 +41,7 @@ import {
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
-import { canonicalJson, sha256Hex } from "../../../src/core/integrity/digest.ts";
+import { canonicalJson, sealWithDigest, sha256Hex } from "../../../src/core/integrity/digest.ts";
import {
applyStateMigration,
applyStateRollback,
@@ -200,6 +200,17 @@ describe("state migration plan", () => {
const { digest, ...bound } = p.manifest;
expect(digest).toBe(sha256Hex(canonicalJson(bound)));
});
+
+ test("the manifest seal is the integrity module's seal, byte for byte", () => {
+ // The module's private seal became a thin alias over the lifted
+ // `sealWithDigest`; this pins the aliasing as behavior-preserving:
+ // the sealed manifest is exactly what the shared primitive returns
+ // for the same bound body.
+ const vault = seedVault();
+ const p = plan(vault, join(tempDir(), "moved"));
+ const { digest: _digest, ...bound } = p.manifest;
+ expect(sealWithDigest(bound)).toEqual(p.manifest);
+ });
});
describe("state migration refuses before it commits", () => {
diff --git a/tests/mcp/egress-resolved-literal-boundary.test.ts b/tests/mcp/egress-resolved-literal-boundary.test.ts
new file mode 100644
index 00000000..60a94ce6
--- /dev/null
+++ b/tests/mcp/egress-resolved-literal-boundary.test.ts
@@ -0,0 +1,185 @@
+/**
+ * The WIRED resolved-literal boundaries (trust-surface-hardening review,
+ * major fix): the mechanism was already unit-tested in
+ * `tests/core/egress-resolved-literals.test.ts`, but no production caller
+ * ever passed `resolvedLiterals`, so the redaction never fired at any
+ * boundary. These tests drive the real compositions - the MCP status
+ * tool's config-mapping redaction, the one builder every JSON-RPC error
+ * answer passes through, and the server's tools/call error envelope - over
+ * a vault whose custody store holds the values, and prove a store-resolved
+ * value is scrubbed where the bytes leave for model context.
+ *
+ * The honest degrades are pinned next to the wiring: an absent, empty or
+ * LOCKED store contributes nothing, and the boundary then answers exactly
+ * as the pre-literal redactor did - a boundary that cannot know the vault's
+ * values must not pretend to redact them.
+ *
+ * Every credential-shaped string below is assembled at runtime via the
+ * fake-credentials helper.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { setSecret, secretsDir } from "../../src/core/brain/secrets/store.ts";
+import { lockSecretKeyfile, unlockSecretKeyfile } from "../../src/core/brain/secrets/store.ts";
+import { redactErrorForCaller } from "../../src/mcp/error-redaction.ts";
+import { internalErrorResponse, MCPServer } from "../../src/mcp/server.ts";
+import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const NOW = new Date("2026-06-05T10:00:00Z");
+// Quiet shapes on purpose: no vendor prefix, no long digit run, so the
+// structural passes alone leave the value untouched and the test isolates
+// the literal pass.
+const STORED = fakeCredential("alpha-gamma-", "epsilon-theta-eta-iota");
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-egress-boundary-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ for (const k of [
+ "VAULT_DIR",
+ "VAULT_AGENT_NAME",
+ "OPEN_SECOND_BRAIN_CONFIG",
+ "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS",
+ "OPEN_SECOND_BRAIN_MCP_ROUTE_METRICS_ENABLED",
+ ]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { 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 storeCredential(): void {
+ setSecret(vault, { name: "quiet_value", value: STORED, agent: "tester", now: NOW });
+}
+
+function writeMachineConfig(body: string): void {
+ writeFileSync(configPath, body, "utf8");
+}
+
+describe("second_brain_status config mapping (real boundary)", () => {
+ test("a store-resolved value that reached the config snapshot is scrubbed in the payload", async () => {
+ storeCredential();
+ // The quiet key name is exactly the case the structural passes miss:
+ // the credential rides under a name that declares nothing.
+ writeMachineConfig(`vault: ${JSON.stringify(vault)}\nquiet_note: ${JSON.stringify(STORED)}\n`);
+ const server = new MCPServer({ vault, configPath });
+ const response = await server.handleRequest({
+ jsonrpc: "2.0",
+ id: "status-1",
+ method: "tools/call",
+ params: { name: "second_brain_status", arguments: {} },
+ });
+ const rendered = JSON.stringify(response);
+ expect(rendered).not.toContain(STORED);
+ expect(rendered).toContain(REDACTION_PLACEHOLDER);
+ });
+
+ test("without a custody store the mapping answers byte-identically to the bare redactor", async () => {
+ // No storeCredential(): the same config value is NOT a known literal,
+ // so the pre-literal behaviour is pinned, not the leak.
+ writeMachineConfig(`vault: ${JSON.stringify(vault)}\nquiet_note: ${JSON.stringify(STORED)}\n`);
+ const server = new MCPServer({ vault, configPath });
+ const response = await server.handleRequest({
+ jsonrpc: "2.0",
+ id: "status-2",
+ method: "tools/call",
+ params: { name: "second_brain_status", arguments: {} },
+ });
+ expect(JSON.stringify(response)).toContain(STORED);
+ });
+});
+
+describe("the JSON-RPC internal error boundary (real composition)", () => {
+ test("an error naming a store-resolved value leaves without it", () => {
+ storeCredential();
+ const response = internalErrorResponse(
+ "err-1",
+ new Error(`upstream probe failed: ${STORED} refused`),
+ vault,
+ TRANSPORT_REACH.remote,
+ );
+ const rendered = JSON.stringify(response);
+ expect(rendered).not.toContain(STORED);
+ expect(rendered).toContain(REDACTION_PLACEHOLDER);
+ });
+
+ test("a locked store contributes nothing: the answer is byte-identical to the bare redactor", () => {
+ storeCredential();
+ const passphrase = fakeCredential("boundary-wrap-", "phrase-5c2a");
+ unlockSecretKeyfile(vault, passphrase, { agent: "tester", now: NOW });
+ lockSecretKeyfile(vault, { agent: "tester", now: NOW });
+ const raw = `upstream probe failed: ${STORED} refused`;
+ const response = internalErrorResponse("err-2", new Error(raw), vault, TRANSPORT_REACH.remote);
+ // A boundary that cannot know the values (the store is locked) must
+ // not pretend: the message is exactly what the three-argument redactor
+ // always produced, marker for marker.
+ expect(response.error?.message).toBe(
+ `internal error: ${redactErrorForCaller(raw, vault, TRANSPORT_REACH.remote)}`,
+ );
+ expect(response.error?.message).toContain(STORED);
+ });
+
+ test("a missing keyfile contributes nothing and the scan mints no keyfile", () => {
+ // The locked state's sibling: the per-secret resolve now refuses the
+ // missing-keyfile state by name, the scan swallows it like any other
+ // per-entry refusal, and the boundary answers byte-identically to the
+ // bare redactor - leaving no custody state behind.
+ storeCredential();
+ rmSync(join(secretsDir(vault), "keyfile"));
+ const raw = `upstream probe failed: ${STORED} refused`;
+ const response = internalErrorResponse("err-3", new Error(raw), vault, TRANSPORT_REACH.remote);
+ expect(response.error?.message).toBe(
+ `internal error: ${redactErrorForCaller(raw, vault, TRANSPORT_REACH.remote)}`,
+ );
+ expect(response.error?.message).toContain(STORED);
+ expect(existsSync(join(secretsDir(vault), "keyfile"))).toBe(false);
+ });
+
+ test("an empty store contributes nothing: the answer is byte-identical to the bare redactor", () => {
+ const raw = `upstream probe failed: ${STORED} refused`;
+ const response = internalErrorResponse("err-4", new Error(raw), vault, TRANSPORT_REACH.remote);
+ expect(response.error?.message).toBe(
+ `internal error: ${redactErrorForCaller(raw, vault, TRANSPORT_REACH.remote)}`,
+ );
+ });
+
+ test("the tools/call error envelope scrubs the literal at remote reach", async () => {
+ storeCredential();
+ writeMachineConfig(`vault: ${JSON.stringify(vault)}\n`);
+ const server = new MCPServer(
+ { vault, configPath, repoRoot: null },
+ { reach: TRANSPORT_REACH.remote },
+ );
+ // `artifact_get` on a well-formed but absent id throws the plain Error
+ // `unknown or expired artifact_id: <id>` - the caller-controlled echo
+ // the tools/call catch redacts before the envelope leaves.
+ const response = await server.handleRequest({
+ jsonrpc: "2.0",
+ id: "call-1",
+ method: "tools/call",
+ params: { name: "brain_artifact_get", arguments: { artifact_id: `probe-${STORED}` } },
+ });
+ const rendered = JSON.stringify(response);
+ expect(rendered).not.toContain(STORED);
+ expect(rendered).toContain(REDACTION_PLACEHOLDER);
+ });
+});
diff --git a/tests/mcp/hygiene-link-integrity.test.ts b/tests/mcp/hygiene-link-integrity.test.ts
index 6618f6b0..167ea9ca 100644
--- a/tests/mcp/hygiene-link-integrity.test.ts
+++ b/tests/mcp/hygiene-link-integrity.test.ts
@@ -74,6 +74,7 @@ test("the detector tuple and its input-schema enum stay in lockstep", () => {
"usefulness",
"slug-collisions",
"tags",
+ "frontmatter-tags",
"capture-scope",
]);
const schema = HYGIENE_TOOLS[0]!.inputSchema as any;
diff --git a/tests/mcp/ingest-plan-format-reach.test.ts b/tests/mcp/ingest-plan-format-reach.test.ts
index 8c631ad1..92b78672 100644
--- a/tests/mcp/ingest-plan-format-reach.test.ts
+++ b/tests/mcp/ingest-plan-format-reach.test.ts
@@ -10,12 +10,13 @@
*/
import { afterEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { hashFile, manifestPath } from "../../src/core/brain/ingest/content-manifest.ts";
import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
import { MCPServer } from "../../src/mcp/server.ts";
@@ -105,3 +106,33 @@ describe("format skips at remote reach", () => {
expect(JSON.stringify(remote["batches"])).not.toContain(PRIVATE_PATH);
});
});
+
+describe("wire emission of the extraction contract (t_586d5d8b)", () => {
+ test("an unchanged contract emits no contract keys", async () => {
+ // No manifest on disk reads back as current-shaped under the live
+ // contract, so nothing about the contract may reach the wire.
+ const result = structured(await plan(fixture(false)));
+ expect(result["contract_changed"]).toBeUndefined();
+ expect(result["contract_changed_files"]).toBeUndefined();
+ });
+
+ test("a v1 manifest surfaces contract_changed with the reprocess count", async () => {
+ const f = fixture(false, TRANSPORT_REACH.local);
+ const path = manifestPath(f.vault);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(
+ path,
+ JSON.stringify({
+ schema_version: 1,
+ entries: { "Clips/open.md": hashFile(join(f.vault, "Clips", "open.md")) },
+ }),
+ "utf8",
+ );
+ // readFileSync pins that the fixture really wrote the bytes it hashes.
+ expect(readFileSync(join(f.vault, "Clips", "open.md"), "utf8")).toContain("Open");
+
+ const result = structured(await plan(f));
+ expect(result["contract_changed"]).toBe(true);
+ expect(result["contract_changed_files"]).toBe(1);
+ });
+});
diff --git a/tests/mcp/session-summary-tool.test.ts b/tests/mcp/session-summary-tool.test.ts
index 28d49d21..6d3cd08a 100644
--- a/tests/mcp/session-summary-tool.test.ts
+++ b/tests/mcp/session-summary-tool.test.ts
@@ -86,6 +86,44 @@ describe("brain_session_summary tool", () => {
expect(got["digest"]).toBeUndefined();
});
+ test("found:false is byte-identical (no divergence keys on the miss)", async () => {
+ const response = await call({ operation: "get", session_id: "missing" });
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ // The wire text is the structured payload serialized with indent 2;
+ // byte-identity means exactly this string and nothing else.
+ expect(result.content[0]!.text).toBe(JSON.stringify({ found: false }, null, 2));
+ });
+
+ test("get after two differing writes carries the additive divergence keys", async () => {
+ await call({ operation: "write", session_id: "dv", decisions: ["first take"] });
+ await call({ operation: "write", session_id: "dv", decisions: ["second take"] });
+
+ const got = payload(await call({ operation: "get", session_id: "dv" }));
+ expect(got["found"]).toBe(true);
+ expect(got["digest_count"]).toBe(2);
+ expect(got["divergent"]).toBe(true);
+ const records = got["records"] as Array<Record<string, unknown>>;
+ expect(records.length).toBe(2);
+ for (const record of records) {
+ expect(typeof record["id"]).toBe("string");
+ expect(typeof record["created_at"]).toBe("string");
+ expect(typeof record["content_hash"]).toBe("string");
+ }
+ // id/hash lists, never full payload echoes.
+ expect(JSON.stringify(records)).not.toContain("first take");
+ const digest = got["digest"] as Record<string, unknown>;
+ expect(digest["decisions"]).toEqual(["second take"]);
+ });
+
+ test("a single-record get adds digest_count and no divergence keys", async () => {
+ await call({ operation: "write", session_id: "solo", decisions: ["only take"] });
+ const got = payload(await call({ operation: "get", session_id: "solo" }));
+ expect(got["found"]).toBe(true);
+ expect(got["digest_count"]).toBe(1);
+ expect("divergent" in got).toBe(false);
+ expect("records" in got).toBe(false);
+ });
+
test("write with no categories is an invalid-params error", async () => {
const response = await call({ operation: "write", session_id: "empty" });
expect(response.error).toBeDefined();
diff --git a/tests/mcp/vault-path-field.test.ts b/tests/mcp/vault-path-field.test.ts
new file mode 100644
index 00000000..05bd5cb8
--- /dev/null
+++ b/tests/mcp/vault-path-field.test.ts
@@ -0,0 +1,120 @@
+/**
+ * The `vault_path` field when the installation secret resolves through the
+ * vault's custody store and the store refuses.
+ *
+ * The field is the one value forty-five tools emit into model context
+ * precisely so host paths do not travel there; its contract says it
+ * degrades to a reason instead of raising. A `$secret:NAME` installation
+ * secret added two more refusals a locked or unresolvable store produces -
+ * both named errors whose own messages carry paths or raw reference
+ * values - and each must degrade through the same mapping, with a
+ * path-free reason, exactly like the unreadable-config condition beside
+ * it.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { loadOrCreateKey } from "../../src/core/brain/secrets/crypto.ts";
+import { clearHeldKey, wrapKeyfile } from "../../src/core/brain/secrets/envelope.ts";
+import { secretsDir, setSecret } from "../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+// Registers the named-secret resolver port config resolves references
+// through; without it the reference branch takes the unwired, generic
+// refusal and the per-cause degradations below cannot be exercised.
+import "../../src/core/secret-resolver.ts";
+import {
+ hostPathReference,
+ SECRET_REFERENCE_UNRESOLVED_REASON,
+ SECRET_STORE_KEYFILE_MISSING_REASON,
+ SECRET_STORE_LOCKED_REASON,
+} from "../../src/mcp/vault-path-field.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-vault-path-field-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ for (const k of ["O2B_INSTALLATION_SECRET", "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+
+afterEach(() => {
+ rmSync(tmp, { 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 configWithInstallationSecret(value: string): void {
+ writeFileSync(configPath, `installation_secret: "${value}"\n`, "utf8");
+}
+
+describe("vault_path on a $secret: installation secret", () => {
+ test("a locked custody store degrades to the named locked reason", () => {
+ configWithInstallationSecret("$secret:install_key");
+ setSecret(vault, {
+ name: "install_key",
+ value: fakeCredential("stored-install-", "key-44af"),
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ wrapKeyfile(keyPath, fakeCredential("vpf-wrap", "-phrase-", "42"), loadOrCreateKey(keyPath));
+ clearHeldKey(keyPath);
+
+ const field = hostPathReference(vault, { configPath });
+ expect(field).toEqual({ error: SECRET_STORE_LOCKED_REASON });
+ // The redaction contract holds in the degraded shape: neither the
+ // vault path nor the keyfile path travels.
+ expect(JSON.stringify(field)).not.toContain(vault);
+ expect(JSON.stringify(field)).not.toContain("keyfile");
+ });
+
+ test("an unresolvable reference degrades to the named reference reason", () => {
+ configWithInstallationSecret("$secret:absent_install_key");
+ const field = hostPathReference(vault, { configPath });
+ expect(field).toEqual({ error: SECRET_REFERENCE_UNRESOLVED_REASON });
+ expect(JSON.stringify(field)).not.toContain(vault);
+ expect(JSON.stringify(field)).not.toContain("absent_install_key");
+ });
+
+ test("a missing keyfile over held entries degrades to the named missing-keyfile reason", () => {
+ // The locked refusal's sibling state on the same resolution path: the
+ // read-only resolve now refuses instead of minting a fresh key over
+ // the surviving ciphertext, and the field degrades it like every other
+ // named store refusal.
+ configWithInstallationSecret("$secret:install_key");
+ setSecret(vault, {
+ name: "install_key",
+ value: fakeCredential("stored-install-", "key-91cd"),
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+ const keyPath = join(secretsDir(vault), "keyfile");
+ rmSync(keyPath);
+
+ const field = hostPathReference(vault, { configPath });
+ expect(field).toEqual({ error: SECRET_STORE_KEYFILE_MISSING_REASON });
+ // The refusal left no custody state behind.
+ expect(existsSync(keyPath)).toBe(false);
+ expect(JSON.stringify(field)).not.toContain(vault);
+ });
+
+ test("a plain installation secret still resolves to the opaque reference", () => {
+ configWithInstallationSecret("a".repeat(32));
+ const field = hostPathReference(vault, { configPath });
+ expect(typeof field).toBe("string");
+ expect(field as string).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
+ });
+});
diff --git a/uv.lock b/uv.lock
index 3c365a12..951b98e7 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.77.0"
+version = "1.78.0"
source = { editable = "." }