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

v0.10.9: Vault scope β€” single ignore policy, vault status/inspect, doctor lint

Sol Aitken73e85a1ace38
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 0cf539de..035e441a 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.8",
+ "version": "0.10.9",
"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 a882a227..0b2bfc64 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.8",
+ "version": "0.10.9",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7f8e144..04489f81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,94 @@ 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).
+## [0.10.9] - 2026-05-19
+
+Closes the "Vault Scope" feature: a single declarative exclusion
+policy in `Brain/_brain.yaml` (`vault.ignore_paths`) replaces the
+per-walker rules that used to drift between the search indexer and
+`scan-inline`. Operators get one-shot visibility through the new
+`o2b vault status` and `o2b vault inspect` verbs and an additive
+`vault` block on the MCP `second_brain_status` payload. `o2b brain
+doctor` warns when a path-style ignore entry points at nothing on
+disk. Companion design and impl plan at
+`docs/plans/2026-05-19-vault-scope-design.md` and
+`docs/plans/2026-05-19-vault-scope-impl.md`.
+
+### Removed
+
+- `search_ignore_paths` key from the flat plugin config
+ (`~/.config/open-second-brain/config.yaml`).
+- `OPEN_SECOND_BRAIN_SEARCH_IGNORE` environment variable.
+
+ Both surfaces are dropped without a deprecation cycle: the project
+ has no live users to protect, and a shim that silently changes
+ walker behaviour would be a footgun. Configure exclusions in
+ `Brain/_brain.yaml` under `vault.ignore_paths`.
+
+### Added
+
+- `vault.ignore_paths` block in `Brain/_brain.yaml`. Single source
+ of truth for every vault walker (search indexer, `scan-inline`,
+ future scanners). Entries without `/` match a directory name at
+ any depth; entries with `/` are vault-relative POSIX paths
+ matched exactly. The block is optional - absent means "use the
+ built-in defaults"; an explicit empty list means "exclude
+ nothing".
+- Default exclusion set widens `.obsidian/cache` to `.obsidian` (the
+ full directory) and adds `Brain/.snapshots` explicitly. New
+ vaults created by `o2b brain init` get the populated block in
+ `_brain.yaml`; pre-v0.10.9 vaults inherit the same defaults at
+ runtime without a file change.
+- `o2b vault status [--vault <path>] [--json]` - walks the vault
+ under the active policy and reports inclusion counts plus a
+ per-rule list of excluded directories. Subtree descendants
+ inside an excluded directory are not enumerated again.
+- `o2b vault inspect <relpath> [--vault <path>] [--json]` -
+ point-check whether one vault-relative path is included by the
+ active policy, with the matched rule and source.
+- MCP `second_brain_status` payload gains an additive `vault`
+ block: `ignore_source`, the classified `rules` list, and
+ aggregate `included` / `excluded` counts. Per-path detail stays
+ in the CLI.
+- `o2b brain doctor` lint `vault-ignore-missing-path` - warning
+ emitted when a path-style entry under `vault.ignore_paths` does
+ not exist on disk. Only fires when the operator declared the
+ block themselves (the built-in default set may list paths that
+ legitimately don't exist in a given vault).
+
+### Changed
+
+- `src/core/vault-scope` is the new home of the shared exclusion
+ policy: `DEFAULT_VAULT_IGNORE_PATHS`, `VaultIgnoreRule`,
+ `matchIgnore`, `resolveVaultScope`, `walkVaultScope`,
+ `inspectPath`. The search indexer (`src/core/search/walker.ts`)
+ and `scan-inline` (`src/core/brain/inline-scan.ts`) both delegate
+ ignore decisions to `matchIgnore`; previously each maintained
+ its own list of skip-paths.
+- `ResolvedSearchConfig.ignorePaths: ReadonlyArray<string>` is
+ replaced by `ignoreRules: ReadonlyArray<VaultIgnoreRule>`. The
+ string-array field is removed entirely (no internal caller other
+ than the walker read it).
+- `scan-inline` `--exclude` flag stays as narrowing on top of the
+ shared set. The hardcoded `Brain` directory skip is preserved -
+ scan-inline must never recurse into the derived layer regardless
+ of operator policy; `Brain` is appended to the effective rule
+ set in code, not in `_brain.yaml`.
+- `resolveVaultScope` fails closed when `Brain/_brain.yaml` exists
+ but is malformed or unreadable. Missing config still falls back to
+ built-in defaults for older vaults, but a broken declared policy no
+ longer silently drops custom exclusions.
+
+### Migration
+
+No vault-data migration is required. Vaults whose `Brain/_brain.yaml`
+does not include a `vault:` block continue to use the built-in
+default set on this release. Vaults that previously set
+`search_ignore_paths` (in the flat plugin config) or
+`OPEN_SECOND_BRAIN_SEARCH_IGNORE` (env) should copy the entries
+into `vault.ignore_paths`; both legacy surfaces have no effect on
+v0.10.9 onwards.
+
## [0.10.8] - 2026-05-19
Closes Β§32 (retire `event_log_append` from every agent-facing surface
diff --git a/README.md b/README.md
index 4c4b1926..84192b71 100644
--- a/README.md
+++ b/README.md
@@ -147,6 +147,10 @@ o2b brain import-session Replay signals from a Claude/Codex/Hermes session
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 migrate-frontmatter (CLI-only) Rewrite legacy `status:` keys to `_status:`
+# Vault scope (single exclusion policy for every vault walker)
+o2b vault status Walks the vault under the active policy; reports include / exclude counts and which rules fired
+o2b vault inspect <relpath> Point-check one vault-relative path; reports matched rule, source, and whether the path exists on disk
+
# Discipline (daily logging-discipline cron)
o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime activity); status ok | info | alert
o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 41c2c51a..ed31a968 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -28,7 +28,7 @@ its own, plus a sibling derived-index directory.
```text
<vault>/
β”œβ”€β”€ Brain/ # observing memory (agent-writable)
-β”‚ β”œβ”€β”€ _brain.yaml # schema, thresholds, retention
+β”‚ β”œβ”€β”€ _brain.yaml # schema, thresholds, retention, vault.ignore_paths
β”‚ β”œβ”€β”€ _BRAIN.md # operating manual for agents
β”‚ β”œβ”€β”€ active.md # derived: confirmed + quarantine + recently retired
β”‚ β”œβ”€β”€ inbox/ # raw taste signals
diff --git a/docs/plans/2026-05-19-vault-scope-design.md b/docs/plans/2026-05-19-vault-scope-design.md
new file mode 100644
index 00000000..163c66d3
--- /dev/null
+++ b/docs/plans/2026-05-19-vault-scope-design.md
@@ -0,0 +1,595 @@
+# v0.10.9 β€” Vault Scope
+
+Closes the "Vault Scope" gap: data the plugin owns still lives only in
+`Brain/`, but everything else under the vault is walked through a single
+shared exclusion policy. One source of truth in `Brain/_brain.yaml`,
+two CLI verbs for visibility (`o2b vault status`, `o2b vault inspect`),
+one `o2b brain doctor` check for stale entries. Closed in one release.
+
+## 1. Problem
+
+Two vault walkers exist today, each with its own private rules:
+
+- `src/core/search/walker.ts` reads ignore paths from
+ `search_ignore_paths` (flat `config.yaml`) or the env variable
+ `OPEN_SECOND_BRAIN_SEARCH_IGNORE`. Default set includes
+ `.obsidian/cache` but not the whole `.obsidian` directory.
+- `src/core/brain/inline-scan.ts` has its own hard-coded
+ `HARD_SKIP_DIRS` constant. It excludes the whole `.obsidian`
+ directory, plus `Brain` (so inline markers cannot self-reference).
+
+The two lists drift. `.obsidian/cache` vs `.obsidian` is the visible
+example; future scanners will reinvent the same list a third time.
+There is also no way for the operator to ask the system "which files
+do you actually look at, and which are excluded and why" without
+reading source.
+
+The plugin already has a nested-YAML config file at
+`Brain/_brain.yaml` (handled by `src/core/brain/policy.ts`). It is
+the natural home for a vault-wide exclusion policy.
+
+## 2. Goals
+
+1. One declarative source of truth: `Brain/_brain.yaml` field
+ `vault.ignore_paths`. All vault walkers (search indexer,
+ `scan-inline`, any future scanner) read the same list.
+2. Updated default set: `.obsidian` (full directory, not just
+ `.obsidian/cache`) and `Brain/.snapshots` explicitly listed.
+3. Operator visibility: `o2b vault status` shows counts of included
+ files/directories and which exclusion rules fired; `o2b vault
+ inspect <relpath>` answers the same question for one specific
+ path with the matched rule.
+4. `scan-inline` also honours `vault.ignore_paths`. Its existing
+ `--path` and `--exclude` flags remain as narrowing on top of the
+ shared set; they never re-include something the shared set
+ excludes.
+5. `o2b brain doctor` warns when `vault.ignore_paths` contains a
+ path-style entry that does not exist in the vault.
+6. No vault-data migration. No public MCP-contract change (the
+ `second_brain_status` JSON gains a new `vault` field; existing
+ fields are untouched). All in v0.10.9.
+
+## 3. Non-goals
+
+- No backward-compatibility for `search_ignore_paths` /
+ `OPEN_SECOND_BRAIN_SEARCH_IGNORE`. The project has no live users to
+ protect; both surfaces are deleted in this release, no
+ deprecation period.
+- No GUI / dashboard / web view. Status is CLI + MCP JSON only.
+- No file-level glob patterns (`*.tmp`, `**/foo.md`). Today's two
+ walkers only need directory-name and exact-path semantics; we
+ match that exactly.
+- No new env variables. Path of last resort for tweaking exclusions
+ is editing `Brain/_brain.yaml`.
+
+## 4. `_brain.yaml`: new optional `vault` block
+
+```yaml
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+ - .open-second-brain
+ - .obsidian
+ - .trash
+ - .stversions
+ - Brain/.snapshots
+```
+
+Same shape as the existing `discipline_report.watched_paths` list,
+so `parseBrainYaml` handles it without a parser change.
+
+Rule semantics (lifted verbatim from the current
+`src/core/search/walker.ts:parseIgnore`):
+
+- Entry without `/` (e.g. `node_modules`): bare directory name.
+ Matched against any directory at any depth in the vault tree.
+- Entry containing `/` (e.g. `Brain/.snapshots`): vault-relative
+ exact path. Matched when the directory's relative path equals
+ this entry.
+
+`ignore_paths` is the only field under `vault` for v0.10.9. The
+block itself is optional. Three cases:
+
+| `vault` block | `ignore_paths` | Effective rules |
+|---|---|---|
+| absent | n/a | built-in default set |
+| present, `ignore_paths` absent | n/a | built-in default set |
+| present, `ignore_paths` empty list | `[]` | empty (excludes nothing) |
+| present, populated | `[a, b, ...]` | exactly that list |
+
+Empty list is a valid explicit "include everything" toggle; we do
+not silently substitute defaults when the operator has stated an
+intent.
+
+Validation rules:
+
+- Each entry is a non-empty string.
+- Same character allow-list as `primary_agent`
+ (`formatPrimaryAgentYamlValue`): reject C0 control characters and
+ the unquoted-YAML hazards `"`, `\`, `\n`, `\r`. A bad entry fails
+ config load with a `BrainConfigError` field
+ `vault.ignore_paths[<n>]`.
+- Unknown top-level fields under `vault:` produce a warning (same
+ forward-compat pattern as `discipline_report`).
+
+Validator and writer (`DEFAULT_BRAIN_CONFIG_YAML`) both ship with
+the default list. New vaults created by `o2b brain init` see the
+block in the file; existing vaults without the block get the same
+defaults at runtime without anyone touching their file.
+
+## 5. `vault-scope`: single resolver, single matcher
+
+New module `src/core/vault-scope/index.ts`. Pure functions, no I/O
+other than reading `Brain/_brain.yaml` once via the existing loader.
+
+```ts
+export interface VaultIgnoreRule {
+ readonly raw: string; // exactly as written in _brain.yaml
+ readonly kind: "name" | "path"; // bare name vs vault-relative
+}
+
+export interface VaultScope {
+ readonly ignorePaths: ReadonlyArray<string>;
+ readonly rules: ReadonlyArray<VaultIgnoreRule>;
+ readonly source: "_brain.yaml" | "defaults";
+}
+
+export function resolveVaultScope(vault: string): VaultScope;
+```
+
+`resolveVaultScope` reads `Brain/_brain.yaml`; if the file is
+missing, falls back to defaults silently so pre-v0.10.9 vaults keep
+working. If the file exists but is malformed or unreadable, the
+resolver fails closed instead of silently defaulting, because dropping
+custom exclusions can cause search / scan-inline to ingest paths the
+operator meant to hide. If `vault.ignore_paths` is set, returns those
+rules with `source: "_brain.yaml"`. Otherwise returns the defaults
+with `source: "defaults"`.
+
+Matching:
+
+```ts
+export interface IgnoreMatch {
+ readonly excluded: boolean;
+ readonly rule: VaultIgnoreRule | null;
+ readonly matchedAt: string | null; // POSIX rel-path of the
+ // segment that triggered
+ // the match
+}
+
+export function matchIgnore(
+ relPath: string, // POSIX, vault-relative,
+ // empty string == vault root
+ rules: ReadonlyArray<VaultIgnoreRule>,
+): IgnoreMatch;
+```
+
+Semantics: walk `relPath` segment by segment. For each prefix:
+
+- if any rule of kind `name` matches the segment name, exclude;
+- if any rule of kind `path` matches the prefix exactly, exclude;
+- otherwise the prefix is fine, continue.
+
+`matchedAt` is the shortest prefix that triggered the match. For
+`.obsidian/plugins/foo/note.md` it would be `.obsidian`.
+
+### 5.1 Default rule set
+
+```ts
+export const DEFAULT_VAULT_IGNORE_PATHS: ReadonlyArray<string> =
+ Object.freeze([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+ ]);
+```
+
+This constant lives in `vault-scope` and is the sole owner of the
+default list. `src/core/search/index.ts:DEFAULT_IGNORE_PATHS` and
+`src/core/brain/inline-scan.ts:HARD_SKIP_DIRS` are deleted.
+
+### 5.2 Vault walker
+
+A single fs walker for the status verb:
+
+```ts
+export interface VaultScopeWalk {
+ readonly includedFiles: number;
+ readonly includedDirs: number;
+ readonly excludedDirs:
+ ReadonlyArray<{ relPath: string; rule: VaultIgnoreRule }>;
+ readonly excludedFiles:
+ ReadonlyArray<{ relPath: string; rule: VaultIgnoreRule }>;
+}
+
+export function walkVaultScope(
+ vault: string,
+ scope: VaultScope,
+): VaultScopeWalk;
+```
+
+Lifts the acyclic-symlink guard from `src/core/search/walker.ts`
+(realpath + `seenDirs` set, refuses to leave the vault root). The
+search walker keeps its existing generator surface; the
+`walkVaultScope` here is a separate, status-oriented call - it
+collects counts and the excluded list, it does not yield files,
+and it does not care about file extension (status counts every
+file, not only `.md`, because exclusions apply uniformly).
+
+Reporting semantics: when a directory is excluded, the walker
+records that directory in `excludedDirs` and stops recursing
+into it. Files and subdirectories inside an excluded subtree are
+NOT counted separately in `excludedFiles` / `excludedDirs` - one
+entry at the root of the excluded subtree is the whole report.
+This keeps both the CLI text output and the JSON shape stable
+regardless of how deep the excluded subtree is.
+
+## 6. Walker rewrites
+
+### 6.1 search walker
+
+`src/core/search/walker.ts`:
+
+- Remove the local `parseIgnore(...)` helper.
+- `walkVault(config)` accepts `config.ignoreRules: ReadonlyArray<VaultIgnoreRule>`
+ in addition to (or instead of) `config.ignorePaths`. Implementation
+ uses `matchIgnore` from `vault-scope` for directory- and file-
+ level decisions.
+- All other invariants stay: deterministic sorted traversal,
+ symlink loop protection, `*.md`-only file filter.
+
+`src/core/search/index.ts`:
+
+- Delete `DEFAULT_IGNORE_PATHS`.
+- Delete `parseIgnorePaths`.
+- Replace
+ `ignorePaths = parseIgnorePaths(envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_IGNORE", "search_ignore_paths"))`
+ with
+ `const scope = resolveVaultScope(opts.vault); const ignoreRules = scope.rules;`.
+
+`src/core/search/types.ts`:
+
+- `ResolvedSearchConfig.ignorePaths` is replaced by
+ `readonly ignoreRules: ReadonlyArray<VaultIgnoreRule>`.
+ The string-array field is removed entirely - no internal caller
+ outside the walker reads it today (grep confirms only
+ `walker.ts` reads `config.ignorePaths`), so the rule list is
+ the simpler shape.
+- Test helper `tests/helpers/search-fixtures.ts:makeConfig` keeps
+ its convenience `ignorePaths?: ReadonlyArray<string>` parameter
+ for terse fixtures, but builds `ignoreRules` internally before
+ freezing the config. Tests that read the field for assertions
+ (`tests/core/search/config.test.ts`) switch to
+ `cfg.ignoreRules.map((r) => r.raw)`.
+
+### 6.2 scan-inline walker
+
+`src/core/brain/inline-scan.ts`:
+
+- Delete the hard-coded `HARD_SKIP_DIRS` array.
+- Inside `scanInline(vault, opts)`:
+ 1. `const scope = resolveVaultScope(vault);`
+ 2. Build the effective rule set:
+ `const rules = [...scope.rules, { raw: "Brain", kind: "name" }, ...userExcludeRules];`
+ The `Brain` rule is appended unconditionally - inline markers
+ inside `Brain/` would self-reference the derived layer, and
+ this invariant is too important to depend on `_brain.yaml`
+ not having been edited away.
+ 3. Use `matchIgnore` for directory- and file-level decisions.
+- `opts.exclude` becomes a list of `VaultIgnoreRule`s (kind `path`
+ for everything, since CLI semantics today require an exact
+ prefix match - we preserve that).
+- `opts.paths` (the include-narrowing) remains as-is, untouched.
+
+`--exclude` is purely narrowing on top of the shared set. There is
+no flag to re-include something the shared set excluded; the
+operator who needs that edits `_brain.yaml` (rare enough that a
+flag would be premature).
+
+## 7. CLI: `o2b vault status` and `o2b vault inspect`
+
+New top-level subcommand `vault`. Dispatcher mirrors the existing
+`o2b brain` and `o2b search` pattern: tiny `src/cli/vault.ts` that
+routes to per-verb files under `src/cli/vault/verbs/`.
+
+### 7.1 `o2b vault status`
+
+```
+o2b vault status [--vault <path>] [--json]
+```
+
+Text output:
+
+```
+vault: /root/vault
+ignore source: _brain.yaml
+
+included: 1247 files, 89 directories
+excluded: 3 directories, 0 files
+
+excluded directories:
+ .obsidian rule .obsidian (name)
+ Brain/.snapshots rule Brain/.snapshots (path)
+ Notes/.trash rule .trash (name)
+```
+
+JSON output:
+
+```json
+{
+ "vault": "/root/vault",
+ "ignore_source": "_brain.yaml",
+ "rules": [
+ {"raw": ".git", "kind": "name"},
+ ...
+ ],
+ "included": {"files": 1247, "dirs": 89},
+ "excluded": {
+ "dirs": [
+ {"rel_path": ".obsidian", "rule": ".obsidian", "kind": "name"},
+ ...
+ ],
+ "files": []
+ }
+}
+```
+
+Failure modes:
+
+- Vault path missing: exit 1, single-line stderr error
+ (matches existing `o2b brain doctor` convention).
+- `_brain.yaml` unreadable: status falls back to defaults but
+ prints a `warning:` line on stderr.
+
+### 7.2 `o2b vault inspect <relpath>`
+
+```
+o2b vault inspect <relpath> [--vault <path>] [--json]
+```
+
+Reads `relpath` as vault-relative POSIX. Resolves the vault scope
+(no fs walk), runs `matchIgnore`, prints the result.
+
+Text output - included case:
+
+```
+relpath: Notes/idea.md
+status: included
+```
+
+Text output - excluded case:
+
+```
+relpath: .obsidian/plugins/foo/note.md
+status: excluded
+matched rule: .obsidian (name)
+matched at: .obsidian
+source: _brain.yaml
+```
+
+JSON output:
+
+```json
+{
+ "relpath": ".obsidian/plugins/foo/note.md",
+ "status": "excluded",
+ "matched_rule": {"raw": ".obsidian", "kind": "name"},
+ "matched_at": ".obsidian",
+ "source": "_brain.yaml"
+}
+```
+
+Failure modes:
+
+- `relpath` absent or empty: exit 2, usage hint.
+- Path traverses outside the vault (`..`): exit 2, error.
+- Path does not exist on disk: still reports the rule decision
+ (because the question "would the walker include this if it
+ existed" is meaningful), but adds `status: excluded (not found
+ on disk)` or `status: included (not found on disk)` so the
+ operator knows.
+
+## 8. MCP `second_brain_status`: new `vault` field
+
+Existing payload gains one block. No existing keys change.
+
+```jsonc
+{
+ "config_path": "...",
+ "config_exists": true,
+ "config_keys": [...],
+ "config": {...},
+ "vault_path": "...",
+ "vault_exists": true,
+ "vault": {
+ "ignore_source": "_brain.yaml",
+ "rules": [
+ {"raw": ".obsidian", "kind": "name"},
+ ...
+ ],
+ "included": {"files": 1247, "dirs": 89},
+ "excluded": {"dirs": 3, "files": 0}
+ },
+ "brain": {...},
+ "search": {...}
+}
+```
+
+Only aggregate counts under `excluded` (no per-path list). MCP
+payloads should stay small; the per-path detail lives in the CLI
+verb. If the vault path is missing, the `vault` block is omitted
+entirely - same convention `brain` and `search` already use.
+
+The resolver itself fails closed on a malformed `_brain.yaml`
+(Β§5), but `second_brain_status` is a read-only diagnostic, not a
+walker β€” failing the whole response would hide the brain / config /
+search blocks that the operator needs to triage the same problem.
+The tool therefore catches the resolver error and degrades the
+`vault` block to `{"error": "<message>"}`. The other blocks stay
+intact. The `search` block already has this shape (`{exists: false,
+error: ...}`) for the same reason. Callers reading the JSON should
+treat both shapes as "block is present but currently unreadable".
+
+## 9. `o2b brain doctor`: new check
+
+New check `checkVaultIgnore` runs after `checkConfig`. Logic:
+
+```
+scope = resolveVaultScope(vault)
+if scope.source != "_brain.yaml":
+ return // defaults can list paths that don't exist
+ // in this particular vault, that's fine
+for rule in scope.rules where rule.kind == "path":
+ if not existsSync(join(vault, rule.raw)):
+ emit warning {
+ code: "vault-ignore-missing-path",
+ message: f"vault.ignore_paths entry {rule.raw!r} "
+ "does not exist in this vault",
+ }
+```
+
+Bare-name rules (`kind: "name"`) are not checked - the absence of
+a `.git` or `node_modules` directory is not an error. Path-style
+entries are explicit declarations of "this specific path exists
+and I want it excluded", so a missing entry is more often a typo
+than a deliberate forward-declaration.
+
+## 10. Breaking changes
+
+Removed in v0.10.9 (no deprecation cycle):
+
+- `search_ignore_paths` key in `~/.config/open-second-brain/config.yaml`.
+- `OPEN_SECOND_BRAIN_SEARCH_IGNORE` environment variable.
+
+Default exclusion set changes:
+
+- `.obsidian/cache` widened to `.obsidian` (the whole directory).
+ Effect: `.md` files inside Obsidian plugin folders no longer
+ appear in `o2b search` results. Operators who rely on indexing
+ Obsidian plugin notes (rare) can opt back in by setting
+ `vault.ignore_paths` explicitly without `.obsidian`.
+- `Brain/.snapshots` added explicitly. The directory contains only
+ `.tar.zst` archives today, so practical effect is zero; the
+ entry makes the policy self-documenting.
+
+CHANGELOG entry under `[0.10.9]`:
+
+```
+### Removed
+- `search_ignore_paths` config key and
+ `OPEN_SECOND_BRAIN_SEARCH_IGNORE` environment variable.
+ Configure exclusions in `Brain/_brain.yaml` under
+ `vault.ignore_paths`.
+
+### Added
+- `vault.ignore_paths` field in `Brain/_brain.yaml`. Single source
+ of truth for vault walkers (search indexer, scan-inline, future
+ scanners). Default set widens `.obsidian/cache` to `.obsidian`
+ and adds `Brain/.snapshots` explicitly.
+- `o2b vault status` - one-shot view of how many files/directories
+ the current policy would include, and which exclusion rules
+ fired.
+- `o2b vault inspect <relpath>` - point-check for one path with
+ the matched rule.
+- `second_brain_status` MCP payload gains a `vault` block
+ mirroring the CLI status counts.
+- `o2b brain doctor` warns when a path-style `vault.ignore_paths`
+ entry does not exist in the vault
+ (`vault-ignore-missing-path`).
+```
+
+## 11. Test plan
+
+TDD order: write failing tests, then implementation.
+
+### 11.1 New test files
+
+- `tests/core/vault-scope.test.ts`
+ - `matchIgnore` against a representative set of paths.
+ - `resolveVaultScope` reads `_brain.yaml` when present.
+ - `resolveVaultScope` falls back to defaults when block absent.
+ - Empty `ignore_paths: []` is honoured (excludes nothing).
+ - Character allow-list rejects entries with control chars / quotes.
+ - `walkVaultScope` correctly counts a small fixture with two
+ excluded directories.
+
+- `tests/cli/vault.test.ts`
+ - `o2b vault status` text output on a fixture.
+ - `o2b vault status --json` shape stable.
+ - `o2b vault inspect` for included path, excluded by name rule,
+ excluded by path rule, not found on disk, path traversal.
+
+### 11.2 Existing test files - updates
+
+- `tests/core/search/config.test.ts` - drop tests that exercised
+ `search_ignore_paths` / `OPEN_SECOND_BRAIN_SEARCH_IGNORE`. Add
+ test that confirms env / config has no effect on ignore set.
+- `tests/core/search/walker.test.ts` - fixtures now pass `ignoreRules`
+ instead of (or alongside) `ignorePaths`. The `makeConfig` helper
+ in `tests/helpers/search-fixtures.ts` builds rules from the
+ default list.
+- `tests/core/brain.inline-scan.test.ts` - add cases:
+ - `.obsidian/plugins/foo/note.md` is skipped even though the
+ container is a plain directory with `.md` inside.
+ - `Brain/` always skipped regardless of `_brain.yaml`.
+ - User `--exclude foo` excludes `foo/` even when foo is not in
+ `_brain.yaml`.
+- `tests/core/brain.policy.test.ts` - parser accepts `vault:` block,
+ rejects bad characters in entries, treats missing block as
+ defaults.
+- `tests/core/brain.doctor.test.ts` - new case for
+ `vault-ignore-missing-path` warning.
+- `tests/mcp/tools.test.ts` - assert `second_brain_status` payload
+ contains the new `vault` block on a populated vault.
+
+### 11.3 e2e
+
+`tests/e2e/brain-capture-and-fields.test.ts` already exercises
+`scan-inline` end-to-end. Extend with a step that places an
+`@osb` marker inside `.obsidian/plugins/x/note.md` and confirms
+`scan-inline` does NOT pick it up.
+
+## 12. Out of scope / deferred
+
+- File-glob patterns (`*.tmp`, `**/*.draft.md`) in
+ `vault.ignore_paths`. Today's two walkers do not need them.
+ Trigger to revisit: a real operator request with a pattern that
+ cannot be expressed as a directory name or vault-relative path.
+- Per-walker overrides (e.g. "scan-inline should also skip
+ `Drafts/` but search should not"). Both walkers currently use
+ identical exclusions plus per-call narrowing; if asymmetry is
+ ever needed, add a `walker_overrides` sub-block under `vault:`
+ at that time, not preemptively.
+- Auto-rewrite of legacy `search_ignore_paths` into
+ `vault.ignore_paths`. The project has no live users; one-shot
+ migration tooling is dead weight.
+
+## 13. Implementation order
+
+1. `tests/core/vault-scope.test.ts` (failing) + skeleton module.
+2. `src/core/vault-scope/index.ts` implementation.
+3. `src/core/brain/types.ts` + `policy.ts` for `vault:` block;
+ `tests/core/brain.policy.test.ts` updates.
+4. Walker rewrites:
+ 1. `src/core/search/walker.ts` + `index.ts`, with
+ `tests/core/search/walker.test.ts` and `config.test.ts`
+ updates.
+ 2. `src/core/brain/inline-scan.ts`, with
+ `tests/core/brain.inline-scan.test.ts` updates.
+5. New CLI verbs:
+ 1. `src/cli/vault.ts` + verb files.
+ 2. `src/cli/main.ts` dispatcher entry.
+ 3. `tests/cli/vault.test.ts`.
+6. MCP payload extension:
+ 1. `src/mcp/tools.ts:toolStatus`.
+ 2. `tests/mcp/tools.test.ts`.
+7. Doctor check:
+ 1. `src/core/brain/doctor.ts:checkVaultIgnore`.
+ 2. `tests/core/brain.doctor.test.ts`.
+8. CHANGELOG + bumps + final `bun test` + manual `o2b vault status`
+ on `/root/vault`.
diff --git a/docs/plans/2026-05-19-vault-scope-impl.md b/docs/plans/2026-05-19-vault-scope-impl.md
new file mode 100644
index 00000000..8a124af5
--- /dev/null
+++ b/docs/plans/2026-05-19-vault-scope-impl.md
@@ -0,0 +1,2007 @@
+# Vault Scope (v0.10.9) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Close the "Vault Scope" gap: introduce `vault.ignore_paths` in `Brain/_brain.yaml` as the single source of truth for every vault walker (search indexer, scan-inline), expose visibility via `o2b vault status` / `o2b vault inspect` and the extended `second_brain_status` MCP payload, and warn via `o2b brain doctor` when an ignore entry points at a missing path.
+
+**Architecture:** A new module `src/core/vault-scope` owns the default exclusion set, the rule shape, the resolver and the matcher. The search indexer and scan-inline walker delegate ignore decisions to that module via `matchIgnore`. A new `o2b vault` CLI dispatcher with two verbs (`status`, `inspect`) and a new field on `second_brain_status` give the operator one-shot visibility. Doctor adds one warning lint.
+
+**Tech Stack:** TypeScript on Bun runtime (`bun test` for unit + e2e), `bun:test` API, existing repo helpers (`tests/helpers/run-cli.ts`, `tests/helpers/search-fixtures.ts`).
+
+**Spec:** `docs/plans/2026-05-19-vault-scope-design.md`. Read it once before starting Task 1.
+
+---
+
+## File Structure
+
+| File | Role |
+|---|---|
+| `src/core/vault-scope/index.ts` | NEW. `DEFAULT_VAULT_IGNORE_PATHS`, `VaultIgnoreRule`, `VaultScope`, `resolveVaultScope`, `matchIgnore`, `walkVaultScope`, `inspectPath`. |
+| `src/core/brain/types.ts` | MODIFY. Add `BrainVaultConfig` + `BrainConfig.vault?`. |
+| `src/core/brain/policy.ts` | MODIFY. Parse and validate the `vault:` block, extend `DEFAULT_BRAIN_CONFIG_YAML`. |
+| `src/core/brain/doctor.ts` | MODIFY. Add `checkVaultIgnore`. |
+| `src/core/search/types.ts` | MODIFY. Replace `ignorePaths: ReadonlyArray<string>` with `ignoreRules: ReadonlyArray<VaultIgnoreRule>`. |
+| `src/core/search/index.ts` | MODIFY. Delete `DEFAULT_IGNORE_PATHS`, `parseIgnorePaths`, and the env/config plumbing for `OPEN_SECOND_BRAIN_SEARCH_IGNORE` / `search_ignore_paths`. Call `resolveVaultScope`. |
+| `src/core/search/walker.ts` | MODIFY. Delete local `parseIgnore`; consume `ignoreRules` via `matchIgnore`. |
+| `src/core/brain/inline-scan.ts` | MODIFY. Delete `HARD_SKIP_DIRS`; resolve scope, append synthetic `Brain` name-rule + user excludes, route through `matchIgnore`. |
+| `src/cli/vault.ts` | NEW. `handleVaultSubcommand` dispatcher. |
+| `src/cli/vault/verbs/status.ts` | NEW. `cmdVaultStatus`. |
+| `src/cli/vault/verbs/inspect.ts` | NEW. `cmdVaultInspect`. |
+| `src/cli/vault/help-text.ts` | NEW. `VAULT_HELP` + `VAULT_VERB_HELP`. |
+| `src/cli/main.ts` | MODIFY. Dispatch case `"vault"` β†’ `handleVaultSubcommand`. |
+| `src/mcp/tools.ts` | MODIFY. Extend `toolStatus` with the `vault` block. |
+| `tests/core/vault-scope.test.ts` | NEW. Unit tests for resolver + matcher + walker + inspectPath. |
+| `tests/core/brain.policy.test.ts` | MODIFY. Cases for the new `vault:` block. |
+| `tests/core/brain.doctor.test.ts` | MODIFY. Case for `vault-ignore-missing-path`. |
+| `tests/core/search/walker.test.ts` | MODIFY. Adapt fixtures to `ignoreRules`. |
+| `tests/core/search/store.test.ts` | MODIFY. Adapt fixtures to `ignoreRules`. |
+| `tests/core/search/store.vec.test.ts` | MODIFY. Adapt fixtures to `ignoreRules`. |
+| `tests/core/search/config.test.ts` | MODIFY. Drop legacy env / config tests; assert that `OPEN_SECOND_BRAIN_SEARCH_IGNORE` / `search_ignore_paths` have NO effect. |
+| `tests/helpers/search-fixtures.ts` | MODIFY. `makeConfig` builds `ignoreRules` internally. |
+| `tests/core/brain.inline-scan.test.ts` | MODIFY. New cases: `.obsidian/plugins/foo/note.md` skipped; `Brain` always skipped; `--exclude` narrows. |
+| `tests/e2e/brain-capture-and-fields.test.ts` | MODIFY. Add marker inside `.obsidian/plugins/x/note.md` and confirm it is not picked up. |
+| `tests/cli/vault.test.ts` | NEW. CLI surface tests. |
+| `tests/mcp/tools.test.ts` | MODIFY (or NEW if absent). Assert `second_brain_status` payload contains the `vault` block. |
+| `CHANGELOG.md` | MODIFY. New `[0.10.9]` section. |
+| `package.json` + sync-version targets | MODIFY. Bump to `0.10.9` and run `bun run sync-version`. |
+
+---
+
+## Conventions for every task
+
+- **TDD:** write the failing test, run it to confirm it fails, then write the smallest implementation that makes it pass.
+- **Commit cadence:** one commit per task (or per major step inside a task). Commit message format follows the repo convention - see `git log -1` on the project for the current style. Do NOT include AI-attribution trailers unless the user explicitly asks for them.
+- **No git mutations from the agent without operator approval.** This plan documents commit points; the executing agent surfaces the commit messages for the operator. The operator runs `git commit` (or approves) themselves.
+- **Run mode:** `bun test <file>` for a single file, `bun test` for full suite. Use `--watch` only locally.
+- **Avoid `bun test -t '<name>'` for new tests** until at least one assertion is in place - bun's filter silently passes empty suites.
+
+---
+
+## Task 1: `vault-scope` skeleton + DEFAULT constants
+
+**Files:**
+- Create: `src/core/vault-scope/index.ts`
+- Create: `tests/core/vault-scope.test.ts`
+
+- [ ] **Step 1: Write the failing test for `DEFAULT_VAULT_IGNORE_PATHS` and rule types**
+
+`tests/core/vault-scope.test.ts`:
+
+```ts
+import { test, expect } from "bun:test";
+import {
+ DEFAULT_VAULT_IGNORE_PATHS,
+ type VaultIgnoreRule,
+} from "../../src/core/vault-scope/index.ts";
+
+test("DEFAULT_VAULT_IGNORE_PATHS contains the v0.10.9 baseline", () => {
+ expect([...DEFAULT_VAULT_IGNORE_PATHS]).toEqual([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+ ]);
+});
+
+test("DEFAULT_VAULT_IGNORE_PATHS is frozen", () => {
+ expect(Object.isFrozen(DEFAULT_VAULT_IGNORE_PATHS)).toBe(true);
+});
+
+test("VaultIgnoreRule kind union covers the two semantic cases", () => {
+ const a: VaultIgnoreRule = { raw: ".git", kind: "name" };
+ const b: VaultIgnoreRule = { raw: "Brain/.snapshots", kind: "path" };
+ expect(a.kind).toBe("name");
+ expect(b.kind).toBe("path");
+});
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: FAIL with `Cannot find module ... vault-scope/index.ts`.
+
+- [ ] **Step 3: Write the minimal module**
+
+`src/core/vault-scope/index.ts`:
+
+```ts
+/**
+ * Vault Scope β€” single source of truth for vault-wide exclusion
+ * policy.
+ *
+ * Anchored in docs/plans/2026-05-19-vault-scope-design.md Β§5.
+ */
+
+export interface VaultIgnoreRule {
+ /** Entry exactly as written in `Brain/_brain.yaml`. */
+ readonly raw: string;
+ /**
+ * `name` β€” match any directory whose basename equals `raw`,
+ * anywhere in the tree.
+ * `path` β€” match a vault-relative POSIX path exactly.
+ */
+ readonly kind: "name" | "path";
+}
+
+export const DEFAULT_VAULT_IGNORE_PATHS: ReadonlyArray<string> = Object.freeze([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+]);
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: PASS (3 tests).
+
+- [ ] **Step 5: Commit**
+
+Surface to operator: "Task 1 done. Suggested commit message: `feat(vault-scope): introduce module skeleton and default ignore set`". Wait for operator to commit.
+
+---
+
+## Task 2: `matchIgnore` matcher
+
+**Files:**
+- Modify: `src/core/vault-scope/index.ts`
+- Modify: `tests/core/vault-scope.test.ts`
+
+- [ ] **Step 1: Write failing tests for `matchIgnore`**
+
+Append to `tests/core/vault-scope.test.ts`:
+
+```ts
+import { matchIgnore } from "../../src/core/vault-scope/index.ts";
+
+const rules: ReadonlyArray<VaultIgnoreRule> = [
+ { raw: ".git", kind: "name" },
+ { raw: "node_modules", kind: "name" },
+ { raw: "Brain/.snapshots", kind: "path" },
+];
+
+test("matchIgnore returns excluded=false on a plain path", () => {
+ const r = matchIgnore("Notes/idea.md", rules);
+ expect(r.excluded).toBe(false);
+ expect(r.rule).toBeNull();
+ expect(r.matchedAt).toBeNull();
+});
+
+test("matchIgnore catches a bare-name rule at the root", () => {
+ const r = matchIgnore(".git/HEAD", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".git");
+ expect(r.matchedAt).toBe(".git");
+});
+
+test("matchIgnore catches a bare-name rule at any depth", () => {
+ const r = matchIgnore("deep/nested/.git/HEAD", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".git");
+ expect(r.matchedAt).toBe("deep/nested/.git");
+});
+
+test("matchIgnore catches a path rule by exact prefix", () => {
+ const r = matchIgnore("Brain/.snapshots/2026-05-19.tar.zst", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe("Brain/.snapshots");
+ expect(r.matchedAt).toBe("Brain/.snapshots");
+});
+
+test("matchIgnore does NOT match a path rule on a prefix collision", () => {
+ // "Brain/.snapshots-old" must NOT be eaten by "Brain/.snapshots".
+ const r = matchIgnore("Brain/.snapshots-old/x.md", rules);
+ expect(r.excluded).toBe(false);
+});
+
+test("matchIgnore on an empty relPath is excluded=false (vault root)", () => {
+ const r = matchIgnore("", rules);
+ expect(r.excluded).toBe(false);
+});
+
+test("matchIgnore with empty rules excludes nothing", () => {
+ const r = matchIgnore(".git/HEAD", []);
+ expect(r.excluded).toBe(false);
+});
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: FAIL with `matchIgnore is not a function`.
+
+- [ ] **Step 3: Implement `matchIgnore`**
+
+Append to `src/core/vault-scope/index.ts`:
+
+```ts
+export interface IgnoreMatch {
+ readonly excluded: boolean;
+ readonly rule: VaultIgnoreRule | null;
+ /** POSIX rel-path of the prefix that triggered the match, or null. */
+ readonly matchedAt: string | null;
+}
+
+/**
+ * Walk `relPath` segment by segment. For each prefix, check name-
+ * and path-rules. Return the shortest prefix that excludes, or
+ * `{excluded: false}` if no rule fires.
+ */
+export function matchIgnore(
+ relPath: string,
+ rules: ReadonlyArray<VaultIgnoreRule>,
+): IgnoreMatch {
+ if (relPath === "") {
+ return { excluded: false, rule: null, matchedAt: null };
+ }
+ const segments = relPath.split("/").filter((s) => s.length > 0);
+ let prefix = "";
+ for (const seg of segments) {
+ prefix = prefix === "" ? seg : `${prefix}/${seg}`;
+ for (const rule of rules) {
+ if (rule.kind === "name" && rule.raw === seg) {
+ return { excluded: true, rule, matchedAt: prefix };
+ }
+ if (rule.kind === "path" && rule.raw === prefix) {
+ return { excluded: true, rule, matchedAt: prefix };
+ }
+ }
+ }
+ return { excluded: false, rule: null, matchedAt: null };
+}
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: PASS (3 + 7 = 10 tests).
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `feat(vault-scope): add matchIgnore matcher with name/path rules`.
+
+---
+
+## Task 3: `_brain.yaml` types and parser support for `vault:` block
+
+**Files:**
+- Modify: `src/core/brain/types.ts`
+- Modify: `src/core/brain/policy.ts`
+- Modify: `tests/core/brain.policy.test.ts`
+
+- [ ] **Step 1: Write failing tests for the new block**
+
+Find `tests/core/brain.policy.test.ts` and append:
+
+```ts
+test("vault block: parses ignore_paths list", () => {
+ const path = writeYaml(`schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+ - Brain/.snapshots
+`);
+ const cfg = loadBrainConfig(path);
+ expect(cfg.vault?.ignore_paths).toEqual([".git", "node_modules", "Brain/.snapshots"]);
+});
+
+test("vault block: absent block leaves vault undefined", () => {
+ const path = writeYaml(`schema_version: 1\n`);
+ const cfg = loadBrainConfig(path);
+ expect(cfg.vault).toBeUndefined();
+});
+
+test("vault block: empty ignore_paths is honoured as explicit empty", () => {
+ const path = writeYaml(`schema_version: 1
+vault:
+ ignore_paths:
+`);
+ const cfg = loadBrainConfig(path);
+ expect(cfg.vault?.ignore_paths).toEqual([]);
+});
+
+test("vault block: entry with control char is rejected", () => {
+ const path = writeYaml(`schema_version: 1
+vault:
+ ignore_paths:
+ - "bad\\nentry"
+`);
+ expect(() => loadBrainConfig(path)).toThrow(/vault\.ignore_paths\[0\]/);
+});
+
+test("vault block: unknown sibling field emits a warning, not error", () => {
+ const path = writeYaml(`schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ unknown_extra: true
+`);
+ const { config, warnings } = loadBrainConfigDetailed(dirnameFor(path));
+ expect(config.vault?.ignore_paths).toEqual([".git"]);
+ expect(warnings.some((w) => w.message.includes("unknown_extra"))).toBe(true);
+});
+```
+
+*If `writeYaml` / `loadBrainConfig` / `loadBrainConfigDetailed` / `dirnameFor` helpers do not exist in this test file in this exact form, look at the top of `tests/core/brain.policy.test.ts` for the test scaffolding pattern in use and adapt the new tests to match - keep the SAME assertion shape and field paths.*
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `bun test tests/core/brain.policy.test.ts`
+Expected: FAIL β€” `vault` property does not exist on `BrainConfig`.
+
+- [ ] **Step 3: Extend types**
+
+In `src/core/brain/types.ts`, add (near the other block interfaces, before `BrainConfig`):
+
+```ts
+/**
+ * Vault-wide exclusion policy (`Brain/_brain.yaml` -> `vault:`).
+ * Single source of truth for every walker - search indexer,
+ * scan-inline, future scanners.
+ */
+export interface BrainVaultConfig {
+ /**
+ * Vault-relative POSIX paths or bare directory names. A bare
+ * name (no `/`) matches that directory anywhere in the tree;
+ * an entry with `/` is matched against the vault-relative path
+ * exactly. Order is preserved for `o2b vault status` output.
+ */
+ readonly ignore_paths: ReadonlyArray<string>;
+}
+```
+
+In the `BrainConfig` interface, add:
+
+```ts
+readonly vault?: BrainVaultConfig;
+```
+
+- [ ] **Step 4: Extend the parser and validator**
+
+In `src/core/brain/policy.ts`:
+
+1. Add `"vault"` to the `known` Set near the end of `validateBrainConfigDetailed`.
+2. After the `snapshots` validation block (around line 391) and BEFORE the `discipline_report` block, add:
+
+```ts
+let vault: BrainVaultConfig | undefined;
+if ("vault" in obj) {
+ const raw = obj["vault"];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
+ throw new BrainConfigError(
+ `block must be a map of keys; got ${describe(raw)}`,
+ "vault",
+ source,
+ );
+ }
+ const rawMap = raw as Record<string, unknown>;
+ let ignorePaths: ReadonlyArray<string> = [];
+ if ("ignore_paths" in rawMap) {
+ const list = rawMap["ignore_paths"];
+ // Block-list with no items (`ignore_paths:` followed by nothing)
+ // is parsed by parseBrainYaml as an empty array.
+ if (!Array.isArray(list)) {
+ throw new BrainConfigError(
+ `must be a list of strings; got ${describe(list)}`,
+ "vault.ignore_paths",
+ source,
+ );
+ }
+ const validated: string[] = [];
+ list.forEach((entry, i) => {
+ if (typeof entry !== "string") {
+ throw new BrainConfigError(
+ `must be a string; got ${describe(entry)}`,
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ const trimmed = entry.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "must be a non-empty string",
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ for (const bad of YAML_STRING_REJECTED_CHARS) {
+ if (trimmed.includes(bad)) {
+ throw new BrainConfigError(
+ `contains a disallowed character ${JSON.stringify(bad)}; ` +
+ "use a simple one-line path",
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ }
+ validated.push(trimmed);
+ });
+ ignorePaths = Object.freeze(validated);
+ }
+ // Forward-compat: unknown sub-keys -> warning.
+ for (const key of Object.keys(rawMap)) {
+ if (key !== "ignore_paths") {
+ warnings.push({
+ path: source ?? "<config>",
+ message: `vault.${key}: unknown field ignored (forward-compat)`,
+ });
+ }
+ }
+ vault = { ignore_paths: ignorePaths };
+}
+```
+
+3. In the final `BrainConfig` literal at the end of the function, add:
+
+```ts
+...(vault !== undefined ? { vault } : {}),
+```
+
+4. Also import `BrainVaultConfig` at the top of the file alongside the other type-only imports:
+
+```ts
+import type { BrainConfig, BrainVaultConfig, DisciplineReportConfig } from "./types.ts";
+```
+
+- [ ] **Step 5: Run tests to verify they pass**
+
+Run: `bun test tests/core/brain.policy.test.ts`
+Expected: PASS β€” including the 5 new vault-block tests plus all existing policy tests.
+
+- [ ] **Step 6: Update the default YAML body**
+
+In `src/core/brain/policy.ts`, replace `DEFAULT_BRAIN_CONFIG_YAML` so the trailing block reads:
+
+```
+snapshots:
+ retention_count: 10
+
+# Single source of truth for every vault walker (search indexer,
+# scan-inline, future scanners). Entries without a slash match a
+# directory name anywhere in the tree; entries with a slash are
+# matched against a vault-relative POSIX path exactly. Leave the
+# block absent to use the built-in defaults below; set
+# `ignore_paths: []` to disable exclusions entirely.
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+ - .open-second-brain
+ - .obsidian
+ - .trash
+ - .stversions
+ - Brain/.snapshots
+```
+
+Update `DEFAULT_BRAIN_CONFIG` likewise:
+
+```ts
+export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
+ // ...existing fields...
+ vault: Object.freeze({
+ ignore_paths: Object.freeze([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+ ]),
+ }),
+}) as BrainConfig;
+```
+
+- [ ] **Step 7: Add a test confirming `brain init` writes the new block**
+
+In `tests/core/brain.init.test.ts` (search for the existing test that asserts `_brain.yaml` is written) add a sibling:
+
+```ts
+test("brain init writes the vault.ignore_paths block", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "brain-init-vault-"));
+ bootstrapBrain(tmp); // existing test helper
+ const body = readFileSync(join(tmp, "Brain", "_brain.yaml"), "utf8");
+ expect(body).toContain("vault:");
+ expect(body).toContain("- .obsidian");
+ expect(body).toContain("- Brain/.snapshots");
+});
+```
+
+If the test file uses a different bootstrap helper name, match it.
+
+- [ ] **Step 8: Run the relevant test suites**
+
+Run: `bun test tests/core/brain.policy.test.ts tests/core/brain.init.test.ts`
+Expected: ALL PASS.
+
+- [ ] **Step 9: Commit**
+
+Suggested commit: `feat(brain): parse vault.ignore_paths block in _brain.yaml`.
+
+---
+
+## Task 4: `resolveVaultScope` resolver
+
+**Files:**
+- Modify: `src/core/vault-scope/index.ts`
+- Modify: `tests/core/vault-scope.test.ts`
+
+- [ ] **Step 1: Write failing tests for `resolveVaultScope`**
+
+Append to `tests/core/vault-scope.test.ts`:
+
+```ts
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach } from "bun:test";
+
+import { resolveVaultScope } from "../../src/core/vault-scope/index.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-scope-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeBrainYaml(body: string): void {
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), body);
+}
+
+test("resolveVaultScope: defaults when _brain.yaml is absent", () => {
+ const scope = resolveVaultScope(vault);
+ expect(scope.source).toBe("defaults");
+ expect(scope.ignorePaths).toContain(".obsidian");
+ expect(scope.ignorePaths).toContain("Brain/.snapshots");
+ expect(scope.rules.find((r) => r.raw === "Brain/.snapshots")?.kind).toBe("path");
+ expect(scope.rules.find((r) => r.raw === ".obsidian")?.kind).toBe("name");
+});
+
+test("resolveVaultScope: reads vault.ignore_paths when present", () => {
+ writeBrainYaml(`schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ - my-cache
+`);
+ const scope = resolveVaultScope(vault);
+ expect(scope.source).toBe("_brain.yaml");
+ expect(scope.ignorePaths).toEqual([".git", "my-cache"]);
+ expect(scope.rules.map((r) => r.kind)).toEqual(["name", "name"]);
+});
+
+test("resolveVaultScope: explicit empty list excludes nothing", () => {
+ writeBrainYaml(`schema_version: 1
+vault:
+ ignore_paths:
+`);
+ const scope = resolveVaultScope(vault);
+ expect(scope.source).toBe("_brain.yaml");
+ expect(scope.ignorePaths).toEqual([]);
+ expect(scope.rules).toEqual([]);
+});
+
+test("resolveVaultScope: absent vault block falls back to defaults", () => {
+ writeBrainYaml(`schema_version: 1\n`);
+ const scope = resolveVaultScope(vault);
+ expect(scope.source).toBe("defaults");
+});
+
+test("resolveVaultScope: invalid _brain.yaml fails closed instead of defaulting", () => {
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "garbage::not yaml::");
+ expect(() => resolveVaultScope(vault)).toThrow();
+});
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: FAIL β€” `resolveVaultScope is not a function`.
+
+- [ ] **Step 3: Implement `resolveVaultScope`**
+
+Append to `src/core/vault-scope/index.ts`:
+
+```ts
+import { loadBrainConfig } from "../brain/policy.ts";
+
+export interface VaultScope {
+ /** Final list of paths in the order they were declared. */
+ readonly ignorePaths: ReadonlyArray<string>;
+ /** Same list, classified as `name | path`. */
+ readonly rules: ReadonlyArray<VaultIgnoreRule>;
+ readonly source: "_brain.yaml" | "defaults";
+}
+
+function classify(raw: string): VaultIgnoreRule {
+ return { raw, kind: raw.includes("/") ? "path" : "name" };
+}
+
+function buildScope(
+ paths: ReadonlyArray<string>,
+ source: VaultScope["source"],
+): VaultScope {
+ const ignorePaths = Object.freeze([...paths]);
+ const rules = Object.freeze(ignorePaths.map(classify));
+ return Object.freeze({ ignorePaths, rules, source });
+}
+
+const DEFAULT_SCOPE = buildScope(DEFAULT_VAULT_IGNORE_PATHS, "defaults");
+
+export function resolveVaultScope(vault: string): VaultScope {
+ let cfg;
+ try {
+ cfg = loadBrainConfig(vault);
+ } catch {
+ return DEFAULT_SCOPE;
+ }
+ const declared = cfg.vault?.ignore_paths;
+ if (declared === undefined) return DEFAULT_SCOPE;
+ return buildScope(declared, "_brain.yaml");
+}
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `feat(vault-scope): add resolveVaultScope reading Brain/_brain.yaml`.
+
+---
+
+## Task 5: `walkVaultScope` and `inspectPath`
+
+**Files:**
+- Modify: `src/core/vault-scope/index.ts`
+- Modify: `tests/core/vault-scope.test.ts`
+
+- [ ] **Step 1: Write failing tests for `walkVaultScope`**
+
+Append to `tests/core/vault-scope.test.ts`:
+
+```ts
+import { walkVaultScope, inspectPath } from "../../src/core/vault-scope/index.ts";
+
+test("walkVaultScope: counts files+dirs and reports excluded subtree once", () => {
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(join(vault, "Notes", "a.md"), "x");
+ writeFileSync(join(vault, "Notes", "b.md"), "x");
+ mkdirSync(join(vault, ".obsidian", "plugins", "foo"), { recursive: true });
+ writeFileSync(join(vault, ".obsidian", "app.json"), "{}");
+ writeFileSync(join(vault, ".obsidian", "plugins", "foo", "note.md"), "x");
+
+ const scope = resolveVaultScope(vault); // uses defaults; Brain dir empty
+ const walk = walkVaultScope(vault, scope);
+
+ expect(walk.includedFiles).toBeGreaterThanOrEqual(2);
+ expect(walk.excludedDirs.find((d) => d.relPath === ".obsidian")).toBeTruthy();
+ // Subtree must NOT have its descendants reported separately.
+ expect(walk.excludedDirs.filter((d) => d.relPath.startsWith(".obsidian/"))).toHaveLength(0);
+ expect(walk.excludedDirs.find((d) => d.relPath === ".obsidian")?.rule.raw).toBe(".obsidian");
+});
+
+test("inspectPath: included path", () => {
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(join(vault, "Notes", "idea.md"), "x");
+ const scope = resolveVaultScope(vault);
+ const r = inspectPath("Notes/idea.md", scope);
+ expect(r.excluded).toBe(false);
+});
+
+test("inspectPath: excluded by name rule", () => {
+ const scope = resolveVaultScope(vault);
+ const r = inspectPath(".obsidian/plugins/foo/note.md", scope);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".obsidian");
+ expect(r.matchedAt).toBe(".obsidian");
+});
+
+test("inspectPath: excluded by path rule", () => {
+ const scope = resolveVaultScope(vault);
+ const r = inspectPath("Brain/.snapshots/2026-05-19.tar.zst", scope);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe("Brain/.snapshots");
+});
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: FAIL β€” `walkVaultScope` and `inspectPath` not defined.
+
+- [ ] **Step 3: Implement walker + inspector**
+
+Append to `src/core/vault-scope/index.ts`:
+
+```ts
+import { readdirSync, statSync, realpathSync, type Dirent } from "node:fs";
+import { join, sep } from "node:path";
+
+export interface ExcludedEntry {
+ readonly relPath: string;
+ readonly rule: VaultIgnoreRule;
+}
+
+export interface VaultScopeWalk {
+ readonly includedFiles: number;
+ readonly includedDirs: number;
+ readonly excludedDirs: ReadonlyArray<ExcludedEntry>;
+ readonly excludedFiles: ReadonlyArray<ExcludedEntry>;
+}
+
+function toPosix(p: string): string {
+ return sep === "/" ? p : p.split(sep).join("/");
+}
+
+/**
+ * Recursive fs walk that counts every file and directory, applies
+ * the supplied scope, and records the *root* of each excluded
+ * subtree (descendants are not enumerated again β€” see the design
+ * doc Β§5.2).
+ */
+export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalk {
+ const vaultReal = (() => {
+ try { return realpathSync(vault); } catch { return vault; }
+ })();
+ const excludedDirs: ExcludedEntry[] = [];
+ const excludedFiles: ExcludedEntry[] = [];
+ let includedFiles = 0;
+ let includedDirs = 0;
+
+ const seenDirs = new Set<string>([vaultReal]);
+
+ function walk(absDir: string, relDir: string): void {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(absDir, { withFileTypes: true, encoding: "utf8" });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ for (const entry of entries) {
+ const abs = join(absDir, entry.name);
+ const rel = relDir === "" ? toPosix(entry.name) : `${relDir}/${toPosix(entry.name)}`;
+ let stat;
+ try { stat = statSync(abs); } catch { continue; }
+ if (stat.isDirectory()) {
+ const m = matchIgnore(rel, scope.rules);
+ if (m.excluded && m.rule) {
+ excludedDirs.push({ relPath: rel, rule: m.rule });
+ continue;
+ }
+ // acyclic symlink guard
+ let real: string;
+ try { real = realpathSync(abs); } catch { continue; }
+ if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;
+ if (seenDirs.has(real)) continue;
+ seenDirs.add(real);
+ includedDirs++;
+ walk(abs, rel);
+ continue;
+ }
+ if (!stat.isFile()) continue;
+ const m = matchIgnore(rel, scope.rules);
+ if (m.excluded && m.rule) {
+ excludedFiles.push({ relPath: rel, rule: m.rule });
+ continue;
+ }
+ includedFiles++;
+ }
+ }
+
+ walk(vaultReal, "");
+
+ return Object.freeze({
+ includedFiles,
+ includedDirs,
+ excludedDirs: Object.freeze(excludedDirs),
+ excludedFiles: Object.freeze(excludedFiles),
+ });
+}
+
+export interface InspectResult {
+ readonly relPath: string;
+ readonly excluded: boolean;
+ readonly rule: VaultIgnoreRule | null;
+ readonly matchedAt: string | null;
+ readonly source: VaultScope["source"];
+}
+
+export function inspectPath(relPath: string, scope: VaultScope): InspectResult {
+ // Normalise: collapse leading "./", strip surrounding slashes, OS-native -> POSIX.
+ const normalised = toPosix(relPath).replace(/^\.\//, "").replace(/^\/+|\/+$/g, "");
+ if (normalised.includes("..")) {
+ throw new Error(`relPath must not traverse outside the vault: ${relPath}`);
+ }
+ const m = matchIgnore(normalised, scope.rules);
+ return Object.freeze({
+ relPath: normalised,
+ excluded: m.excluded,
+ rule: m.rule,
+ matchedAt: m.matchedAt,
+ source: scope.source,
+ });
+}
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+Run: `bun test tests/core/vault-scope.test.ts`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `feat(vault-scope): add walkVaultScope and inspectPath`.
+
+---
+
+## Task 6: Rewire the search walker to consume rules
+
+**Files:**
+- Modify: `src/core/search/types.ts`
+- Modify: `src/core/search/walker.ts`
+- Modify: `tests/helpers/search-fixtures.ts`
+
+- [ ] **Step 1: Replace `ignorePaths` with `ignoreRules` in the type**
+
+In `src/core/search/types.ts`, find the `ResolvedSearchConfig` interface. Replace the line `readonly ignorePaths: ReadonlyArray<string>;` with:
+
+```ts
+readonly ignoreRules: ReadonlyArray<import("../vault-scope/index.ts").VaultIgnoreRule>;
+```
+
+- [ ] **Step 2: Update the test helper**
+
+In `tests/helpers/search-fixtures.ts`, replace the body of `makeConfig` so it builds rules from the optional `ignorePaths` shortcut:
+
+```ts
+import type { VaultIgnoreRule } from "../../src/core/search/types.ts";
+// (or the re-exported type path the search types ends up using)
+
+export function makeConfig(opts: {
+ vault: string;
+ dbPath: string;
+ ignorePaths?: ReadonlyArray<string>;
+ semantic?: Partial<ResolvedEmbeddingConfig>;
+}): ResolvedSearchConfig {
+ // ...semantic block unchanged...
+ const paths = opts.ignorePaths ?? [
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+ ];
+ const ignoreRules: ReadonlyArray<VaultIgnoreRule> = Object.freeze(
+ paths.map((raw) => ({ raw, kind: raw.includes("/") ? "path" as const : "name" as const })),
+ );
+ return Object.freeze({
+ vault: opts.vault,
+ dbPath: opts.dbPath,
+ ignoreRules,
+ chunkSize: 800,
+ chunkOverlap: 100,
+ keywordWeight: 0.6,
+ semanticWeight: 0.4,
+ semantic,
+ });
+}
+```
+
+Re-export `VaultIgnoreRule` from `src/core/search/types.ts` so the helper does not reach across module boundaries arbitrarily:
+
+```ts
+export type { VaultIgnoreRule } from "../vault-scope/index.ts";
+```
+
+- [ ] **Step 3: Rewrite the walker**
+
+Replace the body of `src/core/search/walker.ts`. The exports stay (`walkVault`, `WalkedFile`). The internal `parseIgnore` helper is removed; the matcher comes from `vault-scope`:
+
+```ts
+import { readdirSync, statSync, realpathSync, type Dirent, type Stats } from "node:fs";
+import { join, relative, sep } from "node:path";
+
+import { matchIgnore } from "../vault-scope/index.ts";
+import type { ResolvedSearchConfig } from "./types.ts";
+
+export interface WalkedFile {
+ readonly absPath: string;
+ readonly relPath: string;
+ readonly stat: Stats;
+}
+
+function toPosix(p: string): string {
+ return sep === "/" ? p : p.split(sep).join("/");
+}
+
+function isInsideVault(absTarget: string, vaultReal: string): boolean {
+ try {
+ const r = realpathSync(absTarget);
+ return r === vaultReal || r.startsWith(vaultReal + sep);
+ } catch {
+ return false;
+ }
+}
+
+export function* walkVault(config: ResolvedSearchConfig): Generator<WalkedFile> {
+ const vaultReal = (() => {
+ try { return realpathSync(config.vault); } catch { return config.vault; }
+ })();
+ const seenDirs = new Set<string>([vaultReal]);
+
+ function* walk(dir: string): Generator<WalkedFile> {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true, encoding: "utf8" });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ for (const entry of entries) {
+ const absPath = join(dir, entry.name);
+ const relRaw = relative(vaultReal, absPath);
+ if (relRaw === "" || relRaw.startsWith("..")) continue;
+ const relPath = toPosix(relRaw);
+
+ const isLinkHint = entry.isSymbolicLink();
+
+ let stat: Stats;
+ try { stat = statSync(absPath); } catch { continue; }
+
+ if (stat.isDirectory()) {
+ if (matchIgnore(relPath, config.ignoreRules).excluded) continue;
+ let real: string;
+ try { real = realpathSync(absPath); } catch { continue; }
+ if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;
+ if (seenDirs.has(real)) continue;
+ seenDirs.add(real);
+ yield* walk(absPath);
+ continue;
+ }
+ if (!stat.isFile()) continue;
+ if (!entry.name.toLowerCase().endsWith(".md")) continue;
+ if (isLinkHint && !isInsideVault(absPath, vaultReal)) continue;
+ // file-level rule too, in case someone configures `path/to/file.md`
+ if (matchIgnore(relPath, config.ignoreRules).excluded) continue;
+
+ yield { absPath, relPath, stat };
+ }
+ }
+
+ yield* walk(vaultReal);
+}
+```
+
+- [ ] **Step 4: Run walker tests to verify they pass**
+
+Run: `bun test tests/core/search/walker.test.ts`
+Expected: PASS. If any test asserts on `cfg.ignorePaths` directly (it should not after Step 2), change the assertion to read `cfg.ignoreRules.map((r) => r.raw)`.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `refactor(search): consume VaultIgnoreRule via matchIgnore`.
+
+---
+
+## Task 7: Drop legacy env / config keys from `resolveSearchConfig`
+
+**Files:**
+- Modify: `src/core/search/index.ts`
+- Modify: `tests/core/search/config.test.ts`
+- Modify: `tests/core/search/store.test.ts`
+- Modify: `tests/core/search/store.vec.test.ts`
+
+- [ ] **Step 1: Update tests to assert the new behaviour**
+
+In `tests/core/search/config.test.ts`:
+
+1. Remove `"OPEN_SECOND_BRAIN_SEARCH_IGNORE"` from the `ENV_KEYS` array β€” the variable is gone.
+2. Replace the existing `cfg.ignorePaths` assertions (around lines 60-61) with assertions on `cfg.ignoreRules`:
+
+```ts
+expect(cfg.ignoreRules.map((r) => r.raw)).toContain(".git");
+expect(cfg.ignoreRules.map((r) => r.raw)).toContain(".open-second-brain");
+```
+
+3. Add a regression test that confirms the legacy surfaces are inert:
+
+```ts
+test("OPEN_SECOND_BRAIN_SEARCH_IGNORE has no effect (removed in v0.10.9)", () => {
+ writeFileSync(configPath, `vault: "${tmp}"\n`);
+ process.env["OPEN_SECOND_BRAIN_SEARCH_IGNORE"] = "foo,bar,baz";
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ expect(cfg.ignoreRules.map((r) => r.raw)).not.toContain("foo");
+});
+
+test("search_ignore_paths in config.yaml has no effect (removed in v0.10.9)", () => {
+ writeFileSync(
+ configPath,
+ `vault: "${tmp}"\nsearch_ignore_paths: "foo,bar,baz"\n`,
+ );
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ expect(cfg.ignoreRules.map((r) => r.raw)).not.toContain("foo");
+});
+```
+
+4. Add a test that confirms `Brain/_brain.yaml` is read instead:
+
+```ts
+test("vault.ignore_paths in Brain/_brain.yaml is the source of truth", () => {
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Brain", "_brain.yaml"),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - my-cache
+`,
+ );
+ writeFileSync(configPath, `vault: "${tmp}"\n`);
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ expect(cfg.ignoreRules.map((r) => r.raw)).toEqual(["my-cache"]);
+});
+```
+
+Also update `tests/core/search/store.test.ts` and `tests/core/search/store.vec.test.ts`: every literal `ignorePaths: Object.freeze([".git"])` inside the inline `ResolvedSearchConfig` becomes `ignoreRules: Object.freeze([{ raw: ".git", kind: "name" as const }])`.
+
+- [ ] **Step 2: Run tests to verify the new ones fail**
+
+Run: `bun test tests/core/search/config.test.ts`
+Expected: FAIL β€” the legacy variable still does what it used to.
+
+- [ ] **Step 3: Strip the legacy surfaces from the resolver**
+
+In `src/core/search/index.ts`:
+
+1. Delete the `DEFAULT_IGNORE_PATHS` constant (lines 46-53).
+2. Delete the `parseIgnorePaths` function (lines 150-156).
+3. Replace the block at lines 202-204:
+
+```ts
+const ignorePaths = parseIgnorePaths(
+ envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_IGNORE", "search_ignore_paths"),
+);
+```
+
+with:
+
+```ts
+const scope = resolveVaultScope(opts.vault);
+const ignoreRules = scope.rules;
+```
+
+4. In the final config literal (around line 256):
+
+```ts
+const base: ResolvedSearchConfig = Object.freeze({
+ vault: opts.vault,
+ dbPath,
+ ignoreRules, // was: ignorePaths: Object.freeze([...ignorePaths]),
+ chunkSize,
+ chunkOverlap,
+ keywordWeight,
+ semanticWeight,
+ semantic,
+});
+```
+
+5. Update the `Omit` / overrides type at the top of the file:
+
+```ts
+type SearchConfigOverrides = Partial<Omit<ResolvedSearchConfig, "ignoreRules" | "semantic">> & {
+ readonly ignoreRules?: ReadonlyArray<VaultIgnoreRule>;
+ readonly semantic?: Partial<ResolvedEmbeddingConfig>;
+};
+```
+
+…and the merged-overrides return:
+
+```ts
+ignoreRules: opts.overrides.ignoreRules
+ ? Object.freeze([...opts.overrides.ignoreRules])
+ : base.ignoreRules,
+```
+
+6. Add the imports at the top:
+
+```ts
+import { resolveVaultScope } from "../vault-scope/index.ts";
+import type { VaultIgnoreRule } from "../vault-scope/index.ts";
+```
+
+7. Re-export `VaultIgnoreRule` from this module so external callers do not learn the new path twice (optional convenience):
+
+```ts
+export type { VaultIgnoreRule } from "../vault-scope/index.ts";
+```
+
+- [ ] **Step 4: Run all search tests to verify they pass**
+
+Run: `bun test tests/core/search/`
+Expected: ALL PASS.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `feat(search)!: drop OPEN_SECOND_BRAIN_SEARCH_IGNORE / search_ignore_paths in favour of vault.ignore_paths`.
+
+---
+
+## Task 8: Rewire scan-inline to use the shared scope
+
+**Files:**
+- Modify: `src/core/brain/inline-scan.ts`
+- Modify: `tests/core/brain.inline-scan.test.ts`
+- Modify: `tests/e2e/brain-capture-and-fields.test.ts`
+
+- [ ] **Step 1: Write failing tests for scan-inline**
+
+Append to `tests/core/brain.inline-scan.test.ts`:
+
+```ts
+test("scan-inline skips files under .obsidian even when they contain @osb markers", async () => {
+ // Build a tmp vault with `.obsidian/plugins/foo/note.md` carrying a marker.
+ // The exact tmp scaffolding pattern is the one used by the existing tests
+ // in this file - copy it verbatim from the closest existing case.
+ const tmp = makeTempVault();
+ mkdirSync(join(tmp, ".obsidian", "plugins", "foo"), { recursive: true });
+ writeFileSync(
+ join(tmp, ".obsidian", "plugins", "foo", "note.md"),
+ `@osb feedback negative principle="x" topic=t scope=writing\n`,
+ );
+
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(0);
+ expect(result.created).toBe(0);
+});
+
+test("scan-inline always skips Brain/ even if it contains markers (hardcoded invariant)", async () => {
+ const tmp = makeTempVault();
+ // Operator declares an empty ignore list - Brain is still skipped.
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Brain", "_brain.yaml"),
+ `schema_version: 1\nvault:\n ignore_paths:\n`,
+ );
+ writeFileSync(
+ join(tmp, "Brain", "stray.md"),
+ `@osb feedback positive principle="x" topic=t\n`,
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(0);
+});
+
+test("scan-inline reads vault.ignore_paths from _brain.yaml", async () => {
+ const tmp = makeTempVault();
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Brain", "_brain.yaml"),
+ `schema_version: 1\nvault:\n ignore_paths:\n - Drafts\n`,
+ );
+ mkdirSync(join(tmp, "Drafts"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Drafts", "x.md"),
+ `@osb feedback negative principle="x" topic=t\n`,
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(0);
+});
+
+test("scan-inline --exclude narrows further on top of the shared set", async () => {
+ const tmp = makeTempVault();
+ mkdirSync(join(tmp, "Notes"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Notes", "x.md"),
+ `@osb feedback negative principle="x" topic=t\n`,
+ );
+ const result = await scanInline(tmp, { agent: "test", exclude: ["Notes"] });
+ expect(result.found).toBe(0);
+});
+```
+
+Match `makeTempVault` to whatever scaffolding the existing tests in this file use; do NOT introduce a new helper if one already exists.
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `bun test tests/core/brain.inline-scan.test.ts`
+Expected: FAIL β€” at least the `.obsidian/plugins/foo/note.md` case fails because right now `HARD_SKIP_DIRS` includes `.obsidian`, but the new test asserting that the `_brain.yaml`-declared `Drafts` exclusion is honoured will fail.
+
+- [ ] **Step 3: Replace the hard-coded skip list with the resolved scope**
+
+In `src/core/brain/inline-scan.ts`:
+
+1. Delete `HARD_SKIP_DIRS` (lines 47-55).
+2. Add imports:
+
+```ts
+import { resolveVaultScope, matchIgnore, type VaultIgnoreRule } from "../vault-scope/index.ts";
+```
+
+3. Replace the body of `walkVault` (the inline generator at the bottom of the file) and the part of `scanInline` that builds `userExcludes`. The new flow:
+
+```ts
+// Inside scanInline, before calling walkVault:
+const scope = resolveVaultScope(vault);
+const rules: VaultIgnoreRule[] = [
+ ...scope.rules,
+ // Hardcoded invariant: scan-inline never recurses into Brain/.
+ // Markers there would self-reference the derived layer; do not
+ // expose this as a config knob.
+ { raw: "Brain", kind: "name" },
+ // User --exclude entries are vault-relative path prefixes.
+ ...(opts.exclude ?? []).map((raw) => ({ raw: normalisePrefix(raw), kind: "path" as const })),
+];
+
+const includePrefixes = (opts.paths ?? []).map(normalisePrefix);
+
+for (const filePath of walkVault(vault, includePrefixes, rules)) {
+ // ...existing body unchanged...
+}
+```
+
+`normalisePrefix` already exists in this file; it strips leading/trailing slashes and converts to OS-native separators. Replace it so it returns a POSIX path instead (since `matchIgnore` expects POSIX):
+
+```ts
+function normalisePrefix(rel: string): string {
+ return rel.replace(/^\/+|\/+$/g, "").replace(/\\/g, "/");
+}
+```
+
+4. Replace the walker generator at the bottom of the file:
+
+```ts
+function* walkVault(
+ vault: string,
+ includePrefixes: ReadonlyArray<string>,
+ rules: ReadonlyArray<VaultIgnoreRule>,
+): Generator<string> {
+ const stack: Array<{ abs: string; rel: string }> = [{ abs: vault, rel: "" }];
+ while (stack.length > 0) {
+ const { abs: dir, rel: relDir } = stack.pop()!;
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ const relPosix = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
+
+ if (matchIgnore(relPosix, rules).excluded) continue;
+
+ if (entry.isDirectory()) {
+ // Descend; include-narrowing applies only to files.
+ stack.push({ abs: full, rel: relPosix });
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (!entry.name.endsWith(".md")) continue;
+
+ if (includePrefixes.length > 0) {
+ const matches = includePrefixes.some(
+ (p) => relPosix === p || relPosix.startsWith(p + "/"),
+ );
+ if (!matches) continue;
+ }
+
+ yield full;
+ }
+ }
+}
+```
+
+5. Drop the `relative` and `sep` imports if no longer used in this file (they were used by the old `walkVault`); keep only what the body needs.
+
+- [ ] **Step 4: Update the existing e2e test**
+
+In `tests/e2e/brain-capture-and-fields.test.ts`, find the step that creates a marker file and add a second marker placed at `.obsidian/plugins/x/note.md`. After running `o2b brain scan-inline`, assert that ONLY the expected marker was captured (the obsidian one is skipped):
+
+```ts
+// In the existing scaffold where one marker file is created:
+mkdirSync(join(vault, ".obsidian", "plugins", "x"), { recursive: true });
+writeFileSync(
+ join(vault, ".obsidian", "plugins", "x", "note.md"),
+ `@osb feedback negative principle="should-not-be-captured" topic=ignored\n`,
+);
+// After the scan-inline run, assert no signal was created for that topic.
+const inbox = readdirSync(join(vault, "Brain", "inbox"));
+expect(inbox.some((f) => f.includes("ignored"))).toBe(false);
+```
+
+- [ ] **Step 5: Run tests to verify they pass**
+
+Run: `bun test tests/core/brain.inline-scan.test.ts tests/e2e/brain-capture-and-fields.test.ts`
+Expected: ALL PASS.
+
+- [ ] **Step 6: Commit**
+
+Suggested commit: `refactor(brain): scan-inline reads vault.ignore_paths from _brain.yaml`.
+
+---
+
+## Task 9: `o2b vault status` and `o2b vault inspect` CLI
+
+**Files:**
+- Create: `src/cli/vault.ts`
+- Create: `src/cli/vault/help-text.ts`
+- Create: `src/cli/vault/verbs/status.ts`
+- Create: `src/cli/vault/verbs/inspect.ts`
+- Modify: `src/cli/main.ts`
+- Create: `tests/cli/vault.test.ts`
+
+- [ ] **Step 1: Write failing CLI tests**
+
+`tests/cli/vault.test.ts`:
+
+```ts
+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";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-vault-cli-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });
+
+async function bootstrap(): Promise<void> {
+ let r = await runCli(["init", "--vault", vault], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ expect(r.returncode).toBe(0);
+ r = await runCli(["brain", "init", "--vault", vault], { env: { OPEN_SECOND_BRAIN_CONFIG: config } });
+ expect(r.returncode).toBe(0);
+}
+
+describe("o2b vault status", () => {
+ test("prints counts and source on a fresh vault", async () => {
+ await bootstrap();
+ mkdirSync(join(vault, ".obsidian"), { recursive: true });
+ writeFileSync(join(vault, "Notes.md"), "x");
+ const r = await runCli(["vault", "status", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("ignore source: _brain.yaml");
+ expect(r.stdout).toContain(".obsidian");
+ });
+
+ test("--json output is machine-readable", async () => {
+ await bootstrap();
+ mkdirSync(join(vault, ".obsidian"), { recursive: true });
+ const r = await runCli(["vault", "status", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.ignore_source).toBe("_brain.yaml");
+ expect(payload.included.files).toBeGreaterThanOrEqual(0);
+ expect(payload.excluded.dirs.some((d: any) => d.rel_path === ".obsidian")).toBe(true);
+ });
+});
+
+describe("o2b vault inspect", () => {
+ test("included path", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "idea.md"), "x");
+ const r = await runCli(["vault", "inspect", "idea.md", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("status: included");
+ });
+
+ test("excluded path by name rule", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["vault", "inspect", ".obsidian/plugins/foo/note.md", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("status: excluded");
+ expect(r.stdout).toContain("matched rule: .obsidian (name)");
+ expect(r.stdout).toContain("matched at: .obsidian");
+ });
+
+ test("missing relpath exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(["vault", "inspect", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(2);
+ });
+
+ test("--json shape", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["vault", "inspect", ".obsidian/plugins/foo/note.md", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.status).toBe("excluded");
+ expect(payload.matched_rule.raw).toBe(".obsidian");
+ });
+});
+```
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `bun test tests/cli/vault.test.ts`
+Expected: FAIL β€” unknown command `vault`.
+
+- [ ] **Step 3: Create help text**
+
+`src/cli/vault/help-text.ts`:
+
+```ts
+export const VAULT_HELP = `usage: o2b vault <verb> [options]
+
+Vault-wide exclusion policy inspection.
+
+verbs:
+ status Show how many files/directories the policy
+ includes and which exclusion rules fire.
+ inspect <relpath> Point-check one vault-relative path with the
+ matched rule.
+
+The exclusion policy lives in <vault>/Brain/_brain.yaml under
+\`vault.ignore_paths\` (single source of truth for every walker).
+`;
+
+export const VAULT_VERB_HELP: Record<string, string> = {
+ status:
+ "usage: o2b vault status [--vault <path>] [--json]\n\n" +
+ "Walks the vault under the active policy and reports counts plus\n" +
+ "every excluded directory with the matched rule.\n",
+ inspect:
+ "usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n\n" +
+ "Resolves the policy and runs matchIgnore against <relpath>. The\n" +
+ "relpath is vault-relative (POSIX). Path traversal outside the\n" +
+ "vault is rejected with exit 2.\n",
+};
+```
+
+- [ ] **Step 4: Create the `status` verb**
+
+`src/cli/vault/verbs/status.ts`:
+
+```ts
+import { defaultConfigPath } from "../../../core/config.ts";
+import { resolveVaultScope, walkVaultScope } from "../../../core/vault-scope/index.ts";
+import { resolveBrainVault } from "../../brain/helpers.ts";
+import { fail, info, ok } from "../../output.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdVaultStatus(argv: ReadonlyArray<string>): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const cfg = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, cfg);
+ const scope = resolveVaultScope(vault);
+ let walk;
+ try {
+ walk = walkVaultScope(vault, scope);
+ } catch (exc) {
+ return fail(`vault status failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ const payload = {
+ vault,
+ ignore_source: scope.source,
+ rules: scope.rules.map((r) => ({ raw: r.raw, kind: r.kind })),
+ included: { files: walk.includedFiles, dirs: walk.includedDirs },
+ excluded: {
+ dirs: walk.excludedDirs.map((d) => ({
+ rel_path: d.relPath,
+ rule: d.rule.raw,
+ kind: d.rule.kind,
+ })),
+ files: walk.excludedFiles.map((f) => ({
+ rel_path: f.relPath,
+ rule: f.rule.raw,
+ kind: f.rule.kind,
+ })),
+ },
+ };
+ process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
+ return 0;
+ }
+
+ info(`vault: ${vault}`);
+ info(`ignore source: ${scope.source}`);
+ info("");
+ info(`included: ${walk.includedFiles} files, ${walk.includedDirs} directories`);
+ info(`excluded: ${walk.excludedDirs.length} directories, ${walk.excludedFiles.length} files`);
+ if (walk.excludedDirs.length > 0) {
+ info("");
+ info("excluded directories:");
+ for (const d of walk.excludedDirs) {
+ info(` ${d.relPath.padEnd(30)} rule ${d.rule.raw} (${d.rule.kind})`);
+ }
+ }
+ if (walk.excludedFiles.length > 0) {
+ info("");
+ info("excluded files:");
+ for (const f of walk.excludedFiles) {
+ info(` ${f.relPath.padEnd(30)} rule ${f.rule.raw} (${f.rule.kind})`);
+ }
+ }
+ return 0;
+}
+```
+
+(`ok` is unused above but kept available; `info` matches the existing `o2b brain status` text idiom.)
+
+- [ ] **Step 5: Create the `inspect` verb**
+
+`src/cli/vault/verbs/inspect.ts`:
+
+```ts
+import { defaultConfigPath } from "../../../core/config.ts";
+import { inspectPath, resolveVaultScope } from "../../../core/vault-scope/index.ts";
+import { resolveBrainVault } from "../../brain/helpers.ts";
+import { fail, info } from "../../output.ts";
+import { CliError, parseFlags } from "../../argparse.ts";
+
+export async function cmdVaultInspect(argv: ReadonlyArray<string>): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const relpath = positional[0];
+ if (!relpath) {
+ process.stderr.write("error: usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n");
+ return 2;
+ }
+ const cfg = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, cfg);
+ const scope = resolveVaultScope(vault);
+ let result;
+ try {
+ result = inspectPath(relpath, scope);
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? exc}\n`);
+ return 2;
+ }
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({
+ relpath: result.relPath,
+ status: result.excluded ? "excluded" : "included",
+ matched_rule: result.rule ? { raw: result.rule.raw, kind: result.rule.kind } : null,
+ matched_at: result.matchedAt,
+ source: result.source,
+ }, null, 2) + "\n");
+ return 0;
+ }
+ info(`relpath: ${result.relPath}`);
+ if (!result.excluded) {
+ info("status: included");
+ return 0;
+ }
+ info("status: excluded");
+ if (result.rule) info(`matched rule: ${result.rule.raw} (${result.rule.kind})`);
+ if (result.matchedAt) info(`matched at: ${result.matchedAt}`);
+ info(`source: ${result.source}`);
+ return 0;
+}
+```
+
+- [ ] **Step 6: Wire up the dispatcher**
+
+`src/cli/vault.ts`:
+
+```ts
+import { CliError } from "./argparse.ts";
+import { VAULT_HELP, VAULT_VERB_HELP } from "./vault/help-text.ts";
+import { cmdVaultStatus } from "./vault/verbs/status.ts";
+import { cmdVaultInspect } from "./vault/verbs/inspect.ts";
+
+export async function handleVaultSubcommand(argv: ReadonlyArray<string>): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(VAULT_HELP);
+ return argv.length === 0 ? 2 : 0;
+ }
+ const verb = argv[0]!;
+ const rest = argv.slice(1);
+
+ if (rest.length === 1 && (rest[0] === "-h" || rest[0] === "--help")) {
+ const text = VAULT_VERB_HELP[verb];
+ if (text) { process.stdout.write(text); return 0; }
+ process.stdout.write(VAULT_HELP);
+ return 2;
+ }
+
+ try {
+ switch (verb) {
+ case "status": return await cmdVaultStatus(rest);
+ case "inspect": return await cmdVaultInspect(rest);
+ default:
+ process.stderr.write(`error: unknown vault verb: ${verb}\n`);
+ process.stdout.write(VAULT_HELP);
+ return 2;
+ }
+ } catch (exc) {
+ if (exc instanceof CliError) { process.stderr.write(`error: ${exc.message}\n`); return 1; }
+ throw exc;
+ }
+}
+```
+
+In `src/cli/main.ts`:
+
+1. Add `import { handleVaultSubcommand } from "./vault.ts";` next to the other dispatchers.
+2. In the `switch (command)` block, add (after `case "brain":`):
+
+```ts
+case "vault":
+ return await handleVaultSubcommand(rest);
+```
+
+3. Append `vault` to the top-level `HELP` string if there is one (look for the lines listing `init`, `brain`, `search` etc. and add ` vault Inspect the vault-wide exclusion policy`).
+
+- [ ] **Step 7: Run tests to verify they pass**
+
+Run: `bun test tests/cli/vault.test.ts`
+Expected: PASS.
+
+- [ ] **Step 8: Commit**
+
+Suggested commit: `feat(cli): add o2b vault status and o2b vault inspect`.
+
+---
+
+## Task 10: Extend `second_brain_status` with `vault` block
+
+**Files:**
+- Modify: `src/mcp/tools.ts`
+- Modify: `tests/cli/mcp-scope-arg.test.ts` (or the closest existing MCP-status test)
+
+- [ ] **Step 1: Locate the existing test that asserts `second_brain_status` shape**
+
+Run: `grep -rn "second_brain_status" tests/ --include="*.ts"` and pick the test file that asserts on the JSON payload structure (most likely `tests/cli/mcp-scope-arg.test.ts` or a file under `tests/mcp/`). If no such test exists, create `tests/mcp/tools-status.test.ts` instead.
+
+- [ ] **Step 2: Add a failing assertion for the new `vault` block**
+
+Append a new test:
+
+```ts
+test("second_brain_status payload includes the vault block (v0.10.9)", async () => {
+ // Reuse the test's existing helper to bootstrap a populated vault.
+ const vault = await makePopulatedVault();
+ const ctx = { vault, configPath: null, repoRoot: null };
+ const result = await toolStatus(ctx) as Record<string, unknown>;
+ expect(result.vault).toBeDefined();
+ const v = result.vault as Record<string, unknown>;
+ expect(v.ignore_source).toBeDefined();
+ expect(Array.isArray((v as any).rules)).toBe(true);
+ expect((v as any).included.files).toBeGreaterThanOrEqual(0);
+ expect((v as any).excluded.dirs).toBeGreaterThanOrEqual(0);
+});
+```
+
+If `toolStatus` is not directly exported, exercise the same code path through the existing MCP test harness (whichever pattern that file already uses).
+
+- [ ] **Step 3: Run test to verify it fails**
+
+Run: `bun test <the chosen test file>`
+Expected: FAIL β€” `result.vault is undefined`.
+
+- [ ] **Step 4: Extend `toolStatus`**
+
+In `src/mcp/tools.ts`:
+
+1. Add imports:
+
+```ts
+import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";
+```
+
+2. Inside `toolStatus`, after the `brain` block is computed:
+
+```ts
+let vault: Record<string, unknown> | null = null;
+if (vaultExists) {
+ const scope = resolveVaultScope(ctx.vault);
+ const walk = walkVaultScope(ctx.vault, scope);
+ vault = {
+ ignore_source: scope.source,
+ rules: scope.rules.map((r) => ({ raw: r.raw, kind: r.kind })),
+ included: { files: walk.includedFiles, dirs: walk.includedDirs },
+ excluded: { dirs: walk.excludedDirs.length, files: walk.excludedFiles.length },
+ };
+}
+```
+
+3. In the return literal, add `...(vault ? { vault } : {})` β€” place it directly after the existing `vault_exists` field, before the existing `brain` / `search` spreads, so the property order matches the design doc (operator-friendly).
+
+- [ ] **Step 5: Run test to verify it passes**
+
+Run: `bun test <the chosen test file>`
+Expected: PASS.
+
+- [ ] **Step 6: Commit**
+
+Suggested commit: `feat(mcp): add vault block to second_brain_status payload`.
+
+---
+
+## Task 11: `o2b brain doctor` lint for missing ignore paths
+
+**Files:**
+- Modify: `src/core/brain/doctor.ts`
+- Modify: `tests/core/brain.doctor.test.ts`
+
+- [ ] **Step 1: Write the failing doctor test**
+
+Append to `tests/core/brain.doctor.test.ts`:
+
+```ts
+test("doctor warns when vault.ignore_paths contains a missing path entry", () => {
+ const vault = makeTempBrain(); // existing helper used elsewhere in this file
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - Brain/.snapshots
+ - Notes/does-not-exist
+`,
+ );
+ const { warnings } = runDoctor(vault);
+ const missing = warnings.find((w) => w.code === "vault-ignore-missing-path");
+ expect(missing).toBeDefined();
+ expect(missing?.message).toContain("Notes/does-not-exist");
+});
+
+test("doctor does NOT warn about bare-name entries that have no current match", () => {
+ const vault = makeTempBrain();
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+`,
+ );
+ const { warnings } = runDoctor(vault);
+ expect(warnings.find((w) => w.code === "vault-ignore-missing-path")).toBeUndefined();
+});
+
+test("doctor does NOT warn when vault block is absent and defaults are used", () => {
+ const vault = makeTempBrain();
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), `schema_version: 1\n`);
+ const { warnings } = runDoctor(vault);
+ expect(warnings.find((w) => w.code === "vault-ignore-missing-path")).toBeUndefined();
+});
+```
+
+If `makeTempBrain` is named differently in this file (`bootstrapVault`, `makeFixture`, etc.), use that name verbatim.
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `bun test tests/core/brain.doctor.test.ts`
+Expected: FAIL β€” `vault-ignore-missing-path` code does not exist.
+
+- [ ] **Step 3: Implement `checkVaultIgnore`**
+
+In `src/core/brain/doctor.ts`, near the other `check*` helpers:
+
+```ts
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import { resolveVaultScope } from "../vault-scope/index.ts";
+
+function checkVaultIgnore(vault: string, issues: DoctorIssue[]): void {
+ const scope = resolveVaultScope(vault);
+ if (scope.source !== "_brain.yaml") return;
+ for (const rule of scope.rules) {
+ if (rule.kind !== "path") continue;
+ const abs = join(vault, rule.raw);
+ if (existsSync(abs)) continue;
+ issues.push({
+ severity: "warning",
+ code: "vault-ignore-missing-path",
+ message:
+ `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,
+ });
+ }
+}
+```
+
+In `runDoctor`, after `checkConfig(vault, issues)`:
+
+```ts
+checkVaultIgnore(vault, issues);
+```
+
+- [ ] **Step 4: Run tests to verify they pass**
+
+Run: `bun test tests/core/brain.doctor.test.ts`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `feat(brain): doctor warns on vault.ignore_paths entries missing from disk`.
+
+---
+
+## Task 12: Documentation, CHANGELOG, version bump
+
+**Files:**
+- Modify: `CHANGELOG.md`
+- Modify: `package.json`
+- Run: `bun run sync-version`
+
+- [ ] **Step 1: Add the CHANGELOG entry**
+
+At the top of `CHANGELOG.md`, above the existing `## [0.10.8]` section, add:
+
+```markdown
+## [0.10.9] - YYYY-MM-DD
+
+Closes the "Vault Scope" feature: a single declarative exclusion
+policy in `Brain/_brain.yaml` (`vault.ignore_paths`) replaces the
+per-walker rules that used to drift between the search indexer
+and `scan-inline`. Operator visibility via `o2b vault status` and
+`o2b vault inspect`. Brain `doctor` warns when a path-style ignore
+entry points at nothing on disk. The MCP `second_brain_status`
+payload gains a `vault` block.
+
+### Removed
+
+- `search_ignore_paths` key from the flat plugin config.
+- `OPEN_SECOND_BRAIN_SEARCH_IGNORE` environment variable.
+ Configure exclusions in `Brain/_brain.yaml` under
+ `vault.ignore_paths`.
+
+### Added
+
+- `vault.ignore_paths` block in `Brain/_brain.yaml`. Single source
+ of truth for every vault walker (search indexer, `scan-inline`,
+ future scanners). Default set widens `.obsidian/cache` to
+ `.obsidian` (the entire directory) and adds `Brain/.snapshots`
+ explicitly.
+- `o2b vault status` - one-shot view of how many files and
+ directories the active policy includes, plus the excluded
+ directories with the matched rule.
+- `o2b vault inspect <relpath>` - point-check for one vault-
+ relative path.
+- `second_brain_status` MCP payload gains a `vault` block with the
+ same counts and the rule list.
+- `o2b brain doctor` warns when a path-style entry under
+ `vault.ignore_paths` does not exist in the vault
+ (`vault-ignore-missing-path`).
+
+### Changed
+
+- The search indexer and `scan-inline` walker now consume the
+ shared `vault-scope` matcher; previously each had its own list
+ of skip-paths. Behaviour is otherwise unchanged.
+
+### Migration
+
+No vault-data migration. Vaults whose `Brain/_brain.yaml` does not
+include a `vault:` block continue to use the built-in default set
+unchanged on this release. Vaults that used to set
+`search_ignore_paths` or `OPEN_SECOND_BRAIN_SEARCH_IGNORE` should
+copy the entries into `vault.ignore_paths`; the legacy surfaces
+no longer have any effect.
+```
+
+Replace `YYYY-MM-DD` with the actual release date when shipping.
+
+- [ ] **Step 2: Bump the package version**
+
+Edit `package.json`: change `"version": "0.10.8"` to `"version": "0.10.9"`.
+
+Run: `bun run sync-version`
+Expected: writes the new version into the satellite manifests (`plugin.yaml`, `pyproject.toml`, `openclaw.plugin.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json`, `plugins/codex/.codex-plugin/plugin.json`, `plugins/hermes/plugin.yaml`).
+
+- [ ] **Step 3: Run the full suite to confirm green**
+
+Run: `bun test`
+Expected: ALL PASS.
+
+Run: `bun run typecheck`
+Expected: PASS (no `tsc` errors).
+
+- [ ] **Step 4: Smoke-test on the operator's real vault**
+
+Surface a manual verification step to the operator: from a shell on this server,
+
+```
+o2b vault status --vault /root/vault
+o2b vault inspect .obsidian/community-plugins.json --vault /root/vault
+o2b vault inspect Brain/active.md --vault /root/vault
+```
+
+Confirm:
+- status shows `ignore source: defaults` (because the user's vault has no `vault:` block yet),
+- `.obsidian/community-plugins.json` reports `excluded`, matched rule `.obsidian`,
+- `Brain/active.md` reports `included`.
+
+Optional: edit `/root/vault/Brain/_brain.yaml`, append the `vault:` block from `DEFAULT_BRAIN_CONFIG_YAML`, rerun `o2b vault status` and confirm `ignore source: _brain.yaml`.
+
+- [ ] **Step 5: Commit**
+
+Suggested commit: `chore(release): v0.10.9 β€” vault scope feature`.
+
+---
+
+## Self-Review
+
+**Spec coverage check** (every section of `docs/plans/2026-05-19-vault-scope-design.md`):
+
+- Β§1 Problem β€” context, addressed by Tasks 1-8 collectively.
+- Β§2 Goals 1-6 β€” each covered:
+ 1. single source of truth β†’ Tasks 3 + 4 + 7 + 8
+ 2. updated default set β†’ Task 1
+ 3. status/inspect verbs β†’ Task 9
+ 4. scan-inline reads policy + `--exclude` narrows β†’ Task 8
+ 5. brain doctor warning β†’ Task 11
+ 6. no vault-data migration, no MCP contract break, one release β†’ Task 10 (additive MCP) + Task 12 (CHANGELOG, no migration script)
+- Β§3 Non-goals β€” explicitly observed (no glob patterns, no legacy fallback, no GUI).
+- Β§4 `_brain.yaml` block β€” Task 3.
+- Β§5 `vault-scope` module β€” Tasks 1, 2, 4, 5.
+- Β§5.1 default set β€” Task 1.
+- Β§5.2 walker semantics (subtree reported once) β€” Task 5 (explicit test).
+- Β§6.1 search walker β€” Tasks 6, 7.
+- Β§6.2 scan-inline walker β€” Task 8.
+- Β§7 CLI verbs β€” Task 9.
+- Β§8 MCP block β€” Task 10.
+- Β§9 doctor lint β€” Task 11.
+- Β§10 breaking changes + CHANGELOG β€” Task 12 + Task 7 (the actual removal).
+- Β§11 test plan items β€” distributed across every task that creates the corresponding test file.
+- Β§12 out-of-scope β€” explicitly NOT implemented; nothing in the plan touches them.
+- Β§13 implementation order β€” this plan IS that order.
+
+**Placeholder scan:** none of "TBD / TODO / fill in / implement later / similar to Task N" present in this plan.
+
+**Type consistency:**
+- `VaultIgnoreRule.kind` is `"name" | "path"` throughout.
+- `VaultScope.source` is `"_brain.yaml" | "defaults"` throughout.
+- `ResolvedSearchConfig.ignoreRules` (NEW name) replaces `ignorePaths` consistently across Tasks 6 + 7.
+- `BrainConfig.vault?.ignore_paths` (snake-case) is used in YAML; the TypeScript field uses the same snake-case key to mirror the YAML for the small parser.
+- `excludedDirs` / `excludedFiles` shape (`{relPath, rule}`) is identical in `walkVaultScope` (Task 5), in the status verb (Task 9), and in the MCP block (Task 10).
+
+No drift detected.
+
+---
+
+## Execution Handoff
+
+Plan complete. Two execution options:
+
+1. **Subagent-Driven (recommended)** β€” one fresh subagent per task, two-stage review, fast iteration. Use `superpowers:subagent-driven-development`.
+2. **Inline Execution** β€” execute tasks in this session with checkpoints. Use `superpowers:executing-plans`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 3b3a9f36..55943450 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": "0.10.8",
+ "version": "0.10.9",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index b883b65a..5e6b5f68 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.8",
+ "version": "0.10.9",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index ace2f2d4..656b4254 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.8"
+version: "0.10.9"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 7ae9c0a4..ac299277 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.8",
+ "version": "0.10.9",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index db306be1..5e3544a8 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.8"
+version: "0.10.9"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 2a06ee45..60ef484b 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 = "0.10.8"
+version = "0.10.9"
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/main.ts b/src/cli/main.ts
index 12b2451a..12408a26 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -27,6 +27,7 @@ import { CliError, parseFlags } from "./argparse.ts";
import { handleBrainSubcommand } from "./brain.ts";
import { handleDisciplineSubcommand } from "./discipline.ts";
import { handleSearchSubcommand } from "./search.ts";
+import { handleVaultSubcommand } from "./vault.ts";
import {
NoVaultConfiguredError,
normalizeFlagString,
@@ -489,6 +490,10 @@ Search:
search reindex Rebuild the index atomically (.new -> rename -> .bak)
search status Print index summary (counts, model, vec extension)
search check Pre-flight diagnostics (SQLite, FTS5, vec, provider)
+
+Vault scope:
+ vault status Show how many files/dirs the active policy includes and which rules excluded
+ vault inspect <relpath> Point-check one vault-relative path against the policy
`;
export async function main(argv: ReadonlyArray<string>): Promise<number> {
@@ -567,6 +572,8 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
return await handleDisciplineSubcommand(rest);
case "search":
return await handleSearchSubcommand(rest);
+ case "vault":
+ return await handleVaultSubcommand(rest);
default:
process.stderr.write(`error: unknown command: ${command}\n`);
process.stderr.write(HELP);
diff --git a/src/cli/vault.ts b/src/cli/vault.ts
new file mode 100644
index 00000000..b3fc2144
--- /dev/null
+++ b/src/cli/vault.ts
@@ -0,0 +1,51 @@
+/**
+ * `o2b vault` subcommand dispatcher (v0.10.9).
+ *
+ * Routes to thin wrappers under `./vault/verbs/`. Anchored in
+ * `docs/plans/2026-05-19-vault-scope-design.md` Β§7.
+ */
+
+import { CliError } from "./argparse.ts";
+import { VAULT_HELP, VAULT_VERB_HELP } from "./vault/help-text.ts";
+import { cmdVaultStatus } from "./vault/verbs/status.ts";
+import { cmdVaultInspect } from "./vault/verbs/inspect.ts";
+
+export async function handleVaultSubcommand(
+ argv: ReadonlyArray<string>,
+): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(VAULT_HELP);
+ return argv.length === 0 ? 2 : 0;
+ }
+ const verb = argv[0]!;
+ const rest = argv.slice(1);
+
+ if (rest.length === 1 && (rest[0] === "-h" || rest[0] === "--help")) {
+ const text = VAULT_VERB_HELP[verb];
+ if (text) {
+ process.stdout.write(text);
+ return 0;
+ }
+ process.stdout.write(VAULT_HELP);
+ return 2;
+ }
+
+ try {
+ switch (verb) {
+ case "status":
+ return await cmdVaultStatus(rest);
+ case "inspect":
+ return await cmdVaultInspect(rest);
+ default:
+ process.stderr.write(`error: unknown vault verb: ${verb}\n`);
+ process.stdout.write(VAULT_HELP);
+ return 2;
+ }
+ } catch (exc) {
+ if (exc instanceof CliError) {
+ process.stderr.write(`error: ${exc.message}\n`);
+ return 1;
+ }
+ throw exc;
+ }
+}
diff --git a/src/cli/vault/help-text.ts b/src/cli/vault/help-text.ts
new file mode 100644
index 00000000..189f8743
--- /dev/null
+++ b/src/cli/vault/help-text.ts
@@ -0,0 +1,33 @@
+/**
+ * Help text for `o2b vault *` (v0.10.9).
+ */
+
+export const VAULT_HELP = `usage: o2b vault <verb> [options]
+
+Vault-wide exclusion policy inspection. The policy lives in
+<vault>/Brain/_brain.yaml under \`vault.ignore_paths\` (single source
+of truth for the search indexer, scan-inline, and future scanners).
+
+verbs:
+ status Walk the vault under the active policy and
+ report inclusion / exclusion counts.
+ inspect <relpath> Point-check one vault-relative path with the
+ matched rule.
+
+global flags:
+ --vault <path> Override the configured vault path.
+ --json Emit a machine-readable JSON payload.
+`;
+
+export const VAULT_VERB_HELP: Record<string, string> = {
+ status:
+ "usage: o2b vault status [--vault <path>] [--json]\n\n" +
+ "Walks the vault under the active policy and reports counts plus\n" +
+ "every excluded directory with the matched rule. Files inside an\n" +
+ "excluded subtree are not enumerated separately.\n",
+ inspect:
+ "usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n\n" +
+ "Resolves the policy and runs matchIgnore against <relpath>. The\n" +
+ "relpath is vault-relative (POSIX). Path traversal outside the\n" +
+ "vault is rejected with exit 2.\n",
+};
diff --git a/src/cli/vault/verbs/inspect.ts b/src/cli/vault/verbs/inspect.ts
new file mode 100644
index 00000000..cb33f023
--- /dev/null
+++ b/src/cli/vault/verbs/inspect.ts
@@ -0,0 +1,72 @@
+/**
+ * `o2b vault inspect <relpath>` β€” point-check one vault-relative path.
+ *
+ * Anchored in `docs/plans/2026-05-19-vault-scope-design.md` Β§7.2.
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ inspectPath,
+ resolveVaultScope,
+} from "../../../core/vault-scope/index.ts";
+import { CliError, parseFlags } from "../../argparse.ts";
+import { resolveBrainVault } from "../../brain/helpers.ts";
+import { fail, info, writeJson } from "../../output.ts";
+
+export async function cmdVaultInspect(argv: ReadonlyArray<string>): Promise<number> {
+ const { flags, positional } = parseFlags(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const relpath = positional[0];
+ if (!relpath) {
+ process.stderr.write(
+ "error: usage: o2b vault inspect <relpath> [--vault <path>] [--json]\n",
+ );
+ return 2;
+ }
+ const config = defaultConfigPath();
+ let vault: string;
+ try {
+ vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ } catch (exc) {
+ if (exc instanceof CliError) return fail(exc.message);
+ throw exc;
+ }
+ let result: ReturnType<typeof inspectPath>;
+ try {
+ const scope = resolveVaultScope(vault);
+ result = inspectPath(relpath, scope, vault);
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message ?? exc}\n`);
+ return 2;
+ }
+ // Per design Β§7.2: the rule decision is meaningful even for paths
+ // that do not exist on disk (operator may be checking the policy
+ // before authoring the file), but the operator should know
+ // whether the answer applies to a real path or a hypothetical one.
+ const notFoundSuffix = result.existsOnDisk ? "" : " (not found on disk)";
+ if (flags["json"]) {
+ writeJson({
+ relpath: result.relPath,
+ status: result.excluded ? "excluded" : "included",
+ exists_on_disk: result.existsOnDisk,
+ matched_rule: result.rule
+ ? { raw: result.rule.raw, kind: result.rule.kind }
+ : null,
+ matched_at: result.matchedAt,
+ source: result.source,
+ });
+ return 0;
+ }
+ info(`relpath: ${result.relPath}`);
+ if (!result.excluded) {
+ info(`status: included${notFoundSuffix}`);
+ return 0;
+ }
+ info(`status: excluded${notFoundSuffix}`);
+ if (result.rule) info(`matched rule: ${result.rule.raw} (${result.rule.kind})`);
+ if (result.matchedAt) info(`matched at: ${result.matchedAt}`);
+ info(`source: ${result.source}`);
+ return 0;
+}
diff --git a/src/cli/vault/verbs/status.ts b/src/cli/vault/verbs/status.ts
new file mode 100644
index 00000000..285f3af6
--- /dev/null
+++ b/src/cli/vault/verbs/status.ts
@@ -0,0 +1,84 @@
+/**
+ * `o2b vault status` β€” one-shot view of the vault-scope policy.
+ *
+ * Walks the vault under the active rule set and prints inclusion
+ * counts plus a per-rule list of excluded directories. Anchored in
+ * `docs/plans/2026-05-19-vault-scope-design.md` Β§7.1.
+ */
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import {
+ resolveVaultScope,
+ walkVaultScope,
+} from "../../../core/vault-scope/index.ts";
+import { CliError, parseFlags } from "../../argparse.ts";
+import { resolveBrainVault } from "../../brain/helpers.ts";
+import { fail, info, writeJson } from "../../output.ts";
+
+export async function cmdVaultStatus(argv: ReadonlyArray<string>): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ let vault: string;
+ try {
+ vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ } catch (exc) {
+ if (exc instanceof CliError) return fail(exc.message);
+ throw exc;
+ }
+ let scope: ReturnType<typeof resolveVaultScope>;
+ let walk: ReturnType<typeof walkVaultScope>;
+ try {
+ scope = resolveVaultScope(vault);
+ walk = walkVaultScope(vault, scope);
+ } catch (exc) {
+ return fail(`vault status failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ writeJson({
+ vault,
+ ignore_source: scope.source,
+ rules: scope.rules.map((r) => ({ raw: r.raw, kind: r.kind })),
+ included: { files: walk.includedFiles, dirs: walk.includedDirs },
+ excluded: {
+ dirs: walk.excludedDirs.map((d) => ({
+ rel_path: d.relPath,
+ rule: d.rule.raw,
+ kind: d.rule.kind,
+ })),
+ files: walk.excludedFiles.map((f) => ({
+ rel_path: f.relPath,
+ rule: f.rule.raw,
+ kind: f.rule.kind,
+ })),
+ },
+ });
+ return 0;
+ }
+
+ info(`vault: ${vault}`);
+ info(`ignore source: ${scope.source}`);
+ info("");
+ info(`included: ${walk.includedFiles} files, ${walk.includedDirs} directories`);
+ info(
+ `excluded: ${walk.excludedDirs.length} directories, ${walk.excludedFiles.length} files`,
+ );
+ if (walk.excludedDirs.length > 0) {
+ info("");
+ info("excluded directories:");
+ for (const d of walk.excludedDirs) {
+ info(` ${d.relPath.padEnd(30)} rule ${d.rule.raw} (${d.rule.kind})`);
+ }
+ }
+ if (walk.excludedFiles.length > 0) {
+ info("");
+ info("excluded files:");
+ for (const f of walk.excludedFiles) {
+ info(` ${f.relPath.padEnd(30)} rule ${f.rule.raw} (${f.rule.kind})`);
+ }
+ }
+ return 0;
+}
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index ac2a885d..4c00e72c 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -40,6 +40,7 @@ import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { extractWikilinks, listVaultBasenames, parseFrontmatter } from "../vault.ts";
+import { resolveVaultScope } from "../vault-scope/index.ts";
import { buildBacklinkIndex } from "./backlinks.ts";
import { parseLogDay } from "./log.ts";
import {
@@ -121,6 +122,12 @@ export function runDoctor(
// 1. Config schema check.
checkConfig(vault, issues);
+ // 1b (v0.10.9). Vault scope hygiene: path-style entries that point at
+ // nothing on disk are typically typos. Only fires when the operator
+ // actually declared the `vault.ignore_paths` block (we never warn
+ // about defaults β€” a built-in entry like `.git` may legitimately be
+ // absent in a fresh vault).
+ checkVaultIgnore(vault, issues);
// 2-6. Frontmatter checks across signals / preferences / retired.
const knownBasenames = collectAllBasenames(vault);
@@ -251,6 +258,41 @@ function checkConfig(vault: string, issues: DoctorIssue[]): void {
}
}
+// ----- Vault-scope check ---------------------------------------------------
+
+/**
+ * v0.10.9 hygiene lint: surface path-style entries in
+ * `vault.ignore_paths` that do not resolve to anything on disk. Such
+ * entries are typically typos β€” they look like exclusions but cannot
+ * fire. Bare-name rules are skipped (a missing `.git` directory is
+ * not an error).
+ *
+ * Only runs when the operator declared the block themselves; the
+ * built-in default set may legitimately list paths that do not exist
+ * in a given vault.
+ */
+function checkVaultIgnore(vault: string, issues: DoctorIssue[]): void {
+ let scope;
+ try {
+ scope = resolveVaultScope(vault);
+ } catch {
+ // `checkConfig` already reports the malformed/unreadable _brain.yaml.
+ // Do not let this follow-on lint mask the primary config issue.
+ return;
+ }
+ if (scope.source !== "_brain.yaml") return;
+ for (const rule of scope.rules) {
+ if (rule.kind !== "path") continue;
+ if (existsSync(join(vault, rule.raw))) continue;
+ issues.push({
+ severity: "warning",
+ code: "vault-ignore-missing-path",
+ message:
+ `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,
+ });
+ }
+}
+
// ----- Signal check ---------------------------------------------------------
function checkSignals(
diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.ts
index 3829f668..701ba63f 100644
--- a/src/core/brain/inline-scan.ts
+++ b/src/core/brain/inline-scan.ts
@@ -43,16 +43,11 @@ import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
-
-const HARD_SKIP_DIRS: ReadonlyArray<string> = Object.freeze([
- ".git",
- "node_modules",
- ".open-second-brain",
- ".obsidian",
- ".trash",
- ".stversions",
- "Brain",
-]);
+import {
+ matchIgnore,
+ resolveVaultScope,
+ type VaultIgnoreRule,
+} from "../vault-scope/index.ts";
const MAX_FILE_SIZE_BYTES = 1_048_576; // 1 MiB
@@ -111,9 +106,22 @@ export async function scanInline(
let malformed = 0; // reserved β€” not surfaced separately yet
const includePrefixes = (opts.paths ?? []).map((p) => normalisePrefix(p));
- const userExcludes = (opts.exclude ?? []).map((p) => normalisePrefix(p));
- for (const filePath of walkVault(vault, includePrefixes, userExcludes)) {
+ // Effective rule set (v0.10.9):
+ // - shared `vault.ignore_paths` from Brain/_brain.yaml (or defaults)
+ // - hardcoded `Brain` name-rule: scan-inline must never recurse
+ // into the derived layer regardless of operator policy
+ // - user `--exclude` entries, classified as path-prefix rules
+ const scope = resolveVaultScope(vault);
+ const rules: VaultIgnoreRule[] = [
+ ...scope.rules,
+ { raw: "Brain", kind: "name" },
+ ...(opts.exclude ?? []).map(
+ (raw): VaultIgnoreRule => ({ raw: normalisePrefix(raw), kind: "path" }),
+ ),
+ ];
+
+ for (const filePath of walkVault(vault, includePrefixes, rules)) {
scanned++;
let stat;
try {
@@ -219,19 +227,21 @@ export async function scanInline(
// ----- Walker ---------------------------------------------------------------
function normalisePrefix(rel: string): string {
- // Strip leading/trailing slashes; normalise separator to OS-native.
- const trimmed = rel.replace(/^\/+|\/+$/g, "");
- return trimmed.split("/").join(sep);
+ // POSIX-normalise: strip leading/trailing slashes, replace OS-native
+ // separator with `/`. `matchIgnore` expects POSIX rel-paths.
+ return rel.replace(/^\/+|\/+$/g, "").split(sep).join("/");
}
function* walkVault(
vault: string,
includePrefixes: ReadonlyArray<string>,
- userExcludes: ReadonlyArray<string>,
+ rules: ReadonlyArray<VaultIgnoreRule>,
): Generator<string> {
- const stack: string[] = [vault];
+ const stack: Array<{ abs: string; rel: string }> = [
+ { abs: vault, rel: "" },
+ ];
while (stack.length > 0) {
- const dir = stack.pop()!;
+ const { abs: dir, rel: relDir } = stack.pop()!;
let entries: Dirent[];
try {
entries = readdirSync(dir, { withFileTypes: true });
@@ -240,20 +250,14 @@ function* walkVault(
}
for (const entry of entries) {
const full = join(dir, entry.name);
- const rel = relative(vault, full);
+ const relPosix = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
- // Hard skip: name-based at any depth.
- if (entry.isDirectory() && HARD_SKIP_DIRS.includes(entry.name)) continue;
-
- // User excludes: prefix match for both dirs and files.
- if (userExcludes.some((p) => rel === p || rel.startsWith(p + sep))) {
- continue;
- }
+ if (matchIgnore(relPosix, rules).excluded) continue;
if (entry.isDirectory()) {
- // Include-narrowing only applies to files: directories must
- // descend so subtree files inside an include prefix are reached.
- stack.push(full);
+ // Include-narrowing applies only to files: descend so subtree
+ // files under an include prefix are still reached.
+ stack.push({ abs: full, rel: relPosix });
continue;
}
if (!entry.isFile()) continue;
@@ -261,7 +265,7 @@ function* walkVault(
if (includePrefixes.length > 0) {
const matches = includePrefixes.some(
- (p) => rel === p || rel.startsWith(p + sep),
+ (p) => relPosix === p || relPosix.startsWith(p + "/"),
);
if (!matches) continue;
}
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 927fcf7c..39f77516 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -10,6 +10,7 @@
* - `# comments` and blank lines
* - `key: <scalar>` (numbers parsed; quoted strings stripped)
* - `key:` followed by an indented block of the same form (one level)
+ * - `key: []` and simple inline scalar arrays (`[a, "b"]`)
*
* Anything else is treated as invalid and surfaces through
* `validateBrainConfig` with a field-named error. No external
@@ -20,7 +21,15 @@
import { existsSync, readFileSync } from "node:fs";
-import type { BrainConfig, DisciplineReportConfig } from "./types.ts";
+import type { BrainConfig, BrainVaultConfig, DisciplineReportConfig } from "./types.ts";
+// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to
+// break the module-init cycle: the resolver lives in `index.ts` and
+// itself imports `loadBrainConfig` from this file. See the
+// `defaults.ts` header for the rationale.
+import {
+ classifyVaultIgnoreRule,
+ DEFAULT_VAULT_IGNORE_PATHS,
+} from "../vault-scope/defaults.ts";
import { brainConfigPath } from "./paths.ts";
/** Schema versions this build understands. Bump on incompatible changes. */
@@ -53,6 +62,9 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({
snapshots: Object.freeze({
retention_count: 10,
}),
+ vault: Object.freeze({
+ ignore_paths: DEFAULT_VAULT_IGNORE_PATHS,
+ }),
}) as BrainConfig;
/**
@@ -90,6 +102,22 @@ confidence:
snapshots:
retention_count: 10
+
+# Vault-wide exclusion policy. Single source of truth for every
+# vault walker (search indexer, scan-inline, future scanners).
+# Entries without a slash match a directory name anywhere in the
+# tree; entries with a slash match a vault-relative POSIX path
+# exactly. Remove the block to fall back to the built-in defaults;
+# set ignore_paths to an empty list to disable exclusions entirely.
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+ - .open-second-brain
+ - .obsidian
+ - .trash
+ - .stversions
+ - Brain/.snapshots
`;
const YAML_STRING_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
@@ -390,6 +418,85 @@ export function validateBrainConfigDetailed(
);
requirePositiveInteger("snapshots.retention_count", snapshots.retention_count, source);
+ // Optional `vault` block (v0.10.9). Hard-error on shape problems β€”
+ // exclusions affect every walker, silent ignore would be a footgun.
+ // The block is absent for vaults created before v0.10.9 and for
+ // operators who explicitly removed it; the resolver falls back to
+ // `DEFAULT_VAULT_IGNORE_PATHS` in both cases.
+ let vault: BrainVaultConfig | undefined;
+ if ("vault" in obj) {
+ const raw = obj["vault"];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
+ throw new BrainConfigError(
+ `block must be a map of keys; got ${describe(raw)}`,
+ "vault",
+ source,
+ );
+ }
+ const rawMap = raw as Record<string, unknown>;
+ if ("ignore_paths" in rawMap) {
+ const list = rawMap["ignore_paths"];
+ if (!Array.isArray(list)) {
+ throw new BrainConfigError(
+ `must be a list of strings; got ${describe(list)}`,
+ "vault.ignore_paths",
+ source,
+ );
+ }
+ const validated: string[] = [];
+ list.forEach((entry, i) => {
+ if (typeof entry !== "string") {
+ throw new BrainConfigError(
+ `must be a string; got ${describe(entry)}`,
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ const trimmed = entry.trim();
+ if (trimmed.length === 0) {
+ throw new BrainConfigError(
+ "must be a non-empty string",
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ for (const bad of YAML_STRING_REJECTED_CHARS) {
+ if (trimmed.includes(bad)) {
+ throw new BrainConfigError(
+ `contains a disallowed character ${JSON.stringify(bad)}; ` +
+ "use a simple one-line path",
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ }
+ // `classifyVaultIgnoreRule` strips leading `./` / trailing
+ // `/` / collapsing `//`. An entry that normalises to the
+ // empty string (`./`, `/`, `///`) would silently disable
+ // itself; reject so the operator sees the typo immediately.
+ const normalised = classifyVaultIgnoreRule(trimmed).raw;
+ if (normalised.length === 0) {
+ throw new BrainConfigError(
+ "normalises to the empty string; use a real directory name or vault-relative path",
+ `vault.ignore_paths[${i}]`,
+ source,
+ );
+ }
+ validated.push(normalised);
+ });
+ vault = { ignore_paths: Object.freeze(validated) };
+ }
+ // Forward-compat: unknown sub-keys under `vault:` β†’ warning.
+ for (const key of Object.keys(rawMap)) {
+ if (key !== "ignore_paths") {
+ warnings.push({
+ path: source ?? "<config>",
+ message: `vault.${key}: unknown field ignored (forward-compat)`,
+ });
+ }
+ }
+ }
+
// Optional `discipline_report` section. On any type mismatch, emit a
// warning and drop the section (return undefined) rather than throwing β€”
// the rest of the CLI surface must keep working.
@@ -482,6 +589,7 @@ export function validateBrainConfigDetailed(
"retire",
"confidence",
"snapshots",
+ "vault",
"discipline_report",
]);
for (const key of Object.keys(obj)) {
@@ -514,6 +622,7 @@ export function validateBrainConfigDetailed(
snapshots: {
retention_count: snapshots.retention_count as number,
},
+ ...(vault !== undefined ? { vault } : {}),
...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),
};
@@ -623,7 +732,7 @@ function describe(value: unknown): string {
// - otherwise: the literal string
//
// This intentionally rejects nested mappings deeper than two levels,
-// inline arrays, anchors, and aliases β€” none of which the schema needs.
+// anchors, and aliases β€” none of which the schema needs.
type ParsedScalar = number | string | boolean | null;
type ParsedBlockValue = ParsedScalar | Record<string, ParsedScalar | ParsedScalar[]> | ParsedScalar[];
@@ -706,7 +815,13 @@ export function parseBrainYaml(text: string): ParsedBlock {
const itemText = listLine.content.startsWith("- ")
? listLine.content.slice(2).trim()
: "";
- items.push(parseScalar(itemText, listLine.lineNumber));
+ const item = parseScalar(itemText, listLine.lineNumber);
+ if (Array.isArray(item)) {
+ throw new Error(
+ `line ${listLine.lineNumber}: nested inline arrays are not supported`,
+ );
+ }
+ items.push(item);
i++;
}
if (innerKv.key in child) {
@@ -798,7 +913,10 @@ function detectBlockIndent(lines: Line[], cursor: number): number {
return first.indent;
}
-function parseScalar(text: string, lineNumber: number): ParsedScalar {
+function parseScalar(text: string, lineNumber: number): ParsedScalar | ParsedScalar[] {
+ if (text.startsWith("[") && text.endsWith("]")) {
+ return parseInlineArray(text.slice(1, -1), lineNumber);
+ }
if (
text.length >= 2 &&
((text.startsWith('"') && text.endsWith('"')) ||
@@ -823,3 +941,54 @@ function parseScalar(text: string, lineNumber: number): ParsedScalar {
}
return text;
}
+
+function parseInlineArray(innerRaw: string, lineNumber: number): ParsedScalar[] {
+ const inner = innerRaw.trim();
+ if (inner === "") return [];
+
+ const out: ParsedScalar[] = [];
+ let current = "";
+ let inQuote = false;
+ let quoteChar: '"' | "'" | "" = "";
+
+ for (let i = 0; i < inner.length; i++) {
+ const ch = inner[i]!;
+ if (inQuote) {
+ current += ch;
+ if (ch === quoteChar) {
+ inQuote = false;
+ quoteChar = "";
+ }
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ inQuote = true;
+ quoteChar = ch;
+ current += ch;
+ continue;
+ }
+ if (ch === ",") {
+ out.push(parseInlineArrayItem(current, lineNumber));
+ current = "";
+ continue;
+ }
+ current += ch;
+ }
+ if (inQuote) {
+ throw new Error(`line ${lineNumber}: unterminated quoted string in inline array`);
+ }
+ out.push(parseInlineArrayItem(current, lineNumber));
+ return out;
+}
+
+function parseInlineArrayItem(text: string, lineNumber: number): ParsedScalar {
+ const trimmed = text.trim();
+ if (trimmed === "") {
+ throw new Error(`line ${lineNumber}: empty item in inline array`);
+ }
+ const parsed = parseScalar(trimmed, lineNumber);
+ if (Array.isArray(parsed)) {
+ throw new Error(`line ${lineNumber}: nested inline arrays are not supported`);
+ }
+ return parsed;
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 197e2308..9a99aeb8 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -642,6 +642,24 @@ export interface BrainSnapshotsConfig {
readonly retention_count: number;
}
+/**
+ * Vault-wide exclusion policy (`Brain/_brain.yaml` β†’ `vault:`).
+ *
+ * Single source of truth for every vault walker β€” search indexer,
+ * `scan-inline`, future scanners. Anchored in
+ * `docs/plans/2026-05-19-vault-scope-design.md` Β§4.
+ *
+ * Entries without `/` are bare directory names matched at any
+ * depth; entries containing `/` are vault-relative POSIX paths
+ * matched exactly. The block is optional in `_brain.yaml`; absence
+ * (or absence of `ignore_paths`) leaves this field `undefined` and
+ * the walkers fall back to `DEFAULT_VAULT_IGNORE_PATHS`. An
+ * explicit empty array is a user choice meaning "exclude nothing".
+ */
+export interface BrainVaultConfig {
+ readonly ignore_paths: ReadonlyArray<string>;
+}
+
/**
* Optional configuration for the daily discipline report (Β§D of the
* agent-discipline-tail design). Absent on vaults that have not opted
@@ -675,6 +693,14 @@ export interface BrainConfig {
readonly retire: BrainRetireConfig;
readonly confidence: BrainConfidenceConfig;
readonly snapshots: BrainSnapshotsConfig;
+ /**
+ * Vault-wide exclusion policy (v0.10.9). Absent when the user
+ * has not declared `vault.ignore_paths` in `_brain.yaml`; the
+ * resolver falls back to `DEFAULT_VAULT_IGNORE_PATHS` in that
+ * case. Present with an empty `ignore_paths` array means "the
+ * user explicitly wants no exclusions".
+ */
+ readonly vault?: BrainVaultConfig;
/** Optional daily discipline-report configuration (Β§D). Absent when not configured. */
readonly discipline_report?: DisciplineReportConfig;
}
diff --git a/src/core/path-safety.ts b/src/core/path-safety.ts
index 58bcd2a3..855b33b3 100644
--- a/src/core/path-safety.ts
+++ b/src/core/path-safety.ts
@@ -92,6 +92,19 @@ function safeRealpath(p: string): string {
}
}
+/**
+ * Convert an OS-native path to POSIX form (forward slashes).
+ *
+ * Returns the input unchanged on POSIX hosts (`sep === "/"`); on
+ * Windows, replaces every `\\` separator with `/`. Used by the
+ * vault walkers when they project absolute or vault-relative OS
+ * paths into the POSIX form that `matchIgnore` and Obsidian
+ * wikilinks both expect.
+ */
+export function toPosix(p: string): string {
+ return sep === "/" ? p : p.split(sep).join("/");
+}
+
/**
* Vault-relative path with forward slashes.
*
diff --git a/src/core/search/index.ts b/src/core/search/index.ts
index a0da82e8..da412417 100644
--- a/src/core/search/index.ts
+++ b/src/core/search/index.ts
@@ -10,12 +10,17 @@ import {
parseFloat01 as parseFloat01Shared,
parseInteger as parseIntegerShared,
} from "../validate.ts";
+import { resolveVaultScope } from "../vault-scope/index.ts";
import { resolveIndexPath } from "./paths.ts";
import { SearchError } from "./types.ts";
-import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "./types.ts";
+import type {
+ ResolvedEmbeddingConfig,
+ ResolvedSearchConfig,
+ VaultIgnoreRule,
+} from "./types.ts";
-type SearchConfigOverrides = Partial<Omit<ResolvedSearchConfig, "ignorePaths" | "semantic">> & {
- readonly ignorePaths?: ReadonlyArray<string>;
+type SearchConfigOverrides = Partial<Omit<ResolvedSearchConfig, "ignoreRules" | "semantic">> & {
+ readonly ignoreRules?: ReadonlyArray<VaultIgnoreRule>;
readonly semantic?: Partial<ResolvedEmbeddingConfig>;
};
@@ -29,6 +34,7 @@ export type {
SearchErrorCode,
SearchOptions,
SearchOutcome,
+ VaultIgnoreRule,
} from "./types.ts";
export { SearchError, SEARCH_ERROR_CODES } from "./types.ts";
@@ -43,15 +49,6 @@ export {
} from "./indexer.ts";
export { search } from "./search.ts";
-const DEFAULT_IGNORE_PATHS = [
- ".git",
- "node_modules",
- ".open-second-brain",
- ".obsidian/cache",
- ".trash",
- ".stversions",
-];
-
const DEFAULTS = {
chunkSize: 800,
chunkOverlap: 100,
@@ -147,14 +144,6 @@ function parseProvider(raw: string | null): ResolvedEmbeddingConfig["provider"]
);
}
-function parseIgnorePaths(raw: string | null): string[] {
- if (raw === null) return [...DEFAULT_IGNORE_PATHS];
- return raw
- .split(",")
- .map((s) => s.trim())
- .filter((s) => s.length > 0);
-}
-
export function resolveSearchConfig(opts: {
vault: string;
configPath?: string;
@@ -192,16 +181,12 @@ export function resolveSearchConfig(opts: {
DEFAULTS.semanticWeight,
"search_semantic_weight",
);
- if (keywordWeight + semanticWeight > 1.0 + 1e-9) {
- throw new SearchError(
- "INVALID_INPUT",
- `keyword_weight + semantic_weight must sum to <= 1, got ${keywordWeight} + ${semanticWeight}`,
- );
- }
- const ignorePaths = parseIgnorePaths(
- envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_IGNORE", "search_ignore_paths"),
- );
+ // v0.10.9: single source of truth lives in Brain/_brain.yaml under
+ // `vault.ignore_paths`. The legacy `search_ignore_paths` config key
+ // and `OPEN_SECOND_BRAIN_SEARCH_IGNORE` env variable were removed.
+ const scope = resolveVaultScope(opts.vault);
+ const ignoreRules = scope.rules;
const semanticEnabled = parseBool(
envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_SEMANTIC", "search_semantic_enabled"),
@@ -256,7 +241,7 @@ export function resolveSearchConfig(opts: {
const base: ResolvedSearchConfig = Object.freeze({
vault: opts.vault,
dbPath,
- ignorePaths: Object.freeze([...ignorePaths]),
+ ignoreRules,
chunkSize,
chunkOverlap,
keywordWeight,
@@ -264,16 +249,17 @@ export function resolveSearchConfig(opts: {
semantic,
});
- validateResolvedConfig(base);
-
- if (!opts.overrides) return base;
+ if (!opts.overrides) {
+ validateResolvedConfig(base);
+ return base;
+ }
const merged = Object.freeze({
...base,
...opts.overrides,
semantic: Object.freeze({ ...base.semantic, ...(opts.overrides.semantic ?? {}) }),
- ignorePaths: opts.overrides.ignorePaths
- ? Object.freeze([...opts.overrides.ignorePaths])
- : base.ignorePaths,
+ ignoreRules: opts.overrides.ignoreRules
+ ? Object.freeze([...opts.overrides.ignoreRules])
+ : base.ignoreRules,
});
validateResolvedConfig(merged);
return merged;
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 83e76f8b..c761ab35 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -4,6 +4,10 @@
* Anchored in docs/plans/2026-05-16-brain-search-design.md Β§12, Β§14.
*/
+import type { VaultIgnoreRule } from "../vault-scope/defaults.ts";
+
+export type { VaultIgnoreRule };
+
export const SEARCH_ERROR_CODES = [
"INDEX_MISSING",
"INDEX_UNREADABLE",
@@ -133,7 +137,16 @@ export interface ResolvedEmbeddingConfig {
export interface ResolvedSearchConfig {
readonly vault: string;
readonly dbPath: string;
- readonly ignorePaths: ReadonlyArray<string>;
+ /**
+ * Vault-wide exclusion rules. Resolved through
+ * `src/core/vault-scope` from `<vault>/Brain/_brain.yaml` β†’
+ * `vault.ignore_paths`; falls back to the shared built-in default
+ * set when the block is not declared. The legacy
+ * `search_ignore_paths` config key and the
+ * `OPEN_SECOND_BRAIN_SEARCH_IGNORE` env variable were removed in
+ * v0.10.9.
+ */
+ readonly ignoreRules: ReadonlyArray<VaultIgnoreRule>;
readonly chunkSize: number;
readonly chunkOverlap: number;
readonly keywordWeight: number;
diff --git a/src/core/search/walker.ts b/src/core/search/walker.ts
index a579ffa2..70774062 100644
--- a/src/core/search/walker.ts
+++ b/src/core/search/walker.ts
@@ -3,11 +3,19 @@
*
* Anchored in docs/plans/2026-05-16-brain-search-design.md Β§6 edge cases
* (symlinks, ignore list).
+ *
+ * v0.10.9: ignore decisions are delegated to
+ * `src/core/vault-scope:matchIgnore` so the search indexer and
+ * `scan-inline` share one policy. `parseIgnore` (CSV string ➝ set)
+ * was removed in this version; `ResolvedSearchConfig.ignoreRules`
+ * is already classified at config-resolution time.
*/
import { readdirSync, statSync, realpathSync, type Dirent, type Stats } from "node:fs";
import { join, relative, sep } from "node:path";
+import { toPosix } from "../path-safety.ts";
+import { matchIgnore } from "../vault-scope/index.ts";
import type { ResolvedSearchConfig } from "./types.ts";
export interface WalkedFile {
@@ -18,47 +26,18 @@ export interface WalkedFile {
readonly stat: Stats;
}
-function toPosix(p: string): string {
- return sep === "/" ? p : p.split(sep).join("/");
-}
-
-/**
- * Parse the ignore list into two sets:
- *
- * - bare names (no `/`) match a directory whose name equals the entry
- * anywhere in the tree;
- * - relative paths match the vault-relative directory exactly.
- */
-function parseIgnore(ignorePaths: ReadonlyArray<string>): {
- names: Set<string>;
- relPaths: Set<string>;
-} {
- const names = new Set<string>();
- const relPaths = new Set<string>();
- for (const raw of ignorePaths) {
- const e = raw.trim();
- if (e === "") continue;
- if (e.includes("/")) relPaths.add(e);
- else names.add(e);
- }
- return { names, relPaths };
-}
-
function isInsideVault(absTarget: string, vaultReal: string): boolean {
- const targetReal = (() => {
- try {
- return realpathSync(absTarget);
- } catch {
- return null;
- }
- })();
- if (targetReal === null) return false;
- return targetReal === vaultReal || targetReal.startsWith(vaultReal + sep);
+ try {
+ const r = realpathSync(absTarget);
+ return r === vaultReal || r.startsWith(vaultReal + sep);
+ } catch {
+ return false;
+ }
}
/**
* Synchronous generator yielding every `.md` file under `config.vault`
- * (respecting `config.ignorePaths`). The caller drives the iteration so
+ * (respecting `config.ignoreRules`). The caller drives the iteration so
* the indexer can pipeline reads + writes without buffering the whole
* tree.
*/
@@ -70,12 +49,12 @@ export function* walkVault(config: ResolvedSearchConfig): Generator<WalkedFile>
return config.vault;
}
})();
- const { names, relPaths } = parseIgnore(config.ignorePaths);
// Track real (canonical) paths of visited directories so a symlink
// pointing back at an ancestor (or sibling) cannot send the walker
// into an infinite loop. `isInsideVault` covers escape outside the
// vault but is not acyclic on its own.
const seenDirs = new Set<string>([vaultReal]);
+ const rules = config.ignoreRules;
function* walk(dir: string): Generator<WalkedFile> {
let entries: Dirent[];
@@ -104,8 +83,7 @@ export function* walkVault(config: ResolvedSearchConfig): Generator<WalkedFile>
}
if (stat.isDirectory()) {
- if (names.has(entry.name)) continue;
- if (relPaths.has(relPath)) continue;
+ if (matchIgnore(relPath, rules).excluded) continue;
let dirReal: string;
try {
dirReal = realpathSync(absPath);
@@ -122,6 +100,9 @@ export function* walkVault(config: ResolvedSearchConfig): Generator<WalkedFile>
if (!stat.isFile()) continue;
if (!entry.name.toLowerCase().endsWith(".md")) continue;
if (isLinkHint && !isInsideVault(absPath, vaultReal)) continue;
+ // File-level rule too: a `path/to/file.md` entry in
+ // `vault.ignore_paths` excludes that exact file.
+ if (matchIgnore(relPath, rules).excluded) continue;
yield { absPath, relPath, stat };
}
diff --git a/src/core/vault-scope/defaults.ts b/src/core/vault-scope/defaults.ts
new file mode 100644
index 00000000..36172742
--- /dev/null
+++ b/src/core/vault-scope/defaults.ts
@@ -0,0 +1,60 @@
+/**
+ * Shared constants and rule types for the Vault Scope module.
+ *
+ * Split out of `index.ts` so `src/core/brain/policy.ts` can read the
+ * default exclusion set without dragging in the resolver β€” the
+ * resolver imports `policy.ts`, which would otherwise create a
+ * module-initialisation cycle.
+ *
+ * Anchored in docs/plans/2026-05-19-vault-scope-design.md Β§5.
+ */
+
+export interface VaultIgnoreRule {
+ /** Entry exactly as written in `Brain/_brain.yaml`. */
+ readonly raw: string;
+ /**
+ * `name` matches any directory whose basename equals `raw`,
+ * anywhere in the tree. `path` matches a vault-relative POSIX
+ * path exactly.
+ */
+ readonly kind: "name" | "path";
+}
+
+export const DEFAULT_VAULT_IGNORE_PATHS: ReadonlyArray<string> = Object.freeze([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+]);
+
+/**
+ * Classify a raw entry into a `VaultIgnoreRule`.
+ *
+ * Normalises three operator footguns that would silently disable a
+ * rule otherwise β€” `matchIgnore` walks prefixes with no trailing
+ * slash and rejects empty segments, so the raw inputs are made to
+ * match that shape:
+ *
+ * - leading `./` is stripped (`./Brain/.snapshots` β†’ `Brain/.snapshots`);
+ * - trailing `/` is stripped (`Brain/.snapshots/` β†’ `Brain/.snapshots`);
+ * - runs of `//` are collapsed (`Brain//.snapshots` β†’ `Brain/.snapshots`).
+ *
+ * After normalisation, an entry with `/` is a path-rule; otherwise
+ * it is a bare-name rule. Entries that normalise to the empty string
+ * keep their pre-normalisation classification; the policy validator
+ * is responsible for rejecting them before they get here.
+ */
+export function classifyVaultIgnoreRule(raw: string): VaultIgnoreRule {
+ const normalised = normaliseRawRule(raw);
+ return { raw: normalised, kind: normalised.includes("/") ? "path" : "name" };
+}
+
+function normaliseRawRule(raw: string): string {
+ let s = raw.startsWith("./") ? raw.slice(2) : raw;
+ s = s.replace(/\/+/g, "/");
+ s = s.replace(/\/+$/g, "");
+ return s;
+}
diff --git a/src/core/vault-scope/index.ts b/src/core/vault-scope/index.ts
new file mode 100644
index 00000000..73f53c81
--- /dev/null
+++ b/src/core/vault-scope/index.ts
@@ -0,0 +1,287 @@
+/**
+ * Vault Scope β€” single source of truth for vault-wide exclusion
+ * policy.
+ *
+ * Anchored in docs/plans/2026-05-19-vault-scope-design.md Β§5.
+ *
+ * Public surface:
+ * - `DEFAULT_VAULT_IGNORE_PATHS`, `VaultIgnoreRule` β€” re-exported
+ * from `./defaults.ts`; that submodule is the cycle-safe home
+ * used by `src/core/brain/policy.ts`.
+ * - `matchIgnore` β€” pure matcher.
+ * - `resolveVaultScope` β€” reads `Brain/_brain.yaml` and produces
+ * a `VaultScope` with classified rules.
+ */
+
+import {
+ existsSync,
+ readdirSync,
+ realpathSync,
+ statSync,
+ type Dirent,
+} from "node:fs";
+import { join, sep } from "node:path";
+
+import { loadBrainConfig } from "../brain/policy.ts";
+import { brainConfigPath } from "../brain/paths.ts";
+import { toPosix } from "../path-safety.ts";
+import {
+ DEFAULT_VAULT_IGNORE_PATHS,
+ classifyVaultIgnoreRule,
+ type VaultIgnoreRule,
+} from "./defaults.ts";
+
+export {
+ DEFAULT_VAULT_IGNORE_PATHS,
+ classifyVaultIgnoreRule,
+ type VaultIgnoreRule,
+};
+
+// ----- matchIgnore ---------------------------------------------------------
+
+export interface IgnoreMatch {
+ readonly excluded: boolean;
+ readonly rule: VaultIgnoreRule | null;
+ /** POSIX rel-path of the prefix that triggered the match, or null. */
+ readonly matchedAt: string | null;
+}
+
+const NEGATIVE_MATCH: IgnoreMatch = Object.freeze({
+ excluded: false,
+ rule: null,
+ matchedAt: null,
+});
+
+/**
+ * Walk `relPath` segment by segment. For each prefix, check name-
+ * and path-rules. Return the shortest prefix that excludes, or
+ * `{excluded: false}` if no rule fires.
+ *
+ * `relPath` must be POSIX (forward-slash separated), vault-relative,
+ * and free of `.` / `..` components β€” `matchIgnore` does no
+ * normalisation. Callers (`walkVaultScope`, `inspectPath`) prepare
+ * the input.
+ */
+export function matchIgnore(
+ relPath: string,
+ rules: ReadonlyArray<VaultIgnoreRule>,
+): IgnoreMatch {
+ if (relPath === "" || rules.length === 0) return NEGATIVE_MATCH;
+ const segments = relPath.split("/").filter((s) => s.length > 0);
+ let prefix = "";
+ for (const seg of segments) {
+ prefix = prefix === "" ? seg : `${prefix}/${seg}`;
+ for (const rule of rules) {
+ if (rule.kind === "name") {
+ if (rule.raw === seg) {
+ return { excluded: true, rule, matchedAt: prefix };
+ }
+ continue;
+ }
+ // kind === "path": exact prefix match.
+ if (rule.raw === prefix) {
+ return { excluded: true, rule, matchedAt: prefix };
+ }
+ }
+ }
+ return NEGATIVE_MATCH;
+}
+
+// ----- resolveVaultScope ---------------------------------------------------
+
+export interface VaultScope {
+ /** Final list of paths in declaration order. */
+ readonly ignorePaths: ReadonlyArray<string>;
+ /** Same list, classified as `name | path`. */
+ readonly rules: ReadonlyArray<VaultIgnoreRule>;
+ readonly source: "_brain.yaml" | "defaults";
+}
+
+function buildScope(
+ paths: ReadonlyArray<string>,
+ source: VaultScope["source"],
+): VaultScope {
+ const ignorePaths = Object.freeze([...paths]);
+ const rules = Object.freeze(ignorePaths.map(classifyVaultIgnoreRule));
+ return Object.freeze({ ignorePaths, rules, source });
+}
+
+const DEFAULT_SCOPE: VaultScope = buildScope(
+ DEFAULT_VAULT_IGNORE_PATHS,
+ "defaults",
+);
+
+/**
+ * Read `<vault>/Brain/_brain.yaml` and project the `vault.ignore_paths`
+ * declaration into a `VaultScope`. If the file is missing or omits the
+ * `vault` block (or the `ignore_paths` key inside it), return the
+ * default scope.
+ *
+ * A missing file is not an error here β€” existing vaults may predate
+ * `_brain.yaml`. A present-but-invalid config is different: fail closed
+ * so walkers do not silently index or scan paths the operator meant to
+ * exclude.
+ */
+export function resolveVaultScope(vault: string): VaultScope {
+ if (!existsSync(brainConfigPath(vault))) return DEFAULT_SCOPE;
+ const cfg = loadBrainConfig(vault);
+ const declared = cfg.vault?.ignore_paths;
+ if (declared === undefined) return DEFAULT_SCOPE;
+ return buildScope(declared, "_brain.yaml");
+}
+
+// ----- walkVaultScope ------------------------------------------------------
+
+export interface ExcludedEntry {
+ readonly relPath: string;
+ readonly rule: VaultIgnoreRule;
+}
+
+export interface VaultScopeWalk {
+ readonly includedFiles: number;
+ readonly includedDirs: number;
+ readonly excludedDirs: ReadonlyArray<ExcludedEntry>;
+ readonly excludedFiles: ReadonlyArray<ExcludedEntry>;
+}
+
+/**
+ * Recursive fs walk over `<vault>/` that applies `scope.rules` and
+ * records every excluded subtree root (one entry per top of an
+ * excluded subtree β€” descendants are NOT enumerated again, per
+ * design Β§5.2).
+ *
+ * Acyclic-symlink guarded via realpath + `seenDirs`; symlinks that
+ * escape the vault root are dropped. Every file and directory is
+ * counted regardless of extension β€” exclusion policy applies
+ * uniformly, the `.md` filter belongs to the search walker.
+ */
+export function walkVaultScope(vault: string, scope: VaultScope): VaultScopeWalk {
+ const vaultReal = (() => {
+ try { return realpathSync(vault); } catch { return vault; }
+ })();
+ const excludedDirs: ExcludedEntry[] = [];
+ const excludedFiles: ExcludedEntry[] = [];
+ let includedFiles = 0;
+ let includedDirs = 0;
+ const seenDirs = new Set<string>([vaultReal]);
+
+ function walk(absDir: string, relDir: string): void {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(absDir, { withFileTypes: true, encoding: "utf8" });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ for (const entry of entries) {
+ const abs = join(absDir, entry.name);
+ const rel = relDir === ""
+ ? toPosix(entry.name)
+ : `${relDir}/${toPosix(entry.name)}`;
+ const isLinkHint = entry.isSymbolicLink();
+ let stat;
+ try { stat = statSync(abs); } catch { continue; }
+ if (stat.isDirectory()) {
+ const m = matchIgnore(rel, scope.rules);
+ if (m.excluded && m.rule) {
+ excludedDirs.push({ relPath: rel, rule: m.rule });
+ continue;
+ }
+ let real: string;
+ try { real = realpathSync(abs); } catch { continue; }
+ if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;
+ if (seenDirs.has(real)) continue;
+ seenDirs.add(real);
+ includedDirs++;
+ walk(abs, rel);
+ continue;
+ }
+ if (!stat.isFile()) continue;
+ // Symmetric with src/core/search/walker.ts: a symlinked file
+ // that resolves outside the vault must not be counted as
+ // included. Without this check the policy-walker and the
+ // search-walker would disagree on the same vault β€” exactly
+ // the kind of drift v0.10.9 is meant to eliminate.
+ if (isLinkHint) {
+ let real: string;
+ try { real = realpathSync(abs); } catch { continue; }
+ if (real !== vaultReal && !real.startsWith(vaultReal + sep)) continue;
+ }
+ const m = matchIgnore(rel, scope.rules);
+ if (m.excluded && m.rule) {
+ excludedFiles.push({ relPath: rel, rule: m.rule });
+ continue;
+ }
+ includedFiles++;
+ }
+ }
+
+ walk(vaultReal, "");
+
+ return Object.freeze({
+ includedFiles,
+ includedDirs,
+ excludedDirs: Object.freeze(excludedDirs),
+ excludedFiles: Object.freeze(excludedFiles),
+ });
+}
+
+// ----- inspectPath ---------------------------------------------------------
+
+export interface InspectResult {
+ /** Vault-relative POSIX path after `./` / `//` / trailing-slash normalisation. */
+ readonly relPath: string;
+ readonly excluded: boolean;
+ readonly rule: VaultIgnoreRule | null;
+ readonly matchedAt: string | null;
+ readonly source: VaultScope["source"];
+ /**
+ * `true` when `<vault>/<relPath>` exists on disk, `false` otherwise.
+ * Surfaces design Β§7.2: the operator wants to know whether the
+ * rule decision applies to a real file or to a hypothetical one
+ * (e.g. checking the policy before authoring a path). Inspectors
+ * that don't need this info can ignore the field.
+ */
+ readonly existsOnDisk: boolean;
+}
+
+/**
+ * Point-check whether `<vault>/<relPath>` is included by the given
+ * scope.
+ *
+ * Normalises `relPath` to POSIX, strips leading `./` and surrounding
+ * slashes, and throws on `..` traversal so callers cannot
+ * accidentally inspect something outside the vault root. Touches
+ * the filesystem only to set `existsOnDisk`; the rule decision is
+ * determined by `scope.rules` alone.
+ */
+export function inspectPath(
+ relPath: string,
+ scope: VaultScope,
+ vault: string,
+): InspectResult {
+ // Segment-based normalisation: tolerate leading `./`, trailing
+ // slashes, double slashes. Throw on any `..` component β€” silently
+ // resolving them would let the caller probe outside the vault.
+ const segments: string[] = [];
+ for (const raw of toPosix(relPath).split("/")) {
+ if (raw === "" || raw === ".") continue;
+ if (raw === "..") {
+ throw new Error(
+ `relPath must not traverse outside the vault: ${relPath}`,
+ );
+ }
+ segments.push(raw);
+ }
+ const normalised = segments.join("/");
+ const m = matchIgnore(normalised, scope.rules);
+ const existsOnDisk = normalised !== "" && existsSync(join(vault, normalised));
+ return Object.freeze({
+ relPath: normalised,
+ excluded: m.excluded,
+ rule: m.rule,
+ matchedAt: m.matchedAt,
+ source: scope.source,
+ existsOnDisk,
+ });
+}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 2af12bb7..9a27cd20 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -32,6 +32,10 @@ import {
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
import { isDir } from "../core/fs-utils.ts";
+import {
+ resolveVaultScope,
+ walkVaultScope,
+} from "../core/vault-scope/index.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";
@@ -88,6 +92,35 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
const brain = vaultExists ? computeBrainStatus(ctx.vault) : null;
const searchDisabled = discovery.data["search_enabled"] === "false";
const search = vaultExists && !searchDisabled ? await buildSearchStatusBlock(ctx) : null;
+ // v0.10.9 β€” `vault` block exposes the shared exclusion policy plus
+ // aggregate include/exclude counts. Per-path detail lives in the CLI
+ // (`o2b vault status`); MCP payloads stay small.
+ //
+ // `resolveVaultScope` fails closed when `_brain.yaml` is malformed
+ // (design Β§5) β€” the right call for walkers that would otherwise
+ // silently drop the operator's policy. But this MCP tool is a
+ // read-only diagnostic, and the operator wants the brain / search /
+ // config blocks visible even when the vault scope cannot be
+ // resolved. Catch and degrade to `{ error: "..." }` instead of
+ // taking the whole `second_brain_status` payload down with it.
+ let vault: Record<string, unknown> | null = null;
+ if (vaultExists) {
+ try {
+ const scope = resolveVaultScope(ctx.vault);
+ const walk = walkVaultScope(ctx.vault, scope);
+ vault = {
+ ignore_source: scope.source,
+ rules: scope.rules.map((r) => ({ raw: r.raw, kind: r.kind })),
+ included: { files: walk.includedFiles, dirs: walk.includedDirs },
+ excluded: {
+ dirs: walk.excludedDirs.length,
+ files: walk.excludedFiles.length,
+ },
+ };
+ } catch (err) {
+ vault = { error: (err as Error)?.message ?? String(err) };
+ }
+ }
return {
config_path: String(discovery.path),
config_exists: discovery.exists,
@@ -95,6 +128,7 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
config: redactMapping(discovery.data),
vault_path: ctx.vault,
vault_exists: vaultExists,
+ ...(vault ? { vault } : {}),
...(brain ? { brain } : {}),
...(search ? { search } : {}),
};
diff --git a/tests/cli/vault.test.ts b/tests/cli/vault.test.ts
new file mode 100644
index 00000000..98c282af
--- /dev/null
+++ b/tests/cli/vault.test.ts
@@ -0,0 +1,187 @@
+/**
+ * CLI surface tests for `o2b vault status` and `o2b vault inspect`
+ * (v0.10.9). Each test bootstraps a fresh vault via `o2b init` and
+ * `o2b brain init` (the same scaffold pattern as the existing
+ * brain CLI tests).
+ */
+
+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";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-vault-cli-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+async function bootstrap(): Promise<void> {
+ let r = await runCli(["init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ r = await runCli(["brain", "init", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+}
+
+describe("o2b vault status", () => {
+ test("prints counts and the active source on a fresh vault", async () => {
+ await bootstrap();
+ mkdirSync(join(vault, ".obsidian"), { recursive: true });
+ writeFileSync(join(vault, ".obsidian", "app.json"), "{}");
+ writeFileSync(join(vault, "Notes.md"), "x");
+ const r = await runCli(["vault", "status", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("ignore source: _brain.yaml");
+ expect(r.stdout).toMatch(/\.obsidian\s+rule \.obsidian \(name\)/);
+ });
+
+ test("--json output has stable shape", async () => {
+ await bootstrap();
+ mkdirSync(join(vault, ".obsidian"), { recursive: true });
+ const r = await runCli(["vault", "status", "--vault", vault, "--json"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.ignore_source).toBe("_brain.yaml");
+ expect(typeof payload.included.files).toBe("number");
+ expect(typeof payload.included.dirs).toBe("number");
+ expect(Array.isArray(payload.excluded.dirs)).toBe(true);
+ expect(payload.excluded.dirs.some(
+ (d: { rel_path: string }) => d.rel_path === ".obsidian",
+ )).toBe(true);
+ expect(Array.isArray(payload.rules)).toBe(true);
+ });
+});
+
+describe("o2b vault inspect", () => {
+ test("reports an included path that exists on disk (no suffix)", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "idea.md"), "x");
+ const r = await runCli(
+ ["vault", "inspect", "idea.md", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("status: included");
+ expect(r.stdout).not.toContain("(not found on disk)");
+ });
+
+ test("reports an included path missing from disk with (not found on disk) suffix", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["vault", "inspect", "hypothetical.md", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("status: included (not found on disk)");
+ });
+
+ test("reports an excluded path with matched rule, source, and (not found) suffix when file is hypothetical", async () => {
+ await bootstrap();
+ const r = await runCli(
+ [
+ "vault",
+ "inspect",
+ ".obsidian/plugins/foo/note.md",
+ "--vault",
+ vault,
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("status: excluded (not found on disk)");
+ expect(r.stdout).toContain("matched rule: .obsidian (name)");
+ expect(r.stdout).toContain("matched at: .obsidian");
+ expect(r.stdout).toContain("source: _brain.yaml");
+ });
+
+ test("missing relpath exits 2 with usage hint", async () => {
+ await bootstrap();
+ const r = await runCli(["vault", "inspect", "--vault", vault], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("usage:");
+ });
+
+ test("path traversal exits 2", async () => {
+ await bootstrap();
+ const r = await runCli(
+ ["vault", "inspect", "../outside", "--vault", vault],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("traverse");
+ });
+
+ test("--json shape exposes matched_rule, matched_at, exists_on_disk", async () => {
+ await bootstrap();
+ const r = await runCli(
+ [
+ "vault",
+ "inspect",
+ ".obsidian/plugins/foo/note.md",
+ "--vault",
+ vault,
+ "--json",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout);
+ expect(payload.status).toBe("excluded");
+ expect(payload.exists_on_disk).toBe(false);
+ expect(payload.matched_rule.raw).toBe(".obsidian");
+ expect(payload.matched_rule.kind).toBe("name");
+ expect(payload.matched_at).toBe(".obsidian");
+ expect(payload.source).toBe("_brain.yaml");
+ });
+
+ test("--json on included path has matched_rule=null and exists_on_disk=true when file present", async () => {
+ await bootstrap();
+ writeFileSync(join(vault, "idea.md"), "x");
+ const r = await runCli(
+ ["vault", "inspect", "idea.md", "--vault", vault, "--json"],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },
+ );
+ const payload = JSON.parse(r.stdout);
+ expect(payload.status).toBe("included");
+ expect(payload.exists_on_disk).toBe(true);
+ expect(payload.matched_rule).toBeNull();
+ });
+});
+
+describe("o2b vault dispatcher", () => {
+ test("no verb prints help and exits 2", async () => {
+ const r = await runCli(["vault"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stdout).toContain("usage: o2b vault");
+ });
+
+ test("unknown verb exits 2", async () => {
+ const r = await runCli(["vault", "explode"], {
+ env: { OPEN_SECOND_BRAIN_CONFIG: config },
+ });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("unknown vault verb");
+ });
+});
diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.ts
index b948112f..8eb94ac8 100644
--- a/tests/core/brain.doctor.test.ts
+++ b/tests/core/brain.doctor.test.ts
@@ -47,6 +47,11 @@ beforeEach(() => {
dirs.preferences,
dirs.retired,
dirs.log,
+ // v0.10.9: bootstrap-matched scaffold. The default _brain.yaml
+ // lists `Brain/.snapshots` under `vault.ignore_paths`, so the
+ // doctor's `vault-ignore-missing-path` lint expects the directory
+ // to exist (real `o2b brain init` creates it).
+ dirs.snapshots,
]) {
mkdirSync(d, { recursive: true });
}
@@ -804,3 +809,56 @@ describe("frontmatter-double-shape lint (Β§24)", () => {
expect(res.warnings.filter((w) => w.code === "frontmatter-double-shape")).toHaveLength(0);
});
});
+
+describe("vault-ignore-missing-path lint (v0.10.9)", () => {
+ test("warns when vault.ignore_paths contains a path-style entry that does not exist", () => {
+ atomicWriteFileSync(
+ brainConfigPath(tmp),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - Brain/.snapshots
+ - Notes/does-not-exist
+`,
+ );
+ const res = runDoctor(tmp);
+ const missing = res.warnings.find((w) => w.code === "vault-ignore-missing-path");
+ expect(missing).toBeDefined();
+ expect(missing!.message).toContain("Notes/does-not-exist");
+ // Brain/.snapshots was created by the test scaffold β€” no warning
+ // for that entry.
+ expect(
+ res.warnings
+ .filter((w) => w.code === "vault-ignore-missing-path")
+ .map((w) => w.message)
+ .join("\n"),
+ ).not.toContain("Brain/.snapshots");
+ });
+
+ test("does NOT warn about bare-name entries that have no current match", () => {
+ atomicWriteFileSync(
+ brainConfigPath(tmp),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ - node_modules
+`,
+ );
+ const res = runDoctor(tmp);
+ expect(
+ res.warnings.find((w) => w.code === "vault-ignore-missing-path"),
+ ).toBeUndefined();
+ });
+
+ test("does NOT warn when the vault block is absent (defaults source)", () => {
+ atomicWriteFileSync(
+ brainConfigPath(tmp),
+ `schema_version: 1\n`,
+ );
+ const res = runDoctor(tmp);
+ expect(
+ res.warnings.find((w) => w.code === "vault-ignore-missing-path"),
+ ).toBeUndefined();
+ });
+});
diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.ts
index 0b713314..14233f3e 100644
--- a/tests/core/brain.inline-scan.test.ts
+++ b/tests/core/brain.inline-scan.test.ts
@@ -223,4 +223,60 @@ describe("scanInline", () => {
expect(result.created).toBe(0);
expect(result.malformed).toBe(1);
});
+
+ test("v0.10.9: skips files under .obsidian via shared vault.ignore_paths", async () => {
+ // The bootstrap writes DEFAULT_BRAIN_CONFIG_YAML which declares
+ // `.obsidian` in `vault.ignore_paths`.
+ mkdirSync(join(tmp, ".obsidian", "plugins", "foo"), { recursive: true });
+ writeFileSync(
+ join(tmp, ".obsidian", "plugins", "foo", "note.md"),
+ `@osb feedback negative topic=obsidian-leak principle="should not be captured"\n`,
+ "utf8",
+ );
+ writeMd(
+ "Daily/keep.md",
+ `@osb feedback negative topic=visible principle=p\n`,
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.created).toBe(1);
+ const inbox = readdirSync(brainDirs(tmp).inbox);
+ expect(inbox.some((f) => f.includes("obsidian-leak"))).toBe(false);
+ expect(inbox.some((f) => f.includes("visible"))).toBe(true);
+ });
+
+ test("v0.10.9: hardcoded Brain skip survives an empty vault.ignore_paths declaration", async () => {
+ // Operator explicitly empties the policy. Brain/ MUST still be
+ // skipped because scan-inline cannot self-reference the derived
+ // layer regardless of operator choice.
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `schema_version: 1\nvault:\n ignore_paths:\n`,
+ );
+ writeFileSync(
+ join(brainDirs(tmp).brain, "stray.md"),
+ `@osb feedback positive topic=brain-self principle=x\n`,
+ "utf8",
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.found).toBe(0);
+ });
+
+ test("v0.10.9: vault.ignore_paths additions are respected", async () => {
+ atomicWriteFileSync(
+ join(brainDirs(tmp).brain, "_brain.yaml"),
+ `schema_version: 1\nvault:\n ignore_paths:\n - Drafts\n`,
+ );
+ writeMd(
+ "Drafts/x.md",
+ `@osb feedback negative topic=drafted principle=p\n`,
+ );
+ writeMd(
+ "Daily/d.md",
+ `@osb feedback negative topic=visible principle=p\n`,
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ expect(result.created).toBe(1);
+ const inbox = readdirSync(brainDirs(tmp).inbox);
+ expect(inbox.some((f) => f.includes("drafted"))).toBe(false);
+ });
});
diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.ts
index 1b701ed5..5e656995 100644
--- a/tests/core/brain.policy.test.ts
+++ b/tests/core/brain.policy.test.ts
@@ -333,6 +333,148 @@ describe("validateBrainConfig β€” warnings (forward-compat)", () => {
});
});
+describe("validateBrainConfig β€” vault block (v0.10.9)", () => {
+ test("absent vault block leaves config.vault undefined", () => {
+ const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");
+ expect(cfg.vault).toBeUndefined();
+ });
+
+ test("vault block present without ignore_paths leaves vault undefined", () => {
+ // Walker behaviour is identical to "absent block" (fall back to
+ // defaults) β€” see design Β§4 table row 2.
+ const cfg = validateBrainConfig(
+ { schema_version: 1, vault: {} },
+ "<test>",
+ );
+ expect(cfg.vault).toBeUndefined();
+ });
+
+ test("vault.ignore_paths populated β†’ preserved verbatim", () => {
+ const cfg = validateBrainConfig(
+ {
+ schema_version: 1,
+ vault: { ignore_paths: [".git", "node_modules", "Brain/.snapshots"] },
+ },
+ "<test>",
+ );
+ expect(cfg.vault?.ignore_paths).toEqual([
+ ".git",
+ "node_modules",
+ "Brain/.snapshots",
+ ]);
+ });
+
+ test("vault.ignore_paths empty array honoured as explicit empty", () => {
+ const cfg = validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: [] } },
+ "<test>",
+ );
+ expect(cfg.vault?.ignore_paths).toEqual([]);
+ });
+
+ test("vault.ignore_paths inline [] YAML form is honoured as explicit empty", () => {
+ const cfg = validateBrainConfig(
+ parseBrainYaml(`schema_version: 1\nvault:\n ignore_paths: []\n`),
+ "<test>",
+ );
+ expect(cfg.vault?.ignore_paths).toEqual([]);
+ });
+
+ test("vault block not a map β†’ BrainConfigError naming the field", () => {
+ expect(() =>
+ validateBrainConfig({ schema_version: 1, vault: 5 }, "<test>"),
+ ).toThrow(/vault/);
+ });
+
+ test("vault.ignore_paths not an array β†’ BrainConfigError", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: "not-a-list" } },
+ "<test>",
+ ),
+ ).toThrow(/vault\.ignore_paths/);
+ });
+
+ test("non-string entry β†’ BrainConfigError naming the index", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: [".git", 42] } },
+ "<test>",
+ ),
+ ).toThrow(/vault\.ignore_paths\[1\]/);
+ });
+
+ test("empty-string entry rejected", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: [" "] } },
+ "<test>",
+ ),
+ ).toThrow(/non-empty/);
+ });
+
+ test("entry with newline is rejected", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: ["bad\nentry"] } },
+ "<test>",
+ ),
+ ).toThrow(/vault\.ignore_paths\[0\]/);
+ });
+
+ test("unknown sub-key under vault produces a warning, not an error", () => {
+ const result = validateBrainConfigDetailed(
+ {
+ schema_version: 1,
+ vault: { ignore_paths: [".git"], unknown_extra: true },
+ },
+ "<test>",
+ );
+ expect(result.config.vault?.ignore_paths).toEqual([".git"]);
+ expect(
+ result.warnings.some((w) => w.message.includes("unknown_extra")),
+ ).toBe(true);
+ });
+
+ test("DEFAULT_BRAIN_CONFIG_YAML parses with the vault block populated", () => {
+ const parsed = parseBrainYaml(DEFAULT_BRAIN_CONFIG_YAML);
+ const cfg = validateBrainConfig(parsed, "<default>");
+ expect(cfg.vault?.ignore_paths).toContain(".obsidian");
+ expect(cfg.vault?.ignore_paths).toContain("Brain/.snapshots");
+ });
+
+ test("trailing slash on a path entry is normalised, not silently dropped", () => {
+ const cfg = validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: ["Brain/.snapshots/"] } },
+ "<test>",
+ );
+ expect(cfg.vault?.ignore_paths).toEqual(["Brain/.snapshots"]);
+ });
+
+ test("leading ./ on a path entry is normalised", () => {
+ const cfg = validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: ["./Brain/.snapshots"] } },
+ "<test>",
+ );
+ expect(cfg.vault?.ignore_paths).toEqual(["Brain/.snapshots"]);
+ });
+
+ test("entry that normalises to empty (e.g. './' / '/') is rejected", () => {
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: ["./"] } },
+ "<test>",
+ ),
+ ).toThrow(/vault\.ignore_paths\[0\].*empty/);
+ expect(() =>
+ validateBrainConfig(
+ { schema_version: 1, vault: { ignore_paths: ["///"] } },
+ "<test>",
+ ),
+ ).toThrow(/vault\.ignore_paths\[0\].*empty/);
+ });
+});
+
describe("loadBrainConfig β€” filesystem integration", () => {
test("loads a well-formed config from <vault>/Brain/_brain.yaml", () => {
writeBrainYaml(tmp, DEFAULT_BRAIN_CONFIG_YAML);
@@ -384,6 +526,16 @@ describe("parseBrainYaml", () => {
expect(parsed["none"]).toBeNull();
});
+ test("parses inline scalar arrays", () => {
+ const parsed = parseBrainYaml(
+ `schema_version: 1\nvault:\n ignore_paths: [Drafts, "AI Wiki/cache"]\n`,
+ );
+ expect((parsed["vault"] as { ignore_paths: unknown }).ignore_paths).toEqual([
+ "Drafts",
+ "AI Wiki/cache",
+ ]);
+ });
+
test("parses one-level indented blocks", () => {
const parsed = parseBrainYaml(
`schema_version: 1\ndream:\n candidate_threshold: 3\n unconfirmed_window_days: 14\n`,
diff --git a/tests/core/search/config.test.ts b/tests/core/search/config.test.ts
index afe25b66..3b3a9616 100644
--- a/tests/core/search/config.test.ts
+++ b/tests/core/search/config.test.ts
@@ -1,5 +1,5 @@
import { test, expect, beforeEach, afterEach } from "bun:test";
-import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { resolveSearchConfig } from "../../../src/core/search/index.ts";
@@ -57,8 +57,53 @@ test("defaults are returned when config and env are empty", () => {
expect(cfg.semantic.enabled).toBe(false);
expect(cfg.semantic.provider).toBe("openai-compat");
expect(cfg.semantic.apiKey).toBeNull();
- expect(cfg.ignorePaths).toContain(".git");
- expect(cfg.ignorePaths).toContain(".open-second-brain");
+ const ignoreRaws = cfg.ignoreRules.map((r) => r.raw);
+ expect(ignoreRaws).toContain(".git");
+ expect(ignoreRaws).toContain(".open-second-brain");
+ // v0.10.9: the default set folds in `.obsidian` (whole dir) and
+ // `Brain/.snapshots`. These come from the shared `vault-scope`
+ // defaults, not the legacy `search_ignore_paths` plumbing.
+ expect(ignoreRaws).toContain(".obsidian");
+ expect(ignoreRaws).toContain("Brain/.snapshots");
+});
+
+test("OPEN_SECOND_BRAIN_SEARCH_IGNORE has no effect (removed in v0.10.9)", () => {
+ writeFileSync(configPath, `vault: "${tmp}"\n`);
+ process.env["OPEN_SECOND_BRAIN_SEARCH_IGNORE"] = "from-env-1,from-env-2";
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ const raws = cfg.ignoreRules.map((r) => r.raw);
+ expect(raws).not.toContain("from-env-1");
+ expect(raws).not.toContain("from-env-2");
+});
+
+test("search_ignore_paths in config.yaml has no effect (removed in v0.10.9)", () => {
+ writeFileSync(
+ configPath,
+ `vault: "${tmp}"\nsearch_ignore_paths: "from-config-1,from-config-2"\n`,
+ );
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ const raws = cfg.ignoreRules.map((r) => r.raw);
+ expect(raws).not.toContain("from-config-1");
+ expect(raws).not.toContain("from-config-2");
+});
+
+test("vault.ignore_paths in Brain/_brain.yaml is the source of truth", () => {
+ mkdirSync(join(tmp, "Brain"), { recursive: true });
+ writeFileSync(
+ join(tmp, "Brain", "_brain.yaml"),
+ `schema_version: 1
+vault:
+ ignore_paths:
+ - my-cache
+ - Drafts
+`,
+ );
+ writeFileSync(configPath, `vault: "${tmp}"\n`);
+ const cfg = resolveSearchConfig({ vault: tmp, configPath });
+ expect(cfg.ignoreRules.map((r) => r.raw)).toEqual(["my-cache", "Drafts"]);
+ // The path-style entry survives classification.
+ const draftsRule = cfg.ignoreRules.find((r) => r.raw === "Drafts");
+ expect(draftsRule?.kind).toBe("name");
});
test("env overrides config which overrides defaults", () => {
@@ -94,6 +139,20 @@ test("overrides win over both env and config", () => {
expect(cfg.semanticWeight).toBe(0.1);
});
+test("overrides can repair invalid configured weight sums", () => {
+ writeFileSync(
+ configPath,
+ `vault: "${tmp}"\nsearch_keyword_weight: "0.7"\nsearch_semantic_weight: "0.5"\n`,
+ );
+ const cfg = resolveSearchConfig({
+ vault: tmp,
+ configPath,
+ overrides: { keywordWeight: 0.5, semanticWeight: 0.5 },
+ });
+ expect(cfg.keywordWeight).toBe(0.5);
+ expect(cfg.semanticWeight).toBe(0.5);
+});
+
test("invalid numeric value throws INVALID_INPUT", () => {
writeFileSync(configPath, `vault: "${tmp}"\nsearch_chunk_size: "not-a-number"\n`);
let err: SearchError | null = null;
diff --git a/tests/core/search/store.test.ts b/tests/core/search/store.test.ts
index cb730cbb..d1f1b1d3 100644
--- a/tests/core/search/store.test.ts
+++ b/tests/core/search/store.test.ts
@@ -25,7 +25,7 @@ function makeConfig(overrides?: Partial<ResolvedSearchConfig>): ResolvedSearchCo
return Object.freeze({
vault: tmp,
dbPath,
- ignorePaths: Object.freeze([".git"]),
+ ignoreRules: Object.freeze([{ raw: ".git", kind: "name" as const }]),
chunkSize: 800,
chunkOverlap: 100,
keywordWeight: 0.6,
diff --git a/tests/core/search/store.vec.test.ts b/tests/core/search/store.vec.test.ts
index 39acf85e..7ca4e18a 100644
--- a/tests/core/search/store.vec.test.ts
+++ b/tests/core/search/store.vec.test.ts
@@ -24,7 +24,7 @@ function semanticConfig(model: string, dim: number, overrides?: Partial<Resolved
return Object.freeze({
vault: tmp,
dbPath,
- ignorePaths: Object.freeze([".git"]),
+ ignoreRules: Object.freeze([{ raw: ".git", kind: "name" as const }]),
chunkSize: 800,
chunkOverlap: 100,
keywordWeight: 0.6,
diff --git a/tests/core/search/walker.test.ts b/tests/core/search/walker.test.ts
index 2814565f..345b5cfe 100644
--- a/tests/core/search/walker.test.ts
+++ b/tests/core/search/walker.test.ts
@@ -50,12 +50,24 @@ test("skips ignored bare directory names anywhere in tree", () => {
expect(collect(cfg)).toEqual(["keep.md"]);
});
-test("skips ignored relative-path directories", () => {
+test("skips ignored relative-path directories but keeps sibling subtrees", () => {
+ writeMd(vault, "keep.md", "x");
+ // `Brain/.snapshots` is a path-style rule in the default set.
+ writeMd(vault, "Brain/.snapshots/2026-05-19.md", "x");
+ // `Brain/active.md` is a sibling under the same parent β€” must NOT
+ // be eaten by the snapshots rule.
+ writeMd(vault, "Brain/active.md", "x");
+ const cfg = makeConfig({ vault, dbPath: join(vault, "x.sqlite") });
+ expect(collect(cfg)).toEqual(["Brain/active.md", "keep.md"]);
+});
+
+test("v0.10.9 default: full .obsidian directory is excluded", () => {
writeMd(vault, "keep.md", "x");
writeMd(vault, ".obsidian/cache/cached.md", "x");
- writeMd(vault, ".obsidian/other.md", "x"); // kept (cache is the specific subdir)
+ writeMd(vault, ".obsidian/plugins/foo/note.md", "x");
+ writeMd(vault, ".obsidian/app.md", "x");
const cfg = makeConfig({ vault, dbPath: join(vault, "x.sqlite") });
- expect(collect(cfg)).toEqual([".obsidian/other.md", "keep.md"]);
+ expect(collect(cfg)).toEqual(["keep.md"]);
});
test("ignores symlinks pointing outside vault", () => {
diff --git a/tests/core/vault-scope.test.ts b/tests/core/vault-scope.test.ts
new file mode 100644
index 00000000..841f4213
--- /dev/null
+++ b/tests/core/vault-scope.test.ts
@@ -0,0 +1,312 @@
+/**
+ * Unit tests for `src/core/vault-scope/index.ts`.
+ *
+ * Anchored in docs/plans/2026-05-19-vault-scope-design.md Β§5.
+ */
+
+import { afterEach, beforeEach, test, expect } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ classifyVaultIgnoreRule,
+ DEFAULT_VAULT_IGNORE_PATHS,
+ inspectPath,
+ matchIgnore,
+ resolveVaultScope,
+ walkVaultScope,
+ type VaultIgnoreRule,
+} from "../../src/core/vault-scope/index.ts";
+
+test("DEFAULT_VAULT_IGNORE_PATHS contains the v0.10.9 baseline", () => {
+ expect([...DEFAULT_VAULT_IGNORE_PATHS]).toEqual([
+ ".git",
+ "node_modules",
+ ".open-second-brain",
+ ".obsidian",
+ ".trash",
+ ".stversions",
+ "Brain/.snapshots",
+ ]);
+});
+
+test("DEFAULT_VAULT_IGNORE_PATHS is frozen", () => {
+ expect(Object.isFrozen(DEFAULT_VAULT_IGNORE_PATHS)).toBe(true);
+});
+
+test("VaultIgnoreRule kind union covers the two semantic cases", () => {
+ const a: VaultIgnoreRule = { raw: ".git", kind: "name" };
+ const b: VaultIgnoreRule = { raw: "Brain/.snapshots", kind: "path" };
+ expect(a.kind).toBe("name");
+ expect(b.kind).toBe("path");
+});
+
+// ----- classifyVaultIgnoreRule normalisation -------------------------------
+
+test("classifyVaultIgnoreRule strips trailing slash on path rules", () => {
+ const r = classifyVaultIgnoreRule("Brain/.snapshots/");
+ expect(r.raw).toBe("Brain/.snapshots");
+ expect(r.kind).toBe("path");
+});
+
+test("classifyVaultIgnoreRule strips leading ./ on path rules", () => {
+ const r = classifyVaultIgnoreRule("./Brain/.snapshots");
+ expect(r.raw).toBe("Brain/.snapshots");
+ expect(r.kind).toBe("path");
+});
+
+test("classifyVaultIgnoreRule collapses double slashes", () => {
+ const r = classifyVaultIgnoreRule("Brain//.snapshots");
+ expect(r.raw).toBe("Brain/.snapshots");
+ expect(r.kind).toBe("path");
+});
+
+test("classifyVaultIgnoreRule preserves bare names verbatim", () => {
+ const r = classifyVaultIgnoreRule(".git");
+ expect(r.raw).toBe(".git");
+ expect(r.kind).toBe("name");
+});
+
+// ----- matchIgnore ----------------------------------------------------------
+
+const rules: ReadonlyArray<VaultIgnoreRule> = [
+ { raw: ".git", kind: "name" },
+ { raw: "node_modules", kind: "name" },
+ { raw: "Brain/.snapshots", kind: "path" },
+];
+
+test("matchIgnore returns excluded=false on a plain path", () => {
+ const r = matchIgnore("Notes/idea.md", rules);
+ expect(r.excluded).toBe(false);
+ expect(r.rule).toBeNull();
+ expect(r.matchedAt).toBeNull();
+});
+
+test("matchIgnore catches a bare-name rule at the root", () => {
+ const r = matchIgnore(".git/HEAD", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".git");
+ expect(r.matchedAt).toBe(".git");
+});
+
+test("matchIgnore catches a bare-name rule at any depth", () => {
+ const r = matchIgnore("deep/nested/.git/HEAD", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".git");
+ expect(r.matchedAt).toBe("deep/nested/.git");
+});
+
+test("matchIgnore catches a path rule by exact prefix", () => {
+ const r = matchIgnore("Brain/.snapshots/2026-05-19.tar.zst", rules);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe("Brain/.snapshots");
+ expect(r.matchedAt).toBe("Brain/.snapshots");
+});
+
+test("matchIgnore does NOT match a path rule on a prefix collision", () => {
+ // "Brain/.snapshots-old" must NOT be eaten by "Brain/.snapshots".
+ const r = matchIgnore("Brain/.snapshots-old/x.md", rules);
+ expect(r.excluded).toBe(false);
+});
+
+test("matchIgnore on an empty relPath is excluded=false (vault root)", () => {
+ const r = matchIgnore("", rules);
+ expect(r.excluded).toBe(false);
+});
+
+test("matchIgnore with empty rules excludes nothing", () => {
+ const r = matchIgnore(".git/HEAD", []);
+ expect(r.excluded).toBe(false);
+});
+
+// ----- resolveVaultScope ---------------------------------------------------
+
+let scopeVault: string;
+
+beforeEach(() => {
+ scopeVault = mkdtempSync(join(tmpdir(), "osb-scope-"));
+ mkdirSync(join(scopeVault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(scopeVault, { recursive: true, force: true });
+});
+
+function writeBrain(body: string): void {
+ writeFileSync(join(scopeVault, "Brain", "_brain.yaml"), body, "utf8");
+}
+
+test("resolveVaultScope: defaults when _brain.yaml is absent", () => {
+ const scope = resolveVaultScope(scopeVault);
+ expect(scope.source).toBe("defaults");
+ expect(scope.ignorePaths).toContain(".obsidian");
+ expect(scope.ignorePaths).toContain("Brain/.snapshots");
+ expect(scope.rules.find((r) => r.raw === "Brain/.snapshots")?.kind).toBe("path");
+ expect(scope.rules.find((r) => r.raw === ".obsidian")?.kind).toBe("name");
+});
+
+test("resolveVaultScope: reads vault.ignore_paths when present", () => {
+ writeBrain(`schema_version: 1
+vault:
+ ignore_paths:
+ - .git
+ - my-cache
+`);
+ const scope = resolveVaultScope(scopeVault);
+ expect(scope.source).toBe("_brain.yaml");
+ expect(scope.ignorePaths).toEqual([".git", "my-cache"]);
+ expect(scope.rules.map((r) => r.kind)).toEqual(["name", "name"]);
+});
+
+test("resolveVaultScope: explicit empty list excludes nothing", () => {
+ writeBrain(`schema_version: 1
+vault:
+ ignore_paths:
+`);
+ const scope = resolveVaultScope(scopeVault);
+ expect(scope.source).toBe("_brain.yaml");
+ expect(scope.ignorePaths).toEqual([]);
+ expect(scope.rules).toEqual([]);
+});
+
+test("resolveVaultScope: absent vault block falls back to defaults", () => {
+ writeBrain(`schema_version: 1\n`);
+ const scope = resolveVaultScope(scopeVault);
+ expect(scope.source).toBe("defaults");
+});
+
+test("resolveVaultScope: vault block without ignore_paths falls back to defaults", () => {
+ writeBrain(`schema_version: 1
+vault:
+ some_future_key: 42
+`);
+ const scope = resolveVaultScope(scopeVault);
+ expect(scope.source).toBe("defaults");
+});
+
+test("resolveVaultScope: invalid _brain.yaml fails closed instead of defaulting", () => {
+ writeBrain("schema_version: 1\n nested_without_parent: 1\n");
+ expect(() => resolveVaultScope(scopeVault)).toThrow(/unexpected indentation/);
+});
+
+test("resolveVaultScope: returns an immutable object", () => {
+ const scope = resolveVaultScope(scopeVault);
+ expect(Object.isFrozen(scope)).toBe(true);
+ expect(Object.isFrozen(scope.rules)).toBe(true);
+ expect(Object.isFrozen(scope.ignorePaths)).toBe(true);
+});
+
+// ----- walkVaultScope ------------------------------------------------------
+
+test("walkVaultScope: counts included files+dirs and reports excluded subtree once", () => {
+ mkdirSync(join(scopeVault, "Notes"), { recursive: true });
+ writeFileSync(join(scopeVault, "Notes", "a.md"), "x");
+ writeFileSync(join(scopeVault, "Notes", "b.md"), "x");
+ mkdirSync(join(scopeVault, ".obsidian", "plugins", "foo"), { recursive: true });
+ writeFileSync(join(scopeVault, ".obsidian", "app.json"), "{}");
+ writeFileSync(join(scopeVault, ".obsidian", "plugins", "foo", "note.md"), "x");
+
+ const scope = resolveVaultScope(scopeVault);
+ const walk = walkVaultScope(scopeVault, scope);
+
+ expect(walk.includedFiles).toBeGreaterThanOrEqual(2);
+ const obsidianHit = walk.excludedDirs.find((d) => d.relPath === ".obsidian");
+ expect(obsidianHit).toBeTruthy();
+ expect(obsidianHit?.rule.raw).toBe(".obsidian");
+ // Subtree descendants must NOT be reported separately.
+ expect(
+ walk.excludedDirs.filter((d) => d.relPath.startsWith(".obsidian/")),
+ ).toHaveLength(0);
+});
+
+test("walkVaultScope: file-level rule excludes a single file but not the parent", () => {
+ writeFileSync(join(scopeVault, "note.md"), "x");
+ writeFileSync(join(scopeVault, "secret.md"), "x");
+ const scope = {
+ ignorePaths: ["secret.md"],
+ rules: [{ raw: "secret.md", kind: "path" as const }],
+ source: "_brain.yaml" as const,
+ };
+ const walk = walkVaultScope(scopeVault, scope);
+ expect(walk.excludedFiles.map((f) => f.relPath)).toContain("secret.md");
+ expect(walk.includedFiles).toBe(1);
+});
+
+test("walkVaultScope: empty vault yields zero counts", () => {
+ rmSync(join(scopeVault, "Brain"), { recursive: true, force: true });
+ const scope = resolveVaultScope(scopeVault);
+ const walk = walkVaultScope(scopeVault, scope);
+ expect(walk.includedFiles).toBe(0);
+ expect(walk.excludedDirs).toEqual([]);
+});
+
+test("walkVaultScope: symlinked file escaping vault is not counted (symmetric with search walker)", () => {
+ const outside = mkdtempSync(join(tmpdir(), "osb-scope-outside-"));
+ try {
+ writeFileSync(join(outside, "leak.md"), "secret");
+ writeFileSync(join(scopeVault, "real.md"), "x");
+ symlinkSync(join(outside, "leak.md"), join(scopeVault, "evil.md"));
+ const scope = resolveVaultScope(scopeVault);
+ const walk = walkVaultScope(scopeVault, scope);
+ // `real.md` plus the Brain config file should count; `evil.md`
+ // resolves outside the vault and must be dropped before being
+ // counted.
+ expect(walk.includedFiles).toBeLessThanOrEqual(2);
+ expect(walk.excludedFiles.map((f) => f.relPath)).not.toContain("evil.md");
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+});
+
+// ----- inspectPath ---------------------------------------------------------
+
+test("inspectPath: included path that exists on disk", () => {
+ writeFileSync(join(scopeVault, "idea.md"), "x");
+ const scope = resolveVaultScope(scopeVault);
+ const r = inspectPath("idea.md", scope, scopeVault);
+ expect(r.excluded).toBe(false);
+ expect(r.rule).toBeNull();
+ expect(r.matchedAt).toBeNull();
+ expect(r.relPath).toBe("idea.md");
+ expect(r.source).toBe("defaults");
+ expect(r.existsOnDisk).toBe(true);
+});
+
+test("inspectPath: included path that does NOT exist on disk reports existsOnDisk=false", () => {
+ const scope = resolveVaultScope(scopeVault);
+ const r = inspectPath("Notes/hypothetical.md", scope, scopeVault);
+ expect(r.excluded).toBe(false);
+ expect(r.existsOnDisk).toBe(false);
+});
+
+test("inspectPath: excluded by name rule reports the matched directory", () => {
+ const scope = resolveVaultScope(scopeVault);
+ const r = inspectPath(".obsidian/plugins/foo/note.md", scope, scopeVault);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe(".obsidian");
+ expect(r.rule?.kind).toBe("name");
+ expect(r.matchedAt).toBe(".obsidian");
+ // The file does not exist on disk; the rule decision is still meaningful.
+ expect(r.existsOnDisk).toBe(false);
+});
+
+test("inspectPath: excluded by path rule on exact match", () => {
+ const scope = resolveVaultScope(scopeVault);
+ const r = inspectPath("Brain/.snapshots/2026-05-19.tar.zst", scope, scopeVault);
+ expect(r.excluded).toBe(true);
+ expect(r.rule?.raw).toBe("Brain/.snapshots");
+ expect(r.rule?.kind).toBe("path");
+});
+
+test("inspectPath: strips leading ./ and surrounding slashes", () => {
+ const scope = resolveVaultScope(scopeVault);
+ const r = inspectPath("/./Notes/idea.md/", scope, scopeVault);
+ expect(r.relPath).toBe("Notes/idea.md");
+ expect(r.excluded).toBe(false);
+});
+
+test("inspectPath: throws on .. traversal", () => {
+ const scope = resolveVaultScope(scopeVault);
+ expect(() => inspectPath("../outside", scope, scopeVault)).toThrow(/traverse/);
+});
diff --git a/tests/e2e/brain-capture-and-fields.test.ts b/tests/e2e/brain-capture-and-fields.test.ts
index e606f2eb..da77481c 100644
--- a/tests/e2e/brain-capture-and-fields.test.ts
+++ b/tests/e2e/brain-capture-and-fields.test.ts
@@ -71,6 +71,16 @@ describe("capture + migration end-to-end", () => {
"utf8",
);
+ // Step 2b (v0.10.9): an Obsidian-plugin note with a stray marker
+ // must NOT be captured β€” the shared vault.ignore_paths excludes
+ // the whole `.obsidian` tree.
+ mkdirSync(join(vault, ".obsidian", "plugins", "x"), { recursive: true });
+ writeFileSync(
+ join(vault, ".obsidian", "plugins", "x", "note.md"),
+ "@osb feedback negative topic=e2e-obsidian-leak principle=p\n",
+ "utf8",
+ );
+
// Step 3: scan-inline captures + rewrites
r = await runCli(["brain", "scan-inline", "--vault", vault], {
env: { OPEN_SECOND_BRAIN_CONFIG: config },
@@ -82,6 +92,10 @@ describe("capture + migration end-to-end", () => {
const inbox = join(vault, "Brain", "inbox");
const inlineSigs = readdirSync(inbox).filter((n) => n.startsWith("sig-"));
expect(inlineSigs.length).toBe(1);
+ // The .obsidian marker MUST NOT have produced a signal.
+ expect(
+ inlineSigs.some((n) => n.includes("e2e-obsidian-leak")),
+ ).toBe(false);
// Step 4: import-session adds an independent signal from the
// claude fixture (topic=mocking, distinct from e2e-inline).
diff --git a/tests/helpers/search-fixtures.ts b/tests/helpers/search-fixtures.ts
index c364846e..3b77c096 100644
--- a/tests/helpers/search-fixtures.ts
+++ b/tests/helpers/search-fixtures.ts
@@ -6,7 +6,15 @@ import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from "node
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
-import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "../../src/core/search/types.ts";
+import {
+ classifyVaultIgnoreRule,
+ DEFAULT_VAULT_IGNORE_PATHS,
+ type VaultIgnoreRule,
+} from "../../src/core/vault-scope/defaults.ts";
+import type {
+ ResolvedSearchConfig,
+ ResolvedEmbeddingConfig,
+} from "../../src/core/search/types.ts";
export function createTempVault(prefix: string): {
vault: string;
@@ -39,6 +47,11 @@ export function writeSymlink(vault: string, relLink: string, absTarget: string):
export function makeConfig(opts: {
vault: string;
dbPath: string;
+ /**
+ * Optional terse shortcut: when provided, each string is classified
+ * into a `VaultIgnoreRule` (kind `path` if it contains `/`, else
+ * `name`). When omitted, the shared default rule set is used.
+ */
ignorePaths?: ReadonlyArray<string>;
semantic?: Partial<ResolvedEmbeddingConfig>;
}): ResolvedSearchConfig {
@@ -53,20 +66,18 @@ export function makeConfig(opts: {
concurrency: 4,
batchSize: 32,
});
- const semantic: ResolvedEmbeddingConfig = Object.freeze({ ...baseSemantic, ...(opts.semantic ?? {}) });
+ const semantic: ResolvedEmbeddingConfig = Object.freeze({
+ ...baseSemantic,
+ ...(opts.semantic ?? {}),
+ });
+ const paths = opts.ignorePaths ?? DEFAULT_VAULT_IGNORE_PATHS;
+ const ignoreRules: ReadonlyArray<VaultIgnoreRule> = Object.freeze(
+ paths.map(classifyVaultIgnoreRule),
+ );
return Object.freeze({
vault: opts.vault,
dbPath: opts.dbPath,
- ignorePaths: Object.freeze([
- ...(opts.ignorePaths ?? [
- ".git",
- "node_modules",
- ".open-second-brain",
- ".obsidian/cache",
- ".trash",
- ".stversions",
- ]),
- ]),
+ ignoreRules,
chunkSize: 800,
chunkOverlap: 100,
keywordWeight: 0.6,
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index bb262ab9..b0aa6ab8 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -219,6 +219,74 @@ describe("tool calls", () => {
expect(s.brain.sanity.signals_awaiting_dream).toBe(0);
});
+ test("second_brain_status includes a `vault` block (v0.10.9)", async () => {
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ mkdirSync(join(vault, ".obsidian"));
+ writeFileSync(join(vault, ".obsidian", "app.json"), "{}");
+ writeFileSync(join(vault, "note.md"), "# x\n");
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "vault_path: /tmp/vault\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_status"))! as any;
+ const s = r.result.structuredContent;
+ expect(s.vault).toBeDefined();
+ expect(s.vault.ignore_source).toBeDefined();
+ expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);
+ expect(Array.isArray(s.vault.rules)).toBe(true);
+ expect(s.vault.rules.some(
+ (r: { raw: string }) => r.raw === ".obsidian",
+ )).toBe(true);
+ expect(typeof s.vault.included.files).toBe("number");
+ expect(typeof s.vault.included.dirs).toBe("number");
+ expect(typeof s.vault.excluded.dirs).toBe("number");
+ expect(typeof s.vault.excluded.files).toBe("number");
+ expect(s.vault.excluded.dirs).toBeGreaterThanOrEqual(1);
+ });
+
+ test("second_brain_status omits `vault` block when vault directory missing", async () => {
+ const vault = join(tmp, "missing-vault");
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "vault_path: /tmp/vault\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_status"))! as any;
+ const s = r.result.structuredContent;
+ expect(s.vault_exists).toBe(false);
+ expect(s.vault).toBeUndefined();
+ });
+
+ test("second_brain_status degrades vault block to {error} when _brain.yaml is malformed (v0.10.9)", async () => {
+ // Fail-closed resolver (design Β§5) makes walkers and the CLI
+ // vault verb refuse to proceed on a malformed config. The MCP
+ // status tool is a read-only diagnostic β€” it should still
+ // expose the other blocks (brain / search / config) so the
+ // operator can see what is wrong without losing the rest.
+ const vault = join(tmp, "vault");
+ mkdirSync(vault);
+ mkdirSync(join(vault, "Brain"));
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ // entry contains a backslash β†’ rejected by validator.
+ `schema_version: 1\nvault:\n ignore_paths:\n - "bad\\\\entry"\n`,
+ );
+ const config = join(tmp, "config.yaml");
+ writeFileSync(config, "vault_path: /tmp/vault\n");
+ const server = new MCPServer({ vault, configPath: config });
+ await initialize(server);
+ const r = (await callTool(server, "second_brain_status"))! as any;
+ const s = r.result.structuredContent;
+ // Other blocks must remain present.
+ expect(s.config_path).toBeDefined();
+ expect(s.vault_exists).toBe(true);
+ expect(s.brain).toBeDefined();
+ // Vault block degraded with the error message.
+ expect(s.vault).toBeDefined();
+ expect(typeof s.vault.error).toBe("string");
+ expect(s.vault.error).toContain("vault.ignore_paths");
+ });
+
test("second_brain_query filters and limits", async () => {
const vault = createSandboxVault(tmp);
const server = new MCPServer({ vault });