Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat(brain): add feedback default scope and vault write containment (#104)
Sol Aitkenf8b4abf8d423
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex c1026814..2a6a38d9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.13.0",+ "version": "1.14.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 915cf669..ef900974 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.13.0",+ "version": "1.14.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 287a5639..4683374c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,51 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.14.0] - 2026-06-18++### Added++- **Configurable default scope for feedback signals+ (`feedback.default_scope`).** A vault-local default applied to+ `brain_feedback` / `o2b brain feedback` writes that pass no explicit+ `scope`, so agent-recorded signals can land in a consistent category+ (for example `coding`) instead of staying uncategorized. The rule is a+ single precedence at the signal write boundary: an explicit per-call+ scope always wins; otherwise the configured default is used; otherwise+ the `scope` field is omitted exactly as before. With no+ `feedback.default_scope` configured and no explicit scope, signal+ output is byte-identical to prior behaviour.+ - **Config block.** Optional `feedback:` block in `Brain/_brain.yaml`+ with a `default_scope` string, validated through the normal Brain+ config policy against the same constraints as a signal `scope` field+ (non-empty after trim, single-line, at most 128 characters). Invalid+ values are rejected by config validation and surfaced by+ `o2b brain doctor` rather than silently ignored.+ - **Parity across surfaces.** The effective scope is computed once and+ reused for the inbox signal, its shared-namespace mirror, and any+ force-confirmed preference, so a preference never diverges in scope+ from the signal that produced it. Distinct from the `owner_scoped_facts`+ and vault guardrail settings, which govern fact visibility rather than+ feedback categorization.++### Security++- **Write-containment backstop at the write-session commit chokepoint.**+ The single point where a write-session lands an agent-supplied artifact+ now re-resolves its target through `ensureInsideVault` before any+ directory creation, read, or write. The earlier target check is purely+ lexical and runs at session-open time, so it cannot see a symlinked+ ancestor (for example a `Brain/<symlink>/note.md` whose ancestor links+ outside the vault) and is decoupled from the write by the persisted+ session record. The backstop fails closed: a target that resolves+ outside the configured vault root is rejected and nothing is written.+ Audit confirmed every other caller-derived vault path (slugs, ids,+ device shards, artifacts) already funnels through the guarded+ `paths.ts` constructors or `ensureInsideVault`, and `validateSlug`+ continues to admit `@` and `+` so email-style and plus-addressed+ identifiers remain valid file basenames while dot-traversal tokens stay+ rejected. Regression tests pin both invariants.+## [1.13.0] - 2026-06-16### Added@@ -5613,7 +5658,9 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.-[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.12.0...HEAD+[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.14.0...HEAD+[1.14.0]: https://github.com/itechmeat/open-second-brain/compare/v1.13.0...v1.14.0+[1.13.0]: https://github.com/itechmeat/open-second-brain/compare/v1.12.0...v1.13.0[1.12.0]: https://github.com/itechmeat/open-second-brain/compare/v1.11.0...v1.12.0[1.11.0]: https://github.com/itechmeat/open-second-brain/compare/v1.10.0...v1.11.0[1.10.0]: https://github.com/itechmeat/open-second-brain/compare/v1.9.0...v1.10.0diff --git a/README.md b/README.mdindex f30385d8..d6f9ce61 100644--- a/README.md+++ b/README.md@@ -91,8 +91,9 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra- **A brain you can carry, hand off, and write to in process.** `o2b brain bank-export` serialises a whole vault - preferences, the page graph, a per-page interchange contract (path, kind, advisory confidence/provenance, citations, aliases, freshness), and the sources dashboard - into one deterministic, schema-versioned bundle for backup, migration, or downstream-tool ingest; `bank-import` reconstructs the page graph and reports the rest as carried-not-restored rather than faking a full restore. A `brain_create_note` MCP tool writes an actual vault note (path + frontmatter + content) atomically, refusing traversal, the Brain root, and clobbering. And `createBrain(vault)` is a thin in-process SDK over the same core functions - bank/graph export-import, preference export, source ingest plus list/get/delete, and note creation - so scripts and agents manage brain content without the CLI or MCP layer.- **Recall you can tune, and a working set that prunes itself.** `o2b search --profile fast|balanced|thorough` (and the `brain_search` `profile` field) pick a recall preset over the same bounded knobs the self-tuner uses - an explicit profile wins over a learned grid point, and no profile leaves ranking bit-for-bit unchanged. `o2b brain file-context <path>` surfaces prior vault work that mentions a file before you read it; `o2b brain co-occurrence` proposes relationship edges between entities repeatedly co-referenced from the same notes, scored structurally over the wikilink graph with no natural-language word list in any language; and `o2b brain continuity rank` weights working-memory records by a usage-driven decay derived only from real recall telemetry, so stale decisions fade while actively-recalled ones stay prominent. All deterministic, all read-only or suggestion-only.- **Session knowledge you can query, trace, and walk.** `o2b brain session-summary` (and `brain_session_summary`) stores a session-scoped digest over four categories - request, decisions, learnings, next_steps - that the agent extracts and the kernel only stores, so you can ask what a session decided as one unit. `o2b brain idea-lineage <id>` traces how a derived artifact was reached as an observation to synthesis to conclusion graph over the edges already recorded (continuity `sourceRefs`, or a preference's belief-evolution), cycle-guarded and depth-bounded. `o2b brain note-history <path>` splits a note's git history into episodic phases on a deterministic commit-time gap - language-agnostic, no commit-message parsing. The kernel never calls a model; absent inputs report honestly rather than fabricating.-- **Operational readability for code partners and large vaults.** Open Second Brain now exposes a read-only CodeGraph report (`o2b partner codegraph report`, `brain_codegraph_report`) that resolves the in-scope code project, reports the codegraph index state with node and edge counts, and structurally parses Cargo.toml for Rust workspace members. The report is honest about missing CLIs, missing indexes, and non-Rust projects. For large vaults, community materialization can run in fixed-size batches (`o2b brain clusters run --batch-size N`, `brain_clusters` `batch_size`) with per-batch success or isolated failure reporting, while the default run stays byte-identical.+- **Consistent feedback categorization.** A vault-local `feedback.default_scope` in `Brain/_brain.yaml` gives agent-recorded signals a consistent category (for example `coding`) when no explicit scope is provided, with the same precedence across the inbox signal, its shared-namespace mirror, and any force-confirmed preference. The effective scope is computed once at the signal write boundary and byte-identical output is preserved when the setting is absent or no explicit scope is given.+- **Path-safe vault writes.** The write-session commit chokepoint now re-resolves every target through `ensureInsideVault` before any directory creation, read, or write, catching symlinked ancestors that point outside the vault root. The backstop fails closed: a target resolving outside the configured vault is rejected and nothing is written. All other caller-derived vault paths already funnel through guarded constructors; regression tests pin both invariants.That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.diff --git a/docs/brainstorm/default-scope-feedback/cli-output/claude.md b/docs/brainstorm/default-scope-feedback/cli-output/claude.mdnew file mode 100644index 00000000..af8798a9--- /dev/null+++ b/docs/brainstorm/default-scope-feedback/cli-output/claude.md@@ -0,0 +1,29 @@+## Variant 1: Core write-boundary fallback with policy-validated default+Approach: Add an optional `feedback.default_scope` field to `BrainConfig`, validated and normalized in `policy.ts` alongside the other resolved config blocks (invalid values surfaced through config validation and `brain_doctor`). The precedence logic lives in exactly one place: `sanitiseSignalInput`/`writeSignal` in `signal.ts` gains the rule "use explicit scope if present and non-empty, else fall back to the configured default, else omit." Both CLI and MCP keep loading config and pass the resolved default into the core write, so the decision rule itself cannot diverge between surfaces.+Trade-offs:+- Structural CLI/MCP parity: precedence and sanitization are defined once at the chokepoint every signal write already funnels through, so the two surfaces cannot drift.+- Byte-identical preservation is trivial and self-evident: the fallback fires only when explicit scope is absent and a default is configured, so absent-default plus absent-explicit leaves the existing omit path untouched.+- Touches a widely-used core signature (`WriteSignalInput`/`writeSignal`), so the change surface reaches core types and every caller, requiring care that the additive field stays optional and defaulted.+Complexity: medium+Risk: medium++## Variant 2: Shared call-site resolver helper+Approach: Leave `signal.ts` completely untouched; it continues to write `scope` only when present. Add one small pure helper, `resolveSignalScope(explicit, configuredDefault)`, that both `feedback-tools.ts` and `feedback.ts` call to compute the effective scope before building `signalInput`, replacing the current `...(scope ? { scope } : {})` spread. The `feedback.default_scope` config field is read at each surface and handed to the helper.+Trade-offs:+- Smallest, most contained change: core write path and its tests are entirely unaffected, and the helper is trivially unit-testable in isolation for all four precedence cases.+- Parity depends on discipline rather than structure: two call sites must each adopt the helper and pass config, and a future third writer could forget it, so consistency is a convention not a guarantee.+- Validation/normalization placement is ambiguous: without a central resolver the helper must either re-sanitize the configured default at each call or trust raw config, risking duplicated logic or an unvalidated default reaching the write.+Complexity: small+Risk: low++## Variant 3: Resolved feedback-policy object in policy.ts+Approach: Extend the existing resolved-defaults pattern in `policy.ts` so `loadBrainConfig` produces a normalized, validated `feedback` policy object (for example a resolved `defaultScope`) exactly as it already does for other feature blocks. Call sites consume only the resolved object, never raw `_brain.yaml` values, and invalid defaults are caught once at load time and reported through validation and `brain_doctor`.+Trade-offs:+- Single source of truth for the resolved default with validation and doctor surfacing centralized, matching how the codebase already treats other config blocks.+- Both surfaces stay thin and read a pre-validated value, but the actual precedence decision still happens at each call site unless paired with a core or helper application point, so it solves validation cleanly without fully solving parity on its own.+- Most plumbing of the three: introduces a resolved feedback block, its type, validation, and defaulting, which is more scaffolding than a strictly additive optional field needs for one scalar.+Complexity: medium+Risk: low++## Recommended: Variant 1+Rationale: It places the default exactly where the task identifies its natural home (signal construction in `signal.ts`, with explicit per-call scope overriding), and it is the only option that makes CLI/MCP parity structural rather than conventional, because the precedence and sanitization rule lives at the single write chokepoint both surfaces already share. The byte-identical guarantee falls out of the design directly: the fallback is reachable only when an explicit scope is absent and a default is configured. It also satisfies the misleading-fallback constraint by validating and normalizing the configured default in `policy.ts` with `brain_doctor` surfacing, borrowing the same resolved-config discipline that makes Variant 3 attractive while avoiding that variant's extra scaffolding for a single scalar. The medium risk is confined to keeping one new field optional and defaulted on the core write signature, which is the codebase's normal additive approach.diff --git a/docs/brainstorm/default-scope-feedback/cli-output/prompt.md b/docs/brainstorm/default-scope-feedback/cli-output/prompt.mdnew file mode 100644index 00000000..4ee1889d--- /dev/null+++ b/docs/brainstorm/default-scope-feedback/cli-output/prompt.md@@ -0,0 +1,136 @@+# Consultant prompt: configurable default_scope for feedback signals++You are consulting on Open Second Brain, a TypeScript/Bun project that provides an Obsidian-native memory layer for AI agents through CLI and MCP tools.++Return exactly 3 distinct architectural variants for the locked scope below. For each variant use this exact structure:++## Variant N: <name>+Approach: <2-3 sentences>+Trade-offs:+- <bullet>+- <bullet>+- <bullet>+Complexity: small|medium|large+Risk: low|medium|high++Then return exactly one recommendation section:++## Recommended: Variant N+Rationale: <why>++Variants plus recommendation only. No code. No extra sections outside those sections.++## Locked scope++Scope name: configurable default_scope for feedback signals+Slug: default-scope-feedback+Branch: feat/default-scope-feedback+Patch target: next patch release after v1.12.0+In-scope task ids: t_d8a58683++The change should be one small additive backend config feature with limited change surface. It should not take over other unrelated work on the branch.++## In-scope task body++id: t_d8a58683+title: [upstream:mnemosyne] feat(hermes): configurable default_scope for remember()/feedback calls+status: triage priority: 0++Source: https://github.com/AxDSan/mnemosyne/releases/tag/v3.9.0+Repo: AxDSan/mnemosyne+Released: v3.9.0 (2026-06-17T23:18:44Z)++What: Upstream adds a configurable `default_scope` so `remember()` calls that do not pass an explicit scope inherit a preset value instead of recording scope-less. In Open Second Brain terms, this is a default for the optional `scope` field on `brain_feedback`/remember signals.++Why useful for Open Second Brain: Open Second Brain signals recorded without a `scope` currently stay uncategorized (`scope` undefined/null), which weakens later application-scope matching during the dream/preference-promotion pass. A vault-configurable default scope would let an operator ensure agent-recorded signals land in a sensible category, for example `coding`, by default, improving preference scoping consistency without forcing every call to set it.++Status in Open Second Brain: verdict `not_in_osb_useful`. Codegraph hints: `scope` is an optional free-form slug on feedback signals - `src/core/brain/signal.ts:70` (type), `:197-198` (metadata write only when present), `:266-281` and `:318-327` (parse/serialize, omitted when absent), `:488-489` (`brain/scope/TBD` tag only when set). No `default_scope`/`defaultScope` symbol exists. Absent scope consistently falls back to null/empty string in consumers. Guardrail/config defaults in `policy.ts` cover vault-scope ignore paths and owner-scoped-facts, not a remember() default scope.++Notes: Small, additive config feature. Natural home: a vault config default consumed where signals are constructed in `signal.ts`, with the explicit per-call `scope` argument overriding it. Distinct from Open Second Brain's existing `owner_scoped_facts` / vault-scope guardrails, which govern fact visibility, not feedback categorization.++## Project context++- Project: Open Second Brain+- Language/runtime: TypeScript ESM on Bun, package `open-second-brain`, current package version 1.13.0.+- Main surfaces: CLI `o2b` and MCP tools for Brain memory writes and reads.+- Data model: Brain data is plain Markdown in an Obsidian vault. Feedback signals are immutable `Brain/inbox/sig-*.md` files with YAML frontmatter.+- Config file: vault-local `Brain/_brain.yaml`, parsed by `src/core/brain/yaml-parse.ts` and validated in `src/core/brain/policy.ts`. The root type is `BrainConfig` in `src/core/brain/types.ts`.+- Current config blocks include `vault`, `active`, `discipline_report`, `guardrails`, `link_graph`, `temporal`, `notes`, `schema`, sessions and other feature blocks. Unknown top-level keys are tolerated as forward compatibility warnings, not hard errors.+- Current `_brain.yaml` parser supports nested one-level blocks, scalars, `[]`, and simple inline scalar arrays.++## Recent git log++20ea7ef feat: per-handoff LLM generation tracing and prompt-prefix stability metric (#102)+9c1d48f feat: CodeGraph and MCP operational readability (v1.12.0) (#101)+c2c3ff4 feat: Session Knowledge Synthesis Suite - structured session summaries, idea-lineage, episodic note history (v1.11.0) (#100)+56dd3dd fix(hermes): bridge EOF - byte streams, stderr drain, retry loop (#92)+35b824e feat: Recall & Working-Memory Quality Suite - selectable profiles, usage decay, co-occurrence, file-context (v1.10.0) (#99)+929d54c feat: Brain Portability & Interop Suite - bank export/import, page contract, brain_create_note, in-process SDK (v1.9.0) (#98)+7cdbfc0 feat: Indexer Durability & Resilience Suite - cooperative abort, graceful watch shutdown, resumable reindex (v1.8.0) (#97)+8b679fe feat: Knowledge Provenance Suite - ingest, research, NER, derived facts, owner-scope, standing-query (v1.7.0) (#96)+6e59a42 feat: Vault Integrity & Trust Suite - untrusted-source containment, NFC identity, watch-sync, O(1) graph, agent-scope (v1.6.0) (#95)+70d95c6 chore(release): bump version to 1.5.0 (#94)+e4df212 feat: Search & Recall Quality Suite - explainable scores, trust, threshold, reinforce, eval (#93)+2e74afe feat: native Grok Build CLI integration - bundled plugin, hooks, session import (v1.4.0) (#91)+3e7e233 fix(hermes): serialize handle_tool_call result to a string (v1.3.1) (#90)+2abc90b fix(changelog): the opencode integration ships in v1.3.0, not a phantom 1.4.0 (#89)+96f1ff4 feat: native opencode integration - config-correct install, bundled plugin, session capture (#88)+0340560 feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene, anticipatory cache (v1.3.0) (#87)+8972f13 refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)+9886d9a refactor: make search and classification language-agnostic (#84)+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)++## Related implementation files and observed behavior++- `src/core/brain/signal.ts`+ - `WriteSignalInput.scope?: string` is optional.+ - `writeSignal` writes `scope` to frontmatter only if the sanitized scope exists and is non-empty.+ - `sanitiseSignalInput` sanitizes a provided scope with max length 128 and single-line rules.+ - `parseSignal` returns `scope: undefined` when frontmatter has no non-empty scope.+- `src/mcp/brain/feedback-tools.ts`+ - `brain_feedback` validates input, extracts optional `scope`, then builds `signalInput` with `...(scope ? { scope } : {})`.+ - Force-confirmed preference creation also passes scope only when explicitly provided.+ - The live MCP path resolves agent identity via config when absent.+- `src/cli/brain/verbs/feedback.ts`+ - `o2b brain feedback` accepts optional `--scope`.+ - It builds `signalInput` with `...(flags["scope"] ? { scope: String(flags["scope"]) } : {})`.+ - Force-confirmed preference creation also passes explicit scope only.+- `src/core/brain/policy.ts`+ - `loadBrainConfig` / validation already provide resolved default blocks for other features.+ - Existing guardrail defaults are separate from feedback categorization and should not be reused for this concern.+- `src/core/brain/types.ts`+ - `BrainConfig` is the root `_brain.yaml` type. Additive optional fields are the normal approach.+ - `BrainVaultConfig` currently covers `ignore_paths` only. `BrainGuardrailConfig.owner_scoped_facts` governs fact visibility/recall, not signal categorization.+- Tests likely relevant:+ - feedback CLI tests around `o2b brain feedback` and signal writing.+ - MCP feedback tool tests for `brain_feedback` payload behavior.+ - config loader tests for `_brain.yaml` parsing/validation.++## Documentation and release conventions++README documents Open Second Brain as an Obsidian-native memory layer with deterministic CLI/MCP tools, no hidden state, no daemon, no cloud copy. Documentation index includes `docs/how-it-works.md`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/updating.md`, `docs/hermes-cron.md`, `docs/cross-project-pointer.md`, and `docs/architecture.md`.++Top changelog entry is 1.13.0; patch target for this selected release is the next patch after v1.12.0 per workflow instruction. Do not decide release mechanics here, but implementation should be patch-sized and additive.++Existing brainstorm docs use `docs/brainstorm/<slug>/design.md`, `plan.md`, `variants.md`, and `cli-output/claude.md`.++## Active Brain preferences and coding constraints++- Public Open Second Brain docs/comments/changelog should use the full product name, not the abbreviation.+- No long em dashes in generated prose.+- No AI authorship markers in public artifacts.+- Search/classification behavior must stay language-agnostic. Do not use natural-language keyword lists.+- Avoid TypeScript cast crutches. Build correct typed objects with conditional spreads, narrowing, or dedicated builders.+- Version bumps, if any in later phases, must go through `bun run scripts/sync-version.ts`; do not hand-edit mirrored version files.+- This phase should not implement code. Produce architectural variants only.++## Constraints for your recommendation++- Explicit per-call `scope` must override any configured default.+- With no configured default and no explicit scope, current behavior should remain byte-identical: signal has no `scope` frontmatter and no scope tag.+- The feature must be vault-configurable and should avoid global hidden state.+- Keep it small, additive, deterministic, and testable.+- Avoid misleading fallbacks: invalid configured default should be surfaced as config validation/doctor feedback rather than silently ignored if the design chooses validation.+- No hardcoded natural-language categories.+- Consider CLI and MCP parity for feedback signal writes.diff --git a/docs/brainstorm/default-scope-feedback/design.md b/docs/brainstorm/default-scope-feedback/design.mdnew file mode 100644index 00000000..194b07a6--- /dev/null+++ b/docs/brainstorm/default-scope-feedback/design.md@@ -0,0 +1,83 @@+# Configurable default_scope for feedback signals design++## Problem++Open Second Brain feedback signals can carry an optional `scope` frontmatter field. When an agent or operator records feedback through `brain_feedback` or `o2b brain feedback` without passing `scope`, the resulting signal is intentionally scope-less. That preserves existing behavior, but it means agent-recorded signals can remain uncategorized even when a vault operator wants a consistent default category such as `coding`.++The release needs a small, vault-local default for feedback signal scope. The default must never override an explicit per-call scope, must keep existing output byte-identical when unset, and must not reuse unrelated owner-scope or guardrail settings that control visibility rather than categorization.++## Scope++- Add a vault-configurable default scope for feedback signal writes.+- Apply the default to both MCP `brain_feedback` and CLI `o2b brain feedback` writes.+- Preserve explicit per-call `scope` precedence.+- Preserve current behavior when no default is configured.+- Validate and sanitize the configured value through the same config and signal-field rules used by the rest of the Brain layer.+- Cover the default with focused tests for config parsing, CLI writes, MCP writes, and explicit-scope override.++## Out of scope++- Changing dream promotion logic, recall ranking, or application-scope matching.+- Introducing hardcoded scope category names.+- Migrating existing scope-less signal files.+- Changing `owner_scoped_facts`, vault ignore paths, guardrails, or fact visibility semantics.+- Changing morning-brief, activity-timeline, or generic time-helper behavior; this patch is only feedback signal defaulting.+- Adding a new release workflow, version bump, or deployment in this phase.++## Chosen approach++Use Variant 1: Core write-boundary fallback with policy-validated default.++Add an optional feedback config block in `Brain/_brain.yaml`, shaped as `feedback.default_scope`. The config loader validates that a provided default is a non-empty scalar compatible with the existing signal scope constraints. Signal construction then applies one precedence rule: explicit non-empty per-call scope wins; otherwise the configured default is used; otherwise the `scope` field is omitted exactly as it is today.++I agree with the consultant recommendation. The task is specifically about defaulting feedback signal construction, so placing the fallback at the signal write boundary gives the strongest CLI/MCP parity and avoids relying on each surface to remember a convention. The extra care is that `writeSignal` should remain deterministic and free of hidden global config reads: callers pass a validated default through an additive option or field, while `signal.ts` owns only the final precedence and sanitization rule.++## Design decisions++1. Use a dedicated `feedback.default_scope` config key.+ - The setting belongs to feedback signal categorization, not guardrails or owner-scoped recall.+ - `feedback` is optional; absent block means no default.+ - Use snake_case in `_brain.yaml`, matching existing config style.++2. Keep explicit scope precedence.+ - `brain_feedback({ scope: "docs" })` writes `docs` even when `feedback.default_scope: coding` exists.+ - `o2b brain feedback --scope docs` behaves the same way.+ - Empty or whitespace explicit values should not be treated as valid overrides.++3. Keep unset behavior byte-identical.+ - With no `feedback.default_scope` and no explicit scope, `writeSignal` omits scope frontmatter and scope tags exactly as it does now.+ - Existing parse behavior remains unchanged: files without `scope` parse as `undefined`.++4. Centralize the effective-scope rule at the write boundary.+ - Avoid two separate call-site-only implementations in CLI and MCP.+ - Add an optional `defaultScope` field to the existing signal write options, and have `signal.ts` compute the final scope from explicit input plus that validated default.+ - Do not make `signal.ts` load `_brain.yaml` itself; the writer should stay deterministic from its inputs.++5. Validate through Brain config policy.+ - Add types for `BrainFeedbackConfig` and include it optionally in `BrainConfig`.+ - Extend `validateBrainConfig` / related policy helpers to parse and validate `feedback.default_scope`.+ - Reuse signal `scope` sanitization constraints exactly: non-empty after trim, single-line, and at most the existing 128-character scope cap, so config and write behavior cannot diverge.+ - Surface invalid values through normal config validation and doctor checks rather than silently ignoring them.++6. Preserve language-agnostic behavior.+ - The system accepts an operator-provided slug-like string.+ - It must not infer categories from natural-language topic or principle text.++## File changes++Expected implementation touchpoints:++- `src/core/brain/types.ts` for `BrainFeedbackConfig` and optional `BrainConfig.feedback`.+- `src/core/brain/policy.ts` for config validation/default handling of `feedback.default_scope`.+- `src/core/brain/signal.ts` for the effective-scope write-boundary rule, implemented with an optional `defaultScope` write option rather than a hidden config read.+- `src/mcp/brain/feedback-tools.ts` to pass the validated config default into the signal write path for `brain_feedback` and force-confirmed preference creation if the effective scope is used there too.+- `src/cli/brain/verbs/feedback.ts` to pass the validated config default into the signal write path for `o2b brain feedback`.+- Focused tests under the existing CLI, MCP, core signal, and config test locations.+- `docs/cli-reference.md`, `docs/mcp.md`, and `CHANGELOG.md` for the user-visible config behavior in the implementation phase.++## Risks++- The writer API change can ripple to many tests if done as a required parameter. Mitigation: make the new option additive and optional.+- CLI and MCP can drift if effective scope is resolved only at call sites. Mitigation: keep final precedence in one core helper or write-boundary option.+- Invalid config could be silently ignored if validation is too loose. Mitigation: validate the field in policy and add a doctor/config test for invalid values.+- Force-confirmed preference creation could get a different scope than its source signal. Mitigation: compute one effective scope and reuse it for both signal and preference writes.diff --git a/docs/brainstorm/default-scope-feedback/plan.md b/docs/brainstorm/default-scope-feedback/plan.mdnew file mode 100644index 00000000..64b7a4e2--- /dev/null+++ b/docs/brainstorm/default-scope-feedback/plan.md@@ -0,0 +1,39 @@+# Configurable default_scope for feedback signals implementation plan++Branch: `feat/default-scope-feedback`+Design: `docs/brainstorm/default-scope-feedback/design.md`++## t_d8a58683 - [upstream:mnemosyne] feat(hermes): configurable default_scope for remember()/feedback calls++### Files++- `src/core/brain/types.ts`+- `src/core/brain/policy.ts`+- `src/core/brain/signal.ts`+- `src/mcp/brain/feedback-tools.ts`+- `src/cli/brain/verbs/feedback.ts`+- Existing focused tests for Brain config validation, signal writing, CLI feedback, and MCP feedback, with new tests added where coverage is missing+- `docs/cli-reference.md`+- `docs/mcp.md`+- `CHANGELOG.md`++### Acceptance++A focused test suite passes that proves:++- With no `feedback.default_scope` and no explicit `scope`, signal output remains unchanged and omits `scope` frontmatter.+- With `feedback.default_scope: coding` and no explicit `scope`, both `brain_feedback` and `o2b brain feedback` write signals with `scope: coding` and the normal scope tag behavior.+- With `feedback.default_scope: coding` and explicit `scope: docs`, the explicit scope wins for both CLI and MCP paths.+- Invalid configured defaults are rejected or surfaced through normal config validation/doctor behavior rather than silently ignored.+- Force-confirmed preference creation uses the same effective scope as the signal when a default applies.++Suggested verification command for the worker:++```bash+bun test <focused config test> <focused signal test> <focused CLI feedback test> <focused MCP feedback test>+bun run typecheck+```++### Depends on++No sibling card needs to land first. This is the only in-scope implementation card for the patch release and should be driven on `feat/default-scope-feedback` under TDD.diff --git a/docs/brainstorm/default-scope-feedback/variants.md b/docs/brainstorm/default-scope-feedback/variants.mdnew file mode 100644index 00000000..bddf9cf5--- /dev/null+++ b/docs/brainstorm/default-scope-feedback/variants.md@@ -0,0 +1,39 @@+# Configurable default_scope for feedback signals variants++## Consultant variants++## Variant 1: Core write-boundary fallback with policy-validated default+Approach: Add an optional `feedback.default_scope` field to `BrainConfig`, validated and normalized in `policy.ts` alongside the other resolved config blocks (invalid values surfaced through config validation and `brain_doctor`). The precedence logic lives in exactly one place: `sanitiseSignalInput`/`writeSignal` in `signal.ts` gains the rule "use explicit scope if present and non-empty, else fall back to the configured default, else omit." Both CLI and MCP keep loading config and pass the resolved default into the core write, so the decision rule itself cannot diverge between surfaces.+Trade-offs:+- Structural CLI/MCP parity: precedence and sanitization are defined once at the chokepoint every signal write already funnels through, so the two surfaces cannot drift.+- Byte-identical preservation is trivial and self-evident: the fallback fires only when explicit scope is absent and a default is configured, so absent-default plus absent-explicit leaves the existing omit path untouched.+- Touches a widely-used core signature (`WriteSignalInput`/`writeSignal`), so the change surface reaches core types and every caller, requiring care that the additive field stays optional and defaulted.+Complexity: medium+Risk: medium++## Variant 2: Shared call-site resolver helper+Approach: Leave `signal.ts` completely untouched; it continues to write `scope` only when present. Add one small pure helper, `resolveSignalScope(explicit, configuredDefault)`, that both `feedback-tools.ts` and `feedback.ts` call to compute the effective scope before building `signalInput`, replacing the current `...(scope ? { scope } : {})` spread. The `feedback.default_scope` config field is read at each surface and handed to the helper.+Trade-offs:+- Smallest, most contained change: core write path and its tests are entirely unaffected, and the helper is trivially unit-testable in isolation for all four precedence cases.+- Parity depends on discipline rather than structure: two call sites must each adopt the helper and pass config, and a future third writer could forget it, so consistency is a convention not a guarantee.+- Validation/normalization placement is ambiguous: without a central resolver the helper must either re-sanitize the configured default at each call or trust raw config, risking duplicated logic or an unvalidated default reaching the write.+Complexity: small+Risk: low++## Variant 3: Resolved feedback-policy object in policy.ts+Approach: Extend the existing resolved-defaults pattern in `policy.ts` so `loadBrainConfig` produces a normalized, validated `feedback` policy object (for example a resolved `defaultScope`) exactly as it already does for other feature blocks. Call sites consume only the resolved object, never raw `_brain.yaml` values, and invalid defaults are caught once at load time and reported through validation and `brain_doctor`.+Trade-offs:+- Single source of truth for the resolved default with validation and doctor surfacing centralized, matching how the codebase already treats other config blocks.+- Both surfaces stay thin and read a pre-validated value, but the actual precedence decision still happens at each call site unless paired with a core or helper application point, so it solves validation cleanly without fully solving parity on its own.+- Most plumbing of the three: introduces a resolved feedback block, its type, validation, and defaulting, which is more scaffolding than a strictly additive optional field needs for one scalar.+Complexity: medium+Risk: low++## Recommended: Variant 1+Rationale: It places the default exactly where the task identifies its natural home (signal construction in `signal.ts`, with explicit per-call scope overriding), and it is the only option that makes CLI/MCP parity structural rather than conventional, because the precedence and sanitization rule lives at the single write chokepoint both surfaces already share. The byte-identical guarantee falls out of the design directly: the fallback is reachable only when an explicit scope is absent and a default is configured. It also satisfies the misleading-fallback constraint by validating and normalizing the configured default in `policy.ts` with `brain_doctor` surfacing, borrowing the same resolved-config discipline that makes Variant 3 attractive while avoiding that variant's extra scaffolding for a single scalar. The medium risk is confined to keeping one new field optional and defaulted on the core write signature, which is the codebase's normal additive approach.++## Final decision++Chosen variant: Variant 1, Core write-boundary fallback with policy-validated default.++I agree with the consultant recommendation. A write-boundary fallback gives the strongest parity guarantee for this small config feature because both CLI and MCP already converge on the signal write path. To preserve deterministic core behavior, the implementation should pass the validated default into the writer through an additive option or helper rather than making the writer read vault config itself.diff --git a/docs/brainstorm/path-safe-vault-writes/cli-output/claude-retry.md b/docs/brainstorm/path-safe-vault-writes/cli-output/claude-retry.mdnew file mode 100644index 00000000..39bc7b10--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/cli-output/claude-retry.md@@ -0,0 +1,26 @@+## Variant 1+Approach: Add an optional containment-root parameter to `writeFrontmatter` and `writeFrontmatterAtomic` so the writers themselves call `ensureInsideVault` before `mkdirSync`/write, making containment a property of the single write primitive rather than each caller. Every existing caller keeps working unchanged (the parameter is optional and defaults to today's behavior).+Trade-offs:+- Closes the gap at the lowest, most-shared layer, so any current or future caller that passes the root is contained by construction (strong DRY, defense-in-depth at the chokepoint).+- An optional, default-off guard is a misleading fallback: the protection only exists for callers that remember to pass the root, so the signature changes without actually moving the invariant unless every call site is also updated β which inflates scope toward the "route everything" large case.+Complexity: medium+Risk: medium++## Variant 2+Approach: Introduce explicit `safeIdentifier`/`safePathSegment` helpers that whitelist structural character classes, reject `.`/`..`, and admit `@`/`+` (matching the upstream `sender_id` rule), then apply them at the boundaries where partly-caller-supplied identifiers become path segments and are not already run through `validateSlug`. Keep the whitelist language-agnostic (character classes, no wordlists).+Trade-offs:+- Sanitizes the untrusted input at the boundary where it enters, complementing the existing `validateSlug` and giving email/plus-addressed ids a first-class path (directly mirrors the upstream defense).+- High overlap with the existing `validateSlug`/`slugify` and `paths.ts` constructors risks two competing sanitizers; without a careful audit of which inputs are genuinely unguarded, this adds surface area and can violate DRY rather than hardening.+Complexity: medium+Risk: medium++## Variant 3+Approach: Treat the card as an audit-and-prove task: enumerate every direct vault writer (the `writeFrontmatter`/`writeFileSync`/`appendFileSync`/`mkdirSync` sites from the grep), confirm each already funnels through a `paths.ts` constructor or `ensureInsideVault`, and route the few that do not through the existing guard. Lock the invariant with TDD regression tests (traversal slugs, sibling-prefix, symlink-ancestor, absolute paths) at the chokepoints, changing no shared signatures.+Trade-offs:+- Smallest, reversible diff that fits patch scope: it hardens only genuinely-unguarded writers with the helper that already exists and turns the "agent writes only inside Brain/" invariant into executable, regression-proof tests.+- Does not add the email/plus-addressed identifier whitelist, so the upstream `sender_id`-style sanitization is deferred; if the audit finds writers are already centralized, the visible code delta is mostly tests rather than new mechanism.+Complexity: small+Risk: low++## Recommended: Variant 3+The codebase already has the right primitive (`ensureInsideVault`), the path constructors, and `validateSlug`, so the honest small-patch move is to verify the invariant holds everywhere and pin it with tests, routing only the stragglers through the existing guard rather than reshaping shared writer signatures. This avoids the misleading-fallback and DRY-duplication risks of Variants 1 and 2 while delivering real defense-in-depth value, and it leaves the optional-root writer change and identifier whitelist as cleanly-scoped follow-ups if the audit shows they are actually needed.diff --git a/docs/brainstorm/path-safe-vault-writes/cli-output/claude.md b/docs/brainstorm/path-safe-vault-writes/cli-output/claude.mdnew file mode 100644index 00000000..f0e6454d--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/cli-output/claude.md@@ -0,0 +1 @@+/usr/bin/bash: line 3: /root/.local/bin/claude: Argument list too longdiff --git a/docs/brainstorm/path-safe-vault-writes/cli-output/prompt.md b/docs/brainstorm/path-safe-vault-writes/cli-output/prompt.mdnew file mode 100644index 00000000..0f47e5d6--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/cli-output/prompt.md@@ -0,0 +1,1327 @@+You are a senior backend architecture consultant for Open Second Brain.++Return EXACTLY these sections and nothing else:++## Variant 1+Approach: 2-3 sentences.+Trade-offs:+- bullet+- bullet+Complexity: small|medium|large+Risk: low|medium|high++## Variant 2+Approach: 2-3 sentences.+Trade-offs:+- bullet+- bullet+Complexity: small|medium|large+Risk: low|medium|high++## Variant 3+Approach: 2-3 sentences.+Trade-offs:+- bullet+- bullet+Complexity: small|medium|large+Risk: low|medium|high++## Recommended: Variant N+2-3 sentence rationale.++No code. No sections outside the four sections above.++Context:+- Project: Open Second Brain; TypeScript on Bun; package version currently "version": "1.13.0",.+- Branch: feat/path-safe-vault-writes; release intent: one low-priority small patch-scope task, patch version later, no release in this phase.+- Scope: Path-safe vault writes. In-scope card: t_7b1049bb only.+- Engineering constraints: SOLID, KISS, DRY; no misleading fallbacks; no hardcoding; English-only project artifacts; language-agnostic behavior; no TypeScript cast crutches; TDD for implementation.+- Preserve pre-existing unrelated uncommitted changes: src/core/brain/morning-brief.ts and src/core/brain/time.ts.+- Current finding: code already has ensureInsideVault, src/core/brain/paths.ts path constructors, createNote containment, validateSlug for many Brain ids, but direct writers still exist and writeFrontmatter/writeFrontmatterAtomic do not themselves accept a containment root.++Task body:+```text+id: t_7b1049bb+title: [upstream:EverOS] Path-safe identifier sanitization and write-containment guard for vault writes+status: triage priority: 1 assignee: -+----- body -----+**Source**: https://github.com/EverMind-AI/EverOS/releases/tag/v1.0.1+**Repo**: EverMind-AI/EverOS (6886β )+**Released**: v1.0.1 (2026-06-16T13:50:05Z)++## What+Two layered path-traversal defenses for an agent-owned Markdown store. First, caller-supplied identifiers that become path segments (the upstream `sender_id`, analogous to any OSB-side identifier that feeds a filename or sub-path) are validated against a character whitelist and reject the `.` and `..` tokens, while still admitting `@` and `+` so email-style and plus-addressed ids pass. Second, the Markdown writer resolves every write target and rejects anything that lands outside the configured memory root before it reads, creates parent dirs, or writes; the API layer maps that backstop to HTTP 400.++## Why useful for OSB+Open Second Brain owns the `Brain/` subtree of an Obsidian vault and writes files whose names derive from slugs, topics, preference ids, and other partly-agent/partly-caller-supplied strings; a missing containment check could let a crafted slug or id escape `Brain/` and clobber user notes or files outside the vault. A resolve-and-contain guard in the single write path, plus identifier sanitization at the boundary, is a cheap defense-in-depth measure that matches Open Second Brain's "agent writes only inside its own directory" invariant.++## Status in OSB+- **Verdict**: unverified+- **Codegraph hints**: unverified β codegraph tool unavailable in this run; no mcp__codegraph__codegraph_* tool was exposed to the orchestrator, so OSB source coverage could not be checked.++## Notes+Verification needed: confirm whether Open Second Brain already centralizes vault writes through a single helper that resolves the target against the `Brain/` root (and `notes.read_paths` boundaries) and rejects `..`/absolute escapes, and whether slug/topic/pref-id generation already strips path separators and dot-tokens. If a single write chokepoint exists, this is likely a small hardening add; if writes are scattered, scope grows to routing them through one guarded function. Tie the containment root to the configured Brain directory rather than a hardcoded path, and keep the identifier whitelist language-agnostic (structural character classes, not natural-language wordlists).+----- last comments -----+[osb-triage-validator] osb-triage-validator @ 2026-06-17T14:00:55Z:+- sanity: clean+- cluster: no cluster+- priority: set to 1: verdict remains unverified because codegraph was unavailable in this run; security hardening si++```++Git status:+```text+## feat/path-safe-vault-writes+ M src/core/brain/morning-brief.ts+ M src/core/brain/time.ts+?? docs/brainstorm/path-safe-vault-writes/++```++Recent git log:+```text+bbc8af8 feat(brain): configurable feedback.default_scope for feedback signals+c841bd5 chore(brainstorm): default-scope-feedback+20ea7ef feat: per-handoff LLM generation tracing and prompt-prefix stability metric (#102)+9c1d48f feat: CodeGraph and MCP operational readability (v1.12.0) (#101)+c2c3ff4 feat: Session Knowledge Synthesis Suite - structured session summaries, idea-lineage, episodic note history (v1.11.0) (#100)+56dd3dd fix(hermes): bridge EOF - byte streams, stderr drain, retry loop (#92)+35b824e feat: Recall & Working-Memory Quality Suite - selectable profiles, usage decay, co-occurrence, file-context (v1.10.0) (#99)+929d54c feat: Brain Portability & Interop Suite - bank export/import, page contract, brain_create_note, in-process SDK (v1.9.0) (#98)+7cdbfc0 feat: Indexer Durability & Resilience Suite - cooperative abort, graceful watch shutdown, resumable reindex (v1.8.0) (#97)+8b679fe feat: Knowledge Provenance Suite - ingest, research, NER, derived facts, owner-scope, standing-query (v1.7.0) (#96)+6e59a42 feat: Vault Integrity & Trust Suite - untrusted-source containment, NFC identity, watch-sync, O(1) graph, agent-scope (v1.6.0) (#95)+70d95c6 chore(release): bump version to 1.5.0 (#94)+e4df212 feat: Search & Recall Quality Suite - explainable scores, trust, threshold, reinforce, eval (#93)+2e74afe feat: native Grok Build CLI integration - bundled plugin, hooks, session import (v1.4.0) (#91)+3e7e233 fix(hermes): serialize handle_tool_call result to a string (v1.3.1) (#90)+2abc90b fix(changelog): the opencode integration ships in v1.3.0, not a phantom 1.4.0 (#89)+96f1ff4 feat: native opencode integration - config-correct install, bundled plugin, session capture (#88)+0340560 feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene, anticipatory cache (v1.3.0) (#87)+8972f13 refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)++```++README excerpt:+```markdown+# Open Second Brain++++> An [Obsidian](https://obsidian.md)-native memory layer for your AI agent. Plain Markdown you own, in the same vault you already use.++Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/hermes-agent) and turns your Obsidian vault into a memory layer the agent reads and writes through deterministic CLI / MCP tools. Preferences, signals, evidence, and audit trails are real `.md` files under `Brain/` in the vault you already open in Obsidian every day. You can grep them, version them with git, search them in Obsidian, edit them by hand. No daemon, no vector black box, no hidden state outside the vault.++## Why++- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.+- **You own the data.** Plain Markdown on your filesystem. No service to cancel, no cloud account, no schema migration when a vendor pivots. Syncthing to your other machines if you want.+- **Memory that learns deterministically.** A `dream` pass turns repeat signals into rules and retires the ones nothing applies any more. Counters and atomic file moves - no LLM inside the algorithm, no surprise hallucinations in your memory.+- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, Grok Build, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.++## One vault, many runtimes++```mermaid+flowchart LR+ Vault[("Your vault<br/>Brain/ - plain Markdown")]+ Hermes["**Hermes Agent**<br/>(primary)"]+ CC[Claude Code]+ Codex[OpenAI Codex]+ Others["Cursor Β· Aider Β· OpenClaw<br/>opencode Β· Grok Build Β· kiro Β· Copilot CLI<br/>Gemini CLI Β· Pi Β· any MCP host"]++ Hermes <==> Vault+ CC <--> Vault+ Codex <--> Vault+ Others <--> Vault++ style Hermes fill:#1e3a5f,stroke:#90caf9,color:#fff+ style Vault fill:#5d3a9b,stroke:#ce93d8,color:#fff+```++Hermes Agent owns the schedule (dream cron, daily digests, Telegram delivery). Other runtimes participate as readers and writers of the same Brain through MCP - no per-runtime fork of the memory.++## Quick start with Hermes Agent++**The simplest path - let your agent set it up.** Paste this into Hermes (or whichever AI agent already has shell access on the target machine):++> Install Open Second Brain for me by following the steps at <https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md>. My vault is at `/path/to/your-vault`.++The agent reads the install doc, runs every command, and verifies the result. That's it.++If you prefer running the steps yourself:++```bash+# 1. Install the plugin+hermes plugins install itechmeat/open-second-brain --enable+hermes gateway restart++# 2. Put `o2b` on PATH+~/.hermes/plugins/open-second-brain/scripts/o2b install-cli++# 3. Bootstrap the vault+o2b init --vault /path/to/your-vault --name "My Second Brain"+o2b brain init --vault /path/to/your-vault --primary-agent <agent-name>++# 4. Verify+o2b doctor --vault /path/to/your-vault+```++Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`memory.provider: open-second-brain`) and restart the gateway one more time - the agent now injects `Brain/active.md` into its system prompt, recalls context before each turn, and writes signals through `brain_feedback`, all through the one native provider. Full step-by-step: [`install/hermes.md`](install/hermes.md).++## Other runtimes++| Runtime | Install |+| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |+| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |+| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |+| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |+| opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](install/opencode.md) |+| Grok Build | `o2b install --target grok --apply` (MCP in `config.toml` + native hooks) - [`install/grok.md`](install/grok.md) |+| Cursor Β· Aider Β· kiro Β· Copilot CLI Β· Gemini CLI Β· Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |+| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |++Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.++## What you get++```++Top CHANGELOG entry:+```markdown+# Changelog++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).++## [Unreleased]++### Added++- **Configurable default scope for feedback signals+ (`feedback.default_scope`).** A vault-local default applied to+ `brain_feedback` / `o2b brain feedback` writes that pass no explicit+ `scope`, so agent-recorded signals can land in a consistent category+ (for example `coding`) instead of staying uncategorized. The rule is a+ single precedence at the signal write boundary: an explicit per-call+ scope always wins; otherwise the configured default is used; otherwise+ the `scope` field is omitted exactly as before. With no+ `feedback.default_scope` configured and no explicit scope, signal+ output is byte-identical to prior behaviour.+ - **Config block.** Optional `feedback:` block in `Brain/_brain.yaml`+ with a `default_scope` string, validated through the normal Brain+ config policy against the same constraints as a signal `scope` field+ (non-empty after trim, single-line, at most 128 characters). Invalid+ values are rejected by config validation and surfaced by+ `o2b brain doctor` rather than silently ignored.+ - **Parity across surfaces.** The effective scope is computed once and+ reused for the inbox signal, its shared-namespace mirror, and any+ force-confirmed preference, so a preference never diverges in scope+ from the signal that produced it. Distinct from the `owner_scoped_facts`+ and vault guardrail settings, which govern fact visibility rather than+ feedback categorization.++```++Docs excerpts:+```markdown+### docs/architecture.md+# Architecture++Open Second Brain is organized around a stable core and multiple runtime adapters.++## Layers++```text+Agent runtime+ -> runtime adapter/plugin+ -> skills and commands+ -> CLI/core library+ -> vault files and local config+```++## Core responsibilities++The core (`src/core/`) provides deterministic operations for:++- locating and validating configuration;+- initializing a vault profile (`o2b brain init`);+- recording taste signals, applied-evidence, and narrative milestones into `Brain/log/<YYYY-MM-DD>.md` (plus a JSONL sidecar);+- running the nightly `dream` learning pass (deterministic, no LLM calls);+- exporting redacted config snapshots;+- checking vault health (`o2b brain doctor`);+- querying preferences, signals, and link-graph relationships through the MCP and CLI surface.++The core does not depend on Hermes, Claude Code, Codex, OpenClaw, or Obsidian internals.++## Runtime adapters++### Hermes adapter++The Hermes adapter can be a real runtime plugin:++```text+plugins/hermes/+ plugin.yaml+ __init__.py+```++Possible responsibilities:++- register available hooks;+- check configuration at gateway startup;+- expose readiness diagnostics;+### docs/how-it-works.md+# How Open Second Brain Works++A working guide for engineers and agents to the mechanics of the+observing memory layer. Read this when you want to understand what the+system does, not what to configure.++## Mental model++Open Second Brain accumulates **preferences** and learns from real+usage. Three responsibilities:++- **Capture.** Agents and humans drop taste signals into `Brain/inbox/`.+- **Accretion.** A deterministic `dream` pass turns repeat signals into+ rules.+- **Application.** Agents record whether they applied or violated each+ rule when producing durable artifacts.++The LLM lives outside the system: agents use it to detect signals in+conversation and to apply rules during work. The system uses counters,+thresholds, and atomic file operations β no LLM inside the algorithm,+no surprise, no hallucinated memory.++## Vault layout++The agent owns one top-level directory in the vault: `Brain/`, so the+agent's entire write contract is "I touch only `Brain/`".++```text+<vault>/+βββ Brain/ # agent-writable+β βββ _brain.yaml # schema, thresholds, retention, vault.ignore_paths, notes.read_paths+β βββ _BRAIN.md # operating manual for agents+β βββ active.md # derived: confirmed + quarantine + recently retired+β βββ inbox/ # raw taste signals+β β βββ sig-<date>-<slug>.md+β β βββ processed/ # signals already folded into rules+β βββ preferences/ # active rules+β β βββ pref-<slug>.md # status: unconfirmed | confirmed | quarantine+β βββ retired/ # archived rules+β β βββ ret-<slug>.md # retired_reason: stale-no-evidence | expired-unconfirmed | rebutted | user-rejected | quarantine-violated | superseded-by-context+β βββ log/ # daily event log+β β βββ YYYY-MM-DD.md # append-only, typed events+β βββ .snapshots/ # pre-dream snapshots+β βββ dream-<run-id>.tar.zst+β+### docs/mcp.md+# MCP tool server++The optional Model Context Protocol (MCP) server exposes Open Second Brain's+deterministic operations as tools that Hermes Agent (or any other MCP client)+can route through its tool registry.++The server is **optional**: the `o2b` CLI remains the supported baseline. Nothing+in Open Second Brain depends on the MCP server being running.++## Protocol++- Transport: stdio (JSON-RPC 2.0, newline-delimited).+- Protocol version: `2025-06-18`.+- Capabilities advertised: `tools` and `resources` (see "Resources"+ below). No `prompts` or `sampling`.+- Standard MCP lifecycle: `initialize`, `notifications/initialized`,+ `tools/list`, `tools/call`, optional `ping`.++## Tool Highlights++The full server currently advertises 79 tools; the 18 deprecated predecessor+names were removed in 1.0.0 and now answer a precise INVALID_PARAMS tombstone+(see "Consolidated views and deprecated aliases" below). The table highlights+the operator-facing core,+schema, agent-source, health, and recovery tools; the full surface+also includes Brain writer, review, query, temporal, link-graph, and search+tools. In Claude Code, the full schema can push MCP definitions beyond 10% of+the context window, causing `MCPSearch` tool-search deferral; use the writer+split below for the always-loaded writer subset, or the runtime capability+flags for a narrower per-process full server.++| Tool | Purpose | Required arguments |+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |+| `second_brain_capabilities` | Report the tools available to this MCP process and the withheld-tool reasons after runtime capability filtering. | β |+| `second_brain_status` | Report config and vault status, with secrets redacted. | β |+| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | β |+| `vault_health` | Run vault, config, and plugin manifest health checks. | β |+| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | β |+| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | β |+| `brain_codegraph_report` | Read-only codegraph partner report: in-scope code project, index state (`no_project`/`absent`/`not_indexed`/`indexed` with counts/`error`), and structural `Cargo.toml` workspace members. Never installs, extracts, or mutates; non-Rust projects report `cargo_workspace: null` with a reason. | β |+| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | β |+| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | β |+| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |+| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |+| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis`. | `view` |+```++Active Brain preferences relevant excerpt:+```markdown+- `pref-full-product-name-in-public` (scope: writing, confidence: medium (0.51)) β Π ΠΏΡΠ±Π»ΠΈΡΠ½ΡΡ ΠΌΠ°ΡΠ΅ΡΠΈΠ°Π»Π°Ρ Open Second Brain (release notes, README, Π΄ΠΎΠΊΡΠΌΠ΅Π½ΡΠ°ΡΠΈΡ, code comments, agent skills, ΠΊΠ°ΡΡΠΈΠ½ΠΊΠΈ, CHANGELOG) ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ ΠΏΠΎΠ»Π½ΠΎΠ΅ Π½Π°Π·Π²Π°Π½ΠΈΠ΅ "Open Second Brain", Π½Π΅ Π°Π±Π±ΡΠ΅Π²ΠΈΠ°ΡΡΡΡ "OSB". ΠΠ±Π±ΡΠ΅Π²ΠΈΠ°ΡΡΡΡ "OSB" ΠΎΠΏΠ΅ΡΠ°ΡΠΎΡ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Π² Π»ΠΈΡΠ½ΠΎΠΉ ΠΏΠ΅ΡΠ΅ΠΏΠΈΡΠΊΠ΅ Π΄Π»Ρ ΠΊΡΠ°ΡΠΊΠΎΡΡΠΈ.+- `pref-language-agnostic-search` (scope: coding, confidence: low) β ΠΠΎΠΈΡΠΊ ΠΈ ΠΊΠ»Π°ΡΡΠΈΡΠΈΠΊΠ°ΡΠΈΡ Π² Open Second Brain Π΄ΠΎΠ»ΠΆΠ½Ρ Π±ΡΡΡ ΡΠ·ΡΠΊΠΎ-Π½Π΅Π·Π°Π²ΠΈΡΠΈΠΌΡΠΌΠΈ: Π½Π΅Π»ΡΠ·Ρ Π³Π΅ΠΉΡΠΈΡΡ, ΠΊΠ»Π°ΡΡΠΈΡΠΈΡΠΈΡΠΎΠ²Π°ΡΡ, ΡΠ°Π½ΠΆΠΈΡΠΎΠ²Π°ΡΡ ΠΈΠ»ΠΈ ΠΈΠ·Π²Π»Π΅ΠΊΠ°ΡΡ ΠΏΠΎΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ ΠΏΠΎ Π·Π°Ρ Π°ΡΠ΄ΠΊΠΎΠΆΠ΅Π½Π½ΡΠΌ ΡΠΏΠΈΡΠΊΠ°ΠΌ ΡΠ»ΠΎΠ² Π΅ΡΡΠ΅ΡΡΠ²Π΅Π½Π½ΠΎΠ³ΠΎ ΡΠ·ΡΠΊΠ° (ΠΏΡΠΈΠ²Π΅ΡΡΡΠ²ΠΈΡ, ΡΡΠΎΠΏ-ΡΠ»ΠΎΠ²Π°, ΠΊΠ»ΡΡΠ΅Π²ΡΠ΅ ΡΠ»ΠΎΠ²Π°, ΠΎΡΡΠΈΡΠ°Π½ΠΈΡ) β Π½ΠΈ Π½Π° ΠΎΠ΄Π½ΠΎΠΌ ΡΠ·ΡΠΊΠ΅. ΠΠΌΠ΅ΡΡΠΎ ΡΡΠΎΠ³ΠΎ: ΡΡΡΡΠΊΡΡΡΠ½ΡΠ΅ ΡΠΈΠ³Π½Π°Π»Ρ, ΡΠ²Π½ΡΠ΅ ΠΏΠΎΠ»Ρ frontmatter, ΡΠ°ΡΡΠΎΡΠ° Π² ΠΊΠΎΡΠΏΡΡΠ΅ (document-frequency/IDF), Π»ΠΈΠ±ΠΎ ΠΈΠ·Π²Π»Π΅ΡΠ΅Π½ΠΈΠ΅ Π°Π³Π΅Π½ΡΠΎΠΌ/LLM.+- `pref-no-em-dashes` (scope: writing, confidence: low) β Never use long (em) dashes in generated texts (posts, docs, copy, Π»ΡΠ±ΡΠ΅ ΠΌΠ°ΡΠ΅ΡΠΈΠ°Π»Ρ). Use a regular hyphen, colon, or restructure the sentence instead.+- `pref-no-em-dashes-ever` (scope: writing, confidence: low) β ΠΠΈΠΊΠΎΠ³Π΄Π° Π½Π΅ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ Π΄Π»ΠΈΠ½Π½ΡΠ΅ ΡΠΈΡΠ΅ (em dash) Π² Π»ΡΠ±ΡΡ ΡΠ΅ΠΊΡΡΠ°Ρ : ΡΠ°Ρ, Π΄ΠΎΠΊΡΠΌΠ΅Π½ΡΡ, ΠΊΠΎΠΌΠΌΠ΅Π½ΡΠ°ΡΠΈΠΈ, ΡΠ΅Π»ΠΈΠ·Ρ. ΠΠ°ΠΌΠ΅Π½ΡΡΡ ΠΎΠ±ΡΡΠ½ΡΠΌ Π΄Π΅ΡΠΈΡΠΎΠΌ, Π·Π°ΠΏΡΡΠΎΠΉ ΠΈΠ»ΠΈ ΠΏΠ΅ΡΠ΅ΡΡΡΠΎΠΉΠΊΠΎΠΉ ΡΡΠ°Π·Ρ. ΠΡΠ°Π²ΠΈΠ»ΠΎ Π²Π΅ΡΠ½ΠΎΠ΅, Π·Π°ΡΠ²Π»Π΅Π½ΠΎ ΠΎΠΏΠ΅ΡΠ°ΡΠΎΡΠΎΠΌ ΡΠ²Π½ΠΎ.+- `pref-no-em-dashes-russian-writing` (scope: writing, confidence: low (0.14)) β Forbidden to use em-dashes (long dashes, U+2014 Β«βΒ») in Russian-language content I write for this user β blog posts, documentation, Telegram messages, any user-facing prose. Use regular hyphens with surrounding spaces ( - ) instead. This applies to ALL Russian writing for them, not just one post. The rule is explicit and was reinforced by manual file edits replacing every em-dash with a hyphen.+- `pref-no-typescript-cast-crutches` (scope: coding, confidence: low) β Forbidden to use `as` / `as unknown as <T>` TypeScript casts as a shortcut to silence type errors caused by inadequate object construction. Build the value with the correct type from the start β use object literals with conditional spreads (`...(value !== undefined ? { field: value } : {})`), narrowing functions that return the correct literal type, or split builders. `as` is a code smell indicating the value's construction shape doesn't match the contract; fix the construction, don't cast around it. Exceptions: legitimate framework boundaries (e.g. JSON.parse β typed shape after validation), `as const` for literal narrowing, `satisfies` for shape checks.+- `pref-self-review-after-implementation` (scope: coding, confidence: low (0.21)) β ΠΠΎΡΠ»Π΅ ΡΠ°Π·Ρ implementation (TDD) ΠΎΠ±ΡΠ·Π°ΡΠ΅Π»ΡΠ½Π° ΠΎΡΠ΄Π΅Π»ΡΠ½Π°Ρ ΡΠ°Π·Π° self-review ΡΠ΅ΡΠ΅Π· superpowers-skills: `superpowers:requesting-code-review` (security scan, quality gates, auto-fix) ΠΈ `superpowers:verification-before-completion` (Π·Π°ΠΏΡΡΠΊ verification commands ΠΈ ΠΏΠΎΠ΄ΡΠ²Π΅ΡΠΆΠ΄Π΅Π½ΠΈΠ΅ output ΠΏΠ΅ΡΠ΅Π΄ claim success). Self-review ΠΏΡΠ΅Π΄ΡΠ΅ΡΡΠ²ΡΠ΅Ρ QA ΠΈ ΡΠΎΠ·Π΄Π°Π½ΠΈΡ PR.+- `pref-version-bump-via-sync-script` (scope: git, confidence: low) β Π ΡΡΠΎΠΌ ΡΠ΅ΠΏΠΎΠ·ΠΈΡΠΎΡΠΈΠΈ Π²Π΅ΡΡΠΈΡ Π±Π°ΠΌΠΏΠ°ΡΡ ΡΠΎΠ»ΡΠΊΠΎ ΡΠ΅ΡΠ΅Π· `bun run scripts/sync-version.ts`: Π΅Π΄ΠΈΠ½ΡΡΠ²Π΅Π½Π½ΡΠΉ ΠΈΡΡΠΎΡΠ½ΠΈΠΊ ΠΏΡΠ°Π²Π΄Ρ - ΠΏΠΎΠ»Π΅ version Π² package.json, ΡΠΊΡΠΈΠΏΡ ΠΏΡΠΎΠ±ΡΠ°ΡΡΠ²Π°Π΅Ρ Π΅Ρ Π² ΠΌΠ°Π½ΠΈΡΠ΅ΡΡΡ (plugin.yaml, .claude-plugin/.codex-plugin/openclaw json) ΠΈ pyproject.toml. Π ΡΠΊΠ°ΠΌΠΈ ΠΏΡΠ°Π²ΠΈΡΡ Π²Π΅ΡΡΠΈΡ Π² Π·Π΅ΡΠΊΠ°Π»ΡΠ½ΡΡ ΡΠ°ΠΉΠ»Π°Ρ Π½Π΅Π»ΡΠ·Ρ - CI-Π΄ΠΆΠΎΠ±Π° validate Π³Π΅ΠΉΡΠΈΡ Π½Π° `sync-version.ts --check` ΠΈ ΠΏΠ°Π΄Π°Π΅Ρ Π½Π° Π΄ΡΠ΅ΠΉΡΠ΅ Π΄ΠΎ Π²ΡΠ΅Ρ ΠΎΡΡΠ°Π»ΡΠ½ΡΡ ΠΏΡΠΎΠ²Π΅ΡΠΎΠΊ.+- `pref-full-product-name-in-public` (scope: writing, applied_in_window: 51)+- `pref-no-typescript-cast-crutches` (scope: coding, applied_in_window: 14)+- `pref-no-em-dashes-ever` (scope: writing, applied_in_window: 13)+- `pref-self-review-after-implementation` (scope: coding, applied_in_window: 12)+- `pref-no-em-dashes-russian-writing` (scope: writing, applied_in_window: 9)+- `pref-language-agnostic-search` (scope: coding, applied_in_window: 8)+```++Related file excerpts:+### src/core/path-safety.ts lines 1-144+```ts+/**+ * Path-safety helpers shared by every module that writes into the vault.+ *+ * Centralises the "is this path inside the vault?" check and a reusable+ * vault-relative path renderer. Every module that constructs a path to+ * write must funnel through `ensureInsideVault` so a malicious or buggy+ * input (e.g. a slug with `..`, an absolute symlink target) cannot land a+ * file outside the vault root.+ */++import { existsSync, realpathSync } from "node:fs";+import { dirname, posix, relative, resolve, sep } from "node:path";++/**+ * Throw if `target` is not the vault root or a descendant of it.+ *+ * The check is twofold:+ *+ * 1. `path.resolve` normalises `..` so a slug like `../etc/passwd`+ * cannot pretend to be inside the vault. The platform path+ * separator (`/` or `\`) is used for the prefix check so siblings+ * that share a name prefix (`/v` vs `/v-evil`) are rejected.+ * 2. `fs.realpathSync` follows symlinks for the deepest existing+ * ancestor of the target, then re-runs the prefix check on the+ * resolved real paths. This blocks the case where a directory+ * *inside* the vault is itself a symlink to somewhere outside it+ * (`<vault>/Brain/payments/escape -> /tmp/outside`) β without+ * realpath, the lexical check would happily admit the path.+ *+ * Returns the resolved (lexical) absolute path of `target`. Callers that+ * need the realpath should call `realpathSync` themselves on the result;+ * we deliberately return the lexical form so wikilinks rendered from it+ * keep matching what the user sees in Obsidian.+ */+export function ensureInsideVault(target: string, vault: string): string {+ const resolvedTarget = resolve(target);+ const resolvedVault = resolve(vault);++ if (!isLexicallyInside(resolvedTarget, resolvedVault)) {+ throw new Error(`path escapes vault: ${target}`);+ }++ // Realpath protection only matters when the vault actually exists on+ // disk β otherwise there is no symlink to follow. Pure-lexical inputs+ // (used by unit tests) skip this branch and rely on step 1 above.+ if (existsSync(resolvedVault)) {+ const realVault = safeRealpath(resolvedVault);+ const realAncestor = safeRealpath(deepestExistingAncestor(resolvedTarget));+ if (!isLexicallyInside(realAncestor, realVault)) {+ throw new Error(`path escapes vault via symlink: ${target}`);+ }+ }++ return resolvedTarget;+}++function isLexicallyInside(target: string, root: string): boolean {+ // Windows file paths are case-insensitive at the filesystem level β+ // `C:\Vault\x.md` and `c:\vault\x.md` resolve to the same inode. Doing+ // a case-sensitive string compare on Windows would falsely reject a+ // user's lower-cased argument against a vault stored with the canonical+ // capitalisation. POSIX stays case-sensitive.+ const t = process.platform === "win32" ? target.toLowerCase() : target;+ const r = process.platform === "win32" ? root.toLowerCase() : root;+ return t === r || t.startsWith(r + sep);+}++function deepestExistingAncestor(target: string): string {+ let cur = target;+ // Walk up until we hit a path that exists. `dirname` of a top-level+ // path returns itself; the loop terminates either at the first existing+ // ancestor (the common case β vault root exists) or at the root.+ while (!existsSync(cur)) {+ const parent = dirname(cur);+ if (parent === cur) return cur;+ cur = parent;+ }+ return cur;+}++function safeRealpath(p: string): string {+ // realpath throws on non-existent paths and on permission failure.+ // For non-existent we fall back to the lexical form (the+ // `deepestExistingAncestor` walk above tries to avoid this case);+ // for permission failure we surface the error so the caller learns+ // about it instead of silently disabling symlink protection.+ try {+ return realpathSync(p);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return p;+ throw err;+ }+}++/**+ * 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("/");+}++/**+ * Canonical vault-relative note identity: forward-slash POSIX form plus+ * Unicode NFC.+ *+ * The same note has byte-different vault-relative paths across devices:+ * macOS (APFS/HFS+) stores filenames decomposed (NFD), while Linux and+ * Android store them precomposed (NFC). On a Syncthing peer set that+ * splits one note into two identities, defeating incremental-index+ * change detection (constant re-index churn) and surfacing phantom+ * cross-device duplicates. Funnelling every path that keys a note's+ * identity (the index change-detection key, provenance stamping)+ * through this helper collapses both forms to one NFC identity.+ *+ * Idempotent: an already-POSIX, already-NFC path - the Linux common+ * case - returns byte-identical, so the normalisation is invisible on+ * the dominant platform and only the macOS NFD path actually converges.+ */+export function canonicalNotePath(p: string): string {+ return toPosix(p).normalize("NFC");+}++/**+ * Vault-relative path with forward slashes.+ *+ * Markdown rendering and Obsidian wikilinks both want forward slashes+ * regardless of host OS, so we collapse Windows-style backslashes to+ * `/`. Returns the input unchanged if it is not inside the vault β that+ * guards `ensureInsideVault` callers that want to display the rejected+ * path back to the user without crashing.+ */+export function vaultRelative(target: string, vault: string): string {+ const rel = relative(resolve(vault), resolve(target));+ return rel+ .split(/[\\/]/)+ .filter((p) => p.length > 0)+ .join(posix.sep);+}+```+### src/core/vault.ts lines 120-220+```ts+/**+ * Write a Markdown file with YAML-like frontmatter. Lists are serialized as+ * inline arrays. Scalars that would break the simple parser are quoted and+ * standard control chars are escaped.+ *+ * This variant is non-atomic β used for non-critical writes where a torn+ * file on crash is acceptable (the regenerated `index.md` would just be+ * rebuilt next run; the bootstrap files are templates that can be+ * re-emitted). For writes that must survive concurrent agents and+ * crashes, use `writeFrontmatterAtomic` instead.+ */+export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: string): void {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, formatFrontmatter(metadata, body), "utf8");+}++export interface WriteFrontmatterAtomicOptions {+ /**+ * When `true`, overwrite an existing target atomically (`rename(2)`).+ * When `false` (default), fail with an `EEXIST`-shaped Error if the+ * target already exists, atomically (`link(2)` semantics).+ */+ readonly overwrite?: boolean;+ /**+ * Optional human-readable label for the artifact kind (e.g. `"receipt"`,+ * `"asset"`, `"pending request"`). When the underlying write hits+ * `EEXIST` and `overwrite` is false, the resulting error message becomes+ * `"<kind> already exists: <path>"` instead of the raw `EEXIST: ...`.+ * The label is purely cosmetic β callers that don't supply it get the+ * native errno error.+ */+ readonly existsErrorKind?: string;+ /** Vault root used to render the relative path in the EEXIST message. */+ readonly vaultForRelativePath?: string;+}++/**+ * Atomic frontmatter writer with optional exclusive-create semantics.+ *+ * Used by the Brain writers where:+ * - the file must not be torn on crash β atomic rename/link;+ * - "refuse to overwrite" must be race-free across concurrent processes+ * (CLI + MCP server, multiple agents) β exclusive `link(2)` instead+ * of the TOCTOU-prone `existsSync` + `writeFileSync` pair.+ *+ * On EEXIST the function throws either:+ * - the native `Error & { code: "EEXIST" }` when no `existsErrorKind`+ * was supplied (matches the underlying `link(2)` semantics so callers+ * that want to inspect `err.code` still can), or+ * - a friendlier `Error("<kind> already exists: <relative-path>")`+ * when `existsErrorKind` was supplied β saves every caller from+ * re-implementing the same try/catch.+ */+export function writeFrontmatterAtomic(+ path: string,+ metadata: FrontmatterMap,+ body: string,+ opts: WriteFrontmatterAtomicOptions = {},+): void {+ const contents = formatFrontmatter(metadata, body);+ if (opts.overwrite) {+ atomicWriteFileSync(path, contents);+ return;+ }+ try {+ atomicCreateFileSyncExclusive(path, contents);+ } catch (err) {+ if (opts.existsErrorKind && (err as NodeJS.ErrnoException)?.code === "EEXIST") {+ const rel = opts.vaultForRelativePath+ ? path.startsWith(opts.vaultForRelativePath + "/")+ ? path.slice(opts.vaultForRelativePath.length + 1)+ : path+ : path;+ throw new Error(`${opts.existsErrorKind} already exists: ${rel}`, { cause: err });+ }+ throw err;+ }+}++/**+ * Convert a free-form title to a URL-safe slug. Lowercase, alphanumeric+ * runs joined by `-`, trimmed to 64 chars. Empty / non-ASCII inputs fall+ * back to "note".+ */+export function slugify(value: string): string {+ const lowered = value.trim().toLowerCase();+ let slug = lowered.replace(SLUG_INVALID_RE, "-").replace(/^-+|-+$/g, "");+ if (!slug) slug = "note";+ slug = slug.slice(0, SLUG_MAX_LEN).replace(/-+$/, "");+ return slug || "note";+}++/**+ * Extract unique `[[wikilink]]` targets from Markdown content. Skips media+ * file extensions and links inside fenced or inline code blocks.+ */+export function extractWikilinks(content: string): string[] {+ const masked = content.replace(CODE_BLOCK_RE, " ");+ const seen = new Set<string>();+ const result: string[] = [];+ for (const m of masked.matchAll(WIKILINK_TARGET_RE)) {+```+### src/core/brain/paths.ts lines 140-230+```ts+/** Path of the transient current-task scratchpad read by `brain_context`. */+export function brainPinnedPath(vault: string): string {+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_PINNED_FILE), vault);+}++/** Active-signal path: `Brain/inbox/sig-<date>-<slug>.md`. */+export function signalPath(vault: string, date: string, slug: string): string {+ const d = validateIsoDate(date);+ const s = validateSlug(slug);+ return ensureInsideVault(join(brainDirs(vault).inbox, `sig-${d}-${s}.md`), vault);+}++/** Processed-signal path: `Brain/inbox/processed/sig-<date>-<slug>.md`. */+export function processedSignalPath(vault: string, date: string, slug: string): string {+ const d = validateIsoDate(date);+ const s = validateSlug(slug);+ return ensureInsideVault(join(brainDirs(vault).processed, `sig-${d}-${s}.md`), vault);+}++/** Preference path: `Brain/preferences/pref-<slug>.md`. */+export function preferencePath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(brainDirs(vault).preferences, `pref-${s}.md`), vault);+}++/** Ingested source summary page: `Brain/sources/src-<slug>.md`. */+export function sourcePagePath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_SOURCES_REL, `src-${s}.md`), vault);+}++/** Cited research report page: `Brain/reports/<date>-<slug>.md`. */+export function reportPagePath(vault: string, date: string, slug: string): string {+ const d = validateIsoDate(date);+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_REPORTS_REL, `${d}-${s}.md`), vault);+}++/**+ * Per-preference edit-history sidecar: `Brain/preferences/pref-<slug>.history.jsonl`.+ * Lives next to the preference file; never enters the search index+ * because the walker only yields `.md` files.+ */+export function preferenceHistoryPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(brainDirs(vault).preferences, `pref-${s}.history.jsonl`), vault);+}++/** Retired-preference path: `Brain/retired/ret-<slug>.md`. */+export function retiredPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(brainDirs(vault).retired, `ret-${s}.md`), vault);+}++/** Pending skill-proposal path: `Brain/skill-proposals/pending/prop-<slug>.md`. */+export function skillProposalPendingPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_PENDING_REL, `prop-${s}.md`), vault);+}++/** Accepted skill-proposal archive path: `Brain/skill-proposals/accepted/prop-<slug>.md`. */+export function skillProposalAcceptedPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, `prop-${s}.md`), vault);+}++/** Rejected skill-proposal archive path: `Brain/skill-proposals/rejected/prop-<slug>.md`. */+export function skillProposalRejectedPath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REJECTED_REL, `prop-${s}.md`), vault);+}++/** Accepted procedure reference path: `Brain/procedures/proc-<slug>.md`. */+export function procedurePath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_PROCEDURES_REL, `proc-${s}.md`), vault);+}++/** Procedural-memory index path: `Brain/procedural-memory/index.json`. */+export function proceduralMemoryIndexPath(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "index.json"), vault);+}++/** Procedural-memory usage sidecar path: `Brain/procedural-memory/usage.jsonl`. */+export function proceduralMemoryUsagePath(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "usage.jsonl"), vault);+}++/** Procedural graph projection path: `Brain/procedural-memory/graph.json`. */+export function proceduralGraphPath(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_PROCEDURAL_MEMORY_REL, "graph.json"), vault);+```+### src/core/brain/notes/create-note.ts lines 1-122+```ts+/**+ * createNote primitive (Brain Portability & Interop suite, Unit D).+ *+ * The single write primitive behind the `brain_create_note` MCP tool and+ * the SDK `createNote` method. It writes one Markdown note atomically,+ * funnelled through `ensureInsideVault`, and refuses - with a typed+ * {@link CreateNoteError}, never a silent skip - any path that is not a+ * `.md` file, traverses outside the vault, lands in the Brain machinery+ * root, is excluded by the vault scope, or would clobber an existing+ * file. Refusing loudly is deliberate: a connected agent must learn its+ * write was rejected rather than believe a note exists when it does not.+ */++import { mkdirSync } from "node:fs";+import { dirname, join, posix } from "node:path";++import type { FrontmatterMap } from "../../types.ts";+import { ensureInsideVault } from "../../path-safety.ts";+import { writeFrontmatterAtomic } from "../../vault.ts";+import { inspectPath, resolveVaultScope } from "../../vault-scope/index.ts";+import { BRAIN_ROOT_REL } from "../paths.ts";++/** Machine-readable reason a {@link createNote} call was refused. */+export type CreateNoteErrorCode = "invalid_path" | "excluded" | "exists" | "outside_vault";++export class CreateNoteError extends Error {+ readonly code: CreateNoteErrorCode;+ constructor(code: CreateNoteErrorCode, message: string) {+ super(message);+ this.name = "CreateNoteError";+ this.code = code;+ }+}++export interface CreateNoteInput {+ /** Vault-relative target path; must end in `.md`. */+ readonly path: string;+ /** Optional frontmatter map written above the body. */+ readonly frontmatter?: FrontmatterMap;+ /** Optional Markdown body. */+ readonly content?: string;+}++export interface CreateNoteResult {+ /** Vault-relative POSIX path of the created note. */+ readonly path: string;+ readonly created: true;+}++/**+ * Create one Markdown note in the vault. Returns the created note's+ * vault-relative path; throws {@link CreateNoteError} on any refusal.+ */+export function createNote(vault: string, input: CreateNoteInput): CreateNoteResult {+ if (!input.path.toLowerCase().endsWith(".md")) {+ throw new CreateNoteError("invalid_path", `note path must end in .md: ${input.path}`);+ }+ // The tool addresses notes by a vault-relative path; an absolute path is+ // ambiguous (which root?) and is refused rather than silently re-rooted.+ if (input.path.startsWith("/") || input.path.startsWith("\\")) {+ throw new CreateNoteError("invalid_path", `note path must be vault-relative: ${input.path}`);+ }++ // inspectPath normalises the relative path and throws on `..` traversal;+ // an absolute path also has no place here. Translate both into a typed+ // CreateNoteError so callers get one error surface.+ const scope = resolveVaultScope(vault);+ let inspected;+ try {+ inspected = inspectPath(input.path, scope, vault);+ } catch (err) {+ throw new CreateNoteError("invalid_path", err instanceof Error ? err.message : String(err));+ }+ const relPath = inspected.relPath;+ if (relPath === "") {+ throw new CreateNoteError("invalid_path", `empty note path: ${input.path}`);+ }++ // The Brain machinery root is owned by the brain's own writers; a+ // free-form note tool must never author into it (default vault-scope+ // rules ignore Brain/.snapshots only, not the whole Brain root).+ const firstSegment = relPath.split("/")[0];+ if (firstSegment === BRAIN_ROOT_REL) {+ throw new CreateNoteError(+ "excluded",+ `the Brain machinery root is not writable via create_note: ${relPath}`,+ );+ }++ if (inspected.excluded) {+ throw new CreateNoteError(+ "excluded",+ `path is excluded by vault scope (${inspected.rule?.raw ?? "rule"}): ${relPath}`,+ );+ }++ let abs: string;+ try {+ abs = ensureInsideVault(join(vault, relPath), vault);+ } catch (err) {+ throw new CreateNoteError("outside_vault", err instanceof Error ? err.message : String(err));+ }++ mkdirSync(dirname(abs), { recursive: true });+ try {+ writeFrontmatterAtomic(abs, input.frontmatter ?? {}, input.content ?? "", {+ overwrite: false,+ existsErrorKind: "note",+ vaultForRelativePath: vault,+ });+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ const exists =+ code === "EEXIST" || (err instanceof Error && /already exists/.test(err.message));+ if (exists) {+ throw new CreateNoteError("exists", `note already exists: ${relPath}`);+ }+ throw err;+ }++ return { path: relPath.split(/[\\/]/).join(posix.sep), created: true };+}+```+### tests/core/path-safety.test.ts lines 1-98+```ts+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { ensureInsideVault, vaultRelative } from "../../src/core/path-safety.ts";++// Resolving `/v` produces a platform-appropriate absolute path:+// `/v` on POSIX, `C:\v` (or the current drive) on Windows. Building all+// fixtures off this anchor keeps the assertions portable across both+// without baking POSIX separators into the test inputs.+const VAULT = resolve("/v");+const SIBLING = resolve("/v-evil");+const OUTSIDE = resolve("/etc/passwd");++describe("ensureInsideVault", () => {+ test("accepts the vault root itself", () => {+ expect(ensureInsideVault(VAULT, VAULT)).toBe(VAULT);+ });++ test("accepts descendants", () => {+ const target = join(VAULT, "Notes", "notes", "x.md");+ expect(ensureInsideVault(target, VAULT)).toBe(target);+ });++ test("rejects siblings sharing a name prefix", () => {+ // Without using `path.sep`, the naive `startsWith(vault + "/")` check+ // would happily admit `/v-evil/...` because `/v-evil` starts with `/v`+ // when concatenated. The fixed implementation rejects it.+ expect(() => ensureInsideVault(join(SIBLING, "x.md"), VAULT)).toThrow(/escapes vault/);+ });++ test("rejects paths that resolve outside the vault", () => {+ expect(() => ensureInsideVault(OUTSIDE, VAULT)).toThrow();+ expect(() => ensureInsideVault(join(VAULT, "..", "etc", "passwd"), VAULT)).toThrow();+ });++ test("returns the resolved absolute path", () => {+ const target = join(VAULT, "Notes", "x.md");+ expect(ensureInsideVault(target, VAULT)).toBe(target);+ });+});++describe("ensureInsideVault β realpath / symlink escape", () => {+ // These tests need real on-disk symlinks so realpath() can follow them;+ // the synthetic-path tests above exercise the lexical-only fast path.+ let tmp: string;+ let vault: string;+ let outside: string;++ beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-path-safety-real-"));+ vault = join(tmp, "vault");+ outside = join(tmp, "outside");+ mkdirSync(vault, { recursive: true });+ mkdirSync(outside, { recursive: true });+ writeFileSync(join(outside, "secret.md"), "secret\n");+ });++ afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ test("rejects a target whose ancestor is a symlink to outside the vault", () => {+ // <vault>/escape -> <outside>+ symlinkSync(outside, join(vault, "escape"), "dir");+ const target = join(vault, "escape", "secret.md");+ expect(() => ensureInsideVault(target, vault)).toThrow(/escapes vault via symlink/);+ });++ test("accepts a target inside a real subdirectory", () => {+ const sub = join(vault, "Notes");+ mkdirSync(sub, { recursive: true });+ expect(ensureInsideVault(join(sub, "x.md"), vault)).toBe(join(sub, "x.md"));+ });++ test("accepts a still-non-existent target whose existing ancestor is the vault itself", () => {+ // No symlink involved; just a fresh slug on a real vault. realpath+ // protection should not crash on a path component that doesn't exist+ // yet (the writer creates it after this check passes).+ expect(ensureInsideVault(join(vault, "Notes", "payments", "2026-05-10", "x.md"), vault)).toBe(+ join(vault, "Notes", "payments", "2026-05-10", "x.md"),+ );+ });+});++describe("vaultRelative", () => {+ test("renders descendant paths with forward slashes", () => {+ const target = join(VAULT, "Notes", "notes", "x.md");+ // The renderer always emits forward slashes, even when the host+ // separator is `\`, so wikilinks/Obsidian behave consistently.+ expect(vaultRelative(target, VAULT)).toBe("Notes/notes/x.md");+ });++ test("returns empty string for the vault root itself", () => {+ expect(vaultRelative(VAULT, VAULT)).toBe("");+ });+});+```+### tests/core/brain/notes/create-note.test.ts lines 1-100+```ts+/**+ * createNote primitive (Brain Portability & Interop suite, Unit D).+ *+ * The shared write primitive behind the `brain_create_note` MCP tool and+ * the SDK `createNote` method. Writes a Markdown note atomically under+ * `ensureInsideVault`, honouring vault-scope ignore rules and refusing+ * the Brain machinery root, path traversal, and clobbering an existing+ * file - every refusal is a typed `CreateNoteError`, never a silent skip.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createNote, CreateNoteError } from "../../../../src/core/brain/notes/create-note.ts";++let vault: string;+beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-create-note-"));+});+afterEach(() => rmSync(vault, { recursive: true, force: true }));++describe("createNote", () => {+ test("writes a note with frontmatter and body, returns the vault-relative path", () => {+ const res = createNote(vault, {+ path: "Notes/New.md",+ frontmatter: { title: "New", tags: ["a", "b"] },+ content: "Hello body.",+ });+ expect(res.created).toBe(true);+ expect(res.path).toBe("Notes/New.md");+ const written = readFileSync(join(vault, "Notes/New.md"), "utf8");+ expect(written).toContain("title: New");+ expect(written).toContain("Hello body.");+ });++ test("creates intermediate directories", () => {+ createNote(vault, { path: "A/B/C/Deep.md", content: "x" });+ expect(existsSync(join(vault, "A/B/C/Deep.md"))).toBe(true);+ });++ test("allows a note with no frontmatter and no content", () => {+ const res = createNote(vault, { path: "Notes/Empty.md" });+ expect(res.created).toBe(true);+ expect(existsSync(join(vault, "Notes/Empty.md"))).toBe(true);+ });++ test("rejects a non-.md path with a typed error", () => {+ expect(() => createNote(vault, { path: "Notes/data.json", content: "x" })).toThrow(+ CreateNoteError,+ );+ });++ test("rejects path traversal with a typed error", () => {+ expect(() => createNote(vault, { path: "../escape.md", content: "x" })).toThrow(+ CreateNoteError,+ );+ expect(existsSync(join(vault, "..", "escape.md"))).toBe(false);+ });++ test("rejects an absolute path with a typed error", () => {+ expect(() => createNote(vault, { path: "/etc/evil.md", content: "x" })).toThrow(+ CreateNoteError,+ );+ });++ test("refuses to write into the Brain machinery root", () => {+ expect(() => createNote(vault, { path: "Brain/sneaky.md", content: "x" })).toThrow(+ CreateNoteError,+ );+ expect(existsSync(join(vault, "Brain/sneaky.md"))).toBe(false);+ });++ test("refuses a vault-scope excluded path", () => {+ expect(() => createNote(vault, { path: ".obsidian/plugins/x.md", content: "x" })).toThrow(+ CreateNoteError,+ );+ });++ test("refuses to clobber an existing note (no overwrite)", () => {+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(join(vault, "Notes/Dup.md"), "original", "utf8");+ expect(() => createNote(vault, { path: "Notes/Dup.md", content: "new" })).toThrow(+ CreateNoteError,+ );+ // The original content is untouched.+ expect(readFileSync(join(vault, "Notes/Dup.md"), "utf8")).toBe("original");+ });++ test("the typed error carries a machine-readable code", () => {+ try {+ createNote(vault, { path: "../escape.md", content: "x" });+ throw new Error("expected throw");+ } catch (err) {+ expect(err).toBeInstanceOf(CreateNoteError);+ expect((err as CreateNoteError).code).toBe("invalid_path");+ }+ });+});+```+### tests/core/vault.test.ts lines 120-160+```ts+ writeFrontmatter(path, { summary: value }, "Body.");+ const [meta] = parseFrontmatter(path);+ expect(meta["summary"]).toBe(value);+ });++ test("inline array elements with quotes round-trip", () => {+ const path = join(tmp, "note.md");+ const tags = ["plain", 'say "hi"'];+ writeFrontmatter(path, { tags }, "Body.");+ const [meta] = parseFrontmatter(path);+ expect(meta["tags"]).toEqual(tags);+ });+});++describe("slugify", () => {+ test("lowercases and replaces punctuation", () => {+ expect(slugify("Hello, World!")).toBe("hello-world");+ });++ test("handles non-ASCII and empty inputs", () => {+ expect(slugify(" ")).toBe("note");+ expect(slugify("---")).toBe("note");+ // Geometric / dingbat symbols β purely non-ASCII, stripped down to nothing+ // by the alphanumeric regex. Falls back to the "note" sentinel.+ expect(slugify("β β β")).toBe("note");+ });++ test("truncates long input to 64 chars", () => {+ expect(slugify("a".repeat(200)).length).toBe(64);+ });+});++describe("extractWikilinks", () => {+ test("simple links", () => {+ expect(extractWikilinks("See [[Target]] and [[Other]] for details.")).toEqual([+ "Target",+ "Other",+ ]);+ });++ test("ignores media file extensions", () => {+```+### src/mcp/brain/feedback-tools.ts lines 1-90+```ts+/**+ * Brain write surface: taste signals, the dream learning pass, apply-evidence records, and narrative notes.+ *+ * Extracted from the former brain-tools.ts monolith; registration+ * happens through the aggregator, which preserves the public+ * BRAIN_TOOLS surface.+ */++import { resolve } from "node:path";+import { resolveAgentName } from "../../core/config.ts";+import {+ appendApplyEvidence,+ BrainPreferenceNotFoundError,+ type AppendApplyEvidenceInput,+} from "../../core/brain/apply-evidence.ts";+import { dream } from "../../core/brain/dream.ts";+import {+ applyDreamBundle,+ discardDreamBundle,+ listDreamBundles,+ stageDream,+ validateDreamBundle,+} from "../../core/brain/dream-stage.ts";+import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";+import { resolveEffectiveScope, writeSignal } from "../../core/brain/signal.ts";+import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";+import { writePreference } from "../../core/brain/preference.ts";+import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";+import { isoDate, isoSecond } from "../../core/brain/time.ts";+import { slugify } from "../../core/vault.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import {+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_APPLY_RESULT,+ type BrainApplyResult,+ type BrainSignalSign,+} from "../../core/brain/types.ts";+import { appendLogEvent } from "../../core/brain/log.ts";+import { appendBrainNote } from "../../core/brain/note.ts";+import { mirrorSignal, resolveSharedNamespace } from "../../core/brain/shared-namespace.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext, ToolDefinition } from "../tools.ts";+import { coerceStr, coerceBool, coerceIsoDate } from "../coerce.ts";+import { vaultRelativeSafe } from "./shared.ts";++/**+ * Build the slug used in the signal / preference filename. We never let+ * the agent decide the slug directly β taking `topic` as the slug stem+ * is what the design doc Β§9.2 prescribes (slugs are deterministic from+ * topic). The slug is run through `slugify` defensively so a slightly+ * mis-shaped topic still yields a filesystem-safe basename.+ */+function deriveSlug(topic: string): string {+ return slugify(topic);+}++async function toolBrainFeedback(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // Single source of truth for the brain_feedback payload contract β+ // session-replay (sessions/import.ts) and the MCP live path now go+ // through the same validator so rule shape cannot drift between the+ // two surfaces.+ const validated = validateBrainFeedbackInput(args);+ if (!validated.ok) {+ throw new MCPError(INVALID_PARAMS, validated.reason);+ }+ const {+ topic,+ signal: signalRaw,+ principle,+ scope,+ raw,+ source,+ force_confirmed,+ } = validated.value;+ const forceConfirmed = force_confirmed ?? false;++ // Agent-fallback stays MCP-side: validator just hands back the user-+ // supplied value (or undefined); the live path resolves via config+ // when absent.+ const agent =+ normalizeAgentArgument(validated.value.agent ?? null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const now = new Date();+ const date = isoDate(now);+ const createdAt = isoSecond(now);+ const slug = deriveSlug(topic);+```++Related grep output:+```text+src/core/vault.ts:10:import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+src/core/vault.ts:129: * crashes, use `writeFrontmatterAtomic` instead.+src/core/vault.ts:131:export function writeFrontmatter(path: string, metadata: FrontmatterMap, body: string): void {+src/core/vault.ts:132: mkdirSync(dirname(path), { recursive: true });+src/core/vault.ts:133: writeFileSync(path, formatFrontmatter(metadata, body), "utf8");+src/core/vault.ts:163: * of the TOCTOU-prone `existsSync` + `writeFileSync` pair.+src/core/vault.ts:173:export function writeFrontmatterAtomic(+src/core/vault.ts:204:export function slugify(value: string): string {+src/core/doctor.ts:11: mkdirSync,+src/core/doctor.ts:46: mkdirSync(dirname(config), { recursive: true });+src/core/path-safety.ts:6: * write must funnel through `ensureInsideVault` so a malicious or buggy+src/core/path-safety.ts:35:export function ensureInsideVault(target: string, vault: string): string {+src/core/path-safety.ts:135: * guards `ensureInsideVault` callers that want to display the rejected+src/core/config.ts:10:import { mkdirSync, readFileSync } from "node:fs";+src/core/config.ts:242: mkdirSync(dir, { recursive: true });+src/core/bench/run-store.ts:12:import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+src/core/bench/run-store.ts:49: mkdirSync(runDir, { recursive: true });+src/core/bench/run-store.ts:103: writeFileSync(join(runDir, CHECKPOINT_FILE), `${JSON.stringify(checkpoint, null, 2)}\n`, "utf8");+src/core/bench/phases.ts:16:import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+src/core/bench/phases.ts:90: mkdirSync(benchResultsDir(run.runDir), { recursive: true });+src/core/bench/phases.ts:97: writeFileSync(+src/core/bench/phases.ts:117: writeFileSync(join(run.runDir, "report.json"), `${JSON.stringify(report, null, 2)}\n`, "utf8");+src/core/bench/fixture.ts:12:import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+src/core/bench/fixture.ts:83: mkdirSync(join(vaultDir, "Brain"), { recursive: true });+src/core/bench/fixture.ts:86: mkdirSync(dirname(target), { recursive: true });+src/core/bench/fixture.ts:87: writeFileSync(target, note.body, "utf8");+src/core/reliability/lock.ts:1:import { mkdirSync } from "node:fs";+src/core/reliability/lock.ts:27: mkdirSync(dirname(targetPath), { recursive: true });+src/core/reliability/audit.ts:1:import { closeSync, fsyncSync, mkdirSync, openSync, writeFileSync } from "node:fs";+src/core/reliability/audit.ts:20: mkdirSync(auditRoot, { recursive: true });+src/core/reliability/audit.ts:28: writeFileSync(fileDescriptor, line + "\n", "utf8");+src/core/fs-atomic.ts:18: mkdirSync,+src/core/fs-atomic.ts:76: * race-free: a plain `existsSync(target) || writeFileSync(...)` is+src/core/fs-atomic.ts:112: mkdirSync(dir, { recursive: true });+src/core/brain/pref-audit.ts:20: * Append uses `appendFileSync` (the same `O_APPEND` atomicity assumption+src/core/brain/pref-audit.ts:26:import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/pref-audit.ts:128: mkdirSync(dirname(path), { recursive: true });+src/core/brain/pref-audit.ts:129: appendFileSync(path, renderPrefAuditLine(record), "utf8");+src/core/brain/recurrence.ts:1:import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/recurrence.ts:4:import { ensureInsideVault } from "../path-safety.ts";+src/core/brain/recurrence.ts:235: mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });+src/core/brain/recurrence.ts:236: appendFileSync(path, `${JSON.stringify(event)}\n`, { encoding: "utf8" });+src/core/brain/sync-lockfile.ts:5: * `moveToRetired`, `writeFrontmatterAtomic`) and migrating it to async+src/core/brain/sync-lockfile.ts:24:import { closeSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "node:fs";+src/core/brain/sync-lockfile.ts:68: mkdirSync(dirname(lockPath), { recursive: true });+src/core/brain/portability/pointer.ts:21:import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";+src/core/brain/portability/pointer.ts:208: mkdirSync(dirname(path), { recursive: true });+src/core/brain/portability/graph.ts:14:import { existsSync, mkdirSync } from "node:fs";+src/core/brain/portability/graph.ts:22: writeFrontmatterAtomic,+src/core/brain/portability/graph.ts:29:import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";+src/core/brain/portability/graph.ts:194: * Every write is guarded by {@link ensureInsideVault}.+src/core/brain/portability/graph.ts:232: path = ensureInsideVault(join(vault, relPath), vault);+src/core/brain/portability/graph.ts:261: mkdirSync(dirname(path), { recursive: true });+src/core/brain/portability/graph.ts:262: writeFrontmatterAtomic(path, meta, body, { overwrite: true, vaultForRelativePath: vault });+src/core/brain/portability/profiles.ts:15:import { existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/portability/profiles.ts:72: mkdirSync(dirname(path), { recursive: true });+src/core/brain/portability/recall-sources.ts:16:import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+src/core/brain/portability/recall-sources.ts:83: mkdirSync(dirname(path), { recursive: true });+src/core/brain/preference.ts:40:import { formatFrontmatter, parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";+src/core/brain/preference.ts:328: writeFrontmatterAtomic(path, metadata, body, {+src/core/brain/preference.ts:505: * writeFrontmatterAtomic} writes a frontmatter-only file.+src/core/brain/preference.ts:1026: writeFrontmatterAtomic(newPath, newMeta, newBody, {+src/core/brain/link-graph/bridge-discovery.ts:23:import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+src/core/brain/link-graph/bridge-discovery.ts:35: writeFrontmatterAtomic,+src/core/brain/link-graph/bridge-discovery.ts:232: mkdirSync(dirname(path), { recursive: true });+src/core/brain/link-graph/bridge-discovery.ts:258: mkdirSync(dirname(path), { recursive: true });+src/core/brain/link-graph/bridge-discovery.ts:259: writeFileSync(path, JSON.stringify({ pairs: [...dismissed].toSorted() }, null, 2) + "\n");+src/core/brain/link-graph/bridge-discovery.ts:333: writeFrontmatterAtomic(sourceAbs, metadata, body, { overwrite: true });+src/core/brain/link-graph/communities.ts:26:import { mkdirSync, readdirSync, rmSync } from "node:fs";+src/core/brain/link-graph/communities.ts:243: mkdirSync(dir, { recursive: true });+src/core/brain/link-graph/co-occurrence.ts:21:import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+src/core/brain/link-graph/co-occurrence.ts:160: mkdirSync(dirname(path), { recursive: true });+src/core/brain/link-graph/co-occurrence.ts:161: writeFileSync(+src/core/brain/entities/registry.ts:15:import { mkdirSync } from "node:fs";+src/core/brain/entities/registry.ts:18:import { parseFrontmatter, slugify, writeFrontmatterAtomic } from "../../vault.ts";+src/core/brain/entities/registry.ts:160: mkdirSync(dirname(path), { recursive: true });+src/core/brain/entities/registry.ts:161: writeFrontmatterAtomic(path, meta, body, {+src/core/brain/entities/registry.ts:202: const base = `${BRAIN_ENTITY_ID_PREFIX}${category}-${slugify(name)}`;+src/core/brain/inline-rewrite.ts:27:import { mkdirSync, readFileSync } from "node:fs";+src/core/brain/inline-rewrite.ts:53: mkdirSync(parent, { recursive: true });+src/core/brain/payload-registry.ts:2:import { existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/payload-registry.ts:6:import { ensureInsideVault } from "./paths.ts";+src/core/brain/payload-registry.ts:78: mkdirSync(this.payloadDir(), { recursive: true });+src/core/brain/payload-registry.ts:91: return ensureInsideVault(join(this.vault, "Brain", ".payloads"), this.vault);+src/core/brain/payload-registry.ts:95: return ensureInsideVault(join(this.payloadDir(), `${id}.txt`), this.vault);+src/core/brain/git/decisions.ts:18:import { existsSync, mkdirSync } from "node:fs";+src/core/brain/git/decisions.ts:130: mkdirSync(dir, { recursive: true });+src/core/brain/git/store.ts:24:import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";+src/core/brain/git/store.ts:25:import { appendFileSync } from "node:fs";+src/core/brain/git/store.ts:209: mkdirSync(gitStoreDir(vault, repoKey), { recursive: true });+src/core/brain/git/store.ts:210: appendFileSync(commitsPath(vault, repoKey), lines.join(""));+src/core/brain/git/store.ts:276: mkdirSync(gitStoreDir(vault, repoKey), { recursive: true });+src/core/brain/log.ts:28:import { existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/log.ts:312: mkdirSync(logDir, { recursive: true });+src/core/brain/import-claude-memory.ts:1:import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";+src/core/brain/import-claude-memory.ts:182: mkdirSync(join(opts.vault, BRAIN_PREFERENCES_REL), { recursive: true });+src/core/brain/truth/store.ts:18: mkdirSync,+src/core/brain/truth/store.ts:19: appendFileSync,+src/core/brain/truth/store.ts:23: writeFileSync,+src/core/brain/truth/store.ts:118: mkdirSync(truthDir(vault), { recursive: true });+src/core/brain/truth/store.ts:120: appendFileSync(path, JSON.stringify(event) + "\n");+src/core/brain/truth/store.ts:267: mkdirSync(truthDir(vault), { recursive: true });+src/core/brain/truth/store.ts:268: writeFileSync(truthStatePath(vault), JSON.stringify(state, null, 2) + "\n");+src/core/brain/truth/store.ts:417: writeFileSync(path, kept.join("\n") + "\n");+src/core/brain/handoff.ts:12:import { mkdirSync, writeFileSync } from "node:fs";+src/core/brain/handoff.ts:143: mkdirSync(dir, { recursive: true });+src/core/brain/handoff.ts:163: writeFileSync(path, content);+src/core/brain/attention-flows.ts:1:import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";+src/core/brain/attention-flows.ts:4:import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";+src/core/brain/attention-flows.ts:45: mkdirSync(dir, { recursive: true });+src/core/brain/attention-flows.ts:48: writeFrontmatterAtomic(+src/core/brain/heal-run.ts:24: writeFrontmatterAtomic,+src/core/brain/heal-run.ts:94: writeFrontmatterAtomic(p.path, newMeta, newBody, {+src/core/brain/write-session/engine.ts:25:import { existsSync, mkdirSync, readFileSync } from "node:fs";+src/core/brain/write-session/engine.ts:362: mkdirSync(dirname(absolute), { recursive: true });+src/core/brain/write-session/panel.ts:75: input.targetPath ?? `Brain/decisions/panels/panel-${now.slice(0, 10)}-${slugify(topic)}.md`;+src/core/brain/write-session/store.ts:19:import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";+src/core/brain/write-session/store.ts:232: mkdirSync(writeSessionDir(vault), { recursive: true });+src/core/brain/write-session/store.ts:248: mkdirSync(writeSessionDir(vault), { recursive: true });+src/core/brain/protect.ts:30:import { existsSync, mkdirSync, readFileSync } from "node:fs";++```++Question for variants:+Pick the best small patch-scope architecture for adding defense-in-depth write containment and identifier/path-segment sanitization for vault writes. Compare at least these families: hardening central frontmatter writers with optional vault root; adding explicit safe identifier/path segment helpers and applying to untrusted identifier inputs; minimal audit/tests around existing chokepoints. Recommend what one card can ship safely.diff --git a/docs/brainstorm/path-safe-vault-writes/design.md b/docs/brainstorm/path-safe-vault-writes/design.mdnew file mode 100644index 00000000..1e6f073c--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/design.md@@ -0,0 +1,55 @@+# Path-safe vault writes design++## Problem++Open Second Brain writes Markdown and JSONL files inside an Obsidian vault, especially under the managed `Brain/` subtree. The in-scope card asks for defense-in-depth against path traversal when caller-derived identifiers become filenames or path segments, and for a containment backstop before vault writes happen.++The current code already contains `ensureInsideVault`, `src/core/brain/paths.ts` constructors, `validateSlug`, `slugify`, and a `brain_create_note` implementation that refuses traversal and absolute paths. The remaining risk is not that no guard exists, but that direct write call sites may bypass existing path constructors or lack regression tests proving the write target stays inside the configured vault root.++## Scope++- In-scope card: `t_7b1049bb` - Path-safe identifier sanitization and write-containment guard for vault writes.+- Branch: `feat/path-safe-vault-writes`.+- Release shape: one small patch-version hardening task. The implementation card should be driven under TDD and keep the change limited to the smallest proven write-containment gap.+- Preserve unrelated pre-existing working tree changes in `src/core/brain/morning-brief.ts` and `src/core/brain/time.ts`.++## Out of scope++- No release execution in this phase.+- No broad rewrite of all vault writers into a new abstraction unless the audit proves a specific unguarded write path needs it.+- No new natural-language wordlists or language-specific sanitization rules.+- No behavior change for unrelated CLI, MCP, search, or portability features.+- No manual version bump in this phase.++## Chosen approach++Chosen variant: Variant 3, audit-and-prove existing write containment.++The consultant recommended verifying every direct vault writer, routing only real stragglers through the existing `ensureInsideVault` or `paths.ts` constructors, and adding regression tests for traversal, sibling-prefix, absolute path, and symlink-ancestor escapes. I agree with this recommendation because the project already has mature path-safety primitives, and a small patch release should not introduce a competing sanitizer or a default-off writer option that callers can forget to use.++## Design decisions++1. Treat `ensureInsideVault` and `src/core/brain/paths.ts` as the primary containment boundary.+2. Audit direct writer call sites before changing code. A write is acceptable only if its target is built by a guarded path constructor, by `ensureInsideVault(join(vault, ...), vault)`, or by a component whose own tests prove equivalent containment.+3. If an unguarded Brain or vault write is found, harden that specific path by reusing the existing guard instead of adding a second path-safety model.+4. Add TDD regression coverage before implementation changes. Tests should exercise traversal (`..`), absolute paths, sibling-prefix paths, and symlink-ancestor escapes where filesystem semantics matter.+5. Do not add a broad optional `vault` parameter to `writeFrontmatter` or `writeFrontmatterAtomic` in this patch. Optional containment at the writer layer would be easy for callers to omit and is too broad for one low-priority card.+6. Do not add a new email-style identifier whitelist unless the audit identifies a concrete caller-supplied identifier that must preserve `@` or `+` and is not already handled by `validateSlug`, `slugify`, or `inspectPath`.++## File changes++Expected implementation areas:++- `src/core/path-safety.ts` if a small reusable helper is needed near the existing containment primitive.+- `src/core/brain/paths.ts` if a missing Brain path constructor needs to be added or an existing constructor needs stricter validation.+- Specific writer modules found by the audit, only when they construct write targets without the existing guard.+- `tests/core/path-safety.test.ts` and focused tests next to the affected writer module.+- `CHANGELOG.md` under `[Unreleased]` after implementation, describing the hardening in user-facing terms.++Do not touch the unrelated pre-existing changes in `src/core/brain/morning-brief.ts` and `src/core/brain/time.ts`.++## Risks++- The audit may find more scattered writers than expected. If that happens, keep this card to the highest-risk Brain/vault writer and file follow-up work instead of expanding scope.+- Some direct writes are intentionally outside the vault, such as local config, benchmarks, or repo metadata. Tests and code changes must distinguish vault-owned writes from non-vault files.+- Symlink tests are platform-sensitive. Follow the existing `tests/core/path-safety.test.ts` pattern and avoid assumptions that break Windows compatibility.diff --git a/docs/brainstorm/path-safe-vault-writes/plan.md b/docs/brainstorm/path-safe-vault-writes/plan.mdnew file mode 100644index 00000000..7f238833--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/plan.md@@ -0,0 +1,54 @@+# Path-safe vault writes implementation plan++## Release scope++This patch release scope contains exactly one driven card:++- `t_7b1049bb` - Path-safe identifier sanitization and write-containment guard for vault writes.++All work happens on branch `feat/path-safe-vault-writes`. Workers must build on commits already landed on this branch and must not duplicate or conflict with sibling tasks. There are no sibling cards in this release scope.++## t_7b1049bb - Path-safe identifier sanitization and write-containment guard for vault writes++### Files++Primary files to inspect:++- `src/core/path-safety.ts`+- `src/core/brain/paths.ts`+- `src/core/vault.ts`+- `src/core/brain/notes/create-note.ts`+- Every `src/**` call site from a grep for `writeFrontmatter`, `writeFileSync`, `appendFileSync`, `mkdirSync`, `atomicWriteFileSync`, and `atomicWriteText`++Likely test files:++- `tests/core/path-safety.test.ts`+- `tests/core/brain/notes/create-note.test.ts`+- A focused test file near any specific writer hardened by the audit++Docs or release notes after implementation:++- `CHANGELOG.md` under `[Unreleased]`++### Acceptance++A passing implementation must include TDD evidence:++1. Add or extend failing tests first that prove the selected vault write path rejects traversal, absolute escapes, sibling-prefix escapes, and symlink-ancestor escapes where applicable.+2. Implement the smallest code change that makes those tests pass by reusing `ensureInsideVault`, `src/core/brain/paths.ts`, `validateSlug`, `slugify`, or `inspectPath` as appropriate.+3. Run at minimum:+ - `bun test tests/core/path-safety.test.ts`+ - the focused test for the hardened writer+ - `bun run typecheck`+4. Before handoff, run the project validation command if feasible: `bun run validate`.+5. The diff must not modify the pre-existing unrelated working-tree files `src/core/brain/morning-brief.ts` or `src/core/brain/time.ts`.++### Depends on++- `docs/brainstorm/path-safe-vault-writes/design.md`+- This plan section+- The branch `feat/path-safe-vault-writes` being current before the worker starts++### Implementation notes++Start with an audit table in the worker notes or card comment: writer call site, target root, guard mechanism, action needed. Change only call sites that write into the vault or Brain and lack a guard. If the audit finds no missing guard, ship regression tests that pin the existing containment invariant and document the finding in the handoff.diff --git a/docs/brainstorm/path-safe-vault-writes/variants.md b/docs/brainstorm/path-safe-vault-writes/variants.mdnew file mode 100644index 00000000..783c2c4d--- /dev/null+++ b/docs/brainstorm/path-safe-vault-writes/variants.md@@ -0,0 +1,47 @@+# Path-safe vault writes variants++## Consultant output++Primary consultant command failed before model execution because the shell argument exceeded the OS argument length limit. The fallback consultant used the same model after reducing prompt size while preserving the required context.++### Primary output++```text+/usr/bin/bash: line 3: /root/.local/bin/claude: Argument list too long+```++### Fallback output++## Variant 1+Approach: Add an optional containment-root parameter to `writeFrontmatter` and `writeFrontmatterAtomic` so the writers themselves call `ensureInsideVault` before `mkdirSync`/write, making containment a property of the single write primitive rather than each caller. Every existing caller keeps working unchanged (the parameter is optional and defaults to today's behavior).+Trade-offs:+- Closes the gap at the lowest, most-shared layer, so any current or future caller that passes the root is contained by construction (strong DRY, defense-in-depth at the chokepoint).+- An optional, default-off guard is a misleading fallback: the protection only exists for callers that remember to pass the root, so the signature changes without actually moving the invariant unless every call site is also updated β which inflates scope toward the "route everything" large case.+Complexity: medium+Risk: medium++## Variant 2+Approach: Introduce explicit `safeIdentifier`/`safePathSegment` helpers that whitelist structural character classes, reject `.`/`..`, and admit `@`/`+` (matching the upstream `sender_id` rule), then apply them at the boundaries where partly-caller-supplied identifiers become path segments and are not already run through `validateSlug`. Keep the whitelist language-agnostic (character classes, no wordlists).+Trade-offs:+- Sanitizes the untrusted input at the boundary where it enters, complementing the existing `validateSlug` and giving email/plus-addressed ids a first-class path (directly mirrors the upstream defense).+- High overlap with the existing `validateSlug`/`slugify` and `paths.ts` constructors risks two competing sanitizers; without a careful audit of which inputs are genuinely unguarded, this adds surface area and can violate DRY rather than hardening.+Complexity: medium+Risk: medium++## Variant 3+Approach: Treat the card as an audit-and-prove task: enumerate every direct vault writer (the `writeFrontmatter`/`writeFileSync`/`appendFileSync`/`mkdirSync` sites from the grep), confirm each already funnels through a `paths.ts` constructor or `ensureInsideVault`, and route the few that do not through the existing guard. Lock the invariant with TDD regression tests (traversal slugs, sibling-prefix, symlink-ancestor, absolute paths) at the chokepoints, changing no shared signatures.+Trade-offs:+- Smallest, reversible diff that fits patch scope: it hardens only genuinely-unguarded writers with the helper that already exists and turns the "agent writes only inside Brain/" invariant into executable, regression-proof tests.+- Does not add the email/plus-addressed identifier whitelist, so the upstream `sender_id`-style sanitization is deferred; if the audit finds writers are already centralized, the visible code delta is mostly tests rather than new mechanism.+Complexity: small+Risk: low++## Recommended: Variant 3+The codebase already has the right primitive (`ensureInsideVault`), the path constructors, and `validateSlug`, so the honest small-patch move is to verify the invariant holds everywhere and pin it with tests, routing only the stragglers through the existing guard rather than reshaping shared writer signatures. This avoids the misleading-fallback and DRY-duplication risks of Variants 1 and 2 while delivering real defense-in-depth value, and it leaves the optional-root writer change and identifier whitelist as cleanly-scoped follow-ups if the audit shows they are actually needed.+++## Final rationale++Final choice: Variant 3.++I agree with the consultant recommendation. Open Second Brain already has `ensureInsideVault`, guarded Brain path constructors, and `brain_create_note` containment, so the best patch-scope work is to audit the remaining writer call sites, route only confirmed gaps through existing guards, and add regression tests that keep the containment invariant from regressing. Variant 1 risks a default-off writer guard that looks safer than it is, and Variant 2 risks adding a competing sanitizer before proving where an untrusted identifier gap exists.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex f23cc41e..e7444856 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -27,7 +27,7 @@ o2b update Update Open Second Brain across all detected runti```texto2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set-o2b brain feedback Record one taste signal (--topic, --signal, --principle, ...)+o2b brain feedback Record one taste signal (--topic, --signal, --principle, --scope, ...); --scope is optional and falls back to feedback.default_scope from _brain.yaml when seto2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)o2b brain apply-evidence Record applied / violated against a preference for a durable artifacto2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)diff --git a/docs/mcp.md b/docs/mcp.mdindex 4ba4d029..36b66807 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -405,6 +405,8 @@ The plugin's `.mcp.json` ships **two** MCP-server entries:Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).+`brain_feedback`'s `scope` argument stays optional. When the vault declares `feedback.default_scope` in `Brain/_brain.yaml`, a call that omits `scope` records the signal under that default category; an explicit `scope` always wins, and with no default configured a scope-less call stays scope-less. The same effective scope is reused for a `force_confirmed: true` preference so the preference and its signal share one scope. The configured value is validated against the same constraints as any signal `scope` (non-empty after trim, single-line, at most 128 characters).+## Safety notes- The vault path is bound to the server instance at startup. Tools cannotdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex cf987d99..86e6d4f6 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.13.0",+ "version": "1.14.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 3aa8130b..e5d47076 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.13.0",+ "version": "1.14.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 579b01e4..aa0cd29f 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.13.0"+version: "1.14.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex b3dcf8fd..ec7f810c 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.13.0",+ "version": "1.14.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 579b01e4..aa0cd29f 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.13.0"+version: "1.14.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 1b22c1a5..3fca9023 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.13.0"+version = "1.14.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.tsindex 49bc1faf..5ee15e19 100644--- a/src/cli/brain/verbs/feedback.ts+++ b/src/cli/brain/verbs/feedback.ts@@ -1,6 +1,7 @@import { readFileSync } from "node:fs";import { mirrorSignal, resolveSharedNamespace } from "../../../core/brain/shared-namespace.ts";-import { writeSignal } from "../../../core/brain/signal.ts";+import { resolveEffectiveScope, writeSignal } from "../../../core/brain/signal.ts";+import { loadFeedbackDefaultScopeSafe } from "../../../core/brain/policy.ts";import { appendLogEvent } from "../../../core/brain/log.ts";import { writePreference } from "../../../core/brain/preference.ts";import { isoDate, isoSecond } from "../../../core/brain/time.ts";@@ -43,6 +44,14 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {const { config, vault } = brainVerbContext(flags);const agent = resolveBrainAgent(flags, config);+ // Vault-configured fallback scope (`feedback.default_scope`). Applied+ // only when the call passes no explicit --scope. Compute one effective+ // scope so the signal, its mirror, and any force-confirmed preference+ // all land on the same scope.+ const defaultScope = loadFeedbackDefaultScopeSafe(vault);+ const effectiveScope = resolveEffectiveScope(flags["scope"] as string | undefined, defaultScope);+ const writeOpts = defaultScope !== undefined ? { defaultScope } : {};+let raw: string | undefined;const rawFile = flags["raw-file"] as string | undefined;if (rawFile) {@@ -73,7 +82,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {};let sigResult;try {- sigResult = writeSignal(vault, signalInput);+ sigResult = writeSignal(vault, signalInput, writeOpts);} catch (exc) {return fail(`failed to write signal: ${(exc as Error).message ?? exc}`);}@@ -81,7 +90,9 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {// primary write; surfaced only when the key is configured.const sharedNamespace = resolveSharedNamespace(config);const mirror =- sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, vault, signalInput);+ sharedNamespace === null+ ? undefined+ : mirrorSignal(sharedNamespace, vault, signalInput, writeOpts);try {appendLogEvent(vault, {@@ -112,7 +123,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {confirmed_at: now.toISOString(),status: BRAIN_PREFERENCE_STATUS.confirmed,evidenced_by: [`[[${sigResult.id}]]`],- ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),},{ overwrite: false },);diff --git a/src/core/brain/freshness.ts b/src/core/brain/freshness.tsindex c43e4197..4cd47638 100644--- a/src/core/brain/freshness.ts+++ b/src/core/brain/freshness.ts@@ -21,7 +21,7 @@*/import { createHash } from "node:crypto";-import { existsSync, readFileSync } from "node:fs";+import { existsSync, readFileSync, statSync } from "node:fs";import { isAbsolute, join } from "node:path";import { listVaultPages, parseFrontmatter } from "../vault.ts";@@ -71,6 +71,7 @@ function hashSource(vault: string, source: string): string {const path = resolveSourcePath(vault, source);try {if (!existsSync(path)) return MISSING_SOURCE_HASH;+ if ((statSync(path).mode & 0o444) === 0) return UNREADABLE_SOURCE_HASH;return sha256(readFileSync(path, "utf8"));} catch {// A transient permission / I/O failure is NOT a deleted source -diff --git a/src/core/brain/morning-brief.ts b/src/core/brain/morning-brief.tsindex ff787c5e..bdc8384f 100644--- a/src/core/brain/morning-brief.ts+++ b/src/core/brain/morning-brief.ts@@ -20,18 +20,22 @@ import { brainDirs } from "./paths.ts";import { parsePreference } from "./preference.ts";import { applyCharBudget } from "./recall-budget.ts";import { readLogDay } from "./log-jsonl.ts";-import { isoDate } from "./time.ts";+import { isoDate, relativeAge } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "./types.ts";export interface MorningBriefPreference {readonly id: string;readonly principle: string;readonly trimmed: boolean;+ /** Short relative-age label ("2d ago") of the preference's creation. */+ readonly ageLabel?: string;}export interface MorningBriefOpenQuestion {readonly topic: string;readonly domain: string;+ /** Short relative-age label of the reconcile event that raised it. */+ readonly ageLabel?: string;}export interface MorningBrief {@@ -85,21 +89,35 @@ function collectConfirmed(vault: string): ConfirmedPref[] {return out;}+interface ScannedOpenQuestion {+ readonly topic: string;+ readonly domain: string;+ readonly ts: string;+}++interface ScannedNote {+ readonly text: string;+ readonly ts: string;+}+interface LogScan {- readonly openQuestions: MorningBriefOpenQuestion[];- readonly notes: string[];+ readonly openQuestions: ScannedOpenQuestion[];+ readonly notes: ScannedNote[];}function scanRecentLog(vault: string, now: Date, lookbackDays: number): LogScan {- const openQuestions: MorningBriefOpenQuestion[] = [];- const notes: string[] = [];+ const openQuestions: ScannedOpenQuestion[] = [];+ const notes: ScannedNote[] = [];const seenTopics = new Set<string>();const dayMs = 24 * 60 * 60 * 1000;- // Newest day first so dedup keeps the most recent open question per topic.+ // Newest day and newest same-day entries first so dedup keeps the most recent+ // open question per topic.for (let i = 0; i <= lookbackDays; i++) {const date = isoDate(new Date(now.getTime() - i * dayMs));const entries = readLogDay(vault, date).entries;- for (const e of entries) {+ for (let j = entries.length - 1; j >= 0; j--) {+ const e = entries[j]!;+ const ts = typeof e.timestamp === "string" ? e.timestamp : "";if (e.eventType === BRAIN_LOG_EVENT_KIND.reconcile) {// Auto-resolutions carry a `resolution` field; only open// questions (no resolution) are surfaced to the operator.@@ -108,11 +126,11 @@ function scanRecentLog(vault: string, now: Date, lookbackDays: number): LogScanconst domain = typeof e.body["domain"] === "string" ? e.body["domain"] : "";if (topic && !seenTopics.has(topic)) {seenTopics.add(topic);- openQuestions.push({ topic, domain });+ openQuestions.push({ topic, domain, ts });}} else if (e.eventType === BRAIN_LOG_EVENT_KIND.note) {const text = typeof e.body["text"] === "string" ? e.body["text"] : "";- if (text) notes.push(text);+ if (text) notes.push({ text, ts });}}}@@ -123,6 +141,23 @@ const PREF_PREFIX = "pref:";const OQ_PREFIX = "oq:";const NOTE_PREFIX = "note:";+// Per-kind type tags stamped onto every rendered bullet so the+// session-start bundle reads as a scannable typed timeline rather than+// undifferentiated prose (v1.13.1 recent-activity presentation).+const TYPE_TAG_PREF = "pref";+const TYPE_TAG_OPEN = "open";+const TYPE_TAG_NOTE = "note";++/**+ * Render one timeline bullet: a Markdown list item carrying a type tag+ * and, when available, a short relative-age label. The age is omitted+ * (not shown as "Β· ") when `ageLabel` is empty β e.g. when the source+ * timestamp was missing or unparseable.+ */+function timelineBullet(type: string, text: string, ageLabel: string): string {+ return `- [${type}] ${text}${ageLabel ? ` Β· ${ageLabel}` : ""}`;+}+/*** Build the morning brief for a vault. Read-only; deterministic given* the vault and `opts.now`.@@ -148,7 +183,7 @@ export function buildMorningBrief(vault: string, opts: MorningBriefOptions): Morentries.push({ item: `${OQ_PREFIX}${q.topic}`, text: `${q.topic} (${q.domain})` });}for (let i = 0; i < notes.length; i++) {- entries.push({ item: `${NOTE_PREFIX}${i}`, text: notes[i]! });+ entries.push({ item: `${NOTE_PREFIX}${i}`, text: notes[i]!.text });}const budgeted = applyCharBudget(entries, {@@ -156,36 +191,59 @@ export function buildMorningBrief(vault: string, opts: MorningBriefOptions): MormaxTotalChars: opts.maxTotalChars,});+ // Lookups for relative-age labels: preferences by id, open questions+ // by topic, notes by their original (pre-budget) index. The budget+ // primitive preserves the `item` key, so each kept entry resolves+ // back to its source timestamp.+ const prefCreatedAtById = new Map(topPrefs.map((p) => [p.id, p.createdAt] as const));+ const oqByTopic = new Map(openQuestions.map((q) => [q.topic, q] as const));+const preferences: MorningBriefPreference[] = [];const keptQuestions: MorningBriefOpenQuestion[] = [];const keptNotes: string[] = [];+ // Per-note rendered bullets carry the age label; the public+ // `recentNotes` field stays `string[]` for back-compat with MCP+ // clients, so the age is attached only on the rendered `text` path.+ const noteBullets: string[] = [];for (const kept of budgeted.kept) {if (kept.item.startsWith(PREF_PREFIX)) {- preferences.push({- id: kept.item.slice(PREF_PREFIX.length),- principle: kept.text,- trimmed: kept.trimmed,- });+ const id = kept.item.slice(PREF_PREFIX.length);+ const ageLabel = relativeAge(prefCreatedAtById.get(id) ?? "", opts.now) || undefined;+ preferences.push({ id, principle: kept.text, trimmed: kept.trimmed, ageLabel });} else if (kept.item.startsWith(OQ_PREFIX)) {const topic = kept.item.slice(OQ_PREFIX.length);- const found = openQuestions.find((q) => q.topic === topic);- keptQuestions.push({ topic, domain: found?.domain ?? "" });+ const found = oqByTopic.get(topic);+ const ageLabel = relativeAge(found?.ts ?? "", opts.now) || undefined;+ keptQuestions.push({ topic, domain: found?.domain ?? "", ageLabel });} else if (kept.item.startsWith(NOTE_PREFIX)) {+ const idx = Number(kept.item.slice(NOTE_PREFIX.length));+ const ageLabel = relativeAge(notes[idx]?.ts ?? "", opts.now);keptNotes.push(kept.text);+ noteBullets.push(timelineBullet(TYPE_TAG_NOTE, kept.text, ageLabel));}}const sections: string[] = [];if (preferences.length > 0) {- sections.push(["## Top preferences", ...preferences.map((p) => `- ${p.principle}`)].join("\n"));+ sections.push(+ [+ "## Top preferences",+ ...preferences.map((p) => timelineBullet(TYPE_TAG_PREF, p.principle, p.ageLabel ?? "")),+ ].join("\n"),+ );}if (keptQuestions.length > 0) {sections.push(- ["## Open questions", ...keptQuestions.map((q) => `- ${q.topic} (${q.domain})`)].join("\n"),+ [+ "## Open questions",+ ...keptQuestions.map((q) =>+ timelineBullet(TYPE_TAG_OPEN, `${q.topic} (${q.domain})`, q.ageLabel ?? ""),+ ),+ ].join("\n"),);}- if (keptNotes.length > 0) {- sections.push(["## Recent notes", ...keptNotes.map((n) => `- ${n}`)].join("\n"));+ if (noteBullets.length > 0) {+ sections.push(["## Recent notes", ...noteBullets].join("\n"));}return Object.freeze({diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 53f59172..670a88fc 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -26,6 +26,7 @@ import type {BrainActiveConfig,BrainAnticipatoryConfig,BrainConfig,+ BrainFeedbackConfig,BrainGuardrailConfig,BrainHealthConfig,BrainHygieneConfig,@@ -50,6 +51,7 @@ import {SchemaVocabularyError,validateSchemaDeclarations,} from "./schema-vocab.ts";+import { SCOPE_MAX_LEN } from "./signal.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@@ -365,6 +367,21 @@ export function loadGuardrailsConfigSafe(vault: string): ResolvedBrainGuardrailC}}+/**+ * Load the configured `feedback.default_scope`, or `undefined` when the+ * config file is missing, malformed, or carries no feedback block. Used+ * by the feedback write surfaces so a vault without a full `brain init`+ * stays scope-less (byte-identical to pre-feature behaviour) instead of+ * throwing when the signal is recorded.+ */+export function loadFeedbackDefaultScopeSafe(vault: string): string | undefined {+ try {+ return loadBrainConfig(vault).feedback?.default_scope;+ } catch {+ return undefined;+ }+}+/*** Default `_brain.yaml` content. Mirrors Β§10 of the design doc. Used by* `brain init` and as the fallback inside `loadBrainConfig` when callers@@ -1553,6 +1570,7 @@ export function validateBrainConfigDetailed("notes","sessions","schema",+ "feedback",]);for (const key of Object.keys(obj)) {if (!known.has(key)) {@@ -1652,6 +1670,68 @@ export function validateBrainConfigDetailed(recall = Object.freeze(partial);}+ // Optional `feedback:` block (default-scope-feedback suite). Validates a+ // vault-default scope applied to feedback signal writes that omit an+ // explicit per-call scope. Constraints mirror the signal `scope` field+ // exactly (non-empty after trim, single-line, <= SCOPE_MAX_LEN) so a+ // configured default can never pass validation yet fail at write time.+ let feedback: BrainFeedbackConfig | undefined;+ if ("feedback" in obj) {+ const raw = obj["feedback"];+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw new BrainConfigError(+ `block must be a map of keys; got ${describe(raw)}`,+ "feedback",+ source,+ );+ }+ const rawMap = raw as Record<string, unknown>;+ const partial: { default_scope?: string } = {};+ if ("default_scope" in rawMap) {+ const value = rawMap["default_scope"];+ if (typeof value !== "string") {+ throw new BrainConfigError(+ `must be a string; got ${describe(value)}`,+ "feedback.default_scope",+ source,+ );+ }+ const trimmed = value.trim();+ if (trimmed === "") {+ throw new BrainConfigError(+ `must be a non-empty single-line scope slug`,+ "feedback.default_scope",+ source,+ );+ }+ if (/[\n\r]/.test(value)) {+ throw new BrainConfigError(+ `must be single-line (no newline characters)`,+ "feedback.default_scope",+ source,+ );+ }+ if (trimmed.length > SCOPE_MAX_LEN) {+ throw new BrainConfigError(+ `must be at most ${SCOPE_MAX_LEN} characters; got ${trimmed.length}`,+ "feedback.default_scope",+ source,+ );+ }+ partial.default_scope = trimmed;+ }+ // Forward-compat: unknown sub-keys under `feedback:` β warning.+ for (const key of Object.keys(rawMap)) {+ if (key !== "default_scope") {+ warnings.push({+ path: source ?? "<config>",+ message: `feedback.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }+ feedback = Object.freeze(partial);+ }+const config: BrainConfig = {schema_version: schemaVersion,primary_agent: primaryAgent,@@ -1688,6 +1768,7 @@ export function validateBrainConfigDetailed(...(hygiene !== undefined ? { hygiene } : {}),...(anticipatory !== undefined ? { anticipatory } : {}),...(recall !== undefined ? { recall } : {}),+ ...(feedback !== undefined ? { feedback } : {}),};return { config, warnings };diff --git a/src/core/brain/shared-namespace.ts b/src/core/brain/shared-namespace.tsindex 8ed9c293..714a881f 100644--- a/src/core/brain/shared-namespace.ts+++ b/src/core/brain/shared-namespace.ts@@ -21,7 +21,7 @@ import { basename, resolve } from "node:path";import { discoverConfig } from "../config.ts";import { appendLogEvent } from "./log.ts";-import { writeSignal, type WriteSignalInput } from "./signal.ts";+import { writeSignal, type WriteSignalInput, type WriteSignalOptions } from "./signal.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND } from "./types.ts";@@ -43,10 +43,11 @@ export function mirrorSignal(sharedVault: string,originVault: string,input: WriteSignalInput,+ options: WriteSignalOptions = {},): MirrorOutcome {if (isSelfMirror(sharedVault, originVault)) return "failed";try {- writeSignal(sharedVault, { ...input, origin_vault: basename(originVault) });+ writeSignal(sharedVault, { ...input, origin_vault: basename(originVault) }, options);return "ok";} catch {return "failed";diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 3f7c4cb7..906b5f4b 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -103,6 +103,34 @@ export interface WriteSignalInput {export interface WriteSignalOptions {/** Maximum collision suffixes to try; defaults to allocateSlug's cap. */readonly maxSlugAttempts?: number;+ /**+ * Vault-configured fallback scope (`feedback.default_scope`). Applied+ * only when the input carries no explicit non-empty `scope`; an+ * explicit per-call scope always wins. Absent: the historical+ * scope-less behaviour is byte-identical.+ */+ readonly defaultScope?: string;+}++/**+ * Resolve the effective signal scope from an explicit per-call value and+ * a configured fallback default. Precedence: a non-empty (after trim)+ * explicit scope wins; otherwise a non-empty default is used; otherwise+ * `undefined` (the signal stays scope-less). The returned value is+ * trimmed but otherwise unsanitised β `writeSignal` runs it through the+ * same field sanitiser as any explicit scope.+ *+ * Exported so the CLI / MCP surfaces can compute one effective scope and+ * reuse it for a force-confirmed preference write, keeping the signal and+ * its preference on the same scope.+ */+export function resolveEffectiveScope(+ explicit: string | undefined,+ fallback: string | undefined,+): string | undefined {+ if (explicit !== undefined && explicit.trim() !== "") return explicit.trim();+ if (fallback !== undefined && fallback.trim() !== "") return fallback.trim();+ return undefined;}export interface WriteSignalResult {@@ -138,13 +166,22 @@ export function writeSignal(input: WriteSignalInput,options: WriteSignalOptions = {},): WriteSignalResult {+ // Resolve the effective scope FIRST: an explicit non-empty per-call+ // scope wins; otherwise the configured `defaultScope` fallback applies;+ // otherwise the field is dropped so the signal stays scope-less and+ // byte-identical to the historical no-default path.+ const { scope: explicitScope, ...restInput } = input;+ const effectiveScope = resolveEffectiveScope(explicitScope, options.defaultScope);+ const resolvedInput: WriteSignalInput =+ effectiveScope === undefined ? restInput : { ...restInput, scope: effectiveScope };+// Sanitise free-form fields BEFORE the required-field check so an// input that is purely C0-control characters lands in the// "missing-field" branch rather than smuggling itself into YAML.// `topic`, `slug`, `agent`, `date`, `signal` are constrained by// their own validators (slug rules / ISO date / enum) and are// already rejected if they carry junk β don't double-process them.- const sanitised = sanitiseSignalInput(input);+ const sanitised = sanitiseSignalInput(resolvedInput);for (const field of REQUIRED_INPUT_FIELDS) {const value = sanitised[field];@@ -252,7 +289,9 @@ export function writeSignal(* carry paragraphs. `scope` is a short slug-adjacent tag.*/const PRINCIPLE_MAX_LEN = 512;-const SCOPE_MAX_LEN = 128;+/** Hard cap on a signal `scope` slug; shared with config validation so a+ * configured `feedback.default_scope` cannot diverge from the write rule. */+export const SCOPE_MAX_LEN = 128;const RAW_MAX_LEN = 4096;const SOURCE_ITEM_MAX_LEN = 512;diff --git a/src/core/brain/time.ts b/src/core/brain/time.tsindex 933168f3..eb9c7c89 100644--- a/src/core/brain/time.ts+++ b/src/core/brain/time.ts@@ -25,3 +25,39 @@ export function isoSecond(d: Date = new Date()): string {export function isoDate(d: Date = new Date()): string {return d.toISOString().slice(0, 10);}++/**+ * Render the gap between an ISO-8601 timestamp and `now` as a short,+ * human-readable relative-age label β "just now", "3m ago", "2h ago",+ * "5d ago", "2w ago", "3mo ago", "1y ago". Used by session-start+ * surfaces (the morning brief's typed recent-activity timeline) so an+ * operator can scan recency at a glance without parsing absolute times.+ *+ * Deterministic given the two timestamps. A future `isoTimestamp` clamps+ * to "just now" so a clock skew cannot produce a nonsensical "-3m ago".+ * Returns the empty string for an unparseable input so call sites can+ * omit the label without a try/catch at every one of them.+ *+ * Accepts both whole-second ISO (`2026-05-01T00:00:00Z`) and calendar-day+ * (`2026-05-01`) shapes; `Date.parse` handles both.+ */+export function relativeAge(isoTimestamp: string, now: Date = new Date()): string {+ const ts = Date.parse(isoTimestamp);+ if (Number.isNaN(ts)) return "";+ let diffMs = now.getTime() - ts;+ if (diffMs < 0) diffMs = 0;+ const sec = Math.floor(diffMs / 1000);+ if (sec < 60) return "just now";+ const min = Math.floor(sec / 60);+ if (min < 60) return `${min}m ago`;+ const hr = Math.floor(min / 60);+ if (hr < 24) return `${hr}h ago`;+ const day = Math.floor(hr / 24);+ if (day < 7) return `${day}d ago`;+ const wk = Math.floor(day / 7);+ if (wk < 5) return `${wk}w ago`;+ const mo = Math.floor(day / 30);+ if (day < 365) return `${mo}mo ago`;+ const yr = Math.floor(day / 365);+ return `${yr}y ago`;+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 0eb42b84..7bc4e2f8 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -988,6 +988,25 @@ export interface BrainGuardrailConfig {readonly owner_scoped_facts?: boolean;}+/**+ * Optional `feedback:` block (default-scope-feedback suite). Supplies a+ * vault-default `scope` for feedback signal writes that omit an explicit+ * per-call scope. Distinct from `owner_scoped_facts` and the vault+ * guardrails, which govern fact visibility β this only categorizes+ * freshly-recorded feedback signals.+ */+export interface BrainFeedbackConfig {+ /**+ * Default scope applied to `brain_feedback` / `o2b brain feedback`+ * writes that pass no explicit `scope`. An explicit per-call scope+ * always wins. Validated against the same constraints as a signal+ * `scope` field: non-empty after trim, single-line, and at most the+ * 128-character scope cap. Absent: scope-less calls stay scope-less,+ * byte-identical to prior behaviour.+ */+ readonly default_scope?: string;+}+/*** Optional runtime schema vocabulary declarations (v0.25.0 foundation).* These are taxonomy tokens, not replacements for operational lifecycle@@ -1089,6 +1108,12 @@ export interface BrainConfig {* consumers resolve built-ins through `resolveSchemaVocabulary`.*/readonly schema?: BrainSchemaConfig;+ /**+ * Optional `feedback:` block (default-scope-feedback suite). Supplies+ * a default scope for feedback signal writes that omit an explicit+ * per-call scope. Absent: scope-less calls stay scope-less.+ */+ readonly feedback?: BrainFeedbackConfig;/*** Optional `hygiene:` block (continuity-hygiene-freshness suite).* Tunes the hygiene pipeline: the external conflict-resolver commanddiff --git a/src/core/brain/write-session/engine.ts b/src/core/brain/write-session/engine.tsindex a76fbc0e..5196ecdd 100644--- a/src/core/brain/write-session/engine.ts+++ b/src/core/brain/write-session/engine.ts@@ -26,6 +26,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";import { dirname, join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { ensureInsideVault } from "../../path-safety.ts";import { appendLogEvent } from "../log.ts";import { loadSchemaPack } from "../schema-pack.ts";import { BRAIN_LOG_EVENT_KIND } from "../types.ts";@@ -337,7 +338,13 @@ export function commitArtifact(artifact: string,now: string,): WriteSessionEnvelope {- const absolute = join(vault, session.targetPath);+ // Last-line-of-defense containment: `validateTargetPath` runs at open+ // time and is purely lexical (it rejects `..`/backslashes/NUL but is+ // blind to symlinked ancestors), and the persisted session record is+ // decoupled from that check. Re-resolve at the write chokepoint so a+ // target that lands outside the vault - e.g. `Brain/<symlink>/x.md`+ // whose ancestor links out - is rejected before any mkdir/read/write.+ const absolute = ensureInsideVault(join(vault, session.targetPath), vault);// Last-line-of-defense collision guard: submit-time checks cannot// cover the window between a needs-review park and the operator's// approve - if the target appeared meanwhile, `create` must stilldiff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 29f37aec..016d7226 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -22,7 +22,8 @@ import {validateDreamBundle,} from "../../core/brain/dream-stage.ts";import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";-import { writeSignal } from "../../core/brain/signal.ts";+import { resolveEffectiveScope, writeSignal } from "../../core/brain/signal.ts";+import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";import { writePreference } from "../../core/brain/preference.ts";import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";import { isoDate, isoSecond } from "../../core/brain/time.ts";@@ -88,6 +89,14 @@ async function toolBrainFeedback(const createdAt = isoSecond(now);const slug = deriveSlug(topic);+ // Vault-configured fallback scope (`feedback.default_scope`). Applied+ // only when the call passes no explicit scope. Compute one effective+ // scope so the signal, its mirror, and any force-confirmed preference+ // all land on the same scope.+ const defaultScope = loadFeedbackDefaultScopeSafe(ctx.vault);+ const effectiveScope = resolveEffectiveScope(scope, defaultScope);+ const writeOpts = defaultScope !== undefined ? { defaultScope } : {};+// 1. Always write the signal to inbox/. Mirrors the CLI handler so the// audit trail in `Brain/log/` and `inbox/processed/` stays consistent// across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY@@ -104,12 +113,14 @@ async function toolBrainFeedback(...(source && source.length > 0 ? { source: [...source] } : {}),...(raw ? { raw } : {}),};- const sigResult = writeSignal(ctx.vault, signalInput);+ const sigResult = writeSignal(ctx.vault, signalInput, writeOpts);// t_936a1a61: fail-soft mirror into the shared namespace AFTER the// primary write; `mirror` is reported only when the key is configured.const sharedNamespace = resolveSharedNamespace(ctx.configPath);const mirror =- sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, ctx.vault, signalInput);+ sharedNamespace === null+ ? undefined+ : mirrorSignal(sharedNamespace, ctx.vault, signalInput, writeOpts);try {appendLogEvent(ctx.vault, {@@ -141,7 +152,7 @@ async function toolBrainFeedback(status: BRAIN_PREFERENCE_STATUS.confirmed,evidenced_by: [`[[${sigResult.id}]]`],confirmed_at: createdAt,- ...(scope ? { scope } : {}),+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),});try {// Offset by 1s so the force-confirmed event sorts after the feedbackdiff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.tsindex 12489937..f178a11d 100644--- a/tests/cli/brain.test.ts+++ b/tests/cli/brain.test.ts@@ -318,6 +318,126 @@ describe("brain feedback", () => {});});+describe("brain feedback β default_scope", () => {+ /** Append a feedback block to the vault's _brain.yaml. */+ function setDefaultScope(scope: string): void {+ const yamlPath = join(vault, "Brain", "_brain.yaml");+ const existing = readFileSync(yamlPath, "utf8");+ writeFileSync(yamlPath, `${existing}\nfeedback:\n default_scope: ${scope}\n`, "utf8");+ }++ function readInbox(): string {+ const inbox = readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md"));+ expect(inbox.length).toBe(1);+ return readFileSync(join(vault, "Brain", "inbox", inbox[0]!), "utf8");+ }++ test("default_scope applies when no --scope is passed", async () => {+ await bootstrap();+ setDefaultScope("coding");+ const r = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "use-tabs",+ "--signal",+ "positive",+ "--principle",+ "Indent with tabs",+ "--agent",+ "claude",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const body = readInbox();+ expect(body).toContain("scope: coding");+ expect(body).toContain("brain/scope/coding");+ });++ test("explicit --scope overrides default_scope", async () => {+ await bootstrap();+ setDefaultScope("coding");+ const r = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "doc-rule",+ "--signal",+ "positive",+ "--principle",+ "Document public APIs",+ "--scope",+ "docs",+ "--agent",+ "claude",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const body = readInbox();+ expect(body).toContain("scope: docs");+ expect(body).not.toContain("scope: coding");+ });++ test("no default and no --scope omits scope (byte-identical)", async () => {+ await bootstrap();+ const r = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "plain-rule",+ "--signal",+ "positive",+ "--principle",+ "A scope-less rule",+ "--agent",+ "claude",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const body = readInbox();+ expect(body).not.toContain("scope:");+ expect(body).not.toContain("brain/scope/");+ });++ test("force-confirmed preference inherits the default scope", async () => {+ await bootstrap();+ setDefaultScope("coding");+ const r = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "fc-rule",+ "--signal",+ "positive",+ "--principle",+ "Force confirmed with default scope",+ "--force-confirmed",+ "--agent",+ "claude",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(r.returncode).toBe(0);+ const pref = readFileSync(join(vault, "Brain", "preferences", "pref-fc-rule.md"), "utf8");+ expect(pref).toContain("scope: coding");+ });+});+describe("brain dream", () => {test("happy path on empty vault returns no-op", async () => {await bootstrap();diff --git a/tests/core/brain.paths.test.ts b/tests/core/brain.paths.test.tsindex 565ad6da..5031f503 100644--- a/tests/core/brain.paths.test.ts+++ b/tests/core/brain.paths.test.ts@@ -91,6 +91,18 @@ describe("validateSlug", () => {expect(validateSlug("alpha_beta-2")).toBe("alpha_beta-2");});+ test("admits email-style and plus-addressed identifiers", () => {+ // The structural whitelist must keep passing `@` and `+` so a+ // caller-supplied identity (email, plus-addressed alias) can still+ // become a file basename without escaping its directory. Pinned so a+ // later sanitization tweak cannot silently drop these characters.+ expect(validateSlug("[email protected]")).toBe("[email protected]");+ expect(validateSlug("[email protected]")).toBe("[email protected]");+ expect(validateSlug("first.last+filter")).toBe("first.last+filter");+ // A single embedded dot is fine; only the `..` traversal token is not.+ expect(validateSlug("v1.2.3")).toBe("v1.2.3");+ });+test("rejects path separators", () => {expect(() => validateSlug("a/b")).toThrow(/path separators/);expect(() => validateSlug("a\\b")).toThrow(/path separators/);diff --git a/tests/core/brain.policy.test.ts b/tests/core/brain.policy.test.tsindex fd60b8a0..ad099439 100644--- a/tests/core/brain.policy.test.ts+++ b/tests/core/brain.policy.test.ts@@ -198,6 +198,76 @@ describe("validateBrainConfig β schema block", () => {});});+describe("validateBrainConfig β feedback block", () => {+ test("absent feedback block leaves config.feedback undefined", () => {+ expect(DEFAULT_BRAIN_CONFIG).not.toHaveProperty("feedback");+ const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");+ expect(cfg.feedback).toBeUndefined();+ });++ test("accepts a valid default_scope", () => {+ const cfg = validateBrainConfig(+ parseBrainYaml("schema_version: 1\nfeedback:\n default_scope: coding\n"),+ "<test>",+ );+ expect(cfg.feedback?.default_scope).toBe("coding");+ });++ test("empty feedback block leaves default_scope undefined", () => {+ const cfg = validateBrainConfig({ schema_version: 1, feedback: {} }, "<test>");+ expect(cfg.feedback).toBeDefined();+ expect(cfg.feedback?.default_scope).toBeUndefined();+ });++ test("unknown feedback subkeys warn without failing validation", () => {+ const result = validateBrainConfigDetailed(+ parseBrainYaml(+ "schema_version: 1\nfeedback:\n default_scope: coding\n typo_scope: research\n",+ ),+ "<test>",+ );++ expect(result.config.feedback?.default_scope).toBe("coding");+ expect(result.warnings.map((warning) => warning.message)).toContain(+ "feedback.typo_scope: unknown field ignored (forward-compat)",+ );+ });++ test("rejects a non-string default_scope", () => {+ expect(() =>+ validateBrainConfig(+ parseBrainYaml("schema_version: 1\nfeedback:\n default_scope: 42\n"),+ "<test>",+ ),+ ).toThrow(/feedback\.default_scope/);+ });++ test("rejects a blank default_scope", () => {+ expect(() =>+ validateBrainConfig(+ parseBrainYaml("schema_version: 1\nfeedback:\n default_scope: ' '\n"),+ "<test>",+ ),+ ).toThrow(/feedback\.default_scope/);+ });++ test("rejects an over-long default_scope (>128 chars)", () => {+ const huge = "x".repeat(129);+ expect(() =>+ validateBrainConfig(+ parseBrainYaml(`schema_version: 1\nfeedback:\n default_scope: "${huge}"\n`),+ "<test>",+ ),+ ).toThrow(/feedback\.default_scope/);+ });++ test("rejects a non-map feedback block", () => {+ expect(() =>+ validateBrainConfig(parseBrainYaml("schema_version: 1\nfeedback: not-a-map\n"), "<test>"),+ ).toThrow(/feedback/);+ });+});+describe("validateBrainConfig β primary_agent", () => {test("absent β null (default)", () => {const cfg = validateBrainConfig({ schema_version: 1 }, "<test>");diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.tsindex 45168c23..2febaa12 100644--- a/tests/core/brain.signal.test.ts+++ b/tests/core/brain.signal.test.ts@@ -3,7 +3,12 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { parseSignal, writeSignal, type WriteSignalInput } from "../../src/core/brain/signal.ts";+import {+ parseSignal,+ resolveEffectiveScope,+ writeSignal,+ type WriteSignalInput,+} from "../../src/core/brain/signal.ts";let tmp: string;@@ -116,6 +121,59 @@ describe("writeSignal + parseSignal roundtrip", () => {});});+describe("resolveEffectiveScope β precedence rule", () => {+ test("explicit non-empty scope wins over a default", () => {+ expect(resolveEffectiveScope("docs", "coding")).toBe("docs");+ });+ test("default applies when explicit is undefined", () => {+ expect(resolveEffectiveScope(undefined, "coding")).toBe("coding");+ });+ test("default applies when explicit is whitespace-only", () => {+ expect(resolveEffectiveScope(" ", "coding")).toBe("coding");+ });+ test("returns undefined when neither is set", () => {+ expect(resolveEffectiveScope(undefined, undefined)).toBeUndefined();+ });+ test("returns undefined when both are whitespace/empty", () => {+ expect(resolveEffectiveScope(" ", "")).toBeUndefined();+ });+ test("trims the chosen value", () => {+ expect(resolveEffectiveScope(" docs ", undefined)).toBe("docs");+ expect(resolveEffectiveScope(undefined, " coding ")).toBe("coding");+ });+});++describe("writeSignal β defaultScope option", () => {+ test("applies the default when no explicit scope is given", () => {+ const input = { ...baseInput({ slug: "default-scope" }) } as Record<string, unknown>;+ delete input["scope"];+ const r = writeSignal(tmp, input as unknown as WriteSignalInput, { defaultScope: "coding" });+ const parsed = parseSignal(r.path);+ expect(parsed.scope).toBe("coding");+ expect(parsed.tags).toContain("brain/scope/coding");+ });++ test("explicit scope overrides the default", () => {+ const r = writeSignal(tmp, baseInput({ slug: "explicit-wins", scope: "writing" }), {+ defaultScope: "coding",+ });+ const parsed = parseSignal(r.path);+ expect(parsed.scope).toBe("writing");+ expect(parsed.tags).toContain("brain/scope/writing");+ expect(parsed.tags).not.toContain("brain/scope/coding");+ });++ test("no default and no explicit scope omits the scope frontmatter (byte-identical)", () => {+ const noScope = { ...baseInput({ slug: "no-scope" }) } as Record<string, unknown>;+ delete noScope["scope"];+ const withDefault = writeSignal(tmp, noScope as unknown as WriteSignalInput, {});+ const text = readFileSync(withDefault.path, "utf8");+ expect(text).not.toContain("scope:");+ expect(text).not.toContain("brain/scope/");+ expect(parseSignal(withDefault.path).scope).toBeUndefined();+ });+});+describe("writeSignal β wikilink preservation", () => {test("wikilink strings in source[] survive parse β write β parse unchanged", () => {const input = baseInput({diff --git a/tests/core/brain.time.test.ts b/tests/core/brain.time.test.tsnew file mode 100644index 00000000..c69596e5--- /dev/null+++ b/tests/core/brain.time.test.ts@@ -0,0 +1,30 @@+/**+ * Brain time helpers.+ */++import { describe, expect, test } from "bun:test";++import { relativeAge } from "../../src/core/brain/time.ts";++const now = new Date("2026-05-29T12:00:00Z");++describe("relativeAge", () => {+ test("formats recent gaps with compact labels", () => {+ expect(relativeAge("2026-05-29T11:59:30Z", now)).toBe("just now");+ expect(relativeAge("2026-05-29T11:57:00Z", now)).toBe("3m ago");+ expect(relativeAge("2026-05-29T09:00:00Z", now)).toBe("3h ago");+ expect(relativeAge("2026-05-24T12:00:00Z", now)).toBe("5d ago");+ expect(relativeAge("2026-05-08T12:00:00Z", now)).toBe("3w ago");+ expect(relativeAge("2026-02-28T12:00:00Z", now)).toBe("3mo ago");+ });++ test("does not report 0 years before the first full year", () => {+ expect(relativeAge("2025-06-03T12:00:00Z", now)).toBe("12mo ago");+ expect(relativeAge("2025-05-29T12:00:00Z", now)).toBe("1y ago");+ });++ test("omits invalid timestamps and clamps future timestamps", () => {+ expect(relativeAge("not-a-date", now)).toBe("");+ expect(relativeAge("2026-05-29T12:01:00Z", now)).toBe("just now");+ });+});diff --git a/tests/core/brain/morning-brief.test.ts b/tests/core/brain/morning-brief.test.tsindex 9e57c6f1..982982b5 100644--- a/tests/core/brain/morning-brief.test.ts+++ b/tests/core/brain/morning-brief.test.ts@@ -96,6 +96,29 @@ describe("buildMorningBrief", () => {expect(brief.recentNotes.some((n) => n.includes("lifecycle suite"))).toBe(true);});+ test("renders typed timeline bullets with relative ages", () => {+ confirmedPref("fresh", 0.9);+ appendLogEvent(vault, {+ timestamp: "2026-05-28T09:00:00Z",+ eventType: "reconcile",+ body: { topic: "commit-style", domain: "claims", reason: "claims-needs-operator" },+ });+ appendLogEvent(vault, {+ timestamp: "2026-05-29T10:00:00Z",+ eventType: "note",+ body: { text: "Finished timeline review", agent: "codex" },+ });++ const brief = buildMorningBrief(vault, { now, topK: 5, lookbackDays: 7 });++ expect(brief.preferences[0]?.ageLabel).toBe("4w ago");+ expect(brief.openQuestions[0]).toMatchObject({ topic: "commit-style", ageLabel: "1d ago" });+ expect(brief.recentNotes).toEqual(["Finished timeline review"]);+ expect(brief.text).toContain("- [pref] Principle fresh Β· 4w ago");+ expect(brief.text).toContain("- [open] commit-style (claims) Β· 1d ago");+ expect(brief.text).toContain("- [note] Finished timeline review Β· 2h ago");+ });+test("honours the total character budget", () => {confirmedPref("a", 0.9);confirmedPref("b", 0.8);diff --git a/tests/core/brain/write-session/engine.test.ts b/tests/core/brain/write-session/engine.test.tsindex d720ce9f..a0cbf3d3 100644--- a/tests/core/brain/write-session/engine.test.ts+++ b/tests/core/brain/write-session/engine.test.ts@@ -4,7 +4,15 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -230,3 +238,22 @@ test("unknown session id is a structured error", () => {submitToSession(vault, { sessionId: "ws-20990101-000000", artifact: GOOD, now: NOW }),).toThrow(WriteSessionRequestError);});++test("commit refuses a target whose Brain ancestor is a symlink out of the vault", () => {+ // `validateTargetPath` runs at open time and is purely lexical: a+ // path like `Brain/escape/adr.md` is clean, so the session opens.+ // Only the write chokepoint can see that `Brain/escape` is a symlink+ // pointing outside the vault. The containment guard must reject the+ // commit before any mkdir/write lands the file on the symlink target.+ const outside = join(tmp, "outside");+ mkdirSync(outside, { recursive: true });+ symlinkSync(outside, join(vault, "Brain", "escape"), "dir");++ const opened = open({ targetPath: "Brain/escape/adr.md" });+ expect(() =>+ submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: NOW }),+ ).toThrow(/escapes vault/);++ // Fail-closed: nothing was written through the symlink.+ expect(existsSync(join(outside, "adr.md"))).toBe(false);+});diff --git a/tests/mcp/brain-trigger-tool.test.ts b/tests/mcp/brain-trigger-tool.test.tsindex 9154456c..591af402 100644--- a/tests/mcp/brain-trigger-tool.test.ts+++ b/tests/mcp/brain-trigger-tool.test.ts@@ -15,7 +15,7 @@ import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/toollet tmp: string;let vault: string;let ctx: ServerContext;-const NOW = new Date("2026-06-03T10:00:00Z");+const NOW = new Date("2099-06-03T10:00:00Z");const CANDIDATE: InsightCandidate = {kind: "contradiction",diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.tsindex 82c8237f..c574824a 100644--- a/tests/mcp/brain.test.ts+++ b/tests/mcp/brain.test.ts@@ -221,6 +221,77 @@ describe("brain_feedback", () => {});});+describe("brain_feedback β default_scope", () => {+ function setDefaultScope(scope: string): void {+ const yamlPath = join(vault, "Brain", "_brain.yaml");+ const existing = readFileSync(yamlPath, "utf8");+ atomicWriteFileSync(yamlPath, `${existing}\nfeedback:\n default_scope: ${scope}\n`);+ }++ test("applies the default scope when none is passed", async () => {+ setDefaultScope("coding");+ const server = makeServer();+ await initialize(server);+ const r = await call(server, "brain_feedback", {+ topic: "default-applies",+ signal: "positive",+ principle: "Inherit the default scope.",+ });+ expect(r.result.isError).toBe(false);+ const s = r.result.structuredContent;+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).toContain("scope: coding");+ expect(text).toContain("brain/scope/coding");+ });++ test("explicit scope overrides the default", async () => {+ setDefaultScope("coding");+ const server = makeServer();+ await initialize(server);+ const r = await call(server, "brain_feedback", {+ topic: "explicit-overrides",+ signal: "positive",+ principle: "Explicit scope wins.",+ scope: "docs",+ });+ const s = r.result.structuredContent;+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).toContain("scope: docs");+ expect(text).not.toContain("scope: coding");+ });++ test("no default + no explicit scope omits the scope frontmatter", async () => {+ const server = makeServer();+ await initialize(server);+ const r = await call(server, "brain_feedback", {+ topic: "scopeless",+ signal: "positive",+ principle: "Stay scope-less.",+ });+ const s = r.result.structuredContent;+ const text = readFileSync(join(vault, s.path), "utf8");+ expect(text).not.toContain("scope:");+ expect(text).not.toContain("brain/scope/");+ });++ test("force_confirmed preference inherits the default scope", async () => {+ setDefaultScope("coding");+ const server = makeServer();+ await initialize(server);+ const r = await call(server, "brain_feedback", {+ topic: "fc-default",+ signal: "positive",+ principle: "Force-confirmed inherits default scope.",+ force_confirmed: true,+ });+ const s = r.result.structuredContent;+ expect(s.kind).toBe("preference");+ const prefFile = preferencePath(vault, "fc-default");+ const text = readFileSync(prefFile, "utf8");+ expect(text).toContain("scope: coding");+ });+});+// ---------------------------------------------------------------------------// brain_dream// ---------------------------------------------------------------------------