Skip to content

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

TypeScript

v0.10.8 refactor: per-verb CLI split + shared MCP/CLI helpers

Sol Aitkene589e447cd61
diff --git a/openclaw/index.js b/openclaw/index.js
index ea57bf55..e8c65170 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1554,11 +1554,11 @@ var require_proper_lockfile = __commonJS((exports, module) => {
// src/openclaw/index.ts
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
-import { existsSync as existsSync6 } from "node:fs";
-import { join as join9, resolve as resolvePath } from "node:path";
+import { existsSync as existsSync5 } from "node:fs";
+import { resolve as resolvePath } from "node:path";
// src/core/config.ts
-import { existsSync, readFileSync, statSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join as join2 } from "node:path";
@@ -1632,6 +1632,22 @@ function withTempFile(target, contents, commit) {
}
}
+// src/core/fs-utils.ts
+import { existsSync, statSync } from "node:fs";
+function isFile(p) {
+ if (!existsSync(p))
+ return false;
+ try {
+ return statSync(p).isFile();
+ } catch {
+ return false;
+ }
+}
+function stem(filename) {
+ const dot = filename.lastIndexOf(".");
+ return dot > 0 ? filename.slice(0, dot) : filename;
+}
+
// src/core/config.ts
var SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"];
function defaultConfigPath() {
@@ -1665,7 +1681,7 @@ function parseSimpleYaml(text) {
}
function discoverConfig(path) {
const resolved = path ?? defaultConfigPath();
- if (!isRegularFile(resolved)) {
+ if (!isFile(resolved)) {
return { path: resolved, exists: false, data: {} };
}
try {
@@ -1718,15 +1734,6 @@ function expandTilde(p) {
return join2(homedir(), p.slice(2));
return p;
}
-function isRegularFile(p) {
- if (!existsSync(p))
- return false;
- try {
- return statSync(p).isFile();
- } catch {
- return false;
- }
-}
// src/core/doctor.ts
import {
@@ -1735,7 +1742,6 @@ import {
openSync as openSync2,
readFileSync as readFileSync2,
rmSync,
- statSync as statSync2,
writeSync as writeSync2,
closeSync as closeSync2
} from "node:fs";
@@ -2000,15 +2006,6 @@ function doctor(opts) {
}
return results;
}
-function isFile(p) {
- if (!existsSync2(p))
- return false;
- try {
- return statSync2(p).isFile();
- } catch {
- return false;
- }
-}
// src/core/identity-reminder.ts
import { readFileSync as readFileSync3 } from "node:fs";
@@ -2386,7 +2383,7 @@ function buildPolicyResult(path, status) {
};
}
// src/core/vault.ts
-import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, statSync as statSync3, writeFileSync } from "node:fs";
+import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync, writeFileSync } from "node:fs";
import { dirname as dirname6, join as join5, relative as relative2 } from "node:path";
var FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
var KEY_VALUE_RE = /^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*?)\s*$/;
@@ -2465,10 +2462,6 @@ function formatFrontmatter(metadata, body) {
`) + `
`;
}
-function writeFrontmatter(path, metadata, body) {
- mkdirSync4(dirname6(path), { recursive: true });
- writeFileSync(path, formatFrontmatter(metadata, body), "utf8");
-}
function writeFrontmatterAtomic(path, metadata, body, opts = {}) {
const contents = formatFrontmatter(metadata, body);
if (opts.overwrite) {
@@ -2537,10 +2530,6 @@ function walk(root, dir, skipDirs, skipFiles, out) {
out.push({ title, path: full, metadata: meta });
}
}
-function stem(filename) {
- const dot = filename.lastIndexOf(".");
- return dot > 0 ? filename.slice(0, dot) : filename;
-}
function stripQuotes(s) {
if (s.length >= 2 && (s.startsWith('"') && s.endsWith('"') || s.startsWith("'") && s.endsWith("'"))) {
return s.slice(1, -1);
@@ -3501,7 +3490,7 @@ var openclaw_default = definePluginEntry({
config_keys: Object.keys(discovery.data).sort(),
config: redactMapping(discovery.data),
vault_path: vault,
- vault_exists: existsSync6(vault)
+ vault_exists: existsSync5(vault)
};
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
@@ -3527,7 +3516,7 @@ var openclaw_default = definePluginEntry({
},
async execute(_id, params) {
const vault = resolveVaultPath(api);
- if (!existsSync6(vault))
+ if (!existsSync5(vault))
throw new Error(`vault directory missing: ${vault}`);
const pattern = params["pattern"] ?? null;
const limit = typeof params["limit"] === "number" ? params["limit"] : 50;
@@ -3547,63 +3536,6 @@ var openclaw_default = definePluginEntry({
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
});
- api.registerTool({
- name: "second_brain_capture",
- description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
- parameters: {
- type: "object",
- properties: {
- title: { type: "string", description: "Human-readable note title." },
- content: { type: "string", description: "Markdown body of the note." },
- tags: {
- type: "array",
- items: { type: "string" },
- description: "Optional list of tag strings."
- },
- overwrite: {
- type: "boolean",
- description: "Allow overwriting an existing note with the same slug."
- }
- },
- required: ["title", "content"],
- additionalProperties: false
- },
- async execute(_id, params) {
- const vault = resolveVaultPath(api);
- if (!existsSync6(vault))
- throw new Error(`vault directory missing: ${vault}`);
- const title = params["title"] ?? "";
- const content = params["content"] ?? "";
- const tags = params["tags"] ?? [];
- const overwrite = Boolean(params["overwrite"]);
- if (!title.trim())
- throw new Error("title must not be empty");
- if (!content.trim())
- throw new Error("content must not be empty");
- const notesDir = join9(vault, "AI Wiki", "notes");
- const slug = slugify(title);
- const target = join9(notesDir, `${slug}.md`);
- const noteExisted = existsSync6(target);
- if (noteExisted && !overwrite) {
- throw new Error(`note already exists: ${vaultRelative(target, vault)}`);
- }
- const metadata = {
- title,
- type: "note",
- created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z")
- };
- if (tags.length > 0)
- metadata["tags"] = tags;
- writeFrontmatter(target, metadata, content.trim());
- const result = {
- path: vaultRelative(target, vault),
- absolute_path: target,
- slug,
- overwritten: noteExisted && overwrite
- };
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- }
- });
api.registerTool({
name: "vault_health",
description: "Run vault, config, and plugin manifest health checks.",
@@ -3648,7 +3580,7 @@ var openclaw_default = definePluginEntry({
const created = [];
const skipped = [];
for (const dir of [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports]) {
- const existed = existsSync6(dir);
+ const existed = existsSync5(dir);
mkdirSync5(dir, { recursive: true });
(existed ? skipped : created).push(vaultRelative(dir, vault));
}
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 3aaad43e..1fe77150 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -1,2450 +1,41 @@
/**
* `o2b brain` subcommand dispatcher.
*
- * Routes the eleven Brain verbs (design doc Β§9.2) to thin wrappers over
- * `src/core/brain/*`. The core modules own all I/O and business logic;
- * this file only parses flags, resolves the vault, and shapes the
- * exit-code matrix (0 success / 1 error / 2 informational not-found).
- *
- * Layout mirrors `src/cli/main.ts` β€” one `cmdBrain<Verb>` function per
- * verb, each returning a number that {@link handleBrainSubcommand} hands
- * back to the outer dispatcher.
- *
- * State-changing verbs print a single human-readable line on stdout.
- * Read-only verbs (digest, query, doctor) honour `--json`. The `--json`
- * flag on state-changing verbs (init/feedback/apply-evidence/...) emits a
- * minimal `{ok: true, ...}` summary so scripted callers can still pin on
- * structured output.
- *
- * Pinning / unpinning / reject / pin / rollback / init are intentionally
- * CLI-only β€” the MCP surface in Task 7 does not expose them so an
- * autonomous agent cannot mutate the protected set, retire rules
- * unilaterally, or overwrite the vault from a snapshot.
+ * Routes Brain verbs to thin wrappers over `src/core/brain/*`.
+ * Each verb handler lives in `./verbs/<name>.ts`; this file only
+ * dispatches and prints help.
*/
-import { existsSync, readFileSync, readdirSync, statSync, type Dirent } from "node:fs";
-import { resolve } from "node:path";
-
-import { atomicWriteFileSync } from "../core/fs-atomic.ts";
-
-import {
- defaultConfigPath,
- resolveAgentName,
- resolveVault,
-} from "../core/config.ts";
-import { buildBacklinkIndex } from "../core/brain/backlinks.ts";
-import { normaliseWikilinkTarget, renderPrefLink } from "../core/brain/wikilink.ts";
-import { bootstrapBrain } from "../core/brain/init.ts";
-import {
- appendApplyEvidence,
- BrainPreferenceNotFoundError,
-} from "../core/brain/apply-evidence.ts";
-import { dream } from "../core/brain/dream.ts";
-import {
- applyMigration,
- MigrationError,
- planMigration,
-} from "../core/brain/migrate-frontmatter.ts";
-import { scanInline } from "../core/brain/inline-scan.ts";
-import {
- importSession,
- importSessionPath,
-} from "../core/brain/sessions/import.ts";
-import { SessionImportError } from "../core/brain/sessions/types.ts";
-import {
- buildLiveServer,
- collectExplorerData,
- renderExportedHtml,
- type LiveServerHandle,
-} from "../core/brain/explorer.ts";
-import {
- BrainMergeError,
- mergePreferences,
- type MergePlan,
-} from "../core/brain/merge.ts";
-import { moveToRetired, parsePreference, writePreference } from "../core/brain/preference.ts";
-import { brainDirs, preferencePath } from "../core/brain/paths.ts";
-import { isoDate, isoSecond } from "../core/brain/time.ts";
-import {
- queryByLogSince,
- queryByPreference,
- queryByTopic,
- BrainNotFoundError,
-} from "../core/brain/query.ts";
-import { renderDigest, type RenderDigestOptions } from "../core/brain/digest.ts";
-import { runDoctor } from "../core/brain/doctor.ts";
-import { setPinned } from "../core/brain/pin.ts";
-import {
- applyProtect,
- BrainProtectError,
- isProtectTarget,
- printSnippet,
- PROTECT_TARGETS,
- unprotect,
-} from "../core/brain/protect.ts";
-import { setPrimaryAgent } from "../core/brain/set-primary.ts";
-import { writeSignal } from "../core/brain/signal.ts";
-import {
- extractSnapshotToTemp,
- listSnapshots,
- restoreSnapshot,
- type ExtractSnapshotResult,
-} from "../core/brain/snapshot.ts";
-import {
- buildManifest,
- diffManifests,
- manifestDiffHasDrift,
- readManifestSidecar,
- renderManifestDriftJson,
- renderManifestDriftMarkdown,
-} from "../core/brain/manifest.ts";
-import { diffBrainTrees } from "../core/brain/snapshot-diff.ts";
-import {
- renderDiffJson,
- renderDiffMarkdown,
-} from "../core/brain/snapshot-diff-render.ts";
-import { appendLogEvent, type BrainLogEntry } from "../core/brain/log.ts";
+import { CliError } from "./argparse.ts";
+import { BRAIN_HELP, VERB_HELP } from "./brain/helpers.ts";
import {
- BrainUpgradeError,
- applyUpgrade,
- planUpgrade,
- type UpgradeFilePlan,
- type UpgradePlan,
-} from "../core/brain/upgrade.ts";
-import {
- exportPreferencesJson,
- exportPreferencesLlmsTxt,
-} from "../core/brain/export.ts";
-import {
- BRAIN_LOG_EVENT_KIND,
- BRAIN_PREFERENCE_STATUS,
- BRAIN_SIGNAL_SIGN,
-} from "../core/brain/types.ts";
-import { CliError, parseFlags, type FlagsSchema } from "./argparse.ts";
-import {
- importClaudeMemory,
- ConflictsError,
-} from "../core/brain/import-claude-memory.ts";
-import { defaultMemoryDir } from "../core/brain/claude-memory-paths.ts";
-
-const NO_VAULT_ERROR =
- "error: no vault configured. Pass --vault <path> explicitly, " +
- "set VAULT_DIR in the environment, or run " +
- "`o2b init --vault <path> ...` first to persist a default.";
-
-/**
- * Resolve a vault path from CLI flags or machine-local config. Throws a
- * {@link CliError} with the standard help message when neither source
- * supplies a value β€” the dispatcher converts this into exit code 1.
- */
-function resolveBrainVault(
- flagVal: string | undefined,
- configPath: string | null,
-): string {
- const vault = flagVal ?? resolveVault(configPath ?? undefined);
- if (vault === null || vault === undefined) {
- throw new CliError(NO_VAULT_ERROR);
- }
- return vault;
-}
-
-/** Emit a state-changing command's status line on stdout. */
-function ok(line: string): void {
- process.stdout.write(line + (line.endsWith("\n") ? "" : "\n"));
-}
-
-/** Emit minimal JSON for `--json` on state-changing commands. */
-function okJson(payload: Record<string, unknown>): void {
- process.stdout.write(JSON.stringify({ ok: true, ...payload }, null, 2) + "\n");
-}
-
-function fail(message: string): number {
- process.stderr.write(`error: ${message}\n`);
- return 1;
-}
-
-function info(message: string): void {
- process.stdout.write(message + (message.endsWith("\n") ? "" : "\n"));
-}
-
-/**
- * Strict ISO-8601 timestamp matcher used by `--now / --since / --until`.
- * The plain `new Date(s)` constructor is far too permissive (it happily
- * parses `"2026"`, `"hello world"` via some locales, year-only strings,
- * etc.). We require a full date-time including offset (`Z` or `Β±HH:MM`),
- * which is the shape `isoSecond()` emits and what scripted callers send.
- */
-const ISO_8601_RE =
- /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/;
-
-// ── Common parse helpers ────────────────────────────────────────────────────
-
-/**
- * Wrap `parseFlags` with a uniform failure path: bad flags surface as
- * `CliError` and the dispatcher converts those to exit code 1.
- */
-function parse(
- argv: ReadonlyArray<string>,
- schema: FlagsSchema,
-): {
- flags: Record<string, string | boolean | string[] | undefined>;
- positional: string[];
-} {
- return parseFlags(argv, schema);
-}
-
-// ── Verb handlers ───────────────────────────────────────────────────────────
-
-async function cmdBrainInit(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- config: { type: "string" },
- force: { type: "boolean" },
- "primary-agent": { type: "string" },
- starter: { type: "boolean" },
- "starter-path": { type: "string" },
- json: { type: "boolean" },
- });
- const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
- // `bootstrapBrain` itself refuses without a registered machine config;
- // resolve the vault from flag-or-config so a freshly registered machine
- // can run `o2b brain init` without restating `--vault`.
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- const primaryAgentFlag = flags["primary-agent"];
- let primaryAgent: string | undefined;
- if (typeof primaryAgentFlag === "string") {
- const trimmed = primaryAgentFlag.trim();
- if (trimmed.length === 0) {
- return fail(
- "brain init: --primary-agent must be a non-empty string when provided",
- );
- }
- primaryAgent = trimmed;
- }
-
- const starterPathFlag = flags["starter-path"];
- let starterPath: string | undefined;
- if (typeof starterPathFlag === "string") {
- starterPath = starterPathFlag.trim();
- if (starterPath.length === 0) {
- return fail(
- "brain init: --starter-path must be a non-empty path when provided",
- );
- }
- }
-
- let result;
- try {
- result = bootstrapBrain(vault, {
- force: Boolean(flags["force"]),
- configPath: config,
- starter: Boolean(flags["starter"]),
- ...(primaryAgent !== undefined ? { primaryAgent } : {}),
- ...(starterPath !== undefined ? { starterPath } : {}),
- });
- } catch (exc) {
- return fail(`failed to initialize Brain: ${(exc as Error).message ?? exc}`);
- }
-
- if (flags["json"]) {
- okJson({
- vault,
- created: result.created,
- overwritten: result.overwritten,
- skipped: result.skipped,
- });
- return 0;
- }
- ok(`brain initialized: ${vault}`);
- for (const p of result.created) info(` created: ${p}`);
- for (const p of result.overwritten) info(` overwritten: ${p}`);
- for (const p of result.skipped) info(` exists: ${p}`);
- return 0;
-}
-
-async function cmdBrainFeedback(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- topic: { type: "string" },
- signal: { type: "string" },
- principle: { type: "string" },
- scope: { type: "string" },
- source: { type: "string-array" },
- agent: { type: "string" },
- raw: { type: "string" },
- "raw-file": { type: "string" },
- "force-confirmed": { type: "boolean" },
- date: { type: "string" },
- slug: { type: "string" },
- json: { type: "boolean" },
- });
-
- // Required-flag enforcement is custom here so the error message names
- // the field β€” design doc Β§13.7 demands "missing required argument
- // exits 1 naming the field".
- for (const field of ["topic", "signal", "principle"] as const) {
- if (typeof flags[field] !== "string" || (flags[field] as string).trim() === "") {
- return fail(`brain feedback missing required flag: --${field}`);
- }
- }
-
- const signalSign = String(flags["signal"]);
- if (
- signalSign !== BRAIN_SIGNAL_SIGN.positive &&
- signalSign !== BRAIN_SIGNAL_SIGN.negative
- ) {
- return fail(
- `--signal must be 'positive' or 'negative'; got ${JSON.stringify(signalSign)}`,
- );
- }
-
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
-
- let raw: string | undefined;
- const rawFile = flags["raw-file"] as string | undefined;
- if (rawFile) {
- try {
- raw = readFileSync(rawFile, "utf8");
- } catch (exc) {
- return fail(`cannot read --raw-file: ${(exc as Error).message ?? exc}`);
- }
- } else if (flags["raw"]) {
- raw = String(flags["raw"]);
- }
-
- const now = new Date();
- const date = (flags["date"] as string | undefined) ?? isoDate(now);
- const slug = (flags["slug"] as string | undefined) ?? String(flags["topic"]);
-
- // 1. Always write the signal to inbox/. (Β§9.2: feedback always creates
- // `sig-*`; `--force-confirmed` ADDITIONALLY creates a confirmed pref.)
- let sigResult;
- try {
- sigResult = writeSignal(vault, {
- topic: String(flags["topic"]),
- signal: signalSign as "positive" | "negative",
- agent,
- principle: String(flags["principle"]),
- created_at: now.toISOString(),
- date,
- slug,
- ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
- ...(flags["source"]
- ? { source: flags["source"] as string[] }
- : {}),
- ...(raw !== undefined ? { raw } : {}),
- });
- } catch (exc) {
- return fail(`failed to write signal: ${(exc as Error).message ?? exc}`);
- }
-
- // Emit a feedback log event so the dream loop can later attribute the
- // signal (and pin / unpin parity stays neat: every state-changing CLI
- // verb leaves a breadcrumb).
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(now),
- eventType: BRAIN_LOG_EVENT_KIND.feedback,
- body: {
- signal: `[[${sigResult.id}]]`,
- topic: String(flags["topic"]),
- sign: signalSign,
- agent,
- },
- });
- } catch (err) {
- // Log-event failure is non-fatal: the signal is already on disk and
- // the next dream pass will pick it up via filesystem scan. Surface
- // a warning so the audit trail gap is at least visible to the
- // operator.
- process.stderr.write(
- `warning: append feedback log failed: ${(err as Error).message}\n`,
- );
- }
-
- // 2. Optional escape hatch β€” `--force-confirmed` jumps the loop and
- // creates a `pref-*` directly in `status: confirmed`.
- let prefResult: { path: string; id: string } | null = null;
- if (flags["force-confirmed"]) {
- try {
- prefResult = writePreference(
- vault,
- {
- slug,
- topic: String(flags["topic"]),
- principle: String(flags["principle"]),
- created_at: now.toISOString(),
- unconfirmed_until: now.toISOString(),
- confirmed_at: now.toISOString(),
- status: BRAIN_PREFERENCE_STATUS.confirmed,
- evidenced_by: [`[[${sigResult.id}]]`],
- ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
- },
- { overwrite: false },
- );
- } catch (exc) {
- return fail(
- `failed to force-confirm preference: ${(exc as Error).message ?? exc}`,
- );
- }
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date(now.getTime() + 1000)),
- eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
- body: {
- preference: renderPrefLink({
- id: prefResult.id,
- principle: String(flags["principle"]),
- }),
- agent,
- },
- });
- } catch (err) {
- // Non-fatal: the preference is already on disk; surface so the
- // gap in the audit trail is at least visible.
- process.stderr.write(
- `warning: append force-confirmed log failed: ${(err as Error).message}\n`,
- );
- }
- }
-
- if (flags["json"]) {
- okJson({
- signal_path: sigResult.path,
- signal_id: sigResult.id,
- ...(prefResult
- ? { preference_path: prefResult.path, preference_id: prefResult.id }
- : {}),
- });
- return 0;
- }
- ok(`signal: ${sigResult.path}`);
- ok(`id: ${sigResult.id}`);
- if (prefResult) {
- ok(`preference: ${prefResult.path}`);
- ok(`status: confirmed`);
- }
- return 0;
-}
-
-async function cmdBrainDream(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- now: { type: "string" },
- agent: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- // Match `cmdBrainInit`'s --primary-agent contract: when the flag is
- // supplied, reject blank input rather than silently fall through to
- // the resolved default. A whitespace-only --agent would otherwise
- // bypass the non-primary check entirely.
- const agentFlag = flags["agent"];
- let agent: string;
- if (typeof agentFlag === "string") {
- const trimmed = agentFlag.trim();
- if (trimmed.length === 0) {
- return fail(
- "brain dream: --agent must be a non-empty string when provided",
- );
- }
- agent = trimmed;
- } else {
- agent = resolveAgentName(config);
- }
-
- let now: Date | undefined;
- const nowStr = flags["now"] as string | undefined;
- if (nowStr) {
- if (!ISO_8601_RE.test(nowStr)) {
- return fail(`--now must be a valid ISO-8601 timestamp; got ${nowStr}`);
- }
- const parsed = new Date(nowStr);
- if (!Number.isFinite(parsed.getTime())) {
- return fail(`--now must be a valid ISO-8601 timestamp; got ${nowStr}`);
- }
- now = parsed;
- }
-
- let summary;
- try {
- summary = dream(vault, {
- ...(now !== undefined ? { now } : {}),
- dryRun: Boolean(flags["dry-run"]),
- ...(agent ? { agentName: agent } : {}),
- });
- } catch (exc) {
- return fail(`dream failed: ${(exc as Error).message ?? exc}`);
- }
-
- // Surface non-fatal warnings (Β§21 non-primary check, future advisory
- // codes) on stderr regardless of output mode. The run already
- // completed successfully; stdout stays reserved for the structured
- // summary / human-readable status lines.
- for (const w of summary.warnings ?? []) {
- process.stderr.write(`warning: ${w.code}: ${w.message}\n`);
- }
-
- if (flags["json"]) {
- process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
- return 0;
- }
- ok(`run_id: ${summary.run_id}`);
- ok(`changed: ${summary.changed}`);
- if (summary.new_unconfirmed.length > 0) {
- ok(`new_unconfirmed: ${summary.new_unconfirmed.join(", ")}`);
- }
- if (summary.confirmed.length > 0) {
- ok(`confirmed: ${summary.confirmed.join(", ")}`);
- }
- if (summary.retired.length > 0) {
- ok(
- `retired: ${summary.retired.map((r) => `${r.id} (${r.reason})`).join(", ")}`,
- );
- }
- if (summary.contradictions.length > 0) {
- ok(`contradictions: ${summary.contradictions.join(", ")}`);
- }
- if (summary.moved_to_processed.length > 0) {
- ok(`moved_to_processed: ${summary.moved_to_processed.length}`);
- }
- return 0;
-}
-
-async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- pref: { type: "string" },
- artifact: { type: "string" },
- result: { type: "string" },
- agent: { type: "string" },
- note: { type: "string" },
- json: { type: "boolean" },
- });
- for (const field of ["pref", "artifact", "result"] as const) {
- if (typeof flags[field] !== "string" || (flags[field] as string).trim() === "") {
- return fail(`brain apply-evidence missing required flag: --${field}`);
- }
- }
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
-
- const resultStr = String(flags["result"]);
- if (
- resultStr !== "applied" &&
- resultStr !== "violated" &&
- resultStr !== "outdated"
- ) {
- return fail(
- `--result must be 'applied', 'violated', or 'outdated'; got ${resultStr}`,
- );
- }
-
- try {
- const out = appendApplyEvidence(vault, {
- pref_id: String(flags["pref"]),
- artifact: String(flags["artifact"]),
- result: resultStr,
- agent,
- ...(flags["note"] ? { note: String(flags["note"]) } : {}),
- });
- if (flags["json"]) {
- okJson({ logged_at: out.logged_at, log_path: out.log_path });
- } else {
- ok(`logged: ${out.log_path}`);
- ok(`at: ${out.logged_at}`);
- }
- return 0;
- } catch (exc) {
- if (exc instanceof BrainPreferenceNotFoundError) {
- // Informative not-found per Β§9.2 β€” exit 2, not 1.
- process.stderr.write(`${exc.message}\n`);
- return 2;
- }
- return fail(`apply-evidence failed: ${(exc as Error).message ?? exc}`);
- }
-}
-
-async function cmdBrainDigest(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- since: { type: "string" },
- until: { type: "string" },
- json: { type: "boolean" },
- "silent-if-empty": { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- // Validate inputs before building the options literal so we never
- // materialise an `opts` object with NaN-time `Date`s. Strict ISO-8601
- // pattern check first so `--since 2026` / `--since "hello"` are rejected
- // before `new Date()` happily silently coerces them.
- let sinceDate: Date | undefined;
- if (flags["since"]) {
- const raw = String(flags["since"]);
- if (!ISO_8601_RE.test(raw)) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- const d = new Date(raw);
- if (!Number.isFinite(d.getTime())) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- sinceDate = d;
- }
- let untilDate: Date | undefined;
- if (flags["until"]) {
- const raw = String(flags["until"]);
- if (!ISO_8601_RE.test(raw)) {
- return fail(`--until must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- const d = new Date(raw);
- if (!Number.isFinite(d.getTime())) {
- return fail(`--until must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- untilDate = d;
- }
- const opts: RenderDigestOptions = {
- ...(sinceDate ? { since: sinceDate } : {}),
- ...(untilDate ? { until: untilDate } : {}),
- format: flags["json"] ? "json" : "markdown",
- };
-
- let result;
- try {
- result = renderDigest(vault, opts);
- } catch (exc) {
- return fail(`digest failed: ${(exc as Error).message ?? exc}`);
- }
-
- if (result.empty && flags["silent-if-empty"]) {
- // Β§8: exit 2 with no output. The CLI is the one place this matters
- // β€” scripts can branch on the exit code rather than parsing stdout.
- return 2;
- }
- process.stdout.write(result.content);
- if (!result.content.endsWith("\n")) process.stdout.write("\n");
- return 0;
-}
-
-async function cmdBrainQuery(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- preference: { type: "string" },
- topic: { type: "string" },
- since: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- // Mutually exclusive choice β€” pick one of the three query shapes.
- const modes = ["preference", "topic", "since"].filter(
- (k) => typeof flags[k] === "string" && (flags[k] as string).trim() !== "",
- );
- if (modes.length === 0) {
- return fail(
- "brain query requires exactly one of --preference, --topic, --since",
- );
- }
- if (modes.length > 1) {
- return fail(
- `brain query: pick only one of --preference / --topic / --since (got ${modes.join(", ")})`,
- );
- }
-
- try {
- if (flags["preference"]) {
- const out = queryByPreference(vault, String(flags["preference"]));
- if (flags["json"]) {
- process.stdout.write(JSON.stringify(out, null, 2) + "\n");
- } else {
- renderQueryPreferenceText(out);
- }
- return 0;
- }
- if (flags["topic"]) {
- const out = queryByTopic(vault, String(flags["topic"]));
- if (flags["json"]) {
- process.stdout.write(JSON.stringify(out, null, 2) + "\n");
- } else {
- renderQueryTopicText(out, String(flags["topic"]));
- }
- return 0;
- }
- if (flags["since"]) {
- const raw = String(flags["since"]);
- if (!ISO_8601_RE.test(raw)) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- const d = new Date(raw);
- if (!Number.isFinite(d.getTime())) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- const entries = queryByLogSince(vault, d);
- if (flags["json"]) {
- process.stdout.write(JSON.stringify(entries, null, 2) + "\n");
- } else {
- renderQueryLogText(entries);
- }
- return 0;
- }
- } catch (exc) {
- if (exc instanceof BrainNotFoundError) {
- // Per Β§9.2 informational not-found: exit 2.
- process.stderr.write(`${exc.message}\n`);
- return 2;
- }
- return fail(`query failed: ${(exc as Error).message ?? exc}`);
- }
- return 0; // unreachable but keeps TypeScript happy
-}
-
-async function cmdBrainReject(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- id: { type: "string" },
- reason: { type: "string" },
- yes: { type: "boolean" },
- json: { type: "boolean" },
- });
- if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
- return fail("brain reject missing required flag: --id");
- }
- // v0.10.1: `--reason` is now mandatory. The text is persisted on the
- // retired file (`user_rejected_reason`) and used by dream to mark
- // future signals on the same topic as `signal-suppressed`. Without
- // it the suppression chain breaks and the reject is just a quiet
- // delete β€” exactly the failure mode Β§6 of _summary calls out.
- if (typeof flags["reason"] !== "string" || (flags["reason"] as string).trim() === "") {
- return fail(
- "brain reject missing required flag: --reason (free-form text; persisted on the retired file)",
- );
- }
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = resolveAgentName(config);
-
- // Resolve the preference file. If absent β†’ exit 2 (informational
- // not-found per Β§9.2 pattern, consistent with apply-evidence).
- const rawId = String(flags["id"]).trim();
- const slug = rawId.startsWith("pref-") ? rawId.slice("pref-".length) : rawId;
- const path = preferencePath(vault, slug);
- if (!existsSync(path)) {
- process.stderr.write(
- `preference not found: pref-${slug}; expected ${path}\n`,
- );
- return 2;
- }
- let pref;
- try {
- pref = parsePreference(path);
- } catch (exc) {
- return fail(`failed to parse preference: ${(exc as Error).message ?? exc}`);
- }
-
- // Pin protection β€” refuse without --yes per Β§15 Step 23b.
- if (pref.pinned && !flags["yes"]) {
- process.stderr.write(
- `warning: preference '${pref.id}' is pinned; pass --yes to override\n`,
- );
- return 1;
- }
-
- const now = new Date();
- const todayDate = isoDate(now);
- const retiredBy = `[[Brain/log/${todayDate}]]`;
-
- const reasonText = String(flags["reason"]).trim();
- try {
- moveToRetired(vault, path, "user-rejected", {
- now,
- retired_by: retiredBy,
- user_rejected_reason: reasonText,
- });
- } catch (exc) {
- return fail(`failed to retire preference: ${(exc as Error).message ?? exc}`);
- }
-
- // Log a `reject` event so the audit trail stays complete.
- try {
- const body: Record<string, string> = {
- preference: renderPrefLink({
- id: `ret-${slug}`,
- principle: pref.principle,
- }),
- agent,
- };
- if (flags["reason"]) body["reason"] = String(flags["reason"]);
- if (pref.pinned) body["was_pinned"] = "true";
- appendLogEvent(vault, {
- timestamp: isoSecond(now),
- eventType: BRAIN_LOG_EVENT_KIND.reject,
- body,
- });
- } catch (err) {
- // Non-fatal: the retire move is already persisted; surface so the
- // gap in the audit trail is at least visible.
- process.stderr.write(
- `warning: append reject log failed: ${(err as Error).message}\n`,
- );
- }
-
- if (flags["json"]) {
- okJson({ id: `ret-${slug}`, reason: "user-rejected" });
- } else {
- ok(`retired: ret-${slug} (user-rejected)`);
- }
- return 0;
-}
-
-async function cmdBrainMerge(argv: string[]): Promise<number> {
- const { flags, positional } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- force: { type: "boolean" },
- agent: { type: "string" },
- json: { type: "boolean" },
- });
- if (positional.length !== 2) {
- return fail(
- "brain merge requires exactly two positional ids: <keep-pref-id> <drop-pref-id>",
- );
- }
- const [keepId, dropId] = positional as [string, string];
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent =
- (flags["agent"] as string | undefined) ?? resolveAgentName(config);
- const dryRun = flags["dry-run"] === true;
- const force = flags["force"] === true;
- const wantJson = flags["json"] === true;
-
- // Plan first via dryRun so the prompt shows real numbers without
- // touching disk. A second call commits when the operator agrees.
- // Each `mergePreferences` invocation takes its own fresh timestamp
- // so the commit reflects when it ran (the operator may take a
- // long time to confirm at the prompt below).
- let plan: MergePlan;
- try {
- plan = mergePreferences(vault, keepId, dropId, {
- now: new Date(),
- agentName: agent,
- dryRun: true,
- });
- } catch (exc) {
- if (exc instanceof BrainMergeError) {
- return fail(`brain merge: ${exc.message}`);
- }
- return fail(
- `brain merge: failed to plan merge: ${(exc as Error).message ?? exc}`,
- );
- }
-
- const planLines = [
- `merge plan:`,
- ` keep: ${plan.keep_id}`,
- ` drop: ${plan.drop_id} β†’ ${plan.retired_path}`,
- ` topic: ${plan.topic}${plan.scope ? `, scope: ${plan.scope}` : ""}`,
- ` evidenced_by union: ${plan.merged_evidenced_by.length}`,
- ` applied_sum: ${plan.applied_sum}`,
- ` violated_sum: ${plan.violated_sum}`,
- ` last_evidence_at: ${plan.last_evidence_at ?? "β€”"}`,
- ];
-
- if (dryRun) {
- if (wantJson) {
- okJson({ dry_run: true, plan });
- } else {
- for (const line of planLines) ok(line);
- ok("dry-run; no changes written");
- }
- return 0;
- }
-
- if (!force) {
- if (wantJson) {
- return fail(
- "brain merge: --json without --force is not supported (interactive prompt cannot render)",
- );
- }
- // Non-TTY stdin can only "answer" the prompt with EOF, which we
- // would interpret as N β†’ exit 0 "merge cancelled". For
- // automation that path is misleading (looks like an intentional
- // no-op). Require `--force` instead, same shape as rollback /
- // migrate-frontmatter guards.
- if (!process.stdin.isTTY) {
- return fail(
- "brain merge: --force required when stdin is not a TTY (cannot prompt for confirmation)",
- );
- }
- for (const line of planLines) process.stderr.write(line + "\n");
- process.stderr.write("Proceed? [y/N] ");
- const ans = (await readSingleLine()).toLowerCase();
- if (ans !== "y" && ans !== "yes") {
- ok("merge cancelled");
- return 0;
- }
- }
-
- try {
- mergePreferences(vault, keepId, dropId, {
- now: new Date(),
- agentName: agent,
- });
- } catch (exc) {
- if (exc instanceof BrainMergeError) {
- return fail(`brain merge: ${exc.message}`);
- }
- return fail(
- `brain merge: failed to commit merge: ${(exc as Error).message ?? exc}`,
- );
- }
-
- if (wantJson) {
- okJson({ merged: true, plan });
- } else {
- ok(`merged: ${plan.drop_id} β†’ ${plan.keep_id} (retired as merged-into)`);
- }
- return 0;
-}
-
-async function cmdBrainExplorer(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- port: { type: "string" },
- export: { type: "string" },
- force: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const exportPath = flags["export"] as string | undefined;
- const force = flags["force"] === true;
-
- if (exportPath !== undefined) {
- if (existsSync(exportPath) && !force) {
- return fail(
- `${exportPath} exists; pass --force to overwrite`,
- );
- }
- const graph = collectExplorerData(vault);
- const html = renderExportedHtml(graph);
- try {
- atomicWriteFileSync(exportPath, html);
- } catch (err) {
- return fail(
- `failed to write ${exportPath}: ${(err as Error).message ?? err}`,
- );
- }
- ok(`exported ${graph.nodes.length} nodes to ${exportPath}`);
- return 0;
- }
-
- const portRaw = (flags["port"] as string | undefined) ?? "7777";
- const port = Number.parseInt(portRaw, 10);
- if (!/^\d+$/.test(portRaw) || !Number.isFinite(port) || port < 1 || port > 65535) {
- return fail(`invalid --port value: ${portRaw}`);
- }
-
- let server: LiveServerHandle;
- try {
- server = buildLiveServer(vault, port);
- } catch (err) {
- const msg = (err as Error).message ?? String(err);
- if (/EADDRINUSE|address already in use/i.test(msg)) {
- return fail(`port ${port} already in use; try --port <other>`);
- }
- return fail(`failed to start explorer: ${msg}`);
- }
-
- ok(`Live explorer at ${server.url}`);
- info("Press Ctrl+C to stop.");
-
- await new Promise<void>((resolveStop) => {
- const stop = (): void => {
- void server.close().then(() => resolveStop());
- };
- process.once("SIGINT", stop);
- process.once("SIGTERM", stop);
- });
- return 0;
-}
-
-async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
- const { flags, positional } = parse(argv, {
- vault: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- if (positional.length < 1 || positional.length > 2) {
- return fail(
- "brain snapshot diff requires <run_id_a> [<run_id_b>] (with one arg, the live tree is compared as B)",
- );
- }
- const [a, b] = positional;
- const snaps = listSnapshots(vault);
- if (!snaps.some((s) => s.run_id === a)) {
- process.stderr.write(
- `snapshot not found: ${a}; run \`o2b brain rollback --list\` to enumerate.\n`,
- );
- return 2;
- }
- if (b !== undefined && !snaps.some((s) => s.run_id === b)) {
- process.stderr.write(
- `snapshot not found: ${b}; run \`o2b brain rollback --list\` to enumerate.\n`,
- );
- return 2;
- }
-
- let extA: ExtractSnapshotResult | null = null;
- let extB: ExtractSnapshotResult | null = null;
- try {
- extA = extractSnapshotToTemp(vault, a!);
- const bRoot = b !== undefined
- ? (extB = extractSnapshotToTemp(vault, b)).brainRoot
- : brainDirs(vault).brain;
- const diff = diffBrainTrees(extA.brainRoot, bRoot);
- const out = flags["json"]
- ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
- : renderDiffMarkdown(diff, { aLabel: a!, bLabel: b ?? "live" });
- process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
- return 0;
- } catch (exc) {
- return fail(`snapshot diff failed: ${(exc as Error).message ?? exc}`);
- } finally {
- extA?.cleanup();
- extB?.cleanup();
- }
-}
-
-async function handleBrainSnapshotSubcommand(
- argv: ReadonlyArray<string>,
-): Promise<number> {
- if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
- process.stdout.write(
- "usage: o2b brain snapshot <verb> [args...]\n" +
- "Verbs:\n" +
- " diff <run_id_a> [<run_id_b>] Read-only diff between two snapshots,\n" +
- " or between a snapshot and live Brain/.\n",
- );
- return argv.length === 0 ? 2 : 0;
- }
- const sub = argv[0]!;
- const rest = argv.slice(1);
- switch (sub) {
- case "diff":
- return await cmdBrainSnapshotDiff([...rest]);
- default:
- process.stderr.write(
- `unknown brain snapshot verb: ${sub}; supported: diff\n`,
- );
- return 2;
- }
-}
-
-async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
- const { flags, positional } = parse(argv, {
- vault: { type: "string" },
- clear: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- let name: string | null;
- if (flags["clear"]) {
- if (positional.length > 0) {
- return fail("brain set-primary --clear takes no positional argument");
- }
- name = null;
- } else {
- if (positional.length < 1) {
- return fail(
- "brain set-primary requires <name> or --clear; see `o2b brain help set-primary`",
- );
- }
- if (positional.length > 1) {
- return fail("brain set-primary accepts a single <name> argument");
- }
- const supplied = positional[0]!.trim();
- if (supplied.length === 0) {
- return fail("brain set-primary <name> must be non-empty");
- }
- name = supplied;
- }
-
- let result;
- try {
- result = setPrimaryAgent(vault, name);
- } catch (exc) {
- return fail(`set-primary failed: ${(exc as Error).message ?? exc}`);
- }
-
- if (flags["json"]) {
- okJson({
- previous: result.previous,
- next: result.next,
- changed: result.changed,
- });
- return 0;
- }
-
- const fmt = (v: string | null): string => v ?? "null";
- if (!result.changed) {
- ok(`primary_agent already set to ${fmt(result.next)}`);
- } else {
- ok(`primary_agent: ${fmt(result.previous)} β†’ ${fmt(result.next)}`);
- }
- return 0;
-}
-
-async function cmdBrainProtect(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- target: { type: "string", required: true },
- vault: { type: "string" },
- apply: { type: "boolean" },
- json: { type: "boolean" },
- });
- const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
- if (!isProtectTarget(rawTarget)) {
- return fail(
- `brain protect --target='${flags["target"]}' is unknown; `
- + `supported targets: ${PROTECT_TARGETS.join(", ")}`,
- );
- }
- const target = rawTarget;
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
-
- try {
- if (flags["apply"]) {
- const result = applyProtect({ target, vault });
- if (flags["json"]) {
- okJson({
- target: result.target,
- destination: result.destination,
- changed: result.changed,
- backup: result.backupPath || null,
- });
- return 0;
- }
- const head = result.changed
- ? `brain protect: applied to ${result.destination}`
- : `brain protect: no changes (${result.destination} already current)`;
- ok(head);
- if (result.backupPath) ok(` backup: ${result.backupPath}`);
- return 0;
- }
- // --print (default): emit the snippet body, no writes.
- const snippet = printSnippet({ target, vault });
- if (flags["json"]) {
- okJson({
- target: snippet.target,
- destination: snippet.destination,
- body: snippet.body,
- });
- return 0;
- }
- info(`# o2b brain protect --target ${target}`);
- info(`# destination: ${snippet.destination}`);
- info(`# preview only; re-run with --apply to write the file`);
- process.stdout.write(snippet.body);
- return 0;
- } catch (exc) {
- if (exc instanceof BrainProtectError) {
- return fail(`brain protect failed: ${exc.message}`);
- }
- throw exc;
- }
-}
-
-async function cmdBrainUnprotect(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- target: { type: "string", required: true },
- vault: { type: "string" },
- json: { type: "boolean" },
- });
- const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
- if (!isProtectTarget(rawTarget)) {
- return fail(
- `brain unprotect --target='${flags["target"]}' is unknown; `
- + `supported targets: ${PROTECT_TARGETS.join(", ")}`,
- );
- }
- const target = rawTarget;
- const vault = resolveBrainVault(
- flags["vault"] as string | undefined,
- defaultConfigPath(),
- );
-
- try {
- unprotect({ target, vault });
- } catch (exc) {
- if (exc instanceof BrainProtectError) {
- return fail(`brain unprotect failed: ${exc.message}`);
- }
- throw exc;
- }
- if (flags["json"]) {
- okJson({ target, vault });
- } else {
- ok(`brain unprotect: removed OSB-managed rules for target=${target}`);
- }
- return 0;
-}
-
-async function cmdBrainPin(argv: string[]): Promise<number> {
- return await pinOrUnpin(argv, true);
-}
-
-async function cmdBrainUnpin(argv: string[]): Promise<number> {
- return await pinOrUnpin(argv, false);
-}
-
-async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- id: { type: "string" },
- json: { type: "boolean" },
- });
- if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
- return fail(
- `brain ${value ? "pin" : "unpin"} missing required flag: --id`,
- );
- }
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = resolveAgentName(config);
-
- try {
- const out = setPinned(vault, String(flags["id"]), value, { agent });
- const slug = String(flags["id"]).trim().replace(/^pref-/, "");
- const label = value ? "pinned" : "unpinned";
- const idemLabel = value ? "already pinned" : "already unpinned";
- if (flags["json"]) {
- okJson({ id: `pref-${slug}`, changed: out.changed, pinned: value });
- } else if (out.changed) {
- ok(`${label}: pref-${slug}`);
- } else {
- ok(`${idemLabel}: pref-${slug}`);
- }
- return 0;
- } catch (exc) {
- if (exc instanceof BrainPreferenceNotFoundError) {
- process.stderr.write(`${exc.message}\n`);
- return 2;
- }
- return fail(
- `${value ? "pin" : "unpin"} failed: ${(exc as Error).message ?? exc}`,
- );
- }
-}
-
-async function cmdBrainRollback(argv: string[]): Promise<number> {
- const { flags, positional } = parse(argv, {
- vault: { type: "string" },
- list: { type: "boolean" },
- yes: { type: "boolean" },
- "dry-run": { type: "boolean" },
- "force-rollback": { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const forceRollback = Boolean(flags["force-rollback"]);
-
- // `--list` shows available snapshots in newest-first order, with size
- // for the operator's mental model. Idempotent and read-only.
- if (flags["list"]) {
- const snaps = listSnapshots(vault);
- if (flags["json"]) {
- process.stdout.write(JSON.stringify(snaps, null, 2) + "\n");
- return 0;
- }
- if (snaps.length === 0) {
- ok("no snapshots available");
- return 0;
- }
- ok("run_id\tcreated_at\tsize_bytes");
- for (const s of snaps) {
- ok(`${s.run_id}\t${s.created_at}\t${s.size_bytes}`);
- }
- return 0;
- }
-
- if (positional.length < 1) {
- return fail(
- "brain rollback requires a <run_id> argument (or --list to enumerate snapshots)",
- );
- }
- const runId = positional[0]!;
-
- // Quick existence probe so the user gets a useful exit-2 not-found
- // message instead of a deep error inside `restoreSnapshot`.
- const allSnaps = listSnapshots(vault);
- if (!allSnaps.some((s) => s.run_id === runId)) {
- process.stderr.write(
- `snapshot not found: ${runId}; run \`o2b brain rollback --list\` to enumerate.\n`,
- );
- return 2;
- }
-
- // Drift detection (Β§5-tail). When a sidecar manifest accompanies
- // the snapshot we compare it against a freshly-built manifest of
- // the live Brain/ tree. If they differ and the operator did not
- // pass --force-rollback, we abort with exit 2 so a Syncthing-
- // delivered edit on another device is not silently clobbered. For
- // legacy snapshots (no sidecar β€” produced before v0.10.6) we emit
- // a stderr warning and fall through to the pre-v0.10.6 path.
- // Skip the full sha-256 walk for `--dry-run` β€” that path already
- // shows the operator everything via `diffBrainTrees` and never
- // writes, so drift detection adds no signal.
- const driftDiff = flags["dry-run"]
- ? null
- : (() => {
- const stored = readManifestSidecar(vault, runId);
- if (stored === null) {
- process.stderr.write(
- `warning: no manifest sidecar for snapshot '${runId}'; ` +
- `drift detection skipped (snapshot predates v0.10.6).\n`,
- );
- return null;
- }
- const live = buildManifest(brainDirs(vault).brain);
- return diffManifests(stored, live);
- })();
- const drift = driftDiff !== null && manifestDiffHasDrift(driftDiff);
- if (drift && !forceRollback) {
- // Abort path. --json emits the structured drift payload; the
- // human path emits the markdown rendering. Either way the exit
- // code is 2 and Brain/ stays untouched.
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(renderManifestDriftJson(driftDiff!, runId), null, 2) +
- "\n",
- );
- return 2;
- }
- process.stderr.write(renderManifestDriftMarkdown(driftDiff!, runId) + "\n");
- return 2;
- }
-
- // --dry-run prints the would-be restore plan without modifying
- // Brain/. Mutually exclusive with --yes β€” combining "preview" and
- // "execute non-interactively" is contradictory and would silently
- // hide one of the two intents.
- if (flags["dry-run"]) {
- if (flags["yes"]) {
- return fail("rollback: --dry-run and --yes are mutually exclusive");
- }
- let ext;
- try {
- ext = extractSnapshotToTemp(vault, runId);
- } catch (exc) {
- return fail(`rollback dry-run failed: ${(exc as Error).message ?? exc}`);
- }
- try {
- const liveBrain = brainDirs(vault).brain;
- const diff = diffBrainTrees(liveBrain, ext.brainRoot);
- const out = flags["json"]
- ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n"
- : renderDiffMarkdown(diff, { aLabel: "live", bLabel: runId });
- process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
- return 0;
- } finally {
- ext.cleanup();
- }
- }
-
- // Interactive confirm. We compute a minimal diff summary by counting
- // entries in the current state (the snapshot's content would require
- // extracting first; the headline is intentionally lightweight β€” "you
- // are about to overwrite N files").
- if (!flags["yes"]) {
- // Non-interactive guard: --json output or non-TTY stdin (CI, pipes)
- // would silently hang waiting for input. Fail fast and demand --yes
- // so automation never blocks on a dropped prompt.
- if (flags["json"] || !process.stdin.isTTY) {
- return fail(
- "rollback requires --yes in non-interactive mode (--json or non-TTY stdin)",
- );
- }
- const summary = diffSummary(vault);
- process.stderr.write(
- `About to restore snapshot '${runId}' over Brain/.\n` +
- `Current state: ${summary.preferences} preferences, ${summary.retired} retired, ${summary.signals} signals.\n` +
- `This will OVERWRITE the live Brain/ tree (.snapshots/ is preserved).\n` +
- `Proceed? [y/N] `,
- );
- const ans = await readSingleLine();
- if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") {
- ok("rollback cancelled");
- return 0;
- }
- }
-
- let result;
- try {
- result = restoreSnapshot(vault, runId);
- } catch (exc) {
- return fail(`rollback failed: ${(exc as Error).message ?? exc}`);
- }
-
- // Log the rollback event so the audit trail shows the time-shift.
- try {
- const body: Record<string, string> = {
- run_id: runId,
- restored_files: String(result.restored_files),
- };
- // Record `drift_overridden` only when --force-rollback actually
- // bypassed a real drift β€” the absence of the key keeps the
- // common-case shape minimal.
- if (drift && forceRollback) {
- body["drift_overridden"] = "true";
- }
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date()),
- eventType: BRAIN_LOG_EVENT_KIND.rollback,
- body,
- });
- } catch (err) {
- // Non-fatal: the snapshot was already restored on disk; surface so
- // the gap in the audit trail is at least visible.
- process.stderr.write(
- `warning: append rollback log failed: ${(err as Error).message}\n`,
- );
- }
-
- if (flags["json"]) {
- okJson({ run_id: runId, restored_files: result.restored_files });
- } else {
- ok(`restored: ${runId} (${result.restored_files} files)`);
- }
- return 0;
-}
-
-async function cmdBrainBacklinks(argv: string[]): Promise<number> {
- const { positional, flags } = parse(argv, {
- vault: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- const id = positional[0];
- if (!id) {
- return fail("brain backlinks requires a target id (e.g. pref-foo, ret-bar, sig-...)");
- }
- // Run the input through the same normaliser the index uses so a
- // wikilink-shaped argument (`[[pref-foo]]`, `pref-foo.md`) resolves.
- const target = normaliseWikilinkTarget(id);
- const index = buildBacklinkIndex(vault);
- const refs = index.get(target) ?? [];
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify({ id: target, count: refs.length, refs }, null, 2) + "\n",
- );
- return 0;
- }
-
- process.stdout.write(`Backlinks to ${target}: ${refs.length}\n`);
- if (refs.length === 0) return 0;
- for (const r of refs) {
- const ts = r.timestamp ? ` @ ${r.timestamp}` : "";
- process.stdout.write(
- ` ${r.source} (${r.sourceKind}, field: ${r.field})${ts}\n`,
- );
- }
- return 0;
-}
-
-async function cmdBrainImportSession(argv: string[]): Promise<number> {
- const { flags, positional } = parse(argv, {
- vault: { type: "string" },
- format: { type: "string" },
- since: { type: "string" },
- "dry-run": { type: "boolean" },
- agent: { type: "string" },
- json: { type: "boolean" },
- });
- if (positional.length < 1) {
- return fail("brain import-session requires a <path> argument");
- }
- const sessionPath = positional[0]!;
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
-
- // --format validation: only adapter ids registered in the registry.
- const formatRaw = flags["format"] as string | undefined;
- let format: "claude" | "codex" | "hermes" | undefined;
- if (formatRaw !== undefined && formatRaw !== "auto") {
- if (formatRaw !== "claude" && formatRaw !== "codex" && formatRaw !== "hermes") {
- return fail(
- `--format must be one of auto|claude|codex|hermes; got ${formatRaw}`,
- );
- }
- format = formatRaw;
- }
-
- // Parse --since. Strict ISO-8601 first β€” `new Date(raw)` alone is
- // too permissive (year-only strings, locale-specific shapes). Same
- // contract as cmdBrainDigest / cmdBrainQuery / cmdBrainDream.
- let since: Date | undefined;
- if (flags["since"]) {
- const raw = String(flags["since"]);
- if (!ISO_8601_RE.test(raw)) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- const d = new Date(raw);
- if (!Number.isFinite(d.getTime())) {
- return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
- }
- since = d;
- }
-
- // Decide single-file vs directory based on stat.
- let stat;
- try {
- stat = statSync(sessionPath);
- } catch (err) {
- return fail(`cannot stat ${sessionPath}: ${(err as Error).message ?? err}`);
- }
-
- try {
- const result = stat.isDirectory()
- ? await importSessionPath(vault, sessionPath, {
- agent,
- ...(format ? { format } : {}),
- ...(since ? { since } : {}),
- dryRun: Boolean(flags["dry-run"]),
- })
- : {
- files: [
- await importSession(vault, sessionPath, {
- agent,
- ...(format ? { format } : {}),
- ...(since ? { since } : {}),
- dryRun: Boolean(flags["dry-run"]),
- }),
- ],
- warnings: [],
- };
-
- // Log one event per file processed (skip dry-run).
- if (!flags["dry-run"]) {
- for (const f of result.files) {
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date()),
- eventType: BRAIN_LOG_EVENT_KIND.importSession,
- body: {
- agent,
- file: `[[${f.file}]]`,
- format: f.format,
- turns_scanned: String(f.turns_scanned),
- signals_created: String(f.signals_created),
- signals_deduped: String(f.signals_deduped),
- tool_replays: String(f.tool_replays),
- malformed: String(f.malformed),
- },
- });
- } catch (err) {
- process.stderr.write(
- `warning: append import-session log failed: ${(err as Error).message}\n`,
- );
- }
- }
- }
-
- if (flags["json"]) {
- okJson({
- files: result.files.map((f) => ({
- file: f.file,
- format: f.format,
- turns_scanned: f.turns_scanned,
- signals_created: f.signals_created,
- signals_deduped: f.signals_deduped,
- tool_replays: f.tool_replays,
- malformed: f.malformed,
- errors: f.errors,
- })),
- warnings: result.warnings,
- });
- } else {
- for (const f of result.files) {
- ok(`file: ${f.file}`);
- ok(` format: ${f.format}`);
- ok(` turns_scanned: ${f.turns_scanned}`);
- ok(` signals_created: ${f.signals_created}`);
- ok(` signals_deduped: ${f.signals_deduped}`);
- ok(` tool_replays: ${f.tool_replays}`);
- if (f.malformed > 0) ok(` malformed: ${f.malformed}`);
- for (const e of f.errors) {
- info(` error: ${e.path}: ${e.message}`);
- }
- }
- for (const w of result.warnings) {
- info(` warning: ${w.path}: ${w.message}`);
- }
- }
- return 0;
- } catch (exc) {
- if (exc instanceof SessionImportError) {
- process.stderr.write(`error: ${exc.message}\n`);
- // DETECT_FAIL / UNKNOWN_FORMAT β†’ exit 2 (operator picks --format).
- if (exc.code === "DETECT_FAIL" || exc.code === "UNKNOWN_FORMAT") return 2;
- return 1;
- }
- return fail(`import-session failed: ${(exc as Error).message ?? exc}`);
- }
-}
-
-async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number> {
- const config = defaultConfigPath();
-
- let memory: string | null = null;
- let mode: "dry-run" | "apply" = "dry-run";
- let modeSet = false;
- let allowArbitrary = false;
- let yes = false;
- let asJson = false;
- let vaultFlag: string | undefined;
-
- // Demand a value for `--vault` / `--memory` and reject unknown flags
- // outright. The previous loop silently dropped `--scope` typos and
- // similar mistakes, which would default a fresh agent to `~/.../-X-vault`
- // (often the wrong directory) without complaint. `consumeValue` advances
- // the loop index in-place and returns null on a missing/flag-looking
- // value β€” the caller surfaces the stderr message and returns 2.
- const consumeValue = (flag: string, next: string | undefined): string | null => {
- if (next === undefined || next.startsWith("--")) {
- process.stderr.write(
- `o2b brain import-claude-memory: ${flag} requires a value\n`,
- );
- return null;
- }
- return next;
- };
-
- for (let i = 0; i < argv.length; i++) {
- const a = argv[i];
- if (a === "--vault") {
- const v = consumeValue("--vault", argv[++i]);
- if (v === null) return 2;
- vaultFlag = v;
- continue;
- }
- if (a === "--memory") {
- const v = consumeValue("--memory", argv[++i]);
- if (v === null) return 2;
- memory = v;
- continue;
- }
- if (a === "--dry-run") {
- if (modeSet && mode !== "dry-run") {
- process.stderr.write(
- "o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n",
- );
- return 2;
- }
- mode = "dry-run"; modeSet = true; continue;
- }
- if (a === "--apply") {
- if (modeSet && mode !== "apply") {
- process.stderr.write(
- "o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n",
- );
- return 2;
- }
- mode = "apply"; modeSet = true; continue;
- }
- if (a === "--yes") { yes = true; continue; }
- if (a === "--json") { asJson = true; continue; }
- if (a === "--allow-arbitrary-memory-path") { allowArbitrary = true; continue; }
- process.stderr.write(
- `o2b brain import-claude-memory: unknown flag ${a}\n`,
- );
- return 2;
- }
-
- if (mode === "apply" && !yes && !process.stdin.isTTY) {
- process.stderr.write(
- "o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n",
- );
- return 2;
- }
-
- const vault = resolveBrainVault(vaultFlag, config);
- const memDir = memory ?? defaultMemoryDir(vault);
-
- try {
- const res = importClaudeMemory({
- vault,
- memoryDir: memDir,
- mode,
- allowArbitraryMemoryPath: allowArbitrary,
- });
- if (asJson) {
- process.stdout.write(JSON.stringify(res, null, 2) + "\n");
- return 0;
- }
- if (mode === "dry-run") {
- process.stdout.write(
- `plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`,
- );
- for (const p of res.plans) {
- process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);
- }
- for (const s of res.skipped) {
- process.stdout.write(` SKIP ${s.basename}: ${s.reason}\n`);
- }
- if (res.conflicts.length > 0) {
- process.stdout.write(`conflicts: ${res.conflicts.length}\n`);
- }
- } else {
- process.stdout.write(
- `applied: ${res.applied.length}; unchanged: ${res.skippedUnchanged.length}; skipped: ${res.skipped.length}\n`,
- );
- if (res.snapshotRunId) {
- process.stdout.write(`snapshot: ${res.snapshotRunId}\n`);
- }
- }
- return 0;
- } catch (err) {
- if (err instanceof ConflictsError) {
- process.stderr.write("conflicts:\n");
- for (const c of err.conflicts) {
- process.stderr.write(
- ` ${c.prefId} already exists in Brain but is not in Brain/.imports/claude-memory.json\n`,
- );
- }
- return 2;
- }
- process.stderr.write(
- `o2b brain import-claude-memory: ${(err as Error).message}\n`,
- );
- return 1;
- }
-}
-
-async function cmdBrainScanInline(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- strict: { type: "boolean" },
- path: { type: "string-array" },
- exclude: { type: "string-array" },
- agent: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
-
- let result;
- try {
- result = await scanInline(vault, {
- agent,
- dryRun: Boolean(flags["dry-run"]),
- paths: (flags["path"] as string[] | undefined) ?? [],
- exclude: (flags["exclude"] as string[] | undefined) ?? [],
- });
- } catch (exc) {
- return fail(`scan-inline failed: ${(exc as Error).message ?? exc}`);
- }
-
- // Log event (skip on --dry-run so audit trail only reflects actual writes).
- if (!flags["dry-run"]) {
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date()),
- eventType: BRAIN_LOG_EVENT_KIND.scanInline,
- body: {
- agent,
- scanned: String(result.scanned),
- found: String(result.found),
- created: String(result.created),
- deduped: String(result.deduped),
- malformed: String(result.malformed),
- errors: String(result.errors.length),
- },
- });
- } catch (err) {
- process.stderr.write(
- `warning: append scan-inline log failed: ${(err as Error).message}\n`,
- );
- }
- }
-
- if (flags["json"]) {
- okJson({
- scanned: result.scanned,
- found: result.found,
- created: result.created,
- deduped: result.deduped,
- malformed: result.malformed,
- errors: result.errors.map((e) => ({ path: e.path, message: e.message })),
- files_with_markers: result.filesWithMarkers.map((f) => ({
- path: f.path,
- markers: f.markers,
- })),
- });
- } else {
- ok(`scanned: ${result.scanned}`);
- ok(`found: ${result.found}`);
- ok(`created: ${result.created}`);
- ok(`deduped: ${result.deduped}`);
- if (result.malformed > 0) ok(`malformed: ${result.malformed}`);
- for (const e of result.errors) {
- info(` error: ${e.path}: ${e.message}`);
- }
- }
- if (flags["strict"] && result.malformed > 0) return 2;
- return 0;
-}
-
-async function cmdBrainMigrateFrontmatter(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- apply: { type: "boolean" },
- yes: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const agent = resolveAgentName(config);
-
- // Mutually exclusive: --dry-run and --apply both set is operator
- // confusion; default is dry-run.
- if (flags["dry-run"] && flags["apply"]) {
- return fail(
- "brain migrate-frontmatter: --dry-run and --apply are mutually exclusive",
- );
- }
- const apply = Boolean(flags["apply"]);
-
- // Non-interactive guard mirrors `o2b brain rollback`: --json output
- // or non-TTY stdin must pass --yes, otherwise a missed prompt would
- // hang or silently misbehave.
- if (apply && !flags["yes"]) {
- if (flags["json"] || !process.stdin.isTTY) {
- return fail(
- "brain migrate-frontmatter --apply requires --yes in non-interactive mode (--json or non-TTY stdin)",
- );
- }
- }
-
- if (!apply) {
- // Dry-run path.
- let plan;
- try {
- plan = planMigration(vault);
- } catch (exc) {
- return fail(
- `migrate-frontmatter plan failed: ${(exc as Error).message ?? exc}`,
- );
- }
- if (flags["json"]) {
- okJson({
- files_scanned: plan.files_scanned,
- files_to_migrate: plan.files_to_migrate.length,
- files_already_new: plan.files_already_new.length,
- collisions: plan.collisions.length,
- collision_files: plan.collisions.map((c) => ({
- path: c.path,
- field: c.field,
- })),
- });
- return 0;
- }
- ok(`files_scanned: ${plan.files_scanned}`);
- ok(`files_to_migrate: ${plan.files_to_migrate.length}`);
- ok(`files_already_new: ${plan.files_already_new.length}`);
- ok(`collisions: ${plan.collisions.length}`);
- if (plan.collisions.length > 0) {
- info("Collisions (both legacy and '_'-prefixed shape present):");
- for (const c of plan.collisions) {
- info(` - ${c.path} (field: ${c.field})`);
- }
- }
- if (plan.files_to_migrate.length === 0) {
- ok("nothing to migrate; re-run with --apply --yes when there is.");
- } else {
- ok("re-run with --apply --yes to rewrite these files.");
- }
- return 0;
- }
-
- // Apply path.
- let result;
- try {
- result = await applyMigration(vault, { snapshot: true, now: new Date() });
- } catch (exc) {
- if (exc instanceof MigrationError) {
- // Surface the collision / parse / io error with the structured
- // message exactly as the core returns it.
- process.stderr.write(`error: ${exc.message}\n`);
- return 1;
- }
- return fail(`migrate-frontmatter failed: ${(exc as Error).message ?? exc}`);
- }
-
- // Emit a log event so the audit trail records the rewrite.
- try {
- appendLogEvent(vault, {
- timestamp: isoSecond(new Date()),
- eventType: BRAIN_LOG_EVENT_KIND.migrateFrontmatter,
- body: {
- run_id: result.run_id,
- agent,
- snapshot: result.snapshot_path ?? "(none)",
- files_scanned: String(result.plan.files_scanned),
- files_migrated: String(result.files_migrated.length),
- files_already_new: String(result.plan.files_already_new.length),
- collisions: String(result.plan.collisions.length),
- },
- });
- } catch (err) {
- process.stderr.write(
- `warning: append migrate-frontmatter log failed: ${(err as Error).message}\n`,
- );
- }
-
- if (flags["json"]) {
- okJson({
- run_id: result.run_id,
- snapshot_path: result.snapshot_path,
- files_scanned: result.plan.files_scanned,
- files_migrated: result.files_migrated.length,
- files_already_new: result.plan.files_already_new.length,
- collisions: result.plan.collisions.length,
- });
- return 0;
- }
- ok(`run_id: ${result.run_id}`);
- ok(`snapshot: ${result.snapshot_path ?? "(none)"}`);
- ok(`files_migrated: ${result.files_migrated.length}`);
- ok(`files_already_new: ${result.plan.files_already_new.length}`);
- return 0;
-}
-
-/**
- * `o2b brain upgrade` β€” migrate release-owned files (`_brain.yaml`,
- * `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward when a new
- * open-second-brain version ships. Default is `--dry-run`; `--apply`
- * (with `--yes` in non-interactive mode) rewrites the files after a
- * pre-apply snapshot.
- */
-async function cmdBrainUpgrade(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- "dry-run": { type: "boolean" },
- apply: { type: "boolean" },
- yes: { type: "boolean" },
- check: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- // Flag matrix. `--dry-run` + `--apply` is contradictory. `--check`
- // is a CI shorthand for "dry-run with non-zero exit on pending";
- // combining it with `--apply` is also contradictory.
- if (flags["dry-run"] && flags["apply"]) {
- return fail("brain upgrade: --dry-run and --apply are mutually exclusive");
- }
- if (flags["check"] && flags["apply"]) {
- return fail("brain upgrade: --check and --apply are mutually exclusive");
- }
-
- let plan: UpgradePlan;
- try {
- plan = planUpgrade(vault);
- } catch (exc) {
- return fail(`upgrade plan failed: ${(exc as Error).message ?? exc}`);
- }
-
- // `--check` is the CI gate: print a one-line summary and exit 2
- // when there is anything to do. Stays read-only.
- if (flags["check"]) {
- if (flags["json"]) {
- okJson(renderUpgradePlanJson(plan));
- } else {
- printUpgradePlanText(plan);
- }
- return plan.pending > 0 || plan.errors > 0 ? 2 : 0;
- }
-
- // Default and `--dry-run` share the same output. Exit 0 either
- // way β€” `--check` is the gate variant.
- if (!flags["apply"]) {
- if (flags["json"]) {
- okJson(renderUpgradePlanJson(plan));
- } else {
- printUpgradePlanText(plan);
- }
- return 0;
- }
-
- // Apply path.
- if (plan.errors > 0) {
- return fail(
- `upgrade aborted: ${plan.errors} file(s) failed to plan; ` +
- `run with --dry-run to inspect the error.`,
- );
- }
- if (plan.pending === 0) {
- if (flags["json"]) {
- okJson({ run_id: "", snapshot_path: "", files_updated: [] });
- } else {
- ok("upgrade: nothing to do; all managed files match the current release.");
- }
- return 0;
- }
- if (!flags["yes"]) {
- if (flags["json"] || !process.stdin.isTTY) {
- return fail(
- "brain upgrade --apply requires --yes in non-interactive mode " +
- "(--json or non-TTY stdin)",
- );
- }
- process.stderr.write(
- `About to rewrite ${plan.pending} managed file(s):\n` +
- plan.files
- .filter((f) => f.status === "update")
- .map((f) => ` - ${f.path}\n`)
- .join("") +
- `A pre-apply snapshot will be taken (rollback via run id).\n` +
- `Proceed? [y/N] `,
- );
- const ans = await readSingleLine();
- if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") {
- ok("upgrade cancelled");
- return 0;
- }
- }
-
- let result;
- try {
- result = applyUpgrade(vault, { now: new Date() });
- } catch (exc) {
- if (exc instanceof BrainUpgradeError) {
- process.stderr.write(`error: ${exc.message}\n`);
- return 1;
- }
- return fail(`upgrade failed: ${(exc as Error).message ?? exc}`);
- }
-
- if (flags["json"]) {
- okJson({
- run_id: result.run_id,
- snapshot_path: result.snapshot_path,
- files_updated: result.files_updated,
- });
- } else {
- ok(`run_id: ${result.run_id}`);
- ok(`snapshot: ${result.snapshot_path}`);
- for (const p of result.files_updated) ok(` updated: ${p}`);
- }
- return 0;
-}
-
-function renderUpgradePlanJson(plan: UpgradePlan): {
- pending: number;
- errors: number;
- files: ReadonlyArray<{
- path: string;
- status: UpgradeFilePlan["status"];
- before_size: number;
- after_size: number;
- error?: string;
- }>;
-} {
- return {
- pending: plan.pending,
- errors: plan.errors,
- files: plan.files.map((f) => ({
- path: f.path,
- status: f.status,
- before_size: f.before.length,
- after_size: f.after.length,
- ...(f.error ? { error: f.error } : {}),
- })),
- };
-}
-
-function printUpgradePlanText(plan: UpgradePlan): void {
- for (const f of plan.files) {
- if (f.status === "noop") {
- ok(` ${f.path}: up to date`);
- continue;
- }
- if (f.status === "error") {
- info(` ${f.path}: ERROR ${f.error}`);
- continue;
- }
- info(` ${f.path}: update (${f.before.length} β†’ ${f.after.length} bytes)`);
- info(renderUnifiedDiff(f.before, f.after, f.path));
- }
- if (plan.pending === 0 && plan.errors === 0) {
- ok("upgrade: all managed files match the current release.");
- } else if (plan.pending > 0) {
- ok(
- `upgrade: ${plan.pending} pending update(s); ` +
- `re-run with --apply --yes when ready.`,
- );
- }
-}
-
-/**
- * Bare-bones unified diff renderer. Good enough for human-eye review
- * inside the CLI. We intentionally avoid pulling a dependency for a
- * cosmetic feature; the algorithm is line-by-line with a small
- * sliding window so identical leading / trailing lines collapse
- * naturally.
- */
-function renderUnifiedDiff(before: string, after: string, label: string): string {
- if (before === after) return "";
- const a = before.split("\n");
- const b = after.split("\n");
- const lines: string[] = [`--- ${label} (live)`, `+++ ${label} (release)`];
- // Skip the matching prefix to keep the diff tight.
- let head = 0;
- while (head < a.length && head < b.length && a[head] === b[head]) head++;
- let tailA = a.length;
- let tailB = b.length;
- while (
- tailA > head &&
- tailB > head &&
- a[tailA - 1] === b[tailB - 1]
- ) {
- tailA--;
- tailB--;
- }
- if (head > 0) {
- lines.push(`@@ context: ${head} matching line(s) above @@`);
- }
- for (let i = head; i < tailA; i++) lines.push(`- ${a[i]}`);
- for (let i = head; i < tailB; i++) lines.push(`+ ${b[i]}`);
- if (tailA < a.length || tailB < b.length) {
- const tailCount = Math.max(a.length - tailA, b.length - tailB);
- lines.push(`@@ context: ${tailCount} matching line(s) below @@`);
- }
- return lines.join("\n");
-}
-
-/**
- * `o2b brain export` (Β§28) β€” read-only dump of active preferences in
- * either JSON or llms-txt format. Default sink is stdout; `--out`
- * writes to a file (refusing to overwrite without `--force`).
- */
-async function cmdBrainExport(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- format: { type: "string" },
- out: { type: "string" },
- force: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
- const format = flags["format"] as string | undefined;
- if (format !== "json" && format !== "llms-txt") {
- process.stderr.write(
- "error: --format is required and must be one of json|llms-txt\n",
- );
- return 2;
- }
-
- let body: string;
- try {
- if (format === "json") {
- body = JSON.stringify(exportPreferencesJson(vault)) + "\n";
- } else {
- body = exportPreferencesLlmsTxt(vault);
- }
- } catch (exc) {
- return fail(`export failed: ${(exc as Error).message ?? exc}`);
- }
-
- const outPath = flags["out"] as string | undefined;
- if (outPath === undefined) {
- process.stdout.write(body);
- return 0;
- }
- if (existsSync(outPath) && !flags["force"]) {
- return fail(`${outPath} exists; pass --force to overwrite`);
- }
- try {
- atomicWriteFileSync(outPath, body);
- } catch (exc) {
- return fail(
- `failed to write ${outPath}: ${(exc as Error).message ?? exc}`,
- );
- }
- ok(`wrote ${outPath}`);
- return 0;
-}
-
-async function cmdBrainDoctor(argv: string[]): Promise<number> {
- const { flags } = parse(argv, {
- vault: { type: "string" },
- strict: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
-
- let result;
- try {
- result = runDoctor(vault, { strict: Boolean(flags["strict"]) });
- } catch (exc) {
- return fail(`doctor failed: ${(exc as Error).message ?? exc}`);
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- { warnings: result.warnings, errors: result.errors },
- null,
- 2,
- ) + "\n",
- );
- } else {
- for (const e of result.errors) {
- process.stdout.write(
- `[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`,
- );
- }
- for (const w of result.warnings) {
- process.stdout.write(
- `[WARN] ${w.code}: ${w.message}${w.path ? ` (${w.path})` : ""}\n`,
- );
- }
- if (result.errors.length === 0 && result.warnings.length === 0) {
- ok("brain doctor: clean");
- }
- }
-
- // Exit-code matrix per Β§9.2: errors β†’ 1; warnings β†’ 0 unless --strict
- // (then 2); clean β†’ 0.
- if (result.errors.length > 0) return 1;
- if (result.warnings.length > 0 && flags["strict"]) return 2;
- return 0;
-}
-
-// ── Help text ───────────────────────────────────────────────────────────────
-
-const BRAIN_HELP = `usage: o2b brain <verb> [args...]
-
-Brain verbs (observing memory):
- init Bootstrap <vault>/Brain/ (idempotent; --force overwrites)
- feedback Record a taste signal (--topic, --signal, --principle)
- dream Run the deterministic dreaming pass (idempotent)
- apply-evidence Log a real-work application of a preference
- digest Render the recent-changes digest (markdown or --json)
- query Read by --preference, --topic, or --since
- reject Move a preference to retired (user-rejected); --yes if pinned
- pin Mark a preference exempt from automatic retire (idempotent)
- unpin Clear the pinned flag (idempotent)
- set-primary Declare or clear primary_agent in _brain.yaml (--clear)
- protect Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
- unprotect Remove OSB-managed deny rules for the chosen target (--target)
- merge Merge two near-duplicate preferences (<keep> <drop>; --dry-run, --force)
- upgrade Migrate release-owned files forward (--dry-run by default; --apply --yes)
- export Dump active preferences (--format json|llms-txt [--out <path>])
- explorer Launch the loopback HTML explorer; --export <path> writes a single offline file
- snapshot diff Read-only diff between two snapshots, or snapshot vs live
- rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
- --dry-run previews via the same diff renderer)
- doctor Validate Brain invariants (--strict promotes warnings to exit 2)
- backlinks List inbound references to a Brain artifact id
- migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'
- scan-inline Capture @osb markers from vault markdown files (Daily/, project notes, etc.)
- import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)
- import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferences
-
-Common flags:
- --vault <path> Override the configured vault
- --json Structured output where applicable
- --help Per-verb help (run \`o2b brain <verb> --help\`)
-`;
-
-const VERB_HELP: Record<string, string> = {
- init:
- "usage: o2b brain init [--vault <path>] [--force] [--primary-agent <name>] [--json]\n" +
- "Bootstrap <vault>/Brain/. Requires `o2b init` to have run first.\n" +
- "--primary-agent <name> writes the value into _brain.yaml on first init;\n" +
- "on re-run against an existing _brain.yaml use `o2b brain set-primary` instead.\n",
- feedback:
- "usage: o2b brain feedback --topic <slug> --signal positive|negative --principle <text>\n" +
- " [--scope <slug>] [--source <wikilink>...] [--agent <name>] [--raw <text>|--raw-file <path>]\n" +
- " [--force-confirmed] [--vault <path>] [--json]\n" +
- "Creates a `sig-*.md` in Brain/inbox/. With --force-confirmed also creates a `pref-*.md`.\n",
- dream:
- "usage: o2b brain dream [--vault <path>] [--dry-run] [--now <ISO-8601>] [--json]\n" +
- "Runs the deterministic dreaming algorithm. Idempotent on rerun.\n",
- "apply-evidence":
- "usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
- " [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
- "Appends a single event to today's log. Missing preference exits 2.\n",
- digest:
- "usage: o2b brain digest [--vault <path>] [--since <ISO>] [--until <ISO>] [--json] [--silent-if-empty]\n" +
- "Renders the 24-hour change digest. Empty + --silent-if-empty exits 2.\n",
- query:
- "usage: o2b brain query --preference <id> | --topic <slug> | --since <ISO> [--vault <path>] [--json]\n" +
- "Read-only lookup. One of --preference / --topic / --since is required.\n",
- reject:
- "usage: o2b brain reject --id <pref-id> --reason <text> [--yes] [--vault <path>] [--json]\n" +
- "Move a preference to retired/ with reason 'user-rejected'. --yes required when pinned.\n",
- pin:
- "usage: o2b brain pin --id <pref-id> [--vault <path>] [--json]\n" +
- "Set pinned: true. Idempotent. Exempts the preference from automatic retire.\n",
- unpin:
- "usage: o2b brain unpin --id <pref-id> [--vault <path>] [--json]\n" +
- "Clear pinned: true. Idempotent.\n",
- rollback:
- "usage: o2b brain rollback <run_id> [--vault <path>] [--yes]\n" +
- " [--force-rollback] [--json]\n" +
- " o2b brain rollback <run_id> --dry-run [--vault <path>] [--json]\n" +
- " o2b brain rollback --list [--vault <path>] [--json]\n" +
- "Restore Brain/ from a snapshot. Interactive prompt unless --yes.\n" +
- "--dry-run prints the would-be restore plan as live β†’ snapshot\n" +
- "diff and exits 0 without writing.\n" +
- "From v0.10.6 each snapshot carries a sidecar sha256 manifest of\n" +
- "the Brain/ tree captured at snapshot time. rollback compares it\n" +
- "against the current Brain/ and aborts with exit 2 if they\n" +
- "differ β€” typically because another device (Syncthing) edited the\n" +
- "vault between snapshot and rollback. Pass --force-rollback to\n" +
- "overwrite anyway; the log entry records `drift_overridden: true`.\n" +
- "Snapshots produced before v0.10.6 have no sidecar; rollback emits\n" +
- "a stderr warning and falls through to the legacy direct-restore\n" +
- "path.\n",
- snapshot:
- "usage: o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" +
- " [--vault <path>] [--json]\n" +
- "Read-only diff between two snapshots, or between a snapshot and\n" +
- "the live Brain/ tree (when <run_id_b> is omitted).\n",
- doctor:
- "usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +
- "Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n",
- backlinks:
- "usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
- "List inbound references to the given Brain artifact id (preference, retired, signal).\n",
- "migrate-frontmatter":
- "usage: o2b brain migrate-frontmatter [--vault <path>] [--apply] [--yes] [--json]\n" +
- "Rewrite legacy Group C frontmatter keys ('status:', 'applied_count:', ...)\n" +
- "to the '_'-prefixed shape across Brain/preferences/ and Brain/retired/.\n" +
- "Default is --dry-run; --apply takes a pre-run snapshot (rollback via run_id).\n" +
- "--apply requires --yes in non-interactive mode (--json or non-TTY stdin).\n",
- "set-primary":
- "usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
- " o2b brain set-primary --clear [--vault <path>] [--json]\n" +
- "Declare which agent owns the dream consolidation pass for this vault.\n" +
- "Stored in Brain/_brain.yaml as `primary_agent:`. Dream runs from a\n" +
- "different agent emit a warning but still proceed (observability, not\n" +
- "access control). Use --clear to remove the declaration.\n",
- "scan-inline":
- "usage: o2b brain scan-inline [--vault <path>] [--path <subdir>...] [--exclude <subdir>...]\n" +
- " [--dry-run] [--strict] [--json] [--agent <name>]\n" +
- "Walk the vault for @osb markers (inline form and fenced 'osb' blocks),\n" +
- "create signals in Brain/inbox/, and annotate the source files with\n" +
- "@osbβœ“ [[sig-...]]. Brain/, .git, node_modules, and similar directories\n" +
- "are always skipped. Idempotent on re-run.\n",
- "import-claude-memory":
- "usage: o2b brain import-claude-memory [--vault <path>] [--memory <path>]\n" +
- " [--dry-run | --apply] [--yes] [--json]\n" +
- " [--allow-arbitrary-memory-path]\n" +
- "Read metadata.type:feedback entries from a Claude Code memory directory and\n" +
- "write them as confirmed Brain preferences. A sidecar manifest\n" +
- "Brain/.imports/claude-memory.json tracks idempotency. UPDATE preserves\n" +
- "accumulated evidence fields. CONFLICT (preference exists without a manifest\n" +
- "entry) exits 2 β€” never silent overwrites.\n" +
- "Default is --dry-run; --apply requires --yes in non-interactive mode.\n",
- "import-session":
- "usage: o2b brain import-session <path> [--vault <vault>]\n" +
- " [--format auto|claude|codex|hermes]\n" +
- " [--since <ISO>] [--dry-run] [--json]\n" +
- "Extract signals from a Claude / Codex / Hermes session .jsonl file (or\n" +
- "directory of .jsonl files). Two extraction paths run in parallel:\n" +
- "@osb markers in user/assistant messages, and replay of brain_feedback\n" +
- "tool_use calls. Dedup against the inbox by normalised payload hash.\n" +
- "Autodetect failure exits 2 β€” pass --format to override.\n",
- merge:
- "usage: o2b brain merge <keep-pref-id> <drop-pref-id>\n" +
- " [--dry-run] [--force] [--vault <path>] [--json]\n" +
- " [--agent <name>]\n" +
- "Merge two near-duplicate preferences. <keep> retains identity and\n" +
- "principle; <drop> retires with reason 'merged-into' and a\n" +
- "superseded_by wikilink to <keep>. <keep> picks up the sorted-dedup\n" +
- "union of evidenced_by, the summed applied_count / violated_count,\n" +
- "and max(last_evidence_at). Confidence is recomputed by the next\n" +
- "dream pass β€” not by merge itself.\n" +
- "--dry-run prints the plan and writes nothing.\n" +
- "--force skips the interactive prompt but does NOT bypass invariant\n" +
- "guards (topic/scope mismatch, pin parity).\n",
- export:
- "usage: o2b brain export --format json|llms-txt [--vault <path>]\n" +
- " [--out <path>] [--force]\n" +
- "Read-only dump of active preferences (confirmed | unconfirmed |\n" +
- "quarantine) from Brain/preferences/. Retired and signal entries\n" +
- "are not included. JSON is single-line; llms-txt follows the\n" +
- "llmstxt.org H1 + summary + H2-section shape.\n" +
- "Default sink is stdout; --out writes to <path> (refuses to\n" +
- "overwrite without --force).\n",
- upgrade:
- "usage: o2b brain upgrade [--vault <path>] [--dry-run | --apply | --check]\n" +
- " [--yes] [--json]\n" +
- "Migrate the three release-owned files (`Brain/_brain.yaml`,\n" +
- "`Brain/_BRAIN.md`, `AI Wiki/_OPEN_SECOND_BRAIN.md`) forward to the\n" +
- "shape the installed open-second-brain release ships.\n" +
- "User-owned content (preferences/, retired/, inbox/, log/) is\n" +
- "never touched.\n" +
- "--dry-run (default) prints a per-file plan with a unified diff\n" +
- "for every pending update. Exit 0 regardless of pending count.\n" +
- "--check is dry-run + exit 2 when anything is pending or in error\n" +
- "(CI-friendly).\n" +
- "--apply takes a pre-apply snapshot named upgrade-<ts> (rollback\n" +
- "via run_id) and rewrites every pending file. Requires --yes in\n" +
- "non-interactive mode (--json or non-TTY stdin).\n" +
- "_brain.yaml merge is purely additive: missing schema-keys are\n" +
- "appended, existing values stay. _BRAIN.md and\n" +
- "_OPEN_SECOND_BRAIN.md are byte-compared against the rendered\n" +
- "template and overwritten when they differ.\n",
- explorer:
- "usage: o2b brain explorer [--port <n>] [--vault <path>]\n" +
- " o2b brain explorer --export <path> [--force] [--vault <path>]\n" +
- "Live mode: bind a loopback HTTP server on 127.0.0.1:<port> (default\n" +
- "7777) that renders preferences and retired entries as a force-directed\n" +
- "graph. Press Ctrl+C to stop.\n" +
- "Export mode: write the same view as a single offline HTML file at\n" +
- "<path>. Without --force, refuses to overwrite an existing file.\n" +
- "Zero backend, no LLM, no network access. The page consumes a\n" +
- "prebuilt JSON graph; it does not parse vault Markdown client-side.\n",
-};
-
-// ── Public entry point ──────────────────────────────────────────────────────
-
-/**
- * Dispatch `o2b brain <verb> [...args]`. Returns the exit code; the caller
- * (`main.ts`) forwards it to `process.exit`. Unknown verbs print the
- * brain help text and return 2.
- */
-export async function handleBrainSubcommand(
- argv: ReadonlyArray<string>,
-): Promise<number> {
+ cmdBrainInit,
+ cmdBrainFeedback,
+ cmdBrainDream,
+ cmdBrainApplyEvidence,
+ cmdBrainDigest,
+ cmdBrainQuery,
+ cmdBrainReject,
+ cmdBrainPin,
+ cmdBrainUnpin,
+ cmdBrainSetPrimary,
+ cmdBrainProtect,
+ cmdBrainUnprotect,
+ cmdBrainRollback,
+ cmdBrainDoctor,
+ cmdBrainBacklinks,
+ cmdBrainMerge,
+ cmdBrainExplorer,
+ cmdBrainExport,
+ cmdBrainUpgrade,
+ handleBrainSnapshotSubcommand,
+ cmdBrainMigrateFrontmatter,
+ cmdBrainScanInline,
+ cmdBrainImportSession,
+ cmdBrainImportClaudeMemory,
+} from "./brain/verbs/index.ts";
+
+export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promise<number> {
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
process.stdout.write(BRAIN_HELP);
return argv.length === 0 ? 2 : 0;
@@ -2452,193 +43,46 @@ export async function handleBrainSubcommand(
const verb = argv[0]!;
const rest = argv.slice(1);
- // Per-verb help.
if (rest.length === 1 && (rest[0] === "-h" || rest[0] === "--help")) {
const text = VERB_HELP[verb];
- if (text) {
- process.stdout.write(text);
- return 0;
- }
- // Unknown verb requesting --help: fall back to generic brain help
- // and return 2 (same exit code as the unknown-verb branch in the
- // dispatcher below).
+ if (text) { process.stdout.write(text); return 0; }
process.stdout.write(BRAIN_HELP);
return 2;
}
try {
switch (verb) {
- case "init":
- return await cmdBrainInit(rest);
- case "feedback":
- return await cmdBrainFeedback(rest);
- case "dream":
- return await cmdBrainDream(rest);
- case "apply-evidence":
- return await cmdBrainApplyEvidence(rest);
- case "digest":
- return await cmdBrainDigest(rest);
- case "query":
- return await cmdBrainQuery(rest);
- case "reject":
- return await cmdBrainReject(rest);
- case "pin":
- return await cmdBrainPin(rest);
- case "unpin":
- return await cmdBrainUnpin(rest);
- case "set-primary":
- return await cmdBrainSetPrimary(rest);
- case "protect":
- return await cmdBrainProtect(rest);
- case "unprotect":
- return await cmdBrainUnprotect(rest);
- case "snapshot":
- return await handleBrainSnapshotSubcommand(rest);
- case "rollback":
- return await cmdBrainRollback(rest);
- case "doctor":
- return await cmdBrainDoctor(rest);
- case "backlinks":
- return await cmdBrainBacklinks(rest);
- case "migrate-frontmatter":
- return await cmdBrainMigrateFrontmatter(rest);
- case "scan-inline":
- return await cmdBrainScanInline(rest);
- case "import-session":
- return await cmdBrainImportSession(rest);
- case "import-claude-memory":
- return await cmdBrainImportClaudeMemory(rest);
- case "merge":
- return await cmdBrainMerge(rest);
- case "upgrade":
- return await cmdBrainUpgrade(rest);
- case "export":
- return await cmdBrainExport(rest);
- case "explorer":
- return await cmdBrainExplorer(rest);
+ case "init": return await cmdBrainInit(rest);
+ case "feedback": return await cmdBrainFeedback(rest);
+ case "dream": return await cmdBrainDream(rest);
+ case "apply-evidence": return await cmdBrainApplyEvidence(rest);
+ case "digest": return await cmdBrainDigest(rest);
+ case "query": return await cmdBrainQuery(rest);
+ case "reject": return await cmdBrainReject(rest);
+ case "pin": return await cmdBrainPin(rest);
+ case "unpin": return await cmdBrainUnpin(rest);
+ case "set-primary": return await cmdBrainSetPrimary(rest);
+ case "protect": return await cmdBrainProtect(rest);
+ case "unprotect": return await cmdBrainUnprotect(rest);
+ case "snapshot": return await handleBrainSnapshotSubcommand(rest);
+ case "rollback": return await cmdBrainRollback(rest);
+ case "doctor": return await cmdBrainDoctor(rest);
+ case "backlinks": return await cmdBrainBacklinks(rest);
+ case "migrate-frontmatter": return await cmdBrainMigrateFrontmatter(rest);
+ case "scan-inline": return await cmdBrainScanInline(rest);
+ case "import-session": return await cmdBrainImportSession(rest);
+ case "import-claude-memory": return await cmdBrainImportClaudeMemory(rest);
+ case "merge": return await cmdBrainMerge(rest);
+ case "upgrade": return await cmdBrainUpgrade(rest);
+ case "export": return await cmdBrainExport(rest);
+ case "explorer": return await cmdBrainExplorer(rest);
default:
process.stderr.write(`error: unknown brain verb: ${verb}\n`);
process.stdout.write(BRAIN_HELP);
return 2;
}
} catch (exc) {
- if (exc instanceof CliError) {
- process.stderr.write(`error: ${exc.message}\n`);
- return 1;
- }
+ if (exc instanceof CliError) { process.stderr.write(`error: ${exc.message}\n`); return 1; }
throw exc;
}
}
-
-// ── Helpers ─────────────────────────────────────────────────────────────────
-
-interface DiffSummary {
- readonly preferences: number;
- readonly retired: number;
- readonly signals: number;
-}
-
-/**
- * Count the entries currently under `Brain/{preferences,retired,inbox}/`.
- * Used for the interactive rollback confirmation so the operator sees
- * the scale of the overwrite before pressing `y`.
- */
-function diffSummary(vault: string): DiffSummary {
- const root = resolve(vault, "Brain");
- const safeCount = (p: string): number => {
- if (!existsSync(p)) return 0;
- try {
- const st = statSync(p);
- if (!st.isDirectory()) return 0;
- } catch {
- return 0;
- }
- try {
- const entries: Dirent[] = readdirSync(p, { withFileTypes: true });
- return entries.filter((e) => e.isFile() && e.name.endsWith(".md")).length;
- } catch {
- return 0;
- }
- };
- return {
- preferences: safeCount(resolve(root, "preferences")),
- retired: safeCount(resolve(root, "retired")),
- signals: safeCount(resolve(root, "inbox")),
- };
-}
-
-/**
- * Read a single trimmed line from stdin. Returns `""` on EOF so the
- * default-N branch fires when the prompt receives no input (pipe closed,
- * non-interactive shell).
- */
-function readSingleLine(): Promise<string> {
- return new Promise((res) => {
- let buf = "";
- const onData = (chunk: Buffer | string): void => {
- buf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
- const nl = buf.indexOf("\n");
- if (nl >= 0) {
- process.stdin.removeListener("data", onData);
- process.stdin.removeListener("end", onEnd);
- process.stdin.pause();
- res(buf.slice(0, nl).trim());
- }
- };
- const onEnd = (): void => {
- process.stdin.removeListener("data", onData);
- process.stdin.removeListener("end", onEnd);
- res(buf.trim());
- };
- process.stdin.resume();
- process.stdin.on("data", onData);
- process.stdin.on("end", onEnd);
- });
-}
-
-// ── Renderers (text mode) ───────────────────────────────────────────────────
-
-function renderQueryPreferenceText(
- out: ReturnType<typeof queryByPreference>,
-): void {
- const p = out.preference;
- ok(`id: ${p.id}`);
- ok(`topic: ${p.topic}`);
- if (p.scope) ok(`scope: ${p.scope}`);
- ok(`status: ${"status" in p ? p.status : "(unknown)"}`);
- ok(`principle: ${p.principle}`);
- if (out.evidence.length === 0) {
- ok("evidence: (none)");
- return;
- }
- ok("evidence:");
- for (const e of out.evidence) {
- const artifact = e.body["artifact"] ?? "(unknown)";
- const result = e.body["result"] ?? "(unknown)";
- info(` - ${e.timestamp} ${result}: ${artifact}`);
- }
-}
-
-function renderQueryTopicText(
- out: ReturnType<typeof queryByTopic>,
- topic: string,
-): void {
- ok(`topic: ${topic}`);
- if (out.preference) {
- ok(`preference: ${out.preference.id}`);
- } else {
- ok("preference: (none)");
- }
- ok(`signals: ${out.signals.length}`);
- for (const s of out.signals) {
- info(` - ${s.id} (${s.signal}, ${s.created_at})`);
- }
- ok(`log_events: ${out.all_log_events.length}`);
-}
-
-function renderQueryLogText(entries: ReadonlyArray<BrainLogEntry>): void {
- ok(`entries: ${entries.length}`);
- for (const e of entries) {
- info(` - ${e.timestamp} ${e.eventType}`);
- }
-}
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
new file mode 100644
index 00000000..b6dcb86d
--- /dev/null
+++ b/src/cli/brain/help-text.ts
@@ -0,0 +1,196 @@
+/**
+ * Help text for `o2b brain` and each of its verbs.
+ *
+ * Pure data: no runtime imports beyond what the dispatcher needs.
+ * Split out of `./helpers.ts` so the verb-handler bundle does not
+ * have to load this ~200-line string table when it only needs
+ * `parse` / `resolveBrainVault`.
+ */
+
+export const BRAIN_HELP = `usage: o2b brain <verb> [args...]
+
+Brain verbs (observing memory):
+ init Bootstrap <vault>/Brain/ (idempotent; --force overwrites)
+ feedback Record a taste signal (--topic, --signal, --principle)
+ dream Run the deterministic dreaming pass (idempotent)
+ apply-evidence Log a real-work application of a preference
+ digest Render the recent-changes digest (markdown or --json)
+ query Read by --preference, --topic, or --since
+ reject Move a preference to retired (user-rejected); --yes if pinned
+ pin Mark a preference exempt from automatic retire (idempotent)
+ unpin Clear the pinned flag (idempotent)
+ set-primary Declare or clear primary_agent in _brain.yaml (--clear)
+ protect Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])
+ unprotect Remove OSB-managed deny rules for the chosen target (--target)
+ merge Merge two near-duplicate preferences (<keep> <drop>; --dry-run, --force)
+ upgrade Migrate release-owned files forward (--dry-run by default; --apply --yes)
+ export Dump active preferences (--format json|llms-txt [--out <path>])
+ explorer Launch the loopback HTML explorer; --export <path> writes a single offline file
+ snapshot diff Read-only diff between two snapshots, or snapshot vs live
+ rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
+ --dry-run previews via the same diff renderer)
+ doctor Validate Brain invariants (--strict promotes warnings to exit 2)
+ backlinks List inbound references to a Brain artifact id
+ migrate-frontmatter Rewrite legacy 'status:' / 'applied_count:' keys to '_status:' / '_applied_count:'
+ scan-inline Capture @osb markers from vault markdown files (Daily/, project notes, etc.)
+ import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)
+ import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferences
+
+Common flags:
+ --vault <path> Override the configured vault
+ --json Structured output where applicable
+ --help Per-verb help (run \`o2b brain <verb> --help\`)
+`;
+
+export const VERB_HELP: Record<string, string> = {
+ init:
+ "usage: o2b brain init [--vault <path>] [--force] [--primary-agent <name>] [--json]\n" +
+ "Bootstrap <vault>/Brain/. Requires `o2b init` to have run first.\n" +
+ "--primary-agent <name> writes the value into _brain.yaml on first init;\n" +
+ "on re-run against an existing _brain.yaml use `o2b brain set-primary` instead.\n",
+ feedback:
+ "usage: o2b brain feedback --topic <slug> --signal positive|negative --principle <text>\n" +
+ " [--scope <slug>] [--source <wikilink>...] [--agent <name>] [--raw <text>|--raw-file <path>]\n" +
+ " [--force-confirmed] [--vault <path>] [--json]\n" +
+ "Creates a `sig-*.md` in Brain/inbox/. With --force-confirmed also creates a `pref-*.md`.\n",
+ dream:
+ "usage: o2b brain dream [--vault <path>] [--dry-run] [--now <ISO-8601>] [--json]\n" +
+ "Runs the deterministic dreaming algorithm. Idempotent on rerun.\n",
+ "apply-evidence":
+ "usage: o2b brain apply-evidence --pref <id> --artifact <wikilink> --result applied|violated|outdated\n" +
+ " [--agent <name>] [--note <text>] [--vault <path>] [--json]\n" +
+ "Appends a single event to today's log. Missing preference exits 2.\n",
+ digest:
+ "usage: o2b brain digest [--vault <path>] [--since <ISO>] [--until <ISO>] [--json] [--silent-if-empty]\n" +
+ "Renders the 24-hour change digest. Empty + --silent-if-empty exits 2.\n",
+ query:
+ "usage: o2b brain query --preference <id> | --topic <slug> | --since <ISO> [--vault <path>] [--json]\n" +
+ "Read-only lookup. One of --preference / --topic / --since is required.\n",
+ reject:
+ "usage: o2b brain reject --id <pref-id> --reason <text> [--yes] [--vault <path>] [--json]\n" +
+ "Move a preference to retired/ with reason 'user-rejected'. --yes required when pinned.\n",
+ pin:
+ "usage: o2b brain pin --id <pref-id> [--vault <path>] [--json]\n" +
+ "Set pinned: true. Idempotent. Exempts the preference from automatic retire.\n",
+ unpin:
+ "usage: o2b brain unpin --id <pref-id> [--vault <path>] [--json]\n" +
+ "Clear pinned: true. Idempotent.\n",
+ rollback:
+ "usage: o2b brain rollback <run_id> [--vault <path>] [--yes]\n" +
+ " [--force-rollback] [--json]\n" +
+ " o2b brain rollback <run_id> --dry-run [--vault <path>] [--json]\n" +
+ " o2b brain rollback --list [--vault <path>] [--json]\n" +
+ "Restore Brain/ from a snapshot. Interactive prompt unless --yes.\n" +
+ "--dry-run prints the would-be restore plan as live β†’ snapshot\n" +
+ "diff and exits 0 without writing.\n" +
+ "From v0.10.6 each snapshot carries a sidecar sha256 manifest of\n" +
+ "the Brain/ tree captured at snapshot time. rollback compares it\n" +
+ "against the current Brain/ and aborts with exit 2 if they\n" +
+ "differ β€” typically because another device (Syncthing) edited the\n" +
+ "vault between snapshot and rollback. Pass --force-rollback to\n" +
+ "overwrite anyway; the log entry records `drift_overridden: true`.\n" +
+ "Snapshots produced before v0.10.6 have no sidecar; rollback emits\n" +
+ "a stderr warning and falls through to the legacy direct-restore\n" +
+ "path.\n",
+ snapshot:
+ "usage: o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" +
+ " [--vault <path>] [--json]\n" +
+ "Read-only diff between two snapshots, or between a snapshot and\n" +
+ "the live Brain/ tree (when <run_id_b> is omitted).\n",
+ doctor:
+ "usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +
+ "Validate invariants. Warnings exit 0 (or 2 with --strict). Errors always exit 1.\n",
+ backlinks:
+ "usage: o2b brain backlinks <id> [--vault <path>] [--json]\n" +
+ "List inbound references to the given Brain artifact id (preference, retired, signal).\n",
+ "migrate-frontmatter":
+ "usage: o2b brain migrate-frontmatter [--vault <path>] [--apply] [--yes] [--json]\n" +
+ "Rewrite legacy Group C frontmatter keys ('status:', 'applied_count:', ...)\n" +
+ "to the '_'-prefixed shape across Brain/preferences/ and Brain/retired/.\n" +
+ "Default is --dry-run; --apply takes a pre-run snapshot (rollback via run_id).\n" +
+ "--apply requires --yes in non-interactive mode (--json or non-TTY stdin).\n",
+ "set-primary":
+ "usage: o2b brain set-primary <name> [--vault <path>] [--json]\n" +
+ " o2b brain set-primary --clear [--vault <path>] [--json]\n" +
+ "Declare which agent owns the dream consolidation pass for this vault.\n" +
+ "Stored in Brain/_brain.yaml as `primary_agent:`. Dream runs from a\n" +
+ "different agent emit a warning but still proceed (observability, not\n" +
+ "access control). Use --clear to remove the declaration.\n",
+ "scan-inline":
+ "usage: o2b brain scan-inline [--vault <path>] [--path <subdir>...] [--exclude <subdir>...]\n" +
+ " [--dry-run] [--strict] [--json] [--agent <name>]\n" +
+ "Walk the vault for @osb markers (inline form and fenced 'osb' blocks),\n" +
+ "create signals in Brain/inbox/, and annotate the source files with\n" +
+ "@osbβœ“ [[sig-...]]. Brain/, .git, node_modules, and similar directories\n" +
+ "are always skipped. Idempotent on re-run.\n",
+ "import-claude-memory":
+ "usage: o2b brain import-claude-memory [--vault <path>] [--memory <path>]\n" +
+ " [--dry-run | --apply] [--yes] [--json]\n" +
+ " [--allow-arbitrary-memory-path]\n" +
+ "Read metadata.type:feedback entries from a Claude Code memory directory and\n" +
+ "write them as confirmed Brain preferences. A sidecar manifest\n" +
+ "Brain/.imports/claude-memory.json tracks idempotency. UPDATE preserves\n" +
+ "accumulated evidence fields. CONFLICT (preference exists without a manifest\n" +
+ "entry) exits 2 β€” never silent overwrites.\n" +
+ "Default is --dry-run; --apply requires --yes in non-interactive mode.\n",
+ "import-session":
+ "usage: o2b brain import-session <path> [--vault <vault>]\n" +
+ " [--format auto|claude|codex|hermes]\n" +
+ " [--since <ISO>] [--dry-run] [--json]\n" +
+ "Extract signals from a Claude / Codex / Hermes session .jsonl file (or\n" +
+ "directory of .jsonl files). Two extraction paths run in parallel:\n" +
+ "@osb markers in user/assistant messages, and replay of brain_feedback\n" +
+ "tool_use calls. Dedup against the inbox by normalised payload hash.\n" +
+ "Autodetect failure exits 2 β€” pass --format to override.\n",
+ merge:
+ "usage: o2b brain merge <keep-pref-id> <drop-pref-id>\n" +
+ " [--dry-run] [--force] [--vault <path>] [--json]\n" +
+ " [--agent <name>]\n" +
+ "Merge two near-duplicate preferences. <keep> retains identity and\n" +
+ "principle; <drop> retires with reason 'merged-into' and a\n" +
+ "superseded_by wikilink to <keep>. <keep> picks up the sorted-dedup\n" +
+ "union of evidenced_by, the summed applied_count / violated_count,\n" +
+ "and max(last_evidence_at). Confidence is recomputed by the next\n" +
+ "dream pass β€” not by merge itself.\n" +
+ "--dry-run prints the plan and writes nothing.\n" +
+ "--force skips the interactive prompt but does NOT bypass invariant\n" +
+ "guards (topic/scope mismatch, pin parity).\n",
+ export:
+ "usage: o2b brain export --format json|llms-txt [--vault <path>]\n" +
+ " [--out <path>] [--force]\n" +
+ "Read-only dump of active preferences (confirmed | unconfirmed |\n" +
+ "quarantine) from Brain/preferences/. Retired and signal entries\n" +
+ "are not included. JSON is single-line; llms-txt follows the\n" +
+ "llmstxt.org H1 + summary + H2-section shape.\n" +
+ "Default sink is stdout; --out writes to <path> (refuses to\n" +
+ "overwrite without --force).\n",
+ upgrade:
+ "usage: o2b brain upgrade [--vault <path>] [--dry-run | --apply | --check]\n" +
+ " [--yes] [--json]\n" +
+ "Migrate the three release-owned files (`Brain/_brain.yaml`,\n" +
+ "`Brain/_BRAIN.md`, `AI Wiki/_OPEN_SECOND_BRAIN.md`) forward to the\n" +
+ "shape the installed open-second-brain release ships.\n" +
+ "User-owned content (preferences/, retired/, inbox/, log/) is\n" +
+ "never touched.\n" +
+ "--dry-run (default) prints a per-file plan with a unified diff\n" +
+ "for every pending update. Exit 0 regardless of pending count.\n" +
+ "--check is dry-run + exit 2 when anything is pending or in error\n" +
+ "(CI-friendly).\n" +
+ "--apply takes a pre-apply snapshot named upgrade-<ts> (rollback\n" +
+ "via run_id) and rewrites every pending file. Requires --yes in\n" +
+ "non-interactive mode (--json or non-TTY stdin).\n" +
+ "_brain.yaml merge is purely additive: missing schema-keys are\n" +
+ "appended, existing values stay. _BRAIN.md and\n" +
+ "_OPEN_SECOND_BRAIN.md are byte-compared against the rendered\n" +
+ "template and overwritten when they differ.\n",
+ explorer:
+ "usage: o2b brain explorer [--port <n>] [--vault <path>]\n" +
+ " o2b brain explorer --export <path> [--force] [--vault <path>]\n" +
+ "Live mode: bind a loopback HTTP server on 127.0.0.1:<port> (default\n" +
+ "7777) that renders preferences and retired entries as a force-directed\n" +
+ "graph. Press Ctrl+C to stop.\n" +
+ "Export mode: write the same view as a single offline HTML file at\n" +
+ "<path>. Without --force, refuses to overwrite an existing file.\n" +
+ "Zero backend, no LLM, no network access. The page consumes a\n" +
+ "prebuilt JSON graph; it does not parse vault Markdown client-side.\n",
+};
diff --git a/src/cli/brain/helpers.ts b/src/cli/brain/helpers.ts
new file mode 100644
index 00000000..1356dac6
--- /dev/null
+++ b/src/cli/brain/helpers.ts
@@ -0,0 +1,74 @@
+/**
+ * Brain CLI verb-handler facade.
+ *
+ * # Import convention (load-bearing)
+ *
+ * Every file under `src/cli/brain/verbs/` MUST import shared helpers
+ * through this module β€” never directly from `../argparse.ts`,
+ * `../output.ts`, `../coerce.ts`, or `../helpers.ts`. The barrel
+ * keeps one source of truth for "what is available to a brain verb"
+ * and lets the helper bodies move between submodules without a
+ * cross-cutting import sweep.
+ *
+ * # Layout
+ *
+ * - `./help-text.ts` β€” `BRAIN_HELP` + per-verb `VERB_HELP`.
+ * - `./upgrade-render.ts` β€” `renderUpgradePlanJson`,
+ * `printUpgradePlanText`,
+ * `renderUnifiedDiff`.
+ * - `./query-render.ts` β€” text renderers for `brain query`.
+ * - `./rollback-prompt.ts` β€” `diffSummary`, `readSingleLine`.
+ *
+ * Vault resolution and the `parse` flag-parsing wrapper stay in this
+ * file because they are tiny and called by every verb.
+ */
+
+import { resolveVault } from "../../core/config.ts";
+
+import { CliError, parseFlags, type FlagsSchema } from "../argparse.ts";
+import { NO_VAULT_ERROR } from "../helpers.ts";
+
+// ── Vault resolution ────────────────────────────────────────────────────────
+
+export function resolveBrainVault(
+ flagVal: string | undefined,
+ configPath: string | null,
+): string {
+ const vault = flagVal ?? resolveVault(configPath ?? undefined);
+ if (vault === null || vault === undefined) {
+ throw new CliError(NO_VAULT_ERROR);
+ }
+ return vault;
+}
+
+// ── Flag-parsing wrapper ────────────────────────────────────────────────────
+
+export function parse(
+ argv: ReadonlyArray<string>,
+ schema: FlagsSchema,
+): {
+ flags: Record<string, string | boolean | string[] | undefined>;
+ positional: string[];
+} {
+ return parseFlags(argv, schema);
+}
+
+// ── Re-exports (the barrel that verb handlers import from) ──────────────────
+
+export { CliError } from "../argparse.ts";
+export { fail, info, ok, okJson } from "../output.ts";
+export { ISO_8601_RE, parseOptionalIsoDate } from "../coerce.ts";
+export { NO_VAULT_ERROR } from "../helpers.ts";
+
+export { BRAIN_HELP, VERB_HELP } from "./help-text.ts";
+export {
+ renderUpgradePlanJson,
+ printUpgradePlanText,
+ renderUnifiedDiff,
+} from "./upgrade-render.ts";
+export {
+ renderQueryPreferenceText,
+ renderQueryTopicText,
+ renderQueryLogText,
+} from "./query-render.ts";
+export { diffSummary, readSingleLine, type DiffSummary } from "./rollback-prompt.ts";
diff --git a/src/cli/brain/query-render.ts b/src/cli/brain/query-render.ts
new file mode 100644
index 00000000..0803dea0
--- /dev/null
+++ b/src/cli/brain/query-render.ts
@@ -0,0 +1,59 @@
+/**
+ * Text renderers for `o2b brain query` results.
+ *
+ * Pure projection of the typed `queryByPreference` / `queryByTopic`
+ * results plus log-entry arrays into stdout. JSON output uses the
+ * raw shapes; this module only handles the human-readable variant.
+ */
+
+import type { BrainLogEntry } from "../../core/brain/log.ts";
+import {
+ queryByPreference,
+ queryByTopic,
+} from "../../core/brain/query.ts";
+import { info, ok } from "../output.ts";
+
+export function renderQueryPreferenceText(
+ out: ReturnType<typeof queryByPreference>,
+): void {
+ const p = out.preference;
+ ok(`id: ${p.id}`);
+ ok(`topic: ${p.topic}`);
+ if (p.scope) ok(`scope: ${p.scope}`);
+ ok(`status: ${"status" in p ? p.status : "(unknown)"}`);
+ ok(`principle: ${p.principle}`);
+ if (out.evidence.length === 0) {
+ ok("evidence: (none)");
+ return;
+ }
+ ok("evidence:");
+ for (const e of out.evidence) {
+ const artifact = e.body["artifact"] ?? "(unknown)";
+ const result = e.body["result"] ?? "(unknown)";
+ info(` - ${e.timestamp} ${result}: ${artifact}`);
+ }
+}
+
+export function renderQueryTopicText(
+ out: ReturnType<typeof queryByTopic>,
+ topic: string,
+): void {
+ ok(`topic: ${topic}`);
+ if (out.preference) {
+ ok(`preference: ${out.preference.id}`);
+ } else {
+ ok("preference: (none)");
+ }
+ ok(`signals: ${out.signals.length}`);
+ for (const s of out.signals) {
+ info(` - ${s.id} (${s.signal}, ${s.created_at})`);
+ }
+ ok(`log_events: ${out.all_log_events.length}`);
+}
+
+export function renderQueryLogText(entries: ReadonlyArray<BrainLogEntry>): void {
+ ok(`entries: ${entries.length}`);
+ for (const e of entries) {
+ info(` - ${e.timestamp} ${e.eventType}`);
+ }
+}
diff --git a/src/cli/brain/rollback-prompt.ts b/src/cli/brain/rollback-prompt.ts
new file mode 100644
index 00000000..251dad75
--- /dev/null
+++ b/src/cli/brain/rollback-prompt.ts
@@ -0,0 +1,70 @@
+/**
+ * Helpers used by the interactive `o2b brain rollback` flow:
+ *
+ * - {@link diffSummary} counts Markdown artifacts under
+ * `Brain/preferences/`, `Brain/retired/`, `Brain/inbox/` so the
+ * dispatcher can print a one-line "(X prefs, Y retired, Z signals)"
+ * summary before prompting.
+ * - {@link readSingleLine} reads one trimmed line from stdin without
+ * pulling in `readline`. Used for the y/N prompt when `--yes` is
+ * absent and stdin is a TTY.
+ *
+ * No I/O on Brain content β€” only `fs.statSync` and stdin reads.
+ */
+
+import { existsSync, readdirSync, statSync, type Dirent } from "node:fs";
+import { resolve } from "node:path";
+
+export interface DiffSummary {
+ readonly preferences: number;
+ readonly retired: number;
+ readonly signals: number;
+}
+
+export function diffSummary(vault: string): DiffSummary {
+ const root = resolve(vault, "Brain");
+ const safeCount = (p: string): number => {
+ if (!existsSync(p)) return 0;
+ try {
+ const st = statSync(p);
+ if (!st.isDirectory()) return 0;
+ } catch {
+ return 0;
+ }
+ try {
+ const entries: Dirent[] = readdirSync(p, { withFileTypes: true });
+ return entries.filter((e) => e.isFile() && e.name.endsWith(".md")).length;
+ } catch {
+ return 0;
+ }
+ };
+ return {
+ preferences: safeCount(resolve(root, "preferences")),
+ retired: safeCount(resolve(root, "retired")),
+ signals: safeCount(resolve(root, "inbox")),
+ };
+}
+
+export function readSingleLine(): Promise<string> {
+ return new Promise((res) => {
+ let buf = "";
+ const onData = (chunk: Buffer | string): void => {
+ buf += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ const nl = buf.indexOf("\n");
+ if (nl >= 0) {
+ process.stdin.removeListener("data", onData);
+ process.stdin.removeListener("end", onEnd);
+ process.stdin.pause();
+ res(buf.slice(0, nl).trim());
+ }
+ };
+ const onEnd = (): void => {
+ process.stdin.removeListener("data", onData);
+ process.stdin.removeListener("end", onEnd);
+ res(buf.trim());
+ };
+ process.stdin.resume();
+ process.stdin.on("data", onData);
+ process.stdin.on("end", onEnd);
+ });
+}
diff --git a/src/cli/brain/upgrade-render.ts b/src/cli/brain/upgrade-render.ts
new file mode 100644
index 00000000..602756e1
--- /dev/null
+++ b/src/cli/brain/upgrade-render.ts
@@ -0,0 +1,93 @@
+/**
+ * Renderers for `o2b brain upgrade` plan output (text + JSON).
+ *
+ * Pure projection of {@link UpgradePlan} into stdout β€” no I/O on the
+ * vault, no flag parsing. The verb handler (`./verbs/upgrade.ts`)
+ * calls these after `planUpgrade()` returns.
+ */
+
+import type { UpgradeFilePlan, UpgradePlan } from "../../core/brain/upgrade.ts";
+import { info, ok } from "../output.ts";
+
+export function renderUpgradePlanJson(plan: UpgradePlan): {
+ pending: number;
+ errors: number;
+ files: ReadonlyArray<{
+ path: string;
+ status: UpgradeFilePlan["status"];
+ before_size: number;
+ after_size: number;
+ error?: string;
+ }>;
+} {
+ return {
+ pending: plan.pending,
+ errors: plan.errors,
+ files: plan.files.map((f) => ({
+ path: f.path,
+ status: f.status,
+ before_size: f.before.length,
+ after_size: f.after.length,
+ ...(f.error ? { error: f.error } : {}),
+ })),
+ };
+}
+
+export function printUpgradePlanText(plan: UpgradePlan): void {
+ for (const f of plan.files) {
+ if (f.status === "noop") {
+ ok(` ${f.path}: up to date`);
+ continue;
+ }
+ if (f.status === "error") {
+ info(` ${f.path}: ERROR ${f.error}`);
+ continue;
+ }
+ info(` ${f.path}: update (${f.before.length} β†’ ${f.after.length} bytes)`);
+ info(renderUnifiedDiff(f.before, f.after, f.path));
+ }
+ if (plan.pending === 0 && plan.errors === 0) {
+ ok("upgrade: all managed files match the current release.");
+ } else if (plan.pending > 0) {
+ ok(
+ `upgrade: ${plan.pending} pending update(s); ` +
+ `re-run with --apply --yes when ready.`,
+ );
+ }
+}
+
+/**
+ * Minimal unified-diff renderer used by both `upgrade` (per-file diff)
+ * and `rollback --dry-run` (snapshot vs live). The implementation
+ * trims matching prefix / suffix and prints the changed window β€” it
+ * is not a drop-in replacement for GNU diff, but it is deterministic
+ * and dependency-free.
+ */
+export function renderUnifiedDiff(before: string, after: string, label: string): string {
+ if (before === after) return "";
+ const a = before.split("\n");
+ const b = after.split("\n");
+ const lines: string[] = [`--- ${label} (live)`, `+++ ${label} (release)`];
+ let head = 0;
+ while (head < a.length && head < b.length && a[head] === b[head]) head++;
+ let tailA = a.length;
+ let tailB = b.length;
+ while (
+ tailA > head &&
+ tailB > head &&
+ a[tailA - 1] === b[tailB - 1]
+ ) {
+ tailA--;
+ tailB--;
+ }
+ if (head > 0) {
+ lines.push(`@@ context: ${head} matching line(s) above @@`);
+ }
+ for (let i = head; i < tailA; i++) lines.push(`- ${a[i]}`);
+ for (let i = head; i < tailB; i++) lines.push(`+ ${b[i]}`);
+ if (tailA < a.length || tailB < b.length) {
+ const tailCount = Math.max(a.length - tailA, b.length - tailB);
+ lines.push(`@@ context: ${tailCount} matching line(s) below @@`);
+ }
+ return lines.join("\n");
+}
diff --git a/src/cli/brain/verbs/apply-evidence.ts b/src/cli/brain/verbs/apply-evidence.ts
new file mode 100644
index 00000000..8875deab
--- /dev/null
+++ b/src/cli/brain/verbs/apply-evidence.ts
@@ -0,0 +1,51 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { appendApplyEvidence, BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";
+import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainApplyEvidence(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ pref: { type: "string" },
+ artifact: { type: "string" },
+ result: { type: "string" },
+ agent: { type: "string" },
+ note: { type: "string" },
+ json: { type: "boolean" },
+ });
+ for (const field of ["pref", "artifact", "result"] as const) {
+ if (typeof flags[field] !== "string" || (flags[field] as string).trim() === "") {
+ return fail(`brain apply-evidence missing required flag: --${field}`);
+ }
+ }
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+
+ const resultStr = String(flags["result"]);
+ if (resultStr !== "applied" && resultStr !== "violated" && resultStr !== "outdated") {
+ return fail(`--result must be 'applied', 'violated', or 'outdated'; got ${resultStr}`);
+ }
+
+ try {
+ const out = appendApplyEvidence(vault, {
+ pref_id: String(flags["pref"]),
+ artifact: String(flags["artifact"]),
+ result: resultStr,
+ agent,
+ ...(flags["note"] ? { note: String(flags["note"]) } : {}),
+ });
+ if (flags["json"]) {
+ okJson({ logged_at: out.logged_at, log_path: out.log_path });
+ } else {
+ ok(`logged: ${out.log_path}`);
+ ok(`at: ${out.logged_at}`);
+ }
+ return 0;
+ } catch (exc) {
+ if (exc instanceof BrainPreferenceNotFoundError) {
+ process.stderr.write(`${exc.message}\n`);
+ return 2;
+ }
+ return fail(`apply-evidence failed: ${(exc as Error).message ?? exc}`);
+ }
+}
diff --git a/src/cli/brain/verbs/backlinks.ts b/src/cli/brain/verbs/backlinks.ts
new file mode 100644
index 00000000..895fa426
--- /dev/null
+++ b/src/cli/brain/verbs/backlinks.ts
@@ -0,0 +1,32 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { buildBacklinkIndex } from "../../../core/brain/backlinks.ts";
+import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";
+import { parse, fail, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainBacklinks(argv: string[]): Promise<number> {
+ const { positional, flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const id = positional[0];
+ if (!id) return fail("brain backlinks requires a target id (e.g. pref-foo, ret-bar, sig-...)");
+ const target = normaliseWikilinkTarget(id);
+ const index = buildBacklinkIndex(vault);
+ const refs = index.get(target) ?? [];
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ id: target, count: refs.length, refs }, null, 2) + "\n");
+ return 0;
+ }
+
+ process.stdout.write(`Backlinks to ${target}: ${refs.length}\n`);
+ if (refs.length === 0) return 0;
+ for (const r of refs) {
+ const ts = r.timestamp ? ` @ ${r.timestamp}` : "";
+ process.stdout.write(` ${r.source} (${r.sourceKind}, field: ${r.field})${ts}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/digest.ts b/src/cli/brain/verbs/digest.ts
new file mode 100644
index 00000000..aac36387
--- /dev/null
+++ b/src/cli/brain/verbs/digest.ts
@@ -0,0 +1,49 @@
+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 async function cmdBrainDigest(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ since: { type: "string" },
+ until: { type: "string" },
+ json: { type: "boolean" },
+ "silent-if-empty": { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let sinceDate: Date | undefined;
+ if (flags["since"]) {
+ const raw = String(flags["since"]);
+ if (!ISO_8601_RE.test(raw)) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ const d = new Date(raw);
+ if (!Number.isFinite(d.getTime())) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ sinceDate = d;
+ }
+ let untilDate: Date | undefined;
+ if (flags["until"]) {
+ const raw = String(flags["until"]);
+ if (!ISO_8601_RE.test(raw)) return fail(`--until must be a valid ISO-8601 timestamp; got ${raw}`);
+ const d = new Date(raw);
+ if (!Number.isFinite(d.getTime())) return fail(`--until must be a valid ISO-8601 timestamp; got ${raw}`);
+ untilDate = d;
+ }
+ const opts: RenderDigestOptions = {
+ ...(sinceDate ? { since: sinceDate } : {}),
+ ...(untilDate ? { until: untilDate } : {}),
+ format: flags["json"] ? "json" : "markdown",
+ };
+
+ let result;
+ try {
+ result = renderDigest(vault, opts);
+ } catch (exc) {
+ return fail(`digest failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (result.empty && flags["silent-if-empty"]) return 2;
+ process.stdout.write(result.content);
+ if (!result.content.endsWith("\n")) process.stdout.write("\n");
+ return 0;
+}
diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.ts
new file mode 100644
index 00000000..6b21de46
--- /dev/null
+++ b/src/cli/brain/verbs/doctor.ts
@@ -0,0 +1,29 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { runDoctor } from "../../../core/brain/doctor.ts";
+import { parse, fail, ok, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainDoctor(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ strict: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try { result = runDoctor(vault, { strict: Boolean(flags["strict"]) }); }
+ catch (exc) { return fail(`doctor failed: ${(exc as Error).message ?? exc}`); }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ warnings: result.warnings, errors: result.errors }, null, 2) + "\n");
+ } else {
+ for (const e of result.errors) process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);
+ for (const w of result.warnings) process.stdout.write(`[WARN] ${w.code}: ${w.message}${w.path ? ` (${w.path})` : ""}\n`);
+ if (result.errors.length === 0 && result.warnings.length === 0) ok("brain doctor: clean");
+ }
+
+ if (result.errors.length > 0) return 1;
+ if (result.warnings.length > 0 && flags["strict"]) return 2;
+ return 0;
+}
diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.ts
new file mode 100644
index 00000000..5dc54dda
--- /dev/null
+++ b/src/cli/brain/verbs/dream.ts
@@ -0,0 +1,68 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { dream } from "../../../core/brain/dream.ts";
+import { parse, fail, ok, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";
+
+export async function cmdBrainDream(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ now: { type: "string" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const agentFlag = flags["agent"];
+ let agent: string;
+ if (typeof agentFlag === "string") {
+ const trimmed = agentFlag.trim();
+ if (trimmed.length === 0) {
+ return fail("brain dream: --agent must be a non-empty string when provided");
+ }
+ agent = trimmed;
+ } else {
+ agent = resolveAgentName(config);
+ }
+
+ let now: Date | undefined;
+ const nowStr = flags["now"] as string | undefined;
+ if (nowStr) {
+ if (!ISO_8601_RE.test(nowStr)) {
+ return fail(`--now must be a valid ISO-8601 timestamp; got ${nowStr}`);
+ }
+ const parsed = new Date(nowStr);
+ if (!Number.isFinite(parsed.getTime())) {
+ return fail(`--now must be a valid ISO-8601 timestamp; got ${nowStr}`);
+ }
+ now = parsed;
+ }
+
+ let summary;
+ try {
+ summary = dream(vault, {
+ ...(now !== undefined ? { now } : {}),
+ dryRun: Boolean(flags["dry-run"]),
+ ...(agent ? { agentName: agent } : {}),
+ });
+ } catch (exc) {
+ return fail(`dream failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ for (const w of summary.warnings ?? []) {
+ process.stderr.write(`warning: ${w.code}: ${w.message}\n`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
+ return 0;
+ }
+ ok(`run_id: ${summary.run_id}`);
+ ok(`changed: ${summary.changed}`);
+ if (summary.new_unconfirmed.length > 0) ok(`new_unconfirmed: ${summary.new_unconfirmed.join(", ")}`);
+ if (summary.confirmed.length > 0) ok(`confirmed: ${summary.confirmed.join(", ")}`);
+ if (summary.retired.length > 0) ok(`retired: ${summary.retired.map((r) => `${r.id} (${r.reason})`).join(", ")}`);
+ if (summary.contradictions.length > 0) ok(`contradictions: ${summary.contradictions.join(", ")}`);
+ if (summary.moved_to_processed.length > 0) ok(`moved_to_processed: ${summary.moved_to_processed.length}`);
+ return 0;
+}
diff --git a/src/cli/brain/verbs/explorer.ts b/src/cli/brain/verbs/explorer.ts
new file mode 100644
index 00000000..9211a7f8
--- /dev/null
+++ b/src/cli/brain/verbs/explorer.ts
@@ -0,0 +1,49 @@
+import { existsSync } from "node:fs";
+import { defaultConfigPath } from "../../../core/config.ts";
+import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
+import { buildLiveServer, collectExplorerData, renderExportedHtml, type LiveServerHandle } from "../../../core/brain/explorer.ts";
+import { parse, fail, ok, info, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainExplorer(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ port: { type: "string" },
+ export: { type: "string" },
+ force: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const exportPath = flags["export"] as string | undefined;
+ const force = flags["force"] === true;
+
+ if (exportPath !== undefined) {
+ if (existsSync(exportPath) && !force) return fail(`${exportPath} exists; pass --force to overwrite`);
+ const graph = collectExplorerData(vault);
+ const html = renderExportedHtml(graph);
+ try { atomicWriteFileSync(exportPath, html); }
+ catch (err) { return fail(`failed to write ${exportPath}: ${(err as Error).message ?? err}`); }
+ ok(`exported ${graph.nodes.length} nodes to ${exportPath}`);
+ return 0;
+ }
+
+ const portRaw = (flags["port"] as string | undefined) ?? "7777";
+ const port = Number.parseInt(portRaw, 10);
+ if (!/^\d+$/.test(portRaw) || !Number.isFinite(port) || port < 1 || port > 65535) return fail(`invalid --port value: ${portRaw}`);
+
+ let server: LiveServerHandle;
+ try { server = buildLiveServer(vault, port); }
+ catch (err) {
+ const msg = (err as Error).message ?? String(err);
+ if (/EADDRINUSE|address already in use/i.test(msg)) return fail(`port ${port} already in use; try --port <other>`);
+ return fail(`failed to start explorer: ${msg}`);
+ }
+
+ ok(`Live explorer at ${server.url}`);
+ info("Press Ctrl+C to stop.");
+ await new Promise<void>((resolveStop) => {
+ const stop = (): void => { void server.close().then(() => resolveStop()); };
+ process.once("SIGINT", stop);
+ process.once("SIGTERM", stop);
+ });
+ return 0;
+}
diff --git a/src/cli/brain/verbs/export.ts b/src/cli/brain/verbs/export.ts
new file mode 100644
index 00000000..9b42c315
--- /dev/null
+++ b/src/cli/brain/verbs/export.ts
@@ -0,0 +1,34 @@
+import { existsSync } from "node:fs";
+import { defaultConfigPath } from "../../../core/config.ts";
+import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
+import { exportPreferencesJson, exportPreferencesLlmsTxt } from "../../../core/brain/export.ts";
+import { parse, fail, ok, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainExport(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ format: { type: "string" },
+ out: { type: "string" },
+ force: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const format = flags["format"] as string | undefined;
+ if (format !== "json" && format !== "llms-txt") {
+ process.stderr.write("error: --format is required and must be one of json|llms-txt\n");
+ return 2;
+ }
+
+ let body: string;
+ try {
+ body = format === "json" ? JSON.stringify(exportPreferencesJson(vault)) + "\n" : exportPreferencesLlmsTxt(vault);
+ } catch (exc) { return fail(`export failed: ${(exc as Error).message ?? exc}`); }
+
+ const outPath = flags["out"] as string | undefined;
+ if (outPath === undefined) { process.stdout.write(body); return 0; }
+ if (existsSync(outPath) && !flags["force"]) return fail(`${outPath} exists; pass --force to overwrite`);
+ try { atomicWriteFileSync(outPath, body); }
+ catch (exc) { return fail(`failed to write ${outPath}: ${(exc as Error).message ?? exc}`); }
+ ok(`wrote ${outPath}`);
+ return 0;
+}
diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.ts
new file mode 100644
index 00000000..63860859
--- /dev/null
+++ b/src/cli/brain/verbs/feedback.ts
@@ -0,0 +1,130 @@
+import { readFileSync } from "node:fs";
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { writeSignal } from "../../../core/brain/signal.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { writePreference } from "../../../core/brain/preference.ts";
+import { isoDate, isoSecond } from "../../../core/brain/time.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS, BRAIN_SIGNAL_SIGN } from "../../../core/brain/types.ts";
+import { renderPrefLink } from "../../../core/brain/wikilink.ts";
+import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainFeedback(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ topic: { type: "string" },
+ signal: { type: "string" },
+ principle: { type: "string" },
+ scope: { type: "string" },
+ source: { type: "string-array" },
+ agent: { type: "string" },
+ raw: { type: "string" },
+ "raw-file": { type: "string" },
+ "force-confirmed": { type: "boolean" },
+ date: { type: "string" },
+ slug: { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ for (const field of ["topic", "signal", "principle"] as const) {
+ if (typeof flags[field] !== "string" || (flags[field] as string).trim() === "") {
+ return fail(`brain feedback missing required flag: --${field}`);
+ }
+ }
+
+ const signalSign = String(flags["signal"]);
+ if (signalSign !== BRAIN_SIGNAL_SIGN.positive && signalSign !== BRAIN_SIGNAL_SIGN.negative) {
+ return fail(`--signal must be 'positive' or 'negative'; got ${JSON.stringify(signalSign)}`);
+ }
+
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+
+ let raw: string | undefined;
+ const rawFile = flags["raw-file"] as string | undefined;
+ if (rawFile) {
+ try {
+ raw = readFileSync(rawFile, "utf8");
+ } catch (exc) {
+ return fail(`cannot read --raw-file: ${(exc as Error).message ?? exc}`);
+ }
+ } else if (flags["raw"]) {
+ raw = String(flags["raw"]);
+ }
+
+ const now = new Date();
+ const date = (flags["date"] as string | undefined) ?? isoDate(now);
+ const slug = (flags["slug"] as string | undefined) ?? String(flags["topic"]);
+
+ let sigResult;
+ try {
+ sigResult = writeSignal(vault, {
+ topic: String(flags["topic"]),
+ signal: signalSign as "positive" | "negative",
+ agent,
+ principle: String(flags["principle"]),
+ created_at: now.toISOString(),
+ date,
+ slug,
+ ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
+ ...(flags["source"] ? { source: flags["source"] as string[] } : {}),
+ ...(raw !== undefined ? { raw } : {}),
+ });
+ } catch (exc) {
+ return fail(`failed to write signal: ${(exc as Error).message ?? exc}`);
+ }
+
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(now),
+ eventType: BRAIN_LOG_EVENT_KIND.feedback,
+ body: { signal: `[[${sigResult.id}]]`, topic: String(flags["topic"]), sign: signalSign, agent },
+ });
+ } catch (err) {
+ process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);
+ }
+
+ let prefResult: { path: string; id: string } | null = null;
+ if (flags["force-confirmed"]) {
+ try {
+ prefResult = writePreference(vault, {
+ slug,
+ topic: String(flags["topic"]),
+ principle: String(flags["principle"]),
+ created_at: now.toISOString(),
+ unconfirmed_until: now.toISOString(),
+ confirmed_at: now.toISOString(),
+ status: BRAIN_PREFERENCE_STATUS.confirmed,
+ evidenced_by: [`[[${sigResult.id}]]`],
+ ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),
+ }, { overwrite: false });
+ } catch (exc) {
+ return fail(`failed to force-confirm preference: ${(exc as Error).message ?? exc}`);
+ }
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date(now.getTime() + 1000)),
+ eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,
+ body: { preference: renderPrefLink({ id: prefResult.id, principle: String(flags["principle"]) }), agent },
+ });
+ } catch (err) {
+ process.stderr.write(`warning: append force-confirmed log failed: ${(err as Error).message}\n`);
+ }
+ }
+
+ if (flags["json"]) {
+ okJson({
+ signal_path: sigResult.path,
+ signal_id: sigResult.id,
+ ...(prefResult ? { preference_path: prefResult.path, preference_id: prefResult.id } : {}),
+ });
+ return 0;
+ }
+ ok(`signal: ${sigResult.path}`);
+ ok(`id: ${sigResult.id}`);
+ if (prefResult) {
+ ok(`preference: ${prefResult.path}`);
+ ok(`status: confirmed`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/import-claude-memory.ts b/src/cli/brain/verbs/import-claude-memory.ts
new file mode 100644
index 00000000..5c5b28b4
--- /dev/null
+++ b/src/cli/brain/verbs/import-claude-memory.ts
@@ -0,0 +1,68 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { importClaudeMemory, ConflictsError } from "../../../core/brain/import-claude-memory.ts";
+import { defaultMemoryDir } from "../../../core/brain/claude-memory-paths.ts";
+import { resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number> {
+ const config = defaultConfigPath();
+
+ let memory: string | null = null;
+ let mode: "dry-run" | "apply" = "dry-run";
+ let modeSet = false;
+ let allowArbitrary = false;
+ let yes = false;
+ let asJson = false;
+ let vaultFlag: string | undefined;
+
+ const consumeValue = (flag: string, next: string | undefined): string | null => {
+ if (next === undefined || next.startsWith("--")) {
+ process.stderr.write(`o2b brain import-claude-memory: ${flag} requires a value\n`);
+ return null;
+ }
+ return next;
+ };
+
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === "--vault") { const v = consumeValue("--vault", argv[++i]); if (v === null) return 2; vaultFlag = v; continue; }
+ if (a === "--memory") { const v = consumeValue("--memory", argv[++i]); if (v === null) return 2; memory = v; continue; }
+ if (a === "--dry-run") { if (modeSet && mode !== "dry-run") { process.stderr.write("o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n"); return 2; } mode = "dry-run"; modeSet = true; continue; }
+ if (a === "--apply") { if (modeSet && mode !== "apply") { process.stderr.write("o2b brain import-claude-memory: --apply and --dry-run are mutually exclusive\n"); return 2; } mode = "apply"; modeSet = true; continue; }
+ if (a === "--yes") { yes = true; continue; }
+ if (a === "--json") { asJson = true; continue; }
+ if (a === "--allow-arbitrary-memory-path") { allowArbitrary = true; continue; }
+ process.stderr.write(`o2b brain import-claude-memory: unknown flag ${a}\n`);
+ return 2;
+ }
+
+ if (mode === "apply" && !yes && !process.stdin.isTTY) {
+ process.stderr.write("o2b brain import-claude-memory: --apply requires --yes in non-interactive mode\n");
+ return 2;
+ }
+
+ const vault = resolveBrainVault(vaultFlag, config);
+ const memDir = memory ?? defaultMemoryDir(vault);
+
+ try {
+ const res = importClaudeMemory({ vault, memoryDir: memDir, mode, allowArbitraryMemoryPath: allowArbitrary });
+ if (asJson) { process.stdout.write(JSON.stringify(res, null, 2) + "\n"); return 0; }
+ if (mode === "dry-run") {
+ process.stdout.write(`plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`);
+ for (const p of res.plans) process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);
+ for (const s of res.skipped) process.stdout.write(` SKIP ${s.basename}: ${s.reason}\n`);
+ if (res.conflicts.length > 0) process.stdout.write(`conflicts: ${res.conflicts.length}\n`);
+ } else {
+ process.stdout.write(`applied: ${res.applied.length}; unchanged: ${res.skippedUnchanged.length}; skipped: ${res.skipped.length}\n`);
+ if (res.snapshotRunId) process.stdout.write(`snapshot: ${res.snapshotRunId}\n`);
+ }
+ return 0;
+ } catch (err) {
+ if (err instanceof ConflictsError) {
+ process.stderr.write("conflicts:\n");
+ for (const c of err.conflicts) process.stderr.write(` ${c.prefId} already exists in Brain but is not in Brain/.imports/claude-memory.json\n`);
+ return 2;
+ }
+ process.stderr.write(`o2b brain import-claude-memory: ${(err as Error).message}\n`);
+ return 1;
+ }
+}
diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.ts
new file mode 100644
index 00000000..3ba83986
--- /dev/null
+++ b/src/cli/brain/verbs/import-session.ts
@@ -0,0 +1,88 @@
+import { statSync } from "node:fs";
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { importSession, importSessionPath } from "../../../core/brain/sessions/import.ts";
+import { SessionImportError } from "../../../core/brain/sessions/types.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { parse, fail, ok, okJson, info, resolveBrainVault, ISO_8601_RE } from "../helpers.ts";
+
+export async function cmdBrainImportSession(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ format: { type: "string" },
+ since: { type: "string" },
+ "dry-run": { type: "boolean" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ if (positional.length < 1) return fail("brain import-session requires a <path> argument");
+ const sessionPath = positional[0]!;
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+
+ const formatRaw = flags["format"] as string | undefined;
+ let format: "claude" | "codex" | "hermes" | undefined;
+ if (formatRaw !== undefined && formatRaw !== "auto") {
+ if (formatRaw !== "claude" && formatRaw !== "codex" && formatRaw !== "hermes") return fail(`--format must be one of auto|claude|codex|hermes; got ${formatRaw}`);
+ format = formatRaw;
+ }
+
+ let since: Date | undefined;
+ if (flags["since"]) {
+ const raw = String(flags["since"]);
+ if (!ISO_8601_RE.test(raw)) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ const d = new Date(raw);
+ if (!Number.isFinite(d.getTime())) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ since = d;
+ }
+
+ let stat;
+ try { stat = statSync(sessionPath); }
+ catch (err) { return fail(`cannot stat ${sessionPath}: ${(err as Error).message ?? err}`); }
+
+ try {
+ const result = stat.isDirectory()
+ ? await importSessionPath(vault, sessionPath, { agent, ...(format ? { format } : {}), ...(since ? { since } : {}), dryRun: Boolean(flags["dry-run"]) })
+ : { files: [await importSession(vault, sessionPath, { agent, ...(format ? { format } : {}), ...(since ? { since } : {}), dryRun: Boolean(flags["dry-run"]) })], warnings: [] };
+
+ if (!flags["dry-run"]) {
+ for (const f of result.files) {
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date()), eventType: BRAIN_LOG_EVENT_KIND.importSession,
+ body: { agent, file: `[[${f.file}]]`, format: f.format, turns_scanned: String(f.turns_scanned), signals_created: String(f.signals_created), signals_deduped: String(f.signals_deduped), tool_replays: String(f.tool_replays), malformed: String(f.malformed) },
+ });
+ } catch (err) { process.stderr.write(`warning: append import-session log failed: ${(err as Error).message}\n`); }
+ }
+ }
+
+ if (flags["json"]) {
+ okJson({
+ files: result.files.map((f) => ({ file: f.file, format: f.format, turns_scanned: f.turns_scanned, signals_created: f.signals_created, signals_deduped: f.signals_deduped, tool_replays: f.tool_replays, malformed: f.malformed, errors: f.errors })),
+ warnings: result.warnings,
+ });
+ } else {
+ for (const f of result.files) {
+ ok(`file: ${f.file}`);
+ ok(` format: ${f.format}`);
+ ok(` turns_scanned: ${f.turns_scanned}`);
+ ok(` signals_created: ${f.signals_created}`);
+ ok(` signals_deduped: ${f.signals_deduped}`);
+ ok(` tool_replays: ${f.tool_replays}`);
+ if (f.malformed > 0) ok(` malformed: ${f.malformed}`);
+ for (const e of f.errors) info(` error: ${e.path}: ${e.message}`);
+ }
+ for (const w of result.warnings) info(` warning: ${w.path}: ${w.message}`);
+ }
+ return 0;
+ } catch (exc) {
+ if (exc instanceof SessionImportError) {
+ process.stderr.write(`error: ${exc.message}\n`);
+ if (exc.code === "DETECT_FAIL" || exc.code === "UNKNOWN_FORMAT") return 2;
+ return 1;
+ }
+ return fail(`import-session failed: ${(exc as Error).message ?? exc}`);
+ }
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
new file mode 100644
index 00000000..e199ff97
--- /dev/null
+++ b/src/cli/brain/verbs/index.ts
@@ -0,0 +1,22 @@
+export { cmdBrainInit } from "./init.ts";
+export { cmdBrainFeedback } from "./feedback.ts";
+export { cmdBrainDream } from "./dream.ts";
+export { cmdBrainApplyEvidence } from "./apply-evidence.ts";
+export { cmdBrainDigest } from "./digest.ts";
+export { cmdBrainQuery } from "./query.ts";
+export { cmdBrainReject } from "./reject.ts";
+export { cmdBrainPin, cmdBrainUnpin } from "./pin.ts";
+export { cmdBrainSetPrimary } from "./set-primary.ts";
+export { cmdBrainProtect, cmdBrainUnprotect } from "./protect.ts";
+export { cmdBrainRollback } from "./rollback.ts";
+export { cmdBrainDoctor } from "./doctor.ts";
+export { cmdBrainBacklinks } from "./backlinks.ts";
+export { cmdBrainMerge } from "./merge.ts";
+export { cmdBrainExplorer } from "./explorer.ts";
+export { cmdBrainExport } from "./export.ts";
+export { cmdBrainUpgrade } from "./upgrade.ts";
+export { cmdBrainSnapshotDiff, handleBrainSnapshotSubcommand } from "./snapshot.ts";
+export { cmdBrainMigrateFrontmatter } from "./migrate-frontmatter.ts";
+export { cmdBrainScanInline } from "./scan-inline.ts";
+export { cmdBrainImportSession } from "./import-session.ts";
+export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";
diff --git a/src/cli/brain/verbs/init.ts b/src/cli/brain/verbs/init.ts
new file mode 100644
index 00000000..d8e3cf51
--- /dev/null
+++ b/src/cli/brain/verbs/init.ts
@@ -0,0 +1,59 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { bootstrapBrain } from "../../../core/brain/init.ts";
+import { parse, fail, ok, info, okJson, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainInit(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ config: { type: "string" },
+ force: { type: "boolean" },
+ "primary-agent": { type: "string" },
+ starter: { type: "boolean" },
+ "starter-path": { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const primaryAgentFlag = flags["primary-agent"];
+ let primaryAgent: string | undefined;
+ if (typeof primaryAgentFlag === "string") {
+ const trimmed = primaryAgentFlag.trim();
+ if (trimmed.length === 0) {
+ return fail("brain init: --primary-agent must be a non-empty string when provided");
+ }
+ primaryAgent = trimmed;
+ }
+
+ const starterPathFlag = flags["starter-path"];
+ let starterPath: string | undefined;
+ if (typeof starterPathFlag === "string") {
+ starterPath = starterPathFlag.trim();
+ if (starterPath.length === 0) {
+ return fail("brain init: --starter-path must be a non-empty path when provided");
+ }
+ }
+
+ let result;
+ try {
+ result = bootstrapBrain(vault, {
+ force: Boolean(flags["force"]),
+ configPath: config,
+ starter: Boolean(flags["starter"]),
+ ...(primaryAgent !== undefined ? { primaryAgent } : {}),
+ ...(starterPath !== undefined ? { starterPath } : {}),
+ });
+ } catch (exc) {
+ return fail(`failed to initialize Brain: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ okJson({ vault, created: result.created, overwritten: result.overwritten, skipped: result.skipped });
+ return 0;
+ }
+ ok(`brain initialized: ${vault}`);
+ for (const p of result.created) info(` created: ${p}`);
+ for (const p of result.overwritten) info(` overwritten: ${p}`);
+ for (const p of result.skipped) info(` exists: ${p}`);
+ return 0;
+}
diff --git a/src/cli/brain/verbs/merge.ts b/src/cli/brain/verbs/merge.ts
new file mode 100644
index 00000000..1957f974
--- /dev/null
+++ b/src/cli/brain/verbs/merge.ts
@@ -0,0 +1,65 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { mergePreferences, BrainMergeError } from "../../../core/brain/merge.ts";
+import { parse, fail, ok, okJson, resolveBrainVault, readSingleLine } from "../helpers.ts";
+
+export async function cmdBrainMerge(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ force: { type: "boolean" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ if (positional.length !== 2) return fail("brain merge requires exactly two positional ids: <keep-pref-id> <drop-pref-id>");
+ const [keepId, dropId] = positional as [string, string];
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const dryRun = flags["dry-run"] === true;
+ const force = flags["force"] === true;
+ const wantJson = flags["json"] === true;
+
+ let plan;
+ try {
+ plan = mergePreferences(vault, keepId, dropId, { now: new Date(), agentName: agent, dryRun: true });
+ } catch (exc) {
+ if (exc instanceof BrainMergeError) return fail(`brain merge: ${exc.message}`);
+ return fail(`brain merge: failed to plan merge: ${(exc as Error).message ?? exc}`);
+ }
+
+ const planLines = [
+ `merge plan:`,
+ ` keep: ${plan.keep_id}`,
+ ` drop: ${plan.drop_id} β†’ ${plan.retired_path}`,
+ ` topic: ${plan.topic}${plan.scope ? `, scope: ${plan.scope}` : ""}`,
+ ` evidenced_by union: ${plan.merged_evidenced_by.length}`,
+ ` applied_sum: ${plan.applied_sum}`,
+ ` violated_sum: ${plan.violated_sum}`,
+ ` last_evidence_at: ${plan.last_evidence_at ?? "β€”"}`,
+ ];
+
+ if (dryRun) {
+ if (wantJson) { okJson({ dry_run: true, plan }); }
+ else { for (const line of planLines) ok(line); ok("dry-run; no changes written"); }
+ return 0;
+ }
+
+ if (!force) {
+ if (wantJson) return fail("brain merge: --json without --force is not supported (interactive prompt cannot render)");
+ if (!process.stdin.isTTY) return fail("brain merge: --force required when stdin is not a TTY (cannot prompt for confirmation)");
+ for (const line of planLines) process.stderr.write(line + "\n");
+ process.stderr.write("Proceed? [y/N] ");
+ const ans = (await readSingleLine()).toLowerCase();
+ if (ans !== "y" && ans !== "yes") { ok("merge cancelled"); return 0; }
+ }
+
+ try { mergePreferences(vault, keepId, dropId, { now: new Date(), agentName: agent }); }
+ catch (exc) {
+ if (exc instanceof BrainMergeError) return fail(`brain merge: ${exc.message}`);
+ return fail(`brain merge: failed to commit merge: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (wantJson) { okJson({ merged: true, plan }); }
+ else { ok(`merged: ${plan.drop_id} β†’ ${plan.keep_id} (retired as merged-into)`); }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/migrate-frontmatter.ts b/src/cli/brain/verbs/migrate-frontmatter.ts
new file mode 100644
index 00000000..d7dc3e8e
--- /dev/null
+++ b/src/cli/brain/verbs/migrate-frontmatter.ts
@@ -0,0 +1,91 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { planMigration, applyMigration, MigrationError } from "../../../core/brain/migrate-frontmatter.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainMigrateFrontmatter(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = resolveAgentName(config);
+
+ if (flags["dry-run"] && flags["apply"]) return fail("brain migrate-frontmatter: --dry-run and --apply are mutually exclusive");
+ const apply = Boolean(flags["apply"]);
+
+ if (apply && !flags["yes"] && (flags["json"] || !process.stdin.isTTY)) {
+ return fail("brain migrate-frontmatter --apply requires --yes in non-interactive mode (--json or non-TTY stdin)");
+ }
+
+ if (!apply) {
+ let plan;
+ try { plan = planMigration(vault); }
+ catch (exc) { return fail(`migrate-frontmatter plan failed: ${(exc as Error).message ?? exc}`); }
+ if (flags["json"]) {
+ okJson({
+ files_scanned: plan.files_scanned,
+ files_to_migrate: plan.files_to_migrate.length,
+ files_already_new: plan.files_already_new.length,
+ collisions: plan.collisions.length,
+ collision_files: plan.collisions.map((c) => ({ path: c.path, field: c.field })),
+ });
+ return 0;
+ }
+ ok(`files_scanned: ${plan.files_scanned}`);
+ ok(`files_to_migrate: ${plan.files_to_migrate.length}`);
+ ok(`files_already_new: ${plan.files_already_new.length}`);
+ ok(`collisions: ${plan.collisions.length}`);
+ if (plan.collisions.length > 0) {
+ info("Collisions (both legacy and '_'-prefixed shape present):");
+ for (const c of plan.collisions) info(` - ${c.path} (field: ${c.field})`);
+ }
+ if (plan.files_to_migrate.length === 0) ok("nothing to migrate; re-run with --apply --yes when there is.");
+ else ok("re-run with --apply --yes to rewrite these files.");
+ return 0;
+ }
+
+ let result;
+ try { result = await applyMigration(vault, { snapshot: true, now: new Date() }); }
+ catch (exc) {
+ if (exc instanceof MigrationError) { process.stderr.write(`error: ${exc.message}\n`); return 1; }
+ return fail(`migrate-frontmatter failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date()),
+ eventType: BRAIN_LOG_EVENT_KIND.migrateFrontmatter,
+ body: {
+ run_id: result.run_id, agent,
+ snapshot: result.snapshot_path ?? "(none)",
+ files_scanned: String(result.plan.files_scanned),
+ files_migrated: String(result.files_migrated.length),
+ files_already_new: String(result.plan.files_already_new.length),
+ collisions: String(result.plan.collisions.length),
+ },
+ });
+ } catch (err) { process.stderr.write(`warning: append migrate-frontmatter log failed: ${(err as Error).message}\n`); }
+
+ if (flags["json"]) {
+ okJson({
+ run_id: result.run_id, snapshot_path: result.snapshot_path,
+ files_scanned: result.plan.files_scanned,
+ files_migrated: result.files_migrated.length,
+ files_already_new: result.plan.files_already_new.length,
+ collisions: result.plan.collisions.length,
+ });
+ return 0;
+ }
+ ok(`run_id: ${result.run_id}`);
+ ok(`snapshot: ${result.snapshot_path ?? "(none)"}`);
+ ok(`files_migrated: ${result.files_migrated.length}`);
+ ok(`files_already_new: ${result.plan.files_already_new.length}`);
+ return 0;
+}
diff --git a/src/cli/brain/verbs/pin.ts b/src/cli/brain/verbs/pin.ts
new file mode 100644
index 00000000..101f265b
--- /dev/null
+++ b/src/cli/brain/verbs/pin.ts
@@ -0,0 +1,35 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { setPinned } from "../../../core/brain/pin.ts";
+import { BrainPreferenceNotFoundError } from "../../../core/brain/apply-evidence.ts";
+import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+
+async function pinOrUnpin(argv: string[], value: boolean): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ id: { type: "string" },
+ json: { type: "boolean" },
+ });
+ if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
+ return fail(`brain ${value ? "pin" : "unpin"} missing required flag: --id`);
+ }
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = resolveAgentName(config);
+
+ try {
+ const out = setPinned(vault, String(flags["id"]), value, { agent });
+ const slug = String(flags["id"]).trim().replace(/^pref-/, "");
+ const label = value ? "pinned" : "unpinned";
+ const idemLabel = value ? "already pinned" : "already unpinned";
+ if (flags["json"]) { okJson({ id: `pref-${slug}`, changed: out.changed, pinned: value }); }
+ else if (out.changed) { ok(`${label}: pref-${slug}`); }
+ else { ok(`${idemLabel}: pref-${slug}`); }
+ return 0;
+ } catch (exc) {
+ if (exc instanceof BrainPreferenceNotFoundError) { process.stderr.write(`${exc.message}\n`); return 2; }
+ return fail(`${value ? "pin" : "unpin"} failed: ${(exc as Error).message ?? exc}`);
+ }
+}
+
+export async function cmdBrainPin(argv: string[]): Promise<number> { return pinOrUnpin(argv, true); }
+export async function cmdBrainUnpin(argv: string[]): Promise<number> { return pinOrUnpin(argv, false); }
diff --git a/src/cli/brain/verbs/protect.ts b/src/cli/brain/verbs/protect.ts
new file mode 100644
index 00000000..f59bd71d
--- /dev/null
+++ b/src/cli/brain/verbs/protect.ts
@@ -0,0 +1,60 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { applyProtect, BrainProtectError, isProtectTarget, printSnippet, PROTECT_TARGETS, unprotect } from "../../../core/brain/protect.ts";
+import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainProtect(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ target: { type: "string", required: true },
+ vault: { type: "string" },
+ apply: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
+ if (!isProtectTarget(rawTarget)) {
+ return fail(`brain protect --target='${flags["target"]}' is unknown; supported targets: ${PROTECT_TARGETS.join(", ")}`);
+ }
+ const target = rawTarget;
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+
+ try {
+ if (flags["apply"]) {
+ const result = applyProtect({ target, vault });
+ if (flags["json"]) { okJson({ target: result.target, destination: result.destination, changed: result.changed, backup: result.backupPath || null }); return 0; }
+ const head = result.changed ? `brain protect: applied to ${result.destination}` : `brain protect: no changes (${result.destination} already current)`;
+ ok(head);
+ if (result.backupPath) ok(` backup: ${result.backupPath}`);
+ return 0;
+ }
+ const snippet = printSnippet({ target, vault });
+ if (flags["json"]) { okJson({ target: snippet.target, destination: snippet.destination, body: snippet.body }); return 0; }
+ info(`# o2b brain protect --target ${target}`);
+ info(`# destination: ${snippet.destination}`);
+ info(`# preview only; re-run with --apply to write the file`);
+ process.stdout.write(snippet.body);
+ return 0;
+ } catch (exc) {
+ if (exc instanceof BrainProtectError) return fail(`brain protect failed: ${exc.message}`);
+ throw exc;
+ }
+}
+
+export async function cmdBrainUnprotect(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ target: { type: "string", required: true },
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const rawTarget = typeof flags["target"] === "string" ? flags["target"] : undefined;
+ if (!isProtectTarget(rawTarget)) {
+ return fail(`brain unprotect --target='${flags["target"]}' is unknown; supported targets: ${PROTECT_TARGETS.join(", ")}`);
+ }
+ const target = rawTarget;
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, defaultConfigPath());
+
+ try { unprotect({ target, vault }); }
+ catch (exc) { if (exc instanceof BrainProtectError) return fail(`brain unprotect failed: ${exc.message}`); throw exc; }
+
+ if (flags["json"]) { okJson({ target, vault }); }
+ else { ok(`brain unprotect: removed OSB-managed rules for target=${target}`); }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/query.ts b/src/cli/brain/verbs/query.ts
new file mode 100644
index 00000000..27326486
--- /dev/null
+++ b/src/cli/brain/verbs/query.ts
@@ -0,0 +1,50 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { queryByLogSince, queryByPreference, queryByTopic, BrainNotFoundError } from "../../../core/brain/query.ts";
+import { parse, fail, resolveBrainVault, ISO_8601_RE, renderQueryPreferenceText, renderQueryTopicText, renderQueryLogText } from "../helpers.ts";
+
+export async function cmdBrainQuery(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ preference: { type: "string" },
+ topic: { type: "string" },
+ since: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const modes = ["preference", "topic", "since"].filter(
+ (k) => typeof flags[k] === "string" && (flags[k] as string).trim() !== "",
+ );
+ if (modes.length === 0) return fail("brain query requires exactly one of --preference, --topic, --since");
+ if (modes.length > 1) return fail(`brain query: pick only one of --preference / --topic / --since (got ${modes.join(", ")})`);
+
+ try {
+ if (flags["preference"]) {
+ const out = queryByPreference(vault, String(flags["preference"]));
+ if (flags["json"]) { process.stdout.write(JSON.stringify(out, null, 2) + "\n"); }
+ else { renderQueryPreferenceText(out); }
+ return 0;
+ }
+ if (flags["topic"]) {
+ const out = queryByTopic(vault, String(flags["topic"]));
+ if (flags["json"]) { process.stdout.write(JSON.stringify(out, null, 2) + "\n"); }
+ else { renderQueryTopicText(out, String(flags["topic"])); }
+ return 0;
+ }
+ if (flags["since"]) {
+ const raw = String(flags["since"]);
+ if (!ISO_8601_RE.test(raw)) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ const d = new Date(raw);
+ if (!Number.isFinite(d.getTime())) return fail(`--since must be a valid ISO-8601 timestamp; got ${raw}`);
+ const entries = queryByLogSince(vault, d);
+ if (flags["json"]) { process.stdout.write(JSON.stringify(entries, null, 2) + "\n"); }
+ else { renderQueryLogText(entries); }
+ return 0;
+ }
+ } catch (exc) {
+ if (exc instanceof BrainNotFoundError) { process.stderr.write(`${exc.message}\n`); return 2; }
+ return fail(`query failed: ${(exc as Error).message ?? exc}`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/reject.ts b/src/cli/brain/verbs/reject.ts
new file mode 100644
index 00000000..d742f7c7
--- /dev/null
+++ b/src/cli/brain/verbs/reject.ts
@@ -0,0 +1,71 @@
+import { existsSync } from "node:fs";
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { moveToRetired, parsePreference } from "../../../core/brain/preference.ts";
+import { preferencePath } from "../../../core/brain/paths.ts";
+import { isoDate, isoSecond } from "../../../core/brain/time.ts";
+import { renderPrefLink } from "../../../core/brain/wikilink.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainReject(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ id: { type: "string" },
+ reason: { type: "string" },
+ yes: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ if (typeof flags["id"] !== "string" || (flags["id"] as string).trim() === "") {
+ return fail("brain reject missing required flag: --id");
+ }
+ if (typeof flags["reason"] !== "string" || (flags["reason"] as string).trim() === "") {
+ return fail("brain reject missing required flag: --reason (free-form text; persisted on the retired file)");
+ }
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = resolveAgentName(config);
+
+ const rawId = String(flags["id"]).trim();
+ const slug = rawId.startsWith("pref-") ? rawId.slice("pref-".length) : rawId;
+ const path = preferencePath(vault, slug);
+ if (!existsSync(path)) {
+ process.stderr.write(`preference not found: pref-${slug}; expected ${path}\n`);
+ return 2;
+ }
+ let pref;
+ try { pref = parsePreference(path); }
+ catch (exc) { return fail(`failed to parse preference: ${(exc as Error).message ?? exc}`); }
+
+ if (pref.pinned && !flags["yes"]) {
+ process.stderr.write(`warning: preference '${pref.id}' is pinned; pass --yes to override\n`);
+ return 1;
+ }
+
+ const now = new Date();
+ const todayDate = isoDate(now);
+ const retiredBy = `[[Brain/log/${todayDate}]]`;
+ const reasonText = String(flags["reason"]).trim();
+
+ try {
+ moveToRetired(vault, path, "user-rejected", { now, retired_by: retiredBy, user_rejected_reason: reasonText });
+ } catch (exc) {
+ return fail(`failed to retire preference: ${(exc as Error).message ?? exc}`);
+ }
+
+ try {
+ const body: Record<string, string> = {
+ preference: renderPrefLink({ id: `ret-${slug}`, principle: pref.principle }),
+ agent,
+ };
+ if (flags["reason"]) body["reason"] = String(flags["reason"]);
+ if (pref.pinned) body["was_pinned"] = "true";
+ appendLogEvent(vault, { timestamp: isoSecond(now), eventType: BRAIN_LOG_EVENT_KIND.reject, body });
+ } catch (err) {
+ process.stderr.write(`warning: append reject log failed: ${(err as Error).message}\n`);
+ }
+
+ if (flags["json"]) { okJson({ id: `ret-${slug}`, reason: "user-rejected" }); }
+ else { ok(`retired: ret-${slug} (user-rejected)`); }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/rollback.ts b/src/cli/brain/verbs/rollback.ts
new file mode 100644
index 00000000..4c668381
--- /dev/null
+++ b/src/cli/brain/verbs/rollback.ts
@@ -0,0 +1,98 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { listSnapshots, extractSnapshotToTemp, restoreSnapshot, type ExtractSnapshotResult } from "../../../core/brain/snapshot.ts";
+import { buildManifest, diffManifests, manifestDiffHasDrift, readManifestSidecar, renderManifestDriftJson, renderManifestDriftMarkdown } from "../../../core/brain/manifest.ts";
+import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";
+import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";
+import { brainDirs } from "../../../core/brain/paths.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { parse, fail, ok, okJson, resolveBrainVault, diffSummary, readSingleLine } from "../helpers.ts";
+
+export async function cmdBrainRollback(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ list: { type: "boolean" },
+ yes: { type: "boolean" },
+ "dry-run": { type: "boolean" },
+ "force-rollback": { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const forceRollback = Boolean(flags["force-rollback"]);
+
+ if (flags["list"]) {
+ const snaps = listSnapshots(vault);
+ if (flags["json"]) { process.stdout.write(JSON.stringify(snaps, null, 2) + "\n"); return 0; }
+ if (snaps.length === 0) { ok("no snapshots available"); return 0; }
+ ok("run_id\tcreated_at\tsize_bytes");
+ for (const s of snaps) ok(`${s.run_id}\t${s.created_at}\t${s.size_bytes}`);
+ return 0;
+ }
+
+ if (positional.length < 1) return fail("brain rollback requires a <run_id> argument (or --list to enumerate snapshots)");
+ const runId = positional[0]!;
+
+ const allSnaps = listSnapshots(vault);
+ if (!allSnaps.some((s) => s.run_id === runId)) {
+ process.stderr.write(`snapshot not found: ${runId}; run \`o2b brain rollback --list\` to enumerate.\n`);
+ return 2;
+ }
+
+ const driftDiff = flags["dry-run"] ? null : (() => {
+ const stored = readManifestSidecar(vault, runId);
+ if (stored === null) {
+ process.stderr.write(`warning: no manifest sidecar for snapshot '${runId}'; drift detection skipped (snapshot predates v0.10.6).\n`);
+ return null;
+ }
+ const live = buildManifest(brainDirs(vault).brain);
+ return diffManifests(stored, live);
+ })();
+ const drift = driftDiff !== null && manifestDiffHasDrift(driftDiff);
+ if (drift && !forceRollback) {
+ if (flags["json"]) { process.stdout.write(JSON.stringify(renderManifestDriftJson(driftDiff!, runId), null, 2) + "\n"); return 2; }
+ process.stderr.write(renderManifestDriftMarkdown(driftDiff!, runId) + "\n");
+ return 2;
+ }
+
+ if (flags["dry-run"]) {
+ if (flags["yes"]) return fail("rollback: --dry-run and --yes are mutually exclusive");
+ let ext: ExtractSnapshotResult;
+ try { ext = extractSnapshotToTemp(vault, runId); }
+ catch (exc) { return fail(`rollback dry-run failed: ${(exc as Error).message ?? exc}`); }
+ try {
+ const liveBrain = brainDirs(vault).brain;
+ const diff = diffBrainTrees(liveBrain, ext.brainRoot);
+ const out = flags["json"] ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n" : renderDiffMarkdown(diff, { aLabel: "live", bLabel: runId });
+ process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
+ return 0;
+ } finally { ext.cleanup(); }
+ }
+
+ if (!flags["yes"]) {
+ if (flags["json"] || !process.stdin.isTTY) return fail("rollback requires --yes in non-interactive mode (--json or non-TTY stdin)");
+ const summary = diffSummary(vault);
+ process.stderr.write(
+ `About to restore snapshot '${runId}' over Brain/.\n` +
+ `Current state: ${summary.preferences} preferences, ${summary.retired} retired, ${summary.signals} signals.\n` +
+ `This will OVERWRITE the live Brain/ tree (.snapshots/ is preserved).\nProceed? [y/N] `,
+ );
+ const ans = await readSingleLine();
+ if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") { ok("rollback cancelled"); return 0; }
+ }
+
+ let result;
+ try { result = restoreSnapshot(vault, runId); }
+ catch (exc) { return fail(`rollback failed: ${(exc as Error).message ?? exc}`); }
+
+ try {
+ const body: Record<string, string> = { run_id: runId, restored_files: String(result.restored_files) };
+ if (drift && forceRollback) body["drift_overridden"] = "true";
+ appendLogEvent(vault, { timestamp: isoSecond(new Date()), eventType: BRAIN_LOG_EVENT_KIND.rollback, body });
+ } catch (err) { process.stderr.write(`warning: append rollback log failed: ${(err as Error).message}\n`); }
+
+ if (flags["json"]) { okJson({ run_id: runId, restored_files: result.restored_files }); }
+ else { ok(`restored: ${runId} (${result.restored_files} files)`); }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/scan-inline.ts b/src/cli/brain/verbs/scan-inline.ts
new file mode 100644
index 00000000..a4d83216
--- /dev/null
+++ b/src/cli/brain/verbs/scan-inline.ts
@@ -0,0 +1,56 @@
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { scanInline } from "../../../core/brain/inline-scan.ts";
+import { appendLogEvent } from "../../../core/brain/log.ts";
+import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";
+import { isoSecond } from "../../../core/brain/time.ts";
+import { parse, fail, ok, okJson, info, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainScanInline(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ strict: { type: "boolean" },
+ path: { type: "string-array" },
+ exclude: { type: "string-array" },
+ agent: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+ const agent = (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+
+ let result;
+ try {
+ result = await scanInline(vault, {
+ agent, dryRun: Boolean(flags["dry-run"]),
+ paths: (flags["path"] as string[] | undefined) ?? [],
+ exclude: (flags["exclude"] as string[] | undefined) ?? [],
+ });
+ } catch (exc) { return fail(`scan-inline failed: ${(exc as Error).message ?? exc}`); }
+
+ if (!flags["dry-run"]) {
+ try {
+ appendLogEvent(vault, {
+ timestamp: isoSecond(new Date()), eventType: BRAIN_LOG_EVENT_KIND.scanInline,
+ body: { agent, scanned: String(result.scanned), found: String(result.found), created: String(result.created), deduped: String(result.deduped), malformed: String(result.malformed), errors: String(result.errors.length) },
+ });
+ } catch (err) { process.stderr.write(`warning: append scan-inline log failed: ${(err as Error).message}\n`); }
+ }
+
+ if (flags["json"]) {
+ okJson({
+ scanned: result.scanned, found: result.found, created: result.created, deduped: result.deduped, malformed: result.malformed,
+ errors: result.errors.map((e) => ({ path: e.path, message: e.message })),
+ files_with_markers: result.filesWithMarkers.map((f) => ({ path: f.path, markers: f.markers })),
+ });
+ } else {
+ ok(`scanned: ${result.scanned}`);
+ ok(`found: ${result.found}`);
+ ok(`created: ${result.created}`);
+ ok(`deduped: ${result.deduped}`);
+ if (result.malformed > 0) ok(`malformed: ${result.malformed}`);
+ for (const e of result.errors) info(` error: ${e.path}: ${e.message}`);
+ }
+ if (flags["strict"] && result.malformed > 0) return 2;
+ return 0;
+}
diff --git a/src/cli/brain/verbs/set-primary.ts b/src/cli/brain/verbs/set-primary.ts
new file mode 100644
index 00000000..779e1406
--- /dev/null
+++ b/src/cli/brain/verbs/set-primary.ts
@@ -0,0 +1,36 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { setPrimaryAgent } from "../../../core/brain/set-primary.ts";
+import { parse, fail, ok, okJson, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainSetPrimary(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ clear: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ let name: string | null;
+ if (flags["clear"]) {
+ if (positional.length > 0) return fail("brain set-primary --clear takes no positional argument");
+ name = null;
+ } else {
+ if (positional.length < 1) return fail("brain set-primary requires <name> or --clear; see `o2b brain help set-primary`");
+ if (positional.length > 1) return fail("brain set-primary accepts a single <name> argument");
+ const supplied = positional[0]!.trim();
+ if (supplied.length === 0) return fail("brain set-primary <name> must be non-empty");
+ name = supplied;
+ }
+
+ let result;
+ try { result = setPrimaryAgent(vault, name); }
+ catch (exc) { return fail(`set-primary failed: ${(exc as Error).message ?? exc}`); }
+
+ if (flags["json"]) { okJson({ previous: result.previous, next: result.next, changed: result.changed }); return 0; }
+
+ const fmt = (v: string | null): string => v ?? "null";
+ if (!result.changed) { ok(`primary_agent already set to ${fmt(result.next)}`); }
+ else { ok(`primary_agent: ${fmt(result.previous)} β†’ ${fmt(result.next)}`); }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/snapshot.ts b/src/cli/brain/verbs/snapshot.ts
new file mode 100644
index 00000000..55c88e8c
--- /dev/null
+++ b/src/cli/brain/verbs/snapshot.ts
@@ -0,0 +1,65 @@
+import { listSnapshots, extractSnapshotToTemp, type ExtractSnapshotResult } from "../../../core/brain/snapshot.ts";
+import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";
+import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";
+import { brainDirs } from "../../../core/brain/paths.ts";
+import { defaultConfigPath } from "../../../core/config.ts";
+import { parse, fail, resolveBrainVault } from "../helpers.ts";
+
+export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ if (positional.length < 1 || positional.length > 2) {
+ return fail("brain snapshot diff requires <run_id_a> [<run_id_b>] (with one arg, the live tree is compared as B)");
+ }
+ const [a, b] = positional;
+ const snaps = listSnapshots(vault);
+ if (!snaps.some((s) => s.run_id === a)) {
+ process.stderr.write(`snapshot not found: ${a}; run \`o2b brain rollback --list\` to enumerate.\n`);
+ return 2;
+ }
+ if (b !== undefined && !snaps.some((s) => s.run_id === b)) {
+ process.stderr.write(`snapshot not found: ${b}; run \`o2b brain rollback --list\` to enumerate.\n`);
+ return 2;
+ }
+
+ let extA: ExtractSnapshotResult | null = null;
+ let extB: ExtractSnapshotResult | null = null;
+ try {
+ extA = extractSnapshotToTemp(vault, a!);
+ const bRoot = b !== undefined ? (extB = extractSnapshotToTemp(vault, b)).brainRoot : brainDirs(vault).brain;
+ const diff = diffBrainTrees(extA.brainRoot, bRoot);
+ const out = flags["json"] ? JSON.stringify(renderDiffJson(diff), null, 2) + "\n" : renderDiffMarkdown(diff, { aLabel: a!, bLabel: b ?? "live" });
+ process.stdout.write(out + (out.endsWith("\n") ? "" : "\n"));
+ return 0;
+ } catch (exc) {
+ return fail(`snapshot diff failed: ${(exc as Error).message ?? exc}`);
+ } finally {
+ extA?.cleanup();
+ extB?.cleanup();
+ }
+}
+
+export async function handleBrainSnapshotSubcommand(argv: ReadonlyArray<string>): Promise<number> {
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
+ process.stdout.write(
+ "usage: o2b brain snapshot <verb> [args...]\n" +
+ "Verbs:\n" +
+ " diff <run_id_a> [<run_id_b>] Read-only diff between two snapshots,\n" +
+ " or between a snapshot and live Brain/.\n",
+ );
+ return argv.length === 0 ? 2 : 0;
+ }
+ const sub = argv[0]!;
+ const rest = argv.slice(1);
+ switch (sub) {
+ case "diff": return await cmdBrainSnapshotDiff([...rest]);
+ default:
+ process.stderr.write(`unknown brain snapshot verb: ${sub}; supported: diff\n`);
+ return 2;
+ }
+}
diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.ts
new file mode 100644
index 00000000..822637be
--- /dev/null
+++ b/src/cli/brain/verbs/upgrade.ts
@@ -0,0 +1,67 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { planUpgrade, applyUpgrade, BrainUpgradeError, type UpgradePlan } from "../../../core/brain/upgrade.ts";
+import { parse, fail, ok, okJson, resolveBrainVault, printUpgradePlanText, renderUpgradePlanJson, readSingleLine } from "../helpers.ts";
+
+export async function cmdBrainUpgrade(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ "dry-run": { type: "boolean" },
+ apply: { type: "boolean" },
+ yes: { type: "boolean" },
+ check: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ if (flags["dry-run"] && flags["apply"]) return fail("brain upgrade: --dry-run and --apply are mutually exclusive");
+ if (flags["check"] && flags["apply"]) return fail("brain upgrade: --check and --apply are mutually exclusive");
+
+ let plan: UpgradePlan;
+ try { plan = planUpgrade(vault); }
+ catch (exc) { return fail(`upgrade plan failed: ${(exc as Error).message ?? exc}`); }
+
+ if (flags["check"]) {
+ if (flags["json"]) { okJson(renderUpgradePlanJson(plan)); }
+ else { printUpgradePlanText(plan); }
+ return plan.pending > 0 || plan.errors > 0 ? 2 : 0;
+ }
+
+ if (!flags["apply"]) {
+ if (flags["json"]) { okJson(renderUpgradePlanJson(plan)); }
+ else { printUpgradePlanText(plan); }
+ return 0;
+ }
+
+ if (plan.errors > 0) return fail(`upgrade aborted: ${plan.errors} file(s) failed to plan; run with --dry-run to inspect the error.`);
+ if (plan.pending === 0) {
+ if (flags["json"]) { okJson({ run_id: "", snapshot_path: "", files_updated: [] }); }
+ else { ok("upgrade: nothing to do; all managed files match the current release."); }
+ return 0;
+ }
+ if (!flags["yes"]) {
+ if (flags["json"] || !process.stdin.isTTY) return fail("brain upgrade --apply requires --yes in non-interactive mode (--json or non-TTY stdin)");
+ process.stderr.write(
+ `About to rewrite ${plan.pending} managed file(s):\n` +
+ plan.files.filter((f) => f.status === "update").map((f) => ` - ${f.path}\n`).join("") +
+ `A pre-apply snapshot will be taken (rollback via run id).\nProceed? [y/N] `,
+ );
+ const ans = await readSingleLine();
+ if (ans.toLowerCase() !== "y" && ans.toLowerCase() !== "yes") { ok("upgrade cancelled"); return 0; }
+ }
+
+ let result;
+ try { result = applyUpgrade(vault, { now: new Date() }); }
+ catch (exc) {
+ if (exc instanceof BrainUpgradeError) { process.stderr.write(`error: ${exc.message}\n`); return 1; }
+ return fail(`upgrade failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) { okJson({ run_id: result.run_id, snapshot_path: result.snapshot_path, files_updated: result.files_updated }); }
+ else {
+ ok(`run_id: ${result.run_id}`);
+ ok(`snapshot: ${result.snapshot_path}`);
+ for (const p of result.files_updated) ok(` updated: ${p}`);
+ }
+ return 0;
+}
diff --git a/src/cli/coerce.ts b/src/cli/coerce.ts
new file mode 100644
index 00000000..768c4c1e
--- /dev/null
+++ b/src/cli/coerce.ts
@@ -0,0 +1,65 @@
+/**
+ * Shared coercion helpers for the `o2b` CLI.
+ *
+ * Parse and validate optional CLI flag values. Each helper returns a
+ * `{ value, error }` tuple so the caller can decide the exit code.
+ */
+
+/**
+ * Parse an optional `--<name>` flag whose value should be a finite number.
+ * Returns `{ value: number | null, error: string | null }`.
+ *
+ * Trim before testing for emptiness β€” `Number(" ")` evaluates to `0` in JS.
+ */
+export function parseOptionalNumberFlag(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ name: string,
+): { value: number | null; error: string | null } {
+ const raw = flags[name] as string | undefined;
+ if (raw === undefined) return { value: null, error: null };
+ const trimmed = raw.trim();
+ if (trimmed === "") return { value: null, error: null };
+ const parsed = Number(trimmed);
+ if (!Number.isFinite(parsed)) {
+ return { value: null, error: `--${name} must be a number, got: ${raw}` };
+ }
+ return { value: parsed, error: null };
+}
+
+/**
+ * Strict ISO-8601 timestamp matcher used by `--now / --since / --until`.
+ * The plain `new Date(s)` constructor is far too permissive. We require
+ * a full date-time including offset (`Z` or `Β±HH:MM`).
+ *
+ * Sibling regex: `ISO_UTC_TS_RE` in `src/core/brain/log-jsonl.ts`. That
+ * one is intentionally stricter (Z only, no `Β±HH:MM`, no millisecond
+ * cap) because it parses values that the *writer* (`renderJsonlLine`)
+ * has just emitted in canonical UTC. This one is looser because it
+ * has to accept whatever a human typed on the CLI; the resulting
+ * `Date` is normalised to UTC by the JS runtime before any downstream
+ * code touches it.
+ */
+export const ISO_8601_RE =
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/;
+
+/**
+ * Parse an optional `--<name>` flag as a strict ISO-8601 Date.
+ * Returns `{ value: Date | null, error: string | null }`.
+ */
+export function parseOptionalIsoDate(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ name: string,
+): { value: Date | null; error: string | null } {
+ const raw = flags[name] as string | undefined;
+ if (raw === undefined) return { value: null, error: null };
+ const trimmed = raw.trim();
+ if (trimmed === "") return { value: null, error: null };
+ if (!ISO_8601_RE.test(trimmed)) {
+ return { value: null, error: `--${name} must be a valid ISO-8601 timestamp; got ${raw}` };
+ }
+ const d = new Date(trimmed);
+ if (!Number.isFinite(d.getTime())) {
+ return { value: null, error: `--${name} must be a valid ISO-8601 timestamp; got ${raw}` };
+ }
+ return { value: d, error: null };
+}
diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts
new file mode 100644
index 00000000..e0c90979
--- /dev/null
+++ b/src/cli/helpers.ts
@@ -0,0 +1,32 @@
+/**
+ * Shared CLI utilities used across subcommand modules.
+ */
+
+import { resolveVault } from "../core/config.ts";
+
+export const NO_VAULT_ERROR =
+ "error: no vault configured. Pass --vault <path> explicitly, " +
+ "set VAULT_DIR in the environment, or run " +
+ "`o2b init --vault <path> ...` first to persist a default.";
+
+export class NoVaultConfiguredError extends Error {
+ constructor() {
+ super(NO_VAULT_ERROR);
+ this.name = "NoVaultConfiguredError";
+ }
+}
+
+export function requireVault(flagVal: string | undefined, configPath: string | null): string {
+ const vault = flagVal ?? resolveVault(configPath ?? undefined);
+ if (vault === null || vault === undefined) {
+ throw new NoVaultConfiguredError();
+ }
+ return vault;
+}
+
+export function sortedReplacer(_key: string, value: unknown): unknown {
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
+ }
+ return value;
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 6ff7e152..dad136fc 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -8,7 +8,7 @@
* statement, not a registry β€” keeps the control flow obvious.
*/
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import {
@@ -17,35 +17,34 @@ import {
redactMapping,
resolveAgentName,
resolveTimezone,
- resolveVault,
setConfigValue,
} from "../core/config.ts";
import { doctor } from "../core/doctor.ts";
import { appendEvent } from "../core/event-log.ts";
import { bootstrapVault } from "../core/init.ts";
-import {
- approvePendingRequest,
- buildPaymentDigest,
- checkPolicy,
- consumePendingRequest,
- listPendingRequests,
- loadPendingRequest,
- payMemoryDirs,
- rejectPendingRequest,
- renderPaymentDigestTelegram,
- vaultRelativePath,
- writeAsset,
- writePendingRequest,
- writePolicyIfMissing,
- writeReceipt,
- writeReport,
-} from "../core/pay-memory/index.ts";
-import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
import { listVaultPages, writeFrontmatter } from "../core/vault.ts";
import { CliError, parseFlags } from "./argparse.ts";
import { handleBrainSubcommand } from "./brain.ts";
import { handleDisciplineSubcommand } from "./discipline.ts";
import { handleSearchSubcommand } from "./search.ts";
+import {
+ NoVaultConfiguredError,
+ requireVault,
+ sortedReplacer,
+} from "./helpers.ts";
+import {
+ cmdInitPayMemory,
+ cmdAppendPaymentReceipt,
+ cmdCaptureAsset,
+ cmdPaymentDigest,
+ cmdRequestPaymentApproval,
+ cmdApprovePaymentRequest,
+ cmdRejectPaymentRequest,
+ cmdConsumePaymentRequest,
+ cmdListPendingPayments,
+ cmdCheckPaymentPolicy,
+ cmdPaymentReport,
+} from "./pay-memory/index.ts";
import {
installCli,
renderInstallResult,
@@ -57,75 +56,6 @@ import { MCPServer } from "../mcp/server.ts";
import { serveStdio } from "../mcp/stdio.ts";
import { SERVER_VERSION } from "../mcp/protocol.ts";
-const NO_VAULT_ERROR =
- "error: no vault configured. Pass --vault <path> explicitly, " +
- "set VAULT_DIR in the environment, or run " +
- "`o2b init --vault <path> ...` first to persist a default.";
-
-class NoVaultConfiguredError extends Error {
- constructor() {
- super(NO_VAULT_ERROR);
- this.name = "NoVaultConfiguredError";
- }
-}
-
-function requireVault(flagVal: string | undefined, configPath: string | null): string {
- const vault = flagVal ?? resolveVault(configPath ?? undefined);
- if (vault === null || vault === undefined) {
- // Throw rather than process.exit so the dispatcher's catch can convert
- // this into a clean exit code 1 β€” main() stays reusable in-process
- // (e.g. test harnesses that import and call it).
- throw new NoVaultConfiguredError();
- }
- return vault;
-}
-
-/**
- * Emit `payload` as pretty-printed JSON with sorted keys, plus a trailing
- * newline. Centralises the format so the eleven Pay Memory subcommands
- * don't each repeat the same `JSON.stringify(...) + "\n"` boilerplate.
- */
-function writeJson(payload: unknown): void {
- process.stdout.write(JSON.stringify(payload, sortedReplacer, 2) + "\n");
-}
-
-/**
- * Render a uniform `error: failed to <action>: <reason>\n` message on
- * stderr and return exit-code 1. Use as the `return failWith(...)` last
- * expression of a catch arm so the subcommand keeps its single-exit
- * shape.
- */
-function failWith(action: string, exc: unknown): number {
- const reason = (exc as Error)?.message ?? String(exc);
- process.stderr.write(`error: failed to ${action}: ${reason}\n`);
- return 1;
-}
-
-/**
- * Parse an optional `--<name>` flag whose value should be a finite number.
- * Returns `{ value: number | null, error: string | null }`. The caller is
- * expected to bail with exit 2 + the error string when `error` is set.
- *
- * Trim before testing for emptiness β€” `Number(" ")` evaluates to `0` in
- * JS, and without this whitespace-only flags would silently bypass the
- * missing-amount guard in `check-payment-policy` and
- * `request-payment-approval`.
- */
-function parseOptionalNumberFlag(
- flags: Record<string, string | boolean | string[] | undefined>,
- name: string,
-): { value: number | null; error: string | null } {
- const raw = flags[name] as string | undefined;
- if (raw === undefined) return { value: null, error: null };
- const trimmed = raw.trim();
- if (trimmed === "") return { value: null, error: null };
- const parsed = Number(trimmed);
- if (!Number.isFinite(parsed)) {
- return { value: null, error: `--${name} must be a number, got: ${raw}` };
- }
- return { value: parsed, error: null };
-}
-
// ── Subcommands ─────────────────────────────────────────────────────────────
async function cmdStatus(argv: string[]): Promise<number> {
@@ -408,738 +338,6 @@ async function cmdIndex(argv: string[]): Promise<number> {
return 0;
}
-// ── Pay Memory subcommands ──────────────────────────────────────────────────
-
-async function cmdInitPayMemory(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- agent: { type: "string" },
- overwrite: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const agent =
- (flags["agent"] as string | undefined) ?? resolveAgentName(config);
-
- const dirs = payMemoryDirs(vault);
- const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];
- const created: string[] = [];
- const skipped: string[] = [];
- for (const dir of dirList) {
- const existed = existsSync(dir);
- try {
- mkdirSync(dir, { recursive: true });
- } catch (exc) {
- process.stderr.write(
- `error: failed to create ${dir}: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- (existed ? skipped : created).push(vaultRelativePath(dir, vault));
- }
-
- let policy;
- try {
- policy = writePolicyIfMissing(vault, { overwrite: Boolean(flags["overwrite"]) });
- } catch (exc) {
- process.stderr.write(
- `error: failed to write policy: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- const policyRel = vaultRelativePath(policy.path, vault);
- const policyStatus = policy.status;
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- vault_path: vault,
- agent,
- created,
- skipped,
- policy_path: policyRel,
- policy_status: policyStatus,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- return 0;
- }
-
- process.stdout.write(`pay-memory layout initialized: ${vault}\n`);
- for (const rel of created) process.stdout.write(` created: ${rel}\n`);
- for (const rel of skipped) process.stdout.write(` exists: ${rel}\n`);
- process.stdout.write(` ${policyStatus}: ${policyRel}\n`);
- process.stdout.write(`agent: ${agent}\n`);
- return 0;
-}
-
-async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- agent: { type: "string" },
- service: { type: "string", required: true },
- status: { type: "string", required: true },
- reason: { type: "string", required: true },
- category: { type: "string" },
- endpoint: { type: "string" },
- "expected-cost": { type: "string" },
- "actual-amount": { type: "string" },
- currency: { type: "string" },
- "payment-proof": { type: "string" },
- "result-ref": { type: "string" },
- "result-note": { type: "string" },
- "raw-output-file": { type: "string" },
- slug: { type: "string" },
- date: { type: "string" },
- time: { type: "string" },
- overwrite: { type: "boolean" },
- json: { type: "boolean" },
- "policy-status": { type: "string" },
- "policy-rule": { type: "string" },
- "policy-reasons": { type: "string-array" },
- "policy-checked-at": { type: "string" },
- "from-request": { type: "string" },
- "payment-layer": { type: "string" },
- network: { type: "string" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const agent =
- (flags["agent"] as string | undefined) ?? resolveAgentName(config);
- const tz = resolveTimezone(config);
-
- let rawOutput: string | undefined;
- const rawOutputFile = flags["raw-output-file"] as string | undefined;
- if (rawOutputFile) {
- try {
- rawOutput = readFileSync(rawOutputFile, "utf8");
- } catch (exc) {
- process.stderr.write(
- `error: cannot read raw-output-file: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- }
-
- // --policy-status / --from-request audit context. `--from-request`
- // pulls policy + approval state from the named pending-payment-request
- // so the agent doesn't have to repeat it on the command line. Explicit
- // flags win over `--from-request` so a caller can override individual
- // fields.
- let policyStatus = (flags["policy-status"] as string | undefined) ?? null;
- let policyRule = (flags["policy-rule"] as string | undefined) ?? null;
- let policyReasons = (flags["policy-reasons"] as string[] | undefined) ?? null;
- let policyCheckedAt =
- (flags["policy-checked-at"] as string | undefined) ?? null;
- let approvalStatus: string | null = null;
- let approvedBy: string | null = null;
- let approvedAt: string | null = null;
- const fromRequest = (flags["from-request"] as string | undefined) ?? null;
- if (fromRequest) {
- const loaded = loadPendingRequest(vault, fromRequest);
- if (!loaded) {
- process.stderr.write(`error: pending request not found: ${fromRequest}\n`);
- return 1;
- }
- const meta = loaded.metadata;
- const get = (k: string): string | null => {
- const v = meta[k];
- if (v === undefined || v === null) return null;
- return Array.isArray(v) ? v.join(", ") : String(v);
- };
- policyStatus ??= get("policy_status");
- policyRule ??= get("policy_rule");
- approvalStatus ??= loaded.status;
- approvedBy ??= get("approved_by");
- approvedAt ??= get("approved_at");
- }
- if (policyStatus !== null) {
- const allowed: ReadonlyArray<ReceiptPolicyStatus> = [
- "allowed",
- "approval_required",
- "denied",
- "not_checked",
- ];
- if (!allowed.includes(policyStatus as ReceiptPolicyStatus)) {
- process.stderr.write(
- `error: --policy-status must be one of: ${allowed.join(", ")}\n`,
- );
- return 2;
- }
- }
-
- let result;
- try {
- result = writeReceipt(vault, {
- agent,
- service: String(flags["service"]),
- status: String(flags["status"]),
- reason: String(flags["reason"]),
- paymentLayer: (flags["payment-layer"] as string | undefined) ?? null,
- network: (flags["network"] as string | undefined) ?? null,
- category: (flags["category"] as string | undefined) ?? null,
- endpoint: (flags["endpoint"] as string | undefined) ?? null,
- expectedCost: (flags["expected-cost"] as string | undefined) ?? null,
- actualAmount: (flags["actual-amount"] as string | undefined) ?? null,
- currency: (flags["currency"] as string | undefined) ?? null,
- paymentProof: (flags["payment-proof"] as string | undefined) ?? null,
- resultRef: (flags["result-ref"] as string | undefined) ?? null,
- resultNote: (flags["result-note"] as string | undefined) ?? null,
- rawOutput: rawOutput ?? null,
- slug: (flags["slug"] as string | undefined) ?? null,
- date: (flags["date"] as string | undefined) ?? null,
- time: (flags["time"] as string | undefined) ?? null,
- overwrite: Boolean(flags["overwrite"]),
- tz,
- policyStatus: policyStatus as ReceiptPolicyStatus | null,
- policyRule,
- policyReasons,
- policyCheckedAt,
- approvalRequestId: fromRequest,
- approvalStatus: approvalStatus as
- | "pending"
- | "approved"
- | "rejected"
- | "consumed"
- | null,
- approvedBy,
- approvedAt,
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to write receipt: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- path: result.relativePath,
- absolute_path: result.path,
- slug: result.slug,
- date: result.date,
- created: result.created,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`receipt: ${result.relativePath}\n`);
- process.stdout.write(`slug: ${result.slug}\n`);
- process.stdout.write(`date: ${result.date}\n`);
- }
- return 0;
-}
-
-async function cmdCaptureAsset(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- title: { type: "string", required: true },
- service: { type: "string", required: true },
- "result-url": { type: "string", required: true },
- "source-receipt": { type: "string" },
- "prompt-file": { type: "string" },
- "used-in": { type: "string" },
- slug: { type: "string" },
- overwrite: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
-
- let prompt: string | undefined;
- const promptFile = flags["prompt-file"] as string | undefined;
- if (promptFile) {
- try {
- prompt = readFileSync(promptFile, "utf8");
- } catch (exc) {
- process.stderr.write(
- `error: cannot read prompt-file: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- }
-
- let result;
- try {
- result = writeAsset(vault, {
- title: String(flags["title"]),
- service: String(flags["service"]),
- resultUrl: String(flags["result-url"]),
- sourceReceipt: (flags["source-receipt"] as string | undefined) ?? null,
- prompt: prompt ?? null,
- usedIn: (flags["used-in"] as string | undefined) ?? null,
- slug: (flags["slug"] as string | undefined) ?? null,
- overwrite: Boolean(flags["overwrite"]),
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to write asset: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- path: result.relativePath,
- absolute_path: result.path,
- slug: result.slug,
- created: result.created,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`asset: ${result.relativePath}\n`);
- process.stdout.write(`slug: ${result.slug}\n`);
- }
- return 0;
-}
-
-async function cmdPaymentDigest(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- date: { type: "string" },
- "empty-mode": { type: "string", default: "silent" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const tz = resolveTimezone(config);
-
- const emptyMode = String(flags["empty-mode"]);
- if (!["silent", "empty", "summary"].includes(emptyMode)) {
- process.stderr.write(`error: --empty-mode must be silent|empty|summary\n`);
- return 2;
- }
-
- let digest;
- try {
- digest = buildPaymentDigest(vault, {
- date: (flags["date"] as string | undefined) ?? null,
- tz,
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to build digest: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- date: digest.date,
- services: digest.services,
- receipts: digest.receipts,
- total_amount: digest.totalAmount,
- currency: digest.currency,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- const text = renderPaymentDigestTelegram(digest, {
- emptyMode: emptyMode as "silent" | "empty" | "summary",
- });
- if (text) process.stdout.write(text + "\n");
- }
- return 0;
-}
-
-async function cmdRequestPaymentApproval(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- agent: { type: "string" },
- service: { type: "string", required: true },
- reason: { type: "string", required: true },
- "expected-amount": { type: "string" },
- currency: { type: "string" },
- category: { type: "string" },
- endpoint: { type: "string" },
- "expected-output": { type: "string" },
- "vault-files": { type: "string-array" },
- slug: { type: "string" },
- date: { type: "string" },
- time: { type: "string" },
- "enforce-policy": { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const agent =
- (flags["agent"] as string | undefined) ?? resolveAgentName(config);
- const tz = resolveTimezone(config);
-
- const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(
- flags,
- "expected-amount",
- );
- if (expectedErr) {
- process.stderr.write(`error: ${expectedErr}\n`);
- return 2;
- }
-
- let result;
- try {
- result = writePendingRequest(vault, {
- agent,
- service: String(flags["service"]),
- reason: String(flags["reason"]),
- expectedAmount,
- currency: (flags["currency"] as string | undefined) ?? null,
- category: (flags["category"] as string | undefined) ?? null,
- endpoint: (flags["endpoint"] as string | undefined) ?? null,
- expectedOutput: (flags["expected-output"] as string | undefined) ?? null,
- vaultFiles: (flags["vault-files"] as string[] | undefined) ?? null,
- slug: (flags["slug"] as string | undefined) ?? null,
- date: (flags["date"] as string | undefined) ?? null,
- time: (flags["time"] as string | undefined) ?? null,
- tz,
- enforcePolicy: Boolean(flags["enforce-policy"]),
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to create pending request: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- id: result.id,
- path: result.relativePath,
- status: result.status,
- created: result.created,
- policy_status: result.policyDecision.status,
- policy_rule: result.policyDecision.rule,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`pending: ${result.relativePath}\n`);
- process.stdout.write(`id: ${result.id}\n`);
- process.stdout.write(`policy: ${result.policyDecision.status}\n`);
- }
- return 0;
-}
-
-async function cmdApprovePaymentRequest(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- id: { type: "string", required: true },
- "approved-by": { type: "string", required: true },
- note: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
-
- let result;
- try {
- result = await approvePendingRequest(vault, String(flags["id"]), {
- approvedBy: String(flags["approved-by"]),
- note: (flags["note"] as string | undefined) ?? null,
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to approve request: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- { id: result.id, status: result.status, path: result.relativePath },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`approved: ${result.relativePath}\n`);
- process.stdout.write(`status: ${result.status}\n`);
- }
- return 0;
-}
-
-async function cmdRejectPaymentRequest(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- id: { type: "string", required: true },
- "rejected-by": { type: "string", required: true },
- reason: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
-
- let result;
- try {
- result = await rejectPendingRequest(vault, String(flags["id"]), {
- rejectedBy: String(flags["rejected-by"]),
- reason: (flags["reason"] as string | undefined) ?? null,
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to reject request: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- { id: result.id, status: result.status, path: result.relativePath },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`rejected: ${result.relativePath}\n`);
- process.stdout.write(`status: ${result.status}\n`);
- }
- return 0;
-}
-
-async function cmdConsumePaymentRequest(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- id: { type: "string", required: true },
- receipt: { type: "string", required: true },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
-
- let result;
- try {
- result = await consumePendingRequest(vault, String(flags["id"]), {
- receiptPath: String(flags["receipt"]),
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to consume request: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- { id: result.id, status: result.status, path: result.relativePath },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`consumed: ${result.relativePath}\n`);
- process.stdout.write(`status: ${result.status}\n`);
- }
- return 0;
-}
-
-async function cmdListPendingPayments(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- status: { type: "string", default: "pending" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const status = String(flags["status"]);
- const valid = ["pending", "approved", "rejected", "consumed", "all"];
- if (!valid.includes(status)) {
- process.stderr.write(
- `error: --status must be one of: ${valid.join(", ")}\n`,
- );
- return 2;
- }
-
- let summaries;
- try {
- summaries = listPendingRequests(vault, {
- status: status as "pending" | "approved" | "rejected" | "consumed" | "all",
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to list requests: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- summaries.map((s) => ({
- id: s.id,
- path: s.relativePath,
- status: s.status,
- service: s.service,
- reason: s.reason,
- expected_amount: s.expectedAmount,
- currency: s.currency,
- created: s.created,
- policy_status: s.policyStatus,
- })),
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else if (summaries.length === 0) {
- process.stdout.write(`no requests with status: ${status}\n`);
- } else {
- for (const s of summaries) {
- // Use an explicit null check; a truthy check would hide an actual
- // `expected_amount: "0"` (legitimate for free-tier sandbox calls)
- // because `Boolean("0") === true` only happens for *strings* β€” once
- // any future change starts storing the field as a number, `0`
- // would silently disappear from the list output.
- const cost =
- s.expectedAmount !== null && s.expectedAmount !== ""
- ? ` (${s.expectedAmount}${s.currency ? " " + s.currency : ""})`
- : "";
- process.stdout.write(`${s.status}\t${s.id}\t${s.service}${cost}\t${s.reason}\n`);
- }
- }
- return 0;
-}
-
-async function cmdCheckPaymentPolicy(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- service: { type: "string", required: true },
- "expected-amount": { type: "string" },
- currency: { type: "string" },
- category: { type: "string" },
- date: { type: "string" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
- const tz = resolveTimezone(config);
-
- const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(
- flags,
- "expected-amount",
- );
- if (expectedErr) {
- process.stderr.write(`error: ${expectedErr}\n`);
- return 2;
- }
-
- let decision;
- try {
- decision = checkPolicy(vault, {
- service: String(flags["service"]),
- expectedAmount,
- currency: (flags["currency"] as string | undefined) ?? null,
- category: (flags["category"] as string | undefined) ?? null,
- date: (flags["date"] as string | undefined) ?? null,
- tz,
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to evaluate policy: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- status: decision.status,
- allowed: decision.allowed,
- approval_required: decision.approvalRequired,
- rule: decision.rule,
- reasons: decision.reasons,
- has_policy: decision.hasPolicy,
- policy_path:
- decision.policyPath !== null
- ? vaultRelativePath(decision.policyPath, vault)
- : null,
- currency: decision.currency,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`status: ${decision.status}\n`);
- process.stdout.write(`has_policy: ${decision.hasPolicy}\n`);
- if (decision.rule) process.stdout.write(`rule: ${decision.rule}\n`);
- for (const r of decision.reasons) process.stdout.write(` - ${r}\n`);
- }
- // Exit 0 when allowed; 1 when denied; 3 when approval is required (the
- // shell distinguishes the three so a calling script can branch).
- if (decision.allowed) return 0;
- if (decision.approvalRequired) return 3;
- return 1;
-}
-
-async function cmdPaymentReport(argv: string[]): Promise<number> {
- const { flags } = parseFlags(argv, {
- vault: { type: "string" },
- date: { type: "string", required: true },
- title: { type: "string" },
- task: { type: "string" },
- slug: { type: "string" },
- overwrite: { type: "boolean" },
- json: { type: "boolean" },
- });
- const config = defaultConfigPath();
- const vault = requireVault(flags["vault"] as string | undefined, config);
-
- let result;
- try {
- result = writeReport(vault, {
- date: String(flags["date"]),
- title: (flags["title"] as string | undefined) ?? null,
- task: (flags["task"] as string | undefined) ?? null,
- slug: (flags["slug"] as string | undefined) ?? null,
- overwrite: Boolean(flags["overwrite"]),
- });
- } catch (exc) {
- process.stderr.write(
- `error: failed to write report: ${(exc as Error).message ?? exc}\n`,
- );
- return 1;
- }
-
- if (flags["json"]) {
- process.stdout.write(
- JSON.stringify(
- {
- path: result.relativePath,
- absolute_path: result.path,
- slug: result.slug,
- receipts_used: result.receiptsUsed,
- },
- sortedReplacer,
- 2,
- ) + "\n",
- );
- } else {
- process.stdout.write(`report: ${result.relativePath}\n`);
- process.stdout.write(`receipts: ${result.receiptsUsed}\n`);
- }
- return 0;
-}
-
async function cmdMcp(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, {
vault: { type: "string" },
@@ -1288,13 +486,6 @@ Search:
search check Pre-flight diagnostics (SQLite, FTS5, vec, provider)
`;
-function sortedReplacer(_key: string, value: unknown): unknown {
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
- return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
- }
- return value;
-}
-
export async function main(argv: ReadonlyArray<string>): Promise<number> {
if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
process.stdout.write(HELP);
diff --git a/src/cli/output.ts b/src/cli/output.ts
new file mode 100644
index 00000000..08f41d08
--- /dev/null
+++ b/src/cli/output.ts
@@ -0,0 +1,51 @@
+/**
+ * Shared output helpers for the `o2b` CLI.
+ *
+ * Centralises the repeated stdout/stderr write patterns so every
+ * subcommand uses the same shape for success, error, info, and JSON
+ * output.
+ */
+
+/** Emit a state-changing command's status line on stdout. */
+export function ok(line: string): void {
+ process.stdout.write(line + (line.endsWith("\n") ? "" : "\n"));
+}
+
+/** Emit minimal JSON for `--json` on state-changing commands. */
+export function okJson(payload: Record<string, unknown>): void {
+ process.stdout.write(JSON.stringify({ ok: true, ...payload }, null, 2) + "\n");
+}
+
+/** Write an error message to stderr and return exit code 1. */
+export function fail(message: string): number {
+ process.stderr.write(`error: ${message}\n`);
+ return 1;
+}
+
+/** Emit an informational line on stdout (no `error:` prefix). */
+export function info(message: string): void {
+ process.stdout.write(message + (message.endsWith("\n") ? "" : "\n"));
+}
+
+/**
+ * Render `payload` as pretty-printed JSON with sorted keys, plus a
+ * trailing newline. Centralises the format so subcommands don't each
+ * repeat the same `JSON.stringify(...) + "\n"` boilerplate.
+ */
+export function writeJson(
+ payload: unknown,
+ replacer?: ((key: string, value: unknown) => unknown) | null,
+): void {
+ process.stdout.write(JSON.stringify(payload, replacer ?? undefined, 2) + "\n");
+}
+
+/**
+ * Render a uniform `error: failed to <action>: <reason>\n` message on
+ * stderr and return exit-code 1. Use as the `return failWith(...)` last
+ * expression of a catch arm so the subcommand keeps its single-exit shape.
+ */
+export function failWith(action: string, exc: unknown): number {
+ const reason = (exc as Error)?.message ?? String(exc);
+ process.stderr.write(`error: failed to ${action}: ${reason}\n`);
+ return 1;
+}
diff --git a/src/cli/pay-memory/index.ts b/src/cli/pay-memory/index.ts
new file mode 100644
index 00000000..00ace1ac
--- /dev/null
+++ b/src/cli/pay-memory/index.ts
@@ -0,0 +1,11 @@
+export { cmdInitPayMemory } from "./verbs/init.ts";
+export { cmdAppendPaymentReceipt } from "./verbs/append-receipt.ts";
+export { cmdCaptureAsset } from "./verbs/capture-asset.ts";
+export { cmdPaymentDigest } from "./verbs/digest.ts";
+export { cmdRequestPaymentApproval } from "./verbs/request-approval.ts";
+export { cmdApprovePaymentRequest } from "./verbs/approve.ts";
+export { cmdRejectPaymentRequest } from "./verbs/reject.ts";
+export { cmdConsumePaymentRequest } from "./verbs/consume.ts";
+export { cmdListPendingPayments } from "./verbs/list.ts";
+export { cmdCheckPaymentPolicy } from "./verbs/check-policy.ts";
+export { cmdPaymentReport } from "./verbs/report.ts";
diff --git a/src/cli/pay-memory/verbs/append-receipt.ts b/src/cli/pay-memory/verbs/append-receipt.ts
new file mode 100644
index 00000000..4695e182
--- /dev/null
+++ b/src/cli/pay-memory/verbs/append-receipt.ts
@@ -0,0 +1,163 @@
+import { readFileSync } from "node:fs";
+
+import { defaultConfigPath, resolveAgentName, resolveTimezone } from "../../../core/config.ts";
+import { loadPendingRequest, writeReceipt } from "../../../core/pay-memory/index.ts";
+import type { ReceiptPolicyStatus } from "../../../core/pay-memory/types.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdAppendPaymentReceipt(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ service: { type: "string", required: true },
+ status: { type: "string", required: true },
+ reason: { type: "string", required: true },
+ category: { type: "string" },
+ endpoint: { type: "string" },
+ "expected-cost": { type: "string" },
+ "actual-amount": { type: "string" },
+ currency: { type: "string" },
+ "payment-proof": { type: "string" },
+ "result-ref": { type: "string" },
+ "result-note": { type: "string" },
+ "raw-output-file": { type: "string" },
+ slug: { type: "string" },
+ date: { type: "string" },
+ time: { type: "string" },
+ overwrite: { type: "boolean" },
+ json: { type: "boolean" },
+ "policy-status": { type: "string" },
+ "policy-rule": { type: "string" },
+ "policy-reasons": { type: "string-array" },
+ "policy-checked-at": { type: "string" },
+ "from-request": { type: "string" },
+ "payment-layer": { type: "string" },
+ network: { type: "string" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const agent =
+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const tz = resolveTimezone(config);
+
+ let rawOutput: string | undefined;
+ const rawOutputFile = flags["raw-output-file"] as string | undefined;
+ if (rawOutputFile) {
+ try {
+ rawOutput = readFileSync(rawOutputFile, "utf8");
+ } catch (exc) {
+ process.stderr.write(
+ `error: cannot read raw-output-file: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ }
+
+ let policyStatus = (flags["policy-status"] as string | undefined) ?? null;
+ let policyRule = (flags["policy-rule"] as string | undefined) ?? null;
+ let policyReasons = (flags["policy-reasons"] as string[] | undefined) ?? null;
+ let policyCheckedAt =
+ (flags["policy-checked-at"] as string | undefined) ?? null;
+ let approvalStatus: string | null = null;
+ let approvedBy: string | null = null;
+ let approvedAt: string | null = null;
+ const fromRequest = (flags["from-request"] as string | undefined) ?? null;
+ if (fromRequest) {
+ const loaded = loadPendingRequest(vault, fromRequest);
+ if (!loaded) {
+ process.stderr.write(`error: pending request not found: ${fromRequest}\n`);
+ return 1;
+ }
+ const meta = loaded.metadata;
+ const get = (k: string): string | null => {
+ const v = meta[k];
+ if (v === undefined || v === null) return null;
+ return Array.isArray(v) ? v.join(", ") : String(v);
+ };
+ policyStatus ??= get("policy_status");
+ policyRule ??= get("policy_rule");
+ approvalStatus ??= loaded.status;
+ approvedBy ??= get("approved_by");
+ approvedAt ??= get("approved_at");
+ }
+ if (policyStatus !== null) {
+ const allowed: ReadonlyArray<ReceiptPolicyStatus> = [
+ "allowed",
+ "approval_required",
+ "denied",
+ "not_checked",
+ ];
+ if (!allowed.includes(policyStatus as ReceiptPolicyStatus)) {
+ process.stderr.write(
+ `error: --policy-status must be one of: ${allowed.join(", ")}\n`,
+ );
+ return 2;
+ }
+ }
+
+ let result;
+ try {
+ result = writeReceipt(vault, {
+ agent,
+ service: String(flags["service"]),
+ status: String(flags["status"]),
+ reason: String(flags["reason"]),
+ paymentLayer: (flags["payment-layer"] as string | undefined) ?? null,
+ network: (flags["network"] as string | undefined) ?? null,
+ category: (flags["category"] as string | undefined) ?? null,
+ endpoint: (flags["endpoint"] as string | undefined) ?? null,
+ expectedCost: (flags["expected-cost"] as string | undefined) ?? null,
+ actualAmount: (flags["actual-amount"] as string | undefined) ?? null,
+ currency: (flags["currency"] as string | undefined) ?? null,
+ paymentProof: (flags["payment-proof"] as string | undefined) ?? null,
+ resultRef: (flags["result-ref"] as string | undefined) ?? null,
+ resultNote: (flags["result-note"] as string | undefined) ?? null,
+ rawOutput: rawOutput ?? null,
+ slug: (flags["slug"] as string | undefined) ?? null,
+ date: (flags["date"] as string | undefined) ?? null,
+ time: (flags["time"] as string | undefined) ?? null,
+ overwrite: Boolean(flags["overwrite"]),
+ tz,
+ policyStatus: policyStatus as ReceiptPolicyStatus | null,
+ policyRule,
+ policyReasons,
+ policyCheckedAt,
+ approvalRequestId: fromRequest,
+ approvalStatus: approvalStatus as
+ | "pending"
+ | "approved"
+ | "rejected"
+ | "consumed"
+ | null,
+ approvedBy,
+ approvedAt,
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to write receipt: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ path: result.relativePath,
+ absolute_path: result.path,
+ slug: result.slug,
+ date: result.date,
+ created: result.created,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`receipt: ${result.relativePath}\n`);
+ process.stdout.write(`slug: ${result.slug}\n`);
+ process.stdout.write(`date: ${result.date}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/approve.ts b/src/cli/pay-memory/verbs/approve.ts
new file mode 100644
index 00000000..af587390
--- /dev/null
+++ b/src/cli/pay-memory/verbs/approve.ts
@@ -0,0 +1,42 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { approvePendingRequest } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdApprovePaymentRequest(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ id: { type: "string", required: true },
+ "approved-by": { type: "string", required: true },
+ note: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try {
+ result = await approvePendingRequest(vault, String(flags["id"]), {
+ approvedBy: String(flags["approved-by"]),
+ note: (flags["note"] as string | undefined) ?? null,
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to approve request: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ { id: result.id, status: result.status, path: result.relativePath },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`approved: ${result.relativePath}\n`);
+ process.stdout.write(`status: ${result.status}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/capture-asset.ts b/src/cli/pay-memory/verbs/capture-asset.ts
new file mode 100644
index 00000000..245312fa
--- /dev/null
+++ b/src/cli/pay-memory/verbs/capture-asset.ts
@@ -0,0 +1,74 @@
+import { readFileSync } from "node:fs";
+
+import { defaultConfigPath } from "../../../core/config.ts";
+import { writeAsset } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdCaptureAsset(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ title: { type: "string", required: true },
+ service: { type: "string", required: true },
+ "result-url": { type: "string", required: true },
+ "source-receipt": { type: "string" },
+ "prompt-file": { type: "string" },
+ "used-in": { type: "string" },
+ slug: { type: "string" },
+ overwrite: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let prompt: string | undefined;
+ const promptFile = flags["prompt-file"] as string | undefined;
+ if (promptFile) {
+ try {
+ prompt = readFileSync(promptFile, "utf8");
+ } catch (exc) {
+ process.stderr.write(
+ `error: cannot read prompt-file: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ }
+
+ let result;
+ try {
+ result = writeAsset(vault, {
+ title: String(flags["title"]),
+ service: String(flags["service"]),
+ resultUrl: String(flags["result-url"]),
+ sourceReceipt: (flags["source-receipt"] as string | undefined) ?? null,
+ prompt: prompt ?? null,
+ usedIn: (flags["used-in"] as string | undefined) ?? null,
+ slug: (flags["slug"] as string | undefined) ?? null,
+ overwrite: Boolean(flags["overwrite"]),
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to write asset: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ path: result.relativePath,
+ absolute_path: result.path,
+ slug: result.slug,
+ created: result.created,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`asset: ${result.relativePath}\n`);
+ process.stdout.write(`slug: ${result.slug}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/check-policy.ts b/src/cli/pay-memory/verbs/check-policy.ts
new file mode 100644
index 00000000..718e196a
--- /dev/null
+++ b/src/cli/pay-memory/verbs/check-policy.ts
@@ -0,0 +1,76 @@
+import { defaultConfigPath, resolveTimezone } from "../../../core/config.ts";
+import { checkPolicy } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseOptionalNumberFlag } from "../../coerce.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdCheckPaymentPolicy(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ service: { type: "string", required: true },
+ "expected-amount": { type: "string" },
+ currency: { type: "string" },
+ category: { type: "string" },
+ date: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const tz = resolveTimezone(config);
+
+ const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(
+ flags,
+ "expected-amount",
+ );
+ if (expectedErr) {
+ process.stderr.write(`error: ${expectedErr}\n`);
+ return 2;
+ }
+
+ let decision;
+ try {
+ decision = checkPolicy(vault, {
+ service: String(flags["service"]),
+ expectedAmount,
+ currency: (flags["currency"] as string | undefined) ?? null,
+ category: (flags["category"] as string | undefined) ?? null,
+ date: (flags["date"] as string | undefined) ?? null,
+ tz,
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to evaluate policy: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ status: decision.status,
+ allowed: decision.allowed,
+ approval_required: decision.approvalRequired,
+ rule: decision.rule,
+ reasons: decision.reasons,
+ has_policy: decision.hasPolicy,
+ policy_path:
+ decision.policyPath !== null
+ ? decision.policyPath.slice(vault.length).replace(/^\/+/, "")
+ : null,
+ currency: decision.currency,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`status: ${decision.status}\n`);
+ process.stdout.write(`has_policy: ${decision.hasPolicy}\n`);
+ if (decision.rule) process.stdout.write(`rule: ${decision.rule}\n`);
+ for (const r of decision.reasons) process.stdout.write(` - ${r}\n`);
+ }
+ if (decision.allowed) return 0;
+ if (decision.approvalRequired) return 3;
+ return 1;
+}
diff --git a/src/cli/pay-memory/verbs/consume.ts b/src/cli/pay-memory/verbs/consume.ts
new file mode 100644
index 00000000..49498b60
--- /dev/null
+++ b/src/cli/pay-memory/verbs/consume.ts
@@ -0,0 +1,40 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { consumePendingRequest } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdConsumePaymentRequest(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ id: { type: "string", required: true },
+ receipt: { type: "string", required: true },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try {
+ result = await consumePendingRequest(vault, String(flags["id"]), {
+ receiptPath: String(flags["receipt"]),
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to consume request: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ { id: result.id, status: result.status, path: result.relativePath },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`consumed: ${result.relativePath}\n`);
+ process.stdout.write(`status: ${result.status}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/digest.ts b/src/cli/pay-memory/verbs/digest.ts
new file mode 100644
index 00000000..64342374
--- /dev/null
+++ b/src/cli/pay-memory/verbs/digest.ts
@@ -0,0 +1,57 @@
+import { defaultConfigPath, resolveTimezone } from "../../../core/config.ts";
+import { buildPaymentDigest, renderPaymentDigestTelegram } from "../../../core/pay-memory/index.ts";
+import { requireVault } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdPaymentDigest(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ date: { type: "string" },
+ "empty-mode": { type: "string", default: "silent" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const tz = resolveTimezone(config);
+
+ const emptyMode = String(flags["empty-mode"]);
+ if (!["silent", "empty", "summary"].includes(emptyMode)) {
+ process.stderr.write(`error: --empty-mode must be silent|empty|summary\n`);
+ return 2;
+ }
+
+ let digest;
+ try {
+ digest = buildPaymentDigest(vault, {
+ date: (flags["date"] as string | undefined) ?? null,
+ tz,
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to build digest: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ date: digest.date,
+ services: digest.services,
+ receipts: digest.receipts,
+ total_amount: digest.totalAmount,
+ currency: digest.currency,
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ const text = renderPaymentDigestTelegram(digest, {
+ emptyMode: emptyMode as "silent" | "empty" | "summary",
+ });
+ if (text) process.stdout.write(text + "\n");
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/init.ts b/src/cli/pay-memory/verbs/init.ts
new file mode 100644
index 00000000..5ef4d603
--- /dev/null
+++ b/src/cli/pay-memory/verbs/init.ts
@@ -0,0 +1,77 @@
+/**
+ * `o2b init-pay-memory` β€” bootstrap pay-memory directory layout.
+ */
+
+import { existsSync, mkdirSync } from "node:fs";
+
+import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";
+import { payMemoryDirs, vaultRelativePath, writePolicyIfMissing } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdInitPayMemory(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ overwrite: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const agent =
+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+
+ const dirs = payMemoryDirs(vault);
+ const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];
+ const created: string[] = [];
+ const skipped: string[] = [];
+ for (const dir of dirList) {
+ const existed = existsSync(dir);
+ try {
+ mkdirSync(dir, { recursive: true });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to create ${dir}: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ (existed ? skipped : created).push(vaultRelativePath(dir, vault));
+ }
+
+ let policy;
+ try {
+ policy = writePolicyIfMissing(vault, { overwrite: Boolean(flags["overwrite"]) });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to write policy: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ const policyRel = vaultRelativePath(policy.path, vault);
+ const policyStatus = policy.status;
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ vault_path: vault,
+ agent,
+ created,
+ skipped,
+ policy_path: policyRel,
+ policy_status: policyStatus,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+
+ process.stdout.write(`pay-memory layout initialized: ${vault}\n`);
+ for (const rel of created) process.stdout.write(` created: ${rel}\n`);
+ for (const rel of skipped) process.stdout.write(` exists: ${rel}\n`);
+ process.stdout.write(` ${policyStatus}: ${policyRel}\n`);
+ process.stdout.write(`agent: ${agent}\n`);
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/list.ts b/src/cli/pay-memory/verbs/list.ts
new file mode 100644
index 00000000..347aa4bc
--- /dev/null
+++ b/src/cli/pay-memory/verbs/list.ts
@@ -0,0 +1,65 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { listPendingRequests } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdListPendingPayments(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ status: { type: "string", default: "pending" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const status = String(flags["status"]);
+ const valid = ["pending", "approved", "rejected", "consumed", "all"];
+ if (!valid.includes(status)) {
+ process.stderr.write(
+ `error: --status must be one of: ${valid.join(", ")}\n`,
+ );
+ return 2;
+ }
+
+ let summaries;
+ try {
+ summaries = listPendingRequests(vault, {
+ status: status as "pending" | "approved" | "rejected" | "consumed" | "all",
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to list requests: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ summaries.map((s) => ({
+ id: s.id,
+ path: s.relativePath,
+ status: s.status,
+ service: s.service,
+ reason: s.reason,
+ expected_amount: s.expectedAmount,
+ currency: s.currency,
+ created: s.created,
+ policy_status: s.policyStatus,
+ })),
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else if (summaries.length === 0) {
+ process.stdout.write(`no requests with status: ${status}\n`);
+ } else {
+ for (const s of summaries) {
+ const cost =
+ s.expectedAmount !== null && s.expectedAmount !== ""
+ ? ` (${s.expectedAmount}${s.currency ? " " + s.currency : ""})`
+ : "";
+ process.stdout.write(`${s.status}\t${s.id}\t${s.service}${cost}\t${s.reason}\n`);
+ }
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/reject.ts b/src/cli/pay-memory/verbs/reject.ts
new file mode 100644
index 00000000..c07d3b70
--- /dev/null
+++ b/src/cli/pay-memory/verbs/reject.ts
@@ -0,0 +1,42 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { rejectPendingRequest } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdRejectPaymentRequest(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ id: { type: "string", required: true },
+ "rejected-by": { type: "string", required: true },
+ reason: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try {
+ result = await rejectPendingRequest(vault, String(flags["id"]), {
+ rejectedBy: String(flags["rejected-by"]),
+ reason: (flags["reason"] as string | undefined) ?? null,
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to reject request: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ { id: result.id, status: result.status, path: result.relativePath },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`rejected: ${result.relativePath}\n`);
+ process.stdout.write(`status: ${result.status}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/report.ts b/src/cli/pay-memory/verbs/report.ts
new file mode 100644
index 00000000..daaf0a48
--- /dev/null
+++ b/src/cli/pay-memory/verbs/report.ts
@@ -0,0 +1,53 @@
+import { defaultConfigPath } from "../../../core/config.ts";
+import { writeReport } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdPaymentReport(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ date: { type: "string", required: true },
+ title: { type: "string" },
+ task: { type: "string" },
+ slug: { type: "string" },
+ overwrite: { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+
+ let result;
+ try {
+ result = writeReport(vault, {
+ date: String(flags["date"]),
+ title: (flags["title"] as string | undefined) ?? null,
+ task: (flags["task"] as string | undefined) ?? null,
+ slug: (flags["slug"] as string | undefined) ?? null,
+ overwrite: Boolean(flags["overwrite"]),
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to write report: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ path: result.relativePath,
+ absolute_path: result.path,
+ slug: result.slug,
+ receipts_used: result.receiptsUsed,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`report: ${result.relativePath}\n`);
+ process.stdout.write(`receipts: ${result.receiptsUsed}\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/pay-memory/verbs/request-approval.ts b/src/cli/pay-memory/verbs/request-approval.ts
new file mode 100644
index 00000000..ecb6003f
--- /dev/null
+++ b/src/cli/pay-memory/verbs/request-approval.ts
@@ -0,0 +1,86 @@
+import { defaultConfigPath, resolveAgentName, resolveTimezone } from "../../../core/config.ts";
+import { writePendingRequest } from "../../../core/pay-memory/index.ts";
+import { requireVault, sortedReplacer } from "../../helpers.ts";
+import { parseOptionalNumberFlag } from "../../coerce.ts";
+import { parseFlags } from "../../argparse.ts";
+
+export async function cmdRequestPaymentApproval(argv: string[]): Promise<number> {
+ const { flags } = parseFlags(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ service: { type: "string", required: true },
+ reason: { type: "string", required: true },
+ "expected-amount": { type: "string" },
+ currency: { type: "string" },
+ category: { type: "string" },
+ endpoint: { type: "string" },
+ "expected-output": { type: "string" },
+ "vault-files": { type: "string-array" },
+ slug: { type: "string" },
+ date: { type: "string" },
+ time: { type: "string" },
+ "enforce-policy": { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = requireVault(flags["vault"] as string | undefined, config);
+ const agent =
+ (flags["agent"] as string | undefined) ?? resolveAgentName(config);
+ const tz = resolveTimezone(config);
+
+ const { value: expectedAmount, error: expectedErr } = parseOptionalNumberFlag(
+ flags,
+ "expected-amount",
+ );
+ if (expectedErr) {
+ process.stderr.write(`error: ${expectedErr}\n`);
+ return 2;
+ }
+
+ let result;
+ try {
+ result = writePendingRequest(vault, {
+ agent,
+ service: String(flags["service"]),
+ reason: String(flags["reason"]),
+ expectedAmount,
+ currency: (flags["currency"] as string | undefined) ?? null,
+ category: (flags["category"] as string | undefined) ?? null,
+ endpoint: (flags["endpoint"] as string | undefined) ?? null,
+ expectedOutput: (flags["expected-output"] as string | undefined) ?? null,
+ vaultFiles: (flags["vault-files"] as string[] | undefined) ?? null,
+ slug: (flags["slug"] as string | undefined) ?? null,
+ date: (flags["date"] as string | undefined) ?? null,
+ time: (flags["time"] as string | undefined) ?? null,
+ tz,
+ enforcePolicy: Boolean(flags["enforce-policy"]),
+ });
+ } catch (exc) {
+ process.stderr.write(
+ `error: failed to create pending request: ${(exc as Error).message ?? exc}\n`,
+ );
+ return 1;
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ id: result.id,
+ path: result.relativePath,
+ status: result.status,
+ created: result.created,
+ policy_status: result.policyDecision.status,
+ policy_rule: result.policyDecision.rule,
+ },
+ sortedReplacer,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(`pending: ${result.relativePath}\n`);
+ process.stdout.write(`id: ${result.id}\n`);
+ process.stdout.write(`policy: ${result.policyDecision.status}\n`);
+ }
+ return 0;
+}
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index df777b8c..ac2a885d 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -37,7 +37,7 @@
*/
import { existsSync, readdirSync } from "node:fs";
-import { basename, join } from "node:path";
+import { join } from "node:path";
import { extractWikilinks, listVaultBasenames, parseFrontmatter } from "../vault.ts";
import { buildBacklinkIndex } from "./backlinks.ts";
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index b9dbfe86..058dccac 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -62,7 +62,6 @@ import {
brainDirs,
preferencePath,
processedSignalPath,
- retiredPath,
vaultRelative,
} from "./paths.ts";
import { isoDate, isoSecond } from "./time.ts";
diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.ts
index 0be16036..d34acd73 100644
--- a/src/core/brain/import-claude-memory.ts
+++ b/src/core/brain/import-claude-memory.ts
@@ -11,7 +11,6 @@ import { parseClaudeMemoryFile } from "./claude-memory-parser.ts";
import {
loadManifest,
saveManifest,
- type ClaudeMemoryManifest,
} from "./claude-memory-manifest.ts";
import { planAction, type PlannedFile } from "./claude-memory-plan.ts";
import { renderPreferenceFromMemory, slugifyMemoryName } from "./claude-memory-render.ts";
diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.ts
index e642d2a2..3829f668 100644
--- a/src/core/brain/inline-scan.ts
+++ b/src/core/brain/inline-scan.ts
@@ -38,7 +38,7 @@ import {
computeDedupHash,
type DedupIndexEntry,
} from "./dedup-hash.ts";
-import { discoverMarkersDetailed, type ParsedMarker } from "./inline.ts";
+import { discoverMarkersDetailed } from "./inline.ts";
import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.ts
index f831dda6..a6fff29d 100644
--- a/src/core/brain/log-jsonl.ts
+++ b/src/core/brain/log-jsonl.ts
@@ -34,6 +34,14 @@ export interface ReadLogDayResult {
// JSONL reader cannot leak a value that the markdown side would
// reject. Sub-second precision is allowed because `JSON.stringify`
// of a `Date` produces it; `parseIsoUtc` strips it back to seconds.
+//
+// Sibling regex: `ISO_8601_RE` in `src/cli/coerce.ts`. That one is
+// looser (accepts `Β±HH:MM` offset, caps millisecond precision at 3
+// digits) because it has to admit whatever a human typed on the
+// CLI; this one is strict because it only ever sees values the
+// writer side just produced in canonical UTC. The two intentionally
+// do not share a constant β€” drift in either direction would silently
+// break the contract of the other surface.
const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
/**
diff --git a/src/core/config.ts b/src/core/config.ts
index 50f65e33..852a978b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -7,11 +7,12 @@
* via parallel suites in tests/core/config.test.ts.
*/
-import { existsSync, readFileSync, statSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { atomicWriteFileSync } from "./fs-atomic.ts";
+import { isFile } from "./fs-utils.ts";
import type { ConfigDiscovery } from "./types.ts";
const SECRET_KEY_PARTS = ["key", "token", "secret", "password", "credential"] as const;
@@ -66,7 +67,7 @@ export function parseSimpleYaml(text: string): Record<string, string> {
/** Read and parse the config file, or report it as missing. */
export function discoverConfig(path?: string): ConfigDiscovery {
const resolved = path ?? defaultConfigPath();
- if (!isRegularFile(resolved)) {
+ if (!isFile(resolved)) {
return { path: resolved, exists: false, data: {} };
}
try {
@@ -175,12 +176,3 @@ function expandTilde(p: string): string {
if (p.startsWith("~/")) return join(homedir(), p.slice(2));
return p;
}
-
-function isRegularFile(p: string): boolean {
- if (!existsSync(p)) return false;
- try {
- return statSync(p).isFile();
- } catch {
- return false;
- }
-}
diff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.ts
index 50f29376..d5fbf724 100644
--- a/src/core/discipline/decision.ts
+++ b/src/core/discipline/decision.ts
@@ -1,6 +1,5 @@
import type { BrainEventCounts } from "./log-counts.ts";
import type { GitActivity } from "./activity-git.ts";
-import type { MtimeActivity } from "./activity-mtime.ts";
import type { VaultDelta } from "./vault-delta.ts";
export interface RepoActivityRow {
diff --git a/src/core/discipline/report.ts b/src/core/discipline/report.ts
index 726eaef4..6a7edc69 100644
--- a/src/core/discipline/report.ts
+++ b/src/core/discipline/report.ts
@@ -1,5 +1,4 @@
import { existsSync } from "node:fs";
-import { join } from "node:path";
import { BrainConfigError, loadBrainConfig } from "../brain/policy.ts";
import { countBrainEvents, type BrainEventCounts } from "./log-counts.ts";
diff --git a/src/core/doctor.ts b/src/core/doctor.ts
index 10bb1b2c..e5b2294f 100644
--- a/src/core/doctor.ts
+++ b/src/core/doctor.ts
@@ -12,12 +12,12 @@ import {
openSync,
readFileSync,
rmSync,
- statSync,
writeSync,
closeSync,
} from "node:fs";
import { dirname, join } from "node:path";
+import { isFile } from "./fs-utils.ts";
import type { CheckResult } from "./types.ts";
export function checkVaultWriteable(vault: string): CheckResult {
@@ -295,7 +295,6 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {
}
return results;
}
-
export interface DoctorOptions {
readonly vault: string;
readonly config?: string | null;
@@ -316,12 +315,3 @@ export function doctor(opts: DoctorOptions): CheckResult[] {
}
return results;
}
-
-function isFile(p: string): boolean {
- if (!existsSync(p)) return false;
- try {
- return statSync(p).isFile();
- } catch {
- return false;
- }
-}
diff --git a/src/core/fs-utils.ts b/src/core/fs-utils.ts
new file mode 100644
index 00000000..c5a86b90
--- /dev/null
+++ b/src/core/fs-utils.ts
@@ -0,0 +1,38 @@
+/**
+ * Shared filesystem utilities used across all core modules.
+ *
+ * Centralises the repeated `existsSync + statSync.isFile/isDirectory` and
+ * `stem` (basename without extension) patterns that were previously
+ * copy-pasted across 4+ files.
+ */
+
+import { existsSync, statSync } from "node:fs";
+
+/** True when `p` exists and is a regular file. Never throws. */
+export function isFile(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isFile();
+ } catch {
+ return false;
+ }
+}
+
+/** True when `p` exists and is a directory. Never throws. */
+export function isDir(p: string): boolean {
+ if (!existsSync(p)) return false;
+ try {
+ return statSync(p).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Extract the filename without its extension.
+ * `stem("notes.md")` β†’ `"notes"`, `stem(".gitignore")` β†’ `".gitignore"`.
+ */
+export function stem(filename: string): string {
+ const dot = filename.lastIndexOf(".");
+ return dot > 0 ? filename.slice(0, dot) : filename;
+}
diff --git a/src/core/search/index.ts b/src/core/search/index.ts
index 2b33a487..a0da82e8 100644
--- a/src/core/search/index.ts
+++ b/src/core/search/index.ts
@@ -4,6 +4,12 @@
*/
import { discoverConfig } from "../config.ts";
+import {
+ envOrConfig,
+ parseBool as parseBoolShared,
+ parseFloat01 as parseFloat01Shared,
+ parseInteger as parseIntegerShared,
+} from "../validate.ts";
import { resolveIndexPath } from "./paths.ts";
import { SearchError } from "./types.ts";
import type { ResolvedSearchConfig, ResolvedEmbeddingConfig } from "./types.ts";
@@ -57,59 +63,50 @@ const DEFAULTS = {
batchSize: 32,
};
-function envOrConfig(
- env: NodeJS.ProcessEnv,
- config: Readonly<Record<string, string>>,
- envKey: string,
- configKey: string,
-): string | null {
- const e = env[envKey];
- if (e !== undefined && e !== "") return e;
- const c = config[configKey];
- if (c !== undefined && c !== "") return c;
- return null;
-}
+type IntegerRange = { readonly min?: number; readonly max?: number };
function parseInteger(
raw: string | null,
fallback: number,
fieldName: string,
- opts?: { readonly min?: number; readonly max?: number },
+ range?: IntegerRange,
): number {
- if (raw === null) return fallback;
- const n = Number(raw);
- if (!Number.isFinite(n) || !Number.isInteger(n)) {
- throw new SearchError("INVALID_INPUT", `${fieldName} must be an integer, got '${raw}'`);
+ try {
+ return parseIntegerShared(raw, fallback, fieldName, range);
+ } catch (e) {
+ throw new SearchError("INVALID_INPUT", (e as Error).message);
+ }
+}
+
+function parseFloat01(raw: string | null, fallback: number, fieldName: string): number {
+ try {
+ return parseFloat01Shared(raw, fallback, fieldName);
+ } catch (e) {
+ throw new SearchError("INVALID_INPUT", (e as Error).message);
+ }
+}
+
+function parseBool(raw: string | null, fallback: boolean, fieldName: string): boolean {
+ try {
+ return parseBoolShared(raw, fallback, fieldName);
+ } catch (e) {
+ throw new SearchError("INVALID_INPUT", (e as Error).message);
}
- validateIntegerRange(n, fieldName, opts);
- return n;
}
function validateIntegerRange(
n: number,
fieldName: string,
- opts?: { readonly min?: number; readonly max?: number },
+ range?: IntegerRange,
): void {
- if (opts?.min !== undefined && n < opts.min) {
- throw new SearchError("INVALID_INPUT", `${fieldName} must be >= ${opts.min}, got ${n}`);
+ if (range?.min !== undefined && n < range.min) {
+ throw new SearchError("INVALID_INPUT", `${fieldName} must be >= ${range.min}, got ${n}`);
}
- if (opts?.max !== undefined && n > opts.max) {
- throw new SearchError("INVALID_INPUT", `${fieldName} must be <= ${opts.max}, got ${n}`);
+ if (range?.max !== undefined && n > range.max) {
+ throw new SearchError("INVALID_INPUT", `${fieldName} must be <= ${range.max}, got ${n}`);
}
}
-function parseFloat01(raw: string | null, fallback: number, fieldName: string): number {
- if (raw === null) return fallback;
- const n = Number(raw);
- if (!Number.isFinite(n) || n < 0 || n > 1) {
- throw new SearchError(
- "INVALID_INPUT",
- `${fieldName} must be a number in [0, 1], got '${raw}'`,
- );
- }
- return n;
-}
-
function validateWeight(n: number, fieldName: string): void {
if (!Number.isFinite(n) || n < 0 || n > 1) {
throw new SearchError("INVALID_INPUT", `${fieldName} must be a number in [0, 1], got '${n}'`);
@@ -141,16 +138,6 @@ function validateResolvedConfig(config: ResolvedSearchConfig): void {
validateIntegerRange(config.semantic.batchSize, "embedding_batch_size", { min: 1 });
}
-function parseBool(raw: string | null, fallback: boolean, fieldName: string): boolean {
- if (raw === null) return fallback;
- if (raw === "true" || raw === "1") return true;
- if (raw === "false" || raw === "0") return false;
- throw new SearchError(
- "INVALID_INPUT",
- `${fieldName} must be 'true' or 'false', got '${raw}'`,
- );
-}
-
function parseProvider(raw: string | null): ResolvedEmbeddingConfig["provider"] {
if (raw === null) return DEFAULTS.provider;
if (raw === "openai-compat" || raw === "disabled") return raw;
diff --git a/src/core/validate.ts b/src/core/validate.ts
new file mode 100644
index 00000000..3c31bc6b
--- /dev/null
+++ b/src/core/validate.ts
@@ -0,0 +1,84 @@
+/**
+ * Config-level input validators shared across the core library.
+ *
+ * Extracted from `src/core/search/index.ts` where they were private helpers
+ * for `resolveSearchConfig`. They parse string env/config values into typed
+ * scalars and validate numeric ranges β€” no I/O, no side effects.
+ *
+ * Error convention: every function throws `Error` with a message that
+ * includes the field name. Callers that need a typed error (e.g. SearchError
+ * in the search layer) wrap the message in their own error type.
+ */
+
+/**
+ * Parse a string into an integer, falling back to `default_` when `raw` is
+ * null. Throws `Error` on non-integer, non-finite, or out-of-range input.
+ */
+export function parseInteger(
+ raw: string | null,
+ default_: number,
+ fieldName: string,
+ range?: { readonly min?: number; readonly max?: number },
+): number {
+ if (raw === null) return default_;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || !Number.isInteger(n)) {
+ throw new Error(`${fieldName} must be an integer, got '${raw}'`);
+ }
+ if (range?.min !== undefined && n < range.min) {
+ throw new Error(`${fieldName} must be >= ${range.min}, got ${n}`);
+ }
+ if (range?.max !== undefined && n > range.max) {
+ throw new Error(`${fieldName} must be <= ${range.max}, got ${n}`);
+ }
+ return n;
+}
+
+/**
+ * Parse a string into a number in `[0, 1]`, falling back to `default_` when
+ * `raw` is null. Throws `Error` on out-of-range or non-finite input.
+ */
+export function parseFloat01(
+ raw: string | null,
+ default_: number,
+ fieldName: string,
+): number {
+ if (raw === null) return default_;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n < 0 || n > 1) {
+ throw new Error(`${fieldName} must be a number in [0, 1], got '${raw}'`);
+ }
+ return n;
+}
+
+/**
+ * Parse a string into a boolean. Accepts `"true"`/`"1"` β†’ `true`,
+ * `"false"`/`"0"` β†’ `false`. Throws `Error` on any other value.
+ */
+export function parseBool(
+ raw: string | null,
+ default_: boolean,
+ fieldName: string,
+): boolean {
+ if (raw === null) return default_;
+ if (raw === "true" || raw === "1") return true;
+ if (raw === "false" || raw === "0") return false;
+ throw new Error(`${fieldName} must be 'true' or 'false', got '${raw}'`);
+}
+
+/**
+ * Resolve a value from an environment variable or config map, preferring
+ * the environment. Returns `null` when neither source has a non-empty value.
+ */
+export function envOrConfig(
+ env: NodeJS.ProcessEnv,
+ config: Readonly<Record<string, string>>,
+ envKey: string,
+ configKey: string,
+): string | null {
+ const e = env[envKey];
+ if (e !== undefined && e !== "") return e;
+ const c = config[configKey];
+ if (c !== undefined && c !== "") return c;
+ return null;
+}
diff --git a/src/core/vault.ts b/src/core/vault.ts
index d8cf2ea0..a213c858 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -7,13 +7,14 @@
* through Obsidian and the simple parser.
*/
-import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { dirname, join, relative } from "node:path";
import {
atomicCreateFileSyncExclusive,
atomicWriteFileSync,
} from "./fs-atomic.ts";
+import { stem } from "./fs-utils.ts";
import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";
const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
@@ -317,11 +318,6 @@ function walk(
}
}
-function stem(filename: string): string {
- const dot = filename.lastIndexOf(".");
- return dot > 0 ? filename.slice(0, dot) : filename;
-}
-
function stripQuotes(s: string): string {
if (
s.length >= 2 &&
@@ -405,11 +401,4 @@ function formatYamlValue(value: FrontmatterValue): string {
export const EXCLUDED_DIRS = DEFAULT_SKIP_DIRS;
export const EXCLUDED_FILES = DEFAULT_SKIP_FILES;
-export function _internalIsDir(p: string): boolean {
- if (!existsSync(p)) return false;
- try {
- return statSync(p).isDirectory();
- } catch {
- return false;
- }
-}
+export { isDir } from "./fs-utils.ts";
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 5aa6972e..9df17de6 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -62,7 +62,6 @@ import { normalizeAgentArgument } from "../core/agent-identity.ts";
import {
BRAIN_LOG_EVENT_KIND,
BRAIN_PREFERENCE_STATUS,
- BRAIN_SIGNAL_SIGN,
BRAIN_APPLY_RESULT,
type BrainApplyResult,
type BrainPreference,
@@ -76,102 +75,7 @@ import { sanitiseTextField } from "../core/redactor.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tools.ts";
-
-// ----- Local coercion helpers ----------------------------------------------
-//
-// Mirrors `tools.ts:coerceStr` family. We keep a private copy so the Brain
-// tool module does not depend on the legacy `tools.ts` private API
-// surface β€” the only shared types it imports are `ServerContext` and
-// `ToolDefinition`.
-
-function coerceStr(
- args: Record<string, unknown>,
- key: string,
- required = true,
- defaultValue: string | null = null,
-): string | null {
- const value = args[key];
- if (
- value === undefined ||
- value === null ||
- (typeof value === "string" && value.trim() === "")
- ) {
- if (required) {
- throw new MCPError(INVALID_PARAMS, `missing required argument: ${key}`);
- }
- return defaultValue;
- }
- if (typeof value !== "string") {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
- }
- return value;
-}
-
-function coerceStrList(
- args: Record<string, unknown>,
- key: string,
-): string[] | null {
- const value = args[key];
- if (value === undefined || value === null) return null;
- if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
- throw new MCPError(
- INVALID_PARAMS,
- `argument '${key}' must be a list of strings`,
- );
- }
- return [...value] as string[];
-}
-
-function coerceBool(
- args: Record<string, unknown>,
- key: string,
-): boolean {
- const value = args[key];
- if (value === undefined || value === null) return false;
- if (typeof value !== "boolean") {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);
- }
- return value;
-}
-
-/**
- * Parse an optional ISO-8601 timestamp argument. Empty / missing β†’ null.
- * Anything else must be a parseable date string; otherwise INVALID_PARAMS.
- */
-function coerceIsoDate(
- args: Record<string, unknown>,
- key: string,
-): Date | null {
- const raw = coerceStr(args, key, false);
- if (raw === null) return null;
- const d = new Date(raw);
- if (Number.isNaN(d.getTime())) {
- throw new MCPError(
- INVALID_PARAMS,
- `argument '${key}' must be a valid ISO-8601 timestamp`,
- );
- }
- return d;
-}
-
-/**
- * Coerce the optional `format` argument shared across digest / query /
- * doctor. Accepts `markdown` (default) or `json`. Anything else throws.
- */
-function coerceFormat(
- args: Record<string, unknown>,
- key = "format",
-): "markdown" | "json" {
- const raw = coerceStr(args, key, false);
- if (raw === null) return "markdown";
- if (raw !== "markdown" && raw !== "json") {
- throw new MCPError(
- INVALID_PARAMS,
- `argument '${key}' must be 'markdown' or 'json'`,
- );
- }
- return raw;
-}
+import { coerceStr, coerceBool, coerceIsoDate, coerceFormat } from "./coerce.ts";
// ----- brain_feedback ------------------------------------------------------
diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.ts
new file mode 100644
index 00000000..612fd8a8
--- /dev/null
+++ b/src/mcp/coerce.ts
@@ -0,0 +1,115 @@
+/**
+ * Shared coercion helpers for MCP tool handlers.
+ *
+ * Used by tools.ts, brain-tools.ts, and search-tools.ts to validate
+ * and cast incoming JSON-RPC arguments. All helpers throw `MCPError`
+ * with `INVALID_PARAMS` on bad input.
+ */
+
+import { INVALID_PARAMS, MCPError } from "./protocol.ts";
+
+export function coerceStr(
+ args: Record<string, unknown>,
+ key: string,
+ required = true,
+ defaultValue: string | null = null,
+): string | null {
+ const value = args[key];
+ if (value === undefined || value === null || (typeof value === "string" && value.trim() === "")) {
+ if (required) throw new MCPError(INVALID_PARAMS, `missing required argument: ${key}`);
+ return defaultValue;
+ }
+ if (typeof value !== "string") throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
+ return value;
+}
+
+export function coerceStrList(args: Record<string, unknown>, key: string): string[] {
+ const value = args[key];
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a list of strings`);
+ }
+ return [...value] as string[];
+}
+
+export function coerceInt(
+ args: Record<string, unknown>,
+ key: string,
+ defaultValue: number,
+ min: number,
+ max: number,
+): number {
+ const value = args[key] ?? defaultValue;
+ if (typeof value === "boolean" || typeof value !== "number" || !Number.isInteger(value)) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be an integer`);
+ }
+ if (value < min || value > max) {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be between ${min} and ${max}`);
+ }
+ return value;
+}
+
+export function coerceOptionalNumber(
+ args: Record<string, unknown>,
+ key: string,
+): number | null {
+ const raw = args[key];
+ if (raw === undefined || raw === null) return null;
+ if (typeof raw === "number") {
+ if (!Number.isFinite(raw)) throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a finite number`);
+ return raw;
+ }
+ if (typeof raw === "string") {
+ const trimmed = raw.trim();
+ if (trimmed === "") return null;
+ const parsed = Number(trimmed);
+ if (!Number.isFinite(parsed)) throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);
+ return parsed;
+ }
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);
+}
+
+export function coerceBool(args: Record<string, unknown>, key: string): boolean {
+ const value = args[key];
+ if (value === undefined || value === null) return false;
+ if (typeof value !== "boolean") throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);
+ return value;
+}
+
+export function coerceBoolOptional(args: Record<string, unknown>, key: string): boolean | undefined {
+ if (!(key in args)) return undefined;
+ const v = args[key];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v !== "boolean") throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);
+ return v;
+}
+
+export function coerceStringOptional(
+ args: Record<string, unknown>,
+ key: string,
+ maxLen: number,
+): string | undefined {
+ if (!(key in args)) return undefined;
+ const v = args[key];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v !== "string") throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
+ if (v.length > maxLen) throw new MCPError(INVALID_PARAMS, `argument '${key}' exceeds ${maxLen} characters`);
+ return v;
+}
+
+export function coerceIsoDate(args: Record<string, unknown>, key: string): Date | null {
+ const raw = coerceStr(args, key, false);
+ if (raw === null) return null;
+ const d = new Date(raw);
+ if (Number.isNaN(d.getTime())) throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a valid ISO-8601 timestamp`);
+ return d;
+}
+
+export function coerceFormat(args: Record<string, unknown>, key = "format"): "markdown" | "json" {
+ const raw = coerceStr(args, key, false);
+ if (raw === null) return "markdown";
+ if (raw !== "markdown" && raw !== "json") {
+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be 'markdown' or 'json'`);
+ }
+ return raw;
+}
diff --git a/src/mcp/pay-memory-tools.ts b/src/mcp/pay-memory-tools.ts
new file mode 100644
index 00000000..f6da31fe
--- /dev/null
+++ b/src/mcp/pay-memory-tools.ts
@@ -0,0 +1,532 @@
+/**
+ * MCP tool registry slice for Pay Memory.
+ *
+ * Exposes the eight Pay Memory tools (`payment_*`, `asset_capture`)
+ * that record paid agent actions as inspectable Markdown inside the
+ * vault. None of these handlers run a real payment β€” they only
+ * persist memory (policy decisions, approval state, receipts, assets,
+ * reports). The actual payment rail (`pay.sh`) is invoked separately
+ * by the agent harness.
+ *
+ * Layout mirrors `./brain-tools.ts` and `./search-tools.ts`: each
+ * handler is a local async function; one frozen `PAY_MEMORY_TOOLS`
+ * array is consumed by `buildToolTable()` in `./tools.ts` via
+ * spread.
+ */
+
+import { existsSync, mkdirSync } from "node:fs";
+import { resolve } from "node:path";
+
+import { resolveAgentName, resolveTimezone } from "../core/config.ts";
+import { normalizeAgentArgument } from "../core/agent-identity.ts";
+import {
+ checkPolicy,
+ consumePendingRequest,
+ loadPendingRequest,
+ payMemoryDirs,
+ vaultRelativePath,
+ writeAsset,
+ writePendingRequest,
+ writePolicyIfMissing,
+ writeReceipt,
+ writeReport,
+} from "../core/pay-memory/index.ts";
+import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
+import { INVALID_PARAMS, MCPError } from "./protocol.ts";
+import type { ServerContext, ToolDefinition } from "./tools.ts";
+import { coerceOptionalNumber, coerceStr } from "./coerce.ts";
+
+async function toolPaymentMemoryInit(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const overwrite = Boolean(args["overwrite"] ?? false);
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+
+ const dirs = payMemoryDirs(ctx.vault);
+ const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];
+ const created: string[] = [];
+ const skipped: string[] = [];
+ for (const dir of dirList) {
+ const existed = existsSync(dir);
+ mkdirSync(dir, { recursive: true });
+ (existed ? skipped : created).push(vaultRelativePath(dir, ctx.vault));
+ }
+ const policy = writePolicyIfMissing(ctx.vault, { overwrite });
+ return {
+ vault_path: ctx.vault,
+ agent,
+ created,
+ skipped,
+ policy_path: vaultRelativePath(policy.path, ctx.vault),
+ policy_status: policy.status,
+ };
+}
+
+async function toolPaymentReceiptAppend(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+
+ let policyStatus = coerceStr(args, "policy_status", false) as
+ | ReceiptPolicyStatus
+ | null;
+ let policyRule = coerceStr(args, "policy_rule", false);
+ const policyReasonsRaw = args["policy_reasons"];
+ let policyReasons: string[] | null = null;
+ if (policyReasonsRaw !== undefined && policyReasonsRaw !== null) {
+ if (
+ !Array.isArray(policyReasonsRaw) ||
+ !policyReasonsRaw.every((s) => typeof s === "string")
+ ) {
+ throw new MCPError(INVALID_PARAMS, "policy_reasons must be an array of strings");
+ }
+ policyReasons = [...policyReasonsRaw] as string[];
+ }
+ let policyCheckedAt = coerceStr(args, "policy_checked_at", false);
+ let approvalStatus: "pending" | "approved" | "rejected" | "consumed" | null = null;
+ let approvedBy: string | null = null;
+ let approvedAt: string | null = null;
+ const fromRequest = coerceStr(args, "from_request", false);
+ if (fromRequest) {
+ const loaded = loadPendingRequest(ctx.vault, fromRequest);
+ if (!loaded) {
+ throw new Error(`pending request not found: ${fromRequest}`);
+ }
+ const meta = loaded.metadata;
+ const get = (k: string): string | null => {
+ const v = meta[k];
+ if (v === undefined || v === null) return null;
+ return Array.isArray(v) ? v.join(", ") : String(v);
+ };
+ policyStatus ??= (get("policy_status") as ReceiptPolicyStatus | null) ?? null;
+ policyRule ??= get("policy_rule");
+ approvalStatus = loaded.status;
+ approvedBy = get("approved_by");
+ approvedAt = get("approved_at");
+ }
+ if (policyStatus !== null) {
+ const allowed: ReadonlyArray<ReceiptPolicyStatus> = [
+ "allowed",
+ "approval_required",
+ "denied",
+ "not_checked",
+ ];
+ if (!allowed.includes(policyStatus)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `policy_status must be one of: ${allowed.join(", ")}`,
+ );
+ }
+ }
+
+ const result = writeReceipt(ctx.vault, {
+ agent,
+ service: coerceStr(args, "service", true)!,
+ status: coerceStr(args, "status", true)!,
+ reason: coerceStr(args, "reason", true)!,
+ paymentLayer: coerceStr(args, "payment_layer", false),
+ network: coerceStr(args, "network", false),
+ category: coerceStr(args, "category", false),
+ endpoint: coerceStr(args, "endpoint", false),
+ expectedCost: coerceStr(args, "expected_cost", false),
+ actualAmount: coerceStr(args, "actual_amount", false),
+ currency: coerceStr(args, "currency", false),
+ paymentProof: coerceStr(args, "payment_proof", false),
+ resultRef: coerceStr(args, "result_ref", false),
+ resultNote: coerceStr(args, "result_note", false),
+ rawOutput: coerceStr(args, "raw_output", false),
+ slug: coerceStr(args, "slug", false),
+ date: coerceStr(args, "date", false),
+ time: coerceStr(args, "time", false),
+ overwrite: Boolean(args["overwrite"] ?? false),
+ tz,
+ policyStatus,
+ policyRule,
+ policyReasons,
+ policyCheckedAt,
+ approvalRequestId: fromRequest,
+ approvalStatus,
+ approvedBy,
+ approvedAt,
+ });
+ return {
+ path: result.relativePath,
+ absolute_path: resolve(result.path),
+ slug: result.slug,
+ date: result.date,
+ created: result.created,
+ };
+}
+
+async function toolAssetCapture(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const result = writeAsset(ctx.vault, {
+ title: coerceStr(args, "title", true)!,
+ service: coerceStr(args, "service", true)!,
+ resultUrl: coerceStr(args, "result_url", true)!,
+ sourceReceipt: coerceStr(args, "source_receipt", false),
+ prompt: coerceStr(args, "prompt", false),
+ usedIn: coerceStr(args, "used_in", false),
+ slug: coerceStr(args, "slug", false),
+ overwrite: Boolean(args["overwrite"] ?? false),
+ });
+ return {
+ path: result.relativePath,
+ absolute_path: resolve(result.path),
+ slug: result.slug,
+ created: result.created,
+ };
+}
+
+async function toolPaymentRequestApproval(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const agentArg = coerceStr(args, "agent", false);
+ const agent =
+ normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+
+ const expectedAmount = coerceOptionalNumber(args, "expected_amount");
+
+ const vaultFiles = args["vault_files"];
+ let vaultFilesList: string[] | null = null;
+ if (vaultFiles !== undefined && vaultFiles !== null) {
+ if (!Array.isArray(vaultFiles) || !vaultFiles.every((s) => typeof s === "string")) {
+ throw new MCPError(INVALID_PARAMS, "vault_files must be an array of strings");
+ }
+ vaultFilesList = [...vaultFiles] as string[];
+ }
+
+ const result = writePendingRequest(ctx.vault, {
+ agent,
+ service: coerceStr(args, "service", true)!,
+ reason: coerceStr(args, "reason", true)!,
+ expectedAmount,
+ currency: coerceStr(args, "currency", false),
+ category: coerceStr(args, "category", false),
+ endpoint: coerceStr(args, "endpoint", false),
+ expectedOutput: coerceStr(args, "expected_output", false),
+ vaultFiles: vaultFilesList,
+ slug: coerceStr(args, "slug", false),
+ date: coerceStr(args, "date", false),
+ time: coerceStr(args, "time", false),
+ enforcePolicy: Boolean(args["enforce_policy"] ?? false),
+ tz,
+ });
+ return {
+ id: result.id,
+ path: result.relativePath,
+ absolute_path: resolve(result.path),
+ status: result.status,
+ created: result.created,
+ policy_status: result.policyDecision.status,
+ policy_rule: result.policyDecision.rule,
+ };
+}
+
+async function toolPaymentRequestStatus(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const id = coerceStr(args, "id", true)!;
+ const loaded = loadPendingRequest(ctx.vault, id);
+ if (!loaded) {
+ throw new Error(`pending request not found: ${id}`);
+ }
+ const meta = loaded.metadata;
+ const get = (k: string): string | null => {
+ const v = meta[k];
+ if (v === undefined || v === null) return null;
+ return Array.isArray(v) ? v.join(", ") : String(v);
+ };
+ return {
+ id,
+ path: loaded.relativePath,
+ status: loaded.status,
+ service: get("service"),
+ reason: get("reason"),
+ expected_amount: get("expected_amount"),
+ currency: get("currency"),
+ created: get("created"),
+ approved_by: get("approved_by"),
+ approved_at: get("approved_at"),
+ rejected_by: get("rejected_by"),
+ rejected_at: get("rejected_at"),
+ rejection_reason: get("rejection_reason"),
+ receipt: get("receipt"),
+ policy_status: get("policy_status"),
+ policy_rule: get("policy_rule"),
+ };
+}
+
+async function toolPaymentRequestConsume(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const id = coerceStr(args, "id", true)!;
+ const receiptPath = coerceStr(args, "receipt", true)!;
+ const result = await consumePendingRequest(ctx.vault, id, { receiptPath });
+ return {
+ id: result.id,
+ path: result.relativePath,
+ status: result.status,
+ };
+}
+
+async function toolPaymentPolicyCheck(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const expectedAmount = coerceOptionalNumber(args, "expected_amount");
+ const tz = resolveTimezone(ctx.configPath ?? undefined);
+ const decision = checkPolicy(ctx.vault, {
+ service: coerceStr(args, "service", true)!,
+ expectedAmount,
+ currency: coerceStr(args, "currency", false),
+ category: coerceStr(args, "category", false),
+ date: coerceStr(args, "date", false),
+ tz,
+ });
+ return {
+ status: decision.status,
+ allowed: decision.allowed,
+ approval_required: decision.approvalRequired,
+ rule: decision.rule,
+ reasons: decision.reasons,
+ has_policy: decision.hasPolicy,
+ policy_path:
+ decision.policyPath !== null
+ ? vaultRelativePath(decision.policyPath, ctx.vault)
+ : null,
+ currency: decision.currency,
+ };
+}
+
+async function toolPaymentReportGenerate(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const result = writeReport(ctx.vault, {
+ date: coerceStr(args, "date", true)!,
+ title: coerceStr(args, "title", false),
+ task: coerceStr(args, "task", false),
+ slug: coerceStr(args, "slug", false),
+ overwrite: Boolean(args["overwrite"] ?? false),
+ });
+ return {
+ path: result.relativePath,
+ absolute_path: resolve(result.path),
+ slug: result.slug,
+ receipts_used: result.receiptsUsed,
+ };
+}
+
+export const PAY_MEMORY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "payment_memory_init",
+ description:
+ "Bootstrap the Pay Memory layout (policies/, payments/, assets/, drafts/, reports/) and write the spending policy template.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },
+ overwrite: {
+ type: "boolean",
+ description: "Overwrite an existing policy file. Directories are always idempotent.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolPaymentMemoryInit,
+ },
+ {
+ name: "payment_receipt_append",
+ description:
+ "Save a Markdown receipt for one paid API call. raw_output is run through a redactor before persisting.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },
+ service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },
+ status: { type: "string", description: "Outcome of the paid call ('success', 'failed', ...)." },
+ reason: { type: "string", description: "Why the paid call was made β€” short imperative sentence." },
+ category: { type: "string", description: "Optional category tag." },
+ endpoint: { type: "string", description: "Gateway endpoint URL returned by pay-skills." },
+ expected_cost: { type: "string", description: "Pre-call expected price range." },
+ actual_amount: { type: "string", description: "Actual amount charged (parsed from pay-tool output)." },
+ currency: { type: "string", description: "Currency code (e.g. 'USDC')." },
+ payment_proof: { type: "string", description: "Public proof / signature / receipt id." },
+ result_ref: { type: "string", description: "Generated asset URL or response id." },
+ result_note: { type: "string", description: "Vault path to the asset note (wikilink target)." },
+ raw_output: { type: "string", description: "Raw payment-tool output to persist after redaction." },
+ slug: { type: "string", description: "Optional slug override; default derives from service+reason." },
+ date: { type: "string", description: "Receipt date in YYYY-MM-DD; default = today (vault tz)." },
+ time: { type: "string", description: "Receipt time in HH:MM 24h; default = now (vault tz)." },
+ overwrite: { type: "boolean", description: "Allow overwriting an existing receipt." },
+ policy_status: {
+ type: "string",
+ enum: ["allowed", "approval_required", "denied", "not_checked"],
+ description:
+ "Real outcome of the spending-policy check. Defaults to `not_checked` when omitted β€” the receipt body will explicitly say so rather than claiming the policy approved the call.",
+ },
+ policy_rule: {
+ type: "string",
+ description: "Policy rule name that fired (e.g. `max_single_call`).",
+ },
+ policy_reasons: {
+ type: "array",
+ items: { type: "string" },
+ description: "Human-readable reasons returned by the policy check.",
+ },
+ policy_checked_at: {
+ type: "string",
+ description: "ISO-Z timestamp at which the policy was evaluated.",
+ },
+ from_request: {
+ type: "string",
+ description:
+ "Pending-payment-request id. When supplied, the receipt inherits policy / approval audit fields from that request β€” the agent doesn't have to re-state them.",
+ },
+ payment_layer: {
+ type: "string",
+ description: "Payment rail (default `pay.sh`). Override only when a different rail was used.",
+ },
+ network: {
+ type: "string",
+ description: "Settlement network (default `solana`). Override only when a different network was used.",
+ },
+ },
+ required: ["service", "status", "reason"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentReceiptAppend,
+ },
+ {
+ name: "asset_capture",
+ description:
+ "Save a Markdown note for an asset produced by a paid API call. Frontmatter links back to the receipt.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Human-readable asset title." },
+ service: { type: "string", description: "Provider/skill identifier that produced the asset." },
+ result_url: { type: "string", description: "URL or identifier of the generated asset." },
+ source_receipt: { type: "string", description: "Vault path to the receipt note." },
+ prompt: { type: "string", description: "Prompt sent to the service (rendered as a quote block)." },
+ used_in: { type: "string", description: "Vault path of the draft/page that consumes this asset." },
+ slug: { type: "string", description: "Optional slug override; default derives from title." },
+ overwrite: { type: "boolean", description: "Allow overwriting an existing asset note." },
+ },
+ required: ["title", "service", "result_url"],
+ additionalProperties: false,
+ },
+ handler: toolAssetCapture,
+ },
+ {
+ name: "payment_request_approval",
+ description:
+ "Create a pending-payment-request that the user must approve before the agent runs `pay`. Records the policy check at request time.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ agent: { type: "string" },
+ service: { type: "string" },
+ reason: { type: "string" },
+ expected_amount: { type: ["number", "string"] },
+ currency: { type: "string" },
+ category: { type: "string" },
+ endpoint: { type: "string" },
+ expected_output: { type: "string" },
+ vault_files: { type: "array", items: { type: "string" } },
+ slug: { type: "string" },
+ date: { type: "string" },
+ time: { type: "string" },
+ enforce_policy: {
+ type: "boolean",
+ description: "If true, refuse to create the request when the policy denies it.",
+ },
+ },
+ required: ["service", "reason"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentRequestApproval,
+ },
+ {
+ name: "payment_request_status",
+ description:
+ "Look up a pending-payment-request by id and return its current status and metadata. The agent uses this to poll for human approval.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "The request id (slug)." },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentRequestStatus,
+ },
+ {
+ name: "payment_request_consume",
+ description:
+ "Mark an `approved` request as `consumed` and link the resulting receipt path. Called by the agent after the paid call succeeded.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string" },
+ receipt: { type: "string", description: "Vault-relative path to the receipt note." },
+ },
+ required: ["id", "receipt"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentRequestConsume,
+ },
+ {
+ name: "payment_policy_check",
+ description:
+ "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },
+ expected_amount: {
+ type: ["number", "string"],
+ description: "Expected payment amount; numeric or numeric-string.",
+ },
+ currency: { type: "string", description: "Currency code; defaults to the policy currency." },
+ category: { type: "string", description: "Optional category for per-category caps." },
+ date: { type: "string", description: "Date in YYYY-MM-DD; default = today (vault tz)." },
+ },
+ required: ["service"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentPolicyCheck,
+ },
+ {
+ name: "payment_report_generate",
+ description:
+ "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ date: { type: "string", description: "Date in YYYY-MM-DD whose receipts will be aggregated." },
+ title: { type: "string", description: "Report title; default 'Payment Report <date>'." },
+ task: { type: "string", description: "Optional task description rendered in the body." },
+ slug: { type: "string", description: "Optional slug override." },
+ overwrite: { type: "boolean", description: "Allow overwriting an existing report." },
+ },
+ required: ["date"],
+ additionalProperties: false,
+ },
+ handler: toolPaymentReportGenerate,
+ },
+]);
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 3040336b..ad0a8033 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -23,6 +23,7 @@ import type {
import { withTimeout } from "../core/search/with-timeout.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tools.ts";
+import { coerceBoolOptional, coerceStringOptional } from "./coerce.ts";
const MCP_LIMIT_MAX = 50;
const MCP_CONTENT_MAX = 600;
@@ -41,33 +42,6 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
additionalProperties: false,
};
-function coerceBool(args: Record<string, unknown>, key: string): boolean | undefined {
- if (!(key in args)) return undefined;
- const v = args[key];
- if (v === undefined || v === null) return undefined;
- if (typeof v !== "boolean") {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);
- }
- return v;
-}
-
-function coerceStringOptional(
- args: Record<string, unknown>,
- key: string,
- maxLen: number,
-): string | undefined {
- if (!(key in args)) return undefined;
- const v = args[key];
- if (v === undefined || v === null) return undefined;
- if (typeof v !== "string") {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
- }
- if (v.length > maxLen) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' exceeds ${maxLen} characters`);
- }
- return v;
-}
-
function searchTimeoutError(ms: number): MCPError {
return new MCPError(INTERNAL_ERROR, `search timeout after ${ms}ms`);
}
@@ -124,8 +98,8 @@ async function toolBrainSearch(
limit = raw;
}
- const semantic = coerceBool(args, "semantic");
- const keywordOnly = coerceBool(args, "keyword_only") ?? false;
+ const semantic = coerceBoolOptional(args, "semantic");
+ const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;
const pathPrefix = coerceStringOptional(args, "path_prefix", 256);
const config = resolveSearchConfig({
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 0d4ccc32..2af12bb7 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -1,56 +1,48 @@
/**
- * MCP tool registry. As of v0.10.8 the advertised surface is:
+ * MCP tool registry. As of v0.10.8 the advertised surface is composed
+ * from four sibling slices:
*
- * - Core read/health tools (`second_brain_status`, `second_brain_query`,
- * `vault_health`).
+ * - Core read/health tools (`second_brain_status`,
+ * `second_brain_query`, `vault_health`) β€” defined inline in this
+ * file because they only need `ServerContext` and the shared
+ * coercion helpers.
* - Brain tools (`brain_feedback`, `brain_apply_evidence`,
* `brain_note`, `brain_dream`, `brain_digest`, `brain_query`,
- * `brain_doctor`, `brain_backlinks`) β€” see `./brain-tools.ts`.
- * - Pay Memory tools (`payment_*`, `asset_capture`).
+ * `brain_doctor`, `brain_backlinks`) β€” `./brain-tools.ts`
+ * (`BRAIN_TOOLS`).
+ * - Brain Search (`brain_search`) β€” `./search-tools.ts`
+ * (`SEARCH_TOOLS`).
+ * - Pay Memory tools (`payment_*`, `asset_capture`) β€”
+ * `./pay-memory-tools.ts` (`PAY_MEMORY_TOOLS`).
+ *
+ * Each slice owns its own handlers and tool definitions; this file
+ * only assembles them in a stable order and applies scope filtering.
*
* Β§32 (v0.10.8) retires `event_log_append` and `second_brain_capture`
* from every runtime. The `appendEvent` function in
* `src/core/event-log.ts` stays for the human-side CLI verb
* (`o2b append-event`) and cron-jobs; the MCP surface no longer
- * advertises it. `toolCapture` likewise remains as a CLI helper.
+ * advertises either tool.
*/
-import { existsSync, mkdirSync, statSync } from "node:fs";
-import { join, relative, resolve } from "node:path";
-
import {
discoverConfig,
redactMapping,
- resolveAgentName,
- resolveTimezone,
} from "../core/config.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
+import { isDir } from "../core/fs-utils.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
-import {
- checkPolicy,
- consumePendingRequest,
- loadPendingRequest,
- payMemoryDirs,
- vaultRelativePath,
- writeAsset,
- writePendingRequest,
- writePolicyIfMissing,
- writeReceipt,
- writeReport,
-} from "../core/pay-memory/index.ts";
-import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
+import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";
import {
normalizeAgentArgument,
PLACEHOLDER_AGENT_VALUES,
} from "../core/agent-identity.ts";
-import {
- ensureInsideVault,
- vaultRelative,
-} from "../core/path-safety.ts";
-import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";
+import { vaultRelative } from "../core/path-safety.ts";
+import { listVaultPages } from "../core/vault.ts";
import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
+import { coerceStr, coerceInt } from "./coerce.ts";
export interface ServerContext {
readonly vault: string;
@@ -85,81 +77,6 @@ function vaultRelpath(target: string, vault: string): string {
}
}
-function coerceStr(args: Record<string, unknown>, key: string, required = true, defaultValue: string | null = null): string | null {
- const value = args[key];
- if (value === undefined || value === null || (typeof value === "string" && value.trim() === "")) {
- if (required) {
- throw new MCPError(INVALID_PARAMS, `missing required argument: ${key}`);
- }
- return defaultValue;
- }
- if (typeof value !== "string") {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a string`);
- }
- return value;
-}
-
-function coerceStrList(args: Record<string, unknown>, key: string): string[] {
- const value = args[key];
- if (value === undefined || value === null) return [];
- if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a list of strings`);
- }
- return [...value] as string[];
-}
-
-function coerceInt(
- args: Record<string, unknown>,
- key: string,
- defaultValue: number,
- min: number,
- max: number,
-): number {
- const value = args[key] ?? defaultValue;
- if (typeof value === "boolean" || typeof value !== "number" || !Number.isInteger(value)) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be an integer`);
- }
- if (value < min || value > max) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be between ${min} and ${max}`);
- }
- return value;
-}
-
-/**
- * Coerce an optional MCP argument that should be a finite number. Accepts
- * a real number, a numeric string (`"0.05"`), or an absent value
- * (`undefined`/`null`/empty string/whitespace-only string β†’ `null`).
- * Anything else throws INVALID_PARAMS.
- *
- * Crucially, `Number(" ")` evaluates to `0` in JS β€” without this helper a
- * whitespace-only field would silently change a policy decision. We trim
- * first and treat trimmed-empty as "not provided".
- */
-function coerceOptionalNumber(
- args: Record<string, unknown>,
- key: string,
-): number | null {
- const raw = args[key];
- if (raw === undefined || raw === null) return null;
- if (typeof raw === "number") {
- if (!Number.isFinite(raw)) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a finite number`);
- }
- return raw;
- }
- if (typeof raw === "string") {
- const trimmed = raw.trim();
- if (trimmed === "") return null;
- const parsed = Number(trimmed);
- if (!Number.isFinite(parsed)) {
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);
- }
- return parsed;
- }
- throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a number or numeric string`);
-}
-
-
// ── Tool implementations ────────────────────────────────────────────────────
async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {
@@ -212,45 +129,6 @@ async function toolQuery(ctx: ServerContext, args: Record<string, unknown>): Pro
};
}
-async function toolCapture(ctx: ServerContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
- if (!isDir(ctx.vault)) {
- throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);
- }
- const title = coerceStr(args, "title", true)!;
- const content = coerceStr(args, "content", true)!;
- const tags = coerceStrList(args, "tags");
- const overwrite = Boolean(args["overwrite"] ?? false);
-
- if (!title.trim()) throw new MCPError(INVALID_PARAMS, "title must not be empty");
- if (!content.trim()) throw new MCPError(INVALID_PARAMS, "content must not be empty");
-
- const notesDir = join(ctx.vault, "AI Wiki", "notes");
- mkdirSync(notesDir, { recursive: true });
- const slug = slugify(title);
- const target = join(notesDir, `${slug}.md`);
- ensureInsideVault(target, ctx.vault);
-
- const existed = existsSync(target);
- if (existed && !overwrite) {
- throw new Error(`note already exists: ${vaultRelpath(target, ctx.vault)}`);
- }
-
- const metadata: Record<string, string | number | boolean | string[]> = {
- title,
- type: "note",
- created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
- };
- if (tags.length > 0) metadata["tags"] = tags;
- writeFrontmatter(target, metadata, content.trim());
-
- return {
- path: vaultRelpath(target, ctx.vault),
- absolute_path: resolve(target),
- slug,
- overwritten: existed && overwrite,
- };
-}
-
// Β§32G (v0.10.8): the `event_log_append` MCP handler is gone. The
// bare `appendEvent` function in `src/core/event-log.ts` stays for
// the CLI verb (`o2b append-event`) and cron-jobs that target the
@@ -277,311 +155,6 @@ async function toolVaultHealth(
};
}
-// ── Pay Memory tools ────────────────────────────────────────────────────────
-
-async function toolPaymentMemoryInit(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const overwrite = Boolean(args["overwrite"] ?? false);
- const agentArg = coerceStr(args, "agent", false);
- const agent =
- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
-
- const dirs = payMemoryDirs(ctx.vault);
- const dirList = [dirs.policies, dirs.payments, dirs.assets, dirs.drafts, dirs.reports];
- const created: string[] = [];
- const skipped: string[] = [];
- for (const dir of dirList) {
- const existed = existsSync(dir);
- mkdirSync(dir, { recursive: true });
- (existed ? skipped : created).push(vaultRelativePath(dir, ctx.vault));
- }
- const policy = writePolicyIfMissing(ctx.vault, { overwrite });
- return {
- vault_path: ctx.vault,
- agent,
- created,
- skipped,
- policy_path: vaultRelativePath(policy.path, ctx.vault),
- policy_status: policy.status,
- };
-}
-
-async function toolPaymentReceiptAppend(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const agentArg = coerceStr(args, "agent", false);
- const agent =
- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
- const tz = resolveTimezone(ctx.configPath ?? undefined);
-
- let policyStatus = coerceStr(args, "policy_status", false) as
- | ReceiptPolicyStatus
- | null;
- let policyRule = coerceStr(args, "policy_rule", false);
- const policyReasonsRaw = args["policy_reasons"];
- let policyReasons: string[] | null = null;
- if (policyReasonsRaw !== undefined && policyReasonsRaw !== null) {
- if (
- !Array.isArray(policyReasonsRaw) ||
- !policyReasonsRaw.every((s) => typeof s === "string")
- ) {
- throw new MCPError(INVALID_PARAMS, "policy_reasons must be an array of strings");
- }
- policyReasons = [...policyReasonsRaw] as string[];
- }
- let policyCheckedAt = coerceStr(args, "policy_checked_at", false);
- let approvalStatus: "pending" | "approved" | "rejected" | "consumed" | null = null;
- let approvedBy: string | null = null;
- let approvedAt: string | null = null;
- const fromRequest = coerceStr(args, "from_request", false);
- if (fromRequest) {
- const loaded = loadPendingRequest(ctx.vault, fromRequest);
- if (!loaded) {
- throw new Error(`pending request not found: ${fromRequest}`);
- }
- const meta = loaded.metadata;
- const get = (k: string): string | null => {
- const v = meta[k];
- if (v === undefined || v === null) return null;
- return Array.isArray(v) ? v.join(", ") : String(v);
- };
- policyStatus ??= (get("policy_status") as ReceiptPolicyStatus | null) ?? null;
- policyRule ??= get("policy_rule");
- approvalStatus = loaded.status;
- approvedBy = get("approved_by");
- approvedAt = get("approved_at");
- }
- if (policyStatus !== null) {
- const allowed: ReadonlyArray<ReceiptPolicyStatus> = [
- "allowed",
- "approval_required",
- "denied",
- "not_checked",
- ];
- if (!allowed.includes(policyStatus)) {
- throw new MCPError(
- INVALID_PARAMS,
- `policy_status must be one of: ${allowed.join(", ")}`,
- );
- }
- }
-
- const result = writeReceipt(ctx.vault, {
- agent,
- service: coerceStr(args, "service", true)!,
- status: coerceStr(args, "status", true)!,
- reason: coerceStr(args, "reason", true)!,
- paymentLayer: coerceStr(args, "payment_layer", false),
- network: coerceStr(args, "network", false),
- category: coerceStr(args, "category", false),
- endpoint: coerceStr(args, "endpoint", false),
- expectedCost: coerceStr(args, "expected_cost", false),
- actualAmount: coerceStr(args, "actual_amount", false),
- currency: coerceStr(args, "currency", false),
- paymentProof: coerceStr(args, "payment_proof", false),
- resultRef: coerceStr(args, "result_ref", false),
- resultNote: coerceStr(args, "result_note", false),
- rawOutput: coerceStr(args, "raw_output", false),
- slug: coerceStr(args, "slug", false),
- date: coerceStr(args, "date", false),
- time: coerceStr(args, "time", false),
- overwrite: Boolean(args["overwrite"] ?? false),
- tz,
- policyStatus,
- policyRule,
- policyReasons,
- policyCheckedAt,
- approvalRequestId: fromRequest,
- approvalStatus,
- approvedBy,
- approvedAt,
- });
- return {
- path: result.relativePath,
- absolute_path: resolve(result.path),
- slug: result.slug,
- date: result.date,
- created: result.created,
- };
-}
-
-async function toolAssetCapture(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const result = writeAsset(ctx.vault, {
- title: coerceStr(args, "title", true)!,
- service: coerceStr(args, "service", true)!,
- resultUrl: coerceStr(args, "result_url", true)!,
- sourceReceipt: coerceStr(args, "source_receipt", false),
- prompt: coerceStr(args, "prompt", false),
- usedIn: coerceStr(args, "used_in", false),
- slug: coerceStr(args, "slug", false),
- overwrite: Boolean(args["overwrite"] ?? false),
- });
- return {
- path: result.relativePath,
- absolute_path: resolve(result.path),
- slug: result.slug,
- created: result.created,
- };
-}
-
-async function toolPaymentRequestApproval(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const agentArg = coerceStr(args, "agent", false);
- const agent =
- normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);
- const tz = resolveTimezone(ctx.configPath ?? undefined);
-
- const expectedAmount = coerceOptionalNumber(args, "expected_amount");
-
- const vaultFiles = args["vault_files"];
- let vaultFilesList: string[] | null = null;
- if (vaultFiles !== undefined && vaultFiles !== null) {
- if (!Array.isArray(vaultFiles) || !vaultFiles.every((s) => typeof s === "string")) {
- throw new MCPError(INVALID_PARAMS, "vault_files must be an array of strings");
- }
- vaultFilesList = [...vaultFiles] as string[];
- }
-
- const result = writePendingRequest(ctx.vault, {
- agent,
- service: coerceStr(args, "service", true)!,
- reason: coerceStr(args, "reason", true)!,
- expectedAmount,
- currency: coerceStr(args, "currency", false),
- category: coerceStr(args, "category", false),
- endpoint: coerceStr(args, "endpoint", false),
- expectedOutput: coerceStr(args, "expected_output", false),
- vaultFiles: vaultFilesList,
- slug: coerceStr(args, "slug", false),
- date: coerceStr(args, "date", false),
- time: coerceStr(args, "time", false),
- enforcePolicy: Boolean(args["enforce_policy"] ?? false),
- tz,
- });
- return {
- id: result.id,
- path: result.relativePath,
- absolute_path: resolve(result.path),
- status: result.status,
- created: result.created,
- policy_status: result.policyDecision.status,
- policy_rule: result.policyDecision.rule,
- };
-}
-
-async function toolPaymentRequestStatus(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const id = coerceStr(args, "id", true)!;
- const loaded = loadPendingRequest(ctx.vault, id);
- if (!loaded) {
- throw new Error(`pending request not found: ${id}`);
- }
- const meta = loaded.metadata;
- const get = (k: string): string | null => {
- const v = meta[k];
- if (v === undefined || v === null) return null;
- return Array.isArray(v) ? v.join(", ") : String(v);
- };
- return {
- id,
- path: loaded.relativePath,
- status: loaded.status,
- service: get("service"),
- reason: get("reason"),
- expected_amount: get("expected_amount"),
- currency: get("currency"),
- created: get("created"),
- approved_by: get("approved_by"),
- approved_at: get("approved_at"),
- rejected_by: get("rejected_by"),
- rejected_at: get("rejected_at"),
- rejection_reason: get("rejection_reason"),
- receipt: get("receipt"),
- policy_status: get("policy_status"),
- policy_rule: get("policy_rule"),
- };
-}
-
-async function toolPaymentRequestConsume(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const id = coerceStr(args, "id", true)!;
- const receiptPath = coerceStr(args, "receipt", true)!;
- const result = await consumePendingRequest(ctx.vault, id, { receiptPath });
- return {
- id: result.id,
- path: result.relativePath,
- status: result.status,
- };
-}
-
-async function toolPaymentPolicyCheck(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const expectedAmount = coerceOptionalNumber(args, "expected_amount");
- const tz = resolveTimezone(ctx.configPath ?? undefined);
- const decision = checkPolicy(ctx.vault, {
- service: coerceStr(args, "service", true)!,
- expectedAmount,
- currency: coerceStr(args, "currency", false),
- category: coerceStr(args, "category", false),
- date: coerceStr(args, "date", false),
- tz,
- });
- return {
- status: decision.status,
- allowed: decision.allowed,
- approval_required: decision.approvalRequired,
- rule: decision.rule,
- reasons: decision.reasons,
- has_policy: decision.hasPolicy,
- policy_path:
- decision.policyPath !== null
- ? vaultRelativePath(decision.policyPath, ctx.vault)
- : null,
- currency: decision.currency,
- };
-}
-
-async function toolPaymentReportGenerate(
- ctx: ServerContext,
- args: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- const result = writeReport(ctx.vault, {
- date: coerceStr(args, "date", true)!,
- title: coerceStr(args, "title", false),
- task: coerceStr(args, "task", false),
- slug: coerceStr(args, "slug", false),
- overwrite: Boolean(args["overwrite"] ?? false),
- });
- return {
- path: result.relativePath,
- absolute_path: resolve(result.path),
- slug: result.slug,
- receipts_used: result.receiptsUsed,
- };
-}
-
-function isDir(p: string): boolean {
- if (!existsSync(p)) return false;
- try {
- return statSync(p).isDirectory();
- } catch {
- return false;
- }
-}
export type ToolScope = "full" | "writer";
@@ -620,10 +193,9 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
},
handler: toolQuery,
},
- // `second_brain_capture` is intentionally not advertised β€” Brain
- // replaces it. `event_log_append` was retired in Β§32 (v0.10.8);
- // its handler has been removed. `toolCapture` remains in this
- // file for the legacy `o2b capture` shell flow.
+ // `second_brain_capture` and `event_log_append` were retired from
+ // the MCP surface in Β§32 (v0.10.8); Brain tools replace agent-side
+ // writes.
...BRAIN_TOOLS,
...SEARCH_TOOLS,
{
@@ -641,203 +213,7 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
},
handler: toolVaultHealth,
},
- {
- name: "payment_memory_init",
- description:
- "Bootstrap the Pay Memory layout (policies/, payments/, assets/, drafts/, reports/) and write the spending policy template.",
- inputSchema: {
- type: "object",
- properties: {
- agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },
- overwrite: {
- type: "boolean",
- description: "Overwrite an existing policy file. Directories are always idempotent.",
- },
- },
- additionalProperties: false,
- },
- handler: toolPaymentMemoryInit,
- },
- {
- name: "payment_receipt_append",
- description:
- "Save a Markdown receipt for one paid API call. raw_output is run through a redactor before persisting.",
- inputSchema: {
- type: "object",
- properties: {
- agent: { type: "string", description: "Agent identity (defaults to server-resolved name)." },
- service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },
- status: { type: "string", description: "Outcome of the paid call ('success', 'failed', ...)." },
- reason: { type: "string", description: "Why the paid call was made β€” short imperative sentence." },
- category: { type: "string", description: "Optional category tag." },
- endpoint: { type: "string", description: "Gateway endpoint URL returned by pay-skills." },
- expected_cost: { type: "string", description: "Pre-call expected price range." },
- actual_amount: { type: "string", description: "Actual amount charged (parsed from pay-tool output)." },
- currency: { type: "string", description: "Currency code (e.g. 'USDC')." },
- payment_proof: { type: "string", description: "Public proof / signature / receipt id." },
- result_ref: { type: "string", description: "Generated asset URL or response id." },
- result_note: { type: "string", description: "Vault path to the asset note (wikilink target)." },
- raw_output: { type: "string", description: "Raw payment-tool output to persist after redaction." },
- slug: { type: "string", description: "Optional slug override; default derives from service+reason." },
- date: { type: "string", description: "Receipt date in YYYY-MM-DD; default = today (vault tz)." },
- time: { type: "string", description: "Receipt time in HH:MM 24h; default = now (vault tz)." },
- overwrite: { type: "boolean", description: "Allow overwriting an existing receipt." },
- policy_status: {
- type: "string",
- enum: ["allowed", "approval_required", "denied", "not_checked"],
- description:
- "Real outcome of the spending-policy check. Defaults to `not_checked` when omitted β€” the receipt body will explicitly say so rather than claiming the policy approved the call.",
- },
- policy_rule: {
- type: "string",
- description: "Policy rule name that fired (e.g. `max_single_call`).",
- },
- policy_reasons: {
- type: "array",
- items: { type: "string" },
- description: "Human-readable reasons returned by the policy check.",
- },
- policy_checked_at: {
- type: "string",
- description: "ISO-Z timestamp at which the policy was evaluated.",
- },
- from_request: {
- type: "string",
- description:
- "Pending-payment-request id. When supplied, the receipt inherits policy / approval audit fields from that request β€” the agent doesn't have to re-state them.",
- },
- payment_layer: {
- type: "string",
- description: "Payment rail (default `pay.sh`). Override only when a different rail was used.",
- },
- network: {
- type: "string",
- description: "Settlement network (default `solana`). Override only when a different network was used.",
- },
- },
- required: ["service", "status", "reason"],
- additionalProperties: false,
- },
- handler: toolPaymentReceiptAppend,
- },
- {
- name: "asset_capture",
- description:
- "Save a Markdown note for an asset produced by a paid API call. Frontmatter links back to the receipt.",
- inputSchema: {
- type: "object",
- properties: {
- title: { type: "string", description: "Human-readable asset title." },
- service: { type: "string", description: "Provider/skill identifier that produced the asset." },
- result_url: { type: "string", description: "URL or identifier of the generated asset." },
- source_receipt: { type: "string", description: "Vault path to the receipt note." },
- prompt: { type: "string", description: "Prompt sent to the service (rendered as a quote block)." },
- used_in: { type: "string", description: "Vault path of the draft/page that consumes this asset." },
- slug: { type: "string", description: "Optional slug override; default derives from title." },
- overwrite: { type: "boolean", description: "Allow overwriting an existing asset note." },
- },
- required: ["title", "service", "result_url"],
- additionalProperties: false,
- },
- handler: toolAssetCapture,
- },
- {
- name: "payment_request_approval",
- description:
- "Create a pending-payment-request that the user must approve before the agent runs `pay`. Records the policy check at request time.",
- inputSchema: {
- type: "object",
- properties: {
- agent: { type: "string" },
- service: { type: "string" },
- reason: { type: "string" },
- expected_amount: { type: ["number", "string"] },
- currency: { type: "string" },
- category: { type: "string" },
- endpoint: { type: "string" },
- expected_output: { type: "string" },
- vault_files: { type: "array", items: { type: "string" } },
- slug: { type: "string" },
- date: { type: "string" },
- time: { type: "string" },
- enforce_policy: {
- type: "boolean",
- description: "If true, refuse to create the request when the policy denies it.",
- },
- },
- required: ["service", "reason"],
- additionalProperties: false,
- },
- handler: toolPaymentRequestApproval,
- },
- {
- name: "payment_request_status",
- description:
- "Look up a pending-payment-request by id and return its current status and metadata. The agent uses this to poll for human approval.",
- inputSchema: {
- type: "object",
- properties: {
- id: { type: "string", description: "The request id (slug)." },
- },
- required: ["id"],
- additionalProperties: false,
- },
- handler: toolPaymentRequestStatus,
- },
- {
- name: "payment_request_consume",
- description:
- "Mark an `approved` request as `consumed` and link the resulting receipt path. Called by the agent after the paid call succeeded.",
- inputSchema: {
- type: "object",
- properties: {
- id: { type: "string" },
- receipt: { type: "string", description: "Vault-relative path to the receipt note." },
- },
- required: ["id", "receipt"],
- additionalProperties: false,
- },
- handler: toolPaymentRequestConsume,
- },
- {
- name: "payment_policy_check",
- description:
- "Evaluate a prospective paid call against AI Wiki/policies/spending.json. Returns allowed / approval_required / denied + the rule that fired.",
- inputSchema: {
- type: "object",
- properties: {
- service: { type: "string", description: "Provider/skill identifier, e.g. 'paysponge/fal'." },
- expected_amount: {
- type: ["number", "string"],
- description: "Expected payment amount; numeric or numeric-string.",
- },
- currency: { type: "string", description: "Currency code; defaults to the policy currency." },
- category: { type: "string", description: "Optional category for per-category caps." },
- date: { type: "string", description: "Date in YYYY-MM-DD; default = today (vault tz)." },
- },
- required: ["service"],
- additionalProperties: false,
- },
- handler: toolPaymentPolicyCheck,
- },
- {
- name: "payment_report_generate",
- description:
- "Aggregate a date's payment receipts into a Markdown report under AI Wiki/reports/.",
- inputSchema: {
- type: "object",
- properties: {
- date: { type: "string", description: "Date in YYYY-MM-DD whose receipts will be aggregated." },
- title: { type: "string", description: "Report title; default 'Payment Report <date>'." },
- task: { type: "string", description: "Optional task description rendered in the body." },
- slug: { type: "string", description: "Optional slug override." },
- overwrite: { type: "boolean", description: "Allow overwriting an existing report." },
- },
- required: ["date"],
- additionalProperties: false,
- },
- handler: toolPaymentReportGenerate,
- },
+ ...PAY_MEMORY_TOOLS,
];
if (scope === "full") return all;
return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
diff --git a/src/openclaw/index.ts b/src/openclaw/index.ts
index ef03c7cc..5f52b5bc 100644
--- a/src/openclaw/index.ts
+++ b/src/openclaw/index.ts
@@ -5,16 +5,17 @@
* is no longer a hand-translated copy of the Python original β€” both runtimes
* share the same source of truth.
*
- * The plugin exposes the full Open Second Brain tool surface β€” the original
- * five (`second_brain_status`, `second_brain_query`, `second_brain_capture`,
- * `event_log_append`, `vault_health`) plus the eight Pay Memory tools added
- * in v0.8.0 β€” with parameter schemas mirrored from `src/mcp/tools.ts`.
+ * The plugin exposes the current Open Second Brain tool surface:
+ * `second_brain_status`, `second_brain_query`, `vault_health`, plus the
+ * eight Pay Memory tools added in v0.8.0. Legacy write tools
+ * (`second_brain_capture`, `event_log_append`) are retired from this
+ * agent-facing runtime.
* No subprocess creation; passes the OpenClaw security scanner.
*/
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import { existsSync } from "node:fs";
-import { join, resolve as resolvePath } from "node:path";
+import { resolve as resolvePath } from "node:path";
import {
discoverConfig,
@@ -42,11 +43,8 @@ import {
} from "../core/pay-memory/index.ts";
import type { ReceiptPolicyStatus } from "../core/pay-memory/types.ts";
import { mkdirSync } from "node:fs";
-import { listVaultPages, slugify, writeFrontmatter } from "../core/vault.ts";
-import {
- normalizeAgentArgument,
- PLACEHOLDER_AGENT_VALUES,
-} from "../core/agent-identity.ts";
+import { listVaultPages } from "../core/vault.ts";
+import { normalizeAgentArgument } from "../core/agent-identity.ts";
interface PluginConfig {
vault?: string;
@@ -216,71 +214,11 @@ export default definePluginEntry({
},
);
- api.registerTool(
- {
- name: "second_brain_capture",
- description: "Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
- parameters: {
- type: "object",
- properties: {
- title: { type: "string", description: "Human-readable note title." },
- content: { type: "string", description: "Markdown body of the note." },
- tags: {
- type: "array",
- items: { type: "string" },
- description: "Optional list of tag strings.",
- },
- overwrite: {
- type: "boolean",
- description: "Allow overwriting an existing note with the same slug.",
- },
- },
- required: ["title", "content"],
- additionalProperties: false,
- },
- async execute(_id, params): Promise<unknown> {
- const vault = resolveVaultPath(api);
- if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);
- const title = (params["title"] as string | undefined) ?? "";
- const content = (params["content"] as string | undefined) ?? "";
- const tags = (params["tags"] as string[] | undefined) ?? [];
- const overwrite = Boolean(params["overwrite"]);
- if (!title.trim()) throw new Error("title must not be empty");
- if (!content.trim()) throw new Error("content must not be empty");
-
- const notesDir = join(vault, "AI Wiki", "notes");
- const slug = slugify(title);
- const target = join(notesDir, `${slug}.md`);
- // Capture existence BEFORE writeFrontmatter β€” otherwise existsSync
- // is always true after the write, making `overwritten` a no-op
- // signal whenever overwrite=true.
- const noteExisted = existsSync(target);
- if (noteExisted && !overwrite) {
- throw new Error(`note already exists: ${vaultRelativePath(target, vault)}`);
- }
- const metadata: Record<string, string | number | boolean | string[]> = {
- title,
- type: "note",
- created: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
- };
- if (tags.length > 0) metadata["tags"] = tags;
- writeFrontmatter(target, metadata, content.trim());
- const result = {
- path: vaultRelativePath(target, vault),
- absolute_path: target,
- slug,
- overwritten: noteExisted && overwrite,
- };
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- },
- },
- );
-
- // Β§32G (v0.10.8): the OpenClaw `event_log_append` registration is
- // gone. Agents on this runtime now record via the Brain writer
- // tools served by the MCP server (`brain_feedback`,
- // `brain_apply_evidence`, `brain_note`); the human-side
- // `o2b append-event` CLI is the only remaining caller of
+ // Β§32G (v0.10.8): the OpenClaw `second_brain_capture` and
+ // `event_log_append` registrations are gone. Agents on this runtime
+ // now record via the Brain writer tools served by the MCP server
+ // (`brain_feedback`, `brain_apply_evidence`, `brain_note`); the
+ // human-side `o2b append-event` CLI is the only remaining caller of
// `appendEvent`.
api.registerTool(
diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.ts
index e5b54f83..0b713314 100644
--- a/tests/core/brain.inline-scan.test.ts
+++ b/tests/core/brain.inline-scan.test.ts
@@ -6,7 +6,6 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
- existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
diff --git a/tests/core/brain.log-jsonl-reader.test.ts b/tests/core/brain.log-jsonl-reader.test.ts
index 975b924d..77cea310 100644
--- a/tests/core/brain.log-jsonl-reader.test.ts
+++ b/tests/core/brain.log-jsonl-reader.test.ts
@@ -3,7 +3,6 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
- readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.ts
index f96b9a8a..4f137b83 100644
--- a/tests/core/brain/starter.test.ts
+++ b/tests/core/brain/starter.test.ts
@@ -7,7 +7,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { join } from "node:path";
import {
bootstrapBrain,
diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.ts
index 55ffa70b..0c0c9b34 100644
--- a/tests/core/brain/upgrade.test.ts
+++ b/tests/core/brain/upgrade.test.ts
@@ -15,7 +15,6 @@ import {
mkdtempSync,
readFileSync,
rmSync,
- writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index c446e73d..bb262ab9 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.ts
index 07aeb5b5..0a3a899a 100644
--- a/tests/openclaw/bundle.test.ts
+++ b/tests/openclaw/bundle.test.ts
@@ -40,7 +40,6 @@ describe("openclaw bundle", () => {
// core
"second_brain_status",
"second_brain_query",
- "second_brain_capture",
"vault_health",
// Pay Memory
"payment_memory_init",
@@ -62,6 +61,10 @@ describe("openclaw bundle", () => {
expect(bundleText).not.toContain(`name: "event_log_append"`);
});
+ test("does not register the retired second_brain_capture tool (Β§32G)", () => {
+ expect(bundleText).not.toContain(`name: "second_brain_capture"`);
+ });
+
test("does NOT contain Python references", () => {
expect(bundleText).not.toContain("python3");
expect(bundleText).not.toContain("from open_second_brain");