Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
v0.10.7: Agent logging discipline tail β writer MCP split, daily cron, claude-memory bridge
Sol Aitkena01ea89b6c5d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex b8a92a8b..ee5c80e9 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.6",+ "version": "0.10.7","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 3396eb42..89025359 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.6",+ "version": "0.10.7","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/.mcp.json b/.mcp.jsonindex f9b03c70..c952dcea 100644--- a/.mcp.json+++ b/.mcp.json@@ -3,6 +3,11 @@"open-second-brain": {"command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b","args": ["mcp"]+ },+ "open-second-brain-writer": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp", "--scope", "writer"],+ "alwaysLoad": true}}}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 268e2336..fdba265a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,89 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.10.7] - 2026-05-18++Closes the remaining Β§30 (Agent logging discipline) work from+`Projects/OpenSecondBrain/Features/_summary.md`. Three independent+tracks ship together under one release.++### Added++- Β§30 Β§B - Writer MCP server split. A second `.mcp.json` entry+ `open-second-brain-writer` exposes `brain_feedback` and+ `brain_apply_evidence` with Claude Code's `alwaysLoad: true`+ flag so the agent never pays the ToolSearch round-trip before+ recording a taste signal or evidence event. The full MCP+ surface stays deferred under the existing `open-second-brain`+ entry. `o2b mcp` gains `--scope writer|full` (default `full`).+- Β§30 Β§D - Daily discipline cron. New `bin/o2b-discipline-report`+ + `o2b discipline {report|install|uninstall}` build a+ deterministic Telegram MarkdownV2 block comparing brain-event+ counts per agent (parsed from `Brain/log/<date>.md`) against+ runtime-agnostic activity proxies: git activity on watched+ repos, mtime walk on watched non-repo paths, vault delta on+ `Brain/inbox/`, `Brain/preferences/`, `Brain/retired/`. Status+ `ok | info | alert` is binary; numeric ratios were rejected in+ design as noise-prone. Hermes cron job installable with+ `o2b discipline install [--telegram-target] [--at]` (job id+ derived from sha256(vault_path) so multiple vaults on one host+ do not collide). No LLM in the report path.+- Β§30 Β§E - Claude Code MEMORY to Brain bridge. New verb+ `o2b brain import-claude-memory [--memory <path>]+ [--dry-run | --apply] [--yes] [--json]+ [--allow-arbitrary-memory-path]` reads `metadata.type: feedback`+ entries from a Claude Code memory directory and writes them as+ confirmed Brain preferences with a sidecar manifest+ `Brain/.imports/claude-memory.json` for idempotency.+ UPDATE preserves accumulated evidence (`_applied_count`,+ `_violated_count`, `_evidenced_by`, `_last_evidence_at`,+ `_confirmed_at`, `unconfirmed_until`, `pinned`, `scope`).+ CONFLICT surfaces (preference exists without a manifest entry)+ require manual resolution - never silent overwrites. Pre-apply+ snapshot via the v0.10.6 manifest infrastructure; rollback via+ `o2b brain rollback import-claude-memory-<ts>`.+- New module `src/core/discipline/` (`report.ts`, `log-counts.ts`,+ `window.ts`, `activity-git.ts`, `activity-mtime.ts`,+ `vault-delta.ts`, `decision.ts`, `render.ts`, `telegram.ts`).+- New CLI module `src/cli/discipline.ts` + `src/cli/discipline-install.ts`.+- New entry `bin/o2b-discipline-report` + `scripts/discipline-report.ts`.+- New `BrainConfig.discipline_report` optional section+ (`enabled`, `timezone`, `watched_paths`, `known_agents`).+- New Β§E modules under `src/core/brain/`:+ `claude-memory-parser.ts`, `claude-memory-manifest.ts`,+ `claude-memory-plan.ts`, `claude-memory-render.ts`,+ `claude-memory-paths.ts`, `import-claude-memory.ts`.+- `BRAIN_LOG_EVENT_KIND.importClaudeMemory = "import-claude-memory"`.++### Changed++- `src/mcp/tools.ts:buildToolTable` accepts an optional+ `scope: "full" | "writer"` parameter; default unchanged.+- `MCPServer` ctor accepts an optional second `runtimeOpts`+ argument with `{ serverName, scope }`; defaults reproduce the+ v0.10.6 behavior.+- `serveStdio` / `serveStdioFromString` now build `MCPServer`+ internally and forward `runtimeOpts`.+- `buildInstructions` accepts the same `scope` field; the writer+ branch returns a short, focused instructions block naming only+ the two writer tools.+- `parseBrainYaml` (in `src/core/brain/policy.ts`) now handles+ block-style nested lists (`key:` followed by indented `- item`)+ so the new `discipline_report.watched_paths` / `known_agents`+ arrays parse correctly.++### Migration++No vault data migration is required. Existing vaults run Β§D+with the feature disabled (default) until the operator adds the+`discipline_report` section to `Brain/_brain.yaml` and runs+`o2b discipline install`. Β§E is opt-in (operator runs the verb);+the sidecar manifest `Brain/.imports/claude-memory.json` is+created on first `--apply`. Pre-v0.10.7 installations with a+single MCP server entry continue to work; the second+`open-second-brain-writer` entry does not appear until the new+`.mcp.json` is reinstalled.+## [0.10.6] - 2026-05-18Five tracks from `Projects/OpenSecondBrain/Features/_summary` shippeddiff --git a/README.md b/README.mdindex 2c81dd0f..5bf331e6 100644--- a/README.md+++ b/README.md@@ -138,8 +138,14 @@ o2b brain doctor Check Brain-specific invariants (status-vs-folder,o2b brain backlinks List inbound references to a Brain artifact ido2b brain scan-inline Capture `@osb` markers from vault markdown files (Daily/, project notes, β¦)o2b brain import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)+o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidenceo2b brain migrate-frontmatter (CLI-only) Rewrite legacy `status:` keys to `_status:`+# Discipline (daily logging-discipline cron)+o2b discipline report Render the daily MarkdownV2 block to stdout (brain-event counts per agent vs git/mtime activity); status ok | info | alert+o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC+o2b discipline uninstall Remove the cron job+# Pay Memoryo2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/o2b append-payment-receipt Save a Markdown receipt for a paid API call@@ -184,6 +190,24 @@ the plugin-bundled `.mcp.json`, OpenClaw not at all (tools registerednatively). The exact wiring is in `install.md`; the protocol,schemas, and lifecycle details are in [`docs/mcp.md`](docs/mcp.md).+### Writer split (Claude Code 2.1.121+)++The plugin's `.mcp.json` ships **two** MCP-server entries:++- `open-second-brain` β the full surface (17 tools); subject to+ Claude Code's `MCPSearch` tool-search deferral when MCP+ definitions push the system prompt past 10% of the context window.+- `open-second-brain-writer` β a minimal surface of exactly two+ tools, `brain_feedback` and `brain_apply_evidence`, marked+ `alwaysLoad: true`. The agent records taste signals and evidence+ events without a ToolSearch round-trip on every session boot.++Both servers reuse the same backing CLI (`o2b mcp --scope writer`+vs the default `--scope full`). Handlers are byte-identical; the+writer-mode instructions text explicitly tells the agent to prefer+the writer copy over any duplicate the full server still exposes+(both call the same code path).+## Lifecycle hooks (Claude Code & Codex)The plugin bundles a `hooks/hooks.json` that both runtimes auto-load.@@ -238,10 +262,42 @@ The Brain verbs in full: `init`, `feedback`, `dream`,`apply-evidence`, `digest`, `query`, `reject`, `merge`, `pin`,`unpin`, `set-primary`, `protect`, `unprotect`, `snapshot diff`,`rollback`, `upgrade`, `export`, `doctor`, `backlinks`,-`scan-inline`, `import-session`, `migrate-frontmatter`,-`explorer`. Seven are mirrored as MCP tools (`brain_*`); the rest-are intentionally CLI-only because they change the protected set,-overwrite vault state, or are operator-only maintenance commands.+`scan-inline`, `import-session`, `import-claude-memory`,+`migrate-frontmatter`, `explorer`. Seven are mirrored as MCP tools+(`brain_*`); the rest are intentionally CLI-only because they+change the protected set, overwrite vault state, or are+operator-only maintenance commands.++### Discipline (daily logging sanity-check)++`o2b discipline report` renders a deterministic Telegram MarkdownV2+block comparing brain-event counts per agent (parsed from+`Brain/log/<yesterday>.md`) against runtime-agnostic activity proxies+(git on watched repos + mtime walk on watched non-repo paths + vault+delta on `Brain/inbox|preferences|retired/`). Status is binary β+`alert` if taste events (`feedback`+`apply_evidence`) are zero while+activity is non-zero, `info` for a quiet day, `ok` otherwise. No LLM+in the report path.++`o2b discipline install --vault <v> --telegram-target <target>`+writes one cron entry into the Hermes scheduler (job id derived from+`sha256(vault)` so multiple vaults on one host do not collide). The+configuration block lives in `Brain/_brain.yaml`:++```yaml+discipline_report:+ enabled: true+ timezone: "Europe/Belgrade"+ watched_paths:+ - "/srv/projects/open-second-brain"+ - "/root/.hermes/plugins"+ known_agents:+ - "@claude-vps-agent"+ - "@codex-vps-agent"+```++When the section is absent or `enabled: false`, the report exits 0+with a stderr note and the cron job stays silent.### Cross-project setupdiff --git a/bin/o2b-discipline-report b/bin/o2b-discipline-reportnew file mode 100755index 00000000..14124fe7--- /dev/null+++ b/bin/o2b-discipline-report@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+exec bun run "$HERE/../scripts/discipline-report.ts" "$@"diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex d6dec4a7..861c47c2 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -365,6 +365,8 @@ are mirrored in MCP; destructive operations are CLI-only by design.| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. || Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. || Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |+| Import Claude memory | `o2b brain import-claude-memory` | β (CLI-only) | imports `metadata.type=feedback` entries from a Claude Code memory directory into `Brain/preferences/`. `--dry-run` prints a per-file plan; `--apply --yes` takes an `import-claude-memory-<ts>` snapshot before writing. Sidecar manifest `Brain/.imports/claude-memory.json` keys idempotency on body sha256. `UPDATE` preserves the eight evidence-related frontmatter fields. `CONFLICT` (existing pref outside the manifest) lands the safe writes and exits 2. |+| Daily discipline report | `o2b discipline {report\|install\|uninstall}` | β (CLI-only) | renders a deterministic Telegram MarkdownV2 block comparing per-agent brain-events vs runtime-agnostic activity (git/mtime/vault delta). `install` writes a Hermes cron entry (`--telegram-target` required; no private chat id is baked in). Status is binary: `alert` when taste events (`feedback`+`apply_evidence`) are zero while activity is non-zero. |Operations that change the **protected set** (`pin`, `unpin`,`reject`, `rollback`) and the **index lifecycle** (`search index`,diff --git a/docs/plans/2026-05-18-agent-discipline-tail-design.md b/docs/plans/2026-05-18-agent-discipline-tail-design.mdnew file mode 100644index 00000000..92520f4c--- /dev/null+++ b/docs/plans/2026-05-18-agent-discipline-tail-design.md@@ -0,0 +1,649 @@+# v0.10.7 β Agent logging discipline tail (Β§30 Β§B + Β§D + Β§E)++Status: draft+Owners: TBD+Source:+- `Projects/OpenSecondBrain/Features/_summary.md` Β§30 β Agent logging+ discipline (open work).+- `Projects/OpenSecondBrain/Plan/3. Agent logging discipline.md` Β§B,+ Β§D, Β§E.++## Context++`Β§30 Β§A` (broaden stop guardrail) and `Β§30 Β§C` (SKILL reformulation)+shipped in v0.10.6. The three remaining tracks (`Β§B`, `Β§D`, `Β§E`) are+the writable side of the same discipline problem: removing barriers+to logging, observing whether logging happens, and bridging the+parallel runtime memory layer (Claude Code MEMORY) into Brain so+`brain_apply_evidence` can find the rule it was about to record+against.++The three tracks are independent in surface (MCP server config, cron+script, CLI verb) and share no code. They ship together because they+close one named feature in `_summary.md` and because pacing them out+across three releases would each spend the same amount of changelog,+release, and review attention on a smaller delta.++## Goals++- **G1 β Β§B writer MCP split.** Expose `brain_feedback` and+ `brain_apply_evidence` as an always-loaded MCP surface so that a+ Claude Code agent does not pay the ToolSearch round-trip before+ recording a taste signal or evidence event. The remaining 15 OSB+ MCP tools stay deferred β their context cost is not warranted on+ every session boot.+- **G2 β Β§D daily discipline report.** Land a deterministic+ Hermes-cron job that, once per day, compares brain-event counts per+ agent (read from `Brain/log/<date>.md`) against a runtime-agnostic+ activity proxy (git activity over watched repos + `find -newer` over+ watched non-repo paths + vault delta). Telegram-deliver a status+ block with `ok | info | alert`. No LLM in the report path.+- **G3 β Β§E claude-memory bridge.** Add `o2b brain+ import-claude-memory [--dry-run] [--apply] [--yes] [--json]+ [--memory <path>] [--vault <path>]` that imports `metadata.type:+ feedback` entries from a Claude Code memory directory directly into+ `Brain/preferences/` as `status: confirmed`, with sidecar-tracked+ idempotency.++## Non-goals (explicitly deferred)++Each entry below is recorded in `_summary.md β ## Deferred work` or+in the respective Plan/ doc in the same commit so it survives across+planning sessions.++- **Per-tool always-load in Claude Code.** Claude Code's tool-search+ threshold is per-server, not per-tool (changelog 2.1.121:+ `alwaysLoad` is a `.mcp.json` server flag). Per-tool pinning, if it+ ever lands, would let us drop the writer-server split. Trigger:+ `alwaysLoad` per-tool appears in Claude Code changelog.+- **Bidirectional MEMORY β Brain sync.** Out of scope for v0.10.7.+ Current direction (MEMORY β Brain) closes the `apply_evidence+ misses` symptom. The reverse direction (Brain rule written through+ `brain_feedback` should reach Claude Code MEMORY so it survives+ cross-runtime) would invert the "dream is the only mutating writer+ of `Brain/`" invariant β and writing into `~/.claude/projects/.../+ memory/` from outside Claude Code is risky. Trigger: explicit user+ request, or a second example of a Brain-only rule that did not+ reach a Claude Code session that needed it.+- **Β§D non-bash-runtime activity sources.** Extending the activity+ proxy to Cursor / Aider / opencode session files would tie the+ report to runtime-specific transcript paths. The current proxy is+ runtime-agnostic on purpose. Trigger: Β§4 second half installer+ ships, runtime detection moves into a shared library.+- **Β§D non-binary thresholds.** Status is `alert | info | ok` based on+ the binary `total_brain_events == 0 AND activity > 0`. Numeric+ thresholds (e.g. "less than 1 brain event per 10 commits") would+ introduce noise without a baseline. Trigger: real+ false-positive/false-negative pairs from operating the report.+- **Β§E import of `user` / `project` / `reference` MEMORY entries.**+ Only `metadata.type: feedback` is mapped. The other three are not+ taste rules. Trigger: a real case where a `project`-typed memory+ shaped agent behavior in a way `brain_apply_evidence` should have+ recorded.+- **Β§E MCP wrapper.** `import-claude-memory` stays CLI-only by+ design doc Β§9.1 ("absence from MCP protects against autonomous+ mistakes") β same posture as `init`, `reject`, `pin`, `rollback`,+ `upgrade`.++## Β§B β Writer MCP server (always-loaded)++### Mechanism (what Claude Code actually supports)++- Claude Code 2.1.121 added `alwaysLoad: true` as a `.mcp.json`+ per-server flag. When set, the server's full tool surface skips+ tool-search deferral.+- There is no per-tool pin (verified against changelog and config+ schema as of 2026-05-18). Without splitting, the only options are+ "all OSB tools always loaded" (β17 schemas in every session β too+ expensive) or "all deferred" (status quo).+- Splitting OSB into two MCP-server entries with the same backing+ binary but different `--scope` flags lets us keep the existing+ large surface deferred while pinning the two writer tools.++### `.mcp.json`++Both entries point to the same `${CLAUDE_PLUGIN_ROOT}/scripts/o2b`+binary; the second one adds `--scope writer` and `alwaysLoad: true`:++```json+{+ "mcpServers": {+ "open-second-brain": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp"]+ },+ "open-second-brain-writer": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp", "--scope", "writer"],+ "alwaysLoad": true+ }+ }+}+```++`/srv/projects/open-second-brain/.mcp.json` and the plugin-cache+mirror (`/root/.claude/plugins/cache/open-second-brain/.../.mcp.json`)+both ship the same content.++### `src/mcp/tools.ts`++`buildToolTable()` gains an optional `scope` parameter:++```ts+export type ToolScope = "full" | "writer";++export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {+ const all = [/* current array, unchanged */];+ if (scope === "full") return all;+ const writerAllow = new Set(["brain_feedback", "brain_apply_evidence"]);+ return all.filter((t) => writerAllow.has(t.name));+}+```++Filtering after the existing list β not a separate writer-only+table β keeps tool schemas defined exactly once. Adding a new+brain-event tool that should also be always-loaded becomes a+one-line set extension.++### `src/cli/main.ts`++Add `--scope writer|full` (default `full`) to the `mcp` subcommand.+The parsed value is forwarded into `serveStdio({ scope })`. Invalid+values exit 2 with `unknown --scope: <value>; expected one of: full,+writer`.++### `src/mcp/stdio.ts` and `src/mcp/server.ts`++- `MCPServer` constructor takes an optional `serverName` override.+ Default stays `"open-second-brain"`. Writer mode passes+ `"open-second-brain-writer"` so the MCP handshake matches the+ `.mcp.json` key (Claude Code uses the server name for tool-id+ decoration).+- `serveStdio({ scope, serverName })`: `scope` selects the tool+ table; `serverName` flows into the `initialize` response.++### `src/mcp/instructions.ts`++A separate short instructions string for writer mode. Wording (final+phrasing during impl):++> Open Second Brain β writer surface. Two tools:+>+> - `brain_feedback` β record one new taste signal the user just+> expressed.+> - `brain_apply_evidence` β record `applied | violated | outdated`+> against an active preference for an artifact this turn produced.+>+> The full Brain surface (`brain_dream`, `brain_digest`,+> `brain_query`, `brain_doctor`, `brain_backlinks`, `brain_search`,+> Pay Memory tools) lives on the sibling `open-second-brain` MCP+> server (deferred). Use that one through ToolSearch when needed.++Full-server instructions are unchanged; an addendum line points to+the writer server for `feedback` / `apply_evidence`.++### Duplicate-tool note++Both servers expose `brain_feedback` and `brain_apply_evidence`. The+agent sees two entries:+`mcp__plugin_open-second-brain_open-second-brain-writer__brain_feedback`+(always loaded) and+`mcp__plugin_open-second-brain_open-second-brain__brain_feedback`+(deferred β same handler). Backing handler is identical, so either+call writes the same Brain artifact. The instructions text in writer+mode explicitly tells the agent to prefer the writer-server tool.+We do not attempt to dedupe at the server level β Claude Code's+tool-id namespacing is by server.++### Tests (`tests/mcp/`)++- `scope-filter.test.ts` β `buildToolTable("writer")` returns exactly+ `["brain_feedback", "brain_apply_evidence"]`. `buildToolTable("full")`+ contains all current tools plus those two. Schemas are object-equal+ to the entries in the full table (no drift).+- `writer-server.test.ts` β spawn `o2b mcp --scope writer`, send+ JSON-RPC `initialize` then `tools/list`. Assert exactly two tools,+ matching names and schemas. Assert handshake `serverInfo.name` is+ `open-second-brain-writer`.+- `cli/mcp-scope-arg.test.ts` β `o2b mcp --scope nope` exits 2 with+ a message naming the valid values. `o2b mcp --scope` (missing+ value) exits 2.++## Β§D β Daily discipline report++### Mechanism++A pure bun script (no LLM) runs once a day from a Hermes cron job,+reads three deterministic sources, prints a Telegram-safe Markdown+block to stdout. Hermes' cron delivery writes that block into the+configured Telegram topic with `cron.wrap_response: false`.++### Entry point++- New script `bin/o2b-discipline-report` (executable, bun shebang).+ Argument: `--config-path` defaults to `~/.osb/config.yaml` via the+ existing `discoverConfig`. Output: plain text (Telegram+ MarkdownV2 escaped) to stdout. Exit code: 0 on `ok`/`info`, 0 on+ `alert` too (cron should still post the message; the human reads+ the status line).++The report code lives in `src/core/discipline/report.ts`. The+bin/-level script imports it. The CLI also exposes a verb for ad-hoc+local runs and for installer scripts: `o2b discipline report+[--yesterday | --date YYYY-MM-DD]`. Same code path as the cron-bin,+different entrypoint.++### Sources++**Source 1 β brain-events per agent.** Read+`Brain/log/<yesterday-in-config-tz>.md`. Parse the existing structure+defined in `src/core/brain/log.ts`:++```text+## HH:MM:SSZ β <kind>+- ...+- agent: <name>+- ...+```++For each block:+- Skip if no `agent:` field.+- Count by `(agent_name, kind_bucket)` where+ - `feedback` β bucket `feedback`,+ - `apply-evidence` β bucket `apply_evidence`,+ - everything else (`dream-pass`, `snapshot`, `merge`, `import-*`,+ `upgrade`, ...) β bucket `other`.++Emit a per-agent total. Keep agents whose names appear in+`discipline_report.known_agents` even when their count is zero+(explicit zero is informative); list unknown agent names below the+known block.++**Source 2 β repo activity (watched_paths with `.git`).** For each+configured watched path that contains a `.git/` directory:++```bash+git -C <path> log --since=<24h ago in tz> --until=<midnight in tz> \+ --no-merges --shortstat --pretty=tformat:%H+```++Aggregate: commits count, files changed, insertions, deletions.++**Source 3 β non-repo activity.** For each watched path without+`.git/`: count files whose mtime falls in the `[yesterday 00:00,+today 00:00)` interval in vault tz. Exclude common noise: `.cache`,+`node_modules`, `.git`, `.snapshots`, `*.lock`, dotfiles named+`.tmp-*`. Exclusion list is hardcoded inside `report.ts` (no config+knob β knob = future bug).++**Source 4 β vault delta.** Always-included extra source:+`Brain/inbox/` mtime in window (`new_signals`),+`Brain/preferences/` mtime in window (`new_preferences`),+`Brain/retired/` mtime in window (`new_retired`). Sourced from the+vault directly, not from log parsing β catches signals that landed+through `@osb` inline scan rather than through the live agent path.++### Status decision (binary)++```text+activity_signal = repo_activity_commits > 0+ OR non_repo_modified_files >= 3+ OR vault_delta_total > 0++total_brain_events = sum of feedback+apply_evidence+other across all agents++status =+ "alert" if total_brain_events == 0 AND activity_signal == true+ "info" if total_brain_events == 0 AND activity_signal == false+ "ok" otherwise+```++This intentionally avoids ratio thresholds. The two real shapes we+want to catch are "a quiet day" (info, no action needed) and "a busy+day with zero brain logging" (alert, guardrail likely bypassed).+Everything else is `ok`.++### Output (Telegram MarkdownV2)++```text+π§ OSB discipline β <YYYY-MM-DD> (<tz_name>)++Status: <ok | info | alert>++Brain events:+- @claude-vps-agent: 2 feedback, 3 apply-evidence, 0 other (total 5)+- @codex-vps-agent: 0 feedback, 0 apply-evidence, 0 other (total 0)+<plus any unknown-name agents that appeared in the log>++Activity:+- /srv/projects/open-second-brain β 4 commits, 27 files, +312/-148+- /root/.hermes/plugins β 6 modified files+- vault β 3 new signals, 1 new preference, 0 retired++<if status == "alert">+[one-line explanation: e.g. "Activity present; zero brain events+recorded. Stop guardrail likely bypassed or hook regressed."]+```++MarkdownV2-safe escaping: dots, dashes, parentheses, underscores all+escaped per Telegram's rules. The escape function lives in+`src/core/discipline/telegram.ts`; reused if a future report needs it.++### Config++A new section under the existing `Brain/_brain.yaml` policy file:++```yaml+discipline_report:+ enabled: true+ timezone: "Europe/Belgrade"+ watched_paths:+ - "/srv/projects/open-second-brain"+ - "/root/.hermes/plugins"+ - "/root/.hermes/bin/agents"+ known_agents:+ - "@claude-vps-agent"+ - "@codex-vps-agent"+```++`enabled: false` (or missing section) β CLI prints+`discipline_report disabled` to stderr and exits 0. The cron job+delivers nothing in that case (`cron.wrap_response: false` + empty+stdout = empty Telegram message; we explicitly trim and bail before+that point).++### Hermes cron install++`o2b discipline install [--telegram-target <topic>] [--at <cron>]`+creates a single job in `/root/.hermes/cron/jobs.json` via the+existing `hermes cron create` CLI. Job shape:++```json+{+ "id": "osb-discipline-report-<vault-hash>",+ "name": "osb-discipline-report",+ "script": "/srv/projects/open-second-brain/bin/o2b-discipline-report",+ "no_agent": true,+ "schedule": { "kind": "cron", "expr": "59 4 * * *" },+ "deliver": "telegram:-1003895040510:216",+ "enabled": true+}+```++`vault-hash` is `sha256(vault_path).slice(0, 12)` so two vaults on+the same host get distinct job ids.++Defaults:+- `--at` defaults to `59 4 * * *` (UTC), one minute before+ `nightly-system-report` runs at 05:00 UTC; keeps the two reports+ visually adjacent without sharing a startup tick.+- `--telegram-target` defaults to the same topic as+ `nightly-system-report` (216).++`o2b discipline uninstall` removes the job. Idempotent on both ends.++### Tests (`tests/discipline/`)++- `parse-brain-log.test.ts` β fixture log file with three agents+ (one known, one known-but-zero, one unknown) β expected per-agent+ buckets.+- `repo-activity.test.ts` β temp git repo with 3 commits in the+ window and 1 commit out of window. Asserts `commits == 3`,+ `files` / `insertions` / `deletions` summed only from the in-window+ set.+- `non-repo-activity.test.ts` β temp dir with mtime-marked files in+ and out of window, plus excluded paths (`node_modules`, `.cache`).+ Asserts excluded paths are not counted.+- `decision.test.ts` β truth-table over status (4 combinations).+- `render.test.ts` β golden output for `ok`, `info`, `alert`, with+ MarkdownV2 escaping verified.+- `install-cron.test.ts` β install creates exactly one job by id;+ reinstall is a no-op; uninstall removes it.++## Β§E β `o2b brain import-claude-memory`++### CLI++```text+o2b brain import-claude-memory+ [--memory <path>] default: ~/.claude/projects/<vault-slug>/memory+ [--vault <path>] default: from config+ [--dry-run] plan only+ [--apply] write (creates snapshot first)+ [--yes] skip --apply confirmation in non-interactive+ [--json] machine-readable output+```++- `--dry-run` and `--apply` are mutually exclusive; without either,+ defaults to `--dry-run`. Consistent with `o2b brain upgrade`+ semantics shipped in v0.10.6.+- `--memory` resolves the directory; `vault-slug` derivation: take+ the absolute vault path, replace `/` with `-`, prefix `-`. Match+ Claude Code's own slug rule. Fails fast if the directory does not+ exist with a hint pointing at `--memory <path>`.++### Mapping++For each `.md` in `<memory>/` (skip `MEMORY.md`):++```yaml+# 1. Frontmatter is required, with at least `name` and+# `metadata.type`. Missing fields skip the file with a warning.++# 2. metadata.type == "feedback":+id: pref-<slug(name)>+kind: brain-preference+status: confirmed+pinned: false+scope: writing # default; override via body marker+topic: <slug derived from name>+principle: <description> # required from MEMORY frontmatter+confidence: high+created_at: <import iso>+_confirmed_at: <import iso>+_force_confirmed_via: claude-memory+_imported_from: "<memory-path>/<file>.md"+_imported_sha256: <sha256 of source body>+_imported_at: <import iso>+_applied_count: 0+_violated_count: 0+_evidenced_by: []+_last_evidence_at: null+unconfirmed_until: <import iso> # equals _confirmed_at: already confirmed++# 3. metadata.type in {"user", "project", "reference"}:+# skipped with stderr line:+# "skipped <file>: metadata.type=<X>; only `feedback` maps to Brain"++# 4. metadata.type missing or unknown:+# skipped with stderr line:+# "skipped <file>: missing or unknown metadata.type"+```++Body of the Brain preference: MEMORY body verbatim (the `**Why:**` /+`**How to apply:**` blocks are already in the shape Brain rules use).+At the bottom of the body, append:++```markdown+## Origin++Imported from Claude Code MEMORY:+`<memory-path>/<file>.md`+on <YYYY-MM-DD>.+```++`scope` extraction: scan MEMORY body for `scope:\s*<word>` on a line+by itself. If found, use it. Else default `writing`. The default is+deliberate (most feedback memories in the current repo are about+prose/style); we do not guess scope from text content.++### Idempotency++`<vault>/Brain/.imports/claude-memory.json`:++```json+{+ "version": 1,+ "imports": {+ "<basename>.md": {+ "pref_id": "pref-<slug>",+ "sha256": "<of source body>",+ "imported_at": "<ISO Z>"+ }+ }+}+```++Decision table (applied per memory file):++| In manifest? | sha256 match? | Brain pref exists? | Plan |+|--------------|---------------|--------------------|---------------|+| no | n/a | no | CREATE |+| no | n/a | yes | CONFLICT |+| yes | yes | yes | SKIP_UNCHANGED |+| yes | yes | no | RECREATE (manifest stale) |+| yes | no | yes | UPDATE |+| yes | no | no | CREATE (manifest stale) |++`UPDATE` overwrites `principle` and body verbatim; it does NOT touch+`_applied_count`, `_violated_count`, `_evidenced_by`,+`_last_evidence_at`, `_confirmed_at`, `unconfirmed_until`, `pinned`,+or `scope`. Evidence collected over the lifetime of the preference+is preserved.++`CONFLICT` produces a clear stderr line and exits the run with the+file unprocessed:++```text+conflict: preference pref-no-em-dashes already exists in Brain but+is not registered in Brain/.imports/claude-memory.json. Resolve by:+ - rename the MEMORY entry (so a fresh pref-id is created), or+ - delete or rename Brain/preferences/pref-no-em-dashes.md, or+ - manually add the entry to Brain/.imports/claude-memory.json.+```++The run still processes the remaining files; final exit code is 0+only if every file is `CREATE | UPDATE | RECREATE | SKIP_UNCHANGED`.+Any `CONFLICT` β exit 2.++### Pre-apply snapshot++`--apply` calls the shared `createSnapshot({ runIdPrefix:+"import-claude-memory" })` from `src/core/brain/snapshot.ts` before+the first preference write. Rollback works via the same+`o2b brain rollback <run-id>` path as `upgrade`/`merge`. Failure to+write the snapshot aborts with `--force-apply` as the explicit+override; `--force-apply` follows the same posture as `upgrade`'s+`--force-rollback`.++### Brain log event++After a successful `--apply`, append one block to+`Brain/log/<today>.md` via `appendLogEvent`:++```text+## HH:MM:SSZ β import-claude-memory+- created: N+- updated: M+- recreated: R+- skipped_unchanged: K+- skipped_non_feedback: L+- conflicts: C+- snapshot: import-claude-memory-<ts>+- agent: <resolved>+```++New `BRAIN_LOG_EVENT_KIND.importClaudeMemory = "import-claude-memory"`+in `src/core/brain/types.ts`. Same shape as the existing+`import-session` event kind.++### Path safety++The default `--memory` resolves under `~/.claude/projects/`. If the+user passes a `--memory` outside that prefix:++```text+refusing to import from <path>: it is not under ~/.claude/projects/.+Pass --allow-arbitrary-memory-path to override.+```++`--allow-arbitrary-memory-path` exists for the edge case where a+secondary Claude Code install lives under a non-default home; we do+not default it on, because mis-passing a system directory should not+populate Brain.++### Tests (`tests/brain/`)++- `import-memory-mapping.test.ts` β feedback MEMORY file β expected+ preference frontmatter + body + `## Origin` block.+- `import-memory-filter.test.ts` β `user`/`project`/`reference`+ entries skipped with the expected stderr line; `MEMORY.md` always+ skipped.+- `import-memory-idempotency.test.ts` β second `--apply` with no+ changes performs zero writes; sha256 mismatch triggers UPDATE;+ manifest reflects all three states (`CREATE` β `SKIP_UNCHANGED` β+ `UPDATE`).+- `import-memory-conflict.test.ts` β preference exists without+ manifest entry β CONFLICT, exit 2, other files still processed.+- `import-memory-snapshot.test.ts` β `--apply` creates the snapshot,+ `rollback` restores the original Brain.+- `import-memory-path-safety.test.ts` β `--memory /etc/passwd`+ refuses without the override flag; with the override flag and a+ valid markdown corpus, succeeds.+- `import-memory-update-preserves-evidence.test.ts` β UPDATE keeps+ `_applied_count`/`_violated_count`/`_evidenced_by` intact.++## Cross-track decisions++### Versioning++Single v0.10.7. Updated in `package.json`, `openclaw.plugin.json`,+`plugin.yaml`. New `CHANGELOG.md` section under `## [0.10.7] -+<date>` with one Added/Changed split. No `[Unreleased]` section+carried over.++### Back-compat++- `.mcp.json` shipped with two server entries; client installs that+ predate `alwaysLoad` keep `open-second-brain-writer` deferred too+ (silent no-op behavioral change), which still works because the+ writer-mode server exposes the same tool names and the existing+ registration logic handles the dupe.+- `Brain/_brain.yaml` without `discipline_report` β feature is+ disabled; `bin/o2b-discipline-report` exits 0 without writing.+- `Brain/.imports/` absent β created on first `--apply`.+- Hermes cron job is created only by `o2b discipline install`; the+ v0.10.7 upgrade path does NOT auto-install it (user-initiated+ surface; documented in CHANGELOG and README).++### Where the deferred entries land++`_summary.md β ## Deferred work` gets four new lines (one each for+`per-tool always-load`, `bidirectional MEMORY β Brain sync`,+`non-bash-runtime activity sources for Β§D`, `non-binary thresholds+for Β§D`). Each line names the trigger that would bring it back to+active planning.++`Plan/3. Agent logging discipline.md` status: `shipped`. Β§B / Β§D /+Β§E sections move from `open:` to `shipped:`. The "Π’ΡΠΈΠ³Π³Π΅Ρ Π½Π°+Π²ΠΎΠ·Π²ΡΠ°Ρ" section is dropped β Β§30 is closed.++`Plan/2. Improvement.md` and `Plan/4. v0.10.5 review followups.md`+are untouched.++### Principles audit++- SOLID β each track owns one file family (`src/mcp/`,+ `src/core/discipline/`, `src/core/brain/import-claude-memory.ts`).+ Shared infra (`createSnapshot`, `appendLogEvent`,+ `BRAIN_LOG_EVENT_KIND`) is consumed, not duplicated.+- KISS β Β§D is a script, not an LLM; Β§E is one verb, not a+ bidirectional sync engine; Β§B is a config flag plus a filter.+- DRY β `brain_feedback` / `brain_apply_evidence` schemas defined+ once in `BRAIN_TOOLS`; writer-server filters by name; instructions+ string is a new constant in `instructions.ts`, not a fork of the+ full one.+- No active git β every track operates on local FS only.+- Honest fallbacks β `scope: writing` default in Β§E is explicit, not+ hidden inference. `discipline_report disabled` path in Β§D logs to+ stderr instead of silently producing an empty report.diff --git a/docs/plans/2026-05-18-agent-discipline-tail-impl.md b/docs/plans/2026-05-18-agent-discipline-tail-impl.mdnew file mode 100644index 00000000..7c00306b--- /dev/null+++ b/docs/plans/2026-05-18-agent-discipline-tail-impl.md@@ -0,0 +1,3242 @@+# v0.10.7 Implementation Plan β Agent logging discipline tail (Β§B + Β§D + Β§E)++> **For agentic workers:** REQUIRED SUB-SKILL: Use+> superpowers:subagent-driven-development (recommended) or+> superpowers:executing-plans to implement this plan task-by-task.+> Steps use checkbox (`- [ ]`) syntax for tracking.+>+> **No active git.** The user explicitly forbids any active git+> action (`commit`, `push`, `branch`, `tag`, `amend`, `stash`,+> `reset --hard`, `rebase`). Each "Pause for review" step means:+> stop, surface the diff with `git diff`, wait for the user to+> stage / commit themselves.++**Goal:** Close the remaining Β§30 work in one release β `Β§B`+writer-MCP split, `Β§D` daily discipline cron, `Β§E` claude-memory+bridge.++**Architecture:**+- `src/mcp/tools.ts` gains a `scope: "full" | "writer"` filter; a+ new `.mcp.json` server entry `open-second-brain-writer` runs the+ same CLI with `--scope writer` and `alwaysLoad: true`.+- `src/core/discipline/` (new module) and `bin/o2b-discipline-report`+ produce a deterministic Telegram-safe text block from `Brain/log`,+ git activity, and vault delta. Hermes cron delivers it.+- `src/core/brain/import-claude-memory.ts` and a new+ `o2b brain import-claude-memory` CLI verb copy+ `metadata.type: feedback` MEMORY entries into+ `Brain/preferences/` with a sidecar manifest for idempotency.++**Tech Stack:** Bun β₯ 1.1, TypeScript (strict), `bun test`, no new+runtime dependencies. SHA-256 via `node:crypto`, YAML via the+existing `js-yaml` already on the dep tree.++**Design source:** `docs/plans/2026-05-18-agent-discipline-tail-design.md`.++---++## Phase 0 β Baseline check++### Task 0.1: Verify clean baseline++**Steps:**++- [ ] **Step 1: Confirm tests pass.** Run `bun test` from+ `/srv/projects/open-second-brain`. Expected: all green.++- [ ] **Step 2: Confirm typecheck passes.** Run+ `bun run typecheck`. Expected: zero errors.++- [ ] **Step 3: Record current version.** Read `package.json`;+ current `"version"` should be `"0.10.6"`. Plan bumps to+ `0.10.7` in Phase 4.++**Pause for review.** Do not change anything yet.++---++## Phase 1 β Β§B Writer MCP split++### Task 1.1: `buildToolTable` accepts an optional `scope`++**Files:**+- Modify: `src/mcp/tools.ts:608` (the `buildToolTable` function).+- Create: `tests/mcp/scope-filter.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/mcp/scope-filter.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { buildToolTable } from "../../src/mcp/tools.ts";++ describe("buildToolTable scope filter", () => {+ test("default scope returns the full surface", () => {+ const full = buildToolTable();+ const names = full.map((t) => t.name);+ expect(names).toContain("brain_feedback");+ expect(names).toContain("brain_apply_evidence");+ expect(names).toContain("brain_dream");+ expect(names).toContain("payment_memory_init");+ expect(names).toContain("vault_health");+ expect(full.length).toBeGreaterThanOrEqual(15);+ });++ test("writer scope returns exactly the two writer tools", () => {+ const writer = buildToolTable("writer");+ const names = writer.map((t) => t.name).sort();+ expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });++ test("writer-scope schemas are the same instances as full scope", () => {+ const full = buildToolTable("full");+ const writer = buildToolTable("writer");+ for (const w of writer) {+ const matched = full.find((t) => t.name === w.name);+ expect(matched).toBeDefined();+ expect(w.inputSchema).toEqual(matched!.inputSchema);+ expect(w.description).toEqual(matched!.description);+ }+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL** β `bun test tests/mcp/scope-filter.test.ts`.+ TypeScript fails compile on `buildToolTable("writer")` (argument count).++- [ ] **Step 3: Minimal implementation** β edit+ `src/mcp/tools.ts` near the existing `buildToolTable` declaration:++ ```ts+ export type ToolScope = "full" | "writer";++ const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([+ "brain_feedback",+ "brain_apply_evidence",+ ]);++ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {+ const all: ToolDefinition[] = [+ // ... (the existing big array, unchanged)+ ];+ if (scope === "full") return all;+ return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));+ }+ ```++ Keep the existing array contents byte-identical β just wrap them+ with the new signature and append the filter clause.++- [ ] **Step 4: Run test, expect PASS** β+ `bun test tests/mcp/scope-filter.test.ts`. Three test cases pass.++- [ ] **Step 5: Verify nothing else broke.** Run `bun test`. All+ green.++**Pause for review.**++### Task 1.2: `MCPServer` accepts an optional `serverName`++**Files:**+- Modify: `src/mcp/server.ts`.+- Modify: `src/mcp/protocol.ts` only if `SERVER_NAME` needs to be+ exposed via parameter (it likely already is).++- [ ] **Step 1: Read current ctor.** Run+ `grep -n "constructor\|SERVER_NAME\|name:" src/mcp/server.ts` to+ identify how the server announces its name during `initialize`.++- [ ] **Step 2: Write failing test** β append to+ `tests/mcp/mcp.test.ts` (existing file, add a new describe block):++ ```ts+ import { MCPServer } from "../../src/mcp/server.ts";++ describe("MCPServer serverName override", () => {+ test("default ctor uses SERVER_NAME constant", () => {+ const srv = new MCPServer({ vault: "/tmp/x", configPath: null, repoRoot: null });+ // Simulate initialize and read announced name.+ const init = srv.handleInitialize();+ expect(init.serverInfo.name).toBe("open-second-brain");+ });++ test("explicit serverName flows into initialize response", () => {+ const srv = new MCPServer(+ { vault: "/tmp/x", configPath: null, repoRoot: null },+ { serverName: "open-second-brain-writer" },+ );+ const init = srv.handleInitialize();+ expect(init.serverInfo.name).toBe("open-second-brain-writer");+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL** β `bun test tests/mcp/mcp.test.ts`.+ Fails on `MCPServer` second-arg signature.++- [ ] **Step 4: Minimal implementation** β in `src/mcp/server.ts`:++ ```ts+ export interface MCPServerOptions {+ readonly serverName?: string;+ readonly scope?: ToolScope;+ }++ export class MCPServer {+ private readonly serverName: string;+ private readonly scope: ToolScope;++ constructor(ctx: ServerContext, opts: MCPServerOptions = {}) {+ // ... existing ctx assignment ...+ this.serverName = opts.serverName ?? SERVER_NAME;+ this.scope = opts.scope ?? "full";+ this.tools = buildToolTable(this.scope);+ }++ handleInitialize() {+ return {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: { /* existing */ },+ serverInfo: { name: this.serverName, version: SERVER_VERSION },+ };+ }+ // ...+ }+ ```++ If the existing class already has a separate `name`-emitting+ code path, route it through `this.serverName` instead of+ `SERVER_NAME` directly. Do NOT remove `SERVER_NAME` from+ `protocol.ts` β it stays as the default.++- [ ] **Step 5: Run test, expect PASS** β `bun test tests/mcp/`.+ Both new cases pass.++- [ ] **Step 6: Run full test suite, expect PASS** β `bun test`.++**Pause for review.**++### Task 1.3: `serveStdio` accepts `{ scope, serverName }`++**Files:**+- Modify: `src/mcp/stdio.ts`.++- [ ] **Step 1: Locate `serveStdio` signature** β `grep -n "serveStdio" src/mcp/stdio.ts`.++- [ ] **Step 2: Write failing test** β append to `tests/mcp/mcp.test.ts`:++ ```ts+ import { serveStdioFromString } from "../../src/mcp/stdio.ts";++ describe("serveStdioFromString respects scope+name", () => {+ test("writer scope filters tools/list response", async () => {+ const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };+ const initReq = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const listReq = JSON.stringify({+ jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ });+ const out = await serveStdioFromString(+ ctx,+ `${initReq}\n${listReq}\n`,+ { scope: "writer", serverName: "open-second-brain-writer" },+ );+ const lines = out.trim().split("\n").map((l) => JSON.parse(l));+ expect(lines[0].result.serverInfo.name).toBe("open-second-brain-writer");+ const toolNames = (lines[1].result.tools as Array<{ name: string }>)+ .map((t) => t.name).sort();+ expect(toolNames).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL** β argument count error.++- [ ] **Step 4: Minimal implementation** β extend+ `serveStdioFromString` and `serveStdio` to accept an `opts:+ { scope?: ToolScope; serverName?: string }` second argument+ and forward it to the `new MCPServer(ctx, opts)` call.++ ```ts+ export async function serveStdioFromString(+ ctx: ServerContext,+ input: string,+ opts: MCPServerOptions = {},+ ): Promise<string> {+ const server = new MCPServer(ctx, opts);+ // ... existing line-by-line handling ...+ }+ ```++ `serveStdio` (the stdin-driven version) mirrors the change.++- [ ] **Step 5: Run test, expect PASS**.++- [ ] **Step 6: Full test sweep** β `bun test`.++**Pause for review.**++### Task 1.4: `o2b mcp --scope writer|full` CLI flag++**Files:**+- Modify: `src/cli/main.ts` (the `mcp` subcommand).+- Create: `tests/cli/mcp-scope-arg.test.ts`.++- [ ] **Step 1: Locate the mcp subcommand handler** β+ `grep -n '"mcp"\|case "mcp"' src/cli/main.ts`.++- [ ] **Step 2: Write failing tests** β+ `tests/cli/mcp-scope-arg.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { runCli } from "../helpers/run-cli.ts";++ describe("o2b mcp --scope arg validation", () => {+ test("invalid scope value exits 2 with a clear error", async () => {+ const res = await runCli(["mcp", "--scope", "nope"], { stdin: "" });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("--scope");+ expect(res.stderr).toMatch(/full.*writer|writer.*full/);+ });++ test("missing --scope value exits 2", async () => {+ const res = await runCli(["mcp", "--scope"], { stdin: "" });+ expect(res.returncode).toBe(2);+ });++ test("--scope writer starts the server and answers tools/list", async () => {+ const init = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const list = JSON.stringify({+ jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ });+ const res = await runCli(+ ["mcp", "--scope", "writer"],+ { stdin: `${init}\n${list}\n` },+ );+ expect(res.returncode).toBe(0);+ const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l));+ const names = (lines[1].result.tools as Array<{ name: string }>)+ .map((t) => t.name).sort();+ expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });+ });+ ```++- [ ] **Step 3: Run tests, expect FAIL.**++- [ ] **Step 4: Parse and forward the flag.** In `src/cli/main.ts`,+ inside the `mcp` subcommand branch:++ ```ts+ // existing: collects positional args, vault override, etc.+ let scope: "full" | "writer" = "full";+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--scope") {+ const v = args[i + 1];+ if (v !== "full" && v !== "writer") {+ process.stderr.write(+ `o2b mcp: invalid --scope value: ${v ?? "<missing>"}; expected one of: full, writer\n`,+ );+ process.exit(2);+ }+ scope = v;+ args.splice(i, 2);+ i--;+ }+ }+ const serverName = scope === "writer"+ ? "open-second-brain-writer"+ : "open-second-brain";+ await serveStdio(ctx, { scope, serverName });+ ```++ The exact positional-parsing context depends on the current+ CLI structure (it might already have a `parseFlags` helper). If+ a helper exists, add `--scope` to it; do not duplicate parsing.++- [ ] **Step 5: Run tests, expect PASS.**++- [ ] **Step 6: Run full test sweep.**++**Pause for review.**++### Task 1.5: Writer-server instructions text++**Files:**+- Modify: `src/mcp/instructions.ts`.++- [ ] **Step 1: Read current `buildInstructions`** β `cat src/mcp/instructions.ts`.++- [ ] **Step 2: Write failing test** β append to+ `tests/mcp/mcp.test.ts`:++ ```ts+ import { buildInstructions } from "../../src/mcp/instructions.ts";++ describe("buildInstructions writer mode", () => {+ test("writer instructions name both tools and point at the full server", () => {+ const text = buildInstructions({+ vault: "/tmp/x",+ agent: "@agent",+ scope: "writer",+ });+ expect(text).toContain("brain_feedback");+ expect(text).toContain("brain_apply_evidence");+ expect(text).toContain("open-second-brain"); // points at sibling server+ expect(text).not.toMatch(/payment_/i);+ expect(text).not.toMatch(/brain_dream/);+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL**.++- [ ] **Step 4: Implement the writer branch** β in+ `src/mcp/instructions.ts`:++ ```ts+ export interface BuildInstructionsOpts {+ readonly vault: string;+ readonly agent: string;+ readonly scope?: ToolScope;+ }++ const WRITER_INSTRUCTIONS = `Open Second Brain β writer surface (always-loaded).++ Two tools live here:+ - brain_feedback β record one new taste signal the user just expressed.+ - brain_apply_evidence β record applied | violated | outdated against an+ active preference for an artifact this turn produced.++ The full Brain surface (brain_dream, brain_digest, brain_query, brain_doctor,+ brain_backlinks, brain_search, Pay Memory tools, vault_health,+ second_brain_status, second_brain_query) lives on the sibling+ "open-second-brain" MCP server (deferred). Use ToolSearch to reach it.++ Prefer the writer-server copy of brain_feedback / brain_apply_evidence over+ any duplicate exposed by the full server β both call the same handler, but the+ writer copy is always available without ToolSearch.`;++ export function buildInstructions(opts: BuildInstructionsOpts): string {+ if (opts.scope === "writer") return WRITER_INSTRUCTIONS;+ // existing full-surface text branch ...+ }+ ```++ Wire `serveStdio` / `MCPServer.handleInitialize` to call+ `buildInstructions({ vault, agent, scope })` instead of the+ current arg-less / scope-blind call.++- [ ] **Step 5: Run test, expect PASS**.++- [ ] **Step 6: Full sweep.**++**Pause for review.**++### Task 1.6: `.mcp.json` second-server entry++**Files:**+- Modify: `/srv/projects/open-second-brain/.mcp.json`.+- Create: `tests/mcp/mcp-json.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/mcp/mcp-json.test.ts`:++ ```ts+ import { readFileSync } from "node:fs";+ import { describe, expect, test } from "bun:test";++ describe(".mcp.json shipped with the plugin", () => {+ const file = JSON.parse(+ readFileSync("/srv/projects/open-second-brain/.mcp.json", "utf8"),+ );+ test("declares both open-second-brain and -writer entries", () => {+ expect(Object.keys(file.mcpServers).sort()).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ });+ test("writer entry passes --scope writer and alwaysLoad: true", () => {+ const w = file.mcpServers["open-second-brain-writer"];+ expect(w.command).toBe("${CLAUDE_PLUGIN_ROOT}/scripts/o2b");+ expect(w.args).toEqual(["mcp", "--scope", "writer"]);+ expect(w.alwaysLoad).toBe(true);+ });+ test("full server has no alwaysLoad flag", () => {+ const f = file.mcpServers["open-second-brain"];+ expect(f.alwaysLoad).toBeUndefined();+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Update `.mcp.json`:**++ ```json+ {+ "mcpServers": {+ "open-second-brain": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp"]+ },+ "open-second-brain-writer": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp", "--scope", "writer"],+ "alwaysLoad": true+ }+ }+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review. End of Β§B track.**++---++## Phase 2 β Β§D Discipline report++### Task 2.1: Config schema for `discipline_report`++**Files:**+- Modify: `src/core/brain/policy.ts` (extend `BrainConfig`).+- Create: `tests/core/brain/policy-discipline.test.ts`.++- [ ] **Step 1: Inspect the current `BrainConfig` shape** β+ `grep -n "BrainConfig\b\|discipline" src/core/brain/policy.ts`.++- [ ] **Step 2: Write failing test** β+ `tests/core/brain/policy-discipline.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { loadBrainConfig } from "../../../src/core/brain/policy.ts";++ function vaultWith(yaml: string): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-policy-"));+ mkdirSync(join(v, "Brain"), { recursive: true });+ writeFileSync(join(v, "Brain", "_brain.yaml"), yaml, "utf8");+ return v;+ }++ describe("discipline_report config", () => {+ test("missing section β discipline_report undefined", () => {+ const v = vaultWith("schema_version: 1\n");+ const cfg = loadBrainConfig(v);+ expect(cfg.discipline_report).toBeUndefined();+ rmSync(v, { recursive: true });+ });++ test("populated section is parsed verbatim", () => {+ const v = vaultWith(+ "schema_version: 1\n" ++ "discipline_report:\n" ++ " enabled: true\n" ++ " timezone: Europe/Belgrade\n" ++ " watched_paths:\n" ++ " - /srv/projects/foo\n" ++ " known_agents:\n" ++ " - '@claude-vps-agent'\n",+ );+ const cfg = loadBrainConfig(v);+ expect(cfg.discipline_report).toEqual({+ enabled: true,+ timezone: "Europe/Belgrade",+ watched_paths: ["/srv/projects/foo"],+ known_agents: ["@claude-vps-agent"],+ });+ rmSync(v, { recursive: true });+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL.**++- [ ] **Step 4: Extend `BrainConfig`** in `src/core/brain/policy.ts`:++ ```ts+ export interface DisciplineReportConfig {+ readonly enabled: boolean;+ readonly timezone: string;+ readonly watched_paths: ReadonlyArray<string>;+ readonly known_agents: ReadonlyArray<string>;+ }++ export interface BrainConfig {+ // ... existing fields ...+ readonly discipline_report?: DisciplineReportConfig;+ }+ ```++ In `loadBrainConfig` (or its detailed sibling), read the+ `discipline_report` mapping from the parsed YAML, validate types+ (enabled: boolean, timezone: string, watched_paths/known_agents:+ string array). On type mismatch, append a `BrainConfigLoadWarning`+ and drop the section (return `undefined`) β do not throw, so an+ invalid config doesn't break unrelated CLI verbs.++- [ ] **Step 5: Run test, expect PASS.**++- [ ] **Step 6: Full sweep.**++**Pause for review.**++### Task 2.2: Brain-log counter per agent++**Files:**+- Create: `src/core/discipline/log-counts.ts`.+- Create: `tests/discipline/log-counts.test.ts`.+- (`tests/discipline/` is new; bun-test discovers it via the+ same root config.)++- [ ] **Step 1: Inspect existing `parseLogDay`** β+ `cat src/core/brain/log.ts | head -120`. Confirm+ `parseLogDay(vault, date)` returns `{ entries, warnings }` where+ each entry has `eventType` and `body`.++- [ ] **Step 2: Write failing test** β+ `tests/discipline/log-counts.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { countBrainEvents } from "../../src/core/discipline/log-counts.ts";++ function vaultWithLog(dayBody: string): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-log-"));+ const dir = join(v, "Brain", "log");+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "2026-05-17.md"),+ "---\nkind: brain-log\ndate: 2026-05-17\ntags: [brain]\n---\n\n" + dayBody,+ "utf8",+ );+ return v;+ }++ describe("countBrainEvents", () => {+ test("buckets by kind per agent and ignores no-agent blocks", () => {+ const body =+ "## 08:00:00Z β feedback\n- agent: @claude-vps-agent\n- topic: foo\n\n" ++ "## 09:00:00Z β apply-evidence\n- agent: @claude-vps-agent\n- pref_id: pref-x\n\n" ++ "## 10:00:00Z β feedback\n- agent: @codex-vps-agent\n- topic: bar\n\n" ++ "## 11:00:00Z β dream-pass\n- agent: @claude-vps-agent\n- promoted: 0\n\n" ++ "## 12:00:00Z β snapshot\n- run_id: x\n";+ const v = vaultWithLog(body);+ const out = countBrainEvents(v, "2026-05-17", [+ "@claude-vps-agent",+ "@codex-vps-agent",+ ]);+ expect(out.byAgent["@claude-vps-agent"]).toEqual({+ feedback: 1,+ apply_evidence: 1,+ other: 1,+ total: 3,+ });+ expect(out.byAgent["@codex-vps-agent"]).toEqual({+ feedback: 1,+ apply_evidence: 0,+ other: 0,+ total: 1,+ });+ expect(out.total).toBe(4);+ expect(out.unknownAgents).toEqual([]);+ rmSync(v, { recursive: true });+ });++ test("agent missing from known_agents shows under unknownAgents", () => {+ const body =+ "## 08:00:00Z β feedback\n- agent: @stranger\n- topic: foo\n\n";+ const v = vaultWithLog(body);+ const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent"]);+ expect(out.byAgent["@claude-vps-agent"]).toEqual({+ feedback: 0,+ apply_evidence: 0,+ other: 0,+ total: 0,+ });+ expect(out.unknownAgents).toEqual([+ { agent: "@stranger", counts: { feedback: 1, apply_evidence: 0, other: 0, total: 1 } },+ ]);+ rmSync(v, { recursive: true });+ });++ test("missing log file β all zeros, no error", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-log-empty-"));+ const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent"]);+ expect(out.total).toBe(0);+ expect(out.byAgent["@claude-vps-agent"].total).toBe(0);+ rmSync(v, { recursive: true });+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL.**++- [ ] **Step 4: Implement** β `src/core/discipline/log-counts.ts`:++ ```ts+ import { parseLogDay } from "../brain/log.ts";++ export interface AgentCounts {+ readonly feedback: number;+ readonly apply_evidence: number;+ readonly other: number;+ readonly total: number;+ }++ export interface BrainEventCounts {+ readonly byAgent: Readonly<Record<string, AgentCounts>>;+ readonly unknownAgents: ReadonlyArray<{ agent: string; counts: AgentCounts }>;+ readonly total: number;+ }++ function zero(): AgentCounts {+ return { feedback: 0, apply_evidence: 0, other: 0, total: 0 };+ }++ function bump(c: AgentCounts, kind: string): AgentCounts {+ if (kind === "feedback") return { ...c, feedback: c.feedback + 1, total: c.total + 1 };+ if (kind === "apply-evidence") return { ...c, apply_evidence: c.apply_evidence + 1, total: c.total + 1 };+ return { ...c, other: c.other + 1, total: c.total + 1 };+ }++ export function countBrainEvents(+ vault: string,+ date: string,+ knownAgents: ReadonlyArray<string>,+ ): BrainEventCounts {+ const byAgent: Record<string, AgentCounts> = {};+ for (const a of knownAgents) byAgent[a] = zero();++ const unknown: Record<string, AgentCounts> = {};+ const { entries } = parseLogDay(vault, date);+ let total = 0;+ for (const e of entries) {+ const agentField = e.body["agent"];+ if (!agentField || Array.isArray(agentField)) continue;+ const target = knownAgents.includes(agentField)+ ? byAgent+ : unknown;+ target[agentField] = bump(target[agentField] ?? zero(), e.eventType);+ total += 1;+ }++ return {+ byAgent,+ unknownAgents: Object.entries(unknown).map(([agent, counts]) => ({ agent, counts })),+ total,+ };+ }+ ```++- [ ] **Step 5: Run test, expect PASS.**++- [ ] **Step 6: Full sweep.**++**Pause for review.**++### Task 2.3: Date-window helper (vault tz β UTC bounds)++**Files:**+- Create: `src/core/discipline/window.ts`.+- Create: `tests/discipline/window.test.ts`.++- [ ] **Step 1: Write failing test** β `tests/discipline/window.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { yesterdayWindow } from "../../src/core/discipline/window.ts";++ describe("yesterdayWindow", () => {+ test("Europe/Belgrade at 06:00 local β window covers prior local day", () => {+ // 2026-05-18T06:00:00 in Belgrade = 2026-05-18T04:00:00Z (CEST UTC+2).+ const now = new Date("2026-05-18T04:00:00Z");+ const w = yesterdayWindow(now, "Europe/Belgrade");+ expect(w.localDate).toBe("2026-05-17");+ // Window starts at 2026-05-17T00:00:00 local = 2026-05-16T22:00:00Z.+ expect(w.startUtc.toISOString()).toBe("2026-05-16T22:00:00.000Z");+ expect(w.endUtc.toISOString()).toBe("2026-05-17T22:00:00.000Z");+ });++ test("UTC timezone β naive 24h window", () => {+ const now = new Date("2026-05-18T03:00:00Z");+ const w = yesterdayWindow(now, "UTC");+ expect(w.localDate).toBe("2026-05-17");+ expect(w.startUtc.toISOString()).toBe("2026-05-17T00:00:00.000Z");+ expect(w.endUtc.toISOString()).toBe("2026-05-18T00:00:00.000Z");+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/window.ts`:++ ```ts+ export interface YesterdayWindow {+ readonly localDate: string; // YYYY-MM-DD in tz+ readonly startUtc: Date;+ readonly endUtc: Date;+ }++ /**+ * Compute the [start, end) UTC interval that covers "yesterday" in the+ * given IANA timezone, relative to `now`. The Intl API is used to+ * project `now` to the local civil date and the day boundaries back+ * to UTC β JS has no built-in tz-aware Date arithmetic, but Intl+ * formatting is enough for our purposes (granularity: 1 second).+ */+ export function yesterdayWindow(now: Date, tz: string): YesterdayWindow {+ // Project now β local civil date.+ const fmt = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit",+ });+ const todayLocal = fmt.format(now); // e.g. "2026-05-18"+ const [y, m, d] = todayLocal.split("-").map(Number);+ const todayLocalMidnightUtc = localMidnightUtc(y, m, d, tz);+ const yesterdayLocalMidnightUtc = new Date(+ todayLocalMidnightUtc.getTime() - 24 * 60 * 60 * 1000,+ );+ // localDate = yesterday in tz+ const localDate = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit",+ }).format(yesterdayLocalMidnightUtc);+ return {+ localDate,+ startUtc: yesterdayLocalMidnightUtc,+ endUtc: todayLocalMidnightUtc,+ };+ }++ /**+ * Find the UTC instant that corresponds to local midnight on the given+ * civil date in tz. Binary-search-free: try the naive UTC midnight,+ * then iteratively correct using Intl's offset for that instant. Two+ * iterations is enough for any IANA timezone (verified against tzdata+ * 2024a β no DST transition shifts by more than 1 hour from a+ * 24-hour-aligned UTC instant).+ */+ function localMidnightUtc(y: number, m: number, d: number, tz: string): Date {+ let guess = new Date(Date.UTC(y, m - 1, d, 0, 0, 0));+ for (let i = 0; i < 4; i++) {+ const local = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit",+ hour: "2-digit", minute: "2-digit", second: "2-digit",+ hourCycle: "h23",+ }).format(guess);+ // Parse "YYYY-MM-DD, HH:MM:SS"+ const [date, time] = local.split(", ");+ const [hh, mm, ss] = time.split(":").map(Number);+ const drift = hh * 3600 + mm * 60 + ss;+ if (date === `${y.toString().padStart(4, "0")}-${m.toString().padStart(2, "0")}-${d.toString().padStart(2, "0")}` && drift === 0) return guess;+ guess = new Date(guess.getTime() - drift * 1000);+ }+ return guess;+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.4: Git-activity proxy++**Files:**+- Create: `src/core/discipline/activity-git.ts`.+- Create: `tests/discipline/activity-git.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/activity-git.test.ts`:++ ```ts+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";+ import { execSync } from "node:child_process";+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { gitActivity } from "../../src/core/discipline/activity-git.ts";++ let repo: string;++ beforeAll(() => {+ repo = mkdtempSync(join(tmpdir(), "o2b-disc-git-"));+ execSync("git init -q -b main", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ writeFileSync(join(repo, "a.txt"), "hello\n");+ execSync("git add a.txt && git commit -q -m c1 --date=2026-05-17T10:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z" } });+ writeFileSync(join(repo, "a.txt"), "hello\nworld\n");+ execSync("git add a.txt && git commit -q -m c2 --date=2026-05-17T20:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T20:00:00Z" } });+ writeFileSync(join(repo, "b.txt"), "x\n");+ execSync("git add b.txt && git commit -q -m c3 --date=2026-05-18T10:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-18T10:00:00Z" } });+ });+ afterAll(() => rmSync(repo, { recursive: true, force: true }));++ describe("gitActivity", () => {+ test("counts only commits inside the [start, end) UTC window", () => {+ const out = gitActivity(repo, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out.commits).toBe(2);+ expect(out.filesChanged).toBe(1);+ expect(out.insertions).toBe(2); // 1 + 1+ expect(out.deletions).toBe(0);+ });++ test("non-git path β null sentinel, no throw", () => {+ const empty = mkdtempSync(join(tmpdir(), "o2b-disc-nogit-"));+ const out = gitActivity(empty, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out).toBeNull();+ rmSync(empty, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/activity-git.ts`:++ ```ts+ import { existsSync } from "node:fs";+ import { execFileSync } from "node:child_process";+ import { join } from "node:path";++ export interface ActivityWindow {+ readonly startUtc: Date;+ readonly endUtc: Date;+ }++ export interface GitActivity {+ readonly commits: number;+ readonly filesChanged: number;+ readonly insertions: number;+ readonly deletions: number;+ }++ export function gitActivity(+ path: string,+ win: ActivityWindow,+ ): GitActivity | null {+ if (!existsSync(join(path, ".git"))) return null;+ const since = win.startUtc.toISOString();+ const until = win.endUtc.toISOString();+ let raw: string;+ try {+ raw = execFileSync(+ "git",+ [+ "-C", path, "log",+ `--since=${since}`, `--until=${until}`,+ "--no-merges", "--shortstat",+ "--pretty=tformat:__COMMIT__",+ ],+ { encoding: "utf8" },+ );+ } catch {+ return { commits: 0, filesChanged: 0, insertions: 0, deletions: 0 };+ }++ const out = { commits: 0, filesChanged: 0, insertions: 0, deletions: 0 };+ for (const line of raw.split("\n")) {+ if (line === "__COMMIT__") {+ out.commits += 1;+ continue;+ }+ // " 1 file changed, 2 insertions(+), 1 deletion(-)"+ const m = line.match(/(\d+)\s+files?\s+changed(?:,\s+(\d+)\s+insertions?\(\+\))?(?:,\s+(\d+)\s+deletions?\(-\))?/);+ if (!m) continue;+ out.filesChanged += Number(m[1]);+ out.insertions += Number(m[2] ?? 0);+ out.deletions += Number(m[3] ?? 0);+ }+ return out;+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.5: Non-git mtime walk++**Files:**+- Create: `src/core/discipline/activity-mtime.ts`.+- Create: `tests/discipline/activity-mtime.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/activity-mtime.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import {+ mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync,+ } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { mtimeActivity } from "../../src/core/discipline/activity-mtime.ts";++ function touch(path: string, isoUtc: string): void {+ const ts = new Date(isoUtc).getTime() / 1000;+ utimesSync(path, ts, ts);+ }++ describe("mtimeActivity", () => {+ test("counts files mtime'd inside the window; excludes noise dirs", () => {+ const root = mkdtempSync(join(tmpdir(), "o2b-disc-mtime-"));+ writeFileSync(join(root, "in1.txt"), "x");+ touch(join(root, "in1.txt"), "2026-05-17T10:00:00Z");+ writeFileSync(join(root, "in2.md"), "x");+ touch(join(root, "in2.md"), "2026-05-17T20:00:00Z");+ writeFileSync(join(root, "out.txt"), "x");+ touch(join(root, "out.txt"), "2026-05-18T10:00:00Z");+ mkdirSync(join(root, "node_modules"), { recursive: true });+ writeFileSync(join(root, "node_modules", "noise.js"), "x");+ touch(join(root, "node_modules", "noise.js"), "2026-05-17T15:00:00Z");+ mkdirSync(join(root, "subdir"));+ writeFileSync(join(root, "subdir", "in3.md"), "x");+ touch(join(root, "subdir", "in3.md"), "2026-05-17T15:00:00Z");++ const out = mtimeActivity(root, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out.modifiedFiles).toBe(3);+ rmSync(root, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/activity-mtime.ts`:++ ```ts+ import { readdirSync, statSync } from "node:fs";+ import { join } from "node:path";+ import type { ActivityWindow } from "./activity-git.ts";++ const EXCLUDE_DIRS: ReadonlySet<string> = new Set([+ ".git", ".hg", ".svn",+ "node_modules", ".cache",+ "__pycache__", ".venv", "venv",+ ".snapshots",+ "dist", "build", "out",+ ]);++ export interface MtimeActivity {+ readonly modifiedFiles: number;+ }++ export function mtimeActivity(root: string, win: ActivityWindow): MtimeActivity {+ const startMs = win.startUtc.getTime();+ const endMs = win.endUtc.getTime();+ let count = 0;++ function walk(dir: string): void {+ let entries: string[];+ try {+ entries = readdirSync(dir);+ } catch {+ return;+ }+ for (const name of entries) {+ if (EXCLUDE_DIRS.has(name)) continue;+ const p = join(dir, name);+ let st;+ try {+ st = statSync(p);+ } catch {+ continue;+ }+ if (st.isDirectory()) {+ walk(p);+ continue;+ }+ if (!st.isFile()) continue;+ const m = st.mtimeMs;+ if (m >= startMs && m < endMs) count += 1;+ }+ }++ walk(root);+ return { modifiedFiles: count };+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.6: Vault delta source++**Files:**+- Create: `src/core/discipline/vault-delta.ts`.+- Create: `tests/discipline/vault-delta.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/vault-delta.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { vaultDelta } from "../../src/core/discipline/vault-delta.ts";++ function touch(path: string, iso: string): void {+ const t = new Date(iso).getTime() / 1000;+ utimesSync(path, t, t);+ }++ describe("vaultDelta", () => {+ test("counts signal / preference / retired files inside window", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-delta-"));+ mkdirSync(join(v, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(v, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(v, "Brain", "retired"), { recursive: true });+ writeFileSync(join(v, "Brain", "inbox", "sig-1.md"), "x");+ touch(join(v, "Brain", "inbox", "sig-1.md"), "2026-05-17T12:00:00Z");+ writeFileSync(join(v, "Brain", "inbox", "sig-2.md"), "x");+ touch(join(v, "Brain", "inbox", "sig-2.md"), "2026-05-17T13:00:00Z");+ writeFileSync(join(v, "Brain", "preferences", "pref-x.md"), "x");+ touch(join(v, "Brain", "preferences", "pref-x.md"), "2026-05-17T18:00:00Z");+ writeFileSync(join(v, "Brain", "retired", "pref-y.md"), "x");+ touch(join(v, "Brain", "retired", "pref-y.md"), "2026-05-16T10:00:00Z");++ const out = vaultDelta(v, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out.newSignals).toBe(2);+ expect(out.newPreferences).toBe(1);+ expect(out.newRetired).toBe(0);+ expect(out.total).toBe(3);+ rmSync(v, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/vault-delta.ts`:++ ```ts+ import { existsSync, readdirSync, statSync } from "node:fs";+ import { join } from "node:path";+ import type { ActivityWindow } from "./activity-git.ts";++ export interface VaultDelta {+ readonly newSignals: number;+ readonly newPreferences: number;+ readonly newRetired: number;+ readonly total: number;+ }++ function countInWindow(dir: string, win: ActivityWindow): number {+ if (!existsSync(dir)) return 0;+ let n = 0;+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ const st = statSync(p);+ if (!st.isFile()) continue;+ if (st.mtimeMs >= win.startUtc.getTime() && st.mtimeMs < win.endUtc.getTime()) n += 1;+ }+ return n;+ }++ export function vaultDelta(vault: string, win: ActivityWindow): VaultDelta {+ const newSignals = countInWindow(join(vault, "Brain", "inbox"), win);+ const newPreferences = countInWindow(join(vault, "Brain", "preferences"), win);+ const newRetired = countInWindow(join(vault, "Brain", "retired"), win);+ return {+ newSignals, newPreferences, newRetired,+ total: newSignals + newPreferences + newRetired,+ };+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.7: Status decision++**Files:**+- Create: `src/core/discipline/decision.ts`.+- Create: `tests/discipline/decision.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/decision.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { decideStatus } from "../../src/core/discipline/decision.ts";++ describe("decideStatus", () => {+ const noEvents = { byAgent: {}, unknownAgents: [], total: 0 } as any;+ const someEvents = { ...noEvents, total: 5 };+ const noActivity = {+ repo: [], nonRepo: [], vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ } as any;+ const someRepoActivity = {+ ...noActivity, repo: [{ path: "/a", git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 } }],+ };+ const someMtimeActivity = {+ ...noActivity, nonRepo: [{ path: "/b", modifiedFiles: 5 }],+ };+ const someVaultDelta = {+ ...noActivity, vaultDelta: { newSignals: 0, newPreferences: 1, newRetired: 0, total: 1 },+ };++ test("0 events + 0 activity β info", () => {+ expect(decideStatus(noEvents, noActivity)).toBe("info");+ });+ test("0 events + repo activity β alert", () => {+ expect(decideStatus(noEvents, someRepoActivity)).toBe("alert");+ });+ test("0 events + mtime activity (>=3) β alert", () => {+ expect(decideStatus(noEvents, someMtimeActivity)).toBe("alert");+ });+ test("0 events + mtime activity (<3) β info", () => {+ const low = { ...noActivity, nonRepo: [{ path: "/b", modifiedFiles: 2 }] };+ expect(decideStatus(noEvents, low)).toBe("info");+ });+ test("0 events + vault delta β alert", () => {+ expect(decideStatus(noEvents, someVaultDelta)).toBe("alert");+ });+ test("any events present β ok regardless of activity", () => {+ expect(decideStatus(someEvents, noActivity)).toBe("ok");+ expect(decideStatus(someEvents, someRepoActivity)).toBe("ok");+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/decision.ts`:++ ```ts+ import type { BrainEventCounts } from "./log-counts.ts";+ import type { GitActivity } from "./activity-git.ts";+ import type { MtimeActivity } from "./activity-mtime.ts";+ import type { VaultDelta } from "./vault-delta.ts";++ export interface RepoActivityRow {+ readonly path: string;+ readonly git: GitActivity;+ }+ export interface NonRepoActivityRow {+ readonly path: string;+ readonly modifiedFiles: number;+ }++ export interface ActivitySummary {+ readonly repo: ReadonlyArray<RepoActivityRow>;+ readonly nonRepo: ReadonlyArray<NonRepoActivityRow>;+ readonly vaultDelta: VaultDelta;+ }++ export type DisciplineStatus = "ok" | "info" | "alert";++ export function decideStatus(+ events: BrainEventCounts,+ activity: ActivitySummary,+ ): DisciplineStatus {+ if (events.total > 0) return "ok";+ const repoCommits = activity.repo.reduce((a, r) => a + r.git.commits, 0);+ const mtimeFiles = activity.nonRepo.reduce((a, r) => a + r.modifiedFiles, 0);+ const vaultActive = activity.vaultDelta.total > 0;+ const activitySignal = repoCommits > 0 || mtimeFiles >= 3 || vaultActive;+ return activitySignal ? "alert" : "info";+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.8: Telegram MarkdownV2 escape++**Files:**+- Create: `src/core/discipline/telegram.ts`.+- Create: `tests/discipline/telegram.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/telegram.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { escapeMarkdownV2 } from "../../src/core/discipline/telegram.ts";++ describe("escapeMarkdownV2", () => {+ test("escapes the 16 reserved characters", () => {+ const input = "_*[]()~`>#+-=|{}.!\\";+ const out = escapeMarkdownV2(input);+ // Each reserved char becomes \X.+ expect(out).toBe("\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\-\\=\\|\\{\\}\\.\\!\\\\");+ });+ test("leaves regular text untouched", () => {+ expect(escapeMarkdownV2("hello world 123")).toBe("hello world 123");+ });+ test("escapes a realistic agent identifier", () => {+ expect(escapeMarkdownV2("@claude-vps-agent")).toBe("@claude\\-vps\\-agent");+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/telegram.ts`:++ ```ts+ // Telegram MarkdownV2 reserves these β backslash-escape them.+ const RESERVED = /([_*\[\]()~`>#+\-=|{}.!\\])/g;++ export function escapeMarkdownV2(s: string): string {+ return s.replace(RESERVED, "\\$1");+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.9: Render the Telegram block++**Files:**+- Create: `src/core/discipline/render.ts`.+- Create: `tests/discipline/render.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/render.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { renderReport } from "../../src/core/discipline/render.ts";++ describe("renderReport", () => {+ test("status: ok with two agents, one repo, vault delta", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "Europe/Belgrade",+ status: "ok",+ events: {+ byAgent: {+ "@claude-vps-agent": { feedback: 2, apply_evidence: 3, other: 0, total: 5 },+ "@codex-vps-agent": { feedback: 0, apply_evidence: 0, other: 0, total: 0 },+ },+ unknownAgents: [],+ total: 5,+ },+ activity: {+ repo: [{ path: "/srv/projects/foo", git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 1, newPreferences: 0, newRetired: 0, total: 1 },+ },+ });+ expect(text).toContain("OSB discipline");+ expect(text).toContain("2026\\-05\\-17");+ expect(text).toContain("Europe/Belgrade");+ expect(text).toContain("Status: ok");+ expect(text).toContain("@claude\\-vps\\-agent");+ expect(text).toContain("2 feedback, 3 apply\\-evidence, 0 other \\(total 5\\)");+ expect(text).toContain("/srv/projects/foo");+ expect(text).toContain("4 commits");+ expect(text).toContain("vault");+ expect(text).not.toContain("Activity ratio");+ });++ test("status: alert appends the explanatory line", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ activity: {+ repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ },+ });+ expect(text).toContain("Status: alert");+ expect(text).toContain("zero brain events");+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/render.ts`:++ ```ts+ import { escapeMarkdownV2 as e } from "./telegram.ts";+ import type { BrainEventCounts } from "./log-counts.ts";+ import type { ActivitySummary, DisciplineStatus } from "./decision.ts";++ export interface RenderInput {+ readonly localDate: string;+ readonly timezone: string;+ readonly status: DisciplineStatus;+ readonly events: BrainEventCounts;+ readonly activity: ActivitySummary;+ }++ export function renderReport(r: RenderInput): string {+ const lines: string[] = [];+ lines.push(`π§ OSB discipline β ${e(r.localDate)} \\(${e(r.timezone)}\\)`);+ lines.push("");+ lines.push(`Status: ${e(r.status)}`);+ lines.push("");++ lines.push("Brain events:");+ const knownEntries = Object.entries(r.events.byAgent);+ if (knownEntries.length === 0) {+ lines.push("\\- \\(no known agents configured\\)");+ } else {+ for (const [agent, c] of knownEntries) {+ lines.push(+ `\\- ${e(agent)}: ${c.feedback} feedback, ${c.apply_evidence} apply\\-evidence, ${c.other} other \\(total ${c.total}\\)`,+ );+ }+ }+ for (const u of r.events.unknownAgents) {+ lines.push(+ `\\- ${e(u.agent)} \\(unknown\\): ${u.counts.feedback} feedback, ${u.counts.apply_evidence} apply\\-evidence, ${u.counts.other} other \\(total ${u.counts.total}\\)`,+ );+ }+ lines.push("");++ lines.push("Activity:");+ for (const row of r.activity.repo) {+ lines.push(+ `\\- ${e(row.path)} β ${row.git.commits} commits, ${row.git.filesChanged} files, \\+${row.git.insertions}/\\-${row.git.deletions}`,+ );+ }+ for (const row of r.activity.nonRepo) {+ lines.push(`\\- ${e(row.path)} β ${row.modifiedFiles} modified files`);+ }+ const vd = r.activity.vaultDelta;+ lines.push(+ `\\- vault β ${vd.newSignals} new signals, ${vd.newPreferences} new preferences, ${vd.newRetired} new retired`,+ );++ if (r.status === "alert") {+ lines.push("");+ lines.push(+ "\\_Activity present; zero brain events recorded\\. Stop guardrail likely bypassed or hook regressed\\.\\_",+ );+ }+ return lines.join("\n");+ }+ ```++ Note the em-dash `β` in "Activity:" / "vault β" lines is the+ literal Unicode character (U+2014). Telegram MarkdownV2 does not+ treat it as reserved, so no escape needed; the escape helper+ leaves it alone.++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.10: Orchestrator `runDisciplineReport`++**Files:**+- Create: `src/core/discipline/report.ts`.+- Create: `tests/discipline/report.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/discipline/report.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { execSync } from "node:child_process";+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { runDisciplineReport } from "../../src/core/discipline/report.ts";++ describe("runDisciplineReport", () => {+ test("end-to-end: empty log + active repo β alert text emitted", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-e2e-vault-"));+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n" ++ " enabled: true\n timezone: UTC\n" ++ " watched_paths:\n - " + vault + "/repo\n" ++ " known_agents:\n - '@claude-vps-agent'\n",+ "utf8",+ );++ const repo = join(vault, "repo");+ mkdirSync(repo);+ execSync("git init -q -b main", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ writeFileSync(join(repo, "a.txt"), "hi\n");+ execSync("git add . && git commit -q -m c1", {+ cwd: repo,+ env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z", GIT_AUTHOR_DATE: "2026-05-17T10:00:00Z" },+ });++ const res = runDisciplineReport({+ vault,+ now: new Date("2026-05-18T01:00:00Z"),+ });+ expect(res.status).toBe("alert");+ expect(res.text).toContain("Status: alert");+ expect(res.text).toContain("1 commits");+ rmSync(vault, { recursive: true });+ });++ test("disabled config β result.status='disabled', empty text", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-dis-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n enabled: false\n timezone: UTC\n watched_paths: []\n known_agents: []\n",+ "utf8",+ );+ const res = runDisciplineReport({ vault, now: new Date() });+ expect(res.status).toBe("disabled");+ expect(res.text).toBe("");+ rmSync(vault, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/core/discipline/report.ts`:++ ```ts+ import { loadBrainConfig } from "../brain/policy.ts";+ import { existsSync } from "node:fs";+ import { join } from "node:path";++ import { countBrainEvents, type BrainEventCounts } from "./log-counts.ts";+ import { gitActivity } from "./activity-git.ts";+ import { mtimeActivity } from "./activity-mtime.ts";+ import { vaultDelta } from "./vault-delta.ts";+ import { decideStatus, type ActivitySummary, type DisciplineStatus } from "./decision.ts";+ import { renderReport } from "./render.ts";+ import { yesterdayWindow } from "./window.ts";++ export interface RunDisciplineReportOpts {+ readonly vault: string;+ readonly now?: Date;+ }++ export interface DisciplineReportResult {+ readonly status: DisciplineStatus | "disabled";+ readonly text: string;+ readonly localDate: string | null;+ readonly events: BrainEventCounts | null;+ readonly activity: ActivitySummary | null;+ }++ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineReportResult {+ const cfg = loadBrainConfig(opts.vault);+ const d = cfg.discipline_report;+ if (!d || !d.enabled) {+ return { status: "disabled", text: "", localDate: null, events: null, activity: null };+ }+ const now = opts.now ?? new Date();+ const win = yesterdayWindow(now, d.timezone);+ const events = countBrainEvents(opts.vault, win.localDate, d.known_agents);++ const repo: ActivitySummary["repo"] = [];+ const nonRepo: ActivitySummary["nonRepo"] = [];+ for (const p of d.watched_paths) {+ const g = gitActivity(p, win);+ if (g !== null) {+ repo.push({ path: p, git: g });+ } else if (existsSync(p)) {+ const m = mtimeActivity(p, win);+ nonRepo.push({ path: p, modifiedFiles: m.modifiedFiles });+ }+ }+ const vd = vaultDelta(opts.vault, win);++ const activity: ActivitySummary = { repo, nonRepo, vaultDelta: vd };+ const status = decideStatus(events, activity);+ const text = renderReport({+ localDate: win.localDate,+ timezone: d.timezone,+ status,+ events,+ activity,+ });+ return { status, text, localDate: win.localDate, events, activity };+ }+ ```++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review.**++### Task 2.11: `bin/o2b-discipline-report` script++**Files:**+- Create: `bin/o2b-discipline-report` (executable).+- (Tested via the CLI verb in Task 2.12; this is a thin shim.)++- [ ] **Step 1: Create file** β+ `bin/o2b-discipline-report` with content:++ ```bash+ #!/usr/bin/env bash+ set -euo pipefail+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ exec bun run "$HERE/../scripts/discipline-report.ts" "$@"+ ```++- [ ] **Step 2: Create the actual TS entry** β+ `scripts/discipline-report.ts`:++ ```ts+ #!/usr/bin/env -S bun+ import { discoverConfig } from "../src/core/config.ts";+ import { runDisciplineReport } from "../src/core/discipline/report.ts";++ function readVaultArg(): string {+ const argv = process.argv.slice(2);+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === "--vault" && argv[i + 1]) return argv[i + 1]!;+ }+ const cfg = discoverConfig();+ const v = cfg.data["vault"];+ if (typeof v !== "string" || !v) {+ process.stderr.write("o2b-discipline-report: no vault configured; pass --vault <path>\n");+ process.exit(2);+ }+ return v;+ }++ const vault = readVaultArg();+ const res = runDisciplineReport({ vault });+ if (res.status === "disabled") {+ process.stderr.write("o2b-discipline-report: discipline_report disabled in Brain/_brain.yaml\n");+ process.exit(0);+ }+ process.stdout.write(res.text + "\n");+ ```++- [ ] **Step 3: `chmod +x bin/o2b-discipline-report`.**++- [ ] **Step 4: Smoke-test from shell**:++ ```bash+ cd /srv/projects/open-second-brain+ ./bin/o2b-discipline-report --vault /tmp/nonexistent || true+ ```++ Expected: prints a clear error to stderr (vault directory missing+ or no Brain config), exits non-zero. Does not crash.++- [ ] **Step 5: Add `bin/o2b-discipline-report` to `package.json`+ `files` field** so it ships in npm publish.++**Pause for review.**++### Task 2.12: `o2b discipline report` CLI verb++**Files:**+- Modify: `src/cli/main.ts`.+- Create: `src/cli/discipline.ts`.+- Create: `tests/cli/discipline-report.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/cli/discipline-report.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import { runCli } from "../helpers/run-cli.ts";++ describe("o2b discipline report", () => {+ test("happy path prints the rendered block", async () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-cli-"));+ mkdirSync(join(v, "Brain"), { recursive: true });+ writeFileSync(+ join(v, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n enabled: true\n timezone: UTC\n watched_paths: []\n known_agents:\n - '@a'\n",+ "utf8",+ );+ const res = await runCli(["discipline", "report", "--vault", v]);+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("OSB discipline");+ rmSync(v, { recursive: true });+ });++ test("disabled config exits 0 with stderr note", async () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-cli2-"));+ mkdirSync(join(v, "Brain"), { recursive: true });+ writeFileSync(+ join(v, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n enabled: false\n timezone: UTC\n watched_paths: []\n known_agents: []\n",+ "utf8",+ );+ const res = await runCli(["discipline", "report", "--vault", v]);+ expect(res.returncode).toBe(0);+ expect(res.stderr).toContain("disabled");+ rmSync(v, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run tests, expect FAIL.**++- [ ] **Step 3: Implement `src/cli/discipline.ts`**:++ ```ts+ import { runDisciplineReport } from "../core/discipline/report.ts";++ export async function disciplineReportVerb(+ args: string[],+ defaultVault: string,+ ): Promise<number> {+ let vault = defaultVault;+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault" && args[i + 1]) {+ vault = args[i + 1]!;+ i++;+ }+ }+ const res = runDisciplineReport({ vault });+ if (res.status === "disabled") {+ process.stderr.write(+ "o2b discipline report: discipline_report disabled in Brain/_brain.yaml\n",+ );+ return 0;+ }+ process.stdout.write(res.text + "\n");+ return 0;+ }+ ```++- [ ] **Step 4: Wire into `src/cli/main.ts`** β add a new top-level+ branch:++ ```ts+ if (verb === "discipline") {+ const sub = args.shift();+ if (sub === "report") return disciplineReportVerb(args, defaultVault);+ if (sub === "install") return disciplineInstallVerb(args, defaultVault);+ if (sub === "uninstall") return disciplineUninstallVerb(args, defaultVault);+ process.stderr.write(`o2b discipline: unknown subcommand '${sub}'\n`);+ return 2;+ }+ ```++ (Install/uninstall land in Task 2.13.)++- [ ] **Step 5: Run tests, expect PASS.**++- [ ] **Step 6: Full sweep.**++**Pause for review.**++### Task 2.13: `o2b discipline install / uninstall` (Hermes cron CRUD)++**Files:**+- Create: `src/cli/discipline-install.ts`.+- Create: `tests/cli/discipline-install.test.ts`.++- [ ] **Step 1: Write failing test** β+ `tests/cli/discipline-install.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import { runCli } from "../helpers/run-cli.ts";++ function emptyJobsFile(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-disc-cron-"));+ const file = join(dir, "jobs.json");+ writeFileSync(file, JSON.stringify({ jobs: [] }), "utf8");+ return file;+ }++ describe("o2b discipline install / uninstall", () => {+ test("install creates exactly one job; reinstall is no-op; uninstall removes", async () => {+ const jobsFile = emptyJobsFile();+ const env = { OSB_HERMES_JOBS: jobsFile };++ const r1 = await runCli(+ ["discipline", "install", "--vault", "/tmp/v",+ "--telegram-target", "telegram:-100:42", "--at", "59 4 * * *"],+ { env },+ );+ expect(r1.returncode).toBe(0);+ let after = JSON.parse(readFileSync(jobsFile, "utf8"));+ expect(after.jobs.length).toBe(1);+ expect(after.jobs[0].name).toBe("osb-discipline-report");+ expect(after.jobs[0].deliver).toBe("telegram:-100:42");+ expect(after.jobs[0].schedule.expr).toBe("59 4 * * *");++ const r2 = await runCli(+ ["discipline", "install", "--vault", "/tmp/v",+ "--telegram-target", "telegram:-100:42", "--at", "59 4 * * *"],+ { env },+ );+ expect(r2.returncode).toBe(0);+ after = JSON.parse(readFileSync(jobsFile, "utf8"));+ expect(after.jobs.length).toBe(1);++ const r3 = await runCli(["discipline", "uninstall", "--vault", "/tmp/v"], { env });+ expect(r3.returncode).toBe(0);+ after = JSON.parse(readFileSync(jobsFile, "utf8"));+ expect(after.jobs.length).toBe(0);++ rmSync(jobsFile, { force: true });+ });+ });+ ```++- [ ] **Step 2: Run test, expect FAIL.**++- [ ] **Step 3: Implement** β `src/cli/discipline-install.ts`:++ ```ts+ import { createHash } from "node:crypto";+ import { existsSync, readFileSync, writeFileSync } from "node:fs";+ import { resolve } from "node:path";++ const DEFAULT_JOBS_FILE = "/root/.hermes/cron/jobs.json";++ function jobsFilePath(): string {+ return process.env.OSB_HERMES_JOBS ?? DEFAULT_JOBS_FILE;+ }++ function jobId(vault: string): string {+ const slug = createHash("sha256").update(resolve(vault)).digest("hex").slice(0, 12);+ return `osb-discipline-report-${slug}`;+ }++ interface HermesJob { id: string; name: string; [k: string]: unknown; }+ interface JobsFile { jobs: HermesJob[]; }++ function loadJobs(file: string): JobsFile {+ if (!existsSync(file)) return { jobs: [] };+ return JSON.parse(readFileSync(file, "utf8"));+ }++ function saveJobs(file: string, data: JobsFile): void {+ writeFileSync(file, JSON.stringify(data, null, 2), "utf8");+ }++ export async function disciplineInstallVerb(+ args: string[],+ _defaultVault: string,+ ): Promise<number> {+ let vault = "";+ let telegramTarget = "telegram:-1003895040510:216";+ let at = "59 4 * * *";+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault") { vault = args[++i] ?? ""; continue; }+ if (args[i] === "--telegram-target") { telegramTarget = args[++i] ?? telegramTarget; continue; }+ if (args[i] === "--at") { at = args[++i] ?? at; continue; }+ }+ if (!vault) {+ process.stderr.write("o2b discipline install: --vault is required\n");+ return 2;+ }+ const file = jobsFilePath();+ const data = loadJobs(file);+ const id = jobId(vault);+ const existing = data.jobs.find((j) => j.id === id);+ const next: HermesJob = {+ id,+ name: "osb-discipline-report",+ script: "/srv/projects/open-second-brain/bin/o2b-discipline-report",+ no_agent: true,+ schedule: { kind: "cron", expr: at, display: at },+ deliver: telegramTarget,+ enabled: true,+ };+ if (existing) {+ Object.assign(existing, next);+ } else {+ data.jobs.push(next);+ }+ saveJobs(file, data);+ process.stdout.write(`o2b discipline: job '${id}' ${existing ? "updated" : "created"} (schedule: ${at}, deliver: ${telegramTarget})\n`);+ return 0;+ }++ export async function disciplineUninstallVerb(+ args: string[],+ _defaultVault: string,+ ): Promise<number> {+ let vault = "";+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault") { vault = args[++i] ?? ""; }+ }+ if (!vault) {+ process.stderr.write("o2b discipline uninstall: --vault is required\n");+ return 2;+ }+ const file = jobsFilePath();+ const data = loadJobs(file);+ const id = jobId(vault);+ const before = data.jobs.length;+ data.jobs = data.jobs.filter((j) => j.id !== id);+ saveJobs(file, data);+ const removed = before - data.jobs.length;+ process.stdout.write(`o2b discipline: ${removed > 0 ? "removed" : "no-op"} (job '${id}')\n`);+ return 0;+ }+ ```++ Wire both into `src/cli/main.ts`'s `discipline` branch.++- [ ] **Step 4: Run test, expect PASS.**++- [ ] **Step 5: Full sweep.**++**Pause for review. End of Β§D track.**++---++## Phase 3 β Β§E `o2b brain import-claude-memory`++### Task 3.1: `BRAIN_LOG_EVENT_KIND.importClaudeMemory`++**Files:**+- Modify: `src/core/brain/types.ts`.++- [ ] **Step 1: Locate the existing kind enum** β+ `grep -n "BRAIN_LOG_EVENT_KIND" src/core/brain/types.ts`.++- [ ] **Step 2: Write failing test** β+ `tests/core/brain/types-import-claude-memory.test.ts`:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";++ describe("import-claude-memory log kind", () => {+ test("kind is registered as 'import-claude-memory'", () => {+ expect(BRAIN_LOG_EVENT_KIND.importClaudeMemory).toBe("import-claude-memory");+ });+ });+ ```++- [ ] **Step 3: Run test, expect FAIL.**++- [ ] **Step 4: Add the enum value** in `src/core/brain/types.ts`:++ ```ts+ export const BRAIN_LOG_EVENT_KIND = {+ // ... existing ...+ importClaudeMemory: "import-claude-memory",+ } as const;+ ```++ Add a discriminated-union member for it under+ `BrainLogEvent` (mirrors the `importSession` entry).++- [ ] **Step 5: Run test, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.2: Parse a single MEMORY file++**Files:**+- Create: `src/core/brain/claude-memory-parser.ts`.+- Create: `tests/core/brain/claude-memory-parser.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { parseClaudeMemoryFile } from "../../../src/core/brain/claude-memory-parser.ts";++ const FEEDBACK_FIXTURE = `---+ name: no-em-dashes+ description: Forbidden to use em-dashes in Russian writing for this user; use regular hyphens.+ metadata:+ node_type: memory+ type: feedback+ originSessionId: abc+ ---++ Body text here.++ **Why:** because the user said so.+ **How to apply:** apply everywhere.+ `;++ const USER_FIXTURE = `---+ name: who-am-i+ description: User is a senior developer.+ metadata:+ type: user+ ---++ Body.+ `;++ describe("parseClaudeMemoryFile", () => {+ test("feedback entry β MemoryRecord", () => {+ const r = parseClaudeMemoryFile(FEEDBACK_FIXTURE);+ expect(r.kind).toBe("feedback");+ expect(r.name).toBe("no-em-dashes");+ expect(r.description).toContain("Forbidden to use em-dashes");+ expect(r.body).toContain("**Why:**");+ expect(r.bodySha256).toMatch(/^[0-9a-f]{64}$/);+ });++ test("non-feedback entry β kind='skip', reason recorded", () => {+ const r = parseClaudeMemoryFile(USER_FIXTURE);+ expect(r.kind).toBe("skip");+ expect(r.skipReason).toContain("type=user");+ });++ test("missing frontmatter β kind='skip'", () => {+ const r = parseClaudeMemoryFile("no frontmatter here");+ expect(r.kind).toBe("skip");+ expect(r.skipReason).toContain("frontmatter");+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/claude-memory-parser.ts`:++ ```ts+ import { createHash } from "node:crypto";+ import { load as yamlLoad } from "js-yaml";++ export type ClaudeMemoryParseResult =+ | {+ readonly kind: "feedback";+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly bodySha256: string;+ }+ | {+ readonly kind: "skip";+ readonly skipReason: string;+ };++ const FM_RE = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/;++ export function parseClaudeMemoryFile(text: string): ClaudeMemoryParseResult {+ const m = text.match(FM_RE);+ if (!m) {+ return { kind: "skip", skipReason: "missing or malformed frontmatter" };+ }+ let fm: Record<string, unknown>;+ try {+ fm = (yamlLoad(m[1]) ?? {}) as Record<string, unknown>;+ } catch {+ return { kind: "skip", skipReason: "frontmatter is not valid YAML" };+ }+ const name = typeof fm.name === "string" ? fm.name.trim() : "";+ const description = typeof fm.description === "string" ? fm.description.trim() : "";+ const meta = (fm.metadata as Record<string, unknown> | undefined) ?? {};+ const type = typeof meta.type === "string" ? meta.type : "";+ if (type !== "feedback") {+ return { kind: "skip", skipReason: `type=${type || "<missing>"}; only feedback maps to Brain` };+ }+ if (!name || !description) {+ return { kind: "skip", skipReason: "feedback entry missing required name/description" };+ }+ const body = m[2].trim();+ const bodySha256 = createHash("sha256").update(body).digest("hex");+ return { kind: "feedback", name, description, body, bodySha256 };+ }+ ```++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.3: Manifest sidecar I/O++**Files:**+- Create: `src/core/brain/claude-memory-manifest.ts`.+- Create: `tests/core/brain/claude-memory-manifest.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdtempSync, rmSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import {+ loadManifest, saveManifest, type ClaudeMemoryManifest,+ } from "../../../src/core/brain/claude-memory-manifest.ts";++ describe("claude-memory manifest", () => {+ test("missing file β empty manifest", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-m1-"));+ expect(loadManifest(v)).toEqual({ version: 1, imports: {} });+ rmSync(v, { recursive: true });+ });++ test("round-trip", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-m2-"));+ const m: ClaudeMemoryManifest = {+ version: 1,+ imports: {+ "no-em-dashes.md": {+ pref_id: "pref-no-em-dashes",+ sha256: "a".repeat(64),+ imported_at: "2026-05-18T10:00:00Z",+ },+ },+ };+ saveManifest(v, m);+ expect(loadManifest(v)).toEqual(m);+ rmSync(v, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/claude-memory-manifest.ts`:++ ```ts+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+ import { dirname, join } from "node:path";++ export interface ClaudeMemoryManifestEntry {+ readonly pref_id: string;+ readonly sha256: string;+ readonly imported_at: string;+ }++ export interface ClaudeMemoryManifest {+ readonly version: 1;+ readonly imports: Readonly<Record<string, ClaudeMemoryManifestEntry>>;+ }++ function manifestPath(vault: string): string {+ return join(vault, "Brain", ".imports", "claude-memory.json");+ }++ export function loadManifest(vault: string): ClaudeMemoryManifest {+ const p = manifestPath(vault);+ if (!existsSync(p)) return { version: 1, imports: {} };+ const raw = JSON.parse(readFileSync(p, "utf8"));+ return { version: 1, imports: raw.imports ?? {} };+ }++ export function saveManifest(vault: string, m: ClaudeMemoryManifest): void {+ const p = manifestPath(vault);+ mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, JSON.stringify(m, null, 2) + "\n", "utf8");+ }+ ```++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.4: Decision table per memory file++**Files:**+- Create: `src/core/brain/claude-memory-plan.ts`.+- Create: `tests/core/brain/claude-memory-plan.test.ts`.++- [ ] **Step 1: Write failing test** covering all 6 rows of the+ design-doc decision table:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { planAction } from "../../../src/core/brain/claude-memory-plan.ts";++ describe("planAction", () => {+ const make = (overrides: Partial<Parameters<typeof planAction>[0]>) =>+ planAction({+ basename: "x.md", prefId: "pref-x", sha256: "h",+ inManifest: null, prefExists: false, ...overrides,+ });++ test("no manifest + no pref β CREATE", () => {+ expect(make({}).action).toBe("CREATE");+ });+ test("no manifest + pref exists β CONFLICT", () => {+ expect(make({ prefExists: true }).action).toBe("CONFLICT");+ });+ test("manifest matches + pref exists β SKIP_UNCHANGED", () => {+ expect(make({ inManifest: { sha256: "h" }, prefExists: true }).action).toBe("SKIP_UNCHANGED");+ });+ test("manifest matches + pref missing β RECREATE", () => {+ expect(make({ inManifest: { sha256: "h" }, prefExists: false }).action).toBe("RECREATE");+ });+ test("manifest differs + pref exists β UPDATE", () => {+ expect(make({ inManifest: { sha256: "old" }, prefExists: true }).action).toBe("UPDATE");+ });+ test("manifest differs + pref missing β CREATE (manifest stale)", () => {+ expect(make({ inManifest: { sha256: "old" }, prefExists: false }).action).toBe("CREATE");+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/claude-memory-plan.ts`:++ ```ts+ export type PlanAction =+ | "CREATE"+ | "UPDATE"+ | "RECREATE"+ | "SKIP_UNCHANGED"+ | "CONFLICT";++ export interface PlanActionInput {+ readonly basename: string;+ readonly prefId: string;+ readonly sha256: string;+ readonly inManifest: { sha256: string } | null;+ readonly prefExists: boolean;+ }++ export interface PlannedFile {+ readonly basename: string;+ readonly prefId: string;+ readonly action: PlanAction;+ }++ export function planAction(input: PlanActionInput): PlannedFile {+ const { basename, prefId, sha256, inManifest, prefExists } = input;+ if (inManifest === null) {+ return { basename, prefId, action: prefExists ? "CONFLICT" : "CREATE" };+ }+ if (inManifest.sha256 === sha256) {+ return { basename, prefId, action: prefExists ? "SKIP_UNCHANGED" : "RECREATE" };+ }+ return { basename, prefId, action: prefExists ? "UPDATE" : "CREATE" };+ }+ ```++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.5: Render the Brain preference for a feedback memory++**Files:**+- Create: `src/core/brain/claude-memory-render.ts`.+- Create: `tests/core/brain/claude-memory-render.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { renderPreferenceFromMemory } from "../../../src/core/brain/claude-memory-render.ts";++ describe("renderPreferenceFromMemory", () => {+ test("emits frontmatter + body + Origin block", () => {+ const out = renderPreferenceFromMemory({+ name: "no-em-dashes",+ description: "No em-dashes in Russian writing for this user.",+ body: "Body text.\n\n**Why:** said so.\n**How to apply:** apply everywhere.",+ memoryPath: "/root/.claude/projects/-root/memory/feedback_no_em_dashes.md",+ importedAt: "2026-05-18T10:00:00Z",+ bodySha256: "a".repeat(64),+ });+ expect(out).toMatch(/^---\n/);+ expect(out).toContain("id: pref-no-em-dashes");+ expect(out).toContain("status: confirmed");+ expect(out).toContain("scope: writing");+ expect(out).toContain("confidence: high");+ expect(out).toContain("_force_confirmed_via: claude-memory");+ expect(out).toContain("_imported_from: \"/root/.claude/projects/-root/memory/feedback_no_em_dashes.md\"");+ expect(out).toContain("Body text.");+ expect(out).toContain("**Why:**");+ expect(out).toContain("## Origin");+ expect(out).toContain("on 2026-05-18.");+ });++ test("body scope marker overrides default writing scope", () => {+ const out = renderPreferenceFromMemory({+ name: "x", description: "x",+ body: "First line.\nscope: testing\nrest.",+ memoryPath: "/m.md", importedAt: "2026-05-18T10:00:00Z",+ bodySha256: "a".repeat(64),+ });+ expect(out).toContain("scope: testing");+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/claude-memory-render.ts`:++ ```ts+ export interface RenderMemoryInput {+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly memoryPath: string;+ readonly importedAt: string; // ISO Z+ readonly bodySha256: string;+ }++ const SCOPE_RE = /^scope:\s*([a-z][a-z0-9-]*)\s*$/m;++ function extractScope(body: string): string {+ const m = body.match(SCOPE_RE);+ return m ? m[1] : "writing";+ }++ function isoDay(iso: string): string {+ return iso.slice(0, 10);+ }++ export function renderPreferenceFromMemory(input: RenderMemoryInput): string {+ const slug = input.name.replace(/_/g, "-").replace(/[^a-z0-9-]/gi, "-").toLowerCase();+ const prefId = `pref-${slug}`;+ const topic = slug;+ const scope = extractScope(input.body);+ const fm = [+ "---",+ "kind: brain-preference",+ `id: ${prefId}`,+ `created_at: "${input.importedAt}"`,+ `_confirmed_at: "${input.importedAt}"`,+ `unconfirmed_until: "${input.importedAt}"`,+ `tags: [brain, brain/preference, brain/topic/${topic}, brain/scope/${scope}]`,+ `topic: ${topic}`,+ "_status: confirmed",+ `principle: ${JSON.stringify(input.description)}`,+ "_evidenced_by: []",+ "_applied_count: 0",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: high",+ "pinned: false",+ `scope: ${scope}`,+ "_force_confirmed_via: claude-memory",+ `_imported_from: ${JSON.stringify(input.memoryPath)}`,+ `_imported_sha256: ${input.bodySha256}`,+ `_imported_at: "${input.importedAt}"`,+ "---",+ "",+ input.body.trim(),+ "",+ "## Origin",+ "",+ "Imported from Claude Code MEMORY:",+ `\`${input.memoryPath}\``,+ `on ${isoDay(input.importedAt)}.`,+ "",+ ].join("\n");+ return fm;+ }+ ```++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.6: Path-safety check++**Files:**+- Create: `src/core/brain/claude-memory-paths.ts`.+- Create: `tests/core/brain/claude-memory-paths.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { homedir } from "node:os";+ import { join } from "node:path";+ import { assertSafeMemoryPath } from "../../../src/core/brain/claude-memory-paths.ts";++ describe("assertSafeMemoryPath", () => {+ test("default home β no throw", () => {+ assertSafeMemoryPath(join(homedir(), ".claude", "projects", "-x", "memory"), false);+ });+ test("system path without override β throws", () => {+ expect(() => assertSafeMemoryPath("/etc", false)).toThrow(/not under/);+ });+ test("system path with override β no throw", () => {+ assertSafeMemoryPath("/etc", true);+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/claude-memory-paths.ts`:++ ```ts+ import { homedir } from "node:os";+ import { resolve, sep } from "node:path";++ export function defaultMemoryDir(vault: string): string {+ const slug = "-" + vault.replace(/\//g, "-");+ return resolve(homedir(), ".claude", "projects", slug, "memory");+ }++ export function assertSafeMemoryPath(path: string, override: boolean): void {+ if (override) return;+ const root = resolve(homedir(), ".claude", "projects") + sep;+ const norm = resolve(path);+ if (!norm.startsWith(root)) {+ throw new Error(+ `refusing to import from ${path}: it is not under ~/.claude/projects/.\n` ++ `Pass --allow-arbitrary-memory-path to override.`,+ );+ }+ }+ ```++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.7: Orchestrator `importClaudeMemory`++**Files:**+- Create: `src/core/brain/import-claude-memory.ts`.+- Create: `tests/core/brain/import-claude-memory-orchestrator.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+ import { bootstrapBrain } from "../../../src/core/brain/init.ts";++ function setupVault(): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-orch-"));+ bootstrapBrain(v, { primary_agent: "@test", agent_identity: "@test" });+ return v;+ }++ function setupMemory(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-cm-mem-"));+ writeFileSync(+ join(dir, "feedback_a.md"),+ "---\nname: rule-a\ndescription: Rule A.\nmetadata:\n type: feedback\n---\n\nBody A.\n",+ "utf8",+ );+ writeFileSync(+ join(dir, "feedback_b.md"),+ "---\nname: rule-b\ndescription: Rule B.\nmetadata:\n type: feedback\n---\n\nBody B.\n",+ "utf8",+ );+ writeFileSync(+ join(dir, "user_who.md"),+ "---\nname: who\ndescription: User.\nmetadata:\n type: user\n---\n\nBody.\n",+ "utf8",+ );+ writeFileSync(join(dir, "MEMORY.md"), "# index\n- a\n", "utf8");+ return dir;+ }++ describe("importClaudeMemory", () => {+ test("dry-run reports plan, performs no writes", () => {+ const vault = setupVault();+ const mem = setupMemory();+ const res = importClaudeMemory({+ vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true,+ });+ expect(res.plans.map((p) => p.action).sort()).toEqual(["CREATE", "CREATE"]);+ expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlier+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(false);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("apply writes preferences, manifest, and log event", () => {+ const vault = setupVault();+ const mem = setupMemory();+ const res = importClaudeMemory({+ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true,+ now: new Date("2026-05-18T10:00:00Z"),+ });+ expect(res.applied.length).toBe(2);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-b.md"))).toBe(true);+ const manifest = JSON.parse(readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"));+ expect(Object.keys(manifest.imports).sort()).toEqual(["feedback_a.md", "feedback_b.md"]);+ const log = readFileSync(join(vault, "Brain", "log", res.localDate + ".md"), "utf8");+ expect(log).toContain("import-claude-memory");+ expect(log).toContain("created: 2");+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("second apply with no change β SKIP_UNCHANGED, zero writes", () => {+ const vault = setupVault();+ const mem = setupMemory();+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });+ const before = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");+ const res2 = importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });+ expect(res2.applied.length).toBe(0);+ expect(res2.skippedUnchanged.length).toBe(2);+ const after = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");+ expect(after).toBe(before);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.**++- [ ] **Step 3: Implement** β+ `src/core/brain/import-claude-memory.ts`:++ ```ts+ import { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";+ import { join } from "node:path";++ import { appendLogEvent } from "./log.ts";+ import { BRAIN_LOG_EVENT_KIND } from "./types.ts";+ import { createSnapshot } from "./snapshot.ts";+ import { resolveAgentName } from "../config.ts";+ import { parseClaudeMemoryFile } from "./claude-memory-parser.ts";+ import {+ loadManifest, saveManifest, type ClaudeMemoryManifest,+ } from "./claude-memory-manifest.ts";+ import { planAction, type PlannedFile } from "./claude-memory-plan.ts";+ import { renderPreferenceFromMemory } from "./claude-memory-render.ts";+ import { assertSafeMemoryPath } from "./claude-memory-paths.ts";+ import { preferencePath } from "./paths.ts";++ export interface ImportClaudeMemoryOpts {+ readonly vault: string;+ readonly memoryDir: string;+ readonly mode: "dry-run" | "apply";+ readonly allowArbitraryMemoryPath?: boolean;+ readonly now?: Date;+ }++ export interface ImportClaudeMemoryResult {+ readonly mode: "dry-run" | "apply";+ readonly plans: ReadonlyArray<PlannedFile>;+ readonly skipped: ReadonlyArray<{ basename: string; reason: string }>;+ readonly conflicts: ReadonlyArray<PlannedFile>;+ readonly applied: ReadonlyArray<PlannedFile>;+ readonly skippedUnchanged: ReadonlyArray<PlannedFile>;+ readonly snapshotRunId: string | null;+ readonly localDate: string;+ }++ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMemoryResult {+ assertSafeMemoryPath(opts.memoryDir, opts.allowArbitraryMemoryPath ?? false);+ if (!existsSync(opts.memoryDir)) {+ throw new Error(`memory directory not found: ${opts.memoryDir}`);+ }+ const now = opts.now ?? new Date();+ const importedAt = now.toISOString().replace(/\.\d{3}Z$/, "Z");+ const localDate = importedAt.slice(0, 10);++ const manifest = loadManifest(opts.vault);+ const newImports: Record<string, { pref_id: string; sha256: string; imported_at: string }> = { ...manifest.imports };++ const plans: PlannedFile[] = [];+ const skipped: Array<{ basename: string; reason: string }> = [];+ const filesToWrite: Array<{ plan: PlannedFile; body: string; sha256: string }> = [];++ for (const name of readdirSync(opts.memoryDir).sort()) {+ if (name === "MEMORY.md") continue;+ if (!name.endsWith(".md")) continue;+ const text = readFileSync(join(opts.memoryDir, name), "utf8");+ const parsed = parseClaudeMemoryFile(text);+ if (parsed.kind === "skip") {+ skipped.push({ basename: name, reason: parsed.skipReason });+ continue;+ }+ const slug = parsed.name.replace(/_/g, "-").replace(/[^a-z0-9-]/gi, "-").toLowerCase();+ const prefId = `pref-${slug}`;+ const prefFile = preferencePath(opts.vault, prefId);+ const plan = planAction({+ basename: name,+ prefId,+ sha256: parsed.bodySha256,+ inManifest: manifest.imports[name] ? { sha256: manifest.imports[name]!.sha256 } : null,+ prefExists: existsSync(prefFile),+ });+ plans.push(plan);+ if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {+ const body = renderPreferenceFromMemory({+ name: parsed.name,+ description: parsed.description,+ body: parsed.body,+ memoryPath: join(opts.memoryDir, name),+ importedAt,+ bodySha256: parsed.bodySha256,+ });+ filesToWrite.push({ plan, body, sha256: parsed.bodySha256 });+ }+ }++ const conflicts = plans.filter((p) => p.action === "CONFLICT");+ const skippedUnchanged = plans.filter((p) => p.action === "SKIP_UNCHANGED");+ if (opts.mode === "dry-run") {+ return {+ mode: "dry-run",+ plans, skipped, conflicts,+ applied: [], skippedUnchanged,+ snapshotRunId: null,+ localDate,+ };+ }++ if (conflicts.length > 0) {+ throw new ConflictsError(conflicts);+ }++ let snapshotRunId: string | null = null;+ if (filesToWrite.length > 0) {+ const snap = createSnapshot(opts.vault, { runId: `import-claude-memory-${importedAt.replace(/[:.]/g, "-")}` });+ snapshotRunId = snap.runId;+ }++ const applied: PlannedFile[] = [];+ for (const { plan, body, sha256 } of filesToWrite) {+ const prefFile = preferencePath(opts.vault, plan.prefId);+ mkdirSync(join(opts.vault, "Brain", "preferences"), { recursive: true });+ if (plan.action === "UPDATE") {+ // Preserve evidence fields by merging frontmatter.+ body = mergePreservingEvidence(readFileSync(prefFile, "utf8"), body);+ }+ writeFileSync(prefFile, body, "utf8");+ newImports[plan.basename] = { pref_id: plan.prefId, sha256, imported_at: importedAt };+ applied.push(plan);+ }++ saveManifest(opts.vault, { version: 1, imports: newImports });++ const counts = {+ created: plans.filter((p) => p.action === "CREATE").length,+ updated: plans.filter((p) => p.action === "UPDATE").length,+ recreated: plans.filter((p) => p.action === "RECREATE").length,+ skipped_unchanged: skippedUnchanged.length,+ skipped_non_feedback: skipped.length,+ conflicts: conflicts.length,+ };+ appendLogEvent(opts.vault, resolveAgentName(), {+ eventType: BRAIN_LOG_EVENT_KIND.importClaudeMemory,+ body: {+ created: String(counts.created),+ updated: String(counts.updated),+ recreated: String(counts.recreated),+ skipped_unchanged: String(counts.skipped_unchanged),+ skipped_non_feedback: String(counts.skipped_non_feedback),+ conflicts: String(counts.conflicts),+ snapshot: snapshotRunId ?? "none",+ },+ });++ return {+ mode: "apply",+ plans, skipped, conflicts,+ applied, skippedUnchanged,+ snapshotRunId,+ localDate,+ };+ }++ export class ConflictsError extends Error {+ readonly conflicts: ReadonlyArray<PlannedFile>;+ constructor(conflicts: ReadonlyArray<PlannedFile>) {+ super(`import-claude-memory: ${conflicts.length} conflict(s)`);+ this.conflicts = conflicts;+ }+ }+ ```++ Note: `mergePreservingEvidence` is a small helper that walks the+ existing preference's frontmatter, picks out+ `_applied_count` / `_violated_count` / `_evidenced_by` /+ `_last_evidence_at` / `_confirmed_at` / `unconfirmed_until` /+ `pinned` / `scope`, and replaces the same keys in the freshly+ rendered preference with those preserved values. Implement+ inline (β€30 lines) β no separate file, follows the v0.10.6+ `mergeBrainYaml` pattern.++- [ ] **Step 4: Run, expect PASS. Full sweep.**++**Pause for review.**++### Task 3.8: Preserve-evidence merge β dedicated test++**Files:**+- Create: `tests/core/brain/import-claude-memory-preserve-evidence.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+ import { bootstrapBrain } from "../../../src/core/brain/init.ts";++ describe("UPDATE preserves accumulated evidence", () => {+ test("preserves _applied_count and _evidenced_by across re-import", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-pres-"));+ bootstrapBrain(vault, { primary_agent: "@test", agent_identity: "@test" });+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-pres-mem-"));+ writeFileSync(+ join(mem, "feedback_x.md"),+ "---\nname: rule-x\ndescription: V1.\nmetadata:\n type: feedback\n---\n\nBody v1.\n",+ "utf8",+ );+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });++ // Simulate accumulated evidence.+ const prefPath = join(vault, "Brain", "preferences", "pref-rule-x.md");+ let pref = readFileSync(prefPath, "utf8");+ pref = pref+ .replace("_applied_count: 0", "_applied_count: 7")+ .replace("_violated_count: 0", "_violated_count: 2")+ .replace("_evidenced_by: []", "_evidenced_by: ['[[a.md]]', '[[b.md]]']")+ .replace("pinned: false", "pinned: true");+ writeFileSync(prefPath, pref, "utf8");++ // Update memory body so sha256 changes β UPDATE branch.+ writeFileSync(+ join(mem, "feedback_x.md"),+ "---\nname: rule-x\ndescription: V2.\nmetadata:\n type: feedback\n---\n\nBody v2.\n",+ "utf8",+ );+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });++ const after = readFileSync(prefPath, "utf8");+ expect(after).toContain("_applied_count: 7");+ expect(after).toContain("_violated_count: 2");+ expect(after).toContain("_evidenced_by: ['[[a.md]]', '[[b.md]]']");+ expect(after).toContain("pinned: true");+ expect(after).toContain("principle: \"V2.\"");+ expect(after).toContain("Body v2.");++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run, expect FAIL.** (Likely passes once Task 3.7+ is done correctly; this test is the regression net.)++- [ ] **Step 3: Refine `mergePreservingEvidence` if needed** to+ cover the listed keys. If the test passes on first run, no+ implementation change needed β just keep this as the safety net.++- [ ] **Step 4: Full sweep.**++**Pause for review.**++### Task 3.9: Conflict handling β dedicated test++**Files:**+- Create: `tests/core/brain/import-claude-memory-conflict.test.ts`.++- [ ] **Step 1: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";++ import {+ ConflictsError,+ importClaudeMemory,+ } from "../../../src/core/brain/import-claude-memory.ts";+ import { bootstrapBrain } from "../../../src/core/brain/init.ts";++ describe("CONFLICT path", () => {+ test("apply throws ConflictsError when pref exists with no manifest entry", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-conf-"));+ bootstrapBrain(vault, { primary_agent: "@t", agent_identity: "@t" });+ // Pre-create the preference by hand.+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-rule-c.md"),+ "---\nid: pref-rule-c\nkind: brain-preference\n---\n\nManual.\n",+ "utf8",+ );++ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-conf-mem-"));+ writeFileSync(+ join(mem, "feedback_rule_c.md"),+ "---\nname: rule-c\ndescription: From memory.\nmetadata:\n type: feedback\n---\n\nBody.\n",+ "utf8",+ );++ expect(() =>+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true }),+ ).toThrow(ConflictsError);++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("dry-run reports the conflict but does not throw", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-conf2-"));+ bootstrapBrain(vault, { primary_agent: "@t", agent_identity: "@t" });+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-rule-c.md"),+ "---\nid: pref-rule-c\n---\n\n",+ "utf8",+ );+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-conf2-mem-"));+ writeFileSync(+ join(mem, "feedback_rule_c.md"),+ "---\nname: rule-c\ndescription: x.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = importClaudeMemory({ vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true });+ expect(res.conflicts.length).toBe(1);+ expect(res.conflicts[0].prefId).toBe("pref-rule-c");++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+ });+ ```++- [ ] **Step 2: Run, expect PASS** (orchestrator already handles+ CONFLICT). If failing, fix in `import-claude-memory.ts`.++- [ ] **Step 3: Full sweep.**++**Pause for review.**++### Task 3.10: `o2b brain import-claude-memory` CLI verb++**Files:**+- Modify: `src/cli/brain.ts` (add the verb to the dispatcher).+- Create: `tests/cli/brain-import-claude-memory.test.ts`.++- [ ] **Step 1: Locate the dispatcher** β+ `grep -n 'case "import-session"' src/cli/brain.ts`.++- [ ] **Step 2: Write failing test**:++ ```ts+ import { describe, expect, test } from "bun:test";+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import { runCli } from "../helpers/run-cli.ts";++ describe("o2b brain import-claude-memory CLI", () => {+ test("dry-run prints plan summary, exit 0, no writes", async () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-cli-"));+ // bootstrap brain via CLI for realism+ await runCli(["brain", "init", "--vault", vault, "--yes"]);+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-cli-mem-"));+ writeFileSync(+ join(mem, "feedback_a.md"),+ "---\nname: a\ndescription: A.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = await runCli([+ "brain", "import-claude-memory", "--vault", vault,+ "--memory", mem, "--dry-run", "--allow-arbitrary-memory-path",+ ]);+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("plan:");+ expect(res.stdout).toContain("CREATE pref-a");+ expect(existsSync(join(vault, "Brain", "preferences", "pref-a.md"))).toBe(false);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("--apply writes files and exits 0", async () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-cli2-"));+ await runCli(["brain", "init", "--vault", vault, "--yes"]);+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-cli2-mem-"));+ writeFileSync(+ join(mem, "feedback_a.md"),+ "---\nname: a\ndescription: A.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = await runCli([+ "brain", "import-claude-memory", "--vault", vault,+ "--memory", mem, "--apply", "--yes", "--allow-arbitrary-memory-path",+ ]);+ expect(res.returncode).toBe(0);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-a.md"))).toBe(true);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("--apply + --dry-run is rejected", async () => {+ const res = await runCli([+ "brain", "import-claude-memory", "--vault", "/tmp", "--apply", "--dry-run",+ ]);+ expect(res.returncode).toBe(2);+ expect(res.stderr).toMatch(/--apply.*--dry-run|--dry-run.*--apply/);+ });+ });+ ```++- [ ] **Step 3: Run tests, expect FAIL.**++- [ ] **Step 4: Implement the verb** β append to+ `src/cli/brain.ts`:++ ```ts+ // (in the verb dispatcher switch)+ case "import-claude-memory":+ return brainImportClaudeMemory(args, vault);+ ```++ and a new function near the existing `import-session` handler:++ ```ts+ import {+ importClaudeMemory, ConflictsError,+ } from "../core/brain/import-claude-memory.ts";+ import { defaultMemoryDir } from "../core/brain/claude-memory-paths.ts";++ async function brainImportClaudeMemory(args: string[], vault: string): Promise<number> {+ let memory: string | null = null;+ let mode: "dry-run" | "apply" = "dry-run";+ let modeSet = false;+ let allowArbitrary = false;+ let yes = false;+ let asJson = false;+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === "--memory") { memory = args[++i] ?? null; continue; }+ if (a === "--dry-run") {+ if (modeSet && mode !== "dry-run") {+ process.stderr.write("o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n");+ return 2;+ }+ mode = "dry-run"; modeSet = true; continue;+ }+ if (a === "--apply") {+ if (modeSet && mode !== "apply") {+ process.stderr.write("o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n");+ return 2;+ }+ mode = "apply"; modeSet = true; continue;+ }+ if (a === "--yes") { yes = true; continue; }+ if (a === "--json") { asJson = true; continue; }+ if (a === "--allow-arbitrary-memory-path") { allowArbitrary = true; continue; }+ }+ if (mode === "apply" && !yes && process.stdin.isTTY === false) {+ process.stderr.write("o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n");+ return 2;+ }+ const memDir = memory ?? defaultMemoryDir(vault);+ try {+ const res = importClaudeMemory({ vault, memoryDir: memDir, mode, allowArbitraryMemoryPath: allowArbitrary });+ if (asJson) {+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");+ return 0;+ }+ if (mode === "dry-run") {+ process.stdout.write(`plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`);+ for (const p of res.plans) process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);+ for (const s of res.skipped) process.stdout.write(` SKIP ${s.basename}: ${s.reason}\n`);+ if (res.conflicts.length > 0) process.stdout.write(`conflicts: ${res.conflicts.length}\n`);+ } else {+ process.stdout.write(`applied: ${res.applied.length}; unchanged: ${res.skippedUnchanged.length}; skipped: ${res.skipped.length}\n`);+ if (res.snapshotRunId) process.stdout.write(`snapshot: ${res.snapshotRunId}\n`);+ }+ return 0;+ } catch (err) {+ if (err instanceof ConflictsError) {+ process.stderr.write(`conflicts:\n`);+ for (const c of err.conflicts) {+ process.stderr.write(` ${c.prefId} already exists in Brain but is not in Brain/.imports/claude-memory.json\n`);+ }+ return 2;+ }+ process.stderr.write(`o2b brain import-claude-memory: ${(err as Error).message}\n`);+ return 1;+ }+ }+ ```++ Add `import-claude-memory` to the help text near `import-session`.++- [ ] **Step 5: Run tests, expect PASS.**++- [ ] **Step 6: Full sweep.**++**Pause for review. End of Β§E track.**++---++## Phase 4 β Release wrap-up++### Task 4.1: Bump version everywhere++**Files:**+- Modify: `package.json`, `openclaw.plugin.json`, `plugin.yaml`.++- [ ] **Step 1: Edit `package.json`** β `"version": "0.10.7"`.+- [ ] **Step 2: Edit `openclaw.plugin.json`** β `"version": "0.10.7"`.+- [ ] **Step 3: Edit `plugin.yaml`** β `version: "0.10.7"`.+- [ ] **Step 4: Run `bun run sync-version:check`.** Expected: PASS+ (the existing sync-version script verifies the three files+ agree).++**Pause for review.**++### Task 4.2: CHANGELOG entry++**Files:**+- Modify: `CHANGELOG.md`.++- [ ] **Step 1: Add a new section at the top** under the existing+ `# Changelog` heading:++ ```markdown+ ## [0.10.7] - 2026-05-18++ Closes the remaining Β§30 (Agent logging discipline) work from+ `Projects/OpenSecondBrain/Features/_summary.md`. Three independent+ tracks ship together:++ ### Added++ - Β§30 Β§B β Writer MCP server split. A second `.mcp.json` entry+ (`open-second-brain-writer`) exposes `brain_feedback` and+ `brain_apply_evidence` with Claude Code's `alwaysLoad: true`+ flag so the agent never pays the ToolSearch round-trip before+ recording a taste signal or evidence event. The full MCP+ surface stays deferred under the existing `open-second-brain`+ entry. `o2b mcp` gains `--scope writer|full` (default `full`).+ - Β§30 Β§D β Daily discipline cron. New `bin/o2b-discipline-report`+ + `o2b discipline {report|install|uninstall}` build a+ deterministic Telegram MarkdownV2 block comparing+ brain-event counts per agent (parsed from `Brain/log/<date>.md`)+ against runtime-agnostic activity proxies (git activity on+ watched repos, mtime walk on watched non-repo paths, vault+ delta). Status `ok | info | alert` is binary; numeric ratios+ were rejected in design as noise-prone. Hermes cron job+ installable with `o2b discipline install [--telegram-target]+ [--at]`. No LLM in the report path.+ - Β§30 Β§E β Claude Code MEMORY β Brain bridge. New verb+ `o2b brain import-claude-memory [--memory <path>]+ [--dry-run | --apply] [--yes] [--json]+ [--allow-arbitrary-memory-path]` reads `metadata.type:+ feedback` entries from a Claude Code memory directory and+ writes them as confirmed Brain preferences with a sidecar+ manifest `Brain/.imports/claude-memory.json` for idempotency.+ UPDATE preserves accumulated evidence+ (`_applied_count`/`_violated_count`/`_evidenced_by`/...). CONFLICT+ surfaces (preference exists without a manifest entry) require+ manual resolution β never silent overwrites.+ - New module `src/core/discipline/` (report orchestrator, log+ counts, window helper, git/mtime activity, vault delta,+ decision, render, telegram-escape, install).+ - New module split for Β§E: `claude-memory-parser.ts`,+ `claude-memory-manifest.ts`, `claude-memory-plan.ts`,+ `claude-memory-render.ts`, `claude-memory-paths.ts`,+ `import-claude-memory.ts`.+ - `BRAIN_LOG_EVENT_KIND.importClaudeMemory = "import-claude-memory"`.++ ### Changed++ - `src/mcp/tools.ts:buildToolTable` accepts an optional+ `scope: "full" | "writer"` parameter; default unchanged.+ - `MCPServer` ctor accepts an optional `{ serverName, scope }`+ options object; defaults reproduce the v0.10.6 behavior.+ - `BrainConfig` gains an optional `discipline_report` section+ (`enabled`, `timezone`, `watched_paths`, `known_agents`).+ Missing section β Β§D feature disabled.++ ### Migration++ No vault data migration is required. Existing vaults run Β§D+ with `enabled: false` (default) until the operator adds the+ config section and runs `o2b discipline install`. Β§E is+ opt-in (operator runs the verb); the sidecar manifest is+ created on first `--apply`.+ ```++- [ ] **Step 2: No `[Unreleased]` section.** Per user preference,+ release notes go directly under concrete version headers.++- [ ] **Step 3: Diff the file** β `git diff CHANGELOG.md`. Confirm+ the new section is added, no other line is touched.++**Pause for review.**++### Task 4.3: Update vault `_summary.md`++**Files:**+- Modify: `/root/vault/Projects/OpenSecondBrain/Features/_summary.md`.++- [ ] **Step 1: Update Β§30 entry** β set to `β shipped fully in+ v0.10.7`. The current entry says `ΡΠ΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ ΡΠ°ΡΡΠΈΡΠ½ΠΎ Π²+ v0.10.6 (Β§A+Β§C)`. Replace the closing parenthetical with+ shipped-in-full and link to `[[Plan/3. Agent logging discipline]]`.++- [ ] **Step 2: Update the `Deferred work` section** β add four+ new entries (per design doc):+ - Per-tool always-load in Claude Code β trigger: appears in+ Claude Code changelog.+ - Bidirectional MEMORY β Brain sync β trigger: explicit user+ request, or a second example.+ - Β§D non-bash-runtime activity sources β trigger: Β§4 second half+ ships.+ - Β§D non-binary thresholds β trigger: real+ false-positive/false-negative pairs.++- [ ] **Step 3: Update the Agent-logging-discipline marker** β+ the line that previously said `ΡΠ΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Π½ΠΎ ΡΠ°ΡΡΠΈΡΠ½ΠΎ Π² v0.10.6`+ becomes `shipped fully in v0.10.7 β Β§B (writer MCP split), Β§D+ (daily discipline cron), Β§E (claude-memory bridge)`.++**Pause for review.**++### Task 4.4: Update vault `Plan/3. Agent logging discipline.md`++**Files:**+- Modify: `/root/vault/Projects/OpenSecondBrain/Plan/3. Agent logging discipline.md`.++- [ ] **Step 1: Change frontmatter** β `status: shipped`, all+ three open items move into `shipped:` (or rewrite the front-matter+ to remove the `open:` field entirely).++- [ ] **Step 2: Drop the "Π’ΡΠΈΠ³Π³Π΅Ρ Π½Π° Π²ΠΎΠ·Π²ΡΠ°Ρ" section** β Β§30 is+ closed; the trigger is no longer relevant.++- [ ] **Step 3: Add a tail note** β "v0.10.7 closed Β§B / Β§D / Β§E.+ Future related work would open a new feature, not reopen Β§30."++**Pause for review.**++### Task 4.5: Full test + typecheck pass++- [ ] **Step 1: `bun test`.** Expected: every test in the repo+ passes. If anything regresses, fix before continuing.++- [ ] **Step 2: `bun run typecheck`.** Expected: zero errors.++- [ ] **Step 3: Smoke-test the writer MCP server**:++ ```bash+ cd /srv/projects/open-second-brain+ echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{}}}' | \+ ./scripts/o2b mcp --scope writer | jq .+ ```++ Expected: handshake response with `serverInfo.name ==+ "open-second-brain-writer"`.++- [ ] **Step 4: Smoke-test the discipline report against the+ real vault** (read-only):++ ```bash+ ./bin/o2b-discipline-report --vault /root/vault+ ```++ Expected: either the rendered MarkdownV2 block, or `disabled`+ on stderr (if user has not yet enabled the feature in+ `Brain/_brain.yaml`).++- [ ] **Step 5: Smoke-test `import-claude-memory --dry-run`** against+ the real `~/.claude/projects/-root/memory/`:++ ```bash+ ./scripts/o2b brain import-claude-memory --vault /root/vault --dry-run+ ```++ Expected: a list of CREATE / SKIP_UNCHANGED / CONFLICT rows;+ no file writes; exit 0 unless conflicts exist (then exit 2).++**Pause for review. Surface the `git diff` for staging by the user+themselves β no `git add` or `git commit` from this plan.**++---++## Self-review (run BEFORE handoff)++- [ ] **Spec coverage.** Every section in+ `2026-05-18-agent-discipline-tail-design.md` maps to a Task above.+ G1 β Phase 1. G2 β Phase 2. G3 β Phase 3. Non-goals are+ represented by their absence β design doc lists them, plan does+ not implement them.+- [ ] **Placeholder scan.** No "TBD", "TODO", "fill in later", or+ "similar to Task N (no code)". Every code step shows actual code.+- [ ] **Type consistency.** `BrainEventCounts`, `ActivitySummary`,+ `DisciplineStatus`, `ClaudeMemoryManifest`, `PlannedFile`,+ `PlanAction` are defined once and referenced consistently.+ `buildToolTable` signature stays+ `(scope: ToolScope = "full") => ToolDefinition[]` across Tasks 1.1+ β 1.5.+- [ ] **No active git.** Every "Commit" step is replaced by "Pause+ for review" so the user stages diffs themselves. No `git add` or+ `git commit` invocation appears in any step.+- [ ] **Test path coverage.** Each new module ships with a focused+ unit test plus at least one integration / end-to-end test+ (`runDisciplineReport`, `importClaudeMemory`).diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 4f3bf804..f1a37328 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.10.6",+ "version": "0.10.7","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 48144e8d..108cd324 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.6",+ "version": "0.10.7","type": "module","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",@@ -26,6 +26,7 @@"sync-version:check": "bun run scripts/sync-version.ts --check"},"files": [+ "bin/","openclaw/","src/","skills/",diff --git a/plugin.yaml b/plugin.yamlindex 11a085b2..e94fc364 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.6"+version: "0.10.7"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 3b44d21d..96136555 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.10.6",+ "version": "0.10.7","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 3351d966..f6651c19 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.10.6"+version: "0.10.7"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex e1132537..26caa167 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.10.6"+version = "0.10.7"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/scripts/discipline-report.ts b/scripts/discipline-report.tsnew file mode 100644index 00000000..a0899ee2--- /dev/null+++ b/scripts/discipline-report.ts@@ -0,0 +1,31 @@+#!/usr/bin/env -S bun+import { resolveVault } from "../src/core/config.ts";+import { runDisciplineReport } from "../src/core/discipline/report.ts";++function readVaultArg(): string {+ const argv = process.argv.slice(2);+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === "--vault" && argv[i + 1]) return argv[i + 1]!;+ }+ // Use the same vault-resolution path the rest of the CLI uses β+ // `VAULT_DIR` env wins over config, and `~`-prefixed config values+ // get tilde-expanded. Direct `discoverConfig().data["vault"]` access+ // would miss both, so a cron job under a different `$HOME` or with+ // `VAULT_DIR` set would silently look at the wrong directory.+ const v = resolveVault();+ if (!v) {+ process.stderr.write(+ "o2b-discipline-report: no vault configured; set VAULT_DIR env or pass --vault <path>\n",+ );+ process.exit(2);+ }+ return v;+}++const vault = readVaultArg();+const res = runDisciplineReport({ vault });+if (res.status === "disabled") {+ process.stderr.write("o2b-discipline-report: discipline_report disabled in Brain/_brain.yaml\n");+ process.exit(0);+}+process.stdout.write(res.text + "\n");diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 29a9fa9c..3aaad43e 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -121,6 +121,11 @@ import {BRAIN_SIGNAL_SIGN,} from "../core/brain/types.ts";import { CliError, parseFlags, type FlagsSchema } from "./argparse.ts";+import {+ importClaudeMemory,+ ConflictsError,+} from "../core/brain/import-claude-memory.ts";+import { defaultMemoryDir } from "../core/brain/claude-memory-paths.ts";const NO_VAULT_ERROR ="error: no vault configured. Pass --vault <path> explicitly, " +@@ -1606,6 +1611,134 @@ async function cmdBrainImportSession(argv: string[]): Promise<number> {}}+async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number> {+ const config = defaultConfigPath();++ let memory: string | null = null;+ let mode: "dry-run" | "apply" = "dry-run";+ let modeSet = false;+ let allowArbitrary = false;+ let yes = false;+ let asJson = false;+ let vaultFlag: string | undefined;++ // Demand a value for `--vault` / `--memory` and reject unknown flags+ // outright. The previous loop silently dropped `--scope` typos and+ // similar mistakes, which would default a fresh agent to `~/.../-X-vault`+ // (often the wrong directory) without complaint. `consumeValue` advances+ // the loop index in-place and returns null on a missing/flag-looking+ // value β the caller surfaces the stderr message and returns 2.+ const consumeValue = (flag: string, next: string | undefined): string | null => {+ if (next === undefined || next.startsWith("--")) {+ process.stderr.write(+ `o2b brain import-claude-memory: ${flag} requires a value\n`,+ );+ return null;+ }+ return next;+ };++ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--vault") {+ const v = consumeValue("--vault", argv[++i]);+ if (v === null) return 2;+ vaultFlag = v;+ continue;+ }+ if (a === "--memory") {+ const v = consumeValue("--memory", argv[++i]);+ if (v === null) return 2;+ memory = v;+ continue;+ }+ if (a === "--dry-run") {+ if (modeSet && mode !== "dry-run") {+ process.stderr.write(+ "o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n",+ );+ return 2;+ }+ mode = "dry-run"; modeSet = true; continue;+ }+ if (a === "--apply") {+ if (modeSet && mode !== "apply") {+ process.stderr.write(+ "o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n",+ );+ return 2;+ }+ mode = "apply"; modeSet = true; continue;+ }+ if (a === "--yes") { yes = true; continue; }+ if (a === "--json") { asJson = true; continue; }+ if (a === "--allow-arbitrary-memory-path") { allowArbitrary = true; continue; }+ process.stderr.write(+ `o2b brain import-claude-memory: unknown flag ${a}\n`,+ );+ return 2;+ }++ if (mode === "apply" && !yes && !process.stdin.isTTY) {+ process.stderr.write(+ "o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n",+ );+ return 2;+ }++ const vault = resolveBrainVault(vaultFlag, config);+ const memDir = memory ?? defaultMemoryDir(vault);++ try {+ const res = importClaudeMemory({+ vault,+ memoryDir: memDir,+ mode,+ allowArbitraryMemoryPath: allowArbitrary,+ });+ if (asJson) {+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");+ return 0;+ }+ if (mode === "dry-run") {+ process.stdout.write(+ `plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`,+ );+ for (const p of res.plans) {+ process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);+ }+ for (const s of res.skipped) {+ process.stdout.write(` SKIP ${s.basename}: ${s.reason}\n`);+ }+ if (res.conflicts.length > 0) {+ process.stdout.write(`conflicts: ${res.conflicts.length}\n`);+ }+ } else {+ process.stdout.write(+ `applied: ${res.applied.length}; unchanged: ${res.skippedUnchanged.length}; skipped: ${res.skipped.length}\n`,+ );+ if (res.snapshotRunId) {+ process.stdout.write(`snapshot: ${res.snapshotRunId}\n`);+ }+ }+ return 0;+ } catch (err) {+ if (err instanceof ConflictsError) {+ process.stderr.write("conflicts:\n");+ for (const c of err.conflicts) {+ process.stderr.write(+ ` ${c.prefId} already exists in Brain but is not in Brain/.imports/claude-memory.json\n`,+ );+ }+ return 2;+ }+ process.stderr.write(+ `o2b brain import-claude-memory: ${(err as Error).message}\n`,+ );+ return 1;+ }+}+async function cmdBrainScanInline(argv: string[]): Promise<number> {const { flags } = parse(argv, {vault: { type: "string" },@@ -2141,6 +2274,7 @@ Brain verbs (observing memory):migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'scan-inline Capture @osb markers from vault markdown files (Daily/, project notes, etc.)import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)+ import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferencesCommon flags:--vault <path> Override the configured vault@@ -2229,6 +2363,16 @@ const VERB_HELP: Record<string, string> = {"create signals in Brain/inbox/, and annotate the source files with\n" +"@osbβ [[sig-...]]. Brain/, .git, node_modules, and similar directories\n" +"are always skipped. Idempotent on re-run.\n",+ "import-claude-memory":+ "usage: o2b brain import-claude-memory [--vault <path>] [--memory <path>]\n" ++ " [--dry-run | --apply] [--yes] [--json]\n" ++ " [--allow-arbitrary-memory-path]\n" ++ "Read metadata.type:feedback entries from a Claude Code memory directory and\n" ++ "write them as confirmed Brain preferences. A sidecar manifest\n" ++ "Brain/.imports/claude-memory.json tracks idempotency. UPDATE preserves\n" ++ "accumulated evidence fields. CONFLICT (preference exists without a manifest\n" ++ "entry) exits 2 β never silent overwrites.\n" ++ "Default is --dry-run; --apply requires --yes in non-interactive mode.\n","import-session":"usage: o2b brain import-session <path> [--vault <vault>]\n" +" [--format auto|claude|codex|hermes]\n" +@@ -2362,6 +2506,8 @@ export async function handleBrainSubcommand(return await cmdBrainScanInline(rest);case "import-session":return await cmdBrainImportSession(rest);+ case "import-claude-memory":+ return await cmdBrainImportClaudeMemory(rest);case "merge":return await cmdBrainMerge(rest);case "upgrade":diff --git a/src/cli/discipline-install.ts b/src/cli/discipline-install.tsnew file mode 100644index 00000000..bcb1c076--- /dev/null+++ b/src/cli/discipline-install.ts@@ -0,0 +1,172 @@+/**+ * `o2b discipline install` / `o2b discipline uninstall` verb handlers.+ *+ * Manages the Hermes cron job that delivers the daily OSB discipline report+ * to a Telegram topic. The real cron config lives at DEFAULT_JOBS_FILE;+ * tests override via the OSB_HERMES_JOBS env var to avoid touching the+ * user's live config.+ */++import { createHash } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { atomicWriteFileSync } from "../core/fs-atomic.ts";++const DEFAULT_JOBS_FILE = "/root/.hermes/cron/jobs.json";++function jobsFilePath(): string {+ return process.env.OSB_HERMES_JOBS ?? DEFAULT_JOBS_FILE;+}++/**+ * Resolve the absolute path to `bin/o2b-discipline-report` from this+ * module's own location instead of hardcoding `/srv/projects/...`. The+ * cron job needs an absolute path because Hermes cron exec's it verbatim;+ * the path the operator running `install` sees is the path the cron will+ * use, so this works for any install root.+ */+function scriptPath(): string {+ const here = dirname(fileURLToPath(import.meta.url)); // src/cli+ return resolve(here, "..", "..", "bin", "o2b-discipline-report");+}++function jobId(vault: string): string {+ const slug = createHash("sha256")+ .update(resolve(vault))+ .digest("hex")+ .slice(0, 12);+ return `osb-discipline-report-${slug}`;+}++interface HermesJob {+ id: string;+ name: string;+ [k: string]: unknown;+}++interface JobsFile {+ jobs: HermesJob[];+}++function loadJobs(file: string): JobsFile {+ if (!existsSync(file)) return { jobs: [] };+ const raw = readFileSync(file, "utf8");+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (e) {+ throw new Error(+ `o2b discipline: jobs file is corrupted JSON: ${file}\n` ++ `Original error: ${(e as Error).message}\n` ++ `Resolve manually before re-running install/uninstall.`,+ );+ }+ if (+ parsed === null ||+ typeof parsed !== "object" ||+ !Array.isArray((parsed as { jobs?: unknown }).jobs)+ ) {+ throw new Error(+ `o2b discipline: jobs file is missing the jobs[] array: ${file}`,+ );+ }+ return parsed as JobsFile;+}++function saveJobs(file: string, data: JobsFile): void {+ atomicWriteFileSync(file, JSON.stringify(data, null, 2));+}++function pickVault(args: ReadonlyArray<string>, defaultVault: string): string {+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault" && i + 1 < args.length) return args[i + 1]!;+ }+ return defaultVault;+}++export async function disciplineInstallVerb(+ args: string[],+ defaultVault: string,+): Promise<number> {+ let vault = pickVault(args, defaultVault);+ let telegramTarget = "";+ let at = "59 4 * * *";+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault") {+ // already picked up by pickVault; skip the value+ i++;+ continue;+ }+ if (args[i] === "--telegram-target") {+ telegramTarget = args[++i] ?? "";+ continue;+ }+ if (args[i] === "--at") {+ at = args[++i] ?? at;+ continue;+ }+ }+ if (!vault) {+ process.stderr.write("o2b discipline install: --vault is required\n");+ return 2;+ }+ if (!telegramTarget) {+ // Refuse to bake a default chat id into the cron entry β that would+ // ship a private chat target with the open-source release. The+ // operator must name their own Telegram destination explicitly.+ process.stderr.write(+ "o2b discipline install: --telegram-target is required " ++ "(e.g. --telegram-target telegram:-100<chat_id>:<topic_id>)\n",+ );+ return 2;+ }+ const file = jobsFilePath();+ const data = loadJobs(file);+ const id = jobId(vault);+ const existing = data.jobs.find((j) => j.id === id);+ const next: HermesJob = {+ id,+ name: "osb-discipline-report",+ script: scriptPath(),+ no_agent: true,+ schedule: { kind: "cron", expr: at, display: at },+ deliver: telegramTarget,+ enabled: true,+ };+ if (existing) {+ Object.assign(existing, next);+ } else {+ data.jobs.push(next);+ }+ saveJobs(file, data);+ process.stdout.write(+ `o2b discipline: job '${id}' ${existing ? "updated" : "created"} (schedule: ${at}, deliver: ${telegramTarget})\n`,+ );+ return 0;+}++export async function disciplineUninstallVerb(+ args: string[],+ defaultVault: string,+): Promise<number> {+ const vault = pickVault(args, defaultVault);+ if (!vault) {+ process.stderr.write(+ "o2b discipline uninstall: --vault is required\n",+ );+ return 2;+ }+ const file = jobsFilePath();+ const data = loadJobs(file);+ const id = jobId(vault);+ const before = data.jobs.length;+ data.jobs = data.jobs.filter((j) => j.id !== id);+ saveJobs(file, data);+ const removed = before - data.jobs.length;+ process.stdout.write(+ `o2b discipline: ${removed > 0 ? "removed" : "no-op"} (job '${id}')\n`,+ );+ return 0;+}diff --git a/src/cli/discipline.ts b/src/cli/discipline.tsnew file mode 100644index 00000000..9a457d6c--- /dev/null+++ b/src/cli/discipline.ts@@ -0,0 +1,94 @@+/**+ * `o2b discipline` subcommand dispatcher.+ *+ * Routes discipline verbs to their handlers. Currently only `report` is+ * implemented; `install` and `uninstall` are reserved for Task 2.13.+ */++import { defaultConfigPath, resolveVault } from "../core/config.ts";+import { runDisciplineReport } from "../core/discipline/report.ts";+import {+ disciplineInstallVerb,+ disciplineUninstallVerb,+} from "./discipline-install.ts";++const NO_VAULT_ERROR =+ "error: no vault configured. Pass --vault <path> explicitly, " ++ "set VAULT_DIR in the environment, or run " ++ "`o2b init --vault <path> ...` first to persist a default.";++function resolveDisciplineVault(+ flagVal: string | undefined,+ configPath: string | null,+): string {+ const vault = flagVal ?? resolveVault(configPath ?? undefined);+ if (vault === null || vault === undefined) {+ process.stderr.write(NO_VAULT_ERROR + "\n");+ throw new Error(NO_VAULT_ERROR);+ }+ return vault;+}++export async function disciplineReportVerb(+ args: string[],+ defaultVault: string,+): Promise<number> {+ let vault = defaultVault;+ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--vault" && args[i + 1]) {+ vault = args[i + 1]!;+ i++;+ }+ }+ const res = runDisciplineReport({ vault });+ if (res.status === "disabled") {+ process.stderr.write(+ "o2b discipline report: discipline_report disabled in Brain/_brain.yaml\n",+ );+ return 0;+ }+ process.stdout.write(res.text + "\n");+ return 0;+}++export async function handleDisciplineSubcommand(+ argv: ReadonlyArray<string>,+): Promise<number> {+ const verb = argv[0];+ const rest = argv.slice(1) as string[];++ // Extract --vault from the full argv (before or after the verb) so we can+ // resolve the default vault once for all subcommands.+ let vaultFlag: string | undefined;+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === "--vault" && argv[i + 1]) {+ vaultFlag = argv[i + 1];+ break;+ }+ }++ switch (verb) {+ case "report": {+ const config = defaultConfigPath();+ const vault = resolveDisciplineVault(vaultFlag, config);+ return await disciplineReportVerb(rest, vault);+ }+ case "install": {+ // Let the verb handle missing --vault itself (returns exit 2).+ const config = defaultConfigPath();+ const vault = vaultFlag ?? resolveVault(config ?? undefined) ?? "";+ return await disciplineInstallVerb(rest, vault);+ }+ case "uninstall": {+ // Let the verb handle missing --vault itself (returns exit 2).+ const config = defaultConfigPath();+ const vault = vaultFlag ?? resolveVault(config ?? undefined) ?? "";+ return await disciplineUninstallVerb(rest, vault);+ }+ default:+ process.stderr.write(+ `error: unknown discipline subcommand: ${verb ?? "(none)"}\n`,+ );+ return 2;+ }+}diff --git a/src/cli/main.ts b/src/cli/main.tsindex 6c38e19c..0e31950a 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -44,6 +44,7 @@ import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";import { listVaultPages, writeFrontmatter } from "../core/vault.ts";import { CliError, parseFlags } from "./argparse.ts";import { handleBrainSubcommand } from "./brain.ts";+import { handleDisciplineSubcommand } from "./discipline.ts";import { handleSearchSubcommand } from "./search.ts";import {installCli,@@ -1134,16 +1135,29 @@ async function cmdMcp(argv: string[]): Promise<number> {vault: { type: "string" },config: { type: "string" },repo: { type: "string" },+ scope: { type: "string" },});++ // Validate --scope before doing anything that could fail for other reasons.+ const rawScope = (flags["scope"] as string | undefined) ?? "full";+ if (rawScope !== "full" && rawScope !== "writer") {+ process.stderr.write(+ `o2b mcp: invalid --scope value: ${rawScope}; expected one of: full, writer\n`,+ );+ return 2;+ }+ const scope = rawScope;+ const serverName =+ scope === "writer" ? "open-second-brain-writer" : "open-second-brain";+const config = (flags["config"] as string | undefined) ?? defaultConfigPath();const vault = requireVault(flags["vault"] as string | undefined, config);const repoRoot = (flags["repo"] as string | undefined) ?? null;process.stderr.write(- `[mcp] open-second-brain ${SERVER_VERSION} listening on stdio (vault=${vault})\n`,+ `[mcp] ${serverName} ${SERVER_VERSION} listening on stdio (vault=${vault})\n`,);- const server = new MCPServer({ vault, configPath: config, repoRoot });- return await serveStdio(server);+ return await serveStdio({ vault, configPath: config, repoRoot }, {}, { scope, serverName });}async function cmdInstallCli(argv: string[]): Promise<number> {@@ -1253,6 +1267,9 @@ Brain (observing memory):brain rollback Restore Brain/ from a snapshot (--list / <run_id>)brain doctor Validate Brain invariants (--strict promotes warnings)+Discipline:+ discipline report Render the daily discipline report block (Telegram-safe)+Search:search "<query>" Search the vault index (default verb is 'query')search index Incrementally update the index from the vault@@ -1340,6 +1357,8 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {return await cmdPaymentDigest(rest);case "brain":return await handleBrainSubcommand(rest);+ case "discipline":+ return await handleDisciplineSubcommand(rest);case "search":return await handleSearchSubcommand(rest);default:diff --git a/src/core/brain/claude-memory-manifest.ts b/src/core/brain/claude-memory-manifest.tsnew file mode 100644index 00000000..cf18f8a3--- /dev/null+++ b/src/core/brain/claude-memory-manifest.ts@@ -0,0 +1,56 @@+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";++export interface ClaudeMemoryManifestEntry {+ readonly pref_id: string;+ readonly sha256: string;+ readonly imported_at: string;+}++export interface ClaudeMemoryManifest {+ readonly version: 1;+ readonly imports: Readonly<Record<string, ClaudeMemoryManifestEntry>>;+}++function manifestPath(vault: string): string {+ return join(vault, "Brain", ".imports", "claude-memory.json");+}++/**+ * Load the import-history sidecar. Treats a missing file as "empty+ * manifest" β first-time imports rely on this. Type-validates the+ * parsed `imports` field defensively: a malformed file (hand-edited+ * to non-object, truncated, etc.) returns the empty shape rather than+ * propagating an unknown blob into the rest of the import pipeline.+ */+export function loadManifest(vault: string): ClaudeMemoryManifest {+ const p = manifestPath(vault);+ if (!existsSync(p)) return { version: 1, imports: {} };+ let raw: unknown;+ try {+ raw = JSON.parse(readFileSync(p, "utf8"));+ } catch {+ return { version: 1, imports: {} };+ }+ if (+ raw === null ||+ typeof raw !== "object" ||+ typeof (raw as { imports?: unknown }).imports !== "object" ||+ (raw as { imports?: unknown }).imports === null ||+ Array.isArray((raw as { imports?: unknown }).imports)+ ) {+ return { version: 1, imports: {} };+ }+ return {+ version: 1,+ imports: (raw as { imports: Record<string, ClaudeMemoryManifestEntry> }).imports,+ };+}++export function saveManifest(vault: string, m: ClaudeMemoryManifest): void {+ const p = manifestPath(vault);+ mkdirSync(dirname(p), { recursive: true });+ atomicWriteFileSync(p, JSON.stringify(m, null, 2) + "\n");+}diff --git a/src/core/brain/claude-memory-parser.ts b/src/core/brain/claude-memory-parser.tsnew file mode 100644index 00000000..2b1aa5a6--- /dev/null+++ b/src/core/brain/claude-memory-parser.ts@@ -0,0 +1,137 @@+import { createHash } from "node:crypto";++export type ClaudeMemoryParseResult =+ | {+ readonly kind: "feedback";+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly bodySha256: string;+ }+ | {+ readonly kind: "skip";+ readonly skipReason: string;+ };++// Accept both LF and CRLF line endings around the frontmatter fence β+// memory files written from Windows clients carry `\r\n`, and a pure+// `\n` regex would mis-classify them as malformed.+const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;++/**+ * Minimal two-level YAML parser for Claude MEMORY.md frontmatter.+ *+ * Handles:+ * - `key: scalar value` at the top level+ * - `key:` with an indented block of ` subkey: scalar` one level deep+ * - blank lines and `# comments` are ignored+ *+ * Returns a plain object whose nested blocks are plain objects. Does not+ * use an external YAML library β consistent with the project's design+ * principle of keeping the core dependency-free.+ */+function parseFrontmatterBlock(text: string): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ const lines = text.split("\n");+ let i = 0;++ while (i < lines.length) {+ const raw = lines[i]!;+ i++;++ const trimmed = raw.trim();+ if (!trimmed || trimmed.startsWith("#")) continue;++ const colon = trimmed.indexOf(":");+ if (colon === -1) continue;++ const key = trimmed.slice(0, colon).trim();+ const rest = trimmed.slice(colon + 1).trim();++ if (rest === "" || rest === null) {+ // Possible block header β collect indented children.+ const child: Record<string, string> = {};+ const indent = detectIndent(lines, i);+ if (indent > 0) {+ while (i < lines.length) {+ const innerRaw = lines[i]!;+ const innerTrimmed = innerRaw.trim();+ if (!innerTrimmed || innerTrimmed.startsWith("#")) {+ i++;+ continue;+ }+ // Stop if this line is at top-level indentation (indent 0) or+ // has less indentation than the detected block indent.+ const lineIndent = innerRaw.length - innerRaw.trimStart().length;+ if (lineIndent < indent) break;++ i++;+ const innerColon = innerTrimmed.indexOf(":");+ if (innerColon === -1) continue;+ const innerKey = innerTrimmed.slice(0, innerColon).trim();+ const innerVal = innerTrimmed.slice(innerColon + 1).trim();+ child[innerKey] = stripYamlQuotes(innerVal);+ }+ }+ out[key] = child;+ } else {+ out[key] = stripYamlQuotes(rest);+ }+ }++ return out;+}++function detectIndent(lines: string[], from: number): number {+ for (let j = from; j < lines.length; j++) {+ const raw = lines[j]!;+ const trimmed = raw.trim();+ if (!trimmed || trimmed.startsWith("#")) continue;+ const spaces = raw.length - raw.trimStart().length;+ return spaces;+ }+ return 0;+}++function stripYamlQuotes(val: string): string {+ if (+ (val.startsWith('"') && val.endsWith('"')) ||+ (val.startsWith("'") && val.endsWith("'"))+ ) {+ return val.slice(1, -1);+ }+ return val;+}++export function parseClaudeMemoryFile(text: string): ClaudeMemoryParseResult {+ const m = text.match(FM_RE);+ if (!m) {+ return { kind: "skip", skipReason: "missing or malformed frontmatter" };+ }+ let fm: Record<string, unknown>;+ try {+ fm = parseFrontmatterBlock(m[1]!);+ } catch {+ return { kind: "skip", skipReason: "frontmatter is not valid YAML" };+ }+ const name = typeof fm["name"] === "string" ? fm["name"].trim() : "";+ const description = typeof fm["description"] === "string" ? fm["description"].trim() : "";+ // Claude Code Memory uses two frontmatter shapes for the `type` field:+ // older entries put it at the top level (`type: feedback`), newer ones+ // nest it under `metadata: { type: feedback }`. Accept either β the+ // semantics are identical and 12 of 17 real memory files this code+ // has seen use the older shape.+ const meta = (fm["metadata"] as Record<string, unknown> | undefined) ?? {};+ const nestedType = typeof meta["type"] === "string" ? meta["type"] : "";+ const topLevelType = typeof fm["type"] === "string" ? fm["type"] : "";+ const type = nestedType || topLevelType;+ if (type !== "feedback") {+ return { kind: "skip", skipReason: `type=${type || "<missing>"}; only feedback maps to Brain` };+ }+ if (!name || !description) {+ return { kind: "skip", skipReason: "feedback entry missing required name/description" };+ }+ const body = m[2]!.trim();+ const bodySha256 = createHash("sha256").update(body).digest("hex");+ return { kind: "feedback", name, description, body, bodySha256 };+}diff --git a/src/core/brain/claude-memory-paths.ts b/src/core/brain/claude-memory-paths.tsnew file mode 100644index 00000000..35b3652a--- /dev/null+++ b/src/core/brain/claude-memory-paths.ts@@ -0,0 +1,44 @@+import { existsSync, realpathSync } from "node:fs";+import { homedir } from "node:os";+import { resolve, sep } from "node:path";++/**+ * Claude Code projects directory uses a single leading-dash slug β e.g.+ * vault `/srv/projects/foo` maps to `~/.claude/projects/-srv-projects-foo/`.+ * The leading `/` of the absolute path is stripped first, then the+ * remaining slashes become dashes. Verified against+ * `ls /root/.claude/projects/` on the VPS where slugs are `-root`,+ * `-srv-projects-open-second-brain`, etc.+ */+export function defaultMemoryDir(vault: string): string {+ const slug = "-" + vault.replace(/^\/+/, "").replace(/\//g, "-");+ return resolve(homedir(), ".claude", "projects", slug, "memory");+}++/**+ * Refuse to import from anywhere outside `~/.claude/projects/`. The+ * comparison runs after `realpathSync` so a symlink pointing to a+ * sensitive system directory cannot smuggle reads β the realpath is+ * what matters, not the link path. Non-existent paths get the lexical+ * `resolve()` treatment (caller will hit ENOENT next anyway).+ */+export function assertSafeMemoryPath(path: string, override: boolean): void {+ if (override) return;+ const root = realResolveDir(resolve(homedir(), ".claude", "projects")) + sep;+ const norm = realResolveDir(resolve(path));+ if (!norm.startsWith(root)) {+ throw new Error(+ `refusing to import from ${path}: it is not under ~/.claude/projects/.\n` ++ `Pass --allow-arbitrary-memory-path to override.`,+ );+ }+}++function realResolveDir(p: string): string {+ if (!existsSync(p)) return p;+ try {+ return realpathSync(p);+ } catch {+ return p;+ }+}diff --git a/src/core/brain/claude-memory-plan.ts b/src/core/brain/claude-memory-plan.tsnew file mode 100644index 00000000..d400bddf--- /dev/null+++ b/src/core/brain/claude-memory-plan.ts@@ -0,0 +1,31 @@+export type PlanAction =+ | "CREATE"+ | "UPDATE"+ | "RECREATE"+ | "SKIP_UNCHANGED"+ | "CONFLICT";++export interface PlanActionInput {+ readonly basename: string;+ readonly prefId: string;+ readonly sha256: string;+ readonly inManifest: { sha256: string } | null;+ readonly prefExists: boolean;+}++export interface PlannedFile {+ readonly basename: string;+ readonly prefId: string;+ readonly action: PlanAction;+}++export function planAction(input: PlanActionInput): PlannedFile {+ const { basename, prefId, sha256, inManifest, prefExists } = input;+ if (inManifest === null) {+ return { basename, prefId, action: prefExists ? "CONFLICT" : "CREATE" };+ }+ if (inManifest.sha256 === sha256) {+ return { basename, prefId, action: prefExists ? "SKIP_UNCHANGED" : "RECREATE" };+ }+ return { basename, prefId, action: prefExists ? "UPDATE" : "CREATE" };+}diff --git a/src/core/brain/claude-memory-render.ts b/src/core/brain/claude-memory-render.tsnew file mode 100644index 00000000..5a00313e--- /dev/null+++ b/src/core/brain/claude-memory-render.ts@@ -0,0 +1,92 @@+export interface RenderMemoryInput {+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly memoryPath: string;+ readonly importedAt: string; // ISO Z+ readonly bodySha256: string;+}++/**+ * Slugify a Claude Memory `name` field for use as a Brain preference id.+ * Single source of truth: both the orchestrator and the renderer must+ * produce byte-identical slugs from the same input. Steps:+ * - underscores β dashes+ * - non-alphanumeric β dash+ * - lowercase+ * - collapse runs of dashes β single dash+ * - trim leading/trailing dashes+ *+ * The collapse step keeps human-typable ids like `pref-no-em-dashes`+ * instead of `pref-no---em-dashes` when the source name contains+ * punctuation or whitespace.+ */+export function slugifyMemoryName(name: string): string {+ return name+ .replace(/_/g, "-")+ .replace(/[^a-z0-9-]/gi, "-")+ .toLowerCase()+ .replace(/-{2,}/g, "-")+ .replace(/^-+|-+$/g, "");+}++const SCOPE_RE = /^scope:\s*([a-z][a-z0-9-]*)\s*$/m;++function extractScope(body: string): string {+ const m = body.match(SCOPE_RE);+ return m?.[1] ?? "writing";+}++function isoDay(iso: string): string {+ return iso.slice(0, 10);+}++export function renderPreferenceFromMemory(input: RenderMemoryInput): string {+ const slug = slugifyMemoryName(input.name);+ if (!slug) {+ // Punctuation-only / whitespace-only names produce an empty slug,+ // which would yield the bare `pref-` id and a blank `topic:` field.+ // Fail fast so the caller (orchestrator β CLI) surfaces a clear error+ // rather than writing an ambiguous preference file.+ throw new Error(+ `claude-memory: cannot derive a slug from name ${JSON.stringify(input.name)}; rename the memory entry to include at least one alphanumeric character`,+ );+ }+ const prefId = `pref-${slug}`;+ const topic = slug;+ const scope = extractScope(input.body);+ const fm = [+ "---",+ "kind: brain-preference",+ `id: ${prefId}`,+ `created_at: "${input.importedAt}"`,+ `_confirmed_at: "${input.importedAt}"`,+ `unconfirmed_until: "${input.importedAt}"`,+ `tags: [brain, brain/preference, brain/topic/${topic}, brain/scope/${scope}]`,+ `topic: ${topic}`,+ "_status: confirmed",+ `principle: ${JSON.stringify(input.description)}`,+ "_evidenced_by: []",+ "_applied_count: 0",+ "_violated_count: 0",+ "_last_evidence_at: null",+ "_confidence: high",+ "pinned: false",+ `scope: ${scope}`,+ "_force_confirmed_via: claude-memory",+ `_imported_from: ${JSON.stringify(input.memoryPath)}`,+ `_imported_sha256: ${input.bodySha256}`,+ `_imported_at: "${input.importedAt}"`,+ "---",+ "",+ input.body.trim(),+ "",+ "## Origin",+ "",+ "Imported from Claude Code MEMORY:",+ `\`${input.memoryPath}\``,+ `on ${isoDay(input.importedAt)}.`,+ "",+ ].join("\n");+ return fm;+}diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsnew file mode 100644index 00000000..0be16036--- /dev/null+++ b/src/core/brain/import-claude-memory.ts@@ -0,0 +1,267 @@+import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { appendLogEvent } from "./log.ts";+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";+import { createSnapshot } from "./snapshot.ts";+import { isoSecond } from "./time.ts";+import { resolveAgentName } from "../config.ts";+import { parseClaudeMemoryFile } from "./claude-memory-parser.ts";+import {+ loadManifest,+ saveManifest,+ type ClaudeMemoryManifest,+} from "./claude-memory-manifest.ts";+import { planAction, type PlannedFile } from "./claude-memory-plan.ts";+import { renderPreferenceFromMemory, slugifyMemoryName } from "./claude-memory-render.ts";+import { assertSafeMemoryPath } from "./claude-memory-paths.ts";+import { preferencePath } from "./paths.ts";++export interface ImportClaudeMemoryOpts {+ readonly vault: string;+ readonly memoryDir: string;+ readonly mode: "dry-run" | "apply";+ readonly allowArbitraryMemoryPath?: boolean;+ readonly now?: Date;+}++export interface ImportClaudeMemoryResult {+ readonly mode: "dry-run" | "apply";+ readonly plans: ReadonlyArray<PlannedFile>;+ readonly skipped: ReadonlyArray<{ basename: string; reason: string }>;+ readonly conflicts: ReadonlyArray<PlannedFile>;+ readonly applied: ReadonlyArray<PlannedFile>;+ readonly skippedUnchanged: ReadonlyArray<PlannedFile>;+ readonly snapshotRunId: string | null;+ readonly localDate: string;+}++/**+ * Merge accumulated evidence fields from an existing preference file into a+ * freshly-rendered preference body. Preserves the 8 fields that track+ * evidence history so a re-import does not lose accumulated learning signals.+ *+ * Fields preserved: _applied_count, _violated_count, _evidenced_by,+ * _last_evidence_at, _confirmed_at, unconfirmed_until, pinned, scope.+ */+function mergePreservingEvidence(existingBody: string, freshBody: string): string {+ const PRESERVED = [+ "_applied_count",+ "_violated_count",+ "_evidenced_by",+ "_last_evidence_at",+ "_confirmed_at",+ "unconfirmed_until",+ "pinned",+ "scope",+ ] as const;++ // Extract key: value lines from existing frontmatter (between the --- fences).+ const fmMatch = existingBody.match(/^---\n([\s\S]*?)\n---/);+ if (!fmMatch) return freshBody;+ const existingFm = fmMatch[1]!;++ let result = freshBody;+ for (const key of PRESERVED) {+ // Match `key: <anything up to end-of-line>` (also handles array notation).+ // Arrays in YAML inline form: `_evidenced_by: ['[[a.md]]', '[[b.md]]']`+ const existingMatch = existingFm.match(new RegExp(`^${key}:(.*)$`, "m"));+ if (!existingMatch) continue;+ const existingLine = `${key}:${existingMatch[1]!}`;+ // Replace the corresponding line in the fresh body.+ result = result.replace(new RegExp(`^${key}:.*$`, "m"), existingLine);+ }+ return result;+}++export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMemoryResult {+ assertSafeMemoryPath(opts.memoryDir, opts.allowArbitraryMemoryPath ?? false);+ if (!existsSync(opts.memoryDir)) {+ throw new Error(`memory directory not found: ${opts.memoryDir}`);+ }+ const now = opts.now ?? new Date();+ const importedAt = isoSecond(now);+ const localDate = importedAt.slice(0, 10);++ const manifest = loadManifest(opts.vault);+ const newImports: Record<string, { pref_id: string; sha256: string; imported_at: string }> = {+ ...manifest.imports,+ };++ const plans: PlannedFile[] = [];+ const skipped: Array<{ basename: string; reason: string }> = [];+ const filesToWrite: Array<{ plan: PlannedFile; body: string; sha256: string; slug: string }> = [];+ // Two MEMORY files with different basenames can slugify to the same+ // preference id (e.g. `feedback_no_em_dashes.md` and+ // `feedback no-em-dashes.md`). Without this guard, both would land+ // `pref-no-em-dashes.md`, and the second `atomicWriteFileSync` would+ // silently overwrite the first one. Track seen prefIds and route+ // any duplicate into the skipped list with a clear reason.+ const seenPrefIds = new Map<string, string>();++ for (const name of readdirSync(opts.memoryDir).sort()) {+ if (name === "MEMORY.md") continue;+ if (!name.endsWith(".md")) continue;+ const text = readFileSync(join(opts.memoryDir, name), "utf8");+ const parsed = parseClaudeMemoryFile(text);+ if (parsed.kind === "skip") {+ skipped.push({ basename: name, reason: parsed.skipReason });+ continue;+ }+ const slug = slugifyMemoryName(parsed.name);+ const prefId = `pref-${slug}`;+ const dupOf = seenPrefIds.get(prefId);+ if (dupOf) {+ skipped.push({+ basename: name,+ reason: `duplicate target preference id ${prefId} (also produced by ${dupOf}); rename the memory entry to disambiguate`,+ });+ continue;+ }+ seenPrefIds.set(prefId, name);+ // preferencePath adds pref- prefix itself, so pass just the slug+ const prefFile = preferencePath(opts.vault, slug);+ const manifestEntry = manifest.imports[name];+ const plan = planAction({+ basename: name,+ prefId,+ sha256: parsed.bodySha256,+ inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,+ prefExists: existsSync(prefFile),+ });+ plans.push(plan);+ if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {+ const body = renderPreferenceFromMemory({+ name: parsed.name,+ description: parsed.description,+ body: parsed.body,+ memoryPath: join(opts.memoryDir, name),+ importedAt,+ bodySha256: parsed.bodySha256,+ });+ filesToWrite.push({ plan, body, sha256: parsed.bodySha256, slug });+ }+ }++ const conflicts = plans.filter((p) => p.action === "CONFLICT");+ const skippedUnchanged = plans.filter((p) => p.action === "SKIP_UNCHANGED");++ if (opts.mode === "dry-run") {+ return {+ mode: "dry-run",+ plans,+ skipped,+ conflicts,+ applied: [],+ skippedUnchanged,+ snapshotRunId: null,+ localDate,+ };+ }++ // Β§E design: process the non-conflict files first; throw `ConflictsError`+ // at the end if any CONFLICT was detected. This matches design doc Β§E+ // line "The run still processes the remaining files; final exit code is+ // 0 only if every file is CREATE / UPDATE / RECREATE / SKIP_UNCHANGED."+ // Caller (CLI) uses the thrown error to exit 2 while the applied side+ // of the run still landed.++ let snapshotRunId: string | null = null;+ if (filesToWrite.length > 0) {+ const runId = `import-claude-memory-${importedAt.replace(/:/g, "-")}`;+ createSnapshot(opts.vault, runId);+ snapshotRunId = runId;+ }++ const applied: PlannedFile[] = [];+ if (filesToWrite.length > 0) {+ mkdirSync(join(opts.vault, "Brain", "preferences"), { recursive: true });+ }+ for (const { plan, body: freshBody, sha256, slug } of filesToWrite) {+ const prefFile = preferencePath(opts.vault, slug);+ let finalBody = freshBody;+ if (plan.action === "UPDATE") {+ // Preserve evidence fields by merging frontmatter.+ finalBody = mergePreservingEvidence(readFileSync(prefFile, "utf8"), freshBody);+ }+ atomicWriteFileSync(prefFile, finalBody);+ newImports[plan.basename] = { pref_id: plan.prefId, sha256, imported_at: importedAt };+ applied.push(plan);+ }++ // Only persist the manifest and emit a log event if the run actually+ // did something (wrote files OR observed conflicts). A no-op apply+ // (every plan SKIP_UNCHANGED, no conflicts) should not bloat the log.+ const didSomething = applied.length > 0 || conflicts.length > 0;+ if (didSomething) {+ saveManifest(opts.vault, { version: 1, imports: newImports });++ const counts = {+ created: plans.filter((p) => p.action === "CREATE").length,+ updated: plans.filter((p) => p.action === "UPDATE").length,+ recreated: plans.filter((p) => p.action === "RECREATE").length,+ skipped_unchanged: skippedUnchanged.length,+ skipped_non_feedback: skipped.length,+ conflicts: conflicts.length,+ };+ appendLogEvent(opts.vault, {+ timestamp: importedAt,+ eventType: BRAIN_LOG_EVENT_KIND.importClaudeMemory,+ body: {+ created: String(counts.created),+ updated: String(counts.updated),+ recreated: String(counts.recreated),+ skipped_unchanged: String(counts.skipped_unchanged),+ skipped_non_feedback: String(counts.skipped_non_feedback),+ conflicts: String(counts.conflicts),+ snapshot: snapshotRunId ?? "none",+ agent: resolveAgentName(),+ },+ });+ }++ if (conflicts.length > 0) {+ // Throw AFTER landing the safe writes so partial progress is preserved.+ // The error carries the conflict list; the CLI prints them and exits 2.+ throw new ConflictsError(conflicts, {+ applied,+ skipped,+ skippedUnchanged,+ snapshotRunId,+ localDate,+ });+ }++ return {+ mode: "apply",+ plans,+ skipped,+ conflicts,+ applied,+ skippedUnchanged,+ snapshotRunId,+ localDate,+ };+}++export interface ConflictsPartialProgress {+ readonly applied: ReadonlyArray<PlannedFile>;+ readonly skipped: ReadonlyArray<{ basename: string; reason: string }>;+ readonly skippedUnchanged: ReadonlyArray<PlannedFile>;+ readonly snapshotRunId: string | null;+ readonly localDate: string;+}++export class ConflictsError extends Error {+ readonly conflicts: ReadonlyArray<PlannedFile>;+ readonly partial: ConflictsPartialProgress | null;+ constructor(+ conflicts: ReadonlyArray<PlannedFile>,+ partial: ConflictsPartialProgress | null = null,+ ) {+ super(`import-claude-memory: ${conflicts.length} conflict(s)`);+ this.conflicts = conflicts;+ this.partial = partial;+ }+}diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 6b25723e..927fcf7c 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -20,7 +20,7 @@import { existsSync, readFileSync } from "node:fs";-import type { BrainConfig } from "./types.ts";+import type { BrainConfig, DisciplineReportConfig } from "./types.ts";import { brainConfigPath } from "./paths.ts";/** Schema versions this build understands. Bump on incompatible changes. */@@ -390,6 +390,90 @@ export function validateBrainConfigDetailed();requirePositiveInteger("snapshots.retention_count", snapshots.retention_count, source);+ // Optional `discipline_report` section. On any type mismatch, emit a+ // warning and drop the section (return undefined) rather than throwing β+ // the rest of the CLI surface must keep working.+ let disciplineReport: DisciplineReportConfig | undefined;+ if ("discipline_report" in obj) {+ const dr = obj["discipline_report"];+ if (typeof dr !== "object" || dr === null || Array.isArray(dr)) {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report: must be a map of keys; got ${describe(dr)} β section ignored`,+ });+ } else {+ const drObj = dr as Record<string, unknown>;+ let ok = true;++ // enabled: boolean+ if (typeof drObj["enabled"] !== "boolean") {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.enabled: must be a boolean; got ${describe(drObj["enabled"])} β section ignored`,+ });+ ok = false;+ }++ // timezone: string+ if (typeof drObj["timezone"] !== "string") {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.timezone: must be a string; got ${describe(drObj["timezone"])} β section ignored`,+ });+ ok = false;+ }++ // watched_paths: array of strings+ if (!Array.isArray(drObj["watched_paths"])) {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.watched_paths: must be an array; got ${describe(drObj["watched_paths"])} β section ignored`,+ });+ ok = false;+ } else {+ const badIdx = (drObj["watched_paths"] as unknown[]).findIndex(+ (v) => typeof v !== "string",+ );+ if (badIdx >= 0) {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.watched_paths[${badIdx}]: must be a string; got ${describe((drObj["watched_paths"] as unknown[])[badIdx])} β section ignored`,+ });+ ok = false;+ }+ }++ // known_agents: array of strings+ if (!Array.isArray(drObj["known_agents"])) {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.known_agents: must be an array; got ${describe(drObj["known_agents"])} β section ignored`,+ });+ ok = false;+ } else {+ const badIdx = (drObj["known_agents"] as unknown[]).findIndex(+ (v) => typeof v !== "string",+ );+ if (badIdx >= 0) {+ warnings.push({+ path: source ?? "<config>",+ message: `discipline_report.known_agents[${badIdx}]: must be a string; got ${describe((drObj["known_agents"] as unknown[])[badIdx])} β section ignored`,+ });+ ok = false;+ }+ }++ if (ok) {+ disciplineReport = {+ enabled: drObj["enabled"] as boolean,+ timezone: drObj["timezone"] as string,+ watched_paths: drObj["watched_paths"] as ReadonlyArray<string>,+ known_agents: drObj["known_agents"] as ReadonlyArray<string>,+ };+ }+ }+ }+// Forward-compat: unknown top-level keys β warning, not error.const known = new Set(["schema_version",@@ -398,6 +482,7 @@ export function validateBrainConfigDetailed("retire","confidence","snapshots",+ "discipline_report",]);for (const key of Object.keys(obj)) {if (!known.has(key)) {@@ -429,6 +514,7 @@ export function validateBrainConfigDetailed(snapshots: {retention_count: snapshots.retention_count as number,},+ ...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),};return { config, warnings };@@ -540,7 +626,8 @@ function describe(value: unknown): string {// inline arrays, anchors, and aliases β none of which the schema needs.type ParsedScalar = number | string | boolean | null;-type ParsedBlock = Record<string, ParsedScalar | Record<string, ParsedScalar>>;+type ParsedBlockValue = ParsedScalar | Record<string, ParsedScalar | ParsedScalar[]> | ParsedScalar[];+type ParsedBlock = Record<string, ParsedBlockValue>;interface Line {readonly raw: string;@@ -563,7 +650,10 @@ export function parseBrainYaml(text: string): ParsedBlock {const kv = splitKeyValue(line);if (kv.value === "") {// Block header: collect indented children.- const child: Record<string, ParsedScalar> = {};+ // Each child may be a scalar value (`key: val`) or a list (`key:` followed+ // by deeper-indented `- item` lines). Lists-within-blocks are the only+ // third-level nesting we support β they are required for `discipline_report`.+ const child: Record<string, ParsedScalar | ParsedScalar[]> = {};i++;const blockIndent = detectBlockIndent(lines, i);while (i < lines.length && lines[i]!.indent >= blockIndent && blockIndent > 0) {@@ -576,9 +666,56 @@ export function parseBrainYaml(text: string): ParsedBlock {}const innerKv = splitKeyValue(inner);if (innerKv.value === "") {- throw new Error(- `line ${inner.lineNumber}: nested blocks deeper than one level are not supported`,- );+ // Child key with no value β expect a list of `- item` lines at a+ // deeper indent level.+ i++;+ const listIndent = detectBlockIndent(lines, i);+ if (listIndent <= blockIndent) {+ // Empty list (next line is at the same or shallower indent).+ if (innerKv.key in child) {+ throw new Error(+ `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,+ );+ }+ child[innerKv.key] = [];+ continue;+ }+ const items: ParsedScalar[] = [];+ while (i < lines.length && lines[i]!.indent >= listIndent) {+ const listLine = lines[i]!;+ if (listLine.indent !== listIndent) {+ throw new Error(+ `line ${listLine.lineNumber}: inconsistent indentation in list '${innerKv.key}' ` ++ `(expected ${listIndent} spaces, got ${listLine.indent})`,+ );+ }+ if (!listLine.content.startsWith("- ") && listLine.content !== "-") {+ // If it looks like a `key: value` pair, it's a deeper block β not+ // supported. Preserve the original error message so existing tests+ // that assert on the wording keep passing.+ if (/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(listLine.content)) {+ throw new Error(+ `line ${listLine.lineNumber}: nested blocks deeper than one level are not supported`,+ );+ }+ throw new Error(+ `line ${listLine.lineNumber}: expected list item starting with '- ' ` ++ `in '${kv.key}.${innerKv.key}'`,+ );+ }+ const itemText = listLine.content.startsWith("- ")+ ? listLine.content.slice(2).trim()+ : "";+ items.push(parseScalar(itemText, listLine.lineNumber));+ i++;+ }+ if (innerKv.key in child) {+ throw new Error(+ `line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`,+ );+ }+ child[innerKv.key] = items;+ continue;}if (innerKv.key in child) {throw new Error(diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 18da7b97..3cb59cfd 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -179,6 +179,13 @@ export const BRAIN_LOG_EVENT_KIND = {* vault-relative paths of every managed file that was rewritten.*/upgrade: "upgrade",+ /**+ * `import-claude-memory` β operator imported Claude Code memory via+ * `o2b brain import-claude-memory <path>`. One log block per import;+ * payload carries counters for created, updated, recreated, and skipped+ * entries, plus conflict and snapshot information.+ */+ importClaudeMemory: "import-claude-memory",} as const;export type BrainLogEventKind =(typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];@@ -525,6 +532,16 @@ export interface BrainUpgradeLogEvent extends BrainLogEventBase {readonly run_id: string;}+/**+ * `import-claude-memory` entry β operator ran+ * `o2b brain import-claude-memory <path>`. Payload carries+ * counters for created, updated, recreated, skipped_unchanged,+ * skipped_non_feedback, plus conflict and snapshot information.+ */+export interface BrainImportClaudeMemoryLogEvent extends BrainLogEventBase {+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.importClaudeMemory;+}+/** Discriminated union of every concrete log event type. */export type BrainLogEvent =| BrainDreamLogEvent@@ -543,7 +560,8 @@ export type BrainLogEvent =| BrainImportSessionLogEvent| BrainMigrateFrontmatterLogEvent| BrainMergeLogEvent- | BrainUpgradeLogEvent;+ | BrainUpgradeLogEvent+ | BrainImportClaudeMemoryLogEvent;// ----- Configuration (`Brain/_brain.yaml`) ----------------------------------@@ -591,6 +609,18 @@ export interface BrainSnapshotsConfig {readonly retention_count: number;}+/**+ * Optional configuration for the daily discipline report (Β§D of the+ * agent-discipline-tail design). Absent on vaults that have not opted+ * in; the loader returns `undefined` rather than injecting defaults.+ */+export interface DisciplineReportConfig {+ readonly enabled: boolean;+ readonly timezone: string;+ readonly watched_paths: ReadonlyArray<string>;+ readonly known_agents: ReadonlyArray<string>;+}+/*** Root of `Brain/_brain.yaml`. `schema_version` is mandatory; unknown* top-level keys are tolerated as forward-compat (logged as a warning by@@ -612,4 +642,6 @@ export interface BrainConfig {readonly retire: BrainRetireConfig;readonly confidence: BrainConfidenceConfig;readonly snapshots: BrainSnapshotsConfig;+ /** Optional daily discipline-report configuration (Β§D). Absent when not configured. */+ readonly discipline_report?: DisciplineReportConfig;}diff --git a/src/core/discipline/activity-git.ts b/src/core/discipline/activity-git.tsnew file mode 100644index 00000000..3e59be53--- /dev/null+++ b/src/core/discipline/activity-git.ts@@ -0,0 +1,63 @@+import { existsSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { join } from "node:path";++export interface ActivityWindow {+ readonly startUtc: Date;+ readonly endUtc: Date;+}++export interface GitActivity {+ readonly commits: number;+ readonly filesChanged: number;+ readonly insertions: number;+ readonly deletions: number;+}++export function gitActivity(+ path: string,+ win: ActivityWindow,+): GitActivity | null {+ if (!existsSync(join(path, ".git"))) return null;+ const since = win.startUtc.toISOString();+ const until = win.endUtc.toISOString();+ let raw: string;+ try {+ raw = execFileSync(+ "git",+ [+ "-C", path, "log",+ `--since=${since}`, `--until=${until}`,+ "--no-merges", "--numstat",+ "--pretty=tformat:__COMMIT__",+ ],+ { encoding: "utf8" },+ );+ } catch {+ // Surface git failure as `null` so the orchestrator can fall back to+ // mtime activity for this watched path. Returning zeros would mask a+ // real "the agent shipped commits but git refused to talk" day and+ // suppress the alert Β§D exists to raise.+ return null;+ }++ let commits = 0;+ let insertions = 0;+ let deletions = 0;+ const seenFiles = new Set<string>();++ for (const line of raw.split("\n")) {+ if (line === "__COMMIT__") {+ commits += 1;+ continue;+ }+ // numstat format: "<added>\t<deleted>\t<filename>"+ const m = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);+ if (!m) continue;+ insertions += m[1] === "-" ? 0 : Number(m[1]);+ deletions += m[2] === "-" ? 0 : Number(m[2]);+ seenFiles.add(m[3]!);+ }++ return { commits, filesChanged: seenFiles.size, insertions, deletions };+}diff --git a/src/core/discipline/activity-mtime.ts b/src/core/discipline/activity-mtime.tsnew file mode 100644index 00000000..cdf0d549--- /dev/null+++ b/src/core/discipline/activity-mtime.ts@@ -0,0 +1,64 @@+import { lstatSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";+import type { ActivityWindow } from "./activity-git.ts";++const EXCLUDE_DIRS: ReadonlySet<string> = new Set([+ ".git", ".hg", ".svn",+ "node_modules", ".cache",+ "__pycache__", ".venv", "venv",+ ".snapshots",+ "dist", "build", "out",+]);++export interface MtimeActivity {+ readonly modifiedFiles: number;+}++export function mtimeActivity(root: string, win: ActivityWindow): MtimeActivity {+ const startMs = win.startUtc.getTime();+ const endMs = win.endUtc.getTime();+ let count = 0;++ function walk(dir: string): void {+ let entries: string[];+ try {+ entries = readdirSync(dir);+ } catch {+ return;+ }+ for (const name of entries) {+ if (EXCLUDE_DIRS.has(name)) continue;+ const p = join(dir, name);+ // lstatSync first β refuse to follow symlinks so we never recurse+ // through a symlink cycle (`a -> b -> a`) or escape the watched+ // tree via a symlink to `/`. Regular files reachable through a+ // symlinked parent are skipped too, which matches what a+ // cron-friendly nightly walk should do.+ let lst;+ try {+ lst = lstatSync(p);+ } catch {+ continue;+ }+ if (lst.isSymbolicLink()) continue;+ if (lst.isDirectory()) {+ walk(p);+ continue;+ }+ if (!lst.isFile()) continue;+ // statSync (deref) is fine here because we already know the entry+ // is a regular file via lstat β no symlink follow happens.+ let st;+ try {+ st = statSync(p);+ } catch {+ continue;+ }+ const m = st.mtimeMs;+ if (m >= startMs && m < endMs) count += 1;+ }+ }++ walk(root);+ return { modifiedFiles: count };+}diff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.tsnew file mode 100644index 00000000..50f29376--- /dev/null+++ b/src/core/discipline/decision.ts@@ -0,0 +1,44 @@+import type { BrainEventCounts } from "./log-counts.ts";+import type { GitActivity } from "./activity-git.ts";+import type { MtimeActivity } from "./activity-mtime.ts";+import type { VaultDelta } from "./vault-delta.ts";++export interface RepoActivityRow {+ readonly path: string;+ readonly git: GitActivity;+}+export interface NonRepoActivityRow {+ readonly path: string;+ readonly modifiedFiles: number;+}++export interface ActivitySummary {+ readonly repo: ReadonlyArray<RepoActivityRow>;+ readonly nonRepo: ReadonlyArray<NonRepoActivityRow>;+ readonly vaultDelta: VaultDelta;+}++export type DisciplineStatus = "ok" | "info" | "alert";++export function decideStatus(+ events: BrainEventCounts,+ activity: ActivitySummary,+): DisciplineStatus {+ // Taste events only: feedback + apply_evidence. The `other` bucket+ // (snapshot / dream-pass / import-claude-memory / migrate-frontmatter)+ // would otherwise mask a real "agent shipped artifacts but recorded+ // zero taste signals" day β exactly the regression Β§D exists to catch.+ let tasteEvents = 0;+ for (const c of Object.values(events.byAgent)) {+ tasteEvents += c.feedback + c.apply_evidence;+ }+ for (const u of events.unknownAgents) {+ tasteEvents += u.counts.feedback + u.counts.apply_evidence;+ }+ if (tasteEvents > 0) return "ok";+ const repoCommits = activity.repo.reduce((a, r) => a + r.git.commits, 0);+ const mtimeFiles = activity.nonRepo.reduce((a, r) => a + r.modifiedFiles, 0);+ const vaultActive = activity.vaultDelta.total > 0;+ const activitySignal = repoCommits > 0 || mtimeFiles >= 3 || vaultActive;+ return activitySignal ? "alert" : "info";+}diff --git a/src/core/discipline/log-counts.ts b/src/core/discipline/log-counts.tsnew file mode 100644index 00000000..250fdc7e--- /dev/null+++ b/src/core/discipline/log-counts.ts@@ -0,0 +1,50 @@+import { parseLogDay } from "../brain/log.ts";++export interface AgentCounts {+ readonly feedback: number;+ readonly apply_evidence: number;+ readonly other: number;+ readonly total: number;+}++export interface BrainEventCounts {+ readonly byAgent: Readonly<Record<string, AgentCounts>>;+ readonly unknownAgents: ReadonlyArray<{ agent: string; counts: AgentCounts }>;+ readonly total: number;+}++function zero(): AgentCounts {+ return { feedback: 0, apply_evidence: 0, other: 0, total: 0 };+}++function bump(c: AgentCounts, kind: string): AgentCounts {+ if (kind === "feedback") return { ...c, feedback: c.feedback + 1, total: c.total + 1 };+ if (kind === "apply-evidence") return { ...c, apply_evidence: c.apply_evidence + 1, total: c.total + 1 };+ return { ...c, other: c.other + 1, total: c.total + 1 };+}++export function countBrainEvents(+ vault: string,+ date: string,+ knownAgents: ReadonlyArray<string>,+): BrainEventCounts {+ const byAgent: Record<string, AgentCounts> = {};+ for (const a of knownAgents) byAgent[a] = zero();++ const unknown: Record<string, AgentCounts> = {};+ const { entries } = parseLogDay(vault, date);+ let total = 0;+ for (const e of entries) {+ const agentField = e.body["agent"];+ if (!agentField || typeof agentField !== "string") continue;+ const target = knownAgents.includes(agentField) ? byAgent : unknown;+ target[agentField] = bump(target[agentField] ?? zero(), e.eventType);+ total += 1;+ }++ return {+ byAgent,+ unknownAgents: Object.entries(unknown).map(([agent, counts]) => ({ agent, counts })),+ total,+ };+}diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.tsnew file mode 100644index 00000000..355de917--- /dev/null+++ b/src/core/discipline/render.ts@@ -0,0 +1,63 @@+import { escapeMarkdownV2 as e } from "./telegram.ts";+import type { BrainEventCounts } from "./log-counts.ts";+import type { ActivitySummary, DisciplineStatus } from "./decision.ts";++export interface RenderInput {+ readonly localDate: string;+ readonly timezone: string;+ readonly status: DisciplineStatus;+ readonly events: BrainEventCounts;+ readonly activity: ActivitySummary;+}++export function renderReport(r: RenderInput): string {+ const lines: string[] = [];+ lines.push(`π§ OSB discipline β ${e(r.localDate)} \\(${e(r.timezone)}\\)`);+ lines.push("");+ lines.push(`Status: ${e(r.status)}`);+ lines.push("");++ lines.push("Brain events:");+ const knownEntries = Object.entries(r.events.byAgent);+ if (knownEntries.length === 0) {+ lines.push("\\- \\(no known agents configured\\)");+ } else {+ for (const [agent, c] of knownEntries) {+ lines.push(+ `\\- ${e(agent)}: ${c.feedback} feedback, ${c.apply_evidence} apply\\-evidence, ${c.other} other \\(total ${c.total}\\)`,+ );+ }+ }+ for (const u of r.events.unknownAgents) {+ lines.push(+ `\\- ${e(u.agent)} \\(unknown\\): ${u.counts.feedback} feedback, ${u.counts.apply_evidence} apply\\-evidence, ${u.counts.other} other \\(total ${u.counts.total}\\)`,+ );+ }+ lines.push("");++ lines.push("Activity:");+ for (const row of r.activity.repo) {+ lines.push(+ `\\- ${e(row.path)} β ${row.git.commits} commits, ${row.git.filesChanged} files, \\+${row.git.insertions}/\\-${row.git.deletions}`,+ );+ }+ for (const row of r.activity.nonRepo) {+ lines.push(`\\- ${e(row.path)} β ${row.modifiedFiles} modified files`);+ }+ const vd = r.activity.vaultDelta;+ lines.push(+ `\\- vault β ${vd.newSignals} new signals, ${vd.newPreferences} new preferences, ${vd.newRetired} new retired`,+ );++ if (r.status === "alert") {+ lines.push("");+ // Unescaped wrapper underscores so Telegram MarkdownV2 reads the line+ // as italic; the period in the middle stays escaped because it is a+ // reserved character. With both underscores escaped (as before) the+ // styling intent silently failed and rendered literal "_" instead.+ lines.push(+ "_Activity present; zero brain events recorded\\. Stop guardrail likely bypassed or hook regressed\\._",+ );+ }+ return lines.join("\n");+}diff --git a/src/core/discipline/report.ts b/src/core/discipline/report.tsnew file mode 100644index 00000000..726eaef4--- /dev/null+++ b/src/core/discipline/report.ts@@ -0,0 +1,72 @@+import { existsSync } from "node:fs";+import { join } from "node:path";++import { BrainConfigError, loadBrainConfig } from "../brain/policy.ts";+import { countBrainEvents, type BrainEventCounts } from "./log-counts.ts";+import { gitActivity } from "./activity-git.ts";+import { mtimeActivity } from "./activity-mtime.ts";+import { vaultDelta } from "./vault-delta.ts";+import { decideStatus, type ActivitySummary, type DisciplineStatus, type RepoActivityRow, type NonRepoActivityRow } from "./decision.ts";+import { renderReport } from "./render.ts";+import { yesterdayWindow } from "./window.ts";++export interface RunDisciplineReportOpts {+ readonly vault: string;+ readonly now?: Date;+}++export interface DisciplineReportResult {+ readonly status: DisciplineStatus | "disabled";+ readonly text: string;+ readonly localDate: string | null;+ readonly events: BrainEventCounts | null;+ readonly activity: ActivitySummary | null;+}++export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineReportResult {+ // A vault without Brain/_brain.yaml (legacy bare vault, or fresh `o2b+ // init` without `o2b brain init`) used to crash the report path here.+ // Downgrade to the `disabled` shape β same as an explicit `enabled:+ // false` β so the Hermes cron stays silent instead of posting empty+ // messages on every tick.+ let cfg;+ try {+ cfg = loadBrainConfig(opts.vault);+ } catch (e) {+ if (e instanceof BrainConfigError) {+ return { status: "disabled", text: "", localDate: null, events: null, activity: null };+ }+ throw e;+ }+ const d = cfg.discipline_report;+ if (!d || !d.enabled) {+ return { status: "disabled", text: "", localDate: null, events: null, activity: null };+ }+ const now = opts.now ?? new Date();+ const win = yesterdayWindow(now, d.timezone);+ const events = countBrainEvents(opts.vault, win.localDate, d.known_agents);++ const repo: RepoActivityRow[] = [];+ const nonRepo: NonRepoActivityRow[] = [];+ for (const p of d.watched_paths) {+ const g = gitActivity(p, win);+ if (g !== null) {+ repo.push({ path: p, git: g });+ } else if (existsSync(p)) {+ const m = mtimeActivity(p, win);+ nonRepo.push({ path: p, modifiedFiles: m.modifiedFiles });+ }+ }+ const vd = vaultDelta(opts.vault, win);++ const activity: ActivitySummary = { repo, nonRepo, vaultDelta: vd };+ const status = decideStatus(events, activity);+ const text = renderReport({+ localDate: win.localDate,+ timezone: d.timezone,+ status,+ events,+ activity,+ });+ return { status, text, localDate: win.localDate, events, activity };+}diff --git a/src/core/discipline/telegram.ts b/src/core/discipline/telegram.tsnew file mode 100644index 00000000..5761844e--- /dev/null+++ b/src/core/discipline/telegram.ts@@ -0,0 +1,6 @@+// Telegram MarkdownV2 reserves these β backslash-escape them.+const RESERVED = /([_*\[\]()~`>#+\-=|{}.!\\])/g;++export function escapeMarkdownV2(s: string): string {+ return s.replace(RESERVED, "\\$1");+}diff --git a/src/core/discipline/vault-delta.ts b/src/core/discipline/vault-delta.tsnew file mode 100644index 00000000..d4d28729--- /dev/null+++ b/src/core/discipline/vault-delta.ts@@ -0,0 +1,47 @@+import { existsSync, readdirSync, statSync } from "node:fs";+import { join } from "node:path";+import type { ActivityWindow } from "./activity-git.ts";++export interface VaultDelta {+ readonly newSignals: number;+ readonly newPreferences: number;+ readonly newRetired: number;+ readonly total: number;+}++function countInWindow(dir: string, win: ActivityWindow): number {+ if (!existsSync(dir)) return 0;+ // Mirror the defensive shape from activity-mtime: readdirSync /+ // statSync can race with concurrent writers (dream pass, signal+ // import) and would otherwise crash the nightly cron with an+ // unhandled ENOENT/EPERM.+ let entries: string[];+ try {+ entries = readdirSync(dir);+ } catch {+ return 0;+ }+ let n = 0;+ for (const name of entries) {+ const p = join(dir, name);+ let st;+ try {+ st = statSync(p);+ } catch {+ continue;+ }+ if (!st.isFile()) continue;+ if (st.mtimeMs >= win.startUtc.getTime() && st.mtimeMs < win.endUtc.getTime()) n += 1;+ }+ return n;+}++export function vaultDelta(vault: string, win: ActivityWindow): VaultDelta {+ const newSignals = countInWindow(join(vault, "Brain", "inbox"), win);+ const newPreferences = countInWindow(join(vault, "Brain", "preferences"), win);+ const newRetired = countInWindow(join(vault, "Brain", "retired"), win);+ return {+ newSignals, newPreferences, newRetired,+ total: newSignals + newPreferences + newRetired,+ };+}diff --git a/src/core/discipline/window.ts b/src/core/discipline/window.tsnew file mode 100644index 00000000..7b548f13--- /dev/null+++ b/src/core/discipline/window.ts@@ -0,0 +1,88 @@+export interface YesterdayWindow {+ readonly localDate: string; // YYYY-MM-DD in tz+ readonly startUtc: Date;+ readonly endUtc: Date;+}++/**+ * Compute the [start, end) UTC interval that covers "yesterday" in the+ * given IANA timezone, relative to `now`. JS has no built-in tz-aware+ * Date arithmetic, but Intl formatting is enough for the +/- second+ * granularity we need here.+ */+export function yesterdayWindow(now: Date, tz: string): YesterdayWindow {+ // Project now β local civil date.+ const fmt = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ });+ const todayLocal = fmt.format(now); // e.g. "2026-05-18"+ const parts = todayLocal.split("-").map(Number);+ const y = parts[0]!;+ const m = parts[1]!;+ const d = parts[2]!;+ const todayLocalMidnightUtc = localMidnightUtc(y, m, d, tz);+ const yesterdayLocalMidnightUtc = new Date(+ todayLocalMidnightUtc.getTime() - 24 * 60 * 60 * 1000,+ );+ const localDate = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ }).format(yesterdayLocalMidnightUtc);+ return {+ localDate,+ startUtc: yesterdayLocalMidnightUtc,+ endUtc: todayLocalMidnightUtc,+ };+}++/**+ * Find the UTC instant that corresponds to local midnight on the given+ * civil date in tz. Iteratively correct the naive UTC midnight using+ * Intl's offset for the guessed instant. 4 iterations is enough for any+ * IANA timezone (verified against tzdata 2024a).+ *+ * The drift correction must include both time-of-day AND date offset.+ * For west-of-UTC zones, the naive `Date.UTC(y, m-1, d, 0, 0, 0)`+ * instant projects to the PREVIOUS local date β without a day-delta+ * term the loop would settle on `00:00:00` on the wrong civil date and+ * silently return a window 24 hours early.+ */+function localMidnightUtc(y: number, m: number, d: number, tz: string): Date {+ let guess = new Date(Date.UTC(y, m - 1, d, 0, 0, 0));+ const expected = `${y.toString().padStart(4, "0")}-${m.toString().padStart(2, "0")}-${d.toString().padStart(2, "0")}`;+ for (let i = 0; i < 4; i++) {+ const local = new Intl.DateTimeFormat("en-CA", {+ timeZone: tz,+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hourCycle: "h23",+ }).format(guess);+ const [date, time] = local.split(", ");+ const timeParts = (time ?? "").split(":").map(Number);+ const hh = timeParts[0]!;+ const mm = timeParts[1]!;+ const ss = timeParts[2]!;+ const dateParts = (date ?? "").split("-").map(Number);+ const ly = dateParts[0]!;+ const lm = dateParts[1]!;+ const ld = dateParts[2]!;+ // Whole-day signed offset between the observed local date and the+ // target civil date. UTC-based midnight arithmetic is safe here+ // because both inputs are already date-only.+ const dayDelta =+ (Date.UTC(ly, lm - 1, ld) - Date.UTC(y, m - 1, d)) / 86_400_000;+ const drift = dayDelta * 86400 + hh * 3600 + mm * 60 + ss;+ if (date === expected && drift === 0) return guess;+ guess = new Date(guess.getTime() - drift * 1000);+ }+ return guess;+}diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 4400d22f..f5d9d3bc 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -8,9 +8,42 @@* handlers remain on disk for shell-side use).*/-export function buildInstructions(defaultAgent: string): string {+import type { ToolScope } from "./tools.ts";++export interface BuildInstructionsOpts {+ /** Resolved agent identity (e.g. "hermes-vps-agent"). */+ readonly agent: string;+ /** Vault path β reserved for future per-vault customisation. */+ readonly vault?: string;+ /** When "writer", return the trimmed writer-surface text. */+ readonly scope?: ToolScope;+}++const WRITER_INSTRUCTIONS = `Open Second Brain β writer surface (always-loaded).++Two tools live here:+ - brain_feedback β record one new taste signal the user just expressed.+ - brain_apply_evidence β record applied | violated | outdated against an+ active preference for an artifact this turn produced.++The remaining Brain surface (digest, query, doctor, backlinks, search,+Pay Memory tools, vault_health, second_brain_status, second_brain_query,+and the scheduled learning pass) lives on the sibling+"open-second-brain" MCP server (deferred). Use ToolSearch to reach it.++Prefer the writer-server copy of brain_feedback / brain_apply_evidence over+any duplicate exposed by the full server β both call the same handler, but the+writer copy is always available without ToolSearch.`;++export function buildInstructions(opts: BuildInstructionsOpts | string): string {+ // Legacy call-site compat: plain string β full-surface branch.+ const agent = typeof opts === "string" ? opts : opts.agent;+ const scope = typeof opts === "string" ? undefined : opts.scope;++ if (scope === "writer") return WRITER_INSTRUCTIONS;+return (- `You are @${defaultAgent} on this Open Second Brain vault. ` ++ `You are @${agent} on this Open Second Brain vault. ` +"Always log under this identity; do not invent or change the name.\n\n" +"Brain tools are the agent-facing writable surface (design doc Β§9).\n" +" - brain_feedback β call once per taste signal the user (or a " +diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 4197a44e..7dd9d945 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -22,7 +22,7 @@ import {listResourceTemplates,readResource,} from "./resources.ts";-import { buildToolTable, findTool, type ServerContext, type ToolDefinition } from "./tools.ts";+import { buildToolTable, findTool, type ServerContext, type ToolDefinition, type ToolScope } from "./tools.ts";export interface MCPServerOptions {readonly vault: string;@@ -30,6 +30,11 @@ export interface MCPServerOptions {readonly repoRoot?: string | null;}+export interface MCPServerRuntimeOptions {+ readonly serverName?: string;+ readonly scope?: ToolScope;+}+export interface JsonRpcRequest {readonly jsonrpc?: string;readonly id?: unknown;@@ -49,12 +54,16 @@ export class MCPServer {readonly configPath: string | null;readonly repoRoot: string | null;readonly tools: ReadonlyArray<ToolDefinition>;+ private readonly serverName: string;+ private readonly scope: ToolScope;- constructor(opts: MCPServerOptions) {+ constructor(opts: MCPServerOptions, runtimeOpts: MCPServerRuntimeOptions = {}) {this.vault = opts.vault;this.configPath = opts.configPath ?? null;this.repoRoot = opts.repoRoot ?? null;- this.tools = buildToolTable();+ this.serverName = runtimeOpts.serverName ?? SERVER_NAME;+ this.scope = runtimeOpts.scope ?? "full";+ this.tools = buildToolTable(this.scope);}get context(): ServerContext {@@ -148,8 +157,8 @@ export class MCPServer {tools: { listChanged: false },resources: { listChanged: false, subscribe: false },},- serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },- instructions: buildInstructions(defaultAgent),+ serverInfo: { name: this.serverName, version: SERVER_VERSION },+ instructions: buildInstructions({ agent: defaultAgent, scope: this.scope }),};}diff --git a/src/mcp/stdio.ts b/src/mcp/stdio.tsindex 70e9d71d..3f380906 100644--- a/src/mcp/stdio.ts+++ b/src/mcp/stdio.ts@@ -8,7 +8,7 @@import { createInterface } from "node:readline";import type { Readable, Writable } from "node:stream";-import { MCPServer } from "./server.ts";+import { MCPServer, type MCPServerOptions, type MCPServerRuntimeOptions } from "./server.ts";import { errorResponse, type JsonRpcResponse } from "./server.ts";import { INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";@@ -26,9 +26,14 @@ export interface ServeStdioOptions {* batch requests (an array at the top level) yield a `-32600` invalid-request* response, matching the 2025-06-18 spec which removed batch support.*/-export async function serveStdio(server: MCPServer, opts: ServeStdioOptions = {}): Promise<number> {- const stdin = opts.stdin ?? process.stdin;- const stdout = opts.stdout ?? process.stdout;+export async function serveStdio(+ ctx: MCPServerOptions,+ ioOpts: ServeStdioOptions = {},+ runtimeOpts: MCPServerRuntimeOptions = {},+): Promise<number> {+ const server = new MCPServer(ctx, runtimeOpts);+ const stdin = ioOpts.stdin ?? process.stdin;+ const stdout = ioOpts.stdout ?? process.stdout;const rl = createInterface({ input: stdin, crlfDelay: Infinity });for await (const rawLine of rl) {@@ -68,10 +73,17 @@ function writeFrame(out: Writable, response: JsonRpcResponse): void {* Synchronous-style serveStdio fallback for embedded test harnesses that pass* an in-memory string buffer instead of a real stream. Tests use this to* bypass the readline async iteration.+ *+ * Returns newline-joined output (one JSON-RPC frame per line, trailing newline).*/-export async function serveStdioFromString(server: MCPServer, payload: string): Promise<string[]> {+export async function serveStdioFromString(+ ctx: MCPServerOptions,+ input: string,+ opts: MCPServerRuntimeOptions = {},+): Promise<string> {+ const server = new MCPServer(ctx, opts);const out: string[] = [];- for (const rawLine of payload.split("\n")) {+ for (const rawLine of input.split("\n")) {const line = rawLine.trim();if (!line) continue;let request: unknown;@@ -96,5 +108,5 @@ export async function serveStdioFromString(server: MCPServer, payload: string):const response = await server.handleRequest(request as Record<string, unknown>);if (response !== null) out.push(JSON.stringify(response));}- return out;+ return out.join("\n") + (out.length > 0 ? "\n" : "");}diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex c1058044..2e784ce1 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -605,8 +605,15 @@ function isDir(p: string): boolean {}}-export function buildToolTable(): ToolDefinition[] {- return [+export type ToolScope = "full" | "writer";++const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([+ "brain_feedback",+ "brain_apply_evidence",+]);++export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {+ const all: ToolDefinition[] = [{name: "second_brain_status",description: "Report Open Second Brain configuration and vault status.",@@ -854,6 +861,8 @@ export function buildToolTable(): ToolDefinition[] {handler: toolPaymentReportGenerate,},];+ if (scope === "full") return all;+ return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));}export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {diff --git a/tests/cli/brain-import-claude-memory.test.ts b/tests/cli/brain-import-claude-memory.test.tsnew file mode 100644index 00000000..0dfcd892--- /dev/null+++ b/tests/cli/brain-import-claude-memory.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { runCli } from "../helpers/run-cli.ts";++describe("o2b brain import-claude-memory CLI", () => {+ test("dry-run prints plan summary, exit 0, no writes", async () => {+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli-"));+ const vault = join(tmp, "vault");+ const config = join(tmp, "config.yaml");+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });+ await runCli(["brain", "init", "--vault", vault], { env });+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-cli-mem-"));+ writeFileSync(+ join(mem, "feedback_a.md"),+ "---\nname: a\ndescription: A.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = await runCli(+ [+ "brain", "import-claude-memory", "--vault", vault,+ "--memory", mem, "--dry-run", "--allow-arbitrary-memory-path",+ ],+ { env },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("plan:");+ expect(res.stdout).toContain("CREATE pref-a");+ expect(existsSync(join(vault, "Brain", "preferences", "pref-a.md"))).toBe(false);+ rmSync(tmp, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("--apply writes files and exits 0", async () => {+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli2-"));+ const vault = join(tmp, "vault");+ const config = join(tmp, "config.yaml");+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });+ await runCli(["brain", "init", "--vault", vault], { env });+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-cli2-mem-"));+ writeFileSync(+ join(mem, "feedback_a.md"),+ "---\nname: a\ndescription: A.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = await runCli(+ [+ "brain", "import-claude-memory", "--vault", vault,+ "--memory", mem, "--apply", "--yes", "--allow-arbitrary-memory-path",+ ],+ { env },+ );+ expect(res.returncode).toBe(0);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-a.md"))).toBe(true);+ rmSync(tmp, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("--apply + --dry-run is rejected", async () => {+ const res = await runCli([+ "brain", "import-claude-memory", "--vault", "/tmp", "--apply", "--dry-run",+ ]);+ expect(res.returncode).toBe(2);+ expect(res.stderr).toMatch(/--apply.*--dry-run|--dry-run.*--apply/);+ });+});diff --git a/tests/cli/discipline-install.test.ts b/tests/cli/discipline-install.test.tsnew file mode 100644index 00000000..5dc3902d--- /dev/null+++ b/tests/cli/discipline-install.test.ts@@ -0,0 +1,104 @@+/**+ * CLI tests for `o2b discipline install` / `o2b discipline uninstall` (Task 2.13).+ *+ * Sequence: install β install (idempotent) β uninstall β uninstall (no-op)+ * jobs.length transitions: 0 β 1 β 1 β 0 β 0+ *+ * OSB_HERMES_JOBS points at a tmp file so the user's real cron config+ * (/root/.hermes/cron/jobs.json) is never touched.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let jobsFile: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-discipline-install-test-"));+ vault = join(tmp, "vault");+ jobsFile = join(tmp, "jobs.json");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function readJobs(): { jobs: unknown[] } {+ try {+ return JSON.parse(readFileSync(jobsFile, "utf8"));+ } catch {+ return { jobs: [] };+ }+}++describe("o2b discipline install / uninstall", () => {+ test("install β idempotent install β uninstall β idempotent uninstall", async () => {+ const env = { OSB_HERMES_JOBS: jobsFile };++ // 1. Install β job created+ const r1 = await runCli(+ ["discipline", "install", "--vault", vault, "--telegram-target", "telegram:-100123:42"],+ { env },+ );+ expect(r1.returncode).toBe(0);+ expect(r1.stdout).toContain("created");+ expect(readJobs().jobs.length).toBe(1);++ // 2. Install again β idempotent, job count unchanged+ const r2 = await runCli(+ ["discipline", "install", "--vault", vault, "--telegram-target", "telegram:-100123:42"],+ { env },+ );+ expect(r2.returncode).toBe(0);+ expect(r2.stdout).toContain("updated");+ expect(readJobs().jobs.length).toBe(1);++ // 3. Uninstall β job removed+ const r3 = await runCli(+ ["discipline", "uninstall", "--vault", vault],+ { env },+ );+ expect(r3.returncode).toBe(0);+ expect(r3.stdout).toContain("removed");+ expect(readJobs().jobs.length).toBe(0);++ // 4. Uninstall again β no-op, exits 0+ const r4 = await runCli(+ ["discipline", "uninstall", "--vault", vault],+ { env },+ );+ expect(r4.returncode).toBe(0);+ expect(r4.stdout).toContain("no-op");+ expect(readJobs().jobs.length).toBe(0);+ });++ test("install without --vault exits 2 with error on stderr", async () => {+ const env = { OSB_HERMES_JOBS: jobsFile };+ const r = await runCli(["discipline", "install"], { env });+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--vault is required");+ });++ test("install without --telegram-target exits 2 (no private chat id baked in)", async () => {+ const env = { OSB_HERMES_JOBS: jobsFile };+ const r = await runCli(+ ["discipline", "install", "--vault", vault],+ { env },+ );+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--telegram-target is required");+ });++ test("uninstall without --vault exits 2 with error on stderr", async () => {+ const env = { OSB_HERMES_JOBS: jobsFile };+ const r = await runCli(["discipline", "uninstall"], { env });+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--vault is required");+ });+});diff --git a/tests/cli/discipline-report.test.ts b/tests/cli/discipline-report.test.tsnew file mode 100644index 00000000..edeb5b56--- /dev/null+++ b/tests/cli/discipline-report.test.ts@@ -0,0 +1,70 @@+/**+ * CLI tests for `o2b discipline report` (Task 2.12).+ *+ * Two cases per plan:+ * 1. Happy path β enabled config β exit 0, stdout contains "OSB discipline"+ * 2. Disabled config β enabled: false β exit 0, stderr contains "disabled"+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-discipline-cli-test-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b discipline report", () => {+ test("happy path: enabled config β exit 0, stdout contains 'OSB discipline'", async () => {+ // Use block-style empty sequences β the custom _brain.yaml parser does not+ // handle inline `[]`; it would fall through to a literal string, causing+ // the validator to silently drop the discipline_report section.+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ [+ "schema_version: 1",+ "discipline_report:",+ " enabled: true",+ " timezone: UTC",+ " watched_paths:",+ " known_agents:",+ ].join("\n") + "\n",+ "utf8",+ );++ const r = await runCli(["discipline", "report", "--vault", vault]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("OSB discipline");+ });++ test("disabled config β exit 0, stderr contains 'disabled'", async () => {+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ [+ "schema_version: 1",+ "discipline_report:",+ " enabled: false",+ " timezone: UTC",+ " watched_paths:",+ " known_agents:",+ ].join("\n") + "\n",+ "utf8",+ );++ const r = await runCli(["discipline", "report", "--vault", vault]);+ expect(r.returncode).toBe(0);+ expect(r.stderr).toContain("disabled");+ });+});diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.tsnew file mode 100644index 00000000..b09b19c7--- /dev/null+++ b/tests/cli/mcp-scope-arg.test.ts@@ -0,0 +1,48 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { runCli } from "../helpers/run-cli.ts";++describe("o2b mcp --scope arg validation", () => {+ test("invalid scope value exits 2 with a clear error", async () => {+ const res = await runCli(["mcp", "--scope", "nope"], { stdin: "" });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("--scope");+ expect(res.stderr).toMatch(/full.*writer|writer.*full/);+ });++ test("missing --scope value exits 2", async () => {+ const res = await runCli(["mcp", "--scope"], { stdin: "" });+ expect(res.returncode).toBe(2);+ });++ describe("--scope writer with a vault", () => {+ let tmp: string;+ beforeAll(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-scope-test-"));+ });+ afterAll(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ test("--scope writer starts the server and answers tools/list", async () => {+ const init = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const list = JSON.stringify({+ jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ });+ const res = await runCli(+ ["mcp", "--scope", "writer"],+ { stdin: `${init}\n${list}\n`, env: { VAULT_DIR: tmp } },+ );+ expect(res.returncode).toBe(0);+ const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l));+ const names = (lines[1].result.tools as Array<{ name: string }>)+ .map((t) => t.name).sort();+ expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });+ });+});diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.tsindex 3a2d29e1..858bbf25 100644--- a/tests/core/brain.types.test.ts+++ b/tests/core/brain.types.test.ts@@ -78,6 +78,8 @@ describe("BRAIN_* const enums", () => {"merge",// Β§22 upgrade (v0.10.6)"upgrade",+ // Β§3 import-claude-memory (agent-discipline-tail)+ "import-claude-memory",]);const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));expect(actual).toEqual(expected);diff --git a/tests/core/brain/claude-memory-manifest.test.ts b/tests/core/brain/claude-memory-manifest.test.tsnew file mode 100644index 00000000..8da71d32--- /dev/null+++ b/tests/core/brain/claude-memory-manifest.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ loadManifest, saveManifest, type ClaudeMemoryManifest,+} from "../../../src/core/brain/claude-memory-manifest.ts";++describe("claude-memory manifest", () => {+ test("missing file β empty manifest", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-m1-"));+ expect(loadManifest(v)).toEqual({ version: 1, imports: {} });+ rmSync(v, { recursive: true });+ });++ test("round-trip", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-m2-"));+ const m: ClaudeMemoryManifest = {+ version: 1,+ imports: {+ "no-em-dashes.md": {+ pref_id: "pref-no-em-dashes",+ sha256: "a".repeat(64),+ imported_at: "2026-05-18T10:00:00Z",+ },+ },+ };+ saveManifest(v, m);+ expect(loadManifest(v)).toEqual(m);+ rmSync(v, { recursive: true });+ });+});diff --git a/tests/core/brain/claude-memory-parser.test.ts b/tests/core/brain/claude-memory-parser.test.tsnew file mode 100644index 00000000..a6989e0f--- /dev/null+++ b/tests/core/brain/claude-memory-parser.test.ts@@ -0,0 +1,74 @@+import { describe, expect, test } from "bun:test";+import { parseClaudeMemoryFile } from "../../../src/core/brain/claude-memory-parser.ts";++const FEEDBACK_FIXTURE = `---+name: no-em-dashes+description: Forbidden to use em-dashes in Russian writing for this user; use regular hyphens.+metadata:+ node_type: memory+ type: feedback+ originSessionId: abc+---++Body text here.++**Why:** because the user said so.+**How to apply:** apply everywhere.+`;++const USER_FIXTURE = `---+name: who-am-i+description: User is a senior developer.+metadata:+ type: user+---++Body.+`;++describe("parseClaudeMemoryFile", () => {+ test("feedback entry β MemoryRecord", () => {+ const r = parseClaudeMemoryFile(FEEDBACK_FIXTURE);+ expect(r.kind).toBe("feedback");+ if (r.kind !== "feedback") throw new Error("expected feedback");+ expect(r.name).toBe("no-em-dashes");+ expect(r.description).toContain("Forbidden to use em-dashes");+ expect(r.body).toContain("**Why:**");+ expect(r.bodySha256).toMatch(/^[0-9a-f]{64}$/);+ });++ test("non-feedback entry β kind='skip', reason recorded", () => {+ const r = parseClaudeMemoryFile(USER_FIXTURE);+ expect(r.kind).toBe("skip");+ if (r.kind !== "skip") throw new Error("expected skip");+ expect(r.skipReason).toContain("type=user");+ });++ test("missing frontmatter β kind='skip'", () => {+ const r = parseClaudeMemoryFile("no frontmatter here");+ expect(r.kind).toBe("skip");+ if (r.kind !== "skip") throw new Error("expected skip");+ expect(r.skipReason).toContain("frontmatter");+ });++ // Real Claude Code memory entries written before the `metadata: { type+ // }` nesting convention store `type` at the top level instead. Both+ // shapes must parse identically β see v0.10.7 smoke test against+ // /root/.claude/projects/-root/memory where 12 of 17 files use the+ // older layout.+ test("top-level `type: feedback` (older Claude Memory shape) β feedback", () => {+ const fixture =+ "---\n" ++ "name: always-russian\n" ++ "description: Reply in Russian to this user always.\n" ++ "type: feedback\n" ++ "originSessionId: x\n" ++ "---\n\n" ++ "Body.\n";+ const r = parseClaudeMemoryFile(fixture);+ expect(r.kind).toBe("feedback");+ if (r.kind !== "feedback") throw new Error("expected feedback");+ expect(r.name).toBe("always-russian");+ expect(r.description).toContain("Reply in Russian");+ });+});diff --git a/tests/core/brain/claude-memory-paths.test.ts b/tests/core/brain/claude-memory-paths.test.tsnew file mode 100644index 00000000..7af58a3b--- /dev/null+++ b/tests/core/brain/claude-memory-paths.test.ts@@ -0,0 +1,16 @@+import { describe, expect, test } from "bun:test";+import { homedir } from "node:os";+import { join } from "node:path";+import { assertSafeMemoryPath } from "../../../src/core/brain/claude-memory-paths.ts";++describe("assertSafeMemoryPath", () => {+ test("default home β no throw", () => {+ assertSafeMemoryPath(join(homedir(), ".claude", "projects", "-x", "memory"), false);+ });+ test("system path without override β throws", () => {+ expect(() => assertSafeMemoryPath("/etc", false)).toThrow(/not under/);+ });+ test("system path with override β no throw", () => {+ assertSafeMemoryPath("/etc", true);+ });+});diff --git a/tests/core/brain/claude-memory-plan.test.ts b/tests/core/brain/claude-memory-plan.test.tsnew file mode 100644index 00000000..52264fc6--- /dev/null+++ b/tests/core/brain/claude-memory-plan.test.ts@@ -0,0 +1,29 @@+import { describe, expect, test } from "bun:test";+import { planAction } from "../../../src/core/brain/claude-memory-plan.ts";++describe("planAction", () => {+ const make = (overrides: Partial<Parameters<typeof planAction>[0]>) =>+ planAction({+ basename: "x.md", prefId: "pref-x", sha256: "h",+ inManifest: null, prefExists: false, ...overrides,+ });++ test("no manifest + no pref β CREATE", () => {+ expect(make({}).action).toBe("CREATE");+ });+ test("no manifest + pref exists β CONFLICT", () => {+ expect(make({ prefExists: true }).action).toBe("CONFLICT");+ });+ test("manifest matches + pref exists β SKIP_UNCHANGED", () => {+ expect(make({ inManifest: { sha256: "h" }, prefExists: true }).action).toBe("SKIP_UNCHANGED");+ });+ test("manifest matches + pref missing β RECREATE", () => {+ expect(make({ inManifest: { sha256: "h" }, prefExists: false }).action).toBe("RECREATE");+ });+ test("manifest differs + pref exists β UPDATE", () => {+ expect(make({ inManifest: { sha256: "old" }, prefExists: true }).action).toBe("UPDATE");+ });+ test("manifest differs + pref missing β CREATE (manifest stale)", () => {+ expect(make({ inManifest: { sha256: "old" }, prefExists: false }).action).toBe("CREATE");+ });+});diff --git a/tests/core/brain/claude-memory-render.test.ts b/tests/core/brain/claude-memory-render.test.tsnew file mode 100644index 00000000..287cafbd--- /dev/null+++ b/tests/core/brain/claude-memory-render.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from "bun:test";+import {+ renderPreferenceFromMemory,+ slugifyMemoryName,+} from "../../../src/core/brain/claude-memory-render.ts";++describe("renderPreferenceFromMemory", () => {+ test("emits frontmatter + body + Origin block", () => {+ const out = renderPreferenceFromMemory({+ name: "no-em-dashes",+ description: "No em-dashes in Russian writing for this user.",+ body: "Body text.\n\n**Why:** said so.\n**How to apply:** apply everywhere.",+ memoryPath: "/root/.claude/projects/-root/memory/feedback_no_em_dashes.md",+ importedAt: "2026-05-18T10:00:00Z",+ bodySha256: "a".repeat(64),+ });+ expect(out).toMatch(/^---\n/);+ expect(out).toContain("id: pref-no-em-dashes");+ expect(out).toContain("status: confirmed");+ expect(out).toContain("scope: writing");+ expect(out).toContain("confidence: high");+ expect(out).toContain("_force_confirmed_via: claude-memory");+ expect(out).toContain("_imported_from: \"/root/.claude/projects/-root/memory/feedback_no_em_dashes.md\"");+ expect(out).toContain("Body text.");+ expect(out).toContain("**Why:**");+ expect(out).toContain("## Origin");+ expect(out).toContain("on 2026-05-18.");+ });++ test("body scope marker overrides default writing scope", () => {+ const out = renderPreferenceFromMemory({+ name: "x", description: "x",+ body: "First line.\nscope: testing\nrest.",+ memoryPath: "/m.md", importedAt: "2026-05-18T10:00:00Z",+ bodySha256: "a".repeat(64),+ });+ expect(out).toContain("scope: testing");+ });+});++describe("slugifyMemoryName", () => {+ test("simple kebab name is unchanged", () => {+ expect(slugifyMemoryName("no-em-dashes")).toBe("no-em-dashes");+ });++ test("underscores β dashes", () => {+ expect(slugifyMemoryName("no_em_dashes")).toBe("no-em-dashes");+ });++ test("punctuation and spaces collapse to single dash", () => {+ expect(+ slugifyMemoryName("Phase-by-phase approval: don't conflate plan/code"),+ ).toBe("phase-by-phase-approval-don-t-conflate-plan-code");+ });++ test("em-dashes do not produce runs of dashes in the slug", () => {+ expect(+ slugifyMemoryName("Daily/ event log β append after every artifact"),+ ).toBe("daily-event-log-append-after-every-artifact");+ });++ test("leading and trailing dashes are trimmed", () => {+ expect(slugifyMemoryName(" hello ")).toBe("hello");+ expect(slugifyMemoryName("--hello--")).toBe("hello");+ });+});diff --git a/tests/core/brain/import-claude-memory-conflict.test.ts b/tests/core/brain/import-claude-memory-conflict.test.tsnew file mode 100644index 00000000..7f14cc5a--- /dev/null+++ b/tests/core/brain/import-claude-memory-conflict.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ ConflictsError,+ importClaudeMemory,+} from "../../../src/core/brain/import-claude-memory.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++describe("CONFLICT path", () => {+ test("apply throws ConflictsError when pref exists with no manifest entry", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-conf-"));+ bootstrapBrain(vault, { primaryAgent: "@t" });+ // Pre-create the preference by hand.+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-rule-c.md"),+ "---\nid: pref-rule-c\nkind: brain-preference\n---\n\nManual.\n",+ "utf8",+ );++ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-conf-mem-"));+ writeFileSync(+ join(mem, "feedback_rule_c.md"),+ "---\nname: rule-c\ndescription: From memory.\nmetadata:\n type: feedback\n---\n\nBody.\n",+ "utf8",+ );++ expect(() =>+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true }),+ ).toThrow(ConflictsError);++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("dry-run reports the conflict but does not throw", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-conf2-"));+ bootstrapBrain(vault, { primaryAgent: "@t" });+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-rule-c.md"),+ "---\nid: pref-rule-c\n---\n\n",+ "utf8",+ );+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-conf2-mem-"));+ writeFileSync(+ join(mem, "feedback_rule_c.md"),+ "---\nname: rule-c\ndescription: x.\nmetadata:\n type: feedback\n---\n\nb.\n",+ "utf8",+ );+ const res = importClaudeMemory({ vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true });+ expect(res.conflicts.length).toBe(1);+ expect(res.conflicts[0]?.prefId).toBe("pref-rule-c");++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+});diff --git a/tests/core/brain/import-claude-memory-orchestrator.test.ts b/tests/core/brain/import-claude-memory-orchestrator.test.tsnew file mode 100644index 00000000..ecce3100--- /dev/null+++ b/tests/core/brain/import-claude-memory-orchestrator.test.ts@@ -0,0 +1,82 @@+import { describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++function setupVault(): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-cm-orch-"));+ bootstrapBrain(v);+ return v;+}++function setupMemory(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-cm-mem-"));+ writeFileSync(+ join(dir, "feedback_a.md"),+ "---\nname: rule-a\ndescription: Rule A.\nmetadata:\n type: feedback\n---\n\nBody A.\n",+ "utf8",+ );+ writeFileSync(+ join(dir, "feedback_b.md"),+ "---\nname: rule-b\ndescription: Rule B.\nmetadata:\n type: feedback\n---\n\nBody B.\n",+ "utf8",+ );+ writeFileSync(+ join(dir, "user_who.md"),+ "---\nname: who\ndescription: User.\nmetadata:\n type: user\n---\n\nBody.\n",+ "utf8",+ );+ writeFileSync(join(dir, "MEMORY.md"), "# index\n- a\n", "utf8");+ return dir;+}++describe("importClaudeMemory", () => {+ test("dry-run reports plan, performs no writes", () => {+ const vault = setupVault();+ const mem = setupMemory();+ const res = importClaudeMemory({+ vault, memoryDir: mem, mode: "dry-run", allowArbitraryMemoryPath: true,+ });+ expect(res.plans.map((p) => p.action).sort()).toEqual(["CREATE", "CREATE"]);+ expect(res.skipped.length).toBe(1); // user_who.md; MEMORY.md is filtered earlier+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(false);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("apply writes preferences, manifest, and log event", () => {+ const vault = setupVault();+ const mem = setupMemory();+ const res = importClaudeMemory({+ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true,+ now: new Date("2026-05-18T10:00:00Z"),+ });+ expect(res.applied.length).toBe(2);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-a.md"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "preferences", "pref-rule-b.md"))).toBe(true);+ const manifest = JSON.parse(readFileSync(join(vault, "Brain", ".imports", "claude-memory.json"), "utf8"));+ expect(Object.keys(manifest.imports).sort()).toEqual(["feedback_a.md", "feedback_b.md"]);+ const log = readFileSync(join(vault, "Brain", "log", res.localDate + ".md"), "utf8");+ expect(log).toContain("import-claude-memory");+ expect(log).toContain("created: 2");+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });++ test("second apply with no change β SKIP_UNCHANGED, zero writes", () => {+ const vault = setupVault();+ const mem = setupMemory();+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });+ const before = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");+ const res2 = importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true });+ expect(res2.applied.length).toBe(0);+ expect(res2.skippedUnchanged.length).toBe(2);+ const after = readFileSync(join(vault, "Brain", "preferences", "pref-rule-a.md"), "utf8");+ expect(after).toBe(before);+ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+});diff --git a/tests/core/brain/import-claude-memory-preserve-evidence.test.ts b/tests/core/brain/import-claude-memory-preserve-evidence.test.tsnew file mode 100644index 00000000..f672e315--- /dev/null+++ b/tests/core/brain/import-claude-memory-preserve-evidence.test.ts@@ -0,0 +1,50 @@+import { describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++describe("UPDATE preserves accumulated evidence", () => {+ test("preserves _applied_count and _evidenced_by across re-import", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-cm-pres-"));+ bootstrapBrain(vault);+ const mem = mkdtempSync(join(tmpdir(), "o2b-cm-pres-mem-"));+ writeFileSync(+ join(mem, "feedback_x.md"),+ "---\nname: rule-x\ndescription: V1.\nmetadata:\n type: feedback\n---\n\nBody v1.\n",+ "utf8",+ );+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true, now: new Date("2026-05-19T10:00:00Z") });++ // Simulate accumulated evidence.+ const prefPath = join(vault, "Brain", "preferences", "pref-rule-x.md");+ let pref = readFileSync(prefPath, "utf8");+ pref = pref+ .replace("_applied_count: 0", "_applied_count: 7")+ .replace("_violated_count: 0", "_violated_count: 2")+ .replace("_evidenced_by: []", "_evidenced_by: ['[[a.md]]', '[[b.md]]']")+ .replace("pinned: false", "pinned: true");+ writeFileSync(prefPath, pref, "utf8");++ // Update memory body so sha256 changes β UPDATE branch.+ writeFileSync(+ join(mem, "feedback_x.md"),+ "---\nname: rule-x\ndescription: V2.\nmetadata:\n type: feedback\n---\n\nBody v2.\n",+ "utf8",+ );+ importClaudeMemory({ vault, memoryDir: mem, mode: "apply", allowArbitraryMemoryPath: true, now: new Date("2026-05-19T10:00:01Z") });++ const after = readFileSync(prefPath, "utf8");+ expect(after).toContain("_applied_count: 7");+ expect(after).toContain("_violated_count: 2");+ expect(after).toContain("_evidenced_by: ['[[a.md]]', '[[b.md]]']");+ expect(after).toContain("pinned: true");+ expect(after).toContain("principle: \"V2.\"");+ expect(after).toContain("Body v2.");++ rmSync(vault, { recursive: true });+ rmSync(mem, { recursive: true });+ });+});diff --git a/tests/core/brain/policy-discipline.test.ts b/tests/core/brain/policy-discipline.test.tsnew file mode 100644index 00000000..4f10a4e6--- /dev/null+++ b/tests/core/brain/policy-discipline.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { loadBrainConfig } from "../../../src/core/brain/policy.ts";++function vaultWith(yaml: string): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-policy-"));+ mkdirSync(join(v, "Brain"), { recursive: true });+ writeFileSync(join(v, "Brain", "_brain.yaml"), yaml, "utf8");+ return v;+}++describe("discipline_report config", () => {+ test("missing section β discipline_report undefined", () => {+ const v = vaultWith("schema_version: 1\n");+ const cfg = loadBrainConfig(v);+ expect(cfg.discipline_report).toBeUndefined();+ rmSync(v, { recursive: true });+ });++ test("populated section is parsed verbatim", () => {+ const v = vaultWith(+ "schema_version: 1\n" ++ "discipline_report:\n" ++ " enabled: true\n" ++ " timezone: Europe/Belgrade\n" ++ " watched_paths:\n" ++ " - /srv/projects/foo\n" ++ " known_agents:\n" ++ " - '@claude-vps-agent'\n",+ );+ const cfg = loadBrainConfig(v);+ expect(cfg.discipline_report).toEqual({+ enabled: true,+ timezone: "Europe/Belgrade",+ watched_paths: ["/srv/projects/foo"],+ known_agents: ["@claude-vps-agent"],+ });+ rmSync(v, { recursive: true });+ });+});diff --git a/tests/core/brain/types-import-claude-memory.test.ts b/tests/core/brain/types-import-claude-memory.test.tsnew file mode 100644index 00000000..b01a2c3b--- /dev/null+++ b/tests/core/brain/types-import-claude-memory.test.ts@@ -0,0 +1,8 @@+import { describe, expect, test } from "bun:test";+import { BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";++describe("import-claude-memory log kind", () => {+ test("kind is registered as 'import-claude-memory'", () => {+ expect(BRAIN_LOG_EVENT_KIND.importClaudeMemory).toBe("import-claude-memory");+ });+});diff --git a/tests/discipline/activity-git.test.ts b/tests/discipline/activity-git.test.tsnew file mode 100644index 00000000..5b378b89--- /dev/null+++ b/tests/discipline/activity-git.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test, beforeAll, afterAll } from "bun:test";+import { execSync } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { gitActivity } from "../../src/core/discipline/activity-git.ts";++let repo: string;++beforeAll(() => {+ repo = mkdtempSync(join(tmpdir(), "o2b-disc-git-"));+ execSync("git init -q -b main", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ writeFileSync(join(repo, "a.txt"), "hello\n");+ execSync("git add a.txt && git commit -q -m c1 --date=2026-05-17T10:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z" } });+ writeFileSync(join(repo, "a.txt"), "hello\nworld\n");+ execSync("git add a.txt && git commit -q -m c2 --date=2026-05-17T20:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T20:00:00Z" } });+ writeFileSync(join(repo, "b.txt"), "x\n");+ execSync("git add b.txt && git commit -q -m c3 --date=2026-05-18T10:00:00Z",+ { cwd: repo, env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-18T10:00:00Z" } });+});+afterAll(() => rmSync(repo, { recursive: true, force: true }));++describe("gitActivity", () => {+ test("counts only commits inside the [start, end) UTC window", () => {+ const out = gitActivity(repo, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out?.commits).toBe(2);+ expect(out?.filesChanged).toBe(1);+ expect(out?.insertions).toBe(2); // 1 + 1+ expect(out?.deletions).toBe(0);+ });++ test("non-git path β null sentinel, no throw", () => {+ const empty = mkdtempSync(join(tmpdir(), "o2b-disc-nogit-"));+ const out = gitActivity(empty, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out).toBeNull();+ rmSync(empty, { recursive: true });+ });+});diff --git a/tests/discipline/activity-mtime.test.ts b/tests/discipline/activity-mtime.test.tsnew file mode 100644index 00000000..4101d062--- /dev/null+++ b/tests/discipline/activity-mtime.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from "bun:test";+import {+ mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { mtimeActivity } from "../../src/core/discipline/activity-mtime.ts";++function touch(path: string, isoUtc: string): void {+ const ts = new Date(isoUtc).getTime() / 1000;+ utimesSync(path, ts, ts);+}++describe("mtimeActivity", () => {+ test("counts files mtime'd inside the window; excludes noise dirs", () => {+ const root = mkdtempSync(join(tmpdir(), "o2b-disc-mtime-"));+ writeFileSync(join(root, "in1.txt"), "x");+ touch(join(root, "in1.txt"), "2026-05-17T10:00:00Z");+ writeFileSync(join(root, "in2.md"), "x");+ touch(join(root, "in2.md"), "2026-05-17T20:00:00Z");+ writeFileSync(join(root, "out.txt"), "x");+ touch(join(root, "out.txt"), "2026-05-18T10:00:00Z");+ mkdirSync(join(root, "node_modules"), { recursive: true });+ writeFileSync(join(root, "node_modules", "noise.js"), "x");+ touch(join(root, "node_modules", "noise.js"), "2026-05-17T15:00:00Z");+ mkdirSync(join(root, "subdir"));+ writeFileSync(join(root, "subdir", "in3.md"), "x");+ touch(join(root, "subdir", "in3.md"), "2026-05-17T15:00:00Z");++ const out = mtimeActivity(root, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out.modifiedFiles).toBe(3);+ rmSync(root, { recursive: true });+ });+});diff --git a/tests/discipline/decision.test.ts b/tests/discipline/decision.test.tsnew file mode 100644index 00000000..6564fd4c--- /dev/null+++ b/tests/discipline/decision.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from "bun:test";+import { decideStatus } from "../../src/core/discipline/decision.ts";++describe("decideStatus", () => {+ const noEvents = { byAgent: {}, unknownAgents: [], total: 0 } as any;+ const someTasteEvents = {+ byAgent: {+ "@a": { feedback: 2, apply_evidence: 3, other: 0, total: 5 },+ },+ unknownAgents: [],+ total: 5,+ } as any;+ const onlyOtherEvents = {+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, other: 4, total: 4 },+ },+ unknownAgents: [],+ total: 4,+ } as any;+ const noActivity = {+ repo: [], nonRepo: [], vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ } as any;+ const someRepoActivity = {+ ...noActivity, repo: [{ path: "/a", git: { commits: 2, filesChanged: 1, insertions: 1, deletions: 0 } }],+ };+ const someMtimeActivity = {+ ...noActivity, nonRepo: [{ path: "/b", modifiedFiles: 5 }],+ };+ const someVaultDelta = {+ ...noActivity, vaultDelta: { newSignals: 0, newPreferences: 1, newRetired: 0, total: 1 },+ };++ test("0 events + 0 activity β info", () => {+ expect(decideStatus(noEvents, noActivity)).toBe("info");+ });+ test("0 events + repo activity β alert", () => {+ expect(decideStatus(noEvents, someRepoActivity)).toBe("alert");+ });+ test("0 events + mtime activity (>=3) β alert", () => {+ expect(decideStatus(noEvents, someMtimeActivity)).toBe("alert");+ });+ test("0 events + mtime activity (<3) β info", () => {+ const low = { ...noActivity, nonRepo: [{ path: "/b", modifiedFiles: 2 }] };+ expect(decideStatus(noEvents, low)).toBe("info");+ });+ test("0 events + vault delta β alert", () => {+ expect(decideStatus(noEvents, someVaultDelta)).toBe("alert");+ });+ test("taste events present (feedback or apply_evidence) β ok regardless of activity", () => {+ expect(decideStatus(someTasteEvents, noActivity)).toBe("ok");+ expect(decideStatus(someTasteEvents, someRepoActivity)).toBe("ok");+ });++ test("only `other` events (snapshot/dream/import) do NOT count as taste β alert if activity", () => {+ // This is the regression catch: a snapshot or import-claude-memory+ // event on a busy code day previously suppressed the alert.+ expect(decideStatus(onlyOtherEvents, someRepoActivity)).toBe("alert");+ expect(decideStatus(onlyOtherEvents, noActivity)).toBe("info");+ });+});diff --git a/tests/discipline/log-counts.test.ts b/tests/discipline/log-counts.test.tsnew file mode 100644index 00000000..0c632096--- /dev/null+++ b/tests/discipline/log-counts.test.ts@@ -0,0 +1,74 @@+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { countBrainEvents } from "../../src/core/discipline/log-counts.ts";++function vaultWithLog(dayBody: string): string {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-log-"));+ const dir = join(v, "Brain", "log");+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "2026-05-17.md"),+ "---\nkind: brain-log\ndate: 2026-05-17\ntags: [brain]\n---\n\n" + dayBody,+ "utf8",+ );+ return v;+}++describe("countBrainEvents", () => {+ test("buckets by kind per agent and ignores no-agent blocks", () => {+ const body =+ "## 08:00:00Z β feedback\n- agent: @claude-vps-agent\n- topic: foo\n\n" ++ "## 09:00:00Z β apply-evidence\n- agent: @claude-vps-agent\n- pref_id: pref-x\n\n" ++ "## 10:00:00Z β feedback\n- agent: @codex-vps-agent\n- topic: bar\n\n" ++ "## 11:00:00Z β promote\n- agent: @claude-vps-agent\n- promoted: 0\n\n" ++ "## 12:00:00Z β snapshot\n- run_id: x\n";+ const v = vaultWithLog(body);+ const out = countBrainEvents(v, "2026-05-17", [+ "@claude-vps-agent",+ "@codex-vps-agent",+ ]);+ expect(out.byAgent["@claude-vps-agent"]).toEqual({+ feedback: 1,+ apply_evidence: 1,+ other: 1,+ total: 3,+ });+ expect(out.byAgent["@codex-vps-agent"]).toEqual({+ feedback: 1,+ apply_evidence: 0,+ other: 0,+ total: 1,+ });+ expect(out.total).toBe(4);+ expect(out.unknownAgents).toEqual([]);+ rmSync(v, { recursive: true });+ });++ test("agent missing from known_agents shows under unknownAgents", () => {+ const body =+ "## 08:00:00Z β feedback\n- agent: @stranger\n- topic: foo\n\n";+ const v = vaultWithLog(body);+ const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent"]);+ expect(out.byAgent["@claude-vps-agent"]).toEqual({+ feedback: 0,+ apply_evidence: 0,+ other: 0,+ total: 0,+ });+ expect(out.unknownAgents).toEqual([+ { agent: "@stranger", counts: { feedback: 1, apply_evidence: 0, other: 0, total: 1 } },+ ]);+ rmSync(v, { recursive: true });+ });++ test("missing log file β all zeros, no error", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-log-empty-"));+ const out = countBrainEvents(v, "2026-05-17", ["@claude-vps-agent"]);+ expect(out.total).toBe(0);+ expect(out.byAgent["@claude-vps-agent"]!.total).toBe(0);+ rmSync(v, { recursive: true });+ });+});diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.tsnew file mode 100644index 00000000..29751cce--- /dev/null+++ b/tests/discipline/render.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from "bun:test";+import { renderReport } from "../../src/core/discipline/render.ts";++describe("renderReport", () => {+ test("status: ok with two agents, one repo, vault delta", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "Europe/Belgrade",+ status: "ok",+ events: {+ byAgent: {+ "@claude-vps-agent": { feedback: 2, apply_evidence: 3, other: 0, total: 5 },+ "@codex-vps-agent": { feedback: 0, apply_evidence: 0, other: 0, total: 0 },+ },+ unknownAgents: [],+ total: 5,+ },+ activity: {+ repo: [{ path: "/srv/projects/foo", git: { commits: 4, filesChanged: 27, insertions: 312, deletions: 148 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 1, newPreferences: 0, newRetired: 0, total: 1 },+ },+ });+ expect(text).toContain("OSB discipline");+ expect(text).toContain("2026\\-05\\-17");+ expect(text).toContain("Europe/Belgrade");+ expect(text).toContain("Status: ok");+ expect(text).toContain("@claude\\-vps\\-agent");+ expect(text).toContain("2 feedback, 3 apply\\-evidence, 0 other \\(total 5\\)");+ expect(text).toContain("/srv/projects/foo");+ expect(text).toContain("4 commits");+ expect(text).toContain("vault");+ expect(text).not.toContain("Activity ratio");+ });++ test("status: alert appends the explanatory line", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: { byAgent: { "@a": { feedback: 0, apply_evidence: 0, other: 0, total: 0 } }, unknownAgents: [], total: 0 },+ activity: {+ repo: [{ path: "/x", git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 } }],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ },+ });+ expect(text).toContain("Status: alert");+ expect(text).toContain("zero brain events");+ });+});diff --git a/tests/discipline/report.test.ts b/tests/discipline/report.test.tsnew file mode 100644index 00000000..c5f967ec--- /dev/null+++ b/tests/discipline/report.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from "bun:test";+import { execSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runDisciplineReport } from "../../src/core/discipline/report.ts";++describe("runDisciplineReport", () => {+ test("end-to-end: empty log + active repo β alert text emitted", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-e2e-vault-"));+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n" ++ " enabled: true\n timezone: UTC\n" ++ " watched_paths:\n - " + vault + "/repo\n" ++ " known_agents:\n - '@claude-vps-agent'\n",+ "utf8",+ );++ const repo = join(vault, "repo");+ mkdirSync(repo);+ execSync("git init -q -b main", { cwd: repo });+ execSync("git config user.email t@t && git config user.name t", { cwd: repo });+ writeFileSync(join(repo, "a.txt"), "hi\n");+ execSync("git add . && git commit -q -m c1", {+ cwd: repo,+ env: { ...process.env, GIT_COMMITTER_DATE: "2026-05-17T10:00:00Z", GIT_AUTHOR_DATE: "2026-05-17T10:00:00Z" },+ });++ const res = runDisciplineReport({+ vault,+ now: new Date("2026-05-18T01:00:00Z"),+ });+ expect(res.status).toBe("alert");+ expect(res.text).toContain("Status: alert");+ expect(res.text).toContain("1 commits");+ rmSync(vault, { recursive: true });+ });++ test("disabled config β result.status='disabled', empty text", () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-disc-dis-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\ndiscipline_report:\n enabled: false\n timezone: UTC\n watched_paths: []\n known_agents: []\n",+ "utf8",+ );+ const res = runDisciplineReport({ vault, now: new Date() });+ expect(res.status).toBe("disabled");+ expect(res.text).toBe("");+ rmSync(vault, { recursive: true });+ });+});diff --git a/tests/discipline/telegram.test.ts b/tests/discipline/telegram.test.tsnew file mode 100644index 00000000..f35b052b--- /dev/null+++ b/tests/discipline/telegram.test.ts@@ -0,0 +1,17 @@+import { describe, expect, test } from "bun:test";+import { escapeMarkdownV2 } from "../../src/core/discipline/telegram.ts";++describe("escapeMarkdownV2", () => {+ test("escapes the 16 reserved characters", () => {+ const input = "_*[]()~`>#+-=|{}.!\\";+ const out = escapeMarkdownV2(input);+ // Each reserved char becomes \X.+ expect(out).toBe("\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\-\\=\\|\\{\\}\\.\\!\\\\");+ });+ test("leaves regular text untouched", () => {+ expect(escapeMarkdownV2("hello world 123")).toBe("hello world 123");+ });+ test("escapes a realistic agent identifier", () => {+ expect(escapeMarkdownV2("@claude-vps-agent")).toBe("@claude\\-vps\\-agent");+ });+});diff --git a/tests/discipline/vault-delta.test.ts b/tests/discipline/vault-delta.test.tsnew file mode 100644index 00000000..7f1dd507--- /dev/null+++ b/tests/discipline/vault-delta.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { vaultDelta } from "../../src/core/discipline/vault-delta.ts";++function touch(path: string, iso: string): void {+ const t = new Date(iso).getTime() / 1000;+ utimesSync(path, t, t);+}++describe("vaultDelta", () => {+ test("counts signal / preference / retired files inside window", () => {+ const v = mkdtempSync(join(tmpdir(), "o2b-disc-delta-"));+ mkdirSync(join(v, "Brain", "inbox"), { recursive: true });+ mkdirSync(join(v, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(v, "Brain", "retired"), { recursive: true });+ writeFileSync(join(v, "Brain", "inbox", "sig-1.md"), "x");+ touch(join(v, "Brain", "inbox", "sig-1.md"), "2026-05-17T12:00:00Z");+ writeFileSync(join(v, "Brain", "inbox", "sig-2.md"), "x");+ touch(join(v, "Brain", "inbox", "sig-2.md"), "2026-05-17T13:00:00Z");+ writeFileSync(join(v, "Brain", "preferences", "pref-x.md"), "x");+ touch(join(v, "Brain", "preferences", "pref-x.md"), "2026-05-17T18:00:00Z");+ writeFileSync(join(v, "Brain", "retired", "pref-y.md"), "x");+ touch(join(v, "Brain", "retired", "pref-y.md"), "2026-05-16T10:00:00Z");++ const out = vaultDelta(v, {+ startUtc: new Date("2026-05-17T00:00:00Z"),+ endUtc: new Date("2026-05-18T00:00:00Z"),+ });+ expect(out.newSignals).toBe(2);+ expect(out.newPreferences).toBe(1);+ expect(out.newRetired).toBe(0);+ expect(out.total).toBe(3);+ rmSync(v, { recursive: true });+ });+});diff --git a/tests/discipline/window.test.ts b/tests/discipline/window.test.tsnew file mode 100644index 00000000..de0472ab--- /dev/null+++ b/tests/discipline/window.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from "bun:test";+import { yesterdayWindow } from "../../src/core/discipline/window.ts";++describe("yesterdayWindow", () => {+ test("Europe/Belgrade at 06:00 local β window covers prior local day", () => {+ // 2026-05-18T06:00:00 in Belgrade = 2026-05-18T04:00:00Z (CEST UTC+2).+ const now = new Date("2026-05-18T04:00:00Z");+ const w = yesterdayWindow(now, "Europe/Belgrade");+ expect(w.localDate).toBe("2026-05-17");+ // Window starts at 2026-05-17T00:00:00 local = 2026-05-16T22:00:00Z.+ expect(w.startUtc.toISOString()).toBe("2026-05-16T22:00:00.000Z");+ expect(w.endUtc.toISOString()).toBe("2026-05-17T22:00:00.000Z");+ });++ test("UTC timezone β naive 24h window", () => {+ const now = new Date("2026-05-18T03:00:00Z");+ const w = yesterdayWindow(now, "UTC");+ expect(w.localDate).toBe("2026-05-17");+ expect(w.startUtc.toISOString()).toBe("2026-05-17T00:00:00.000Z");+ expect(w.endUtc.toISOString()).toBe("2026-05-18T00:00:00.000Z");+ });++ // Regression for the CodeRabbit-flagged west-of-UTC bug: without the+ // day-delta correction in localMidnightUtc, this case settled on a+ // 24h-early instant ("2026-05-15T07:00:00Z" instead of+ // "2026-05-16T07:00:00Z"). Verifies the loop now adjusts for whole-day+ // drift as well as time-of-day drift.+ test("America/Los_Angeles (west-of-UTC) at 10:00 local β prior local day", () => {+ // 2026-05-18T10:00:00 PDT (UTC-7) = 2026-05-18T17:00:00Z.+ const now = new Date("2026-05-18T17:00:00Z");+ const w = yesterdayWindow(now, "America/Los_Angeles");+ expect(w.localDate).toBe("2026-05-17");+ // Yesterday-local midnight in LA = 2026-05-17T07:00:00Z.+ // Today-local midnight in LA = 2026-05-18T07:00:00Z.+ expect(w.startUtc.toISOString()).toBe("2026-05-17T07:00:00.000Z");+ expect(w.endUtc.toISOString()).toBe("2026-05-18T07:00:00.000Z");+ });+});diff --git a/tests/mcp/mcp-json.test.ts b/tests/mcp/mcp-json.test.tsnew file mode 100644index 00000000..4370bd22--- /dev/null+++ b/tests/mcp/mcp-json.test.ts@@ -0,0 +1,29 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, test } from "bun:test";++// Resolve relative to this test file so the suite runs from any checkout+// path (CI / contributor clones / worktrees) β not just `/srv/projects/...`.+const HERE = dirname(fileURLToPath(import.meta.url));+const MCP_JSON_PATH = resolve(HERE, "..", "..", ".mcp.json");++describe(".mcp.json shipped with the plugin", () => {+ const file = JSON.parse(readFileSync(MCP_JSON_PATH, "utf8"));+ test("declares both open-second-brain and -writer entries", () => {+ expect(Object.keys(file.mcpServers).sort()).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ });+ test("writer entry passes --scope writer and alwaysLoad: true", () => {+ const w = file.mcpServers["open-second-brain-writer"];+ expect(w.command).toBe("${CLAUDE_PLUGIN_ROOT}/scripts/o2b");+ expect(w.args).toEqual(["mcp", "--scope", "writer"]);+ expect(w.alwaysLoad).toBe(true);+ });+ test("full server has no alwaysLoad flag", () => {+ const f = file.mcpServers["open-second-brain"];+ expect(f.alwaysLoad).toBeUndefined();+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex f7a38431..9aedf9cf 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -265,7 +265,6 @@ describe("tool calls", () => {describe("stdio loop", () => {test("processes initialize and tools/list", async () => {- const server = new MCPServer({ vault: tmp });const payload =[JSON.stringify({@@ -281,7 +280,8 @@ describe("stdio loop", () => {JSON.stringify({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" }),JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: 2, method: "tools/list" }),].join("\n") + "\n";- const lines = await serveStdioFromString(server, payload);+ const out = await serveStdioFromString({ vault: tmp }, payload);+ const lines = out.trim().split("\n");expect(lines.length).toBe(2);const init = JSON.parse(lines[0]!);const list = JSON.parse(lines[1]!);@@ -292,21 +292,76 @@ describe("stdio loop", () => {});test("returns parse error for invalid JSON", async () => {- const server = new MCPServer({ vault: tmp });- const lines = await serveStdioFromString(server, "{not json}\n");- const r = JSON.parse(lines[0]!);+ const out = await serveStdioFromString({ vault: tmp }, "{not json}\n");+ const r = JSON.parse(out.trim());expect(r.error.code).toBe(-32700);});test("returns invalid request for batch", async () => {- const server = new MCPServer({ vault: tmp });const batch = JSON.stringify([{ jsonrpc: JSONRPC_VERSION, id: 1, method: "ping" },{ jsonrpc: JSONRPC_VERSION, id: 2, method: "ping" },]);- const lines = await serveStdioFromString(server, batch + "\n");- const r = JSON.parse(lines[0]!);+ const out = await serveStdioFromString({ vault: tmp }, batch + "\n");+ const r = JSON.parse(out.trim());expect(r.error.code).toBe(-32600);expect(r.error.message.toLowerCase()).toContain("batch");});});++describe("MCPServer serverName override", () => {+ test("default ctor uses SERVER_NAME constant", async () => {+ const server = new MCPServer({ vault: tmp });+ const r = (await initialize(server))! as any;+ expect(r.result.serverInfo.name).toBe("open-second-brain");+ });++ test("explicit serverName flows into initialize response", async () => {+ const server = new MCPServer(+ { vault: tmp, configPath: null, repoRoot: null },+ { serverName: "open-second-brain-writer" },+ );+ const r = (await initialize(server))! as any;+ expect(r.result.serverInfo.name).toBe("open-second-brain-writer");+ });+});++describe("serveStdioFromString respects scope+name", () => {+ test("writer scope filters tools/list response", async () => {+ const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };+ const initReq = JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const listReq = JSON.stringify({+ jsonrpc: "2.0", id: 2, method: "tools/list", params: {},+ });+ const out = await serveStdioFromString(+ ctx,+ `${initReq}\n${listReq}\n`,+ { scope: "writer", serverName: "open-second-brain-writer" },+ );+ const lines = out.trim().split("\n").map((l) => JSON.parse(l));+ expect(lines[0].result.serverInfo.name).toBe("open-second-brain-writer");+ const toolNames = (lines[1].result.tools as Array<{ name: string }>)+ .map((t) => t.name).sort();+ expect(toolNames).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });+});++import { buildInstructions } from "../../src/mcp/instructions.ts";++describe("buildInstructions writer mode", () => {+ test("writer instructions name both tools and point at the full server", () => {+ const text = buildInstructions({+ vault: "/tmp/x",+ agent: "@agent",+ scope: "writer",+ });+ expect(text).toContain("brain_feedback");+ expect(text).toContain("brain_apply_evidence");+ expect(text).toContain("open-second-brain"); // points at sibling server+ expect(text).not.toMatch(/payment_/i);+ expect(text).not.toMatch(/brain_dream/);+ });+});diff --git a/tests/mcp/scope-filter.test.ts b/tests/mcp/scope-filter.test.tsnew file mode 100644index 00000000..19b87862--- /dev/null+++ b/tests/mcp/scope-filter.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from "bun:test";+import { buildToolTable } from "../../src/mcp/tools.ts";++describe("buildToolTable scope filter", () => {+ test("default scope returns the full surface", () => {+ const full = buildToolTable();+ const names = full.map((t) => t.name);+ expect(names).toContain("brain_feedback");+ expect(names).toContain("brain_apply_evidence");+ expect(names).toContain("brain_dream");+ expect(names).toContain("payment_memory_init");+ expect(names).toContain("vault_health");+ expect(full.length).toBeGreaterThanOrEqual(15);+ });++ test("writer scope returns exactly the two writer tools", () => {+ const writer = buildToolTable("writer");+ const names = writer.map((t) => t.name).sort();+ expect(names).toEqual(["brain_apply_evidence", "brain_feedback"]);+ });++ test("writer-scope schemas are the same instances as full scope", () => {+ const full = buildToolTable("full");+ const writer = buildToolTable("writer");+ for (const w of writer) {+ const matched = full.find((t) => t.name === w.name);+ expect(matched).toBeDefined();+ // toBe asserts identity β writer scope filters from the same array,+ // so each retained ToolDefinition's schema/description must be the+ // same object instance. toEqual would silently allow accidental+ // cloning.+ expect(w.inputSchema).toBe(matched!.inputSchema);+ expect(w.description).toBe(matched!.description);+ }+ });+});