Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: v0.10.12 operational friction reduction (#27)

Sol Aitken0462b918f91d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 2d1abf34..bf1ecf1b 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.11",
+ "version": "0.10.12",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 30003129..3085ac75 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.11",
+ "version": "0.10.12",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 816e13a0..b3f60230 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,41 @@ 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.12] - 2026-05-20
+
+Operational friction reduction: one-command update across all
+runtimes, weekly brain digest with agent quality summary, Cursor
+SQLite deep parsing for accurate transcript activity, and Obsidian
+deep-links in the live explorer. Companion design and impl plan at
+`docs/superpowers/specs/2026-05-20-v0.10.12-design.md` and
+`docs/plans/2026-05-20-v0.10.12-impl.md`.
+
+### Added
+
+- `o2b update` β€” one-command update across all detected runtimes.
+ Skips unchanged payloads via sidecar hash comparison. Supports
+ `--target`, `--dry-run`, `--force`, `--json`. Post-update verify
+ with drift detection.
+- `o2b brain digest --window 7d` β€” arbitrary time windows for the
+ digest. Accepts `Nd` or bare `N` format (e.g. `7d`, `14`, `30d`).
+- Agent quality summary in digest β€” per-agent event counts, type
+ breakdown (feedback / apply-evidence / note), and confirmed/retired
+ attribution within the window.
+- `o2b discipline install --weekly` β€” installs a weekly brain digest
+ cron job (`osb-weekly-brain-digest`) defaulting to Monday 08:59 UTC.
+ Uses `scripts/discipline-report.ts --window 7d`.
+- Cursor SQLite deep parsing β€” discipline report reads `state.vscdb`
+ for session count + message count, eliminating mtime false-positives.
+ Falls back gracefully on any SQLite error.
+- Obsidian deep-link in explorer β€” double-click a node in live mode
+ to open the file in Obsidian via `obsidian://open?path=<absolute>`.
+ Fallback copies path to clipboard.
+
+### Changed
+
+- `scripts/discipline-report.ts` now accepts `--window Nd` for
+ digest mode, falling back to daily discipline report otherwise.
+
## [0.10.11] - 2026-05-20
Multi-runtime install orchestrator plus a configurable
diff --git a/README.md b/README.md
index 954adc66..0aa10828 100644
--- a/README.md
+++ b/README.md
@@ -125,6 +125,7 @@ o2b export-config Write a redacted config snapshot
o2b mcp Run the MCP tool server (stdio)
o2b tool-call Invoke an MCP tool handler from the CLI
o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks
+o2b update Update OSB installation across all detected runtimes; --target <name> / --dry-run / --force / --json
# Brain (observing memory)
o2b brain init Bootstrap Brain/{inbox,preferences,retired,log,.snapshots}/ + _brain.yaml + _BRAIN.md; --starter drops the bundled example set
@@ -132,7 +133,7 @@ o2b brain feedback Record one taste signal (--topic, --signal, --prin
o2b brain dream Run the deterministic consolidation pass (idempotent; usually cron'd)
o2b brain apply-evidence Record applied / violated against a preference for a durable artifact
o2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)
-o2b brain digest Render a Markdown or JSON summary of recent Brain transitions
+o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookback
o2b brain query Read helper: by preference, by topic, or by log timestamp
o2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.
o2b brain merge (CLI-only) Fold one confirmed/quarantine pref into another (<keep> <drop>); --dry-run / --force; drop retires with reason 'merged-into'
@@ -144,7 +145,7 @@ o2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, o
o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot (--dry-run previews; drift abort vs --force-rollback)
o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes
o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])
-o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence.
+o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode).
o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, …)
o2b brain backlinks List inbound references to a Brain artifact id
o2b brain scan-inline Capture `@osb` markers from vault markdown files (Daily/, project notes, …)
@@ -158,8 +159,8 @@ o2b vault inspect <relpath> Point-check one vault-relative path; reports match
# 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
+o2b discipline install Register the Hermes cron job that delivers the report. --telegram-target is required; --at defaults to "59 4 * * *" UTC; --weekly installs a Monday 08:59 weekly digest
+o2b discipline uninstall Remove the cron job; --weekly removes only the weekly digest, without flag removes both
# Pay Memory
o2b init-pay-memory Bootstrap AI Wiki/{policies,payments,assets,drafts,reports}/
@@ -512,8 +513,10 @@ GNOME Keyring, Windows Hello, 1Password) is configured by
## Updating
-Each runtime's CLI is authoritative for refreshing the plugin β€”
-follow the matching `## 7. Update` section in `install.md`:
+The quickest path is `o2b update` β€” it detects all installed runtimes,
+skips unchanged payloads, applies updates sequentially, and verifies
+afterwards. For manual per-runtime updates, follow the matching
+`## 7. Update` section in `install.md`:
- Hermes: `hermes plugins update open-second-brain && hermes gateway restart`
- Claude Code: `claude plugin marketplace update open-second-brain && claude plugin update open-second-brain@open-second-brain`
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 80b4a0d1..85e0e036 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -364,7 +364,7 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| Record application | `o2b brain apply-evidence` | `brain_apply_evidence`| appends log event; `result ∈ {applied, violated, outdated}`; artifact supports `[[file:120-145]]` ranges |
| Record milestone | `o2b brain note <text>` | `brain_note` | appends one `note` log event to `Brain/log/<today>.md` plus the JSONL sidecar. Multi-line collapses to one line. CLI mirror exists for cron / shell. |
| Pull active context | β€” (use MCP) | `brain_context` | read-only; returns `Brain/active.md` body + counts. Always-loaded on the writer MCP server so runtimes without a `SessionStart` hook (Cursor, Aider, raw Claude API) can fetch it at session start. |
-| Render summary | `o2b brain digest` | `brain_digest` | read-only; includes `top_applied` and `top_referenced` sections |
+| Render summary | `o2b brain digest [--window Nd]` | `brain_digest` | read-only; includes `top_applied`, `top_referenced`, and `agent_summary` sections |
| Inspect state | `o2b brain query` | `brain_query` | read-only |
| Computed backlinks | `o2b brain backlinks <id>` | `brain_backlinks` | read-only; inverted reference map across `preferences/`, `retired/`, `log/` |
| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; six lint rules |
@@ -381,7 +381,7 @@ are mirrored in MCP; destructive operations are CLI-only by design.
| 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. |
+| 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; `--weekly` installs a Monday digest; `uninstall --weekly` removes only the weekly job). 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-20-v0.10.12-impl.md b/docs/plans/2026-05-20-v0.10.12-impl.md
new file mode 100644
index 00000000..e7e0403c
--- /dev/null
+++ b/docs/plans/2026-05-20-v0.10.12-impl.md
@@ -0,0 +1,1778 @@
+# v0.10.12 β€” Operational Friction Reduction Implementation Plan
+
+> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
+
+**Goal:** Four features reducing daily OSB operational friction: `o2b update`, weekly brain digest, Cursor SQLite deep parsing, Obsidian deep-link in explorer.
+
+**Architecture:** All features extend existing modules β€” InstallAdapter registry, brain_digest windowed mode, discipline-report transcript resolvers, brain-explorer HTML template. No new architectural layers.
+
+**Tech Stack:** Bun, TypeScript, bun:sqlite, proper-lockfile
+
+---
+
+### Task 1: Parse `--window` flag for `brain_digest`
+
+**Objective:** Add `parseWindow` utility that accepts `Nd` or bare `N` format.
+
+**Files:**
+- Modify: `src/cli/brain/verbs/digest.ts`
+- Test: `tests/cli/brain-digest-window-cli.test.ts`
+
+**Step 1: Write failing test**
+
+Create `tests/cli/brain-digest-window-cli.test.ts`:
+
+```typescript
+import { describe, expect, test } from "bun:test";
+import { parseWindow } from "../../../src/cli/brain/verbs/digest.ts";
+
+describe("parseWindow", () => {
+ test("parses '7d' as 7 days", () => {
+ expect(parseWindow("7d")).toBe(7);
+ });
+
+ test("parses bare '7' as 7 days", () => {
+ expect(parseWindow("7")).toBe(7);
+ });
+
+ test("parses '1d' as 1 day", () => {
+ expect(parseWindow("1d")).toBe(1);
+ });
+
+ test("parses '30d' as 30 days", () => {
+ expect(parseWindow("30d")).toBe(30);
+ });
+
+ test("rejects '0d'", () => {
+ expect(() => parseWindow("0d")).toThrow();
+ });
+
+ test("rejects '-1d'", () => {
+ expect(() => parseWindow("-1d")).toThrow();
+ });
+
+ test("rejects 'abc'", () => {
+ expect(() => parseWindow("abc")).toThrow();
+ });
+
+ test("rejects '1.5d'", () => {
+ expect(() => parseWindow("1.5d")).toThrow();
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+Run: `bun test tests/cli/brain-digest-window-cli.test.ts`
+Expected: FAIL β€” `parseWindow` not exported
+
+**Step 3: Add `parseWindow` function**
+
+In `src/cli/brain/verbs/digest.ts`, add before `cmdBrainDigest`:
+
+```typescript
+export function parseWindow(raw: string): number {
+ const m = /^(\d+)(?:d)?$/.exec(raw);
+ if (!m) throw new Error(`invalid --window value: ${raw} (expected Nd or N, e.g. 7d)`);
+ const n = parseInt(m[1]!, 10);
+ if (n <= 0) throw new Error(`invalid --window value: ${raw} (must be positive)`);
+ return n;
+}
+```
+
+**Step 4: Run test to verify pass**
+
+Run: `bun test tests/cli/brain-digest-window-cli.test.ts`
+Expected: PASS β€” all 8 tests
+
+**Step 5: Commit**
+
+```bash
+git add src/cli/brain/verbs/digest.ts tests/cli/brain-digest-window-cli.test.ts
+git commit -m "feat: add parseWindow utility for --window flag"
+```
+
+---
+
+### Task 2: Wire `--window` flag into `cmdBrainDigest`
+
+**Objective:** Pass parsed window days to `renderDigest` as the `since` calculation basis.
+
+**Files:**
+- Modify: `src/cli/brain/verbs/digest.ts`
+
+**Step 1: Add `--window` to parse flags**
+
+Add `"window": { type: "string" }` to the `parse()` call.
+
+**Step 2: Compute `since` from `--window` when provided**
+
+After the existing `sinceDate`/`untilDate` logic, add:
+
+```typescript
+if (flags["window"]) {
+ const windowDays = parseWindow(String(flags["window"]));
+ const until = untilDate ?? new Date();
+ sinceDate = new Date(until.getTime() - windowDays * 24 * 60 * 60 * 1000);
+}
+```
+
+**Step 3: Run existing tests**
+
+Run: `bun test tests/core/brain/digest-most-applied.test.ts tests/core/brain.digest.test.ts`
+Expected: PASS
+
+**Step 4: Commit**
+
+```bash
+git add src/cli/brain/verbs/digest.ts
+git commit -m "feat: wire --window flag into brain digest CLI"
+```
+
+---
+
+### Task 3: Add agent quality summary core computation
+
+**Objective:** Compute per-agent event counts + confirmed/retired attribution for the digest window.
+
+**Files:**
+- Create: `src/core/brain/digest-agent-summary.ts`
+- Test: `tests/core/brain/digest-agent-summary.test.ts`
+
+**Step 1: Write test file**
+
+Create `tests/core/brain/digest-agent-summary.test.ts`:
+
+```typescript
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeAgentSummary } from "../../../src/core/brain/digest-agent-summary.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_APPLY_RESULT,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-agent-summary-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+
+afterEach(() => {
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+});
+
+describe("computeAgentSummary", () => {
+ test("returns empty array when no log entries", () => {
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+ expect(summary).toEqual([]);
+ });
+
+ test("counts events per agent", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-15T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "testing", signal: "positive", principle: "test" },
+ agent: "claude-vps-agent",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-16T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-a]]", result: BRAIN_APPLY_RESULT.applied, artifact: "[[x.md]]" },
+ agent: "claude-vps-agent",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-17T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "naming", signal: "negative", principle: "no abbreviations" },
+ agent: "codex-agent",
+ });
+
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+
+ expect(summary.length).toBe(2);
+ const claude = summary.find((a) => a.agent === "claude-vps-agent")!;
+ expect(claude.total_events).toBe(2);
+ expect(claude.feedback_count).toBe(1);
+ expect(claude.apply_evidence_count).toBe(1);
+ expect(claude.note_count).toBe(0);
+
+ const codex = summary.find((a) => a.agent === "codex-agent")!;
+ expect(codex.total_events).toBe(1);
+ });
+
+ test("excludes events outside the window", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-01T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "old", signal: "positive", principle: "old" },
+ agent: "claude-vps-agent",
+ });
+
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+ expect(summary).toEqual([]);
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+Run: `bun test tests/core/brain/digest-agent-summary.test.ts`
+Expected: FAIL β€” module not found
+
+**Step 3: Implement `computeAgentSummary`**
+
+Create `src/core/brain/digest-agent-summary.ts`:
+
+```typescript
+/**
+ * Agent quality summary for the brain digest.
+ *
+ * Groups Brain/log events by agent within the given window and returns
+ * per-agent counts: total events, breakdown by type (feedback /
+ * apply-evidence / note), and attribution to confirmed/retired rules.
+ */
+
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parseLogDay, type BrainLogEntry } from "./log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+
+export interface AgentSummaryEntry {
+ readonly agent: string;
+ readonly total_events: number;
+ readonly feedback_count: number;
+ readonly apply_evidence_count: number;
+ readonly note_count: number;
+ readonly confirmed_attributed: number;
+ readonly retired_attributed: number;
+}
+
+export function computeAgentSummary(
+ vault: string,
+ since: Date,
+ until: Date,
+): ReadonlyArray<AgentSummaryEntry> {
+ const logs = readLogsInWindow(vault, since, until);
+ const byAgent = new Map<string, AgentAccumulator>();
+
+ for (const entry of logs) {
+ const agent = entry.agent ?? "unknown";
+ let acc = byAgent.get(agent);
+ if (!acc) {
+ acc = {
+ agent,
+ total_events: 0,
+ feedback_count: 0,
+ apply_evidence_count: 0,
+ note_count: 0,
+ confirmed_attributed: 0,
+ retired_attributed: 0,
+ };
+ byAgent.set(agent, acc);
+ }
+ acc.total_events++;
+ switch (entry.eventType) {
+ case BRAIN_LOG_EVENT_KIND.feedback:
+ acc.feedback_count++;
+ break;
+ case BRAIN_LOG_EVENT_KIND.applyEvidence:
+ acc.apply_evidence_count++;
+ break;
+ case BRAIN_LOG_EVENT_KIND.note:
+ acc.note_count++;
+ break;
+ }
+ }
+
+ // Attribution: for each log entry that references a preference,
+ // check if that preference was confirmed or retired in the window.
+ const seenPrefs = new Set<string>();
+ for (const entry of logs) {
+ const agent = entry.agent ?? "unknown";
+ const acc = byAgent.get(agent);
+ if (!acc) continue;
+
+ const pref = entry.body["preference"];
+ if (typeof pref !== "string") continue;
+ const prefId = extractPrefId(pref);
+ if (!prefId) continue;
+
+ const key = `${agent}:${prefId}`;
+ if (seenPrefs.has(key)) continue;
+ seenPrefs.add(key);
+
+ const confirmedAt = getConfirmedAt(vault, prefId);
+ const retiredAt = getRetiredAt(vault, prefId);
+
+ if (confirmedAt && isInWindow(confirmedAt, since, until)) {
+ acc.confirmed_attributed++;
+ }
+ if (retiredAt && isInWindow(retiredAt, since, until)) {
+ acc.retired_attributed++;
+ }
+ }
+
+ return [...byAgent.values()].sort((a, b) => b.total_events - a.total_events);
+}
+
+interface AgentAccumulator {
+ agent: string;
+ total_events: number;
+ feedback_count: number;
+ apply_evidence_count: number;
+ note_count: number;
+ confirmed_attributed: number;
+ retired_attributed: number;
+}
+
+function readLogsInWindow(
+ vault: string,
+ since: Date,
+ until: Date,
+): BrainLogEntry[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return [];
+ const sinceDay = since.toISOString().slice(0, 10);
+ const untilDay = until.toISOString().slice(0, 10);
+ const out: BrainLogEntry[] = [];
+ const dates = readdirSync(dirs.log, { withFileTypes: true })
+ .filter((d) => d.isFile() && d.name.endsWith(".md"))
+ .map((d) => d.name.slice(0, -3))
+ .filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))
+ .sort();
+ for (const date of dates) {
+ if (date < addDays(sinceDay, -1)) continue;
+ if (date > addDays(untilDay, 1)) continue;
+ const { entries } = parseLogDay(vault, date);
+ for (const e of entries) {
+ if (e.timestamp >= since.toISOString() && e.timestamp < until.toISOString()) {
+ out.push(e);
+ }
+ }
+ }
+ return out;
+}
+
+function addDays(day: string, delta: number): string {
+ const t = Date.parse(`${day}T00:00:00Z`);
+ if (!Number.isFinite(t)) return day;
+ return new Date(t + delta * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
+}
+
+function extractPrefId(raw: string): string | null {
+ const m = /\[\[([^\]|#]+)/.exec(raw);
+ if (m) return m[1]!.trim();
+ if (raw.startsWith("pref-")) return raw;
+ return null;
+}
+
+function getConfirmedAt(vault: string, prefId: string): string | null {
+ const dirs = brainDirs(vault);
+ const path = join(dirs.preferences, `${prefId}.md`);
+ if (!existsSync(path)) return null;
+ try {
+ const text = readFileSync(path, "utf8");
+ const m = /^confirmed_at:\s*(.+)$/m.exec(text);
+ return m ? m[1]!.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
+function getRetiredAt(vault: string, prefId: string): string | null {
+ const dirs = brainDirs(vault);
+ const retiredId = prefId.replace("pref-", "ret-");
+ const path = join(dirs.retired, `${retiredId}.md`);
+ if (!existsSync(path)) return null;
+ try {
+ const text = readFileSync(path, "utf8");
+ const m = /^retired_at:\s*(.+)$/m.exec(text);
+ return m ? m[1]!.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
+function isInWindow(iso: string, since: Date, until: Date): boolean {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return false;
+ return t >= since.getTime() && t < until.getTime();
+}
+```
+
+**Step 4: Run test to verify pass**
+
+Run: `bun test tests/core/brain/digest-agent-summary.test.ts`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/core/brain/digest-agent-summary.ts tests/core/brain/digest-agent-summary.test.ts
+git commit -m "feat: add agent quality summary computation for digest"
+```
+
+---
+
+### Task 4: Integrate agent summary into digest renderer
+
+**Objective:** Add agent quality summary section to digest Markdown and JSON output.
+
+**Files:**
+- Modify: `src/core/brain/digest.ts`
+
+**Step 1: Add import and new JSON types**
+
+In `src/core/brain/digest.ts`:
+
+```typescript
+import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";
+```
+
+Add before `DigestJson`:
+
+```typescript
+export interface DigestJsonAgentSummary {
+ readonly agent: string;
+ readonly total_events: number;
+ readonly feedback_count: number;
+ readonly apply_evidence_count: number;
+ readonly note_count: number;
+ readonly confirmed_attributed: number;
+ readonly retired_attributed: number;
+}
+```
+
+Add to `DigestJson`:
+
+```typescript
+readonly agent_summary: ReadonlyArray<DigestJsonAgentSummary>;
+```
+
+**Step 2: Add to `DigestData` interface**
+
+```typescript
+readonly agent_summary: ReadonlyArray<AgentSummaryEntry>;
+```
+
+**Step 3: Compute in `collectDigestData`**
+
+Before the return in `collectDigestData`:
+
+```typescript
+const agent_summary = computeAgentSummary(vault, since, until);
+```
+
+Add to return object: `agent_summary,`
+
+**Step 4: Add to JSON payload**
+
+In the JSON construction:
+
+```typescript
+agent_summary: data.agent_summary,
+```
+
+**Step 5: Add to Markdown rendering**
+
+In `renderMarkdown`, after the `most_applied` section and before `top_applied`:
+
+```typescript
+if (data.agent_summary.length > 0) {
+ lines.push(`## Agent summary (${data.agent_summary.length})`, "");
+ for (const item of data.agent_summary) {
+ const parts = [
+ `**${item.agent}**`,
+ `${item.total_events} events`,
+ `(feedback: ${item.feedback_count}, apply: ${item.apply_evidence_count}, note: ${item.note_count})`,
+ ];
+ if (item.confirmed_attributed > 0) parts.push(`β†’ ${item.confirmed_attributed} confirmed`);
+ if (item.retired_attributed > 0) parts.push(`β†’ ${item.retired_attributed} retired`);
+ lines.push(`- ${parts.join(" ")}`);
+ }
+ lines.push("");
+}
+```
+
+**Step 6: Run all digest tests**
+
+Run: `bun test tests/core/brain/digest*.test.ts`
+Expected: PASS
+
+**Step 7: Commit**
+
+```bash
+git add src/core/brain/digest.ts
+git commit -m "feat: integrate agent summary into digest renderer"
+```
+
+---
+
+### Task 5: Update `scripts/discipline-report.ts` for `--window`
+
+**Objective:** Parameterize the discipline report script to support `--window` flag.
+
+**Files:**
+- Modify: `scripts/discipline-report.ts`
+
+**Step 1: Rewrite the script**
+
+Replace `scripts/discipline-report.ts` with:
+
+```typescript
+#!/usr/bin/env -S bun
+import { resolveVault } from "../src/core/config.ts";
+import { runDisciplineReport } from "../src/core/discipline/report.ts";
+import { renderDigest } from "../src/core/brain/digest.ts";
+
+function parseArgs(): { vault: string; window: string | null } {
+ const argv = process.argv.slice(2);
+ let vault: string | undefined;
+ let window: string | null = null;
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === "--vault" && argv[i + 1]) {
+ vault = argv[++i]!;
+ } else if (argv[i] === "--window" && argv[i + 1]) {
+ window = argv[++i]!;
+ }
+ }
+ const v = vault ?? 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 { vault: v, window };
+}
+
+const { vault, window } = parseArgs();
+
+if (window) {
+ const m = /^(\d+)(?:d)?$/.exec(window);
+ if (!m) {
+ process.stderr.write(`o2b-discipline-report: invalid --window value: ${window}\n`);
+ process.exit(2);
+ }
+ const days = parseInt(m[1]!, 10);
+ if (days <= 0) {
+ process.stderr.write(`o2b-discipline-report: --window must be positive: ${window}\n`);
+ process.exit(2);
+ }
+ const now = new Date();
+ const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
+ const result = renderDigest(vault, { since, until: now, format: "markdown" });
+ process.stdout.write(result.content);
+ if (!result.content.endsWith("\n")) process.stdout.write("\n");
+} else {
+ 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 2: Run existing path (no --window)**
+
+Run: `bun run scripts/discipline-report.ts --vault /root/vault`
+Expected: outputs daily discipline report (or "disabled")
+
+**Step 3: Commit**
+
+```bash
+git add scripts/discipline-report.ts
+git commit -m "feat: add --window flag to discipline-report script"
+```
+
+---
+
+### Task 6: Add `--weekly` flag to `o2b discipline install`
+
+**Objective:** Install a weekly digest cron job alongside the daily one.
+
+**Files:**
+- Modify: `src/cli/discipline-install.ts`
+- Test: `tests/cli/discipline-install.test.ts`
+
+**Step 1: Read existing test file**
+
+Read `tests/cli/discipline-install.test.ts` to understand patterns.
+
+**Step 2: Modify `disciplineInstallVerb`**
+
+In `src/cli/discipline-install.ts`, add `--weekly` flag parsing:
+
+```typescript
+let weekly = false;
+// In the for loop, add:
+if (args[i] === "--weekly") {
+ weekly = true;
+ continue;
+}
+```
+
+Add helper functions:
+
+```typescript
+function weeklyJobId(vault: string): string {
+ const slug = createHash("sha256")
+ .update(resolve(vault) + ":weekly")
+ .digest("hex")
+ .slice(0, 12);
+ return `osb-weekly-brain-digest-${slug}`;
+}
+
+function weeklyScriptPath(): string {
+ return scriptPath() + " --window 7d";
+}
+```
+
+When `weekly` is true, use:
+- `id: weeklyJobId(vault)`
+- `name: "osb-weekly-brain-digest"`
+- `script: weeklyScriptPath()`
+- Default schedule `"59 8 * * 1"` (override with `--at`)
+
+**Step 3: Run existing tests**
+
+Run: `bun test tests/cli/discipline-install.test.ts`
+Expected: PASS
+
+**Step 4: Commit**
+
+```bash
+git add src/cli/discipline-install.ts
+git commit -m "feat: add --weekly flag to discipline install"
+```
+
+---
+
+### Task 7: Implement `o2b update` core logic
+
+**Objective:** Core update orchestration β€” detect β†’ plan β†’ compare β†’ apply per target.
+
+**Files:**
+- Create: `src/core/install/update.ts`
+- Create: `tests/core/install/update.test.ts`
+
+**Step 1: Write test file**
+
+Create `tests/core/install/update.test.ts`:
+
+```typescript
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runUpdate } from "../../../src/core/install/update.ts";
+import { createRegistry } from "../../../src/core/install/registry.ts";
+import type {
+ InstallAdapter,
+ InstallEnv,
+ DetectResult,
+ InstallPlan,
+ ApplyResult,
+ VerifyResult,
+} from "../../../src/core/install/types.ts";
+
+let vault: string;
+let home: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-update-"));
+ home = mkdtempSync(join(tmpdir(), "osb-update-home-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });
+});
+
+afterEach(() => {
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+ try { rmSync(home, { recursive: true, force: true }); } catch {}
+});
+
+function makeEnv(): InstallEnv {
+ return { vault, home, cwd: process.cwd(), env: {}, now: new Date() };
+}
+
+function fakeAdapter(
+ target: string,
+ status: "installed" | "not-installed" = "installed",
+ payloadHash?: string,
+): InstallAdapter {
+ return {
+ target,
+ label: target,
+ detect(): DetectResult {
+ return { target, status, configPath: `/tmp/${target}-config`, notes: [] };
+ },
+ plan(): InstallPlan {
+ return {
+ target,
+ steps: [{ kind: "json-merge", path: "/tmp/c.json", preview: "merge" }],
+ postNotes: ["restart " + target],
+ };
+ },
+ apply(): ApplyResult {
+ return {
+ target,
+ steps_executed: 1,
+ manifest: {
+ target,
+ applied_at: new Date().toISOString(),
+ operation: "json-merge",
+ config_path: "/tmp/c.json",
+ },
+ };
+ },
+ uninstall() {
+ return { target, removed_keys: [], removed_paths: [], skipped: [] };
+ },
+ verify(): VerifyResult {
+ return { target, status: "ok", details: [], fix_hint: null };
+ },
+ };
+}
+
+describe("runUpdate", () => {
+ test("skips not-installed targets", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("cursor", "not-installed"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: false, force: false, target: null });
+ expect(result.targets.length).toBe(1);
+ expect(result.targets[0].status).toBe("skipped");
+ });
+
+ test("applies when no previous manifest exists", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: false, force: false, target: null });
+ expect(result.targets[0].status).toBe("applied");
+ });
+
+ test("dry-run reports would-apply without applying", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: true, force: false, target: null });
+ expect(result.targets[0].status).toBe("would-apply");
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+Run: `bun test tests/core/install/update.test.ts`
+Expected: FAIL β€” module not found
+
+**Step 3: Implement `runUpdate`**
+
+Create `src/core/install/update.ts`:
+
+```typescript
+/**
+ * Update orchestrator for v0.10.12.
+ *
+ * Runs the InstallAdapter pipeline (detect β†’ plan β†’ compare β†’ apply)
+ * across all registered targets or a single --target. Skips targets
+ * where the payload hash hasn't changed since the last update.
+ */
+
+import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { createHash } from "node:crypto";
+
+import type { Registry } from "./registry.ts";
+import type {
+ InstallAdapter,
+ InstallEnv,
+ ApplyOpts,
+ McpPayload,
+} from "./types.ts";
+import { InstallError } from "./types.ts";
+import { buildPayload } from "./payload.ts";
+
+export interface UpdateTargetResult {
+ readonly target: string;
+ readonly status: "applied" | "up-to-date" | "skipped" | "would-apply" | "error" | "verified-drift";
+ readonly reason?: string;
+ readonly postNotes?: ReadonlyArray<string>;
+ readonly error?: string;
+ readonly hint?: string;
+}
+
+export interface UpdateResult {
+ readonly targets: ReadonlyArray<UpdateTargetResult>;
+}
+
+export interface UpdateOptions {
+ readonly dryRun: boolean;
+ readonly force: boolean;
+ readonly target: string | null;
+}
+
+interface SidecarManifest {
+ targets: Record<string, {
+ payload_hash: string;
+ applied_at: string;
+ }>;
+}
+
+function sidecarPath(vault: string): string {
+ return join(vault, ".open-second-brain", "update.lock.json");
+}
+
+function loadSidecar(vault: string): SidecarManifest {
+ const path = sidecarPath(vault);
+ if (!existsSync(path)) return { targets: {} };
+ try {
+ return JSON.parse(readFileSync(path, "utf8"));
+ } catch {
+ return { targets: {} };
+ }
+}
+
+function saveSidecar(vault: string, manifest: SidecarManifest): void {
+ const path = sidecarPath(vault);
+ const dir = join(vault, ".open-second-brain");
+ if (!existsSync(dir)) {
+ try { mkdirSync(dir, { recursive: true }); } catch {}
+ }
+ writeFileSync(path, JSON.stringify(manifest, sortedReplacer, 2) + "\n");
+}
+
+function computePayloadHash(payload: McpPayload): string {
+ return createHash("sha256")
+ .update(JSON.stringify(payload, sortedReplacer))
+ .digest("hex");
+}
+
+function sortedReplacer(_key: string, value: unknown): unknown {
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ const sorted: Record<string, unknown> = {};
+ for (const k of Object.keys(value as Record<string, unknown>).sort()) {
+ sorted[k] = (value as Record<string, unknown>)[k];
+ }
+ return sorted;
+ }
+ return value;
+}
+
+export function runUpdate(
+ registry: Registry,
+ env: InstallEnv,
+ opts: UpdateOptions,
+): UpdateResult {
+ const targets = opts.target
+ ? [registry.get(opts.target)].filter((a): a is InstallAdapter => a !== undefined)
+ : registry.list();
+
+ const results: UpdateTargetResult[] = [];
+ const sidecar = loadSidecar(env.vault);
+
+ for (const adapter of targets) {
+ const detect = adapter.detect(env);
+
+ if (detect.status === "not-installed" || detect.status === "unsupported-on-this-platform") {
+ results.push({
+ target: adapter.target,
+ status: "skipped",
+ reason: `${adapter.label} is ${detect.status}`,
+ postNotes: detect.notes.length > 0 ? detect.notes : undefined,
+ });
+ continue;
+ }
+
+ let payload: McpPayload;
+ try {
+ payload = buildPayload({
+ vault: env.vault,
+ agent_name: env.env["VAULT_AGENT_NAME"] ?? null,
+ timezone: env.env["VAULT_TIMEZONE"] ?? null,
+ });
+ } catch (e) {
+ results.push({
+ target: adapter.target,
+ status: "error",
+ error: `Failed to build payload: ${(e as Error).message}`,
+ });
+ continue;
+ }
+
+ const currentHash = computePayloadHash(payload);
+ const previous = sidecar.targets[adapter.target];
+
+ if (previous && previous.payload_hash === currentHash && !opts.force) {
+ results.push({
+ target: adapter.target,
+ status: "up-to-date",
+ reason: "payload unchanged",
+ });
+ continue;
+ }
+
+ const plan = adapter.plan(payload, env);
+
+ if (opts.dryRun) {
+ results.push({
+ target: adapter.target,
+ status: "would-apply",
+ postNotes: plan.postNotes,
+ });
+ continue;
+ }
+
+ const applyOpts: ApplyOpts = {
+ dryRun: false,
+ force: opts.force,
+ stdout: process.stdout,
+ stderr: process.stderr,
+ };
+
+ try {
+ adapter.apply(plan, payload, env, applyOpts);
+ } catch (e) {
+ if (e instanceof InstallError) {
+ results.push({
+ target: adapter.target,
+ status: "error",
+ error: e.message,
+ hint: e.hint,
+ });
+ } else {
+ results.push({
+ target: adapter.target,
+ status: "error",
+ error: (e as Error).message,
+ });
+ }
+ continue;
+ }
+
+ sidecar.targets[adapter.target] = {
+ payload_hash: currentHash,
+ applied_at: new Date().toISOString(),
+ };
+ saveSidecar(env.vault, sidecar);
+
+ results.push({
+ target: adapter.target,
+ status: "applied",
+ postNotes: plan.postNotes,
+ });
+ }
+
+ return { targets: results };
+}
+```
+
+**Step 4: Run test to verify pass**
+
+Run: `bun test tests/core/install/update.test.ts`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add src/core/install/update.ts tests/core/install/update.test.ts
+git commit -m "feat: add update orchestrator core logic"
+```
+
+---
+
+### Task 8: Implement `o2b update` CLI verb
+
+**Objective:** CLI handler for `o2b update` with flag parsing and output rendering.
+
+**Files:**
+- Create: `src/cli/update.ts`
+- Modify: `src/cli/main.ts`
+- Test: `tests/cli/update.test.ts`
+
+**Step 1: Write test file**
+
+Create `tests/cli/update.test.ts`:
+
+```typescript
+import { describe, expect, test } from "bun:test";
+import { parseUpdateArgs } from "../../src/cli/update.ts";
+
+describe("parseUpdateArgs", () => {
+ test("parses no flags", () => {
+ const args = parseUpdateArgs([]);
+ expect(args.target).toBeNull();
+ expect(args.dryRun).toBe(false);
+ expect(args.force).toBe(false);
+ expect(args.json).toBe(false);
+ });
+
+ test("parses --target", () => {
+ const args = parseUpdateArgs(["--target", "claudecode"]);
+ expect(args.target).toBe("claudecode");
+ });
+
+ test("parses --dry-run", () => {
+ const args = parseUpdateArgs(["--dry-run"]);
+ expect(args.dryRun).toBe(true);
+ });
+
+ test("parses --force", () => {
+ const args = parseUpdateArgs(["--force"]);
+ expect(args.force).toBe(true);
+ });
+
+ test("parses --json", () => {
+ const args = parseUpdateArgs(["--json"]);
+ expect(args.json).toBe(true);
+ });
+});
+```
+
+**Step 2: Run test to verify failure**
+
+Run: `bun test tests/cli/update.test.ts`
+Expected: FAIL
+
+**Step 3: Implement CLI verb**
+
+Create `src/cli/update.ts`:
+
+```typescript
+/**
+ * `o2b update` CLI verb.
+ *
+ * Exit codes:
+ * 0 all targets updated or up-to-date
+ * 1 runtime error
+ * 2 usage error
+ * 3 drift detected after update
+ */
+
+import { homedir } from "node:os";
+
+import { parseFlags } from "./argparse.ts";
+import { defaultConfigPath, discoverConfig } from "../core/config.ts";
+import { defaultRegistry } from "../core/install/registry.ts";
+import "../core/install/adapters/aider.ts";
+import "../core/install/adapters/copilot-cli.ts";
+import "../core/install/adapters/cursor.ts";
+import "../core/install/adapters/gemini-cli.ts";
+import "../core/install/adapters/generic.ts";
+import "../core/install/adapters/kiro.ts";
+import "../core/install/adapters/opencode.ts";
+import "../core/install/adapters/pi.ts";
+
+import { runUpdate, type UpdateResult, type UpdateTargetResult } from "../core/install/update.ts";
+import type { InstallEnv, VerifyResult } from "../core/install/types.ts";
+
+interface ParsedUpdateArgs {
+ readonly target: string | null;
+ readonly dryRun: boolean;
+ readonly force: boolean;
+ readonly json: boolean;
+}
+
+export function parseUpdateArgs(argv: string[]): ParsedUpdateArgs {
+ const { flags } = parseFlags(argv, {
+ target: { type: "string" },
+ "dry-run": { type: "boolean" },
+ force: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ return {
+ target: (flags["target"] as string | undefined) ?? null,
+ dryRun: Boolean(flags["dry-run"]),
+ force: Boolean(flags["force"]),
+ json: Boolean(flags["json"]),
+ };
+}
+
+function buildEnv(): InstallEnv {
+ const cfg = discoverConfig(defaultConfigPath()).data;
+ const vault = cfg["vault"] ?? process.env["VAULT_DIR"] ?? "";
+ const env = { ...process.env } as Record<string, string>;
+ if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];
+ if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];
+ return { vault, home: homedir(), cwd: process.cwd(), env, now: new Date() };
+}
+
+function renderResult(result: UpdateResult, json: boolean): void {
+ if (json) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return;
+ }
+
+ for (const t of result.targets) {
+ const icon = statusIcon(t.status);
+ process.stdout.write(`${icon} ${t.target}`);
+ if (t.reason) process.stdout.write(` β€” ${t.reason}`);
+ if (t.error) process.stdout.write(` β€” ERROR: ${t.error}`);
+ if (t.hint) process.stdout.write(`\n hint: ${t.hint}`);
+ if (t.postNotes && t.postNotes.length > 0) {
+ for (const note of t.postNotes) process.stdout.write(`\n β†’ ${note}`);
+ }
+ process.stdout.write("\n");
+ }
+
+ const applied = result.targets.filter((t) => t.status === "applied").length;
+ const upToDate = result.targets.filter((t) => t.status === "up-to-date").length;
+ const skipped = result.targets.filter((t) => t.status === "skipped").length;
+ const errors = result.targets.filter((t) => t.status === "error").length;
+ process.stdout.write(`\n${applied} applied, ${upToDate} up-to-date, ${skipped} skipped`);
+ if (errors > 0) process.stdout.write(`, ${errors} errors`);
+ process.stdout.write("\n");
+}
+
+function statusIcon(status: UpdateTargetResult["status"]): string {
+ switch (status) {
+ case "applied": return "βœ“";
+ case "up-to-date": return "=";
+ case "skipped": return "β—‹";
+ case "would-apply": return "~";
+ case "error": return "βœ—";
+ case "verified-drift": return "!";
+ default: return "?";
+ }
+}
+
+export async function cmdUpdate(argv: string[]): Promise<number> {
+ let args: ParsedUpdateArgs;
+ try {
+ args = parseUpdateArgs(argv);
+ } catch (e) {
+ process.stderr.write(`error: ${(e as Error).message}\n`);
+ return 2;
+ }
+
+ const env = buildEnv();
+ if (!env.vault) {
+ process.stderr.write("error: vault not configured. Set VAULT_DIR or run `o2b init`.\n");
+ return 2;
+ }
+
+ if (args.target && !defaultRegistry.get(args.target)) {
+ process.stderr.write(
+ `error: unknown --target: ${args.target}. ` +
+ `Available: ${defaultRegistry.targets().join(", ")}\n`,
+ );
+ return 2;
+ }
+
+ const result = runUpdate(defaultRegistry, env, {
+ dryRun: args.dryRun,
+ force: args.force,
+ target: args.target,
+ });
+
+ renderResult(result, args.json);
+
+ // Post-update verify
+ if (!args.dryRun) {
+ const targets = args.target
+ ? [defaultRegistry.get(args.target)!]
+ : defaultRegistry.list();
+ const verifyResults: VerifyResult[] = [];
+ for (const a of targets) {
+ if (a.detect(env).status === "installed") {
+ verifyResults.push(a.verify(env));
+ }
+ }
+ const drift = verifyResults.some((r) => r.status === "drift");
+ if (drift) {
+ process.stderr.write("\nwarning: drift detected after update. Run `o2b install --check` for details.\n");
+ return 3;
+ }
+ }
+
+ const hasError = result.targets.some((t) => t.status === "error");
+ return hasError ? 1 : 0;
+}
+```
+
+**Step 4: Run test to verify pass**
+
+Run: `bun test tests/cli/update.test.ts`
+Expected: PASS
+
+**Step 5: Register in main.ts**
+
+In `src/cli/main.ts`:
+
+1. Add import:
+```typescript
+import { cmdUpdate } from "./update.ts";
+```
+
+2. Add case in the switch (before `default`):
+```typescript
+case "update":
+ return await cmdUpdate(rest);
+```
+
+3. Add to HELP string (under the main Commands section):
+```
+ update Update OSB installation across all detected runtimes
+```
+
+**Step 6: Run typecheck and tests**
+
+Run: `bun run typecheck`
+Run: `bun test tests/cli/update.test.ts tests/core/install/update.test.ts`
+Expected: both pass
+
+**Step 7: Commit**
+
+```bash
+git add src/cli/update.ts src/cli/main.ts tests/cli/update.test.ts
+git commit -m "feat: add o2b update CLI verb"
+```
+
+---
+
+### Task 9: Cursor SQLite deep parsing
+
+**Objective:** Replace mtime-only probe with SQLite parsing returning session count + message count.
+
+**Files:**
+- Modify: `src/core/discipline/transcripts/types.ts`
+- Modify: `src/core/discipline/transcripts/cursor.ts`
+- Modify: `src/core/discipline/transcripts/index.ts`
+- Test: `tests/core/discipline/transcripts/cursor-sqlite.test.ts`
+
+**Step 1: Extend `TranscriptRuntime` interface**
+
+In `src/core/discipline/transcripts/types.ts`, add:
+
+```typescript
+export interface TranscriptDetail {
+ readonly sessionCount: number;
+ readonly messageCount: number;
+}
+
+export interface TranscriptRuntime {
+ readonly runtime: "claudecode" | "codex" | "cursor";
+ readonly agentHint: string | null;
+ collect(dayStartMs: number, dayEndMs: number, home?: string): string[];
+ /**
+ * Optional detailed collector returning session/message counts.
+ * Falls back to `collect().length` if not implemented.
+ */
+ collectDetail?(dayStartMs: number, dayEndMs: number, home?: string): TranscriptDetail | null;
+}
+```
+
+Add to `TranscriptRuntimeActivity`:
+
+```typescript
+export interface TranscriptRuntimeActivity {
+ readonly runtime: string;
+ readonly fileCount: number;
+ readonly agentHint: string | null;
+ readonly detail?: TranscriptDetail;
+}
+```
+
+**Step 2: Update aggregator to use `collectDetail`**
+
+In `src/core/discipline/transcripts/index.ts`, modify `collectTranscriptActivity`:
+
+```typescript
+for (const r of runtimes) {
+ const files = r.collect(opts.dayStartMs, opts.dayEndMs, opts.home);
+ const detail = r.collectDetail?.(opts.dayStartMs, opts.dayEndMs, opts.home) ?? null;
+ byRuntime.push({
+ runtime: r.runtime,
+ fileCount: files.length,
+ agentHint: r.agentHint,
+ ...(detail ? { detail } : {}),
+ });
+ total += files.length;
+}
+```
+
+**Step 3: Implement Cursor SQLite parsing**
+
+Rewrite `src/core/discipline/transcripts/cursor.ts`:
+
+```typescript
+/**
+ * Cursor session-transcript paths for the discipline report.
+ *
+ * v0.10.12: reads `state.vscdb` SQLite to extract session count and
+ * message count. Falls back to mtime probe on any error.
+ */
+
+import { existsSync, readdirSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import type { TranscriptDetail, TranscriptRuntime } from "./types.ts";
+
+export const cursorTranscript: TranscriptRuntime = {
+ runtime: "cursor",
+ agentHint: "cursor-vps-agent",
+ collect(dayStartMs, dayEndMs, home = homedir()): string[] {
+ const dbs = findDatabases(home);
+ const out: string[] = [];
+ for (const db of dbs) {
+ try {
+ const st = statSync(db);
+ if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) out.push(db);
+ } catch {}
+ }
+ return out;
+ },
+ collectDetail(dayStartMs, dayEndMs, home = homedir()): TranscriptDetail | null {
+ const dbs = findDatabases(home);
+ let totalSessions = 0;
+ let totalMessages = 0;
+ let anyActive = false;
+
+ for (const db of dbs) {
+ try {
+ const result = queryCursorDb(db, dayStartMs, dayEndMs);
+ if (result) {
+ totalSessions += result.sessionCount;
+ totalMessages += result.messageCount;
+ if (result.sessionCount > 0) anyActive = true;
+ }
+ } catch {
+ // Fall back to mtime for this specific DB
+ try {
+ const st = statSync(db);
+ if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) anyActive = true;
+ } catch {}
+ }
+ }
+
+ if (!anyActive && totalSessions === 0) return null;
+ return { sessionCount: totalSessions, messageCount: totalMessages };
+ },
+};
+
+function findDatabases(home: string): string[] {
+ const roots = [
+ join(home, ".config", "Cursor", "User", "workspaceStorage"),
+ join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),
+ join(home, ".cursor", "workspaceStorage"),
+ ];
+ const out: string[] = [];
+ for (const root of roots) {
+ if (!existsSync(root)) continue;
+ let dirs: import("node:fs").Dirent[];
+ try {
+ dirs = readdirSync(root, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const d of dirs) {
+ if (!d.isDirectory()) continue;
+ const db = join(root, d.name, "state.vscdb");
+ if (existsSync(db)) out.push(db);
+ }
+ }
+ return out;
+}
+
+function queryCursorDb(
+ dbPath: string,
+ dayStartMs: number,
+ dayEndMs: number,
+): { sessionCount: number; messageCount: number } | null {
+ let Database: typeof import("bun:sqlite").Database;
+ try {
+ Database = require("bun:sqlite").Database;
+ } catch {
+ return null;
+ }
+
+ let db: InstanceType<typeof Database>;
+ try {
+ db = new Database(dbPath, { readonly: true });
+ } catch {
+ return null;
+ }
+
+ try {
+ // Cursor stores session data in ItemTable with keys like
+ // "sessionData.<sessionId>". The value is a JSON blob.
+ // We query all session keys and parse the JSON to count messages
+ // and check timestamps.
+ const rows = db
+ .query("SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'")
+ .all() as Array<{ key: string; value: string }>;
+
+ let sessionCount = 0;
+ let messageCount = 0;
+
+ for (const row of rows) {
+ try {
+ const data = JSON.parse(row.value);
+ // Cursor session data structure: the value may contain
+ // `messages` array or `turns` array. We count whatever
+ // array-like structure is present.
+ const messages = data?.messages ?? data?.turns ?? data?.data?.messages;
+ if (Array.isArray(messages)) {
+ // Check if any message falls in the day window
+ let hasActivityInWindow = false;
+ for (const msg of messages) {
+ const ts = msg?.timestamp ?? msg?.createdAt ?? msg?.created_at;
+ if (ts) {
+ const tsMs = typeof ts === "number" ? ts : Date.parse(ts);
+ if (Number.isFinite(tsMs) && tsMs >= dayStartMs && tsMs < dayEndMs) {
+ hasActivityInWindow = true;
+ }
+ }
+ }
+ if (hasActivityInWindow) {
+ sessionCount++;
+ messageCount += messages.length;
+ }
+ }
+ } catch {
+ // Malformed JSON β€” skip this session
+ }
+ }
+
+ return { sessionCount, messageCount };
+ } finally {
+ try { db.close(); } catch {}
+ }
+}
+```
+
+**Step 4: Write test file**
+
+Create `tests/core/discipline/transcripts/cursor-sqlite.test.ts`:
+
+```typescript
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { cursorTranscript } from "../../../../src/core/discipline/transcripts/cursor.ts";
+
+describe("cursorTranscript collectDetail", () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "osb-cursor-"));
+ });
+
+ afterEach(() => {
+ try { rmSync(home, { recursive: true, force: true }); } catch {}
+ });
+
+ test("returns null when no Cursor data exists", () => {
+ const dayStart = Date.now() - 24 * 60 * 60 * 1000;
+ const dayEnd = Date.now();
+ const detail = cursorTranscript.collectDetail!(dayStart, dayEnd, home);
+ expect(detail).toBeNull();
+ });
+
+ test("falls back gracefully when SQLite is unavailable", () => {
+ // Create a fake directory structure without actual SQLite
+ const wsRoot = join(home, ".config", "Cursor", "User", "workspaceStorage", "fake-hash");
+ mkdirSync(wsRoot, { recursive: true });
+ // Create a non-SQLite file where state.vscdb would be
+ writeFileSync(join(wsRoot, "state.vscdb"), "not a sqlite database");
+
+ const dayStart = Date.now() - 24 * 60 * 60 * 1000;
+ const dayEnd = Date.now();
+ // Should not throw β€” graceful fallback
+ const detail = cursorTranscript.collectDetail!(dayStart, dayEnd, home);
+ // Returns null because the file isn't a valid SQLite DB
+ expect(detail).toBeNull();
+ });
+});
+```
+
+**Step 5: Run test to verify pass**
+
+Run: `bun test tests/core/discipline/transcripts/cursor-sqlite.test.ts`
+Expected: PASS
+
+**Step 6: Run all discipline tests**
+
+Run: `bun test tests/discipline/ tests/core/discipline/`
+Expected: PASS
+
+**Step 7: Commit**
+
+```bash
+git add src/core/discipline/transcripts/types.ts src/core/discipline/transcripts/cursor.ts src/core/discipline/transcripts/index.ts tests/core/discipline/transcripts/cursor-sqlite.test.ts
+git commit -m "feat: add Cursor SQLite deep parsing for transcript activity"
+```
+
+---
+
+### Task 10: Obsidian deep-link in explorer
+
+**Objective:** Double-click on a node in live-mode opens the file in Obsidian.
+
+**Files:**
+- Modify: `src/core/brain/explorer.ts`
+- Modify: `templates/brain-explorer.html`
+- Test: `tests/core/brain/explorer-deeplink.test.ts`
+
+**Step 1: Add `__VAULT_PATH__` placeholder to template**
+
+In `templates/brain-explorer.html`, add near the `__GRAPH_JSON__` line (in the `<script>` block where graph data is injected):
+
+```html
+<script>
+const VAULT_PATH = "__VAULT_PATH__";
+</script>
+```
+
+**Step 2: Modify `renderExportedHtml` to accept vaultPath**
+
+In `src/core/brain/explorer.ts`, add a new placeholder constant:
+
+```typescript
+const VAULT_PATH_PLACEHOLDER = "__VAULT_PATH__";
+```
+
+Modify `renderExportedHtml` to accept an optional vaultPath:
+
+```typescript
+export function renderExportedHtml(graph: ExplorerGraph, vaultPath?: string): string {
+ const json = JSON.stringify(graph).replace(/[<>&]/g, (c) => {
+ switch (c) {
+ case "<": return "\\u003c";
+ case ">": return "\\u003e";
+ case "&": return "\\u0026";
+ default: return c;
+ }
+ });
+ let html = loadTemplate().replace(PLACEHOLDER, () => json);
+ if (vaultPath) {
+ html = html.replace(VAULT_PATH_PLACEHOLDER, vaultPath.replace(/\\/g, "\\\\").replace(/'/g, "\\'"));
+ } else {
+ html = html.replace(VAULT_PATH_PLACEHOLDER, "");
+ }
+ return html;
+}
+```
+
+**Step 3: Pass vaultPath in live server**
+
+In `buildLiveServer`, modify the response:
+
+```typescript
+if (url.pathname === "/" || url.pathname === "/index.html") {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph, vault);
+ return new Response(html, {
+ headers: { "content-type": "text/html; charset=utf-8" },
+ });
+}
+```
+
+**Step 4: Add double-click handler to template**
+
+In `templates/brain-explorer.html`, in the `selectNode` function or as a separate double-click handler on the canvas:
+
+```javascript
+// After the existing canvas click handler, add:
+canvas.addEventListener("dblclick", (e) => {
+ if (!VAULT_PATH) return;
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ if (!n) return;
+ const filePath = VAULT_PATH + "/Brain/preferences/" + n.id + ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ const opened = window.open(uri, "_blank");
+ if (!opened) {
+ // Fallback: copy path to clipboard
+ navigator.clipboard.writeText(filePath).then(() => {
+ showTooltip("Obsidian not detected β€” path copied to clipboard");
+ }).catch(() => {
+ showTooltip("Path: " + filePath);
+ });
+ }
+});
+
+function showTooltip(text) {
+ let tip = document.getElementById("deeplink-tooltip");
+ if (!tip) {
+ tip = document.createElement("div");
+ tip.id = "deeplink-tooltip";
+ tip.style.cssText = "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:8px 16px;border-radius:4px;font-size:12px;z-index:9999;transition:opacity 0.3s;";
+ document.body.appendChild(tip);
+ }
+ tip.textContent = text;
+ tip.style.opacity = "1";
+ clearTimeout(tip._timer);
+ tip._timer = setTimeout(() => { tip.style.opacity = "0"; }, 3000);
+}
+```
+
+Also add double-click handler for listbox items:
+
+```javascript
+// In the listbox onclick handler, add dblclick:
+list.addEventListener("dblclick", (ev) => {
+ if (!VAULT_PATH) return;
+ const li = ev.target.closest("li[data-node-id]");
+ if (!li) return;
+ const nodeId = li.getAttribute("data-node-id");
+ const filePath = VAULT_PATH + "/Brain/preferences/" + nodeId + ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ window.open(uri, "_blank");
+});
+```
+
+**Step 5: Write test**
+
+Create `tests/core/brain/explorer-deeplink.test.ts`:
+
+```typescript
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { collectExplorerData, renderExportedHtml, __resetExplorerTemplateCacheForTests } from "../../../src/core/brain/explorer.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-explorer-dl-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ __resetExplorerTemplateCacheForTests();
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+});
+
+describe("explorer deep-link", () => {
+ test("renderExportedHtml substitutes vault path", () => {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph, "/my/vault");
+ expect(html).toContain("/my/vault");
+ expect(html).not.toContain("__VAULT_PATH__");
+ });
+
+ test("renderExportedHtml with no vault path renders empty", () => {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ expect(html).not.toContain("__VAULT_PATH__");
+ });
+});
+```
+
+**Step 6: Run test to verify pass**
+
+Run: `bun test tests/core/brain/explorer-deeplink.test.ts`
+Expected: PASS
+
+**Step 7: Run all explorer tests**
+
+Run: `bun test tests/core/brain/explorer*.test.ts`
+Expected: PASS
+
+**Step 8: Commit**
+
+```bash
+git add src/core/brain/explorer.ts templates/brain-explorer.html tests/core/brain/explorer-deeplink.test.ts
+git commit -m "feat: add Obsidian deep-link on double-click in explorer"
+```
+
+---
+
+### Task 11: Bump version and update CHANGELOG
+
+**Objective:** Bump version to 0.10.12 and add changelog entry.
+
+**Files:**
+- Modify: `package.json`
+- Modify: `CHANGELOG.md`
+
+**Step 1: Bump version in package.json**
+
+Change `"version": "0.10.11"` to `"version": "0.10.12"`.
+
+**Step 2: Add CHANGELOG entry**
+
+At the top of `CHANGELOG.md`:
+
+```markdown
+## 0.10.12 β€” 2026-05-XX
+
+### Added
+- `o2b update` β€” one-command update across all detected runtimes. Skips unchanged payloads via sidecar hash comparison. Supports `--target`, `--dry-run`, `--force`, `--json`.
+- `o2b brain digest --window 7d` β€” arbitrary time windows for the digest. Weekly cron installable via `o2b discipline install --weekly`.
+- Agent quality summary in digest β€” per-agent event counts, type breakdown, and confirmed/retired attribution.
+- Cursor SQLite deep parsing β€” discipline report now reads `state.vscdb` for session count + message count, eliminating mtime false-positives.
+- Obsidian deep-link in explorer β€” double-click a node in live mode to open the file in Obsidian.
+
+### Changed
+- `scripts/discipline-report.ts` now accepts `--window Nd` for digest mode.
+```
+
+**Step 3: Run typecheck**
+
+Run: `bun run typecheck`
+Expected: PASS
+
+**Step 4: Run full test suite**
+
+Run: `bun test`
+Expected: PASS
+
+**Step 5: Commit**
+
+```bash
+git add package.json CHANGELOG.md
+git commit -m "chore: bump version to 0.10.12, update CHANGELOG"
+```
+
+---
+
+## Verification Checklist
+
+After all tasks:
+
+```bash
+# Typecheck
+bun run typecheck
+
+# Full test suite
+bun test
+
+# Manual smoke test β€” update
+o2b update --dry-run
+
+# Manual smoke test β€” digest with window
+o2b brain digest --window 7d
+
+# Manual smoke test β€” discipline install weekly
+o2b discipline install --weekly --telegram-target telegram:-1003895040510:216 --vault /root/vault
+
+# Manual smoke test β€” explorer live
+o2b brain explorer &
+# Open http://127.0.0.1:7777 in browser, double-click a node
+```
diff --git a/docs/superpowers/specs/2026-05-20-v0.10.12-design.md b/docs/superpowers/specs/2026-05-20-v0.10.12-design.md
new file mode 100644
index 00000000..dde16bd9
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-20-v0.10.12-design.md
@@ -0,0 +1,291 @@
+# v0.10.12 β€” Operational Friction Reduction
+
+**Date:** 2026-05-20
+**Status:** draft
+**Author:** Sisyphus (via brainstorming)
+**Audience:** implementation
+
+## Problem Statement
+
+Two pain points in daily OSB operation:
+
+1. **Manual per-runtime update on every release.** Operator runs 5-7 steps per machine to update OSB installation across all runtimes (Claude Code, Codex, Hermes, Cursor, etc.). Error-prone and tedious.
+2. **No trend visibility.** Daily discipline report gives a single-day snapshot. No understanding of "how the agent learns over a week" β€” confidence trends, agent engagement quality, rule adoption patterns.
+
+## Scope
+
+Four features, one PR, one release (v0.10.12):
+
+| # | Feature | Priority |
+|---|---------|----------|
+| 1 | `o2b update` CLI verb | Primary |
+| 2 | Weekly Brain Digest (`--window 7d`) | Primary |
+| 3 | Cursor SQLite deep parsing | Companion |
+| 4 | Obsidian deep-link in explorer | Companion |
+
+**Out of scope (explicitly deferred):**
+- Window-triggers for Hermes cron (Β§25) β€” Hermes-side change, tracked separately
+- `--scope project` for Cursor/opencode/kiro β€” already deferred, trigger not met
+- Live-refresh in explorer (SSE/WS) β€” already deferred, trigger not met
+
+---
+
+## Feature 1: `o2b update`
+
+### What it does
+
+One command that updates OSB installation across all detected runtimes by re-running the InstallAdapter pipeline with the current version's payload. Skips runtimes where the payload hasn't changed.
+
+### User-facing surface
+
+```bash
+# Update all detected runtimes
+o2b update
+
+# Update a specific runtime
+o2b update --target claudecode
+
+# Dry-run: show what would change without applying
+o2b update --dry-run
+
+# Force apply even if payload appears unchanged
+o2b update --force
+
+# JSON output for scripting
+o2b update --json
+```
+
+### Behavior
+
+For each target (or `--target X`):
+
+1. **Detect** β€” run `adapter.detect(env)` to check runtime status
+2. **Plan** β€” generate current `McpPayload` and call `adapter.plan(payload, env)`
+3. **Compare** β€” check sidecar manifest (`install.lock.json`) for previous payload; if identical, skip with "up-to-date" note
+4. **Apply** β€” if payload differs (or `--force`), call `adapter.apply(plan, payload, env, opts)`
+5. **Post-notes** β€” emit per-runtime restart hints (e.g., "restart Claude Code", `hermes gateway restart`)
+6. **Verify** β€” run `o2b install --check` at the end for all targets
+
+If a runtime fails to update: clear error message with hint pointing to the required manual step. No auto-recovery for cases requiring user decision.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| 0 | All targets updated or already up-to-date |
+| 1 | Runtime error (I/O, subprocess failure) |
+| 2 | Usage error (unknown target, bad flags) |
+| 3 | `--check` found drift after update |
+| 4 | User-modified-block conflict (use `--force` to override) |
+
+### File changes
+
+- **New:** `src/cli/update.ts` β€” CLI verb handler, arg parsing, orchestration loop
+- **New:** `src/core/install/update.ts` β€” core update logic (detect β†’ plan β†’ compare β†’ apply β†’ verify)
+- **New:** `tests/cli/update.test.ts`
+- **New:** `tests/core/install/update.test.ts`
+- **Modify:** `src/cli/main.ts` β€” register `update` subcommand
+- **Modify:** `CHANGELOG.md` β€” v0.10.12 entry
+
+### Design decisions
+
+- **Reuse InstallAdapter machinery entirely.** No new adapter interface, no new registry. The update logic is orchestration over existing `detect/plan/apply/verify`.
+- **Payload comparison via sidecar manifest.** The `install.lock.json` already stores `applied_at`, `operation`, `owned_keys`, `owned_paths`. We extend it with an additive `payload_hash` field (sha256 of the canonical McpPayload JSON) so update can skip unchanged targets without re-applying. This is backward-compatible: entries without `payload_hash` are treated as "unknown β€” apply on first update run", and the hash is written after the first successful update.
+- **Sequential, not parallel.** Runtimes share filesystem state (the vault, the skill symlinks). Sequential execution avoids race conditions. The total time is still sub-second for most setups.
+- **`--force` bypasses payload hash check.** Useful when operator knows the payload changed but the hash didn't (e.g., env variable update that doesn't affect the McpPayload struct but affects runtime behavior).
+
+---
+
+## Feature 2: Weekly Brain Digest
+
+### What it does
+
+Extends `brain_digest` to accept a `--window` parameter for arbitrary time windows (e.g., `7d`, `14d`, `30d`). Adds a weekly cron job that delivers a 7-day digest every Monday morning.
+
+### CLI surface
+
+```bash
+# Default: 24h (unchanged)
+o2b brain digest
+
+# Weekly window
+o2b brain digest --window 7d
+
+# Custom window
+o2b brain digest --window 14d
+
+# JSON output
+o2b brain digest --window 7d --json
+```
+
+### Window parser
+
+Accepts `Nd` format where N is a positive integer (e.g., `1d`, `7d`, `14d`, `30d`). Bare integers without `d` suffix are also accepted (e.g., `7` β†’ 7 days). Invalid format or non-positive values β†’ exit 2 with error message.
+
+### Digest content (weekly mode)
+
+Same sections as daily, but over the 7-day window:
+
+1. **New confirmed rules** β€” preferences with `confirmed_at` inside the window
+2. **Confidence downshifts** β€” rules whose confidence_band dropped during the window
+3. **Top-5 most-applied** β€” by evidence-application count within the window
+4. **Agent quality summary** β€” per-agent breakdown:
+ - Total brain-events (feedback + apply-evidence + note)
+ - Breakdown by event type
+ - How many events led to confirmed rules in the same window
+ - How many events led to retired rules in the same window
+
+### Agent quality summary implementation
+
+Read `Brain/log/<date>.md` (or `.jsonl`) for all dates in the window. Group events by `agent` field. For each agent:
+
+- Count events by type (`feedback`, `apply-evidence`, `note`)
+- Cross-reference with `Brain/preferences/` β€” count preferences whose `confirmed_at` falls in the window AND whose first `applied` event matches this agent (via `evidenced_by` wikilink or log entry `preference` field)
+- Cross-reference with `Brain/retired/` β€” count retirements in window traceable to this agent's signals
+
+### Cron integration
+
+**Parameterize `bin/o2b-discipline-report`:**
+
+Add `--window` flag to the script. When set, it calls `o2b brain digest --window <value>` instead of the daily discipline report.
+
+**New install verb:**
+
+```bash
+o2b discipline install --weekly --telegram-target telegram:-100<chat>:<topic> --at "59 8 * * 1"
+```
+
+Creates a second Hermes cron job (separate from daily) with:
+- `name: "osb-weekly-brain-digest"`
+- `script: "bin/o2b-discipline-report --window 7d"`
+- `schedule: "59 8 * * 1"` (Monday 08:59 UTC β€” Monday morning in Europe/Belgrade)
+
+### File changes
+
+- **Modify:** `src/core/brain/digest.ts` β€” accept `windowDays` parameter in `RenderDigestOptions`; adjust `since` calculation; add agent quality summary section to Markdown/JSON output
+- **Modify:** `src/cli/brain/verbs/digest.ts` β€” parse `--window` flag
+- **Modify:** `bin/o2b-discipline-report` β€” accept `--window` flag, route to `o2b brain digest --window`
+- **Modify:** `src/cli/discipline-install.ts` β€” add `--weekly` flag to install verb
+- **New:** `src/core/brain/digest-agent-summary.ts` β€” agent quality summary computation (pure read over Brain/log/)
+- **New:** `tests/core/brain/digest-window.test.ts`
+- **New:** `tests/core/brain/digest-agent-summary.test.ts`
+- **Modify:** `CHANGELOG.md`
+
+### Design decisions
+
+- **`--window` not `--weekly`.** More general β€” operator can request any window. `--weekly` would lock us into a boolean.
+- **Agent quality in the digest core, not discipline.** Discipline report is about "is the agent writing to Brain at all". Digest is about "what changed in Brain". Agent quality summary belongs in digest because it references confirmed/retired rules, not just event counts.
+- **Graceful degradation.** If log files are missing for some days in the window, the digest still renders with available data. No crash on partial data.
+
+---
+
+## Feature 3: Cursor SQLite Deep Parsing
+
+### What it does
+
+Replace the mtime-only probe for Cursor transcripts with actual SQLite parsing. Returns the number of unique sessions and total message count for the day.
+
+### Data extracted
+
+From `state.vscdb`:
+- **Session count** β€” number of unique `sessionId` values with activity in the day window
+- **Message count** β€” total number of messages/turns across all sessions in the window
+
+No per-turn timestamps stored or returned. Just aggregate counts.
+
+### SQLite schema assumption
+
+Cursor uses the standard VSCode-derived `state.vscdb` with a `ItemTable` containing `key` and `value` columns. Session data is stored as JSON in the `value` column under keys like `sessionData.<sessionId>`.
+
+The query pattern:
+```sql
+SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'
+```
+
+Parse the JSON value to extract message count and session timestamps.
+
+**Important:** The exact schema may vary between Cursor versions. The implementation must:
+1. Try the known schema first
+2. If the query fails (SQL error, missing table, locked database), fall back to the mtime probe and log a warning to stderr
+3. If the query returns rows but the JSON structure is unexpected, fall back to mtime and log a warning
+4. Never crash the discipline report β€” all SQLite errors are caught and degraded gracefully
+
+### File changes
+
+- **Modify:** `src/core/discipline/transcripts/cursor.ts` β€” replace mtime probe with SQLite parsing
+- **Modify:** `src/core/discipline/transcripts/types.ts` β€” extend `TranscriptRuntime` return type to include session/message counts (or use a new result type)
+- **Modify:** `src/core/discipline/transcripts/index.ts` β€” handle new result shape
+- **New:** `tests/core/discipline/transcripts/cursor-sqlite.test.ts`
+- **Modify:** `CHANGELOG.md`
+
+### Design decisions
+
+- **`bun:sqlite` only.** Already in the stack. No new dependencies.
+- **Fallback to mtime on any SQLite error.** If the schema changed, the database is locked, or permissions are wrong, we degrade gracefully to the old mtime behavior.
+- **Isolated in one file.** No changes to other transcript resolvers (Claude Code, Codex).
+
+---
+
+## Feature 4: Obsidian Deep-Link in Explorer
+
+### What it does
+
+Double-click on a node in live-mode `o2b brain explorer` opens the corresponding `pref-X.md` file directly in Obsidian via `obsidian://open?path=<absolute_path>`.
+
+### Implementation
+
+1. **Server-side:** `buildLiveServer` passes `vaultPath` to the HTML template via a new placeholder `__VAULT_PATH__` (similar to `__GRAPH_JSON__`).
+2. **Template:** Add `__VAULT_PATH__` placeholder and ~30 lines of JS:
+ - On double-click of a canvas node or listbox item
+ - Construct `obsidian://open?path=${encodeURIComponent(absolutePath)}`
+ - Attempt to open via `window.open(uri, '_blank')`
+ - Fallback: copy absolute path to clipboard + show tooltip "Obsidian not detected β€” path copied"
+
+3. **Path construction:** `<vaultPath>/Brain/preferences/pref-<id>.md`
+
+Only active in live-mode. Export-mode has no vault path, so no deep-link.
+
+### File changes
+
+- **Modify:** `src/core/brain/explorer.ts` β€” pass `vaultPath` to template in live server mode
+- **Modify:** `templates/brain-explorer.html` β€” add `__VAULT_PATH__` placeholder + double-click handler
+- **New:** `tests/core/brain/explorer-deeplink.test.ts`
+- **Modify:** `CHANGELOG.md`
+
+### Design decisions
+
+- **`path=` not `vault=`.** `obsidian://open?path=<absolute>` works regardless of how the vault is registered in Obsidian. `vault=<name>` requires the vault name to match Obsidian's registered name, which may differ from the directory basename.
+- **Silent fallback.** If `window.open` doesn't trigger Obsidian (not installed, blocked by browser), copy path to clipboard and show a brief tooltip. No modal dialogs.
+- **No server-side code for the fallback.** Pure client-side JS. The server only provides the vault path.
+
+---
+
+## Cross-Cutting Concerns
+
+### Testing strategy
+
+- All new core logic has unit tests
+- CLI verbs tested via synthetic argv
+- SQLite parsing tested with a mock `state.vscdb` fixture
+- Explorer deep-link tested via template substitution unit test (no browser automation needed)
+
+### Backward compatibility
+
+- `o2b brain digest` without `--window` behaves identically to current (24h default)
+- `o2b update` is a new verb β€” no existing behavior changed
+- Cursor transcript fallback ensures no regression for users with incompatible Cursor versions
+- Explorer deep-link only adds behavior β€” existing click/keyboard interaction unchanged
+
+### Version bump
+
+- `package.json` version β†’ `0.10.12`
+- `CHANGELOG.md` entry with all four features
+
+---
+
+## Deferred Items (update _summary.md)
+
+Add to the Deferred work section:
+
+- **Β§25 Window-triggers for Hermes cron.** Weekly digest relies on standard cron scheduling. If VPS is offline during the Monday window, the digest is skipped. Window-trigger support (fire-on-next-boot-after-missed-window) is a Hermes-side feature, not OSB-core. Track separately.
+- **Β§14 Obsidian deep-link β€” export mode.** Static export cannot provide vault path, so deep-link is live-mode only. If operators request deep-link in exported HTML, we would need to embed vault path at export time (operator provides `--vault-path` flag). Trigger: explicit request.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 09ec19f6..bd0ce65a 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.11",
+ "version": "0.10.12",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index a955a224..745d28a5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.10.11",
+ "version": "0.10.12",
"type": "module",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
diff --git a/plugin.yaml b/plugin.yaml
index 79b749e1..f0a82acd 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.11"
+version: "0.10.12"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 7e1f78f3..e48f48f3 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.11",
+ "version": "0.10.12",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 0ac03be7..1cd2b7f4 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.10.11"
+version: "0.10.12"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index d5e37ee1..60af9b6b 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.11"
+version = "0.10.12"
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.ts
index a0899ee2..e79aa985 100644
--- a/scripts/discipline-report.ts
+++ b/scripts/discipline-report.ts
@@ -1,31 +1,50 @@
#!/usr/bin/env -S bun
import { resolveVault } from "../src/core/config.ts";
import { runDisciplineReport } from "../src/core/discipline/report.ts";
+import { renderDigest } from "../src/core/brain/digest.ts";
+import { parseWindow } from "../src/cli/brain/verbs/digest.ts";
-function readVaultArg(): string {
+function parseArgs(): { vault: string; window: string | null } {
const argv = process.argv.slice(2);
+ let vault: string | undefined;
+ let window: string | null = null;
for (let i = 0; i < argv.length; i++) {
- if (argv[i] === "--vault" && argv[i + 1]) return argv[i + 1]!;
+ if (argv[i] === "--vault" && argv[i + 1]) {
+ vault = argv[++i]!;
+ } else if (argv[i] === "--window" && argv[i + 1]) {
+ window = argv[++i]!;
+ }
}
- // 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();
+ const v = vault ?? 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;
+ return { vault: v, window };
}
-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);
+const { vault, window } = parseArgs();
+
+if (window) {
+ let days: number;
+ try {
+ days = parseWindow(window);
+ } catch (e) {
+ process.stderr.write(`o2b-discipline-report: invalid --window: ${window}\n`);
+ process.exit(2);
+ }
+ const now = new Date();
+ const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
+ const result = renderDigest(vault, { since, until: now, format: "markdown" });
+ process.stdout.write(result.content);
+ if (!result.content.endsWith("\n")) process.stdout.write("\n");
+} else {
+ 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");
}
-process.stdout.write(res.text + "\n");
diff --git a/src/cli/brain/verbs/digest.ts b/src/cli/brain/verbs/digest.ts
index aac36387..cae5f15f 100644
--- a/src/cli/brain/verbs/digest.ts
+++ b/src/cli/brain/verbs/digest.ts
@@ -2,11 +2,20 @@ import { defaultConfigPath } from "../../../core/config.ts";
import { renderDigest, type RenderDigestOptions } from "../../../core/brain/digest.ts";
import { parse, fail, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";
+export function parseWindow(raw: string): number {
+ const m = /^(\d+)(?:d)?$/.exec(raw);
+ if (!m) throw new Error(`invalid --window value: ${raw} (expected Nd or N, e.g. 7d)`);
+ const n = parseInt(m[1]!, 10);
+ if (n <= 0) throw new Error(`invalid --window value: ${raw} (must be positive)`);
+ return n;
+}
+
export async function cmdBrainDigest(argv: string[]): Promise<number> {
const { flags } = parse(argv, {
vault: { type: "string" },
since: { type: "string" },
until: { type: "string" },
+ window: { type: "string" },
json: { type: "boolean" },
"silent-if-empty": { type: "boolean" },
});
@@ -29,6 +38,20 @@ export async function cmdBrainDigest(argv: string[]): Promise<number> {
if (!Number.isFinite(d.getTime())) return fail(`--until must be a valid ISO-8601 timestamp; got ${raw}`);
untilDate = d;
}
+ if (flags["window"]) {
+ if (flags["since"]) {
+ return fail("--since and --window are mutually exclusive");
+ }
+ let windowDays: number;
+ try {
+ windowDays = parseWindow(String(flags["window"]));
+ } catch (e) {
+ process.stderr.write(`error: ${(e as Error).message}\n`);
+ return 2;
+ }
+ const until = untilDate ?? new Date();
+ sinceDate = new Date(until.getTime() - windowDays * 24 * 60 * 60 * 1000);
+ }
const opts: RenderDigestOptions = {
...(sinceDate ? { since: sinceDate } : {}),
...(untilDate ? { until: untilDate } : {}),
diff --git a/src/cli/discipline-install.ts b/src/cli/discipline-install.ts
index bcb1c076..6e533024 100644
--- a/src/cli/discipline-install.ts
+++ b/src/cli/discipline-install.ts
@@ -40,6 +40,19 @@ function jobId(vault: string): string {
return `osb-discipline-report-${slug}`;
}
+function weeklyJobId(vault: string): string {
+ const slug = createHash("sha256")
+ .update(resolve(vault) + ":weekly")
+ .digest("hex")
+ .slice(0, 12);
+ return `osb-weekly-brain-digest-${slug}`;
+}
+
+function weeklyScriptPath(vault: string): string {
+ const escaped = vault.replace(/\\/g, "\\\\").replace(/'/g, "'\\''");
+ return scriptPath() + " --window 7d --vault '" + escaped + "'";
+}
+
interface HermesJob {
id: string;
name: string;
@@ -93,21 +106,31 @@ export async function disciplineInstallVerb(
let vault = pickVault(args, defaultVault);
let telegramTarget = "";
let at = "59 4 * * *";
+ let atProvided = false;
+ let weekly = false;
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] === "--weekly") {
+ weekly = true;
+ continue;
+ }
if (args[i] === "--telegram-target") {
telegramTarget = args[++i] ?? "";
continue;
}
if (args[i] === "--at") {
at = args[++i] ?? at;
+ atProvided = true;
continue;
}
}
+ if (weekly && !atProvided) {
+ at = "59 8 * * 1";
+ }
if (!vault) {
process.stderr.write("o2b discipline install: --vault is required\n");
return 2;
@@ -124,14 +147,18 @@ export async function disciplineInstallVerb(
}
const file = jobsFilePath();
const data = loadJobs(file);
- const id = jobId(vault);
+ const id = weekly ? weeklyJobId(vault) : jobId(vault);
const existing = data.jobs.find((j) => j.id === id);
const next: HermesJob = {
id,
- name: "osb-discipline-report",
- script: scriptPath(),
+ name: weekly ? "osb-weekly-brain-digest" : "osb-discipline-report",
+ script: weekly ? weeklyScriptPath(vault) : scriptPath(),
no_agent: true,
- schedule: { kind: "cron", expr: at, display: at },
+ schedule: {
+ kind: "cron",
+ expr: at,
+ display: at,
+ },
deliver: telegramTarget,
enabled: true,
};
@@ -151,7 +178,16 @@ export async function disciplineUninstallVerb(
args: string[],
defaultVault: string,
): Promise<number> {
- const vault = pickVault(args, defaultVault);
+ let vault: string | undefined;
+ let weekly = false;
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === "--vault" && i + 1 < args.length) {
+ vault = args[++i];
+ } else if (args[i] === "--weekly") {
+ weekly = true;
+ }
+ }
+ vault = vault ?? defaultVault;
if (!vault) {
process.stderr.write(
"o2b discipline uninstall: --vault is required\n",
@@ -160,13 +196,13 @@ export async function disciplineUninstallVerb(
}
const file = jobsFilePath();
const data = loadJobs(file);
- const id = jobId(vault);
+ const ids = weekly ? [weeklyJobId(vault)] : [jobId(vault), weeklyJobId(vault)];
const before = data.jobs.length;
- data.jobs = data.jobs.filter((j) => j.id !== id);
+ data.jobs = data.jobs.filter((j) => !ids.includes(j.id));
saveJobs(file, data);
const removed = before - data.jobs.length;
process.stdout.write(
- `o2b discipline: ${removed > 0 ? "removed" : "no-op"} (job '${id}')\n`,
+ `o2b discipline: ${removed > 0 ? "removed" : "no-op"} (job '${ids.join("', '")}')\n`,
);
return 0;
}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index ad6ee18b..fd3aa9a7 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -54,6 +54,7 @@ import {
renderUninstallResult,
uninstallCli,
} from "./install-cli.ts";
+import { cmdUpdate } from "./update.ts";
import { planUninstall, renderPlan } from "./uninstall.ts";
import { cmdInstall } from "./install/install.ts";
import { cmdUninstallTarget } from "./install/uninstall-target.ts";
@@ -531,6 +532,7 @@ Commands:
mcp Run the optional MCP tool server (stdio JSON-RPC)
install-cli Create symlinks for o2b and vault-log in ~/.local/bin
install Multi-runtime install orchestrator (v0.10.11) β€” detect / plan / apply / --check (see install/)
+ update Update OSB installation across all detected runtimes
uninstall Print an uninstall plan; --target X removes a per-runtime install
tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout
@@ -627,6 +629,8 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
return await cmdInstallCli(rest);
case "install":
return await cmdInstall(rest);
+ case "update":
+ return await cmdUpdate(rest);
case "uninstall":
return await cmdUninstall(rest);
case "tool-call":
diff --git a/src/cli/update.ts b/src/cli/update.ts
new file mode 100644
index 00000000..456805b4
--- /dev/null
+++ b/src/cli/update.ts
@@ -0,0 +1,159 @@
+/**
+ * `o2b update` CLI verb.
+ *
+ * Exit codes:
+ * 0 all targets updated or up-to-date
+ * 1 runtime error
+ * 2 usage error
+ * 3 drift detected after update
+ * 4 user-modified-block conflict (use `--force` to override)
+ */
+
+import { homedir } from "node:os";
+
+import { parseFlags } from "./argparse.ts";
+import { defaultConfigPath, discoverConfig, resolveVault } from "../core/config.ts";
+import { defaultRegistry } from "../core/install/registry.ts";
+import "../core/install/adapters/aider.ts";
+import "../core/install/adapters/copilot-cli.ts";
+import "../core/install/adapters/cursor.ts";
+import "../core/install/adapters/gemini-cli.ts";
+import "../core/install/adapters/generic.ts";
+import "../core/install/adapters/kiro.ts";
+import "../core/install/adapters/opencode.ts";
+import "../core/install/adapters/pi.ts";
+
+import { runUpdate, type UpdateResult, type UpdateTargetResult } from "../core/install/update.ts";
+import type { InstallEnv, VerifyResult } from "../core/install/types.ts";
+
+interface ParsedUpdateArgs {
+ readonly target: string | null;
+ readonly dryRun: boolean;
+ readonly force: boolean;
+ readonly json: boolean;
+}
+
+export function parseUpdateArgs(argv: string[]): ParsedUpdateArgs {
+ const { flags } = parseFlags(argv, {
+ target: { type: "string" },
+ "dry-run": { type: "boolean" },
+ force: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ return {
+ target: (flags["target"] as string | undefined) ?? null,
+ dryRun: Boolean(flags["dry-run"]),
+ force: Boolean(flags["force"]),
+ json: Boolean(flags["json"]),
+ };
+}
+
+function buildEnv(): InstallEnv {
+ const cfg = discoverConfig(defaultConfigPath()).data;
+ const vault = resolveVault() ?? "";
+ const env = { ...process.env } as Record<string, string>;
+ if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];
+ if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];
+ return { vault, home: homedir(), cwd: process.cwd(), env, now: new Date() };
+}
+
+function statusIcon(status: UpdateTargetResult["status"]): string {
+ switch (status) {
+ case "applied":
+ return "βœ“";
+ case "up-to-date":
+ return "=";
+ case "skipped":
+ return "β—‹";
+ case "would-apply":
+ return "~";
+ case "error":
+ return "βœ—";
+ default:
+ return "?";
+ }
+}
+
+function renderResult(result: UpdateResult, json: boolean): void {
+ if (json) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return;
+ }
+
+ for (const t of result.targets) {
+ process.stdout.write(`${statusIcon(t.status)} ${t.target}`);
+ if (t.reason) process.stdout.write(` β€” ${t.reason}`);
+ if (t.error) process.stdout.write(` β€” ERROR: ${t.error}`);
+ if (t.hint) process.stdout.write(`\n hint: ${t.hint}`);
+ if (t.postNotes && t.postNotes.length > 0) {
+ for (const note of t.postNotes) process.stdout.write(`\n β†’ ${note}`);
+ }
+ process.stdout.write("\n");
+ }
+
+ const applied = result.targets.filter((t) => t.status === "applied").length;
+ const upToDate = result.targets.filter((t) => t.status === "up-to-date").length;
+ const skipped = result.targets.filter((t) => t.status === "skipped").length;
+ const errors = result.targets.filter((t) => t.status === "error").length;
+ process.stdout.write(`\n${applied} applied, ${upToDate} up-to-date, ${skipped} skipped`);
+ if (errors > 0) process.stdout.write(`, ${errors} errors`);
+ process.stdout.write("\n");
+}
+
+export async function cmdUpdate(argv: string[]): Promise<number> {
+ let args: ParsedUpdateArgs;
+ try {
+ args = parseUpdateArgs(argv);
+ } catch (exc) {
+ process.stderr.write(`error: ${(exc as Error).message}\n`);
+ return 2;
+ }
+
+ const env = buildEnv();
+ if (!env.vault) {
+ process.stderr.write("error: vault not configured. Set VAULT_DIR or run `o2b init`.\n");
+ return 2;
+ }
+
+ if (args.target && !defaultRegistry.get(args.target)) {
+ process.stderr.write(
+ `error: unknown --target: ${args.target}. ` +
+ `Available: ${defaultRegistry.targets().join(", ")}\n`,
+ );
+ return 2;
+ }
+
+ const result = runUpdate(defaultRegistry, env, {
+ dryRun: args.dryRun,
+ force: args.force,
+ target: args.target,
+ });
+
+ renderResult(result, args.json);
+
+ if (!args.dryRun) {
+ const targets = args.target ? [defaultRegistry.get(args.target)!] : defaultRegistry.list();
+ const verifyResults: VerifyResult[] = [];
+ for (const adapter of targets) {
+ if (adapter.detect(env).status === "installed") {
+ verifyResults.push(adapter.verify(env));
+ }
+ }
+ const drift = verifyResults.some((r) => r.status === "drift");
+ if (drift) {
+ process.stderr.write(
+ "\nwarning: drift detected after update. Run `o2b install --check` for details.\n",
+ );
+ return 3;
+ }
+ }
+
+ const hasError = result.targets.some((t) => t.status === "error");
+ if (hasError) {
+ const hasUserModifiedBlock = result.targets.some(
+ (t) => t.kind === "user-modified-block",
+ );
+ return hasUserModifiedBlock ? 4 : 1;
+ }
+ return 0;
+}
diff --git a/src/core/brain/digest-agent-summary.ts b/src/core/brain/digest-agent-summary.ts
new file mode 100644
index 00000000..b4f68292
--- /dev/null
+++ b/src/core/brain/digest-agent-summary.ts
@@ -0,0 +1,210 @@
+/**
+ * Agent quality summary for the brain digest.
+ *
+ * Groups Brain/log events by agent within the given window and returns
+ * per-agent counts: total events, breakdown by type (feedback /
+ * apply-evidence / note), and attribution to confirmed/retired rules.
+ */
+
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "./paths.ts";
+import { parseLogDay, type BrainLogEntry } from "./log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+
+export interface AgentSummaryEntry {
+ readonly agent: string;
+ readonly total_events: number;
+ readonly feedback_count: number;
+ readonly apply_evidence_count: number;
+ readonly note_count: number;
+ readonly confirmed_attributed: number;
+ readonly retired_attributed: number;
+}
+
+interface AgentAccumulator {
+ agent: string;
+ total_events: number;
+ feedback_count: number;
+ apply_evidence_count: number;
+ note_count: number;
+ confirmed_attributed: number;
+ retired_attributed: number;
+}
+
+export function computeAgentSummary(
+ vault: string,
+ since: Date,
+ until: Date,
+): ReadonlyArray<AgentSummaryEntry> {
+ const logs = readLogsInWindow(vault, since, until);
+ const byAgent = new Map<string, AgentAccumulator>();
+
+ for (const entry of logs) {
+ const agent = getEntryAgent(entry);
+ let acc = byAgent.get(agent);
+ if (!acc) {
+ acc = {
+ agent,
+ total_events: 0,
+ feedback_count: 0,
+ apply_evidence_count: 0,
+ note_count: 0,
+ confirmed_attributed: 0,
+ retired_attributed: 0,
+ };
+ byAgent.set(agent, acc);
+ }
+ acc.total_events++;
+ switch (entry.eventType) {
+ case BRAIN_LOG_EVENT_KIND.feedback:
+ acc.feedback_count++;
+ break;
+ case BRAIN_LOG_EVENT_KIND.applyEvidence:
+ acc.apply_evidence_count++;
+ break;
+ case BRAIN_LOG_EVENT_KIND.note:
+ acc.note_count++;
+ break;
+ }
+ }
+
+ const seenPrefs = new Set<string>();
+ const prefFirstAgent = new Map<string, string>();
+
+ for (const entry of logs) {
+ const agent = getEntryAgent(entry);
+ const pref = entry.body["preference"];
+ if (typeof pref !== "string") continue;
+ const prefId = extractPrefId(pref);
+ if (!prefId) continue;
+
+ if (!prefFirstAgent.has(prefId)) {
+ prefFirstAgent.set(prefId, agent);
+ }
+ }
+
+ for (const entry of logs) {
+ const agent = getEntryAgent(entry);
+ const acc = byAgent.get(agent);
+ if (!acc) continue;
+
+ const pref = entry.body["preference"];
+ if (typeof pref !== "string") continue;
+ const prefId = extractPrefId(pref);
+ if (!prefId) continue;
+
+ const key = `${agent}:${prefId}`;
+ if (seenPrefs.has(key)) continue;
+
+ const firstAgent = prefFirstAgent.get(prefId);
+ if (firstAgent !== agent) continue;
+
+ seenPrefs.add(key);
+
+ const confirmedAt = getConfirmedAt(vault, prefId);
+ const retiredAt = getRetiredAt(vault, prefId);
+
+ if (confirmedAt && isInWindow(confirmedAt, since, until)) {
+ acc.confirmed_attributed++;
+ }
+ if (retiredAt && isInWindow(retiredAt, since, until)) {
+ acc.retired_attributed++;
+ }
+ }
+
+ return [...byAgent.values()].sort((a, b) => {
+ const diff = b.total_events - a.total_events;
+ return diff !== 0 ? diff : a.agent.localeCompare(b.agent);
+ });
+}
+
+function readLogsInWindow(
+ vault: string,
+ since: Date,
+ until: Date,
+): BrainLogEntry[] {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.log)) return [];
+ const sinceIso = since.toISOString();
+ const untilIso = until.toISOString();
+ const sinceDay = sinceIso.slice(0, 10);
+ const untilDay = untilIso.slice(0, 10);
+ const out: BrainLogEntry[] = [];
+ const dates = readdirSync(dirs.log, { withFileTypes: true })
+ .filter((d) => d.isFile() && d.name.endsWith(".md"))
+ .map((d) => d.name.slice(0, -3))
+ .filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n))
+ .sort();
+ for (const date of dates) {
+ if (date < addDays(sinceDay, -1)) continue;
+ if (date > addDays(untilDay, 1)) continue;
+ const { entries } = parseLogDay(vault, date);
+ for (const e of entries) {
+ if (e.timestamp >= sinceIso && e.timestamp < untilIso) {
+ out.push(e);
+ }
+ }
+ }
+ out.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
+ return out;
+}
+
+function addDays(day: string, delta: number): string {
+ const t = Date.parse(`${day}T00:00:00Z`);
+ if (!Number.isFinite(t)) return day;
+ return new Date(t + delta * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
+}
+
+function extractPrefId(raw: string): string | null {
+ const m = /\[\[([^\]|#]+)/.exec(raw);
+ if (m) return m[1]!.trim();
+ if (raw.startsWith("pref-")) return raw;
+ return null;
+}
+
+function getEntryAgent(entry: BrainLogEntry): string {
+ const runtimeAgent = entry.agent;
+ if (typeof runtimeAgent === "string" && runtimeAgent.trim() !== "") {
+ return runtimeAgent;
+ }
+ const bodyAgent = entry.body["agent"];
+ if (typeof bodyAgent === "string" && bodyAgent.trim() !== "") {
+ return bodyAgent;
+ }
+ return "unknown";
+}
+
+function getConfirmedAt(vault: string, prefId: string): string | null {
+ const dirs = brainDirs(vault);
+ const path = join(dirs.preferences, `${prefId}.md`);
+ if (!existsSync(path)) return null;
+ try {
+ const text = readFileSync(path, "utf8");
+ const m = /^confirmed_at:\s*(.+)$/m.exec(text);
+ return m ? m[1]!.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
+function getRetiredAt(vault: string, prefId: string): string | null {
+ const dirs = brainDirs(vault);
+ const retiredId = prefId.replace("pref-", "ret-");
+ const path = join(dirs.retired, `${retiredId}.md`);
+ if (!existsSync(path)) return null;
+ try {
+ const text = readFileSync(path, "utf8");
+ const m = /^retired_at:\s*(.+)$/m.exec(text);
+ return m ? m[1]!.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
+function isInWindow(iso: string, since: Date, until: Date): boolean {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return false;
+ return t >= since.getTime() && t < until.getTime();
+}
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index 87850875..6d3f754a 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -39,6 +39,7 @@ import { existsSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { backlinkCount, buildBacklinkIndex } from "./backlinks.ts";
+import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";
import { findMergeCandidates } from "./merge-candidates.ts";
import { computeMostApplied } from "./most-applied.ts";
import { brainDirs, vaultRelative } from "./paths.ts";
@@ -190,6 +191,16 @@ export interface DigestJsonMostApplied {
readonly entries: ReadonlyArray<DigestJsonMostAppliedEntry>;
}
+export interface DigestJsonAgentSummary {
+ readonly agent: string;
+ readonly total_events: number;
+ readonly feedback_count: number;
+ readonly apply_evidence_count: number;
+ readonly note_count: number;
+ readonly confirmed_attributed: number;
+ readonly retired_attributed: number;
+}
+
/**
* Near-duplicate pair surfaced for operator review. Detected by
* `findMergeCandidates`. Reflects current vault state, not windowed
@@ -225,6 +236,7 @@ export interface DigestJson {
readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;
+ readonly agent_summary: ReadonlyArray<DigestJsonAgentSummary>;
/**
* Window-scoped most-applied list (v0.10.11). Mirrors the
* `Most-applied (Nd)` section of `Brain/active.md` and uses the
@@ -284,6 +296,7 @@ export function renderDigest(
top_applied: data.top_applied,
top_referenced: data.top_referenced,
merge_suggestions: data.merge_suggestions,
+ agent_summary: data.agent_summary,
most_applied: data.most_applied,
};
return Object.freeze({
@@ -310,6 +323,7 @@ interface DigestData {
readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;
readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;
readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;
+ readonly agent_summary: ReadonlyArray<AgentSummaryEntry>;
readonly most_applied: DigestJsonMostApplied;
}
@@ -416,6 +430,8 @@ function collectDigestData(
jaccard: c.jaccard,
}));
+ const agent_summary = computeAgentSummary(vault, since, until);
+
// Most-applied (Nd) β€” mirrors the section in `Brain/active.md`.
// The window length / limit come from `_brain.yaml`; a corrupted
// config falls back to defaults so the digest never breaks on
@@ -463,6 +479,7 @@ function collectDigestData(
top_applied,
top_referenced,
merge_suggestions,
+ agent_summary,
most_applied,
};
}
@@ -527,10 +544,8 @@ function isEmpty(data: DigestData): boolean {
data.retired.length === 0 &&
data.confidence_shifts.length === 0 &&
data.contradictions.length === 0 &&
- // most_applied is windowed β€” entries imply real activity that the
- // operator wants to see in the daily digest even when nothing else
- // changed (v0.10.11).
- data.most_applied.entries.length === 0
+ data.most_applied.entries.length === 0 &&
+ data.agent_summary.length === 0
);
}
@@ -852,6 +867,20 @@ function renderMarkdown(
}
lines.push("");
}
+ if (data.agent_summary.length > 0) {
+ lines.push(`## Agent summary (${data.agent_summary.length})`, "");
+ for (const item of data.agent_summary) {
+ const parts = [
+ `**${item.agent}**`,
+ `${item.total_events} events`,
+ `(feedback: ${item.feedback_count}, apply: ${item.apply_evidence_count}, note: ${item.note_count})`,
+ ];
+ if (item.confirmed_attributed > 0) parts.push(`β†’ ${item.confirmed_attributed} confirmed`);
+ if (item.retired_attributed > 0) parts.push(`β†’ ${item.retired_attributed} retired`);
+ lines.push(`- ${parts.join(" ")}`);
+ }
+ lines.push("");
+ }
if (data.top_applied.length > 0) {
lines.push(`## Top applied (${data.top_applied.length})`, "");
for (const item of data.top_applied) {
@@ -912,4 +941,3 @@ function renderMarkdown(
return lines.join("\n").replace(/\n+$/, "\n");
}
-
diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.ts
index fdbdc13d..0d081737 100644
--- a/src/core/brain/explorer.ts
+++ b/src/core/brain/explorer.ts
@@ -232,6 +232,7 @@ const TEMPLATE_PATH = resolve(
* surfaces immediately instead of producing a half-rendered HTML file.
*/
const PLACEHOLDER = "__GRAPH_JSON__";
+const VAULT_PATH_PLACEHOLDER = "__VAULT_PATH__";
let templateCache: string | undefined;
@@ -272,7 +273,10 @@ function loadTemplate(): string {
* / `$1` injection through the JSON body (principle bodies are free
* text and may contain `$`).
*/
-export function renderExportedHtml(graph: ExplorerGraph): string {
+export function renderExportedHtml(
+ graph: ExplorerGraph,
+ vaultPath?: string,
+): string {
const json = JSON.stringify(graph).replace(/[<>&]/g, (c) => {
switch (c) {
case "<":
@@ -285,7 +289,16 @@ export function renderExportedHtml(graph: ExplorerGraph): string {
return c;
}
});
- return loadTemplate().replace(PLACEHOLDER, () => json);
+ let html = loadTemplate().replace(PLACEHOLDER, () => json);
+ if (vaultPath) {
+ html = html.replace(
+ VAULT_PATH_PLACEHOLDER,
+ JSON.stringify(vaultPath).slice(1, -1).replace(/\//g, "\\/"),
+ );
+ } else {
+ html = html.replace(VAULT_PATH_PLACEHOLDER, "");
+ }
+ return html;
}
/** Test-only escape hatch: forget the cached template body. */
@@ -319,7 +332,7 @@ export function buildLiveServer(vault: string, port: number): LiveServerHandle {
const url = new URL(req.url);
if (url.pathname === "/" || url.pathname === "/index.html") {
const graph = collectExplorerData(vault);
- const html = renderExportedHtml(graph);
+ const html = renderExportedHtml(graph, vault);
return new Response(html, {
headers: { "content-type": "text/html; charset=utf-8" },
});
diff --git a/src/core/brain/log.ts b/src/core/brain/log.ts
index c19734b2..49fa47ab 100644
--- a/src/core/brain/log.ts
+++ b/src/core/brain/log.ts
@@ -58,6 +58,7 @@ export type BrainLogEntryPayload = Readonly<
export interface BrainLogEntry {
readonly timestamp: string;
readonly eventType: BrainLogEventKind;
+ readonly agent?: string;
readonly body: BrainLogEntryPayload;
}
@@ -193,6 +194,7 @@ export function parseLogDay(vault: string, date: string): ParseLogDayResult {
entries.push({
timestamp: `${validDate}T${hh}:${mm}:${ss}Z`,
eventType: kindStr as BrainLogEventKind,
+ agent: typeof payload.agent === "string" ? payload.agent : undefined,
body: Object.freeze(payload),
});
}
@@ -262,6 +264,13 @@ export function appendLogEvent(
const path = logPath(vault, ts.date);
const jsonlPath = logJsonlPath(vault, ts.date);
const logDir = brainDirs(vault).log;
+ const topLevelAgent = (event as { agent?: unknown }).agent;
+ const eventBody =
+ typeof topLevelAgent === "string" && typeof event.body["agent"] !== "string"
+ ? Object.freeze({ ...event.body, agent: topLevelAgent })
+ : event.body;
+ const diskEvent: BrainLogEntry =
+ eventBody === event.body ? event : { ...event, body: eventBody };
// Β§23 (v0.10.8): each event lands in both `<date>.jsonl` (machine
// surface, primary for `readLogDay`) and `<date>.md` (human-facing
@@ -284,7 +293,7 @@ export function appendLogEvent(
const existingJsonl = existsSync(jsonlPath)
? readFileSync(jsonlPath, "utf8")
: "";
- const line = renderJsonlLine(event);
+ const line = renderJsonlLine(diskEvent);
const nextJsonl =
existingJsonl === ""
? `${line}\n`
@@ -293,7 +302,7 @@ export function appendLogEvent(
// ---- Markdown (human surface) -------------------------------------
const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
- const block = renderEventBlock(event, ts.hms);
+ const block = renderEventBlock(diskEvent, ts.hms);
let next: string;
if (existing === "") {
diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.ts
index 7b542762..6d1d1ac2 100644
--- a/src/core/discipline/render.ts
+++ b/src/core/discipline/render.ts
@@ -55,8 +55,14 @@ export function renderReport(r: RenderInput): string {
const transcripts = r.activity.transcripts;
if (transcripts && transcripts.byRuntime.length > 0) {
const parts = transcripts.byRuntime
- .filter((b) => b.fileCount > 0)
- .map((b) => `${e(b.runtime)}: ${b.fileCount}`);
+ .filter((b) => b.fileCount > 0 || b.detail)
+ .map((b) => {
+ const base = `${e(b.runtime)}: ${b.fileCount}`;
+ if (b.detail) {
+ return `${base} \\(${b.detail.sessionCount} sessions, ${b.detail.messageCount} messages\\)`;
+ }
+ return base;
+ });
if (parts.length > 0) {
lines.push(`\\- transcripts β€” ${parts.join(", ")}`);
}
diff --git a/src/core/discipline/transcripts/cursor.ts b/src/core/discipline/transcripts/cursor.ts
index 53e2b039..6a76931d 100644
--- a/src/core/discipline/transcripts/cursor.ts
+++ b/src/core/discipline/transcripts/cursor.ts
@@ -5,14 +5,107 @@
* files. We probe both the Linux layout
* (`~/.config/Cursor/User/workspaceStorage/<hash>/state.vscdb`) and
* the macOS layout (under `~/Library/Application Support/Cursor/`).
- * v0.10.11 only checks file mtime; deeper SQLite parsing is deferred.
+ * collect() remains the mtime probe for backward compat; collectDetail()
+ * does a deeper SQLite parse when bun:sqlite is available.
*/
import { existsSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
-import type { TranscriptRuntime } from "./types.ts";
+import type { TranscriptDetail, TranscriptRuntime } from "./types.ts";
+
+function findDatabases(home: string): string[] {
+ const roots = [
+ join(home, ".config", "Cursor", "User", "workspaceStorage"),
+ join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),
+ // macOS XDG-style fallback used by some Cursor builds
+ join(home, ".cursor", "workspaceStorage"),
+ ];
+ const out: string[] = [];
+ for (const root of roots) {
+ if (!existsSync(root)) continue;
+ let dirs: import("node:fs").Dirent[];
+ try {
+ dirs = readdirSync(root, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const d of dirs) {
+ if (!d.isDirectory()) continue;
+ const db = join(root, d.name, "state.vscdb");
+ if (existsSync(db)) out.push(db);
+ }
+ }
+ return out;
+}
+
+function queryCursorDb(dbPath: string, dayStartMs: number, dayEndMs: number): TranscriptDetail | null {
+ let Database: typeof import("bun:sqlite").Database;
+ try {
+ Database = require("bun:sqlite").Database;
+ } catch {
+ return null;
+ }
+
+ let db: InstanceType<typeof Database>;
+ try {
+ db = new Database(dbPath, { readonly: true });
+ } catch {
+ return null;
+ }
+
+ try {
+ const rows = db
+ .query("SELECT key, value FROM ItemTable WHERE key LIKE 'sessionData.%'")
+ .all() as Array<{ key: string; value: string }>;
+
+ let sessionCount = 0;
+ let messageCount = 0;
+
+ for (const row of rows) {
+ try {
+ const data = JSON.parse(row.value);
+ const messages = data?.messages ?? data?.turns ?? data?.data?.messages;
+ if (Array.isArray(messages)) {
+ let hasActivityInWindow = false;
+ for (const msg of messages) {
+ const ts = msg?.timestamp ?? msg?.createdAt ?? msg?.created_at;
+ if (ts) {
+ const tsMs = typeof ts === "number" ? ts : Date.parse(ts);
+ if (Number.isFinite(tsMs) && tsMs >= dayStartMs && tsMs < dayEndMs) {
+ hasActivityInWindow = true;
+ }
+ }
+ }
+ if (hasActivityInWindow) {
+ sessionCount++;
+ for (const msg of messages) {
+ const ts = msg?.timestamp ?? msg?.createdAt ?? msg?.created_at;
+ if (ts) {
+ const tsMs = typeof ts === "number" ? ts : Date.parse(ts);
+ if (Number.isFinite(tsMs) && tsMs >= dayStartMs && tsMs < dayEndMs) {
+ messageCount++;
+ }
+ }
+ }
+ }
+ }
+ } catch {
+ // ignore malformed rows
+ }
+ }
+
+ if (sessionCount === 0 && messageCount === 0) return null;
+ return { sessionCount, messageCount };
+ } finally {
+ try {
+ db.close();
+ } catch {
+ // ignore close failures
+ }
+ }
+}
export const cursorTranscript: TranscriptRuntime = {
runtime: "cursor",
@@ -47,4 +140,24 @@ export const cursorTranscript: TranscriptRuntime = {
}
return out;
},
+ collectDetail(dayStartMs, dayEndMs, home = homedir()): TranscriptDetail | null {
+ const dbs = findDatabases(home);
+ let totalSessions = 0;
+ let totalMessages = 0;
+
+ for (const db of dbs) {
+ try {
+ const result = queryCursorDb(db, dayStartMs, dayEndMs);
+ if (result) {
+ totalSessions += result.sessionCount;
+ totalMessages += result.messageCount;
+ }
+ } catch {
+ // ignore unreadable dbs and keep probing the rest
+ }
+ }
+
+ if (totalSessions === 0) return null;
+ return { sessionCount: totalSessions, messageCount: totalMessages };
+ },
};
diff --git a/src/core/discipline/transcripts/index.ts b/src/core/discipline/transcripts/index.ts
index a6d4f551..0ee491e0 100644
--- a/src/core/discipline/transcripts/index.ts
+++ b/src/core/discipline/transcripts/index.ts
@@ -38,13 +38,14 @@ export function collectTranscriptActivity(
let total = 0;
for (const r of runtimes) {
const files = r.collect(opts.dayStartMs, opts.dayEndMs, opts.home);
+ const detail = r.collectDetail?.(opts.dayStartMs, opts.dayEndMs, opts.home) ?? null;
byRuntime.push({
runtime: r.runtime,
fileCount: files.length,
agentHint: r.agentHint,
+ ...(detail ? { detail } : {}),
});
total += files.length;
}
return { byRuntime, totalFiles: total };
}
-
diff --git a/src/core/discipline/transcripts/types.ts b/src/core/discipline/transcripts/types.ts
index 5815ac61..6adfc09d 100644
--- a/src/core/discipline/transcripts/types.ts
+++ b/src/core/discipline/transcripts/types.ts
@@ -21,12 +21,19 @@ export interface TranscriptRuntime {
* `home` is injectable for tests.
*/
collect(dayStartMs: number, dayEndMs: number, home?: string): string[];
+ collectDetail?(dayStartMs: number, dayEndMs: number, home?: string): TranscriptDetail | null;
+}
+
+export interface TranscriptDetail {
+ readonly sessionCount: number;
+ readonly messageCount: number;
}
export interface TranscriptRuntimeActivity {
readonly runtime: string;
readonly fileCount: number;
readonly agentHint: string | null;
+ readonly detail?: TranscriptDetail;
}
export interface TranscriptActivity {
diff --git a/src/core/install/types.ts b/src/core/install/types.ts
index 58f28f5a..e30d0817 100644
--- a/src/core/install/types.ts
+++ b/src/core/install/types.ts
@@ -106,6 +106,8 @@ export interface ManifestEntry {
readonly owned_paths?: ReadonlyArray<string>;
readonly owned_block_marker?: string;
readonly fallback_file?: string | null;
+ /** SHA-256 of the last applied MCP payload (update orchestrator). */
+ readonly payload_hash?: string;
}
export interface ApplyResult {
diff --git a/src/core/install/update.ts b/src/core/install/update.ts
new file mode 100644
index 00000000..0f75af8f
--- /dev/null
+++ b/src/core/install/update.ts
@@ -0,0 +1,137 @@
+import { createHash } from "node:crypto";
+
+import type { Registry } from "./registry.ts";
+import { buildPayload } from "./payload.ts";
+import { InstallError } from "./types.ts";
+import type {
+ ApplyOpts,
+ InstallAdapter,
+ InstallEnv,
+ InstallStepKind,
+ McpPayload,
+ VerifyResult,
+} from "./types.ts";
+import { readManifest, recordEntry } from "./manifest.ts";
+
+export interface UpdateTargetResult {
+ readonly target: string;
+ readonly status: "applied" | "up-to-date" | "skipped" | "would-apply" | "error";
+ readonly reason?: string;
+ readonly postNotes?: ReadonlyArray<string>;
+ readonly error?: string;
+ readonly hint?: string;
+ readonly kind?: InstallStepKind | "user-modified-block";
+}
+
+export interface UpdateResult {
+ readonly targets: ReadonlyArray<UpdateTargetResult>;
+}
+
+export interface UpdateOptions {
+ readonly dryRun: boolean;
+ readonly force: boolean;
+ readonly target: string | null;
+}
+
+function sortedReplacer(_key: string, value: unknown): unknown {
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ const out: Record<string, unknown> = {};
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
+ out[key] = (value as Record<string, unknown>)[key];
+ }
+ return out;
+ }
+ return value;
+}
+
+function computePayloadHash(payload: McpPayload): string {
+ return createHash("sha256").update(JSON.stringify(payload, sortedReplacer)).digest("hex");
+}
+
+function targetList(registry: Registry, target: string | null): ReadonlyArray<InstallAdapter> {
+ if (target) {
+ const adapter = registry.get(target);
+ return adapter ? [adapter] : [];
+ }
+ return registry.list();
+}
+
+export function runUpdate(registry: Registry, env: InstallEnv, opts: UpdateOptions): UpdateResult {
+ const manifest = readManifest(env.vault);
+ const results: UpdateTargetResult[] = [];
+
+ for (const adapter of targetList(registry, opts.target)) {
+ const detect = adapter.detect(env);
+
+ if (detect.status === "not-installed" || detect.status === "unsupported-on-this-platform") {
+ results.push({
+ target: adapter.target,
+ status: "skipped",
+ reason: `${adapter.label} is ${detect.status}`,
+ postNotes: detect.notes.length > 0 ? detect.notes : undefined,
+ });
+ continue;
+ }
+
+ let payload: McpPayload;
+ try {
+ payload = buildPayload({
+ vault: env.vault,
+ agent_name: env.env["VAULT_AGENT_NAME"] ?? null,
+ timezone: env.env["VAULT_TIMEZONE"] ?? null,
+ });
+ } catch (exc) {
+ results.push({
+ target: adapter.target,
+ status: "error",
+ error: `Failed to build payload: ${(exc as Error).message}`,
+ });
+ continue;
+ }
+
+ const currentHash = computePayloadHash(payload);
+ const previous = manifest.installs[adapter.target];
+ if (previous?.payload_hash === currentHash && !opts.force) {
+ results.push({ target: adapter.target, status: "up-to-date", reason: "payload unchanged" });
+ continue;
+ }
+
+ const plan = adapter.plan(payload, env);
+
+ if (opts.dryRun) {
+ results.push({ target: adapter.target, status: "would-apply", postNotes: plan.postNotes });
+ continue;
+ }
+
+ const applyOpts: ApplyOpts = {
+ dryRun: false,
+ force: opts.force,
+ stdout: process.stdout,
+ stderr: process.stderr,
+ };
+
+ try {
+ const applyResult = adapter.apply(plan, payload, env, applyOpts);
+ recordEntry(env.vault, { ...applyResult.manifest, payload_hash: currentHash });
+ } catch (exc) {
+ if (exc instanceof InstallError) {
+ results.push({
+ target: adapter.target,
+ status: "error",
+ error: exc.message,
+ hint: exc.hint,
+ kind: exc.kind === "user-modified-block" ? "user-modified-block" : undefined,
+ });
+ } else {
+ results.push({ target: adapter.target, status: "error", error: (exc as Error).message });
+ }
+ continue;
+ }
+
+ results.push({ target: adapter.target, status: "applied", postNotes: plan.postNotes });
+ }
+
+ return { targets: results };
+}
+
+export type { VerifyResult };
diff --git a/templates/brain-explorer.html b/templates/brain-explorer.html
index 3b8da48d..ebc73503 100644
--- a/templates/brain-explorer.html
+++ b/templates/brain-explorer.html
@@ -129,6 +129,7 @@
document.getElementById("details-body").textContent = "Failed to parse graph data: " + e.message;
return;
}
+ const VAULT_PATH = "__VAULT_PATH__";
document.getElementById("vault-name").textContent = graph.vault_basename || "(unnamed vault)";
document.getElementById("stats").textContent =
@@ -146,6 +147,20 @@
"edge-supersedes": "#c92a2a",
};
+ function showTooltip(text) {
+ let tip = document.getElementById("deeplink-tooltip");
+ if (!tip) {
+ tip = document.createElement("div");
+ tip.id = "deeplink-tooltip";
+ tip.style.cssText = "position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#333;color:#fff;padding:8px 16px;border-radius:4px;font-size:12px;z-index:9999;transition:opacity 0.3s;";
+ document.body.appendChild(tip);
+ }
+ tip.textContent = text;
+ tip.style.opacity = "1";
+ clearTimeout(tip._timer);
+ tip._timer = setTimeout(() => { tip.style.opacity = "0"; }, 3000);
+ }
+
// ---- State -------------------------------------------------------------
const nodes = graph.nodes.map((n) => ({
...n,
@@ -524,6 +539,16 @@
if (!li) return;
selectNode(li.getAttribute("data-node-id"));
};
+ list.ondblclick = (ev) => {
+ if (!VAULT_PATH) return;
+ const li = ev.target.closest("li[data-node-id]");
+ if (!li) return;
+ const nodeId = li.getAttribute("data-node-id");
+ const filePath = VAULT_PATH + (nodeId.startsWith("ret-")
+ ? "/Brain/retired/" : "/Brain/preferences/") + nodeId + ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ window.open(uri, "_blank");
+ };
}
// Defer the listbox rebuild to the next animation frame so a held-
@@ -595,6 +620,25 @@
const n = findNode(x, y);
selectNode(n ? n.id : null);
});
+ canvas.addEventListener("dblclick", (e) => {
+ if (!VAULT_PATH) return;
+ const r = canvas.getBoundingClientRect();
+ const x = e.clientX - r.left;
+ const y = e.clientY - r.top;
+ const n = findNode(x, y);
+ if (!n) return;
+ const filePath = VAULT_PATH + (n.id.startsWith("ret-")
+ ? "/Brain/retired/" : "/Brain/preferences/") + n.id + ".md";
+ const uri = "obsidian://open?path=" + encodeURIComponent(filePath);
+ const opened = window.open(uri, "_blank");
+ if (!opened) {
+ navigator.clipboard.writeText(filePath).then(() => {
+ showTooltip("Obsidian not detected β€” path copied to clipboard");
+ }).catch(() => {
+ showTooltip("Path: " + filePath);
+ });
+ }
+ });
// Β§14 polish: keyboard handlers on the listbox. The listbox is
// `tabindex="0"`, so it joins the natural tab order after the
diff --git a/tests/cli/brain-digest-window-cli.test.ts b/tests/cli/brain-digest-window-cli.test.ts
new file mode 100644
index 00000000..ab403c3c
--- /dev/null
+++ b/tests/cli/brain-digest-window-cli.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from "bun:test";
+import { parseWindow, cmdBrainDigest } from "../../src/cli/brain/verbs/digest.ts";
+
+describe("parseWindow", () => {
+ test("parses '7d' as 7 days", () => {
+ expect(parseWindow("7d")).toBe(7);
+ });
+ test("parses bare '7' as 7 days", () => {
+ expect(parseWindow("7")).toBe(7);
+ });
+ test("parses '1d' as 1 day", () => {
+ expect(parseWindow("1d")).toBe(1);
+ });
+ test("parses '30d' as 30 days", () => {
+ expect(parseWindow("30d")).toBe(30);
+ });
+ test("rejects '0d'", () => {
+ expect(() => parseWindow("0d")).toThrow();
+ });
+ test("rejects '-1d'", () => {
+ expect(() => parseWindow("-1d")).toThrow();
+ });
+ test("rejects 'abc'", () => {
+ expect(() => parseWindow("abc")).toThrow();
+ });
+ test("rejects '1.5d'", () => {
+ expect(() => parseWindow("1.5d")).toThrow();
+ });
+});
+
+describe("cmdBrainDigest --window exit codes", () => {
+ test("invalid --window exits with code 2", async () => {
+ const code = await cmdBrainDigest(["--window", "abc"]);
+ expect(code).toBe(2);
+ });
+
+ test("non-positive --window exits with code 2", async () => {
+ const code = await cmdBrainDigest(["--window", "0d"]);
+ expect(code).toBe(2);
+ });
+});
diff --git a/tests/cli/discipline-install.test.ts b/tests/cli/discipline-install.test.ts
index 5dc3902d..9dc99d56 100644
--- a/tests/cli/discipline-install.test.ts
+++ b/tests/cli/discipline-install.test.ts
@@ -78,6 +78,65 @@ describe("o2b discipline install / uninstall", () => {
expect(readJobs().jobs.length).toBe(0);
});
+ test("weekly install uses weekly job name, script, and default schedule", async () => {
+ const env = { OSB_HERMES_JOBS: jobsFile };
+
+ const r = await runCli(
+ [
+ "discipline",
+ "install",
+ "--weekly",
+ "--vault",
+ vault,
+ "--telegram-target",
+ "telegram:-100123:42",
+ ],
+ { env },
+ );
+
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("created");
+
+ const job = readJobs().jobs[0] as {
+ id: string;
+ name: string;
+ script: string;
+ schedule: { kind: string; expr: string; display: string };
+ };
+ expect(job.id).toMatch(/^osb-weekly-brain-digest-/);
+ expect(job.name).toBe("osb-weekly-brain-digest");
+ expect(job.script).toContain("--window 7d");
+ expect(job.schedule.expr).toBe("59 8 * * 1");
+ expect(job.schedule.display).toBe("59 8 * * 1");
+ });
+
+ test("weekly install respects --at override", async () => {
+ const env = { OSB_HERMES_JOBS: jobsFile };
+
+ const r = await runCli(
+ [
+ "discipline",
+ "install",
+ "--weekly",
+ "--at",
+ "0 9 * * 1",
+ "--vault",
+ vault,
+ "--telegram-target",
+ "telegram:-100123:42",
+ ],
+ { env },
+ );
+
+ expect(r.returncode).toBe(0);
+
+ const job = readJobs().jobs[0] as {
+ schedule: { expr: string; display: string };
+ };
+ expect(job.schedule.expr).toBe("0 9 * * 1");
+ expect(job.schedule.display).toBe("0 9 * * 1");
+ });
+
test("install without --vault exits 2 with error on stderr", async () => {
const env = { OSB_HERMES_JOBS: jobsFile };
const r = await runCli(["discipline", "install"], { env });
@@ -101,4 +160,48 @@ describe("o2b discipline install / uninstall", () => {
expect(r.returncode).toBe(2);
expect(r.stderr).toContain("--vault is required");
});
+
+ test("uninstall --weekly removes only the weekly job", async () => {
+ const env = { OSB_HERMES_JOBS: jobsFile };
+
+ await runCli(
+ ["discipline", "install", "--vault", vault, "--telegram-target", "telegram:-100123:42"],
+ { env },
+ );
+ await runCli(
+ ["discipline", "install", "--weekly", "--vault", vault, "--telegram-target", "telegram:-100123:42"],
+ { env },
+ );
+ expect(readJobs().jobs.length).toBe(2);
+
+ const r = await runCli(
+ ["discipline", "uninstall", "--vault", vault, "--weekly"],
+ { env },
+ );
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("removed");
+ expect(readJobs().jobs.length).toBe(1);
+ expect(readJobs().jobs[0]).toMatchObject({ name: "osb-discipline-report" });
+ });
+
+ test("uninstall without --weekly removes both jobs", async () => {
+ const env = { OSB_HERMES_JOBS: jobsFile };
+
+ await runCli(
+ ["discipline", "install", "--vault", vault, "--telegram-target", "telegram:-100123:42"],
+ { env },
+ );
+ await runCli(
+ ["discipline", "install", "--weekly", "--vault", vault, "--telegram-target", "telegram:-100123:42"],
+ { env },
+ );
+ expect(readJobs().jobs.length).toBe(2);
+
+ const r = await runCli(
+ ["discipline", "uninstall", "--vault", vault],
+ { env },
+ );
+ expect(r.returncode).toBe(0);
+ expect(readJobs().jobs.length).toBe(0);
+ });
});
diff --git a/tests/cli/update.test.ts b/tests/cli/update.test.ts
new file mode 100644
index 00000000..5da5c58b
--- /dev/null
+++ b/tests/cli/update.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from "bun:test";
+import { parseUpdateArgs } from "../../src/cli/update.ts";
+
+describe("parseUpdateArgs", () => {
+ test("parses no flags", () => {
+ const args = parseUpdateArgs([]);
+ expect(args.target).toBeNull();
+ expect(args.dryRun).toBe(false);
+ expect(args.force).toBe(false);
+ expect(args.json).toBe(false);
+ });
+
+ test("parses --target", () => {
+ const args = parseUpdateArgs(["--target", "claudecode"]);
+ expect(args.target).toBe("claudecode");
+ });
+
+ test("parses --dry-run", () => {
+ const args = parseUpdateArgs(["--dry-run"]);
+ expect(args.dryRun).toBe(true);
+ });
+
+ test("parses --force", () => {
+ const args = parseUpdateArgs(["--force"]);
+ expect(args.force).toBe(true);
+ });
+
+ test("parses --json", () => {
+ const args = parseUpdateArgs(["--json"]);
+ expect(args.json).toBe(true);
+ });
+});
diff --git a/tests/core/brain.digest.test.ts b/tests/core/brain.digest.test.ts
index 6287a267..4ef83f7c 100644
--- a/tests/core/brain.digest.test.ts
+++ b/tests/core/brain.digest.test.ts
@@ -280,9 +280,9 @@ describe("graceful degradation for confidence shifts / contradictions", () => {
},
});
const res = renderDigest(tmp, { since: SINCE, until: UNTIL });
- // Empty because no preference exists with matching window dates
- // and no shifts/contradictions in the payload.
- expect(res.empty).toBe(true);
+ // Not empty β€” the dream event produces an agent_summary entry
+ // (attributed to "unknown" since no agent field is present).
+ expect(res.empty).toBe(false);
});
test("a dream event with confidence_shifts populates the section", () => {
diff --git a/tests/core/brain/digest-agent-summary.test.ts b/tests/core/brain/digest-agent-summary.test.ts
new file mode 100644
index 00000000..63c81284
--- /dev/null
+++ b/tests/core/brain/digest-agent-summary.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { computeAgentSummary } from "../../../src/core/brain/digest-agent-summary.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import {
+ BRAIN_LOG_EVENT_KIND,
+ BRAIN_APPLY_RESULT,
+} from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-agent-summary-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+
+afterEach(() => {
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+});
+
+describe("computeAgentSummary", () => {
+ test("returns empty array when no log entries", () => {
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+ expect(summary).toEqual([]);
+ });
+
+ test("counts events per agent", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-15T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "testing", signal: "positive", principle: "test" },
+ agent: "claude-vps-agent",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-16T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-a]]", result: BRAIN_APPLY_RESULT.applied, artifact: "[[x.md]]" },
+ agent: "claude-vps-agent",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-17T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "naming", signal: "negative", principle: "no abbreviations" },
+ agent: "codex-agent",
+ });
+
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+
+ expect(summary.length).toBe(2);
+ const claude = summary.find((a) => a.agent === "claude-vps-agent")!;
+ expect(claude.total_events).toBe(2);
+ expect(claude.feedback_count).toBe(1);
+ expect(claude.apply_evidence_count).toBe(1);
+ expect(claude.note_count).toBe(0);
+
+ const codex = summary.find((a) => a.agent === "codex-agent")!;
+ expect(codex.total_events).toBe(1);
+ });
+
+ test("excludes events outside the window", () => {
+ appendLogEvent(vault, {
+ timestamp: "2026-05-01T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { topic: "old", signal: "positive", principle: "old" },
+ agent: "claude-vps-agent",
+ });
+
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+ expect(summary).toEqual([]);
+ });
+
+ test("only first agent gets confirmed_attributed for a shared pref", () => {
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-a.md"),
+ "---\nid: pref-a\ntopic: testing\nstatus: confirmed\nprinciple: test principle\nconfirmed_at: 2026-05-15T11:30:00Z\n---\n",
+ );
+
+ appendLogEvent(vault, {
+ timestamp: "2026-05-15T10:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-a]]", result: BRAIN_APPLY_RESULT.applied, artifact: "[[x.md]]" },
+ agent: "agent-a",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-15T11:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,
+ body: { preference: "[[pref-a]]", result: BRAIN_APPLY_RESULT.applied, artifact: "[[y.md]]" },
+ agent: "agent-b",
+ });
+ appendLogEvent(vault, {
+ timestamp: "2026-05-15T12:00:00Z",
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: {
+ topic: "testing",
+ signal: "positive",
+ principle: "test principle",
+ preference: "[[pref-a]]",
+ result: "confirmed",
+ },
+ agent: "agent-b",
+ });
+
+ const since = new Date("2026-05-13T00:00:00Z");
+ const until = new Date("2026-05-20T00:00:00Z");
+ const summary = computeAgentSummary(vault, since, until);
+
+ const agentA = summary.find((a) => a.agent === "agent-a")!;
+ const agentB = summary.find((a) => a.agent === "agent-b")!;
+
+ expect(agentA.confirmed_attributed).toBe(1);
+ expect(agentB.confirmed_attributed).toBe(0);
+ });
+});
diff --git a/tests/core/brain/explorer-deeplink.test.ts b/tests/core/brain/explorer-deeplink.test.ts
new file mode 100644
index 00000000..0bb96770
--- /dev/null
+++ b/tests/core/brain/explorer-deeplink.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { collectExplorerData, renderExportedHtml, __resetExplorerTemplateCacheForTests } from "../../../src/core/brain/explorer.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-explorer-dl-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ __resetExplorerTemplateCacheForTests();
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+});
+
+describe("explorer deep-link", () => {
+ test("renderExportedHtml substitutes vault path", () => {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph, "/my/vault");
+ expect(html).toContain("\\/my\\/vault");
+ expect(html).not.toContain("__VAULT_PATH__");
+ });
+
+ test("renderExportedHtml with no vault path renders empty", () => {
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ expect(html).not.toContain("__VAULT_PATH__");
+ });
+});
diff --git a/tests/core/discipline/transcripts/cursor-sqlite.test.ts b/tests/core/discipline/transcripts/cursor-sqlite.test.ts
new file mode 100644
index 00000000..d544f2b8
--- /dev/null
+++ b/tests/core/discipline/transcripts/cursor-sqlite.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { cursorTranscript } from "../../../../src/core/discipline/transcripts/cursor.ts";
+
+describe("cursorTranscript collectDetail", () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "osb-cursor-"));
+ });
+
+ afterEach(() => {
+ try {
+ rmSync(home, { recursive: true, force: true });
+ } catch {
+ // ignore cleanup failures
+ }
+ });
+
+ test("returns null when no Cursor data exists", () => {
+ const dayStart = Date.now() - 24 * 60 * 60 * 1000;
+ const dayEnd = Date.now();
+ const detail = cursorTranscript.collectDetail!(dayStart, dayEnd, home);
+ expect(detail).toBeNull();
+ });
+
+ test("falls back gracefully when SQLite is unavailable", () => {
+ const wsRoot = join(home, ".config", "Cursor", "User", "workspaceStorage", "fake-hash");
+ mkdirSync(wsRoot, { recursive: true });
+ writeFileSync(join(wsRoot, "state.vscdb"), "not a sqlite database");
+
+ const dayStart = Date.now() - 24 * 60 * 60 * 1000;
+ const dayEnd = Date.now();
+ const detail = cursorTranscript.collectDetail!(dayStart, dayEnd, home);
+ expect(detail).toBeNull();
+ });
+
+ test("counts sessions and messages from Cursor sqlite state", () => {
+ const wsRoot = join(home, ".config", "Cursor", "User", "workspaceStorage", "hash-1");
+ mkdirSync(wsRoot, { recursive: true });
+ const dbPath = join(wsRoot, "state.vscdb");
+ const db = new Database(dbPath);
+ db.run("CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT)");
+ db.run("INSERT INTO ItemTable (key, value) VALUES (?, ?)", [
+ "sessionData.1",
+ JSON.stringify({
+ messages: [
+ { timestamp: "2026-05-19T10:00:00Z", content: "hi" },
+ { timestamp: "2026-05-19T10:05:00Z", content: "there" },
+ ],
+ }),
+ ]);
+ db.run("INSERT INTO ItemTable (key, value) VALUES (?, ?)", [
+ "sessionData.2",
+ JSON.stringify({
+ messages: [{ timestamp: "2026-05-16T10:00:00Z", content: "old" }],
+ }),
+ ]);
+ db.close();
+
+ const dayStart = new Date("2026-05-19T00:00:00Z").getTime();
+ const dayEnd = new Date("2026-05-20T00:00:00Z").getTime();
+ const detail = cursorTranscript.collectDetail!(dayStart, dayEnd, home);
+ expect(detail).toEqual({ sessionCount: 1, messageCount: 2 });
+ });
+});
diff --git a/tests/core/install/update.test.ts b/tests/core/install/update.test.ts
new file mode 100644
index 00000000..2392df92
--- /dev/null
+++ b/tests/core/install/update.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, test, beforeEach, afterEach } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runUpdate } from "../../../src/core/install/update.ts";
+import { createRegistry } from "../../../src/core/install/registry.ts";
+import { readManifest } from "../../../src/core/install/manifest.ts";
+import type {
+ InstallAdapter,
+ InstallEnv,
+ DetectResult,
+ InstallPlan,
+ ApplyResult,
+ VerifyResult,
+} from "../../../src/core/install/types.ts";
+
+let vault: string;
+let home: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-update-"));
+ home = mkdtempSync(join(tmpdir(), "osb-update-home-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });
+});
+
+afterEach(() => {
+ try { rmSync(vault, { recursive: true, force: true }); } catch {}
+ try { rmSync(home, { recursive: true, force: true }); } catch {}
+});
+
+function makeEnv(): InstallEnv {
+ return { vault, home, cwd: process.cwd(), env: {}, now: new Date() };
+}
+
+function fakeAdapter(
+ target: string,
+ status: "installed" | "not-installed" = "installed",
+): InstallAdapter {
+ return {
+ target,
+ label: target,
+ detect(): DetectResult {
+ return { target, status, configPath: `/tmp/${target}-config`, notes: [] };
+ },
+ plan(): InstallPlan {
+ return {
+ target,
+ steps: [{ kind: "json-merge", path: "/tmp/c.json", preview: "merge" }],
+ postNotes: ["restart " + target],
+ };
+ },
+ apply(): ApplyResult {
+ return {
+ target,
+ steps_executed: 1,
+ manifest: {
+ target,
+ applied_at: new Date().toISOString(),
+ operation: "json-merge",
+ config_path: "/tmp/c.json",
+ },
+ };
+ },
+ uninstall() {
+ return { target, removed_keys: [], removed_paths: [], skipped: [] };
+ },
+ verify(): VerifyResult {
+ return { target, status: "ok", details: [], fix_hint: null };
+ },
+ };
+}
+
+describe("runUpdate", () => {
+ test("skips not-installed targets", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("cursor", "not-installed"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: false, force: false, target: null });
+ expect(result.targets.length).toBe(1);
+ expect(result.targets[0]!.status).toBe("skipped");
+ });
+
+ test("applies when no previous manifest exists", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: false, force: false, target: null });
+ expect(result.targets[0]!.status).toBe("applied");
+ });
+
+ test("dry-run reports would-apply without applying", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const result = runUpdate(reg, makeEnv(), { dryRun: true, force: false, target: null });
+ expect(result.targets[0]!.status).toBe("would-apply");
+ });
+
+ test("skips when payload hash is unchanged", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const env = makeEnv();
+
+ const first = runUpdate(reg, env, { dryRun: false, force: false, target: null });
+ expect(first.targets[0]!.status).toBe("applied");
+
+ const second = runUpdate(reg, env, { dryRun: false, force: false, target: null });
+ expect(second.targets[0]!.status).toBe("up-to-date");
+ expect(second.targets[0]!.reason).toBe("payload unchanged");
+ });
+
+ test("--force bypasses hash-skip", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const env = makeEnv();
+
+ const first = runUpdate(reg, env, { dryRun: false, force: false, target: null });
+ expect(first.targets[0]!.status).toBe("applied");
+
+ const forced = runUpdate(reg, env, { dryRun: false, force: true, target: null });
+ expect(forced.targets[0]!.status).toBe("applied");
+ });
+
+ test("payload_hash stored in install.lock.json after apply", () => {
+ const reg = createRegistry();
+ reg.register(fakeAdapter("claudecode"));
+ const env = makeEnv();
+
+ runUpdate(reg, env, { dryRun: false, force: false, target: null });
+
+ const manifest = readManifest(env.vault);
+ const entry = manifest.installs["claudecode"];
+ expect(entry).toBeDefined();
+ expect(entry!.payload_hash).toBeDefined();
+ expect(entry!.payload_hash).toMatch(/^[0-9a-f]{64}$/);
+ });
+});